text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I need to develop a fairly simple algorithm , but am kindof confused as how to best write a test for it.General description : User needs to be able to delete a Plan . Plan has Tasks associated with it , these need to be deleted as well ( as long as they 're not already done ) .Pseudo-code as how the algorithm should behave : Now as far as I understand it , unit tests are not supposed to touch the Database or generally require access to any outside systems , so I 'm guessing I have two options here:1 ) Mock out the Repository calls , and check whether they have been called the appropriate number of times as Asserts2 ) Create stubs for both repository classes , setting their delete flag manually and then verify that the appropriate objects have been marked for deletion.In both approaches , the big question is : What exactly am I testing here ? What is the EXTRA value that such tests would give me ? Any insight in this would be highly appreciated . This is technically not linked to any specific unit testing framework , although we have RhinoMocks to be used . But I 'd prefer a general explanation , so that I can properly wrap my head around this . <code> PlanController.DeletePlan ( plan ) = > PlanDbRepository.DeletePlan ( ) ForEach Task t in plan.Tasks If t.Status = Status.Open Then TaskDbRepository.DeleteTask ( t ) End If End ForEach
How would I go about unit testing this ?
C_sharp : In a heavily multi-threaded scenario , I have problems with a particular EF query . It 's generally cheap and fast : This compiles into a very reasonable SQL query : The query , in general , has optimal query plan , uses the right indices and returns in tens of milliseconds which is completely acceptable.However , when a critical number of threads ( < =40 ) starts executing this query , the performance on it drops to tens of seconds.There are no locks in the database , no queries are writing data to these tables and it reproduces very well with a database that 's practically isolated from any other operations . The DB resides on the same physical machine and the machine is not overloaded at any point , i.e . has plenty of spare CPU , memory and other resources the CPU is overloaded by this operation.Now what 's really bizarre is that when I replace the EF Any ( ) call with Context.Database.ExecuteSqlCommand ( ) with the copy-pasted SQL ( also using parameters ) , the problem magically disappears . Again , this reproduces very reliably - replacing the Any ( ) call with copy-pasted SQL increases the performance by 2-3 orders of magnitude .An attached profiler ( dotTrace ) sampling shows that the threads seem to all spend their time in the following method : Is there anything I 've missed or did we hit some ADO.NET / SQL Server cornercase ? MORE CONTEXTThe code running this query is a Hangfire job . For the purpose of test , a script queues a lot of jobs to be performed and up to 40 threads keep processing the job . Each job uses a separate DbContext instance and it 's not really being used a lot . There are a few more queries before and after the problematic query and they take expected times to execute.We 're using many different Hangfire jobs for similar purposes and they behave as expected . Same with this one , except when it gets slow under high concurrency ( of exact same jobs ) . Also , just switching to SQL on this particular query fixes the problem.The profiling snapshot above is representative , all the threads slow down on this particular method call and spend the vast majority of their time on it.UPDATEI 'm currently re-running a lot of those checks for sanity and errors . The easy reproduction means it 's still on a remote machine to which I ca n't connect using VS for debugging . One of the checks showed that my previous statement about free CPU was false , the CPU was not entirely overloaded but multiple cores were in fact running on full capacity for the whole duration of the long running jobs.Re-checking everything again and will come back with updates here . <code> Context.MyEntity .Any ( se = > se.SameEntity.Field == someValue & & se.AnotherEntity.Field == anotherValue & & se.SimpleField == simpleValue // few more simple predicates with fields on the main entity ) ; SELECT CASE WHEN ( EXISTS ( SELECT 1 AS [ C1 ] FROM ( SELECT [ Extent1 ] . [ Field1 ] AS [ Field1 ] FROM [ dbo ] . [ MyEntity ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ SameEntity ] AS [ Extent2 ] ON [ Extent1 ] . [ SameEntity_Id ] = [ Extent2 ] . [ Id ] WHERE ( N'123 ' = [ Extent2 ] . [ SimpleField ] ) AND ( 123 = [ Extent1 ] . [ AnotherEntity_Id ] ) AND -- further simple predicates here -- ) AS [ Filter1 ] INNER JOIN [ dbo ] . [ AnotherEntity ] AS [ Extent3 ] ON [ Filter1 ] . [ AnotherEntity_Id1 ] = [ Extent3 ] . [ Id ] WHERE N'123 ' = [ Extent3 ] . [ SimpleField ] ) ) THEN cast ( 1 as bit ) ELSE cast ( 0 as bit ) END AS [ C1 ] FROM ( SELECT 1 AS X ) AS [ SingleRowTable1 ]
Curious slowness of EF vs SQL
C_sharp : I have the following method in my custom WebTest : On my GetRequestEnumerator I am calling the method like this : Note : The original code is more complicated than this , but it is irrelevant.This is working fine when running the load test on my local machine : You can see that each request is being identified by the value of ReportingName propertyHowever , If I run the load test on Visual Studio Online services , requests are grouped by URL instead of the value on ReportingName : Requests are being grouped as command { GET } and command { POST } because the URL is the same for every request on my test case ( https : //test.xxxx.com/api/command ) , only differing by HTTP method on some of them.I searched for hours on the Internet and only managed to find this open thread about it on MSDN : Reporting Name does not show up in Page Results of Online Load TestWhat is happening ? <code> private WebTestRequest CreateRequest ( CommandInput command ) { WebTestRequest request = new WebTestRequest ( URL ) ; request.ReportingName = command.CommandName ; request.Method = command.HttpMethod ; // ... return request ; } public override IEnumerable < WebTestRequest > GetRequestEnumerator ( ) { return new CommandInput [ ] { new CommandInput ( ) { CommandName = `` configuration '' , HttpMethod = `` POST '' } , new CommandInput ( ) { CommandName = `` login '' , HttpMethod = `` POST '' } , new CommandInput ( ) { CommandName = `` quick_view '' , HttpMethod = `` GET '' } , new CommandInput ( ) { CommandName = `` esign_document '' , HttpMethod = `` POST '' } } .Select ( CreateRequest ) .GetEnumerator ( ) ; }
WebTestRequest.ReportingName is ignored when using VS Team Services
C_sharp : They use StructureMap for IoC where I am currently working.I have an application class that will implement multiple properties of the same interface ... and I need to bind DIFFERENT IMPLEMENTATIONS ... and no , I can not do this : IProvider < T > FOR INSTANCE : In Unity , there are many ways to do this , for instance ; ... however , StructureMaps SetterProperty attribute doesnt allow for this.QUESTION : How do I bind different implementations into an instance-property ? SAMPLE REGISTRY : Here is an example of what my registry might look like ... <code> public class MyApplication { [ SetterProperty ] public IProvider OneProvider { get ; set ; } [ SetterProperty ] public IProvider TwoProvider { get ; set ; } } public class FooProvider : IProvider { // I would like to force this one to bind-on OneProvider ... } public class BarProvider : IProvider { // I would like to force this one to bind-on TwoProvider ... } [ Dependency ( `` FooProvider '' ) ] public IProvider OneProvider { get ; set ; } [ Dependency ( `` BarProvider '' ) ] public IProvider TwoProvider { get ; set ; } public ContainerRegistry ( ) { Scan ( scan = > { scan.TheCallingAssembly ( ) ; scan.WithDefaultConventions ( ) ; scan.LookForRegistries ( ) ; scan.AssembliesFromApplicationBaseDirectory ( f = > f.FullName.StartsWith ( `` My.Awesome.Company '' , true , null ) ) ; scan.AddAllTypesOf ( typeof ( IApplication ) ) ; scan.AddAllTypesOf ( typeof ( IManager < > ) ) ; scan.AddAllTypesOf ( typeof ( IProvider ) ) ; scan.AddAllTypesOf ( typeof ( IUnitOfWorkFactory < > ) ) ; scan.SingleImplementationsOfInterface ( ) ; } ) ; For ( typeof ( IApplication ) ) .Use ( typeof ( MyApplication ) ) ; }
How Do I Bind Different Concretes to a Property Using StructureMap
C_sharp : I am deserializing an Object using this codeMy UserData class is as followsWhen it deserializes I get an object returned as if I had just called new UserData ( ) but if I remove the : BindableBase from the class definition it deserializes correctly . I guess this is because the base class contains some properties that arent in the JSON but I just want those ignored . Is there a setting for this ? The BindableBase class is as follows The JSON is as follows <code> PlayerData = JsonConvert.DeserializeObject < UserData > ( response.Content ) ; public class UserData : BindableBase { public string UID { get ; set ; } public string UDID { get ; set ; } public object liveID { get ; set ; } public int timeLastSeen { get ; set ; } public string country { get ; set ; } public string username { get ; set ; } public string session { get ; set ; } public int serverTime { get ; set ; } public int PremiumCurrency { get ; set ; } public UserData ( ) { } } [ Windows.Foundation.Metadata.WebHostHidden ] [ DataContract ] public abstract class BindableBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged ; protected bool SetProperty < T > ( ref T storage , T value , [ CallerMemberName ] String propertyName = null ) { if ( object.Equals ( storage , value ) ) return false ; storage = value ; this.OnPropertyChanged ( propertyName ) ; return true ; } protected void OnPropertyChanged ( [ CallerMemberName ] string propertyName = null ) { var eventHandler = this.PropertyChanged ; if ( eventHandler ! = null ) { eventHandler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } } { `` UID '' : `` 4 '' , `` UDID '' : `` '' , `` liveID '' : null , `` timeLastSeen '' : 1392730436 , `` country '' : `` GB '' , `` username '' : `` User4 '' , `` PremiumCurrency '' : `` 20 '' , `` session '' : `` 5c8583311732fa816e333dc5e6426d65 '' , `` serverTime '' : 1392730437 }
Deserializing JSON produces default class
C_sharp : I was wondering ... When I have a code like this : Can MyAgent contain code that recognizes it is running under a lock block ? What about : Can MyAgent contain code that recognizes it is running under a loop block ? The same question can be asked for using blocks , unsafe code , etc ... - well you get the idea ... Is this possible in C # ? This is just a theoretical question , I 'm not trying to achieve anything ... just knowledge . <code> lock ( obj ) { MyCode.MyAgent ( ) ; } for ( int i=0 ; i < 5 ; i++ ) { MyCode.MyAgent ( ) ; }
Under what context am I running in C # ?
C_sharp : I have a category/file tree structure . Both categories and files can have parents , so I derived them from a common base class that has a Parent property . Since all parents will obviously always be categories ( files ca n't be a parent ) , it seems to make sense to make the Parent property of the node be the CategoryNode type . Is it bad form for the base class to refer to the derived class ? If so , why ? What 's a better way to structure this , if so ? <code> class Node { public CategoryNode Parent { get ; set ; } } class File : Node { ... } class CategoryNode : Node { ... }
Is it bad form to refer to a derived type in a base type ?
C_sharp : My understanding is that LINQ IEnumerable extensions are supposed to call Dispose on the IEnumerators produced by the IEnumerable . See this answer on SO . However , I 'm not seeing that in practice . Is the other SO answer incorrect , or have I found a bug in LINQ ? Here 's a minimal reproduction of the issue using Mono . It also reproduces in Dotnet Core 2.1 & 2.2.If the Dispose was getting called you would see I got disposed twice on the console . Instead you get no I got disposeds . The Union and the Select are required to reproduce the issue.Any C # gurus know if I 've hit a bug ? Update : I believe this is a bug , and I 've filed : https : //github.com/dotnet/corefx/issues/40384 . <code> using System ; using System.Threading ; using System.Linq ; using System.Collections.Generic ; using System.Collections ; namespace union { class MyEnumerable : IEnumerable < long > { public IEnumerator < long > GetEnumerator ( ) { return new MyEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } } class MyEnumerator : IEnumerator < long > { public long Current { get { return 0 ; } } object IEnumerator.Current { get { return Current ; } } public bool MoveNext ( ) { return false ; } public void Reset ( ) { return ; } public void Dispose ( ) { Console.WriteLine ( `` I got disposed '' ) ; } } class Program { static void Main ( string [ ] args ) { var enum1 = new MyEnumerable ( ) ; var enum2 = new MyEnumerable ( ) ; enum1.Union ( enum2 ) .Select ( x = > x + 1 ) .ToList ( ) ; Console.WriteLine ( `` All done ! `` ) ; } } }
LINQ is n't calling Dispose on my IEnumerator when using Union and Select , expected behavior or bug ?
C_sharp : I would like to know if it is possible to remove an IDictionary item by its key and in the same time get its actual value that has been removed ? Examplesomething like : Output <code> Dictionary < string , string > myDic = new Dictionary < string , string > ( ) ; myDic [ `` key1 '' ] = `` value1 '' ; string removed ; if ( nameValues.Remove ( `` key1 '' , out removed ) ) //No overload for this ... { Console.WriteLine ( $ '' We have just remove { removed } '' ) ; } //We have just remove value1
IDictionary How to get the removed item value while removing
C_sharp : In javascript , it is common to use closures and create then immediately invoke an anonymous function , as below : Due to strong typing , this very verbose in C # : Is there a more elegant way to go about this type of thing in C # ? <code> var counter = ( function ( ) { var n = 0 ; return function ( ) { return n++ ; } } ( ) ) ; Func < int > counter = ( ( Func < Func < int > > ) ( ( ) = > { int n = 0 ; return ( ) = > n++ ; } ) ) ( ) ;
Invoking Lambdas at Creation
C_sharp : I do n't understand the difference between Anonymous Class and object Classif i have an anonymous type object : i can see how i can iterate through it and get values of the properties doing this x.name ... but if i change this to an object then if i loop through it i will not be able to access the properties ? ? i have tried different ways to be able to get the values from this object and i failed , may be i missed something ? and what is the point of generating object array and how can i consume it ? ? and i know that i ca n't do something like this : new Object [ ] { name = ' x ' ... <code> var x = new [ ] { new { name = `` x '' , phone = 125 } , new { name = `` f '' , phone = 859 } , new { name= '' s '' , phone=584 } } ; var x = new Object [ ] { new { name = `` x '' , phone = 125 } , new { name = `` f '' , phone = 859 } , new { name= '' s '' , phone=584 } } ;
what is the difference between Anonymous Class Array and Object Array ?
C_sharp : This has probably been already asked but it 's hard to search for.What is the difference between [ Something ] and [ SomethingAttribute ] ? Both of the following compile : Are there any differences between these apart from their appearance ? What 's the general guideline on their use ? <code> [ DefaultValue ( false ) ] public bool Something { get ; set ; } [ DefaultValueAttribute ( false ) ] public bool SomethingElse { get ; set ; }
What 's the difference between [ Something ] and [ SomethingAttribute ]
C_sharp : I 'm trying to design a class that exposes the ability to add asynchronous processing concerns . In synchronous programming , this might look likein an asynchronous world , where each concern may need to return a task , this is n't so simple . I 've seen this done lots of ways , but I 'm curious if there are any best practices that people have found . One simple possibility isIs there some `` standard '' that people have adopted for this ? There does n't seem to be a consistent approach I 've observed across popular APIs . <code> public class ProcessingArgs : EventArgs { public int Result { get ; set ; } } public class Processor { public event EventHandler < ProcessingArgs > Processing { get ; } public int Process ( ) { var args = new ProcessingArgs ( ) ; Processing ? .Invoke ( args ) ; return args.Result ; } } var processor = new Processor ( ) ; processor.Processing += args = > args.Result = 10 ; processor.Processing += args = > args.Result+=1 ; var result = processor.Process ( ) ; public class Processor { public IList < Func < ProcessingArgs , Task > > Processing { get ; } =new List < Func < ProcessingArgs , Task > > ( ) ; public async Task < int > ProcessAsync ( ) { var args = new ProcessingArgs ( ) ; foreach ( var func in Processing ) { await func ( args ) ; } return args.Result } }
Pattern for delegating async behavior in C #
C_sharp : Comparing `` î '' With `` i '' Current culture was en-GB . I would expect all of these to return 1 . Why does having a longer string change the sort order ? <code> string.Compare ( `` î '' , `` I `` , StringComparison.CurrentCulture ) -- returns -1string.Compare ( `` î '' , `` I `` , StringComparison.CurrentCultureIgnoreCase ) -- returns -1string.Compare ( `` î '' , `` I '' , StringComparison.CurrentCulture ) -- returns 1 ( unexpected ) string.Compare ( `` î '' , `` I '' , StringComparison.CurrentCultureIgnoreCase ) -- returns 1 ( unexpected ) string.Compare ( `` i '' , `` I `` , StringComparison.CurrentCulture ) -- returns -1string.Compare ( `` i '' , `` I `` , StringComparison.CurrentCultureIgnoreCase ) -- returns -1string.Compare ( `` i '' , `` I '' , StringComparison.CurrentCulture ) -- returns -1string.Compare ( `` i '' , `` I '' , StringComparison.CurrentCultureIgnoreCase ) -- returns 0
Weird string sorting when 2nd string is longer
C_sharp : I had to reinstall everything on my computer including Visual Studio , my question is , before I reinstalled Visual Studio was showing the code on my C # programs in a method using Unicode operators for example : instead of However upon reinstalling Visual Studio they 've reverted back to the text format , does anyone know what setting I need to enable to get them to show as the Unicode versions ? Any help you could give would be massively appreciated . <code> if ( 1 ≠ 2 ) { } if ( 1 ! = 2 ) { }
Visual Studio a way to show operators as opposed to text Example : ≠ instead of ! =
C_sharp : Foreword : I am trying to describe the scenario very precisely here . The TL ; DR version is 'how do I tell if a lambda will be compiled into an instance method or a closure ' ... I am using MvvmLight in my WPF projects , and that library recently changed to using WeakReference instances in order to hold the actions that are passed into a RelayCommand . So , effectively , we have an object somewhere which is holding a WeakReference to an Action < T > .Now , since upgrading to the latest version , some of our commands stopped working . And we had some code like this : This caused a closure ( please correct me if I 'm not using the correct term ) class to be generated - like this : This worked fine previously , as the action was stored within the RelayCommand instance , and was kept alive whether it was compiled to an instance method or a closure ( i.e . using the ' < > DisplayClass ' syntax ) .However , now , because it is held in a WeakReference , the code only works if the lambda specified is compiled into an instance method . This is because the closure class is instantiated , passed into the RelayCommand and virtually instantly garbage collected , meaning that when the command came to be used , there was no action to perform . So , the above code has to be modified . Changing it to the following causes that , for instance : This causes the compiled code to result in a member - like the following : Now the above is all fine , and I understand why it did n't work previously , and how changing it caused it to work . However , what I am left with is something which means the code I write now has to be stylistically different based on a compiler decision which I am not privy to . So , my question is - is this a documented behaviour in all circumstances - or could the behaviour change based on future implementations of the compiler ? Should I just forget trying to use lambdas and always pass an instance method into the RelayCommand ? Or should I have a convention whereby the action is always cached into an instance member : Any background reading pointers are also gratefully accepted ! <code> ctor ( Guid token ) { Command = new RelayCommand ( x = > Messenger.Default.Send ( x , token ) ) ; } [ CompilerGenerated ] private sealed class < > c__DisplayClass4 { public object token ; public void < .ctor > b__0 ( ReportType x ) { Messenger.Default.Send < ReportTypeSelected > ( new ReportTypeSelected ( X ) , this.token ) ; } } Guid _token ; ctor ( Guid token ) { _token = token ; Command = new RelayCommand ( x = > Messenger.Default.Send ( x , _token ) ) ; } [ CompilerGenerated ] private void < .ctor > b__0 ( ReportType x ) { Messenger.Default.Send < ReportTypeSelected > ( new ReportTypeSelected ( X ) , this._token ) ; } Action < ReportTypeSelected > _commandAction ; ctor ( Guid token ) { _commandAction = x = > Messenger.Default.Send ( x , token ) ; Command = new RelayCommand ( _commandAction ) ; }
Determining when a lambda will be compiled to an instance method
C_sharp : My problem isi have this JSON file : and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException , as if my list is empty . this is my code : and these are my two class for the saves : and can you help me solve it ? <code> JavaScriptSerializer ser = new JavaScriptSerializer ( ) ; Causali o = new Causali ( ) ; List < CausaliList > lista = new List < CausaliList > ( ) ; WebRequest causali = ( HttpWebRequest ) WebRequest.Create ( `` http : //trackrest.cgestmobile.it/causali '' ) ; WebResponse risposta = ( HttpWebResponse ) CreateCausaliRequest ( causali ) .GetResponse ( ) ; Stream data = risposta.GetResponseStream ( ) ; StreamReader Leggi = new StreamReader ( data ) ; string output = Leggi.ReadToEnd ( ) ; lista = ser.Deserialize < List < CausaliList > > ( output ) ; lst2.Items.Add ( lista [ 0 ] ) ; class Causali { public int id ; public string causaliname ; public string identificationcode ; public string expired ; } class CausaliList { public Causali causali ; }
Deserializing a JSON file with c #
C_sharp : I seem to be having trouble executing a lambda expression that I 've previously assigned to a variable . Here 's a small C # example program I 've put together : I want it to produce this output:3 2 5 8 1 4 7 9 61 2 3 4 5 6 7 8 99 8 7 6 5 4 3 2 1But , confusingly , it produces this output:3 2 5 8 1 4 7 9 63 2 5 8 1 4 7 9 63 2 5 8 1 4 7 9 6Basically , I just want to be able to pass the same expression to the two different ordering operations without having to type it out twice , hence why I assign it to selector beforehand . I have a real-world use case where the lambda expression is really long/messy and I do n't want to duplicate the mess , I 'd rather just refer to a variable like I have here.So , a ) what is causing the current output ? b ) how can I get the output that I want ? <code> public class Program { public static void Main ( string [ ] args ) { int [ ] notOrdered = { 3 , 2 , 5 , 8 , 1 , 4 , 7 , 9 , 6 } ; Print ( notOrdered ) ; IEnumerable < int > ascOrdered = Order ( notOrdered , true ) ; Print ( ascOrdered ) ; IEnumerable < int > descOrdered = Order ( notOrdered , false ) ; Print ( descOrdered ) ; } static IEnumerable < T > Order < T > ( IEnumerable < T > enumerables , bool ascending ) { Expression < Func < T , object > > selector = ( z ) = > z ; // simple for demo purposes ; pretend it 's complex if ( ascending ) return enumerables.OrderBy ( z = > selector ) ; else return enumerables.OrderByDescending ( z = > selector ) ; } static void Print < T > ( IEnumerable < T > enumerables ) { foreach ( T enumerable in enumerables ) Console.Write ( enumerable.ToString ( ) + `` `` ) ; Console.WriteLine ( ) ; } }
Assigning a lambda expression causes it to not be executed later ?
C_sharp : I 'm working on a prototype EF application , using POCOs . Mainly as an introduction to the framework I 'm wondering about a good way to set up the application in a nice structure . Later on I 'm planning to incorporate WCF into it.What I 've done is the following:1 ) I created an edmx file , but with the Code Generation Property set to None and generated my database schema,2 ) I created the POCOs which all look like:3 ) I created a ContextThe interface looks like this:4 ) Lastly I created a repository , implementing an interface : Now , when I get on playing around with this , this design dictates me to instantiate a repository every time I want to fetch or mutate some data , like this : Somehow this just feels wrong and flawed , on the other hand , just instantiating every repository in the derived context does n't feel too good either , because of potentially instantiating objects I might not need at all.Any tips on how to make this design sound ? Should I leave it this way ? Any things I should add or avoid in general when doing this ? <code> public class Person { public Person ( ) { } public Person ( string firstName , string lastName ) { FirstName = firstName ; LastName = lastName ; } public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } public class PocoContext : ObjectContext , IPocoContext { private IObjectSet < Person > persons ; public PocoContext ( ) : base ( `` name=PocoContainer '' , `` PocoContainer '' ) { ContextOptions.LazyLoadingEnabled = true ; persons= CreateObjectSet < Person > ( ) ; } public IObjectSet < Person > Persons { get { return persons ; } } public int Save ( ) { return base.SaveChanges ( ) ; } } public interface IPocoContext { IObjectSet < Person > Persons { get ; } int Save ( ) ; } public class PersonRepository : IEntityRepository < Person > { private IPocoContext context ; public PersonRepository ( ) { context = new PocoContext ( ) ; } public PersonRepository ( IPocoContext context ) { this.context = context ; } // other methods from IEntityRepository < T > } public interface IEntityRepository < T > { void Add ( T entity ) ; List < T > GetAll ( ) ; T GetById ( int id ) ; void Delete ( T entity ) ; } using ( var context = new PocoContext ( ) ) { PersonRepository prep = new PersonRepository ( ) ; List < Person > pers = prep.GetAll ( ) ; }
Setting up an EF application 's structure
C_sharp : I need to perform multi string replacement . I have a string where several parts need to be changed according to substitution map.All replacement must be done in one action - it means if `` a '' should be replaced with `` b '' and also `` b '' must be replaced with `` c '' and input string is `` abc '' , the result will be `` bcc '' I have a sollution based on building regex and then replacing all matches . I wrote it some time ago , now I 'm refactoring the code and not so satisfied with it . Is there better ( faster , simplier ) sollution ? This is what I have : And test case : <code> public static string Replace ( string s , Dictionary < string , string > substitutions ) { string pattern = `` '' ; int i = 0 ; foreach ( string ch in substitutions.Keys ) { if ( i == 0 ) pattern += `` ( `` + Regex.Escape ( ch ) + `` ) '' ; else pattern += `` | ( `` + Regex.Escape ( ch ) + `` ) '' ; i++ ; } var r = new Regex ( pattern ) ; var parts = r.Split ( s ) ; string ret = `` '' ; foreach ( string part in parts ) { if ( part.Length == 1 & & substitutions.ContainsKey ( part [ 0 ] .ToString ( ) ) ) { ret += substitutions [ part [ 0 ] .ToString ( ) ] ; } else { ret += part ; } } return ret ; } var test = `` test aabbcc '' ; var output = Replace ( test , new Dictionary < string , string > { { `` a '' , '' b '' } , { `` b '' , '' y '' } } ) ; Assert.That ( output== '' test bbyycc '' ) ;
Fast multi-string replacement
C_sharp : I have two IEnumerables of different types , both of which derive from a common base class . Now I try to union the enumerables to get an enumerable of the base class . I have to explicitly cast one of the enumerables to the base class for this to work.I would have guessed that the Compiler would have automatically chosen the closest common base type for the resulting enumerable , but it does not.Here is an example of that behavior : var c seems to be easy to explain , as the first enumerable is now of type BaseClass , so a union with the second list , which contains elements which are derived from BaseClass also is easy to understand.var dis not so easy to understand for me , because we start with an enumerable of DerivedClass1 and union that with BaseClass elements . I am surprised that this works . Is it because a union operation is kind of an commutative operation and so it has to work as c also works ? <code> namespace ConsoleApp1 { public class BaseClass { } public class DerivedClass1 : BaseClass { } public class DerivedClass2 : BaseClass { } class Program { static void Main ( string [ ] args ) { List < DerivedClass1 > list1 = new List < DerivedClass1 > ( ) ; List < DerivedClass2 > list2 = new List < DerivedClass2 > ( ) ; var a = list1.Union ( list2 ) ; // Compiler Error IEnumerable < BaseClass > b = list1.Union ( list2 ) ; // Compiler Error var c = list1.Cast < BaseClass > ( ) .Union ( list2 ) ; // This works var d = list1.Union ( list2.Cast < BaseClass > ( ) ) ; // This works var e = list1.Cast < BaseClass > ( ) .Union ( list2.Cast < BaseClass > ( ) ) ; // This works , but ReSharper wants to remove one of the casts } } }
Why cant the compiler resolve the resulting type ?
C_sharp : Is there a way to control access to methods to certain roles in .net . Like I 'm using windows authentication only for retrieving user names and nothing more.User roles are maintained in a different application . I think it 's possible through attributes but I 'm not really sure how <code> class A { //should only be called by Admins** public void Method1 ( ) { } //should only be called by Admins and PM's** public void Method2 ( ) { } }
Controlling access to methods
C_sharp : I 've been looking into Functional Programming lately and wanting to bring some concepts to my C # world . I 'm trying to compose functions to create services ( or whatever you 'd call them ) instead of creating classes with injectable dependencies.I 've come up with a way to partially apply a function ( to have the same effect as injecting dependencties ) with two arguments and one return argument by creating a static method like this : This works , however I would like to pass it a static method , like this one : When I try to wire this up , I get the error The type arguments for method 'Program.PartiallyApply < T1 , T2 , TResult > ( Func < T1 , T2 , TResult > , T1 ) ' can not be inferred from the usage . But when I add a step creating an explicit Func < string , string , string which I point to the method it does work : Why ca n't the compiler work out the type args when passing the static method directly ? Is there a way where I could use static methods without the need to explicitly map them to a Func < > with essentially the same ( type ) arguments ? UPDATEReading Functional programming in C # by Enrico Buonanno ( highly recommended ) gives another good option for getting around this . In 7.1.3 he gives several options on how to work with Funcs directly , instead of method groups.You could make a getter only property with a Func like this : <code> // this makes a func with a single arg from a func with twostatic Func < T2 , TResult > PartiallyApply < T1 , T2 , TResult > ( Func < T1 , T2 , TResult > f , T1 t1 ) { // use given t1 argument to create a new function Func < T2 , TResult > map = t2 = > f ( t1 , t2 ) ; return map ; } static string MakeName ( string a , string b ) = > a + `` `` + b ; static void Main ( string [ ] args ) { var first = `` John '' ; var last = `` Doe '' ; var f1 = PartiallyApply ( MakeName , first ) ; // can not be inferred from the usage Func < string , string , string > make = MakeName ; // map it to func var f2 = PartiallyApply ( make , first ) ; // works var name = f2 ( last ) ; Console.WriteLine ( name ) ; Console.ReadKey ( ) ; } static Func < string , string , string > MakeName = > ( a , b ) = > a + `` `` + b ;
Static method signature type arguments and partial application
C_sharp : I am a bit clueless about the next task . I wish to select a text between `` that its inside a tag but not outside of the tag , i.e . a selection inside another selection.I have the next tag : < | and | > and i want to select a text only if its between the `` and between the tags. < | blah blah blah `` should be selected '' not selected `` select it too '' | > `` not selected too '' I think something aboutBut it does n't work . <code> ( \ < \| ) ( \ '' ) .* ? ( \ '' ) ( \|\ > )
Regular expression , selects a portion of text inside other
C_sharp : Given the struct S1 : and an equality test : areEqual evaluates to true , as expected.Now lets slightly change our struct to S2 ( replacing the pointer with a string ) : with an analog test : this evaluates to true as well.Now the interesting part . If we combine both structs to S3 : and test for equality : The equality test fails , unexpectedly . Even worse , does also fail the test.Why do the last two equality tests evaluate to false ? EditBugreport for reference . <code> unsafe readonly struct S1 { public readonly int A1 , A2 ; public readonly int* B ; public S1 ( int a1 , int a2 , int* b ) { A1 = a1 ; A2 = a2 ; B = b ; } } int x = 10 ; var a = new S1 ( 1 , 2 , & x ) ; var b = new S1 ( 1 , 2 , & x ) ; var areEqual = Equals ( a , b ) ; // true unsafe readonly struct S2 { public readonly int A1 , A2 ; public readonly string C ; public S2 ( int a1 , int a2 , string c ) { A1 = a1 ; A2 = a2 ; C = c ; } } var a = new S2 ( 1 , 2 , `` ha '' ) ; var b = new S2 ( 1 , 2 , `` ha '' ) ; var areEqual = Equals ( a , b ) ; // true unsafe readonly struct S3 { public readonly int A1 , A2 ; public readonly int* B ; public readonly string C ; public S3 ( int a1 , int a2 , int* b , string c ) { A1 = a1 ; A2 = a2 ; B = b ; C = c ; } } int x = 10 ; var a = new S3 ( 1 , 2 , & x , `` ha '' ) ; var b = new S3 ( 1 , 2 , & x , `` ha '' ) ; var areEqual = Equals ( a , b ) ; // false Equals ( a , a ) ; // false
Unexpected equality tests , Equals ( a , a ) evaluates to false
C_sharp : Suppose I 've a generic method as : Are this.Fun < Feature > and this.Fun < Category > different instantiations of the generic method ? In general , how does the generic method get instantiated ? Different generic argument produces different method , or same method along with different metadata which is used at runtime ? Please support your answer with some quote ( s ) from the language specification.Also , suppose I did these : then later on , Does the lineX undo the thing which I did at line1 ? Or it depends on somethig else also ? <code> void Fun < T > ( FunArg arg ) { } client.SomeEvent += this.Fun < Feature > ; //line1client.SomeEvent += this.Fun < Category > ; //line2client.SomeEvent += this.Fun < Result > ; //line3 client.SomeEvent -= this.Fun < Feature > ; //lineX
How generic methods gets instantiated in C # ?
C_sharp : I have the following KeyBindings : When I press Ctrl+Shift+S to execute the SaveAs command , it works -- but directly afterwards , the Save command is also executed . Is this caused by my Gesture definitions ? <code> < KeyBinding Gesture= '' Ctrl+S '' Command= '' Save '' / > < KeyBinding Gesture= '' Ctrl+Shift+S '' Command= '' SaveAs '' / >
How can I ensure that only one KeyBinding command is executed when a keyboard shortcut is used ?
C_sharp : I just wonder how to write a number that has to be expressed as string.For instance : or or or <code> if ( SelectedItem.Value == 0.ToString ( ) ) ... if ( SelectedItem.Value == `` 0 '' ) ... public const string ZeroNumber = `` 0 '' ; if ( SelectedItem.Value == _zeroNumber ) ... if ( Int.Parse ( SelectedItem.Value ) == 0 )
BestPractice for conditions with strings and numbers
C_sharp : Excuse the poor wording , but I could n't find a better way to explain it.From my understanding , C # is a WORA language- you can write it on one machine and deploy it on another , because the MSIL is n't compiled until the application is actually run.So then why is it that BitConverter.IsLittleEndian is defined like so : BIGENDIAN here is a preprocessor directive , which means that it 's resolved at compile-time . So if the developer 's machine is little endian , and the target uses big endian , will IsLittleEndian still report true on the target machine ? <code> # if BIGENDIAN public static readonly bool IsLittleEndian /* = false*/ ; # else public static readonly bool IsLittleEndian = true ; # endif
Why is BIGENDIAN a directive if it 's not resolved at compile-time ?
C_sharp : I have a custom control that when I drag onto the form , creates the following designer.cs code : I 'd like it ( Visual Studio ) to completely ignore the .Color attribute and leave it be . How can I tell it to do that ? Thank you ! <code> // // colorPickerBackground// this.colorPickerBackground.Color = Color.Empty ; this.colorPickerBackground.Location = new System.Drawing.Point ( 256 , 175 ) ; this.colorPickerBackground.Name = `` colorPickerBackground '' ; this.colorPickerBackground.Size = new System.Drawing.Size ( 156 , 21 ) ; this.colorPickerBackground.TabIndex = 17 ; this.colorPickerBackground.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler ( this.colorPicke
How can I tell Visual Studio to not populate a field in the designer code ?
C_sharp : I 'm hunting down a bug in a large business application , where business processes are failing but partially persisted to the database . To make things harder to figure out , the process fails only once every few weeks , with hundreds of thousands successfully processed between every failure . The error frequency seems to go up when concurrency/number of worker processes goes up.So far , we 've been able to recreate what we 're seeing with this program . ( .NET 4.7.1 framework ) Our production code does not explicitly make calls to transaction.Rollback ( ) , it is simply in my example as the means to reproduce the error message and behavior . But if any of our third party libraries makes this call , I would like to throw exception and exit as soon as possible . Preferably in the application layer.How can I detect that the call to Rollback ( ) has been made ? I really do not want to make crud operations without being sure that the transactionScope is able to do it 's job.Update 1My unwanted `` rollback '' was caused by a bug somewhere in the connection sharing mechanism of .Net . The bug is reproduced on all .Net Framework version between 4.5.1 and 4.8 , and also on the new System.Data.SqlClient package.An issue has been added to the System.Data.SqlClient repository . <code> using ( var transactionScope = new TransactionScope ( TransactionScopeOption.RequiresNew ) ) { using ( var sqlConnection = new SqlConnection ( `` Server=localhost ; Database=Database1 ; Trusted_Connection=True '' ) ) { sqlConnection.Open ( ) ; // Doing some unwanted nested manual transaction and rolling it back var transaction = sqlConnection.BeginTransaction ( ) ; new SqlCommand ( $ '' INSERT INTO TestTable VALUES ( 'This will be rolled back } ' ) '' , sqlConnection ) .ExecuteNonQuery ( ) ; transaction.Rollback ( ) ; // Now doing some work with the DB . // You might expect it to become a part of transactionScope , but that is NOT the case ! // So this command will actually succeed , with data written to the DB . new SqlCommand ( $ '' INSERT INTO TestTable VALUES ( 'This will be inserted ' ) '' , sqlConnection ) .ExecuteNonQuery ( ) ; // Doing something which promotes the local transaction to a distributed transaction . using ( var sqlConnection2 = new SqlConnection ( `` Server=localhost ; Database=Database2 ; Trusted_Connection=True '' ) ) { // The program will fail here , with message `` The transaction has aborted , Failure while attempting to promote transaction . '' sqlConnection2.Open ( ) ; new SqlCommand ( $ '' INSERT INTO TestTable2 VALUES ( 'We will never come this far ' ) '' , sqlConnection2 ) .ExecuteNonQuery ( ) ; } } transactionScope.Complete ( ) ; }
How to detect that rollback has occurred ?
C_sharp : By abusing the type system in c # , I can create code , where the compiler will enforce a rule , to ensure an impossible operation is not performed . In the below code , its specific to matrix multiplication . Obviously the below is totally impractical/wrong , but are there reasons we cant have something like this in c # in the future , where I could define a type like Matrix < 2,2 > and have the compiler ensure safety ? Also , does anything like this exist in any mainstream languages ? I 'd suspect something like this might be possible with metaprogramming in C++ ? ? <code> public abstract class MatrixDimension { } public class One : MatrixDimension { } public class Two : MatrixDimension { } public class Three : MatrixDimension { } public class Matrix < TRow , TCol > where TRow : MatrixDimension where TCol : MatrixDimension { // matrix mult . rule . N×M * M×P = N×P public Matrix < TRow , T_RHSCol > Mult < T_RHSCol > ( Matrix < TCol , T_RHSCol > rhs ) where T_RHSCol : MatrixDimension { return null ; } } public class TwoByTwo : Matrix < Two , Two > { } public void Main ( ) { var twoByTwo = new Matrix < Two , Two > ( ) ; var oneByTwo = new Matrix < One , Two > ( ) ; var twoByThree = new Matrix < Two , Three > ( ) ; var threeByTwo = new Matrix < Three , Two > ( ) ; var _twoByTwo = new TwoByTwo ( ) ; var _2x2 = twoByTwo.Mult ( twoByTwo ) ; var _1x2 = oneByTwo.Mult ( twoByTwo ) ; var _3x3 = twoByThree.Mult ( threeByTwo ) ; var _2x2_ = _twoByTwo.Mult ( twoByTwo ) ; var invalid = twoByThree.Mult ( twoByThree ) ; // compile fails , as expected }
Using generics to enforce valid structure at compile time
C_sharp : Im using this code to Send a Mail with excel attachment from gridview , it works fine for the mail part but the excel attachment is always blank i have already debugged the code and sure that the datasource of the Gridview passes the data it needed to the gridview , it seems that im not rendering the gridview to excel right . the whole process is in a for each loop depending on the number of elements inside the foreach..am i missing some code ? <code> protected void MailButton_Click ( object sender , EventArgs e ) { List < FOAM > foamList = new List < FOAM > ( servs.GetAreaList ( ) ) ; foreach ( FOAM foam in foamList ) { Session [ `` Area '' ] = foam.ItemAreaCode ; Session [ `` Principal '' ] = foam.PrincipalAmount ; Session [ `` Accountability '' ] = foam.AccountableAmount ; Session [ `` Count '' ] = foam.ItemCount ; foamdetails.ItemAreaCode = foam.ItemAreaCode ; FOAMTemplateGridview.DataSource = servs.GetFoamAsOfUnsettledforAOM ( foamdetails ) ; FOAMTemplateGridview.DataBind ( ) ; StringWriter _writer = new StringWriter ( ) ; HttpContext.Current.Server.Execute ( `` AreaManagersMail.aspx '' , _writer ) ; StringWriter stw = new StringWriter ( ) ; HtmlTextWriter hw = new HtmlTextWriter ( stw ) ; FOAMTemplateGridview.RenderControl ( hw ) ; MailMessage newMail = new MailMessage ( ) ; newMail.Priority = MailPriority.High ; newMail.To.Add ( `` test @ test.com '' ) ; newMail.Subject = `` Unsettled FOAM As of `` + DateTime.Today.ToString ( `` MMMM dd , yyyy '' ) + `` -A '' + foam.ItemAreaCode ; System.Text.Encoding Enc = System.Text.Encoding.ASCII ; byte [ ] mBArray = Enc.GetBytes ( stw.ToString ( ) ) ; System.IO.MemoryStream mAtt = new System.IO.MemoryStream ( mBArray , false ) ; newMail.Attachments.Add ( new Attachment ( mAtt , `` test.xls '' ) ) ; newMail.Body = _writer.ToString ( ) ; newMail.From = new MailAddress ( `` test @ test.com '' ) ; newMail.IsBodyHtml = true ; SmtpClient SmtpSender = new SmtpClient ( ) ; SmtpSender.Port = 25 ; SmtpSender.Host = `` MailHost '' ; SmtpSender.Send ( newMail ) ; newMail.Dispose ( ) ; } }
Retrieving Blank Excel upon attaching excel in Mail
C_sharp : Feel free to load your guns and take aim , but I want to understand why you should n't do this.I have created a custom class designed to replace any instances of List ( which I use to update XML objects behind them ) : The idea is whenever I add or remove an item from this list my bound events will fire and I can deal with the XML behind automatically.This works like a charm , so far so good.But how do I handle a conversion between object.ToList ( ) and my derived version ? A lot of people are saying you should derive from Collection instead ... why ? <code> public class ListwAddRemove < T > : List < T > { public event EventHandler < ListModifyEventArgs > OnAdd ; public event EventHandler < ListModifyEventArgs > OnRemove ; new public void Add ( T o ) { base.Add ( o ) ; if ( OnAdd ! = null ) { OnAdd ( this , new ListModifyEventArgs ( o ) ) ; } } new public void Remove ( T o ) { base.Remove ( o ) ; if ( OnRemove ! = null ) { OnRemove ( this , new ListModifyEventArgs ( o ) ) ; } } }
Custom ( derived ) List < T >
C_sharp : Here is an example of a property I have , coded as simply as possibleThis is verbose ; I would like to make it more concise if possible . The following would be acceptable ... ... but it does n't compile . Keyword 'this ' is not valid in a static property , static method , or static field initializerSo I came up with the followingWhich I like best , but is there a better way ? Note - I realize that mutable structs are usually evil , but they seem really useful for this one particular problem . <code> private IEnumerable < int > _blocks ; private bool _blocksEvaluated ; public IEnumerable < int > Blocks { get { if ( ! _blocksEvaluated ) { _blocksEvaluated = true ; _blocks = this.CalculateBlocks ( 0 ) .FirstOrDefault ( ) ; } return _blocks ; } } private Lazy < IEnumerable < int > > _blocks = new Lazy < IEnumerable < int > > ( ( ) = > this.CalculateBlocks ( 0 ) .FirstOrDefault ( ) ) ; struct MyLazy < TResult > { private bool evaluated ; private TResult result ; public TResult Evaluate ( Func < TResult > func ) { if ( ! evaluated ) { evaluated = true ; result = func ( ) ; } return result ; } } private MyLazy < IEnumerable < int > > _blocks ; public IEnumerable < int > Blocks { get { return _blocks.Evaluate ( ( ) = > this.CalculateBlocks ( 0 ) .FirstOrDefault ( ) ) ; } }
Lazy property requiring `` this ''
C_sharp : Edit : Solved ! thanks to @ kfinity.AskTom suggests using select /*+ opt_param ( '_optimizer_use_feedback ' 'false ' ) */ at the start of your query to disable the feedback usage . This has fixed the problem for me.tldr : Adding a randomized comment to a query makes it run consistent , removing this comment breaks it.Warning : long.EnvironmentMy preferred way of working is with queries in the source as string so that they are in version control and I can see changes over time . Along with that I use dapper and the oracle.ManagedDataAccess NuGet package . The application in question is a WPF app ( in both cases ) running on .NET framework 4.7.2 . I 'm using Visual studio professional 2017 15.9.5.The problemAbout a year back I encountered this problem with a query . I do n't remember which it was , I do know that I did n't have the time to document it and post it here . I do now and I ran into the same problem . Back then I somehow figured out that if I restarted my PC or changed the query text , it would run fine again . Just occasionally the symptoms of the problem would show up , I 'd add a comment to the query , or remove the one previously there , I would test that specific function every release . I 'd test it everytime because if it was faulty on my machine , it would also be faulty on the target user machine . At the time I figured it was a driver/hardware issue with my pc . The way I figured out I could fix it by changing the query text is because I would cut and paste ( ctrl-x ctrl-v ) the entire query from the code to Oracle developer and edit it there . At some point I noticed even an extra whitespace or enter would make it work again.Back to now , I 've got the problem again . This time it 's different because it does n't fail occasionally anymore . It 's very consistent . Thinking back about how I figured this was a driver/hardware issue , I build and ran the application on 3 different machines , all the same results . I can run the query in Oracle developer , using ctrl + end to run the entire query , not just 50 lines . It runs in about 10 seconds . It runs consistently , over and over again , which makes sense if nothing changes.If I run it from my application , it runs fine - but only once . It takes about 10 seconds as well . If I refresh the data , which runs the query again , it hangs . There are no exceptions , if I break the debugger it 's just chilling on the database.Query < > ( ) call . If I either restart my PC or change the query , it will run - exactly once.v $ session_longops/full table scanOf course , I went to google for help . Found some interesting articles that did n't really help me along : https : //mjsoracleblog.wordpress.com/2014/10/24/oracle-performance-mystery-wildly-varying-query-response-time/Oracle inconsistent performance behaviour of queryUntil I found this : https : //asktom.oracle.com/pls/asktom/f ? p=100:11:0 : : : :P11_QUESTION_ID:1191435335912They mention v $ session_longops which supposedly gives us insight into long running operations.I ran this while I had just refreshed the data in the application , causing the query to run for a second time . I see this : The first query ran fine , indexes where fine . The 2nd time it started up a full table scan . It does n't need this because it runs fine in the first time and in oracle developer as well . As expected , if I leave it running ( takes over 20 minutes ) the table scan completes and I get the same result as the first time around.I found that you can use explain plan for to explain a query plan without using the GUI in Oracle developer . This gave me 2 wildly different plans , the one in Oracle developer always has this note : - 'PLAN_TABLE ' is old version . So I 'm not sure that I can trust this information , I do n't know what to do with it.Plan from Oracle developerPlan from codeThe fixLike I said before , adding or removing a comment or rather changing the query text fixes the problem and does n't start a full table scan , ever . I added a comment containing DateTime.Now to the query so that it is always different . It consistently works . While technically this fixes the problem I think it is quite a ridiculous fix to an even more ridiculous problem . I 'd rather know why this happens and if maybe I 'm doing something else wrong . So the question is , why does a randomized comment fix my query ? The codeSome context : this is an ERP system , the query gets all the workorders that have a hierarchic structure , or that are just on themselves , combines them , then adds their required materials and some other information like their description . It only does this for workorders that are not closed yet.SQL : C # ( does NOT work ) : C # ( does work consistently ) : <code> select *from v $ session_longopswhere time_remaining > 0 select -- Hierarchic info , some aliases exceeded 30 chars and had to be shorted to current state hierarchic_workorders.ccn as HierarchicCcn , hierarchic_workorders.mas_loc as HierarchicMasLoc , hierarchic_workorders.wo_num as HierarchicWoNum , hierarchic_workorders.wo_line as HierarchicWoLine , wo.item as HierarchicItem , wo.revision as HierarchicRevision , wo_item.description as HierarchicDescription , wo_rtg.wc as HierarchicWorkCenter , hierarchic_workorders.startdate as HierarchicStartDate , hierarchic_workorders.mfgclosedate as HierarchicMfgClosedDate , hierarchic_workorders.chassisnumbers as HierarchicChassisNumbers , hierarchic_workorders.wo_level as HierarchicLevel , hierarchic_workorders.parent_wo_num as HierarchicParentWoNum , hierarchic_workorders.parent_wo_line as HierarchicParentWoLine , hierarchic_workorders.parent_wo_bom_useq as HierarchicParentwobomuseq , -- wo bom info wo_bom.ccn as WoRtgCcn , wo_bom.mas_loc as WoRtgMasloc , wo_bom.wo_num as WoRtgWoNum , wo_bom.wo_line as WoRtgWoLine , wo_bom.wo_bom_useq as WoRtgWobomUseq , wo_bom.item as WoRtgItem , wo_bom.revision as WoRtgRevision , wo_bom_item.description as WoRtgDescription , wo_bom.bom_comp_qty as WoRtgBomCompQty , wo_bom.bom_commit as WoRtgCommit , wo_bom.backflush as WoRtgBackflush , wo_bom.issue_qty as WoRtgIssueQty , wo_bom.commit_qty as WoRtgCommitQty , wo_bom.reqd_qty as WoRtgReqdQtyfrom live.wo_bom -- =========================================================================================================================================================================== -- Maybe it 's possible to remove this or the other min operation join in hierarchic_workorders , to make it faster - not sure if possible ==================================== -- ===========================================================================================================================================================================left join ( select wo_rtg_min_operation.min_operation , wo_rtg . * from live.wo_rtg left join ( select ccn , mas_loc , wo_num , wo_line , lpad ( to_char ( min ( to_number ( trim ( operation ) ) ) ) , 4 , ' ' ) as min_operation from live.wo_rtg group by ccn , mas_loc , wo_num , wo_line ) wo_rtg_min_operation on wo_rtg_min_operation.ccn = wo_rtg.ccn and wo_rtg_min_operation.mas_loc = wo_rtg.mas_loc and wo_rtg_min_operation.wo_num = wo_rtg.wo_num and wo_rtg_min_operation.wo_line = wo_rtg.wo_line ) wo_rtg on wo_rtg.ccn = wo_bom.ccn and wo_rtg.mas_loc = wo_bom.mas_loc and wo_rtg.wo_num = wo_bom.wo_num and wo_rtg.wo_line = wo_bom.wo_line -- This case when is painfully slow but it ca n't really be cached or indexed and wo_rtg.operation = ( case when wo_bom.operation = ' ' then wo_rtg.min_operation else wo_bom.operation end ) -- =========================================================================================================================================================================== -- Find all open MPS orders and highest hierarchic PRP orders . Having these be a subquery instead of the starting data drastically increases performance ======================== -- ===========================================================================================================================================================================join ( select ccn , mas_loc , wo_num , wo_line , startdate , mfgclosedate , chassisnumbers , wo_level , parent_wo_num , parent_wo_line , parent_wo_bom_useq from ( -- =========================================================================================================================================================================== -- PRP ====================================================================================================================================================================== -- =========================================================================================================================================================================== select 'PRP ' as type , wowob.ccn , wowob.mas_loc , wowob.wo_num , wowob.wo_line , apssplit_min_operation.operation_start_date as startdate , wo.mfg_close_date as mfgclosedate , trim ( trim ( wo.user_alpha2 ) || ' ' || trim ( wo.user_alpha3 ) || ' ' || trim ( wo.chassis3 ) || ' ' || trim ( wo.chassis4 ) || ' ' || trim ( wo.chassis5 ) ) as chassisnumbers , level as wo_level , wowob.parent_wo_num , wowob.parent_wo_line , wowob.parent_wo_bom_useq from live.wowob join live.wo on wo.ccn = wowob.ccn and wo.mas_loc = wowob.mas_loc and wo.wo_num = wowob.wo_num and wo.wo_line = wowob.wo_line left join ( select ccn , mas_loc , orderident , order_line , lpad ( to_char ( min ( to_number ( trim ( operation ) ) ) ) , 4 , ' ' ) as min_operation , operation_start_date from live.apssplit where schedule = 'SHOP ' and order_type = ' W ' group by ccn , mas_loc , orderident , order_line , operation_start_date ) apssplit_min_operation on apssplit_min_operation.ccn = wowob.ccn and apssplit_min_operation.mas_loc = wowob.mas_loc and apssplit_min_operation.orderident = wowob.wo_num and apssplit_min_operation.order_line = wowob.wo_line -- Only select open wo 's -- Underlying wo 's obviously have to start BEFORE their parents , we do n't have to check them all for this reason . where apssplit_min_operation.operation_start_date is not null and apssplit_min_operation.operation_start_date < sysdate + : days_ahead -- wo.mfg_close_date is null and -- wo.fin_close_date is null and -- wo.ord_qty - wo.scrap_qty - wo.complete_qty > 0 -- and wo.start_date < sysdate + : days_ahead -- and wowob.wo_num = ' 334594 ' -- Grab the childs of only the highest parents . connect by prior wowob.ccn = wowob.ccn and prior wowob.mas_loc = wowob.mas_loc and prior wowob.wo_num = wowob.parent_wo_num and prior wowob.wo_line = wowob.parent_wo_line start with wowob.ccn || wowob.mas_loc || wowob.wo_num || wowob.wo_line in ( -- Subquery to select all the highest hierarchic wowob 's that are still open in wo . -- Performance : -- all : 21253 in ? -- Open only : 174 in 0.155 seconds select wowob.ccn || wowob.mas_loc || wowob.wo_num || wowob.wo_line as wowob_key from live.wowob -- Parent join left join live.wowob parent_wowob on wowob.ccn = parent_wowob.ccn and wowob.mas_loc = parent_wowob.mas_loc and wowob.parent_wo_num = parent_wowob.wo_num and wowob.parent_wo_line = parent_wowob.wo_line -- end parent join where wowob.ccn = : ccn and wowob.mas_loc = : mas_loc and parent_wowob.ccn is null ) union all -- =========================================================================================================================================================================== -- MPS ====================================================================================================================================================================== -- =========================================================================================================================================================================== select 'MPS ' as type , wo.ccn , wo.mas_loc , wo.wo_num , wo.wo_line , apssplit_min_operation.operation_start_date as startdate , wo.mfg_close_date as mfgclosedate , trim ( trim ( wo.user_alpha2 ) || ' ' || trim ( wo.user_alpha3 ) || ' ' || trim ( wo.chassis3 ) || ' ' || trim ( wo.chassis4 ) || ' ' || trim ( wo.chassis5 ) ) as chassisnumbers , 1 as wo_level , `` as parent_wo_num , `` as parent_wo_line , `` as parent_wo_bom_useq from live.wo join live.item_ccn on item_ccn.ccn = wo.ccn and item_ccn.item = wo.item and item_ccn.revision = wo.revision and item_ccn.mastsched = ' Y ' -- mps and item_ccn.planned = ' ' -- mrp and item_ccn.prp = ' ' -- NOT prp ... left join ( select ccn , mas_loc , orderident , order_line , lpad ( to_char ( min ( to_number ( trim ( operation ) ) ) ) , 4 , ' ' ) as min_operation , operation_start_date from live.apssplit where schedule = 'SHOP ' and order_type = ' W ' group by ccn , mas_loc , orderident , order_line , operation_start_date ) apssplit_min_operation on apssplit_min_operation.ccn = wo.ccn and apssplit_min_operation.mas_loc = wo.mas_loc and apssplit_min_operation.orderident = wo.wo_num and apssplit_min_operation.order_line = wo.wo_line -- Only select open wo 's -- Underlying wo 's obviously have to start BEFORE their parents , we do n't have to check them all for this reason . where apssplit_min_operation.operation_start_date is not null and apssplit_min_operation.operation_start_date < sysdate + : days_ahead ) order by startdate ) hierarchic_workorders on hierarchic_workorders.ccn = wo_bom.ccn and hierarchic_workorders.mas_loc = wo_bom.mas_loc and hierarchic_workorders.wo_num = wo_bom.wo_num and hierarchic_workorders.wo_line = wo_bom.wo_line -- =========================================================================================================================================================================== -- Descriptions from wo . wowob and wo_bom are different items and they have different descriptions . ========================================================================= -- ===========================================================================================================================================================================left join live.wo on wo.ccn = hierarchic_workorders.ccn and wo.mas_loc = hierarchic_workorders.mas_loc and wo.wo_num = hierarchic_workorders.wo_num and wo.wo_line = hierarchic_workorders.wo_lineleft join live.item wo_item on wo_item.item = wo.item and wo_item.revision = wo.revisionleft join live.item wo_bom_item on wo_bom_item.item = wo_bom.item and wo_bom_item.revision = wo_bom.revision using ( IDbConnection database = new OracleConnection ( _applicationSettings.OracleConnectionString ) ) { DynamicParameters parameters = new DynamicParameters ( ) ; parameters.Add ( `` ccn '' , ccn ) ; parameters.Add ( `` mas_loc '' , masLoc ) ; parameters.Add ( `` days_ahead '' , daysAhead ) ; return database.Query < HierarchicWoWoBom > ( Query , parameters ) .ToList ( ) ; } using ( IDbConnection database = new OracleConnection ( _applicationSettings.OracleConnectionString ) ) { DynamicParameters parameters = new DynamicParameters ( ) ; parameters.Add ( `` ccn '' , ccn ) ; parameters.Add ( `` mas_loc '' , masLoc ) ; parameters.Add ( `` days_ahead '' , daysAhead ) ; return database.Query < HierarchicWoWoBom > ( $ '' -- { DateTime.Now } : randomized comment so that this query keeps working.\n '' + Query , parameters ) .ToList ( ) ; }
Oracle query only runs consistently when adding a random comment
C_sharp : This is my very first question after many years of lurking here , so I hope I do n't break any rules.In some of my ASP.NET Core API 's POST methods , I 'd like to make it possible for clients to provide only the properties they want to update in the body of their POST request.Here 's a simplified version of my code : MaxBar and MaxFoo both are nullable integer values , where the null value signifies there 's no maximum.I 'm trying to make it possible to let clients send e.g . the following to this endpoint : Setting MaxBar to null , and setting MaxFoo to 10Setting MaxBar to null , not touching MaxFooUpdate MaxBar to 5 , not touching MaxFooIn my method UpdateFooAsync , I want to update only the properties that have been specified in the request.However , when model binding occurs , unspecified properties are set to their default values ( null for nullable types ) .What would be the best way to find out if a value was explicitly set to null ( it should be set to null ) , or was just not present in the request ( it should not be updated ) ? I 've tried checking the ModelState , but it contained no keys for the 'model ' , only for the Guid typed parameter.Any other way to solve the core problem would be welcome as well , of course.Thanks ! <code> [ Route ( `` api/v { version : apiVersion } / [ controller ] '' ) ] [ ApiController ] public sealed class FooController : ControllerBase { public async Task < IActionResult > UpdateFooAsync ( Guid fooGuid , [ FromBody ] UpdateFooModel model ) { ... Apply updates for specified properties , checking for authorization where needed ... return Ok ( ) ; } } public sealed class UpdateFooModel { [ BindProperty ] public int ? MaxFoo { get ; set ; } [ BindProperty ] public int ? MaxBar { get ; set ; } } public sealed class Foo { public int ? MaxFoo { get ; set ; } public int ? MaxBar { get ; set ; } } { `` maxBar '' : null , `` maxFoo '' : 10 } { `` maxBar '' : null } { `` maxBar '' : 5 }
Differentiating between explicit 'null ' and 'not specified ' in ASP.NET Core ApiController
C_sharp : Suppose , we have a very simple class : and we want to make an instance of this class : So , in case of List2 it is ok , using `` = '' we set property . But in List1 case it looks like we set property , but actually , we suppose to set it somewhere before , and here we only set values . And it very similar to array initializing : Why C # uses this confusing syntax here ? Edit : I guess I confused many viewers with C # 6.0 syntax , but it 's not the point . Let 's use old good C # 3.0 and .net 2.0 . And lets add more fun too this and add some values ( `` 1 '' and `` 2 '' ) to the list from start , as Jeff Mercado recommended : It shows the same weird syntax . And at the end I have list { `` 1 '' , `` 2 '' , `` asdf '' , `` qwer '' } , which is even more confusing . I can expect this the less . <code> class ObjectList { public List < string > List1 { get ; } = new List < string > ( ) ; public List < string > List2 { get ; set ; } } ObjectList objectList = new ObjectList { List1 = { `` asdf '' , `` qwer '' } , List2 = new List < string > { `` zxcv '' , `` 1234 '' } } ; string [ ] arr = { `` val1 '' , `` val2 '' } class Program { static void Main ( string [ ] args ) { ObjectList objectList = new ObjectList { List1 = { `` asdf '' , `` qwer '' } , } ; } } class ObjectList { List < string > _List1 = new List < string > ( ) { `` 1 '' , `` 2 '' } ; public List < string > List1 { get { return _List1 ; } } }
Weird syntax of collection initializers
C_sharp : I am doing a Func - > Expression - > Func conversion . It works fine if I create the Func < > ( ) from a method ( first example below ) however if I create the function using an expression tree ( 2nd example ) it fails with a NullReferenceException when accessing func2.Method.DeclaringType.FullName . And this is because DeclaringType is null . ( NJection uses reflection so I think that is why it needs DeclaringType . ) How can I fill in DeclaringType type for the Func < > that was created by compiling an Expression Tree ? ( maybe its not possible ? ) DeclaringType is set in the first example.Using a Func < > from a Method ... ( works well ) Using an Expression tree ( does not work ) ... <code> // Build a Func < > Func < int , int > add = Add ; // Convert it to an Expression using NJection LibraryExpression < Func < int , int > > expr = ToExpr < Func < int , int > > ( add ) ; // Convert it back to a Func < > Func < int , int > func = expr.Compile ( ) ; // Run the Func < > int result = func ( 100 ) ; // Build a Func < > using an Expression TreeParameterExpression numParam = Expression.Parameter ( typeof ( int ) ) ; ConstantExpression five = Expression.Constant ( 5 , typeof ( int ) ) ; BinaryExpression numAddFive = Expression.Add ( numParam , five ) ; Func < int , int > func2 = Expression.Lambda < Func < int , int > > ( numAddFive , new ParameterExpression [ ] { numParam } ) .Compile ( ) ; // Convert to an Expression using NJection ( EXCEPTION ON NEXT LINE ) // ToExpr is trying to access func2.Method.DeclaringType.FullName ( DeclaringType is null ) Expression < Func < int , int > > exp2 = ToExpr < Func < int , int > > ( func2 ) ; // Convert it back to a Func < > Func < int , int > func2b = exp2.Compile ( ) ; // Run the Func < > int result2 = func2b ( 100 ) ;
Is there a way to set 'DeclaringType ' in an expression tree ?
C_sharp : The code below will compile but fails at runtime . It 's provided just to give an idea of what I 'm trying to do . What I would like to do is create a method that accepts a collection of objects ( effectively an `` untyped '' collection ) and if this collect is comprised of numbers of a single type return the mean using the Average ( ) extension method I 'm sure I could use reflection to find the appropriate Average method and invoke it ( not pretty ) . Is there a shorter/cleaner/better way to do this ? I can use the latest C # and .NET runtime . <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace nnConsole { class Program { static void Main ( string [ ] args ) { var ints = new object [ 4 ] { 1 , 2 , 3 , 4 } ; var dbls = new object [ 4 ] { 1.0 , 2.0 , 3.0 , 4.0 } ; Console.WriteLine ( ReallyMean ( ints ) ) ; Console.WriteLine ( ReallyMean ( dbls ) ) ; } static public double ReallyMean ( ICollection < object > data ) { var unique = data.Distinct ( ) ; var types = unique.Select ( x = > x.GetType ( ) ) .Distinct ( ) ; if ( types.Count ( ) == 1 ) { if ( types.First ( ) .IsValueType ) { /*********************** * magic here to create ddata var that will * call the appropriate extension method for average */ dynamic ddata = data ; // DOES NOT WORK return ddata.Average ( ) ; } } return double.NaN ; } } }
Is there a clever way to call a type dependent extension method dynamically ?
C_sharp : The above code is copy from Page 153 c # in a Nutshell , I do n't understand why the { } are missing after the using statement , is that a typo in the book ( unlikely ) or just not needed ? As the syntax is that using need to follow by a block of code inside { } .I would expect this code to be : <code> using System.Net ; // ( See Chapter 16 ) ... string s = null ; using ( WebClient wc = new WebClient ( ) ) // why there is no brackets after this using statement try { s = wc.DownloadString ( `` http : //www.albahari.com/nutshell/ '' ) ; } catch ( WebException ex ) { if ( ex.Status == WebExceptionStatus.Timeout ) Console.WriteLine ( `` Timeout '' ) ; else throw ; // Ca n't handle other sorts of WebException , so rethrow } using System.Net ; // ( See Chapter 16 ) ... string s = null ; using ( WebClient wc = new WebClient ( ) ) // why there is no brackets after this using statement { try { s = wc.DownloadString ( `` http : //www.albahari.com/nutshell/ '' ) ; } catch ( WebException ex ) { if ( ex.Status == WebExceptionStatus.Timeout ) Console.WriteLine ( `` Timeout '' ) ; else throw ; // Ca n't handle other sorts of WebException , so rethrow } }
c # `` using '' statement follow by try statement can the bracket be ombitted in that case ?
C_sharp : I safely search a list for an object like this : If there are no objects that match my criteria then someResult is going to be null.But if I only have the index of the object I want , things are not so nice . I seem to have to so something like this : I admit that is not terrible to have to write . But it seems to me that there should be a way to just have the list return null if the index ends up being bogus.Is there away to have a one ( or two ) line look up using existing .net methods ? ( I know I could easily write an extension method , but I am wondering if there is a built in way to do this . ) <code> var someResult = myList.FirstOrDefault ( x= > x.SomeValue == `` SomethingHere '' ) ; try { var someResult = myList [ 4 ] ; } catch ( ArgumentOutOfRangeException ) { someResult = null ; }
Is there a concise built-in way to get a list item by index that is not going to throw an exception ?
C_sharp : I have a custom class that I use to build table strings . I would like to rewrite the code so that I can chain the operators . Something like : So it seems like I would have each of these methods ( functions ) return the object itself so that I can then call another method ( function ) on the resulting object , but I ca n't figure out how to get a c # class to refer to itself.Any help ? <code> myObject .addTableCellwithCheckbox ( `` chkIsStudent '' , isUnchecked , isWithoutLabel ) .addTableCellwithTextbox ( `` tbStudentName '' , isEditable ) etc .
How do I declare a class in C # so that I can chain methods ?
C_sharp : So I have a dotNet CoreCLR application for hololens and it 's my understanding that standard sockets are n't supported in CoreCLR and the recommended avenue is to use StreamSocket.It 's also my understanding that CodedInputStream and StreamSocket are n't compatible.So I 've been manually trying to decode the size pre-send but it 's a varInt32 which can be anything from 2-4 bytes . This is as far as I 've gotten but that variable size issue is giving me problems.Any suggestions on how I might fix this code or alternatives I might use ? Edit : I 've also had a look at the CodedInputStream.cs SlowReadRawVarint32 ( ) and tried this with no success ... I 'm thinking the DataReader is doing something non-standard . <code> int bytenum = 0 ; int num = 0 ; while ( ( bytes [ bytenum ] & 0x80 ) == 0x80 ) { bytenum++ ; } while ( bytenum > = 0 ) { int tem = bytes [ bytenum ] & 0x7F ; num = num < < 7 ; num = num | tem ; bytenum -- ; } var dr = new DataReader ( socket.InputStream ) ; await dr.LoadAsync ( 1 ) ; int result = -1 ; int tmp = dr.ReadByte ( ) ; if ( tmp > = 128 ) { result = tmp & 0x7f ; await dr.LoadAsync ( 1 ) ; if ( ( tmp = dr.ReadByte ( ) ) < 128 ) { result |= tmp < < 7 ; } else { result |= ( tmp & 0x7f ) < < 7 ; await dr.LoadAsync ( 1 ) ; if ( ( tmp = dr.ReadByte ( ) ) < 128 ) { result |= tmp < < 14 ; } else { result |= ( tmp & 0x7f ) < < 14 ; await dr.LoadAsync ( 1 ) ; if ( ( tmp = dr.ReadByte ( ) ) < 128 ) { result |= tmp < < 21 ; } else { result |= ( tmp & 0x7f ) < < 21 ; await dr.LoadAsync ( 1 ) ; result |= ( tmp = dr.ReadByte ( ) ) < < 28 ; if ( tmp > = 128 ) { // Discard upper 32 bits . for ( int i = 0 ; i < 5 ; i++ ) { await dr.LoadAsync ( 1 ) ; if ( dr.ReadByte ( ) < 128 ) { } } } } } } } else { result = tmp ; }
Manually decoding the Size presend on a CodedInputStream
C_sharp : I have a MyProject project where I have IMyService interface and MyService class that implements IMyService . In Startup.cs class I dependency injection them : Because MyService has many dependencies ( makes many REST calls to 3rd party etc . ) I would like to create a stub version of it for development environment . I created new MyStubsProject that references to MyProject . And I implemented stub version of IMyService to MyStubsProject : So now I want to add dependency injection to Startup.cs class : But if I add that , there will be circular dependency between MyProject and MyStubsProject.How should I implement reference to the class MyStubService or MyStubsProject project in Startup.cs ? <code> // MyProject project | Startup.cspublic void ConfigureServices ( IServiceCollection services ) { services.AddScoped < IMyService , MyService > ( ) ; } // MyStubsProject projectpublic class MyStubService : IMyService { ... } // MyProject project | Startup.cspublic void ConfigureServices ( IServiceCollection services ) { if ( isDevelopmentEnvironment ) services.AddScoped < IMyService , MyStubService > ( ) ; else services.AddScoped < IMyService , MyService > ( ) ; }
How to implement dependency injection in Startup.cs when dependencies are circular ?
C_sharp : ContextI have two classes : LiteralModel is a wrapper around a string Value property . Expression has a string Name and a LiteralModel called Literal.All are public properties with public getters and setters , and so I would expect both of them to serialize and deserialize easily , even with the null guards , and , for the most part , they do . The ProblemThe Literal property of the ExpressionModel does not deserialize properly . Below is a minimal test that demonstrates the issue : As you can see , the JSON looks how I want/expect , ( wrapping the string `` 61 '' ) , but when I deserialize that back into an ExpressionModel , the Literal test fails -- it gets a LiteralModel of an empty string.What I 've TriedIf I remove the smart-ness of the Literal getter of the expression model , it behaves as expected -- all tests pass . But smart properties do work on the string properties . So why not on my LiteralModel object ? Even weirder , all tests pass if I move the null-check to the setter instead of the getter like so : ConclusionIn short , nothing phases the serializer , and smart setters are fine , but smart getters break deserialization , except for string . This seems like wildly arbitrary behavior . Does anyone know why this might be or if there 's any way to get these classes to work as written ? <code> public class ExpressionModel { private string name ; public string Name { get = > name ? ? `` `` ; set = > name = value ; } private LiteralModel literal ; public LiteralModel Literal { get = > literal ? ? new LiteralModel ( ) ; set = > literal = value ; } } public class LiteralModel { private string value ; public string Value { get = > value ? ? `` `` ; set = > this.value = value ; } } public void TestNewtonsoftExpressionDeserialization ( ) { ExpressionModel expression = new ExpressionModel { Name = `` test '' , Literal = new LiteralModel { Value = `` 61 '' } } ; string json = JsonConvert.SerializeObject ( expression ) ; Assert.IsTrue ( json.Contains ( `` 61 '' ) ) ; // passes ExpressionModel sut = JsonConvert.DeserializeObject < ExpressionModel > ( json ) ; Assert.AreEqual ( `` test '' , sut.Name ) ; // passes Assert.AreEqual ( `` 61 '' , sut.Literal.Value ) ; // fails } public LiteralModel Literal { get = > literal ; set = > literal = value ? ? new LiteralModel ( ) ; }
Why does the Newtonsoft deserializer not deserialize a smart getter ?
C_sharp : I have two unit tests that use TypeMock Isolator to isolate and fake a method from asp.net 's SqlMembershipProvider.In test 1 I have : In test 2 I have : When I run each test by itself they both pass successfully . When I run both tests , test number 1 runs first and passes , then test number 2 runs and fails with the exception thrown in test 1.Why would the WillThrow ( ) instruction in test 1 `` bleed over '' to test 2 ? After all , test 2 explicitly defines different behavior - WillReturn ( ) ? <code> Isolate.WhenCalled ( ( ) = > Membership.CreateUser ( ... ) ) ) .WithExactArguments ( ) .WillThrow ( new Exception ( ) ) ; Isolate.WhenCalled ( ( ) = > Membership.CreateUser ( ... ) ) ) .WithExactArguments ( ) .WillReturn ( new MembershipUser ( ... ) ) ;
TypeMock Isolator : WillThrow ( ) bleeds across unit test boundaries ?
C_sharp : I discovered a strange behavior when using property indexer ( C # ) .Consider the following program : Why do I get all results back when using the default indexer ( the x2 variable ) ? It seems that the int parameter ( 0 ) is automatically converted to the enum type ( Type1 ) . This is not what I was expecting ... .Thanks in advance for the explanations ! <code> public class Program { public static void Main ( string [ ] args ) { CustomMessageList cml = new CustomMessageList { new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) // Type1 } ; // Empty IEnumerable < CustomMessage > x1 = cml [ MessageType.Type2 ] ; // Contains all elements ( 6 ) IEnumerable < CustomMessage > x2 = cml [ 0 ] ; // MessageType.Type1 ? ? ? ? // Does not compile ! IEnumerable < CustomMessage > x3 = cml [ 1 ] ; // NOT MessageType.Type2 ? ? ? ? } } public class CustomMessageList : List < CustomMessage > { public IEnumerable < CustomMessage > this [ MessageType type ] { get { return this.Where ( msg = > msg.MessageType == type ) ; } } } public class CustomMessage { public MessageType MessageType { get ; set ; } } public enum MessageType { Type1 , Type2 , Type3 }
Property indexer with default 0 ( zero ) value
C_sharp : I have an employees list in my application . Every employee has name and surname , so I have a list of elements like : I want my customers to have a feature to search employees by names with a fuzzy-searching algorithm . For example , if user enters `` Yuma Turmon '' , the closest element - `` Uma Turman '' will return . I use a Levenshtein distance algorithm , I found here.I iterate user 's input ( full name ) over the list of employee names and compare distance . If it is below 3 , for example , I return found employee.Now I want allow users to search by reversed names - for example , if user inputs `` Turmon Uma '' it will return `` Uma Turman '' , as actually real distance is 1 , because First name and Last name is the same as Last name and First name . My algorithm now counts it as different strings , far away . How can I modify it so that names are found regardless of order ? <code> [ `` Jim Carry '' , `` Uma Turman '' , `` Bill Gates '' , `` John Skeet '' ] static class LevenshteinDistance { /// < summary > /// Compute the distance between two strings . /// < /summary > public static int Compute ( string s , string t ) { int n = s.Length ; int m = t.Length ; int [ , ] d = new int [ n + 1 , m + 1 ] ; // Step 1 if ( n == 0 ) { return m ; } if ( m == 0 ) { return n ; } // Step 2 for ( int i = 0 ; i < = n ; d [ i , 0 ] = i++ ) { } for ( int j = 0 ; j < = m ; d [ 0 , j ] = j++ ) { } // Step 3 for ( int i = 1 ; i < = n ; i++ ) { //Step 4 for ( int j = 1 ; j < = m ; j++ ) { // Step 5 int cost = ( t [ j - 1 ] == s [ i - 1 ] ) ? 0 : 1 ; // Step 6 d [ i , j ] = Math.Min ( Math.Min ( d [ i - 1 , j ] + 1 , d [ i , j - 1 ] + 1 ) , d [ i - 1 , j - 1 ] + cost ) ; } } // Step 7 return d [ n , m ] ; } }
Implementing Levenstein distance for reversed string combination ?
C_sharp : is there any functional difference between : and if so , is there a more compelling reason to use one over the other ? <code> if ( photos.Any ( it = > it.Archived ) ) if ( photos.Where ( it = > it.Archived ) .Any ( ) )
are these two linq expressions functionally equivalent ?
C_sharp : I 'm working on optimization techniques performed by the .NET Native compiler.I 've created a sample loop : And I 've compiled it with Native . Then I disassembled the result .dll file with machine code inside in IDA . As the result , I have : ( I 've removed a few unnecessary lines , so do n't worry that address lines are inconsistent ) I understand that add esi , 0FFFFFFFFh means really subtract one from esi and alter Zero Flag if needed , so we can jump to the beginning if zero has n't been reached yet . What I do n't understand is why did the compiler reverse the loop ? I came to the conclusion that is just faster than for exampleBut is it really because of that and is the speed difference really significant ? <code> for ( int i = 0 ; i < 100 ; i++ ) { Function ( ) ; } LOOP : add esi , 0FFFFFFFFhjnz LOOP LOOP : inc esicmp esi , 064hjl LOOP
Why does .NET Native compile loop in reverse order ?
C_sharp : Basically , I want to write a wrapper for all ICollection < > types . Lets call it DelayedAddCollection . It should take any ICollection as its .Furthermore , I need access to that ICollection type 's generic type as the Add method needs to restrict its parameter to that type.The syntax I would imagine would look something like this ... What is the real correct syntax to do this ? <code> public DelayedAddConnection < T > : where T : ICollection < U > { ... . public void Add ( U element ) { ... } }
How do I create a generic class that takes as its generic type a generic class ?
C_sharp : I 'm working on Project Euler number 5 . I 've not Googled , as that will typically lead to a SO with the answer . So , this is what I 've got : In my mind , this makes sense . Yet VS2012 is giving me a StackOverFlowException suggesting I make sure I 'm not in an infinite loop or using recursion . My question is , why is this an infinite loop ? I 've a feeling I 'm missing something completely silly.EDITSince people seem to keep posting them , I 'll reiterate the fact that I did n't use Google for fear of stumbling on the answer . I do n't want the answer to the problem . I only wanted to know why I was getting the exception . <code> private int Euler5 ( int dividend , int divisor ) { if ( divisor < 21 ) { // if it equals zero , move to the next divisor if ( dividend % divisor == 0 ) { divisor++ ; return Euler5 ( dividend , divisor ) ; } else { dividend++ ; return Euler5 ( dividend , 1 ) ; // move to the dividend } } // oh hey , the divisor is above 20 , so what 's the dividend return dividend ; }
How to break out of this loop
C_sharp : I 'm trying to use a .NET Regex to validate the input format of a string . The string can be of the formatSo 0AAA , 107ZF , 503GH , 0AAAA are all valid . The string with which I construct my Regex is as follows : Yet this does not validate strings in which the second term is one of 03 , 07 or AA . Whilst debugging , I removed the third term from the string used to construct the regex , and found that input strings of the form 103 , 507 , 6AA WOULD validate ... ... . Any ideas why , when I then put the third term back into the Regex , the input strings such as 1AAGM do not match ? ThanksTom <code> single digit 0-9 followed bysingle letter A-Z OR 07 OR 03 or AA followed bytwo letters A-Z `` ( [ 0-9 ] { 1 } ) '' + `` ( ( 03 $ ) | ( 07 $ ) | ( AA $ ) | [ A-Z ] { 1 } ) '' + `` ( [ A-Z ] { 2 } ) ''
Simple Regular Expression ( Regex ) issue ( .net )
C_sharp : I have a method A ( ) that processes some queries . This method , from opening bracket to just before its return statement , times at +/-70ms . A good 50 % of which comes from opening the connection , about 20 % comes from the actual queries , 5-10 % is used by some memory access , the rest is ( probably ) used for disposing the connection , commands and reader.Although this big chunk of time used for handling the connection is annoying enough , what bothers me more is that when I call A ( ) from method B ( ) : Another 180ms of lag gets added and I ca n't seem to figure out why . I already tried having A return null , which changes nothing.The only disk I/O and networking happens in A. I thought the transfer from disk and network to local memory should 've happened in A , and therefore a call to A from B should not be influenced by this , but apparently this is not the case ? Is this network latency I 'm experiencing here ? If so , then why does this also happen when I just let B return null ? I have no other explanation at the moment ... Everything resides in the same assembly , Measuring without a debugger attached changes nothing , Returning 'null ' immediately show 0 ms , returning null instead of the normal return value changes nothing ( but enforces the idea this is somehow related to latency ) .A is roughly implemented as follows , like any simple method accessing a database . It 's contrived , but shows the basic idea and flow : Any ideas ? <code> B ( ) { var timer = Stopwatch.Startnew ( ) A ( ) ; timer.Stop ( ) ; // elapsed : +/- 250ms Debugger.Break ( ) ; } A ( ) { var totalTimer = Stopwatch.StartNew ( ) ; var stuff = new Stuffholder ( ) ; using ( connection ) { using ( command ) { using ( reader ) { // fill 'stuff ' } } } totalTimer.Stop ( ) ; // elapsed : +/- 70ms return stuff ; }
Overhead in returning from a method
C_sharp : I have two lists like these:2 list also have same size . I want some operations in listQ relation to listVal : if listVal 's any indexes have same values , I want to take average listQ 's values in same indexes . For example : So , I want listQ 's same indexes be same.Now , each these indexes must have 23.45 : Likewise ; listVal [ 0 ] [ 2 ] [ 0 ] = listVal [ 0 ] [ 2 ] [ 2 ] = 1 . Therefore listQ [ 0 ] [ 2 ] [ 0 ] and listQ [ 0 ] [ 2 ] [ 2 ] 's average must be taken.How can I do this ? EDIT : @ Roman Izosimov 's and @ Petko Petkov 's solutions are working correctly . Which one has higher performance ? What do you think ? <code> public static List < List < List < double > > > listQ = new List < List < List < double > > > ( ) ; public static List < List < List < double > > > listVal = new List < List < List < double > > > ( ) ; listVal [ 0 ] [ 0 ] [ 1 ] = listVal [ 0 ] [ 0 ] [ 2 ] = 3 . ( listQ [ 0 ] [ 0 ] [ 1 ] + listQ [ 0 ] [ 0 ] [ 2 ] ) / 2 = ( 26.5 + 20.4 ) / 2 = 23.45. listQ [ 0 ] [ 0 ] [ 1 ] = 23.45listQ [ 0 ] [ 0 ] [ 2 ] = 23.45
List operations related to another list 's conditions
C_sharp : I am trying to set up a navigation between views using a MVVM pattern . My application contains a MainWindow and two views with a button each . When I click on the button in the View1 I want to set up the View2 on the MainWindow.I have found several tutorials witch explain how to navigate from a view to another with a button on the main window ( simulate a tabControl ) , it works but it is not what I want.I 'm looking for something like : View1_View.xaml.cs : MainWindow.xaml.cs : My problem is if I do so , from the class View1_View I can not access to the method SwitchToView2 ( ) if it is not static , and if it is static I lose the context of the MainWindow.How should I proceed ? Thanks . <code> public partial class View1_View : UserControl { private View1_ViewModel _viewModel = new View1_ViewModel ( ) ; public View1_View ( ) { InitializeComponent ( ) ; } private void Btn_SwitchToView2_Click ( object sender , RoutedEventArgs e ) { MainWindow.SwitchToView2 ( ) ; } } public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; this.DataContext = new View1_View ( ) ; } public void SwitchToView2 ( ) { this.DataContext = new View2_View ( ) ; } }
WPF view who leads to another using MVVM
C_sharp : this is a small code which shows virtual methods.This code is printing the below output : I can not understand why a.F ( ) will print B.F ? I thought it will print D.F because Class B overrides the F ( ) of Class A , then this method is being hidden in Class C using the `` new '' keyword , then it 's again being overridden in Class D. So finally D.F stays.but it 's not doing that . Could you please explain why it is printing B.F ? <code> class A { public virtual void F ( ) { Console.WriteLine ( `` A.F '' ) ; } } class B : A { public override void F ( ) { Console.WriteLine ( `` B.F '' ) ; } } class C : B { new public virtual void F ( ) { Console.WriteLine ( `` C.F '' ) ; } } class D : C { public override void F ( ) { Console.WriteLine ( `` D.F '' ) ; } } class Test { static void Main ( ) { D d = new D ( ) ; A a = d ; B b = d ; a.F ( ) ; b.F ( ) ; } } B.FB.F
Need to understand the below code for C # virtual methods
C_sharp : In C # I could do this : But can I do something like that in C++ ? I tried : But it does n't compile . <code> char [ ] a = new char [ ] { ' a ' , ' a ' , ' a ' } ; char *a = new char [ ] { ' a ' , ' a ' , ' a ' } ;
Array initialization when using new
C_sharp : I have a class called playingcards it inherits from a cards class . I instantiated it as an object called chuckcards . One of the data members is CARD ID . I 'm trying to assign a int to the value . it is declared public int the class.Here 's how its instantiated.playingcards [ ] chuckcards = new playingcards [ 10 ] ; Here is how I try to assign values.The error I get is Object reference not set to an instance of an object.I do n't know what I 'm doing wrong ? Could I make a method that assigns the value to each member ? if so that 's gon na be a pain for certain things but I could do it ? or is their a simple way ? <code> for ( int ctr = 1 ; ctr < 10 ; ctr++ ) { chuckcards [ ctr ] .cardID = ctr ; temp++ ; }
giving a class object a value c #
C_sharp : How can I quickly create a string list with numbered strings ? Right now I 'm using : This works , however I wonder if there 's a quicker way to initialize such a string list , maybe in one or two lines ? <code> var str = new List < string > ( ) ; for ( int i = 1 ; i < = 10 ; i++ ) { str.Add ( `` This is string number `` + i ) ; }
Quick way to initialize list of numbered strings ?
C_sharp : I 've noticed this type of behavior before , and it occurred to me to ask a question this time : I have a simple `` proof of concept '' program that spawns a few threads , waits for them to do some work , then exits . But Main is n't returning unless I call server.Close ( ) ( which closes the socket and ends the server 's thread 's execution ) : According to article 10.2 , `` Application termination '' of the ECMA C # language specs : If the return type of the entry point method is void , reaching the right brace ( } ) which terminates that method , or executing a return statement that has no expression , results in a termination status code of 0.The debugger confirms that the right brace is being reached , but the standard does n't explicitly say that leaving Main will exit the application , only that the termination status code is set . It also mentions that : ... finalizers for all of [ the application 's ] objects that have not yet been garbage collected are called , unless such cleanup has been suppressed ( by a call to the library method GC.SuppressFinalize , for example ) .I suspected that behind the scenes a finalizer might be the problem , since the server object implements IDisposable , and it 's not uncommon to have a finalizer that calls Dispose . But the CLR limits finalizers to two seconds of execution when the program is being terminated ( Just in-case something strange was happening with the timeout I tried calling GC.SuppressFinalize on the server object and got the same result ) .I 'm a bit stumped as to what the server thread could be doing to hold up termination of the application indefinitely . <code> private void Run ( ) { var server = StartServer ( ) ; //Starts a thread in charge of listening on a socket _serverResetEvent.WaitOne ( ) ; ThriftProtocolAccessManager protocolManager = CreateProtocolManager ( ) ; //Does n't create any threads const int numTestThreads = 10 ; Barrier testCompletedBarrier ; Thread [ ] testThreads = GenerateTestThreads ( numTestThreads , protocolManager , out testCompletedBarrier ) ; //Creates x threads , where x is numTestThreads testThreads .AsParallel ( ) .ForAll ( thread = > thread.Start ( ) ) ; //Start them `` at the same time '' ( For testing purposes testCompletedBarrier.SignalAndWait ( ) ; //Barrier has participants equal to numTestThreads + 1 and each thread calls this //server.Close ( ) would go here . When it is here , the program returns as expected Console.WriteLine ( `` All Threads Complete '' ) ; //This is getting called } private static void Main ( string [ ] args ) { new Program ( ) .Run ( ) ; Console.WriteLine ( `` Run completed '' ) ; //This is also called } //The debugger confirms this brace is reached as well
Why is n't Main returning ?
C_sharp : If I want to periodically check if there is a cancellation request , I would use the following code below constantly inside my DoWork event handler : Is there a clean way for checking a cancellation request in BackgroundWorker in C # without re-typing the same code over and over again ? Please refer to the following code below : <code> if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } void worker_DoWork ( object sender , DoWorkEventArgs e ) { ... BackgroundWorker w = sender as BackgroundWorker ; if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } some_time_consuming_task ... if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } another_time_consuming_task ... if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } ... }
Is there a clean way for checking a cancellation request in BackgroundWorker without re-typing the same code over and over again ?
C_sharp : I expect the following code to deadlock when Clear tries to lock on the same object that Build has already locked : Output : ClearBuildEdit 1Thank you all for your answers.If I add a call to Build inside the lock of Clear ( keeping the rest of the code the same ) : A deadlock does occur ( or at least that 's what I think , LINQ Pad crashes ) .According to your answers , this should n't happen , because it 's still the same thread.Thanks ! <code> void Main ( ) { ( new SiteMap ( ) ) .Build ( ) ; } class SiteMap { private readonly object _lock = new object ( ) ; public void Build ( ) { lock ( _lock ) { Clear ( ) ; Console.WriteLine ( `` Build '' ) ; } } public void Clear ( ) { lock ( _lock ) { Console.WriteLine ( `` Clear '' ) ; } } } public void Clear ( ) { lock ( _lock ) { Build ( ) ; Console.WriteLine ( `` Clear '' ) ; } }
Why does n't this code deadlock ?
C_sharp : I wrote a program that compiles my .cs files using csc.exe : The compile instruction runs but produces no results , just a quick flash of a black console screen . Basically what seems to be happening , is when all the strings are parsed in the commandline as arguments for the process , the .cs project source directory is broken up by each white space ie c : \users\ % username % \Documents\Visual Studio 2010\ is broken up as c : \users\ % username % \Documents\Visual then Studio then 2010\Projects\Myproject\myproj.csand subsequently the compilation fails . <code> namespace myCompiler { public partial class Form1 : Form { string compilerFolder ; string outputFolder ; string projectFile ; string output = @ '' /out : '' ; public Form1 ( ) { InitializeComponent ( ) ; } private void startCompile_Click ( object sender , EventArgs e ) { Compile ( ) ; } public void findCompile_Click ( object sender , EventArgs e ) { DialogResult result1 = folderBrowserDialog1.ShowDialog ( ) ; compilerFolder = folderBrowserDialog1.SelectedPath ; MessageBox.Show ( compilerFolder ) ; cscLabel.Text = compilerFolder ; } private void outputCompile_Click ( object sender , EventArgs e ) { DialogResult result2 = folderBrowserDialog2.ShowDialog ( ) ; outputFolder = folderBrowserDialog2.SelectedPath ; outputLabel.Text = ( outputFolder ) ; MessageBox.Show ( outputFolder ) ; } private void findProject_Click ( object sender , EventArgs e ) { if ( openFileDialog1.ShowDialog ( ) == DialogResult.OK ) { projectFile = openFileDialog1.FileName ; projectLabel.Text = ( projectFile ) ; MessageBox.Show ( projectFile ) ; } } public void Compile ( ) { try { Process compile = new Process ( ) ; string outputExe = fileName.Text ; string compiler = compilerFolder + @ '' \csc.exe '' ; string arGs = output + outputFolder + @ '' \ '' + outputExe + `` `` + projectFile ; compile.StartInfo.FileName = ( compiler ) ; compile.StartInfo.Arguments = ( arGs ) ; compile.StartInfo.RedirectStandardOutput = true ; compile.StartInfo.UseShellExecute = false ; compile.Start ( ) ; string stdOutput = `` '' ; while ( ! compile.HasExited ) { stdOutput += compile.StandardOutput.ReadToEnd ( ) ; MessageBox.Show ( stdOutput ) ; } } catch ( Exception errorMsg ) { MessageBox.Show ( errorMsg.Message ) ; } } private void testButton_Click ( object sender , EventArgs e ) { MessageBox.Show ( projectFile ) ; MessageBox.Show ( compilerFolder ) ; } } }
Expected behaviour with white space in the command line
C_sharp : I have two snippets , one in Java and one in c # .the Java snippet returns 7101.674and in c # produces a result of 7103.674.why am I off by 2 and what is correct ? <code> float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; long e = 1234L ; int f = 0xa ; int g = 014 ; char h = ' Z ' ; char ia = ' ' ; byte j = 123 ; short k = 4321 ; System.out.println ( a+b+ca+d+e+f+g+h+ia+j+k ) ; float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; long e = 1234L ; int f = 0xa ; int g = 014 ; char h = ' Z ' ; char ia = ' ' ; byte j = 123 ; short k = 4321 ; Console.WriteLine ( a+b+ca+d+e+f+g+h+ia+j+k ) ;
why does java and c # differ in simple Addition
C_sharp : Because I am using a `` using '' here , If there is an exception any where in the TRY will the FtpWebRequest , FtpWebRespons and responseStream automatically be closed ? <code> Try Dim request As FtpWebRequest = CType ( WebRequest.Create ( `` '' ) , FtpWebRequest ) request.Method = WebRequestMethods.Ftp.ListDirectoryDetails request.Credentials = New NetworkCredential ( `` '' , `` '' ) Using response As FtpWebResponse = CType ( request.GetResponse ( ) , FtpWebResponse ) Using responseStream As Stream = response.GetResponseStream ( ) Using reader As New StreamReader ( responseStream ) TextBox1.Text = reader.ReadToEnd TextBox1.Text += vbNewLine TextBox1.Text += vbNewLine ' Use the + for appending ( set the textbox to multiline ) End Using End Using End Using Catch ex As Exception MessageBox.Show ( ex.Message.ToString ( ) ) End Try
if there is an exception in the `` using '' will it be automatically closed
C_sharp : Why input length on regex does not affect performance and how is that possible ? The generated string is like this : 128 random characters . then two numbers inside parenthesis . and this is repeated many times.The regex gets all the numbers inside parenthesis . here is the pattern.So the matches would be likeHere is the code that does the benchmark . I start the stop watch after input is generated because i want to only evaluate Matching time.This is the output in my Console if I repeat loop 10 times.If I repeat loop 1000 times.If I repeat loop 1000000 times.Screenshot if you dont believeIs this some kind of lazy evaluation ? if so then how it can show the count of matches ? how ever I did this under debugger and I could see the matches.Is there something especial in my regex pattern that makes it fast ? but how string length does not affect performance ? I cant understand . <code> 128 radnom characters ... . ( -2435346|45436 ) 128 radnom characters ... . ( -32525562|-325346 ) \ ( ( [ -+ ] ? \d+\| [ -+ ] ? \d+ ) \ ) -2435346|45436-32525562|-325346etc ... Random rand = new Random ( ) ; Func < string > getRandString = // generates 128 random characters . ( ) = > Enumerable.Range ( 0 , 128 ) .Select ( x = > ( char ) rand.Next ( ) ) .Aggregate ( `` '' , ( a , b ) = > a + b ) ; Func < int > getRandInteger = ( ) = > rand.Next ( ) ; // generates random number.string format = `` { 0 } ( { 1 } | { 2 } ) '' ; // Generate the big string.StringBuilder bigstr = new StringBuilder ( ) ; for ( int i = 0 ; i < 100 ; i++ ) // repeat 100 times . { bigstr.Append ( string.Format ( format , getRandString ( ) , getRandInteger ( ) , getRandInteger ( ) ) ) ; } string input = bigstr.ToString ( ) ; Stopwatch stopwatch = Stopwatch.StartNew ( ) ; var matches = Regex.Matches ( input , @ '' \ ( ( [ -+ ] ? \d+\| [ -+ ] ? \d+ ) \ ) '' ) ; stopwatch.Stop ( ) ; Console.WriteLine ( `` Time Elapsed : \t { 0 } \nInputLength : \t { 1 } \nMatches Count : \t { 2 } '' , stopwatch.Elapsed , input.Length , matches.Count ) ; Time Elapsed : 00:00:00.0004132InputLength : 1500Matches Count : 10 Time Elapsed : 00:00:00.0004373 // seriously ? InputLength : 149937Matches Count : 1000 Time Elapsed : 00:00:00.0004900 // wtf ? InputLength : 149964452Matches Count : 1000000
Why regex does not care about string length
C_sharp : I 've got a Linq To Sql query ( or with brackets ) here that works on my local SQL2008 , in about 00:00:00s - 00:00:01s , but on the remote server , it takes around 00:02:10s . There 's about 56k items in dbo.Movies , dbo.Boxarts , and 300k in dbo.OmdbEntriesThe inner query first takes all the related items in the tables and then creates a new object , then from that object , find only the t_Meters that are n't null . Then from those t_Meters , select only the distinct items and then sort them , to return a list of 98 or so ints.I do n't know enough about SQL Databases yet or not to intuitively know whether or not that that 's an extreme set of db calls to put into a single query , but since it only takes a second or less on my local server , I thought it was alright . edit : Here 's the LINQ code that I have n't really cleaned up at all : http : //pastebin.com/JUkdjHDJ It 's messy , but it gets the job done ... The fix I found was calling ToArray after OrderBy , but before Distinct helped out immensely . So instead of I didI 'm sure had I linked the Linq code ( and cleaned it up ) rather than the autogenerated SQL query , you would have been able to solve this easily , sorry about that . <code> { SELECT//pull distinct t_meter out of the created objectDistinct2.t_Meter AS t_Meter//match all movie data on the same movie_idFROM ( SELECT DISTINCT Extent2.t_Meter AS t_Meter FROM dbo.Movies AS Extent1 INNER JOIN dbo.OmdbEntries AS Extent2 ON Extent1.movie_ID = Extent2.movie_ID INNER JOIN dbo.BoxArts AS Extent3 ON Extent1.movie_ID = Extent3.movie_ID //pull the genres matched on movie_ids INNER JOIN ( SELECT DISTINCT Extent4.movie_ID AS movie_ID FROM dbo.MovieToGenres AS Extent4 //all genres matched on movie ids INNER JOIN dbo.Genres AS Extent5 ON Extent4.genre_ID = Extent5.genre_ID ) AS Distinct1 ON Distinct1.movie_ID = Extent1.movie_ID WHERE 1 = 1//sort the t_meters by ascending ) AS Distinct2ORDER BY Distinct2.t_Meter ASC } var results = IQueryableWithDBDatasTMeter.Distinct ( ) .OrderBy ( ) .ToArray ( ) var orderedResults = IQueryableWithDBDatasTMeter.OrderBy ( ) .ToArray ( ) var distinctOrderedResults = orderedResults.Distinct ( ) .ToArray ( )
DbContext times out on remote server only
C_sharp : If I do the following : This works and testdecimal ends up being 12222.Should n't this reasonably/logically fail parsing ? I was surprised to see that it worked and was curious as to what is the logic behind it that allows this . <code> string teststring = `` 12,2,2,2 '' ; decimal testdecimal ; decimal.TryParse ( teststring , out testdecimal )
Why does decimal.TryParse successfully parse something like 12,2,2,2
C_sharp : When I place an open brace in Visual Studio 2017 ( C # ) the cursor automatically goes to the next line to the left of the end brace . Like this ( period as cursor ) : I 'd like the cursor to automatically be on its own line like this ( period as cursor ) : Does anybody know how to make the cursor automatically go where the period is in the second example ? <code> if ( ) { . } if ( ) { . }
How to automatically place cursor between braces on its own line using Visual Studio 2017
C_sharp : Today I was thinking it would be neat to make anonymous object which is type of some interface , and I have seen on SO that I am not only one.Before I started checking out what happens I wrote some code like the one below.To my amusement it compiled , I am using .net framework 4 and I know there is no way to do anonymous objects implement interface , but I have not seen complaint from VS about this code.Even better when I put braces intelisense is finding `` Property '' of my interface , just like it would be valid code.Why is this piece compiling and when ran it is giving null reference exception ? <code> namespace test { class Program { static void Main ( string [ ] args ) { Holder holder = new Holder { someInterface = { Property = 1 } } ; Console.WriteLine ( holder.someInterface.Property ) ; } } class Holder { public ISomeInterface someInterface { get ; set ; } } interface ISomeInterface { int Property { get ; set ; } } }
Assign to interface array initializator compiles but why ?
C_sharp : I have a person table filled with Person information . I would like to get a list of the personer inside the table and check if they have renewed thier password in last 24 hours , and then return a person name and a boolean property whether they have updated the password or not . This is my Person table : Person table : Code : So my question is how can I , inside of select new { ... } return if the personer have renewed the password or not ? All help is appriciated ! And I´m open for any other suggestions for solution to this problem . <code> varchar ( 30 ) Name , DateTime LastRenewedPassword . public class Person { public string Name { get ; set ; } public boolean HasRenewedPassword { get ; set ; } } public List < Person > GetPersons ( ) { using ( var context = Entities ( ) ) { var persons = from p in contex.Persons select new Person { Name = p.Name , HasRenewedPassword = // Has the personer renewed the password for the last 24 hours ? } } }
Boolean inside of Select ( )
C_sharp : I 'm wondering if I should change the software architecture of one of my projects.I 'm developing software for a project where two sides ( in fact a host and a device ) use shared code . That helps because shared data , e.g . enums can be stored in one central place.I 'm working with what we call a `` channel '' to transfer data between device and host . Each channel has to be implemented on device and host side . We have different kinds of channels , ordinary ones and special channels which transfer measurement data.My current solution has the shared code in an abstract base class . From there on code is split between the two sides . As it has turned out there are a few cases when we would have shared code but we ca n't share it , we have to implement it on each side.The principle of DRY ( do n't repeat yourself ) says that you should n't have code twice.My thought was now to concatenate the functionality of e.g . the abstract measurement channel on the device side and the host side in an abstract class with shared code . That means though that once we create an actual class for either the device or the host side for that channel we have to hide the functionality that is used by the other side . Is this an acceptable thing to do : Now , DeviceMeasurementChannel is only using the functionality for the device side from MeasurementChannelAbstract . By declaring all methods/members of MeasurementChannelAbstract protected you have to use the new keyword to enable that functionality to be accessed from the outside.Is that acceptable or are there any pitfalls , caveats , etc . that could arise later when using the code ? <code> public abstract class ChannelAbstract { protected void ChannelAbstractMethodUsedByDeviceSide ( ) { } protected void ChannelAbstractMethodUsedByHostSide ( ) { } } public abstract class MeasurementChannelAbstract : ChannelAbstract { protected void MeasurementChannelAbstractMethodUsedByDeviceSide ( ) { } protected void MeasurementChannelAbstractMethodUsedByHostSide ( ) { } } public class DeviceMeasurementChannel : MeasurementChannelAbstract { public new void MeasurementChannelAbstractMethodUsedByDeviceSide ( ) { base.MeasurementChannelAbstractMethodUsedByDeviceSide ( ) ; } public new void ChannelAbstractMethodUsedByDeviceSide ( ) { base.ChannelAbstractMethodUsedByDeviceSide ( ) ; } } public class HostMeasurementChannel : MeasurementChannelAbstract { public new void MeasurementChannelAbstractMethodUsedByHostSide ( ) { base.MeasurementChannelAbstractMethodUsedByHostSide ( ) ; } public new void ChannelAbstractMethodUsedByHostSide ( ) { base.ChannelAbstractMethodUsedByHostSide ( ) ; } }
Is it good practice to blank out inherited functionality that will not be used ?
C_sharp : I want to parse plain text comments and look for certain tags within them . The types of tags I 'm looking for look like : Where `` name '' is a [ a-z ] string ( from a fixed list ) and `` 1234 '' represents a [ 0-9 ] + number . These tags can occur within a string zero or more times and be surrounded by arbitrary other text . For example , the following strings are all valid : The following strings are all NOT valid : The last one is n't valid because `` notinfixedlist '' is n't a supported named identifier.I can easily parse this using simple regex , for example ( I 'm omitting named groups for simplicity sake ) : or specifying a fixed list directly : but I 'd like to use antlr for a few reasons : I want anything that does n't match that format to result in a parse error , so if the text contains `` < `` or `` > '' but does n't match the pattern , it fails . Those characters must be escaped as `` & lt ; '' and `` & gt ; '' respectively if it 's not a tag.I may extend this in the future to support other kinds of patterns ( eg : `` { foo+666 } '' or `` [ [ @ 1234 ] ] '' and would like to avoid an explosion of regex statements . Having a single grammar file I can extend would be great.I like the fact that antlr4 implements the visitor pattern and my code gets called when a tag of a specific type is encountered instead of having to hack together varying regex.How do I implement such a grammar using antlr4 ? Most of the examples I 've seen are for languages which follow exact rules for the entire text , whereas I only want the grammar to apply to matching patterns within arbitrary text.I 've come up with this , which I believe is correct : Is this correct ? <code> < name # 1234 > `` Hello < foo # 56 > world ! '' '' < bar # 1 > ! `` `` 1 & lt ; 2 '' '' + < baz # 99 > + < squid # 0 > and also < baz # 99 > .\n\nBy the way , maybe < foo # 9876 > '' `` 1 < 2 '' '' < foo > '' '' < bar # > '' '' Hello < notinfixedlist # 1234 > '' < [ a-z ] + # \d+ > < ( foo|bar|baz|squid ) # \d+ > grammar Tags ; parse : ( tag | text ) * ; tag : ' < ' fixedlist ' # ' ID ' > ' ; fixedlist : 'foo ' | 'bar ' | 'baz ' | 'squid ' ; text : ~ ( ' < ' | ' > ' ) + ; ID : [ 0-9 ] + ;
Extracing specific tags from arbitrary plain text
C_sharp : I would like to know , in .NET , if the ( managed ) Microsoft UI Automation framework provides some way to instantiate an AutomationElement type given the AutomationId value of a window , suppressing this way the need to search the window by a window handle or other kind of identifiers.A pseudo example written in VB.NET to understand my purpose : <code> Dim automationId As Integer = 1504Dim element As AutomationElement = AutomationElement.FromAutomationId ( automationId )
Can be instantiated the type AutomationElement given an AutomationId value ?
C_sharp : I have a class which is basically a message handler , it accepts requests , finds a processor for that message type , creates an appropriate response and returns it . To this end , I have created a delegate as follows public delegate Rs ProcessRequest < Rq , Rs > ( Rq request ) ; and then inside my class , created a number of supported messages and their process methods . The problem is the main process method which should figure out which process method to use ca n't find the method using the GetMethod ( ) method.Here is the whole code , if you could tell me how to dynamically select the appropriate method and then execute it , thats pretty much what I am looking for.Now I assign those fields to methods as I go , I just ca n't dynamically execute them . <code> public delegate Rs ProcessRequest < in Rq , out Rs > ( Rq request ) where Rq : API.Request where Rs : API.Response ; public class WebSocketServer { private WebSocketMessageHandler messageHander ; // Incoming message handlers public ProcessRequest < InitUDPConnectionRq , InitUDPConnectionRs > ProcessInitUDPConnection ; public ProcessRequest < ListenHandshakeRq , ListenHandshakeRs > ProcessListenHandshake ; public ProcessRequest < PresenceChangeRq , PresenceChangeRs > ProcessPresenceChange ; public ProcessRequest < ChatMessageRq , ChatMessageRs > ProcessChatMessage ; public ProcessRequest < RDPRequestResponseRq , RDPRequestResponseRs > ProcessRDPRequestResponse ; public ProcessRequest < RDPIncomingRequestRq , RDPIncomingRequestRs > ProcessRDPIncomingRequest ; public WebSocketServer ( WebSocketMessageHandler handler ) { this.messageHander = handler ; } public void processRequest ( API.Request request ) { String resquestType = request.GetType ( ) .Name ; String processorName = resquestType.Substring ( 0 , resquestType.Length - 2 ) ; API.Response response = null ; // Do we have a process method for this processor MethodInfo methodInfo = this.GetType ( ) .GetMethod ( `` Process '' + processorName ) ; if ( methodInfo ! = null ) { // Execute the method via Invoke ... . , but code never gets here } else { logger.Warn ( `` Failed to find a processor for `` + processorName ) ; response = new ErrorRs ( request.id , `` Failed to find a processor for `` + processorName ) ; } sendResponse ( response , request ) ; } } // Link into the hooks so we can receive requests_appContext.ConnectionManager.Connection.webSocketServer.ProcessInitUDPConnection = ProcessInitUDPConnection ; _appContext.ConnectionManager.Connection.webSocketServer.ProcessListenHandshake = ProcessListenHandshake ; _appContext.ConnectionManager.Connection.webSocketServer.ProcessPresenceChange = ProcessPresenceChange ; _appContext.ConnectionManager.Connection.webSocketServer.ProcessChatMessage = ProcessChatMessage ; // 1 method as an exampleprivate PresenceChangeRs ProcessPresenceChange ( PresenceChangeRq request ) { _appContext.RosterManager.presenceChange ( request.user , request.presence ) ; return new PresenceChangeRs ( ) ; }
Dynamically executing delegates
C_sharp : I am learning about implementing interfaces and generics , I made this code , but VStudio says that I did not implement System.Collections.Enumerable.GetEnumerator ( ) .Did I not do this below , generically ? It wants two implementations ? <code> namespace Generic_cars { class VehicleLot : IEnumerable < Vehicle > { public List < Vehicle > Lot = new List < Vehicle > ( ) ; IEnumerator < Vehicle > IEnumerable < Vehicle > .GetEnumerator ( ) { foreach ( Vehicle v in Lot ) { yield return v ; } ; } } }
IEnumerable , requires two implementations ?
C_sharp : I have this code to open multiple urls from a richtextbox , it works fine , but the problem is that it opens all sites in separate browsers . Any ideas how I can open the pages like tabs in the same browser ? <code> private void button1_Click ( object sender , EventArgs e ) { for ( int i = 0 ; i < richTextBox1.Lines.Length ; i++ ) { Process.Start ( `` http : // '' + richTextBox1.Lines [ i ] ) ; } }
how to open multiple urls from richtextbox
C_sharp : While reading this answer from another question I was 100 % sure that the following code would lock up the UI and not cause any movement.I and several others in the comments said it would not work but the OP insisted that it did and we should try . I ended up making a new Winforms project , adding a button , then putting the above code in the event handler for click and the form did indeed shake.How is the form moving when the message pump is being blocked by this method , OnPaint should not be able to be called on the form nor any of its child controls , how is this working ? <code> private void button1_Click ( object sender , EventArgs e ) { for ( int i = 0 ; i < 5 ; i++ ) { this.Left += 10 ; System.Threading.Thread.Sleep ( 75 ) ; this.Left -= 10 ; System.Threading.Thread.Sleep ( 75 ) ; } }
Why does my form NOT lock up ?
C_sharp : I do n't know if I 'm missing something ... anyway : You can see , for example , that the object with the property 'HomeTeam ' = ' Forest Green Rovers ' has the state = 'Unchanged ' . Anyway all entities are 'unchanged ' in my case . So , if I 'm correct , the saveChanges should n't try to insert those in my table but that 's what it 's happening : The primary key has been violated , but EF should n't have tried to add this record ( the one with the property HomeTeam = 'Forest Green Rovers ' ) since it 's 'Unchanged ' , right ? Why is EF doing that ? The entity : } More Info : ops . I have found my error and it 's really stupid : - ( in a related function inside the for there was some uncommented code where I was adding entities without checking the PK constraints . The state 'Unchanged ' ( first image ) confused me and I have kept focusing on that ... Sorry : - ) <code> { using System ; using System.Collections.Generic ; public partial class MatchInfo { [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2214 : DoNotCallOverridableMethodsInConstructors '' ) ] public MatchInfo ( ) { this.Sport = `` Soccer '' ; this.OddsInfoes1X2 = new HashSet < OddsInfo1X2 > ( ) ; this.Odds1X2Movements = new HashSet < OddsMovement > ( ) ; this.OddsInfoOverUnders = new HashSet < OddsInfoOverUnder > ( ) ; this.OddsMovementOverUnders = new HashSet < OddsMovementOverUnder > ( ) ; this.HistoryResults = new HashSet < HistoryResult > ( ) ; } public string League { get ; set ; } public System.DateTime Date { get ; set ; } public string HomeTeam { get ; set ; } public string AwayTeam { get ; set ; } public string FinalScore { get ; set ; } public string Sport { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < OddsInfo1X2 > OddsInfoes1X2 { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < OddsMovement > Odds1X2Movements { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < OddsInfoOverUnder > OddsInfoOverUnders { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < OddsMovementOverUnder > OddsMovementOverUnders { get ; set ; } public virtual TeamsStatFinal TeamsStatFinal { get ; set ; } [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2227 : CollectionPropertiesShouldBeReadOnly '' ) ] public virtual ICollection < HistoryResult > HistoryResults { get ; set ; } } foreach ( something ) { /*iterating on a web page and where I build the object oMatchInfo */ if ( oMatchInfo ! = null ) { oMatchInfoTemp = ( from m in context.MatchInfoes where m.HomeTeam == oMatchInfo.HomeTeam & & m.AwayTeam == oMatchInfo.AwayTeam & & m.Date == oMatchInfo.Date select m ) .FirstOrDefault < MatchInfo > ( ) ; if ( oMatchInfoTemp == null ) { context.MatchInfoes.Add ( oMatchInfo ) ; } else { context.OddsInfoes1X2.AddRange ( oMatchInfo.OddsInfoes1X2 ) ; } } } /* here there is the context.saveChanges ( ) - the context is the same */
SaveChanges ( ) is saving Unchanged records
C_sharp : This was a interview question - How will you efficiently trim the duplicate characters in string with single character . Example : suppose this is the input string `` reeeturrrnneedd '' The output should be : `` returned '' I explained it by using splitting the string and loop through the char array , but interviewer does not convinced with the answer said this is not the efficient way.Then I thought about Linq to object and use distinct but it will give incorrect output as it remove all duplicate characters and output will be `` retund '' Can someone tell me the more efficient way to do it ? <code> private void test ( ) { string s = `` reeeturrrnneeddryyf '' ; StringBuilder sb = new StringBuilder ( ) ; char pRvChar = default ( char ) ; foreach ( var item in s.ToCharArray ( ) ) { if ( pRvChar == item ) { continue ; } pRvChar = item ; sb.Append ( pRvChar ) ; } MessageBox.Show ( sb.ToString ( ) ) ; }
Trimming duplicate characters with single character in string
C_sharp : I 've been thinking recently about the Liskov Substitution Principle and how it relates to my current task . I have a main form which contains a menu ; into this main form I will dock a specific form as a MDI child . This specific form may or may not contain a menu . If it does , I want to merge it with the main menu . So the situation is like this : Now the two children are not `` exactly '' interchangeble : one has a menu ; the other does n't . Is this a misuse of the is/as contruct in C # ? If this is not correct , what would be the clean solution ? <code> public class MainForm { public void Dock ( SpecificBaseForm childForm ) { this.Dock ( childForm ) ; if ( childForm is IHaveMenu ) { this.Menu.Merge ( childForm as IHaveMenu ) .Menu ; } } } public interface IHaveMenu { Menu Menu { get ; } } public abstract class SpecificBaseForm { } public class SpecificFormFoo : SpecificBaseForm { } public class SpecificFormBar : SpecificBaseForm , IHaveMenu { public Menu Menu { get { return this.Menu ; } } }
Does one child implementing an interface , but another not , violate the Liskov Substitution Principle ?
C_sharp : I am working on EF . I am trying to insert into a table , the insert function is in a thread . And this is my save data function The above code runs for some time , but after that I encountered an error at u.SaveChanges ( ) ; System.Data.Entity.Core.EntityException : 'An error occurred while closing the provider connection . See the inner exception for details . ' MySqlException : Fatal error encountered during command execution . MySqlException : Fatal error encountered attempting to read the resultset . MySqlException : Reading from the stream has failed . IOException : Unable to read data from the transport connection : 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 . SocketException : 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 respondI have looked into each solution and tried them but still unable to resolve this issue . I must be missing something that I do n't know . Update 1 My whole codeCalling constructorCalling handlerSaving data into DBAny help would be highly appreciated . <code> private void DataReceivedHandler ( object sender , SerialDataReceivedEventArgs e ) { int bytes = port.BytesToRead ; //string indata = sp.ReadExisting ( ) ; Thread.Sleep ( 50 ) ; try { receivedBytes = port.BaseStream.Read ( buffer , 0 , ( int ) buffer.Length ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } var receiveData = BitConverter.ToString ( buffer , 0 , receivedBytes ) ; var finalData = receiveData.Replace ( `` - '' , `` '' ) ; //Thread.Sleep ( 100 ) ; Console.WriteLine ( `` Thread Going to Start '' ) ; new Thread ( ( ) = > { SaveData ( finalData ) ; } ) .Start ( ) ; // starting the thread port.DiscardOutBuffer ( ) ; port.DiscardInBuffer ( ) ; } public void SaveData ( string finalData ) { Console.WriteLine ( LineNumber ( ) + `` Data Transmiting ... '' ) ; thread = Thread.CurrentThread ; mdc_dbEntities e = new mdc_dbEntities ( ) ; var msn = e.mdc_meter_config.Where ( m = > m.m_hex == sr ) .Select ( s = > new { s.msn , s.p_id , s.meter_id } ) .ToList ( ) ; var H = finalData.Substring ( 0 , 2 ) ; using ( mdc_dbEntities u = new mdc_dbEntities ( ) ) { foreach ( var res in msn ) { var cust_id = e.mdc_meter_cust_rel.Where ( m = > m.msn == res.msn ) .Select ( s = > s.cust_id ) .FirstOrDefault ( ) ; mdc_meters_data data = new mdc_meters_data ( ) { msn = res.msn , cust_id = cust_id , device_id = res.meter_id.ToString ( ) , kwh = e_val.ToString ( ) , voltage_p1 = a_vol_val.ToString ( ) , voltage_p2 = b_vol_val.ToString ( ) , voltage_p3 = c_vol_val.ToString ( ) , current_p1 = a_curr_val.ToString ( ) , current_p2 = b_curr_val.ToString ( ) , current_p3 = c_curr_val.ToString ( ) , data_date_time = Convert.ToDateTime ( theDate.ToString ( format ) ) , d_type = d_type.ToString ( ) , pf1 = a_pf_val.ToString ( ) , pf2 = b_pf_val.ToString ( ) , pf3 = c_pf_val.ToString ( ) , p_id = res.p_id , } ; u.mdc_meters_data.Add ( data ) ; } u.SaveChanges ( ) ; } Console.WriteLine ( LineNumber ( ) + `` Data Saved '' ) ; Thread.Sleep ( 50 ) ; } try { thread.Abort ( ) ; // aborting it after insertion //Thread.Sleep ( 50 ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } } public CommunicationEngine ( ) { port.ReadTimeout = 500 ; port.DataReceived += new SerialDataReceivedEventHandler ( DataReceivedHandler ) ; port.Open ( ) ; Console.WriteLine ( `` Port opened successfully '' ) ; Console.WriteLine ( `` I am Recieving '' ) ; } private void DataReceivedHandler ( object sender , SerialDataReceivedEventArgs e ) { int bytes = port.BytesToRead ; Thread.Sleep ( 50 ) ; Console.WriteLine ( `` Bytes are ok ... '' + port.BytesToRead + `` Recieved `` ) ; try { receivedBytes = port.BaseStream.Read ( buffer , 0 , ( int ) buffer.Length ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } var receiveData = BitConverter.ToString ( buffer , 0 , receivedBytes ) ; var finalData = receiveData.Replace ( `` - '' , `` '' ) ; //Thread.Sleep ( 100 ) ; Console.WriteLine ( `` Thread Going to Start '' ) ; try { new Thread ( ( ) = > { SaveData ( finalData ) ; } ) .Start ( ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } port.DiscardOutBuffer ( ) ; port.DiscardInBuffer ( ) ; } public void SaveData ( string finalData ) { Console.WriteLine ( LineNumber ( ) + `` Data Transmiting ... '' ) ; thread = Thread.CurrentThread ; if ( finalData.Length == 138 ) { comm = true ; var H = finalData.Substring ( 0 , 2 ) ; var FC = finalData.Substring ( 2 , 9 ) ; var len = finalData.Substring ( 10 , 2 ) ; var sr = finalData.Substring ( 12 , 12 ) ; var energy_tag = finalData.Substring ( 24 , 4 ) ; var e_val = hexToDec ( finalData.Substring ( 28 , 8 ) ) / 10 ; var a_curr_tag = finalData.Substring ( 36 , 4 ) ; var a_curr_val = hexToDec ( finalData.Substring ( 40 , 8 ) ) / 1000 ; var b_curr_tag = finalData.Substring ( 48 , 4 ) ; var b_curr_val = hexToDec ( finalData.Substring ( 52 , 8 ) ) / 1000 ; var c_curr_tag = finalData.Substring ( 60 , 4 ) ; var c_curr_val = hexToDec ( finalData.Substring ( 64 , 8 ) ) / 1000 ; var a_vol_tag = finalData.Substring ( 72 , 4 ) ; var a_vol_val = hexToDec ( finalData.Substring ( 76 , 8 ) ) / 10 ; var b_vol_tag = finalData.Substring ( 84 , 4 ) ; var b_vol_val = hexToDec ( finalData.Substring ( 88 , 8 ) ) / 10 ; var c_vol_tag = finalData.Substring ( 96 , 4 ) ; var c_vol_val = hexToDec ( finalData.Substring ( 100 , 8 ) ) / 10 ; var a_pf_tag = finalData.Substring ( 108 , 4 ) ; var a_pf_val = hexToDec ( finalData.Substring ( 112 , 4 ) ) / 1000 ; var b_pf_tag = finalData.Substring ( 116 , 4 ) ; var b_pf_val = hexToDec ( finalData.Substring ( 120 , 4 ) ) / 1000 ; var c_pf_tag = finalData.Substring ( 124 , 4 ) ; var c_pf_val = hexToDec ( finalData.Substring ( 128 , 4 ) ) / 1000 ; var crc = finalData.Substring ( 132 , 4 ) ; var ftr = finalData.Substring ( 136 , 2 ) ; var d_type = `` 600 '' ; DateTime theDate = DateTime.Now ; string format = `` yyyy-MM-dd HH : mm : ss '' ; Console.WriteLine ( LineNumber ( ) + `` Data Ready to be inserted in DB '' ) ; using ( mdc_dbEntities u = new mdc_dbEntities ( ) ) { var msnList = u.mdc_meter_config.Where ( m = > m.m_hex == sr ) .Select ( s = > new { s.msn , s.p_id , s.meter_id } ) .ToList ( ) ; foreach ( var res in msnList ) { var cust_id = u.mdc_meter_cust_rel.Where ( m = > m.msn == res.msn ) .Select ( s = > s.cust_id ) .FirstOrDefault ( ) ; mdc_meters_data data = new mdc_meters_data ( ) { msn = res.msn , cust_id = cust_id , device_id = res.meter_id.ToString ( ) , kwh = e_val.ToString ( ) , voltage_p1 = a_vol_val.ToString ( ) , voltage_p2 = b_vol_val.ToString ( ) , voltage_p3 = c_vol_val.ToString ( ) , current_p1 = a_curr_val.ToString ( ) , current_p2 = b_curr_val.ToString ( ) , current_p3 = c_curr_val.ToString ( ) , data_date_time = Convert.ToDateTime ( theDate.ToString ( format ) ) , d_type = d_type.ToString ( ) , pf1 = a_pf_val.ToString ( ) , pf2 = b_pf_val.ToString ( ) , pf3 = c_pf_val.ToString ( ) , p_id = res.p_id , } ; u.mdc_meters_data.Add ( data ) ; } try { u.SaveChanges ( ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } } Console.WriteLine ( LineNumber ( ) + `` Data Saved '' ) ; Thread.Sleep ( 50 ) ; } else if ( finalData.Length == 30 ) { var msn_no = finalData.Substring ( 12 , 12 ) ; mdc_dbEntities p = new mdc_dbEntities ( ) ; var update = p.meter_control.Where ( c = > ( c.comm_executed == 0 ) ) .Where ( o = > ( o.m_hex == msn_no ) ) .SingleOrDefault ( ) ; if ( update.comm_sent == `` Disconnect '' ) { update.comm_executed = 1 ; update.comm = 0 ; p.SaveChanges ( ) ; Console.WriteLine ( `` Meter Disconnected ... . '' ) ; } else if ( update.comm_sent == `` Connect '' ) { update.comm_executed = 1 ; update.comm = 1 ; p.SaveChanges ( ) ; Console.WriteLine ( `` Meter Connected ... . '' ) ; } comm = true ; } else { comm = true ; } try { thread.Abort ( ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message.ToString ( ) ) ; } }
EF inserting values in table failed after some time
C_sharp : I have an interesting thought-problem right now , so maybe someone of you could help.Basically what I have is an array of bytes and need to know the order of each individual item in that array - by value . Oh man , i will just show you a small example , i think that will help better : I want to get this as a resultWhat would be a smart way to do this ? In addition i would like the algorithm to retain the order , if the entries are valued equal . Soshould result in <code> byte [ ] array = new byte [ 4 ] { 42 , 5 , 17 , 39 } 4 1 2 3 new byte [ 4 ] { 22 , 33 , 33 , 11 } 2 3 4 1
Get the order of bytes by value
C_sharp : I ’ m having an issue ( probably due to my lack of familiarity of C # generics ) in getting the unclosed type of a generic . I have several methods that look rather similar to the following except for the explicit validator interface in use . The method GetRecursiveBaseTypesAndInterfaces does as it says and gathers all base types and interfaces of a given type . So what I 'm eventually doing is getting the unclosed type of the explicit validator interface and getting it 's type as closed on each of the original type T 's base classes and interfaces . This works great , however I 'd like to clean up my code and accomplish this in a more generic form than aboveknowing that any validator of T will extend IValidator ( as bellow ) My uncompleted attempt at a generic version of the above method looks like : How do I define unclosedType ( or restructure the method ) to do the same work as the original method with a call toOr would it be possible to refine my method more so as a call like the following would be sufficient ? <code> public IEnumerable < IDeleteValidator < T > > GetDeleteValidators < T > ( ) { var validatorList = new List < IDeleteValidator < T > > ( ) ; foreach ( var type in GetRecursiveBaseTypesAndInterfaces ( typeof ( T ) ) ) { var validatorType = typeof ( IDeleteValidator < > ) .MakeGenericType ( type ) ; var validators = ObjectFactory .GetAllInstances ( validatorType ) .Cast < IDeleteValidator < T > > ( ) ; validatorList.AddRange ( validators ) ; } return validatorList ; } public interface IDeleteValidator < in T > : IValidator < T > { } public IEnumerable < TValidator > GetValidators < T , TValidator > ( ) where TValidator : IValidator < T > { var validatorList = new List < TValidator > ( ) ; foreach ( var type in GetRecursiveBaseTypesAndInterfaces ( typeof ( T ) ) ) { var unclosedType = ? ? ? var validatorType = typeof ( unclosedType ) .MakeGenericType ( type ) ; var validators = ObjectFactory .GetAllInstances ( validatorType ) .Cast < TValidator > ( ) ; validatorList.AddRange ( validators ) ; } return validatorList ; } GetValidators < Whatever , IDeleteValidator < Whatever > > ( ) ; GetValidators < IDeleteValidator < Whatever > > ( ) ;
Retrieving the unclosed type of a generic type closing a generic type
C_sharp : Possible Duplicate : Foreach can throw an InvalidCastException ? Consider the following block of codeNotice the cast from Base to DerivedLeft in foreach statement . This compiles fine ( Visual Studio 2010 ) , without any error or even warning.Obviously , on the second loop-iteration we will get an InvalidCastException . If I was asked a question about reaction of compiler to such code , I would without a doubt say , that compiler wo n't let this go unnoticed and produce at least a warning.But apparently it does n't . So , why does the compiler let this slip through ? <code> public class Base { } public class DerivedLeft : Base { } public class DerivedRight : Base { } class Program { static void Main ( string [ ] args ) { List < Base > list = new List < Base > { new DerivedLeft ( ) , new DerivedRight ( ) } ; foreach ( DerivedLeft dl in list ) { Console.WriteLine ( dl.ToString ( ) ) ; } } }
Why does compiler let this slip ?
C_sharp : everyone , I want one application that could control window open and close multi-time . For example , press 1 , open a window ; press 2 , close the window.And there is my code I found , which only could do this once.Could somebody be nice to help me correct it ? Thanks a lot . <code> public static void Main ( string [ ] args ) { var appthread = new Thread ( new ThreadStart ( ( ) = > { app = new testWpf.App ( ) ; app.ShutdownMode = ShutdownMode.OnExplicitShutdown ; app.Run ( ) ; } ) ) ; appthread.SetApartmentState ( ApartmentState.STA ) ; appthread.Start ( ) ; while ( true ) { var key = Console.ReadKey ( ) .Key ; // press 1 to open if ( key == ConsoleKey.D1 ) { DispatchToApp ( ( ) = > new Window ( ) .Show ( ) ) ; } // Press 2 to exit if ( key == ConsoleKey.D2 ) { DispatchToApp ( ( ) = > app.Shutdown ( ) ) ; } } } static void DispatchToApp ( Action action ) { app.Dispatcher.Invoke ( action ) ; }
How I re-open WPF window in the same pragrom/application ?
C_sharp : I want to transfer BusinessObjects from one PC to another . If I think about a number of around 40 different object types to transfer the use of many contracts for the different objects would seem to be quite some overload for always the same task : `` Send Object A to Computer B and save object to DB '' ( objects all have a persistent method ) .As the Objects can have many different types , I only want to to use a generic method to : serialize a BO objecttransfer it to another PCdeserialize it with correct typemake a consistency check save to dbis my problem . At the moment I 'm thinking about sending the type as eytra information.Then I want to do something like : And afterwards just use generic methods from a base object to save object to database , to keep the transfer classes as simple as possible.Is there a possibility to do something like this ? Or am I going in a completly wrong direction and it would be easier to achieve this task with another approach ? <code> BinaryFormatter aFormatter = new BinaryFormatter ( ) ; aFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple ; Object.ParseTypeFromString ( aObjektType ) aObject = aFormatter.Deserialize ( stream ) as Object.ParseTypeFromString ( aObjektType ) ;
How to use a variable as type
C_sharp : I am reading through documents , and splitting words to get each word in the dictionary , but how could I exclude some words ( like `` the/a/an '' ) . This is my function : Also , in this scenario , where is the right place to add .ToLower ( ) call to make all the words from file in lowercase ? I was thinking about something like this before the ( temp = file.. ) : <code> private void Splitter ( string [ ] file ) { try { tempDict = file .SelectMany ( i = > File.ReadAllLines ( i ) .SelectMany ( line = > line.Split ( new [ ] { ' ' , ' , ' , ' . ' , ' ? ' , ' ! ' , } , StringSplitOptions.RemoveEmptyEntries ) ) .AsParallel ( ) .Distinct ( ) ) .GroupBy ( word = > word ) .ToDictionary ( g = > g.Key , g = > g.Count ( ) ) ; } catch ( Exception ex ) { Ex ( ex ) ; } } file.ToList ( ) .ConvertAll ( d = > d.ToLower ( ) ) ;
Excluding words from dictionary
C_sharp : I 'm trying to convert this simple class to IL code : In fact I used ILDasm to know the IL instructions before trying to use Emit to create the class dynamically . The result it shows is : From that , I tried using Emit like this : Now try using it : That means the IL code would be wrong at some point . But comparing it with what is actually generated by ILDasm , I do n't see any difference . What is wrong here ? <code> public class IL { Dictionary < string , int > props = new Dictionary < string , int > ( ) { { `` 1 '' ,1 } } ; } .class public auto ansi beforefieldinit IL extends [ mscorlib ] System.Object { .field private class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > props .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { // .maxstack 4 .locals init ( class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > V_0 ) IL_0000 : ldarg.0 IL_0001 : newobj instance void class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > : :.ctor ( ) IL_0006 : stloc.0 IL_0007 : ldloc.0 IL_0008 : ldstr `` 1 '' IL_000d : ldc.i4.1 IL_000e : callvirt instance void class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > : :Add ( ! 0 , ! 1 ) IL_0013 : ldloc.0 IL_0014 : stfld class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > IL : :props IL_0019 : ldarg.0 IL_001a : call instance void [ mscorlib ] System.Object : :.ctor ( ) IL_001f : ret } // end of method IL : :.ctor } // end of class IL var aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly ( new System.Reflection.AssemblyName ( `` test '' ) , AssemblyBuilderAccess.Run ) ; var mBuilder = aBuilder.DefineDynamicModule ( `` module '' ) ; var tBuilder = mBuilder.DefineType ( `` IL '' ) ; var field = tBuilder.DefineField ( `` props '' , typeof ( Dictionary < string , int > ) , System.Reflection.FieldAttributes.Private ) ; var con = tBuilder.DefineConstructor ( System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName , System.Reflection.CallingConventions.HasThis , Type.EmptyTypes ) ; var conIL = con.GetILGenerator ( ) ; conIL.Emit ( OpCodes.Ldarg_0 ) ; conIL.Emit ( OpCodes.Newobj , typeof ( Dictionary < string , int > ) .GetConstructor ( Type.EmptyTypes ) ) ; conIL.Emit ( OpCodes.Stloc_0 ) ; conIL.Emit ( OpCodes.Ldloc_0 ) ; conIL.Emit ( OpCodes.Ldstr , `` 1 '' ) ; conIL.Emit ( OpCodes.Ldc_I4_1 ) ; conIL.Emit ( OpCodes.Callvirt , typeof ( Dictionary < string , int > ) .GetMethod ( `` Add '' ) ) ; conIL.Emit ( OpCodes.Ldloc_0 ) ; conIL.Emit ( OpCodes.Stfld , field ) ; conIL.Emit ( OpCodes.Ldarg_0 ) ; conIL.Emit ( OpCodes.Call , typeof ( object ) .GetConstructor ( Type.EmptyTypes ) ) ; conIL.Emit ( OpCodes.Ret ) ; var t = tBuilder.CreateType ( ) ; var instance = Activator.CreateInstance ( t ) ; //exception has been thrown here //saying `` Common Language Runtime detected an invalid program . ''
Converting simple class to IL failed due to some invalid IL code ?
C_sharp : I would appreciate any help from the PLYNQ experts out there ! I will take time reviewing answers , I have a more established profile on math.SE.I have an object of type ParallelQuery < List < string > > , which has 44 lists which I would like to process in parallel ( five at a time , say ) . My process has a signature likeThe processing will return a result , which is a pair of Boolean values , as below.The problem . Given an IEnumerable < List < string > > processMe , my PLYNQ query tries to implement this method : https : //msdn.microsoft.com/en-us/library/dd384151 ( v=vs.110 ) .aspx . It is written asUnfortunately it does not run in parallel , only sequentially . ( ** note that this implementation does n't make `` sense '' , I am just trying to get the parallelisation to work for now . ) I tried a slightly different implementation , which did run in parallel , but there was no aggregation . I defined an aggregation method ( which is essentially a Boolean AND on both parts of ProcessResult , i.e . aggregate ( [ A1 , A2 ] , [ B1 , B2 ] ) ≡ [ A1 & & B1 , A2 & & B2 ] ) .And used the PLYNQ query https : //msdn.microsoft.com/en-us/library/dd383667 ( v=vs.110 ) .aspxThe problem here was that the AggregateProcessResults code was never hit , for some reason—I am clueless where the results were going ... Thanks for reading , any help appreciated : ) <code> private ProcessResult Process ( List < string > input ) private struct ProcessResult { public ProcessResult ( bool initialised , bool successful ) { ProcessInitialised = initialised ; ProcessSuccessful = successful ; } public bool ProcessInitialised { get ; } public bool ProcessSuccessful { get ; } } processMe.AsParallel ( ) .Aggregate < List < string > , ConcurrentStack < ProcessResult > , ProcessResult > ( new ConcurrentStack < ProcessResult > , //aggregator seed ( agg , input ) = > { //updating the aggregate result var res = Process ( input ) ; agg.Push ( res ) ; return agg ; } , agg = > { //obtain the result from the aggregator agg ProcessResult res ; // ( in this case just the most recent result** ) agg.TryPop ( out res ) ; return res ; } ) ; private static ProcessResult AggregateProcessResults ( ProcessResult aggregate , ProcessResult latest ) { bool ini = false , suc = false ; if ( aggregate.ProcessInitialised & & latest.ProcessInitialised ) ini = true ; if ( aggregate.ProcessSuccessful & & latest.ProcessSuccessful ) suc = true ; return new ProcessResult ( ini , suc ) ; } .Aggregate < List < string > , ProcessResult , ProcessResult > ( new ProcessResult ( true , true ) , ( res , input ) = > Process ( input ) , ( agg , latest ) = > AggregateProcessResults ( agg , latest ) , agg = > agg
Possible reasons why ParallelQuery.Aggregate does not run in parallel
C_sharp : I have added a web ref to my .net project which contains the methods for a 3rd party service.When I try to call one of the methods its expecting an OrderIdentifier object to be passed but its giving me the error : InvalidOperationException : < > f__AnonymousType0 ` 3 [ System.DateTime , ETS_OpenAccessNew.ETS.DateRange , ETS_OpenAccessNew.ETS.AuctionIdentification ] can not be serialized because it does not have a parameterless constructor.My code is as follows : The classes being referenced are as follows : Any ideas on what I 'm doing wrong here would be much appreciatedUpdate - I have now included the parameterless contructor to the AuctionIdentification class but still getting the same error <code> OrderIdentifier oi = new OrderIdentifier { area = testArea , portfolio = testPortfolio } ; DateRange dr = new DateRange { from = DateTime.Today.AddDays ( -7 ) , to = DateTime.Today } ; var Ai = new AuctionIdentification { Item = DateTime.Today.AddDays ( -1 ) , ItemElementName = ItemChoiceType1.AuctionDate , name = `` test '' , duration = AuctionIdentificationDuration.Item30min , durationSpecified = true } ; object items = new { deliveryDay = DateTime.Today.AddDays ( -1 ) , deliveryDays = dr , AuctionIdentification = Ai } ; oi.Items = new object [ 1 ] { items } ; var orders = oa.RetrieveOrders ( oi ) ; [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class OrderIdentifier : IdentifiedOrder { } [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( OrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Order ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrderIdentification ) ) ] [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class IdentifiedOrder : AbstractOrderObject { private string areaField ; private string portfolioField ; private object [ ] itemsField ; /// < remarks/ > public string area { get { return this.areaField ; } set { this.areaField = value ; } } /// < remarks/ > public string portfolio { get { return this.portfolioField ; } set { this.portfolioField = value ; } } /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( `` AuctionIdentification '' , typeof ( AuctionIdentification ) ) ] [ System.Xml.Serialization.XmlElementAttribute ( `` deliveryDay '' , typeof ( System.DateTime ) , DataType= '' date '' ) ] [ System.Xml.Serialization.XmlElementAttribute ( `` deliveryDays '' , typeof ( DateRange ) ) ] public object [ ] Items { get { return this.itemsField ; } set { this.itemsField = value ; } } } /// < remarks/ > [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Curve ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( IdentifiedOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( OrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Order ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrderIdentification ) ) ] [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class AbstractOrderObject : OpenAccessAbstractObject { } /// < remarks/ > [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MarketResultIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Broadcast ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderBatch ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionInformationQuery ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionDateTime ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AsynchronousResponseHeader ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaPortfolioInformationQuery ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MessageAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Messages ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MessageIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ClientMessage ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MarketResult ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrderIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyPeriod ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CurvePoint ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AbstractOrderObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Curve ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( IdentifiedOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( OrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Order ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrderIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaAuctionIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaPortfolioInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AsynchronousNotification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ExclusiveGroupIndexToIdMapping ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockIndexToIdMapping ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockPeriod ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SmartBlockOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SmartBlockOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderForBatch ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ErrorObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Acknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( UserLogoutAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SetNewPasswordAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SetMessagesAsReadAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradeableAreaSetsAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveSmartBlockOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveMessagesAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveMarketResultAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveHourlyOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveComplexOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveBlockOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAuctionInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreaPortfolioInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreaInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ReportRelayServerErrorResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ReportRelayErrorResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RemoveReverseConnectionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RegisterUserOnServerResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RegisterForAsyncEventsResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ProcessAsynchronousNotificationResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( LogoutAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( GetNotificationsResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EstablishSessionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EstablishReverseConnectionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterHourlyOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterComplexOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterBlockOrderBatchAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterBlockOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( DeRegisterUserOnServerResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelHourlyOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelComplexOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelBlockOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BroadcastAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AcceptNotificationResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrievePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveViewablePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradablePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveBlocksAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveExclusiveGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveViewableAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradableAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelBlockAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelExclusiveGroupAcknowledgement ) ) ] [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class OpenAccessAbstractObject : DomainObject { public OpenAccessAbstractObject ( ) { } } [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ResponseLimitationHeader ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( OpenAccessAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MarketResultIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Broadcast ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderBatch ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionInformationQuery ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionDateTime ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AsynchronousResponseHeader ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaPortfolioInformationQuery ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MessageAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Messages ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MessageIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ClientMessage ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( MarketResult ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrderIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyPeriod ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( HourlyOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CurvePoint ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AbstractOrderObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Curve ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( IdentifiedOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( OrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Order ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrderIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ComplexOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaAuctionIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaPortfolioInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AreaInformation ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AsynchronousNotification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ExclusiveGroupIndexToIdMapping ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockIndexToIdMapping ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AuctionIdentification ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderIdentifier ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockPeriod ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SmartBlockOrderAbstractObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SmartBlockOrder ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BlockOrderForBatch ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ErrorObject ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( Acknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( UserLogoutAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SetNewPasswordAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( SetMessagesAsReadAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradeableAreaSetsAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveSmartBlockOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveMessagesAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveMarketResultAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveHourlyOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveComplexOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveBlockOrdersAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAuctionInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreaPortfolioInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreaInformationAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ReportRelayServerErrorResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ReportRelayErrorResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RemoveReverseConnectionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RegisterUserOnServerResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RegisterForAsyncEventsResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( ProcessAsynchronousNotificationResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( LogoutAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( GetNotificationsResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EstablishSessionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EstablishReverseConnectionResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterHourlyOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterComplexOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterBlockOrderBatchAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( EnterBlockOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( DeRegisterUserOnServerResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelHourlyOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelComplexOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelBlockOrderAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( BroadcastAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( AcceptNotificationResponse ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrievePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveViewablePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradablePortfoliosAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveBlocksAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveExclusiveGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveViewableAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( RetrieveTradableAreasAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelBlockAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelGroupAcknowledgement ) ) ] [ System.Xml.Serialization.XmlIncludeAttribute ( typeof ( CancelExclusiveGroupAcknowledgement ) ) ] [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class DomainObject : System.Web.Services.Protocols.SoapHeader { } [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.Xml '' , `` 4.7.3130.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( Namespace= '' urn : openaccess '' ) ] public partial class AuctionIdentification : OpenAccessAbstractObject { public AuctionIdentification ( ) { } private System.DateTime itemField ; private ItemChoiceType1 itemElementNameField ; private string nameField ; private AuctionIdentificationDuration durationField ; private bool durationFieldSpecified ; /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( `` AuctionDate '' , typeof ( System.DateTime ) , DataType= '' date '' ) ] [ System.Xml.Serialization.XmlElementAttribute ( `` UTCDateTime '' , typeof ( System.DateTime ) ) ] [ System.Xml.Serialization.XmlChoiceIdentifierAttribute ( `` ItemElementName '' ) ] public System.DateTime Item { get { return this.itemField ; } set { this.itemField = value ; } } /// < remarks/ > [ System.Xml.Serialization.XmlIgnoreAttribute ( ) ] public ItemChoiceType1 ItemElementName { get { return this.itemElementNameField ; } set { this.itemElementNameField = value ; } } /// < remarks/ > public string name { get { return this.nameField ; } set { this.nameField = value ; } } /// < remarks/ > public AuctionIdentificationDuration duration { get { return this.durationField ; } set { this.durationField = value ; } } /// < remarks/ > [ System.Xml.Serialization.XmlIgnoreAttribute ( ) ] public bool durationSpecified { get { return this.durationFieldSpecified ; } set { this.durationFieldSpecified = value ; } } } //Retrieve Orders [ System.Web.Services.Protocols.SoapHeaderAttribute ( `` SessionTokenValue '' ) ] [ System.Web.Services.Protocols.SoapHeaderAttribute ( `` ResponseLimitationHeaderValue '' , Direction=System.Web.Services.Protocols.SoapHeaderDirection.InOut ) ] [ System.Web.Services.Protocols.SoapRpcMethodAttribute ( `` RetrieveOrders '' , RequestNamespace= '' urn : openaccess '' , ResponseNamespace= '' urn : openaccess '' , Use=System.Web.Services.Description.SoapBindingUse.Literal ) ] public RetrieveOrdersAcknowledgement RetrieveOrders ( OrderIdentifier OrderIdentifier ) { object [ ] results = this.Invoke ( `` RetrieveOrders '' , new object [ ] { OrderIdentifier } ) ; return ( ( RetrieveOrdersAcknowledgement ) ( results [ 0 ] ) ) ; }
Web Service method - can not be serialized because it does not have a parameterless constructor
C_sharp : I am working on the first lab of headfirst C # . I ran into a problem in my program that the dogs go at the same speed . I cant figure out why they do so , because in my eyes every object instance get a random 1 to 5 pixels added to its X location . The randomness of this should make enough of a difference.So because I dont want to post my entire set of classes of Lab 1 I recreated a small and independent version with only two dogs racing , and without the betting aspect.Form1.Designer contains : -Two pictureboxes with a hound in it.-a Start buttonGreyhound.cs class : Form1.cs class : Can anyone see something wrong with the way this is created ? A reason for why the dogs would run at the same speed instead of random 1 to 5 pixels per time . <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.Drawing ; namespace test { public class Greyhound { public int DogID ; public PictureBox myPictureBox ; public Point StartingPosition ; public Point CurrentPosition ; public Random Randomizer ; public bool Run ( ) { int AddDistance = Randomizer.Next ( 1 , 7 ) ; CurrentPosition.X += AddDistance ; myPictureBox.Location = CurrentPosition ; if ( CurrentPosition.X > 600 ) { return true ; } else { return false ; } } public void ReturnToStart ( ) { CurrentPosition = StartingPosition ; myPictureBox.Location = StartingPosition ; } } } 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 test { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void timer1_Tick ( object sender , EventArgs e ) { Greyhound One = new Greyhound ( ) { DogID = 1 , myPictureBox = pictureBox1 , StartingPosition = pictureBox1.Location , CurrentPosition = pictureBox1.Location , Randomizer = new Random ( ) } ; Greyhound Two = new Greyhound ( ) { DogID = 2 , myPictureBox = pictureBox2 , StartingPosition = pictureBox1.Location , CurrentPosition = pictureBox2.Location , Randomizer = new Random ( ) } ; if ( One.Run ( ) ) { timer1.Enabled = false ; MessageBox.Show ( `` Dog One WON ! `` ) ; } else if ( Two.Run ( ) ) { timer1.Enabled = false ; MessageBox.Show ( `` Dog Two WON ! `` ) ; } } private void button1_Click ( object sender , EventArgs e ) { timer1.Enabled = true ; } } }
Dogs go at same speed
C_sharp : Why does this snippet of code produces 60ddd , and this one produces ddd302010 ? Seems like it 's very simple , but I ca n't get my head around it.Please , show me direction in which I can go in order to find a detailed answer.Thanks ! <code> string str = 30 + 20 + 10 + `` ddd '' ; Console.WriteLine ( str ) ; string str = `` ddd '' + 30 + 20 + 10 ; Console.WriteLine ( str ) ;
How does c # string evaluates its own value ?
C_sharp : Is there a way to use value ending with space as XmlPoke value ? When I execute task , value is replaced but without space at the end.Reproduction : test.targets : test.xml : When I run : I get output.xml without space : Is there a way to force XmlPoke to set correct value ( with space at the end ) ? <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Project ToolsVersion= '' 14.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < Target Name= '' Build '' > < Copy SourceFiles= '' test.xml '' DestinationFiles= '' output.xml '' / > < XmlPoke Query= '' /root/element/ @ attr [ .='replaceme ' ] |/root/replaceme '' Value= '' X `` XmlInputPath= '' output.xml '' / > < /Target > < /Project > < root > < element attr= '' replaceme '' / > < replaceme/ > < /root > MSBuild /v : detailed test.targets < root > < element attr= '' X '' / > < replaceme > X < /replaceme > < /root >
XmlPoke task trims value
C_sharp : I am wanting to trim any white space off a collection of strings . I used the following code but it does n't seem to work . Could anyone explain why ? <code> result.ForEach ( f = > f = f.Trim ( ) ) ;
Do n't understand why the ForEach command is n't working
C_sharp : This question is somewhat an illustration to a related post , I believe the example below describes the essence of the problem.Is n't it bad that the second call to GetData raises exception only because GetData received a parameter cast to dynamic ? The method itself is fine with such argument : it treats it as a string and returns correct result . But result is then cast to dynamic again , and suddenly result data can not be treated according to its underlying type . Unless it 's explicitly cast back to a static type , as we see in the last lines of the example.I failed to understand why it had to be implemented this way . It breaks interoperability between static and dynamic types . Once dynamic is used , it kind of infects the rest of the call chain potentially causing problems like this one.UPDATE . Some people pointed out that Count ( ) is an extension method , and it makes sense that it 's not recognized . Then I changed a call res2.Count ( ) to res2.Count ( from an extension method to a property of Ilist ) , but the program raised the same exception in the same place ! Now that is strange.UPDATE2 . flq pointed to Eric Lippert 's blog posts on this topic , and I believe this post gives sufficient reasoning for why it is implemented this way : http : //blogs.msdn.com/b/ericlippert/archive/2012/10/22/a-method-group-of-one.aspx <code> class Program { public static IList < string > GetData ( string arg ) { return new string [ ] { `` a '' , `` b '' , `` c '' } ; } static void Main ( string [ ] args ) { var arg1 = `` abc '' ; var res1 = GetData ( arg1 ) ; Console.WriteLine ( res1.Count ( ) ) ; dynamic arg2 = `` abc '' ; var res2 = GetData ( arg2 ) ; try { Console.WriteLine ( res2.Count ( ) ) ; } catch ( RuntimeBinderException ) { Console.WriteLine ( `` Exception when accessing Count method '' ) ; } IEnumerable < string > res3 = res2 ; Console.WriteLine ( res3.Count ( ) ) ; } }
Bad interoperability between static and dynamic C #
C_sharp : I am writing an IComparer < T > implementation by deriving from the Comparer < T > class , as recommended by MSDN . For example : However , under this approach , the MyComparer class inherits the Default and Create static members from the Comparer < T > class . This is undesirable , since the implementation of the said members is unrelated to my derived class , and may lead to misleading behaviour : My comparer can not have a default instance due to the required Helper argument , nor can it initialize itself from a Comparison < T > , so I can not hide the inherited static members with meaningful implementations.What is the recommended practice for such situations ? I 'm considering three options : Implement IComparer < T > manually , rather than deriving from Comparer < T > , so as to avoid inheriting the said static membersLeave the inherited static members in place , and assume consumers will know not to use themHide the inherited static members with new implementations that throw InvalidOperationException : <code> public class MyComparer : Comparer < MyClass > { private readonly Helper _helper ; public MyComparer ( Helper helper ) { if ( helper == null ) throw new ArgumentNullException ( nameof ( helper ) ) ; _helper = helper ; } public override int Compare ( MyClass x , MyClass y ) { // perform comparison using _helper } } // calls MyClass.CompareTo or throws InvalidOperationExceptionMyComparer.Default.Compare ( new MyClass ( ) , new MyClass ( ) ) ; public static new Comparer < MyClass > Default { get { throw new InvalidOperationException ( ) ; } } public static new Comparer < MyClass > Create ( Comparison < MyClass > comparison ) { throw new InvalidOperationException ( ) ; }
Should derived classes hide the Default and Create static members inherited from Comparer < T > ?
C_sharp : Is there a difference between these two implementations ? 1 :2 : The first one seems to be more correct than the second in regards to memory leaks . But is it really correct ? <code> public class SMSManager : ManagerBase { private EventHandler < SheetButtonClickEventArgs > _buttonClickevent ; public SMSManager ( DataBlock smsDataBlock , DataBlock telephonesDataBlock ) : base ( smsDataBlock ) { _buttonClickevent = new EventHandler < SheetButtonClickEventArgs > ( OnButtonClick ) ; SheetEvents.ButtonClick += _buttonClickevent ; } public override void Dispose ( ) { base.Dispose ( ) ; if ( _buttonClickevent ! = null ) SheetEvents.ButtonClick -= _buttonClickevent ; } } public class SMSManager : ManagerBase { public SMSManager ( DataBlock smsDataBlock , DataBlock telephonesDataBlock ) : base ( smsDataBlock ) { SheetEvents.ButtonClick += new EventHandler < SheetButtonClickEventArgs > ( OnButtonClick ) ; } public override void Dispose ( ) { base.Dispose ( ) ; SheetEvents.ButtonClick -= new EventHandler < SheetButtonClickEventArgs > ( OnButtonClick ) ; } }
Difference between two dispose implementations ?