text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Most of the implementation complexity of the collection framework arises from the fact , that Scala can - unlike C # 's LINQ or other collection frameworks - return the `` best '' collection type for higher order functions : Why does this principle not hold for methods like seq , par , view , force ? Is there a technical limitation which prevents it from working ? Or is this by design/intent ? Considering that LINQ is basically lazy , Scala 's equivalent ( view , force ) is n't more type-safe ( only when using the strict methods ) , right ? <code> val numbers = List ( 1,2,3,4,5 ) numbers map ( 2* ) // returns a List [ Int ] = List ( 2 , 4 , 6 , 8 ) val doubles = Array ( 1.0 , 2.0 , 3.0 ) doubles filter ( _ < 3 ) // returns Array [ Double ] = Array ( 1.0 , 2.0 ) numbers.view.map ( 2* ) .force // returns Seq [ Int ] = List ( 2 , 4 , 6 , 8 ) numbers.seq // returns scala.collection.immutable.Seq [ Int ] = List ( 1 , 2 , 3 , 4 ) doubles.par.seq // returns scala.collection.mutable.ArraySeq [ Double ] = ArraySeq ( 1.0 , 2.0 , 3.0 ) | Can Scala collection 's seq/par/view/force be seen as a violation of the uniform return type principle ? |
C_sharp : We are building an ASP.NET project , and encapsulating all of our business logic in service classes . Some is in the domain objects , but generally those are rather anemic ( due to the ORM we are using , that wo n't change ) . To better enable unit testing , we define interfaces for each service and utilize D.I.. E.g . here are a couple of the interfaces : All of the methods in these services are basically groups of tasks , and the classes contain no private member variables ( other than references to the dependent services ) . Before we worried about Unit Testing , we 'd just declare all these classes as static and have them call each other directly . Now we 'll set up the class like this if the service depends on other services : This really is n't usually a problem , but I wonder why not set up a factory class that we pass around instead ? i.e.Then instead of calling : we 'd callWhat 's the downfall of this method ? It 's still testable , it still allows us to use D.I . ( and handle external dependencies like database contexts and e-mail senders via D.I . within and outside the factory ) , and it eliminates a lot of D.I . setup and consolidates dependencies more.Thanks for your thoughts ! <code> IEmployeeServiceIDepartmentServiceIOrderService ... public EmployeeService : IEmployeeService { private readonly IOrderService _orderSvc ; private readonly IDepartmentService _deptSvc ; private readonly IEmployeeRepository _empRep ; public EmployeeService ( IOrderService orderSvc , IDepartmentService deptSvc , IEmployeeRepository empRep ) { _orderSvc = orderSvc ; _deptSvc = deptSvc ; _empRep = empRep ; } //methods down here } public ServiceFactory { virtual IEmployeeService GetEmployeeService ( ) ; virtual IDepartmentService GetDepartmentService ( ) ; virtual IOrderService GetOrderService ( ) ; } _orderSvc.CalcOrderTotal ( orderId ) _svcFactory.GetOrderService.CalcOrderTotal ( orderid ) | Why not lump all service classes into a Factory method ( instead of injecting interfaces ) ? |
C_sharp : I ran into a weird case where Close event of the child window propagate to the parent window and causes it to close as well . I made a minimum example as shown belowFor TestWindow there is nothing but the default WPF window generated by VSand in App.xaml.cs I override the OnStartup event and use it as a custom Main functionNow if you click on the X button to close TestWindow , the application shuts down instead of showing the MainWindow . If you comment out t.ShowDialog then the MainWindow will show just fine . Next if you listen to the Closing event of MainWindow you will find that it will trigger after the TestWindow closes which does n't seem right to me <code> protected override void OnStartup ( StartupEventArgs e ) { base.OnStartup ( e ) ; TestWindow t = new TestWindow ( ) ; t.ShowDialog ( ) ; } | Why would Window.Close event propagate ? |
C_sharp : I have something like the following to be a key for a generic dictionary.From what I understand of EqualityComparer < T > .Default , it should see that I have implemented IEquatable < T > and therefore create an EqualityComparer on the fly . Dictionary < TKey , TValue > requires an equality implementation to determine whether keys are equal . If comparer is null , this constructor uses the default generic equality comparer , EqualityComparer < T > .Default . If type TKey implements the System.IEquatable < T > generic interface , the default equality comparer uses that implementation.However from what I see of using the dictionary indexer Dictionary < T > [ ] , it still relies on overriding GetHashcode e.g public override int GetHashCode ( ) I can see that there are recommendations to override the lot for consistency , but I 'm trying to understand it more . Is it because IEquatable should instead be directly on MyClass rather than in IMyClass ? But I 'd prefer it on the IMyClass so implementers need to be a dictionary key . I 'm experimenting with IEqualityComparer , but from what I understand I do n't need it . <code> class IMyClass < T > : IEquatable < IMyClass > where T : struct { //etc } class MyClass < T > : IMyClass < T > where T : struct { public bool Equals ( IRatingKey < T > other ) { //etc } } | My IEquatable is still using Object.GetHashcode for Dictionary < T > [ ] |
C_sharp : Basically , the title says what I 'd like to do.I have a string such as the following.I 'd like to convert this into a 2-dimensional boolean array ( obviously , 0 - > false and 1 - > true ) . My current approach is removing non-linebreak-whitespace , then iterating through the lines of the string.This leaves me with transforming a string such as 10101 into a boolean array of true , false , true , false , true . Now , I 'm hoping that there are pre-existing methods to do this conversion - using Java , I 'm pretty sure it could be done using the streams API , but unfortunately , I 'm not that adept with C # yet.Hence , my question : Are there existing methods to do this conversion in a compact way ? Or do I have to manually iterate over the string and do a == 0/==1 comparison for each character ? <code> 1 0 1 0 10 0 0 0 01 0 0 0 10 0 0 0 01 0 1 0 1 | How to transform a string of 0s and 1s into a boolean array |
C_sharp : Let we have two members equal by signature , but one is static and another - is not : but such code generate brings a compiler error : Type 'Foo ' already defines a member called 'Test ' with the same parameter typesBut why ? Let we compiled that successfully , then : Foo.Test ( ) should output `` static '' new Foo ( ) .Test ( ) ; should output `` instance '' Ca n't call the static member instead of instance one because in this case another , more reasonable compiler error will occur : Member 'Foo.Test ( ) ' can not be accessed with an instance reference ; qualify it with a type name instead <code> class Foo { public void Test ( ) { Console.WriteLine ( `` instance '' ) ; } public static void Test ( ) { Console.WriteLine ( `` static '' ) ; } } | Why does C # compiler overload resolution algorithm treat static and instance members with equal signature as equal ? |
C_sharp : I am working through a code sample , and I just want to hear some opinions on the way that they have done things . They use plain old ADO.NET . They have a generic function called Read that brings back 1 record . Here is the code : I do n't know why : They use Func < IDataReader , T > make as part of the method signature ? Is it efficient to do it like this ? Is there a better way/best practice to do this ? I do n't understand T t = default ( T ) ; ? Is it efficient to do it like this ? Is there a better way/best practice to do this ? What does t = make ( reader ) ; do ? Is it efficient to do it like this ? Is there a better way/best practice to do this ? The calling function would look something like this : I do n't understand the Func Make part ? Can someone please explain to me what is happening here and if this is good practices . Any changes would be appreciated , but please provide detailed sample code : ) <code> public static T Read < T > ( string storedProcedure , Func < IDataReader , T > make , object [ ] parms = null ) { using ( SqlConnection connection = new SqlConnection ( ) ) { connection.ConnectionString = connectionString ; using ( SqlCommand command = new SqlCommand ( ) ) { command.Connection = connection ; command.CommandType = CommandType.StoredProcedure ; command.CommandText = storedProcedure ; command.SetParameters ( parms ) ; connection.Open ( ) ; T t = default ( T ) ; var reader = command.ExecuteReader ( ) ; if ( reader.Read ( ) ) t = make ( reader ) ; return t ; } } } public Customer GetCustomer ( int customerId ) { // Other code here string storedProcedure = `` MyStoredProcedure '' ; object [ ] parameters = { `` @ CustomerId '' , customerId } ; return Db.Read ( storedProcedure , Make , parameters ) ; } private static Func < IDataReader , Customer > Make = reader = > new Customer { CustomerId = reader [ `` CustomerId '' ] .AsId ( ) , Company = reader [ `` CompanyName '' ] .AsString ( ) , City = reader [ `` City '' ] .AsString } ; | Creating a generic retrieval method to return 1 record |
C_sharp : I need to load a collection of items as documents in AvalonDock 2.0 . These objects inherit from an abstract class , for which I want to render a frame inside the document depending on which subclass are.This is my XAML : So far I 've achieved to show as many documents as items are in the OpenProjects collection , but I ca n't seem to show anything inside each document . Plus , I do n't know if I 'm using ActiveContent properly : I want to assign to CurrentProject the ViewModel assigned on the current active document.Thank you for your time . <code> < ad : DockingManager Background= '' Gray '' DocumentsSource= '' { Binding Path=OpenProjects } '' ActiveContent= '' { Binding Path=CurrentProject , Mode=TwoWay } '' > < ad : DockingManager.DocumentHeaderTemplate > < DataTemplate > < TextBlock Text= '' { Binding Path=OpenProjects/Name } '' / > < /DataTemplate > < /ad : DockingManager.DocumentHeaderTemplate > < ad : DockingManager.LayoutItemTemplate > < DataTemplate > < Grid > < Grid.Resources > < DataTemplate DataType= '' { x : Type vm : SubclassAViewModel } '' > < Frame Source= '' Pages/SubclassAProject.xaml '' / > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : SubclassBViewModel } '' > < Frame Source= '' Pages/SubclassBProject.xaml '' / > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : SubclassCViewModel } '' > < Frame Source= '' Pages/SubclassCProject.xaml '' / > < /DataTemplate > < /Grid.Resources > < /Grid > < /DataTemplate > < /ad : DockingManager.LayoutItemTemplate > < ad : LayoutRoot > < ad : LayoutPanel > < ad : LayoutDocumentPaneGroup > < ad : LayoutDocumentPane > < /ad : LayoutDocumentPane > < /ad : LayoutDocumentPaneGroup > < /ad : LayoutPanel > < /ad : LayoutRoot > < /ad : DockingManager > | How do I bind an ObservableCollection to an AvalonDock DocumentPaneGroup ? |
C_sharp : Let 's imagine we got the following : A ) Factory interface such asB ) Concrete factory such asC ) Employees family : Manager and Sales inherited from an abstract Employee . More on my simple ) architectureSome client codeI wanted to ask about some business logic architecture details . Using the architecture I ca n't design what the Company class should be , do n't know how do I integrate it . I have read that it more appropriate to use Role-based architecture in such cases . Could you provide an example ( Company , Employees entities ) ? Thanks ! <code> public interface IEmployeeFactory { IEmployee CreateEmployee ( Person person , Constants.EmployeeType type , DateTime hiredate ) ; } public sealed class EmployeeFactory : Interfaces.IEmployeeFactory { public Interfaces.IEmployee CreateEmployee ( Person person , Constants.EmployeeType type , DateTime hiredate ) { switch ( type ) { case BusinessObjects.Common.Constants.EmployeeType.MANAGER : { return new Concrete.Manager ( person , hiredate ) ; } case BusinessObjects.Common.Constants.EmployeeType.SALES : { return new Concrete.Sales ( person , hiredate ) ; } default : { throw new ArgumentException ( `` Invalid employee type '' ) ; } } } } public sealed class EmployeeFactoryClient { private Interfaces.IEmployeeFactory factory ; private IDictionary < String , Interfaces.IEmployee > employees ; public Interfaces.IEmployee this [ String key ] { get { return this.employees [ key ] ; } set { this.employees [ key ] = value ; } } public EmployeeFactoryClient ( Interfaces.IEmployeeFactory factory ) { this.factory = factory ; this.employees = new Dictionary < String , Interfaces.IEmployee > ( ) ; } public void AddEmployee ( Person person , Constants.EmployeeType type , DateTime hiredate , String key ) { this.employees.Add ( new KeyValuePair < String , Interfaces.IEmployee > ( key , this.factory.CreateEmployee ( person , type , hiredate ) ) ) ; } public void RemoveEmployee ( String key ) { this.employees.Remove ( key ) ; } public void ListAll ( ) { foreach ( var item in this.employees ) { Console.WriteLine ( `` Employee ID : `` + item.Key.ToString ( ) + `` ; Details : `` + item.Value.ToString ( ) ) ; } } } class ApplicationShell { public static void Main ( ) { var client = new EmployeeFactoryClient ( new EmployeeFactory ( ) ) ; client.AddEmployee ( new Person { FirstName = `` Walter '' , LastName = `` Bishop '' , Gender = BusinessObjects.Common.Constants.SexType.MALE , Birthday = new DateTime ( ) } , BusinessObjects.Common.Constants.EmployeeType.MANAGER , new DateTime ( ) , `` A0001M '' ) ; Console.WriteLine ( client [ `` A0001M '' ] .ToString ( ) ) ; Console.ReadLine ( ) ; } } | Roles , Abstract Pattern , Loose Coupling |
C_sharp : I often need to augment a object with a property for instance . Until now ( tired of it ; ) and it 's ugly too ) I have done it this way : Is there a clever way to do this ? What I have done previously is something like this : I guess this could be done with some reflection , but I imagine there is a faster approach which makes something equivalent to the first cumbersome approach.Thanks , Lasse <code> var someListOfObjects = ... ; var objectsWithMyProperty = from o in someListOfObjects select new { o.Name , /* Just copying all the attributes I need */ o.Address , /* which may be all of them . */ SomeNewProperty = value } ; var objectsWithMyProperty = from o in someListOfObjects select new { OldObject = o , /* I access all of the old properties from here */ SomeNewProperty = value } ; | How to augment anonymous type object in C # |
C_sharp : ( This question was first asked in the Ninject Google Group , but I see now that Stackoverflow seems to be more active . ) I 'm using the NamedScopeExtension to inject the same ViewModel into both the View and the Presenter . After the View have been released , memory profiling shows that the ViewModel is still retained by the Ninject cache . How can I make Ninject release the ViewModel ? All ViewModels are released when the Form is Closed and Disposed , but I 'm creating and deleting Controls using a Factory in the Form and would like the ViewModels be garbage collected to ( the Presenter and View gets collected ) .See the following UnitTest , using dotMemoryUnit , for an illustration of the problem : The dotMemory.Check assert fails and when analyzing the snapshot the ViewModel has references to the Ninject cache . I thought the named scope should be released when the View was released . Regards , Andreas <code> using System ; using FluentAssertions ; using JetBrains.dotMemoryUnit ; using Microsoft.VisualStudio.TestTools.UnitTesting ; using Ninject ; using Ninject.Extensions.DependencyCreation ; using Ninject.Extensions.NamedScope ; namespace UnitTestProject { [ TestClass ] [ DotMemoryUnit ( FailIfRunWithoutSupport = false ) ] public class UnitTest1 { [ TestMethod ] public void TestMethod ( ) { // Call in sub method so no local variables are left for the memory profiling SubMethod ( ) ; // Assert dotMemory.Check ( m = > { m.GetObjects ( w = > w.Type.Is < ViewModel > ( ) ) .ObjectsCount.Should ( ) .Be ( 0 ) ; } ) ; } private static void SubMethod ( ) { // Arrange var kernel = new StandardKernel ( ) ; string namedScope = `` namedScope '' ; kernel.Bind < View > ( ) .ToSelf ( ) .DefinesNamedScope ( namedScope ) ; kernel.DefineDependency < View , Presenter > ( ) ; kernel.Bind < ViewModel > ( ) .ToSelf ( ) .InNamedScope ( namedScope ) ; kernel.Bind < Presenter > ( ) .ToSelf ( ) .WithCreatorAsConstructorArgument ( `` view '' ) ; // Act var view = kernel.Get < View > ( ) ; kernel.Release ( view ) ; } } public class View { public View ( ) { } public View ( ViewModel vm ) { ViewModel = vm ; } public ViewModel ViewModel { get ; set ; } } public class ViewModel { } public class Presenter { public View View { get ; set ; } public ViewModel ViewModel { get ; set ; } public Presenter ( View view , ViewModel viewModel ) { View = view ; ViewModel = viewModel ; } } } | NamedScope and garbage collection |
C_sharp : I want to provide a set of filters for a user to pick from , and each filter will correspond to an Expression < Func < X , bool > > . So , I might want to take a dynamic list of available items ( 'Joe ' , 'Steve ' , 'Pete ' , etc ) , and create a collection of `` hard-coded '' filters based on those names , and let the user select which filter ( s ) he wants to use . My problem is that even when I try to `` hard-code '' my expression based on a string value from the dynamic list , the expression is still storing the value as , what looks to me , a property hanging off of an anonymous type ( and I do n't know how to serialize the anon . type ) . Sorry if this is confusing , I 'm not quite sure how to articulate this . Here 's my sample code : My problem is that when I look at when I look at the body of my expression , it reads as follows : When what I really want is for the first one to read like this : ( if I change my code to this , instead , that 's exactly what I get : ) I 've tried forcing my value to a local string value before sticking it into the Expression , but it does n't seem to help : I do n't understand why ( or really even how ) it 's still looking at some anonymous type even once I 'm using a local variable that is declared to a string . Is there a way to make this work as I want it to ? <code> public class Foo { public string Name { get ; set ; } } static void Main ( string [ ] args ) { Foo [ ] source = new Foo [ ] { new Foo ( ) { Name = `` Steven '' } , new Foo ( ) { Name = `` John '' } , new Foo ( ) { Name = `` Pete '' } , } ; List < Expression < Func < Foo , bool > > > filterLst = new List < Expression < Func < Foo , bool > > > ( ) ; foreach ( Foo f in source ) { Expression < Func < Foo , bool > > exp = x = > x.Name == f.Name ; filterLst.Add ( exp ) ; } } } ( x.Name = value ( ConsoleApplication1.Program+ < > c__DisplayClass3 ) .value ) ( x.Name = `` Steven '' ) Expression < Func < Foo , bool > > exp = x = > x.Name == `` Steven '' ; List < Expression < Func < Foo , bool > > > filterLst = new List < Expression < Func < Foo , bool > > > ( ) ; foreach ( Foo f in source ) { string value = f.Name ; Expression < Func < Foo , bool > > exp = x = > x.Name == value ; filterLst.Add ( exp ) ; } | LINQ : How to force a value based reference ? |
C_sharp : Following two methods ( one uses IEnumerator < int > , and other uses List < int > .Enumerator ) even though looks identical produces different results.There are couple of questions which clearly explains this behavior , you can check them here , here , and here.I still have following two doubtsWhy List.Enumerator does not throw `` NotSupportedException '' for Reset ? Why Reset was implemented explicitly and not implicitly like MoveNext and Current ? <code> static void M1 ( ) { var list = new List < int > ( ) { 1 , 2 , 3 , 4 } ; IEnumerator < int > iterator = list.GetEnumerator ( ) ; while ( iterator.MoveNext ( ) ) { Console.Write ( iterator.Current ) ; } iterator.Reset ( ) ; while ( iterator.MoveNext ( ) ) { Console.Write ( iterator.Current ) ; } } static void M2 ( ) { var list = new List < int > ( ) { 1 , 2 , 3 , 4 } ; //Here the iterator will be List < int > .Enumerator ( which is a struct ) var iterator = list.GetEnumerator ( ) ; while ( iterator.MoveNext ( ) ) { Console.Write ( iterator.Current ) ; } //This will not work , as Reset method was implemented explicitly //iterator.Reset ( ) ; //So casting it to IEnumerator is required //which will lead to boxing and other issues of struct and interface ( ( IEnumerator < int > ) iterator ) .Reset ( ) ; //Following loop will NOT work while ( iterator.MoveNext ( ) ) { Console.Write ( iterator.Current ) ; } } | Behavior of Reset method of List < T > .Enumerator |
C_sharp : I have an observable stream that produces values at inconsistent intervals like this : And I would like to sample this but without any empty samples once the a value has been produced : I obviously thought Replay ( ) .RefCount ( ) could be used here to provide the last known value to Sample ( ) but as it does n't re-subscribe to the source stream it did n't work out.Any thoughts on how I can do this ? <code> -- -- -- 1 -- -2 -- -- -- 3 -- -- -- -- -- -- -- -- 4 -- -- -- -- -- -- -- 5 -- - -- -- -- 1 -- -2 -- -- -- 3 -- -- -- -- -- -- -- -- 4 -- -- -- -- -- -- -- 5 -- -- -- -- -_ -- -- 1 -- -- 2 -- -- 3 -- -- 3 -- -- 3 -- -- 4 -- -- 4 -- -- 4 -- -- 5 -- -- 5 | Reactive Extensions ( Rx ) - sample with last known value when no value is present in interval |
C_sharp : Resharper just prompted me on this line of code : indicating that I should not say `` = false '' because bools , apparently , default to false in C # . I 've been programming in C # for over a year and a half and never knew that . I guess it just slipped through the cracks , but this leaves me wondering what 's good practice.Do I work on the assumption that default values are understood by all ? This would result in cleaner code , but invites ambiguity if another programmer is n't aware of the default value . <code> private static bool shouldWriteToDatabase = false ; | Is it always OK to not explicitly initialize a value if you would only be setting it to its default value ? |
C_sharp : So I 'm using SharpSVN ( SharpSvn.1.7-x86 1.7008.2243 ) and I keep running into a problem . Every time I try to use the SvnWorkingCopyClient on a repo that 's at the root of a drive ( for example say I have the D : \ drive , and it itself is a repo ) it throws a svn_dirent_is_absolute error at me.In fact the only command I could find that did n't care was SvnClient.GetUriFromWorkingCopy ( string ) Any Ideas on how I could resolve this ( aside from moving my working copy , or linking on the filesystem ) ? I 'm hoping to find a way in code , or an alternative to work around this limitation ( as it appears that SVN 1.7 does n't have this limitation anymore ) .Here 's some code ? I also stumbled across this http : //subversion.tigris.org/issues/show_bug.cgi ? id=3535 and http : //subversion.tigris.org/ds/viewMessage.do ? dsForumId=463 & viewType=browseAll & dsMessageId=2456472So , since that happened way back when , should n't this not be an issue anymore ? <code> private void fakeFunction ( ) { var RootPath= '' d : \ '' ; using ( var client = new SharpSvn.SvnClient ( ) ) using ( var workingClient = new SvnWorkingCopyClient ( ) ) { SvnWorkingCopyVersion workingVersion = null ; // Exception happens here if ( workingClient.GetVersion ( this.RootPath , out workingVersion ) ) { CurrentRevision = workingVersion.End ; // This will resolve just fine var targetUri = client.GetUriFromWorkingCopy ( RootPath ) ; var target = SvnTarget.FromUri ( targetUri ) ; SvnInfoEventArgs info = null ; if ( client.GetInfo ( target , out info ) ) { if ( workingVersion.End ! = info.Revision ) { System.Collections.ObjectModel.Collection < SvnLogEventArgs > logEventArgs = null ; if ( client.GetLog ( targetUri , out logEventArgs ) ) { var oldBack = Console.BackgroundColor ; var oldFor = Console.ForegroundColor ; Console.BackgroundColor = ConsoleColor.DarkMagenta ; Console.ForegroundColor = ConsoleColor.White ; foreach ( var l in logEventArgs ) { Console.WriteLine ( `` [ { 0 } - { 1 } ] - { 2 } '' , l.Revision , l.Author , l.LogMessage ) ; } Console.BackgroundColor = oldBack ; Console.ForegroundColor = oldFor ; } System.Console.WriteLine ( `` Repo not up to date . `` ) ; } } } } } | Ca n't read root |
C_sharp : I have 3 classes : A , B , and CAll of these classes implement an interface IMyInterfaceI would like the interface to be defined like so : So that it can return data of type E.The type `` E '' will be a POCO object created with the Entity Framework v4.In a separate class I have : I tried putting < object > in place of < ? ? > but it could not cast my poco entity type.I tried having my entities implement an empty interface IEntity then using results in : Any recommendations ? Edit : I 've tried declaring my A , B , and C classes as : and results in the same error . <code> internal IMyInterface < E > where E : class { E returnData ( ) ; } public class MyClass ( ) { IMyInterface < ? ? > businessLogic ; public setBusinessLogic ( IMyInterface < E > myObject ) where E : class { businessLogic = myObject ; } } IMyInterface < IEntity > businessLogic ; ... businessLogic = new A < POCOObject > ( ) ; Can not implicitly convert type ' A < POCOObject > ' to 'IMyInterface < IEntity > ' . An explicit conversion exists ( are you missing a cast ? ) internal class A : IBidManager < EntityObjectType > internal class A < E > : IBidManager < E > where E : class | C # Dependency Injection problem |
C_sharp : I was n't exactly sure how to ask this so I made an SSCCEI have this simple WCF serviceand I 'm trying to get a Winforms client to call the webservice method ; this is what I havenow on the service side , some of the properties are null as shown by the following screenshot.Why is it that the FileName has the right value but the others do n't ? <code> [ ServiceContract ] [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.PerCall ) ] public class EmailService { [ WebInvoke ( UriTemplate = `` /SendEmail '' , Method = `` POST '' , ResponseFormat = WebMessageFormat.Json , RequestFormat = WebMessageFormat.Xml ) ] public bool SendEmail ( EmailData data ) { try { byte [ ] fileBinaryContents = Convert.FromBase64String ( data.Enc64FileContents ) ; File.WriteAllBytes ( data.FileName , fileBinaryContents ) ; return true ; } catch ( Exception ) { return false ; } } } [ DataContract ( Namespace = `` http : //somenamespace/ '' ) ] public class EmailData { [ DataMember ] public string FileName { get ; set ; } [ DataMember ] public string EmailAddress { get ; set ; } [ DataMember ] public string Enc64FileContents { get ; set ; } } string URI = `` http : //localhost:59961/EmailService/SendEmail '' ; string fileContents = Convert.ToBase64String ( File.ReadAllBytes ( `` test.txt '' ) ) ; EmailData emailData = new EmailData { EmailAddress = `` foo @ bar.com '' , Enc64FileContents = fileContents , FileName = `` test.txt '' } ; XNamespace ns = `` http : //somenamespace/ '' ; XElement emailDataElement = new XElement ( ns + `` EmailData '' ) ; emailDataElement.Add ( new XElement ( ns + `` FileName '' , emailData.FileName ) ) ; emailDataElement.Add ( new XElement ( ns + `` Enc64FileContents '' , emailData.Enc64FileContents ) ) ; emailDataElement.Add ( new XElement ( ns + `` EmailAddress '' , emailData.EmailAddress ) ) ; var xml = emailDataElement.ToString ( SaveOptions.DisableFormatting ) ; using ( WebClient wc = new WebClient ( ) ) { wc.Headers [ HttpRequestHeader.ContentType ] = `` application/xml ; charset=utf-8 '' ; string response = wc.UploadString ( URI , `` POST '' , xml ) ; } | Simple WCF service , not all parameters from client making through to the service |
C_sharp : Why after starting the program will be displayed C : :Foo ( object o ) ? I can not understand why when you call C : : Foo , selects method with the object , not with int . What 's the class B and that method is marked as override ? In class C , there are two methods with the same name but different parameters , is it not overloaded ? Why not ? Does it matter that one of the methods to be overridden in the parent ? It somehow disables overload ? <code> using System ; namespace Program { class A { static void Main ( string [ ] args ) { var a = new C ( ) ; int x = 123 ; a.Foo ( x ) ; } } class B { public virtual void Foo ( int x ) { Console.WriteLine ( `` B : :Foo '' ) ; } } class C : B { public override void Foo ( int x ) { Console.WriteLine ( `` C : :Foo ( int x ) '' ) ; } public void Foo ( object o ) { Console.WriteLine ( `` C : :Foo ( object o ) '' ) ; } } } | Why overloading does not work ? |
C_sharp : What is the WPF equivalent of the following Java SWT code ? I want to create an Image from a list of RGBA values and display on a Canvas.Then draw it on a Canvas : <code> private Image GetImage ( ) { ImageData imageData = new ImageData ( imageWidth , imageHeight,32 , palette ) ; int pixelVecLoc=0 ; for ( int h = 0 ; h < imageHeight & & ( pixelVecLoc < currentImagePixelVec.size ( ) ) ; h++ ) { for ( int w = 0 ; w < imageWidth & & ( pixelVecLoc < currentImagePixelVec.size ( ) ) ; w++ ) { int p = 0 ; Pixel pixel = currentImagePixelVec.get ( pixelVecLoc ) ; p = ( pixel.Alpha < < 24 ) | ( pixel.Red < < 16 ) | ( pixel.Green < < 8 ) | pixel.Blue ; imageData.setPixel ( w , h , p ) ; pixelVecLoc++ ; } } imageData = imageData.scaledTo ( imageScaleWidth , imageScaleHeight ) ; Image image = ImageDescriptor.createFromImageData ( imageData ) .createImage ( ) ; return image ; } gc.drawImage ( image , 0 , 0 ) ; | What is the WPF equivalent of displaying an Image on a Canvas using ImageData in Java SWT |
C_sharp : I am trying to do a simple test , in which I pass in two generic objects to a test function , see if they can be cast to List < S > , and further , check if the counts of the lists are equal.The following code works : But if I uncomment the line marked with LINE MARKER 1 , I get the following error : I do not know beforehand that Test will receive Lists . But my intention is to first check if obj1 and obj2 can be taken as lists , and then to compareThanks in advance for your help . <code> private static void Test < T > ( T obj1 , T obj2 ) { if ( typeof ( T ) .IsGenericType ) { var genericTypeParam1 = typeof ( T ) .GetGenericArguments ( ) .First ( ) ; Console.WriteLine ( genericTypeParam1 ) ; // LINE MARKER 1 // var obj1AsList = ( obj1 as IEnumerable < genericTypeParam1 > ) ; } } static void Main ( string [ ] args ) { Test ( Enumerable.Range ( 0 , 5 ) .ToList ( ) , Enumerable.Range ( 0 , 5 ) .ToList ( ) ) ; Console.ReadLine ( ) ; } The type or namespace name 'genericTypeParam1 ' could not be found ( are you missing a using directive or an assembly reference ? ) var obj1AsList = obj1 as List < genericTypeParam1 > ; var obj2AsList = obj2 as List < genericTypeParam1 > ; var flag = ( obj1AsList ! = null ) & & ( obj2AsList ! = null ) & & ( obj1AsList.Count ( ) == obj2AsList.Count ( ) ) ; | Can not cast a generic type to list in C # |
C_sharp : Consider this code : andQuestion 1.If I use discard instead of a variable name , does it have performance benefit ? eg . by reducing assignment operations.Question 2.Is there any way to write the MultSum smart enough so it does n't calculate the discards ! ? <code> var ( mult , sum ) = MultSum ( a , b ) ; var ( _ , sum ) = MultSum ( a , b ) ; | Are there any performance benefits in C # discards ? |
C_sharp : I 'm storing an update operation as thus : For example : Then I 'm trying to apply this update later ( simplified ) : However , myUpdate.Value is a DateTime , not a DateTime ? . This is because when you cast a nullable to an object , it either becomes null or boxes the value type.Since ( DateTime ? ) myUpdate.Value would work to get it back to the correct type , I tried to simulate this compile-time construct using Convert.ChangeType . However , it says that casting from DateTime to DateTime ? is not possible.What approach can I use here to get the object back into its original type ? Is there any way to store a nullable types , regular structs and regular objects in a single field , and get the exact thing stored into it back again ? <code> class Update { public Expression MemberExpression { get ; set ; } public Type FieldType { get ; set ; } public object NewValue { get ; set ; } } var myUpdate = new Update { MemberExpression = ( MyType o ) = > o.LastModified , FieldType = typeof ( DateTime ? ) , NewValue = ( DateTime ? ) DateTime.Now } var lambda = myUpdate.MemberExpression as LambdaExpression ; var memberExpr = lambda.Body as MemberExpression ; var prop = memberExpr.Member as PropertyInfo ; prop.SetValue ( item , myUpdate.Value ) ; | Unboxing nullable types - workaround ? |
C_sharp : I need to inform a so-called worker thread to stop work at the next available oppertunity . Currently I 'm using something like this : The concern I have is that StopRequested is being set to True on a different thread . Is this safe ? I know I ca n't lock a boolean . Perhaps there 's a different way to inform a thread that a stop is required . For example I would be happy to check Thread.CurrentThread.ThreadState == ThreadState.StopRequested but it 's not clear how I can set the thread state as such . <code> public void Run ( ) { while ( ! StopRequested ) DoWork ( ) ; } | Options for informing a Thread to stop |
C_sharp : I found some examples of how to create unit of work with ef4 , i have n't used di/ioc and i would like to keep things simple and this an example ( 90 % inspired ) and i think it 's ok but since i am looking at a pattern to use from now on i would like to ask an opinion one last time.And finallyAfter getting rid if the IUnitOfWork and IDisposal the CreateUser looks like this : <code> public interface IUnitOfWork { void Save ( ) ; } public partial class TemplateEntities : ObjectContext , IUnitOfWork { ... . public void Save ( ) { SaveChanges ( ) ; } } public interface IUserRepository { User GetUser ( string username ) ; string GetUserNameByEmail ( string email ) ; void AddUser ( User userToAdd ) ; void UpdateUser ( User userToUpdate ) ; void DeleteUser ( User userToDelete ) ; //some other } public class UserRepository : IUserRepository , IDisposable { public TemplateEntities ctx ; public UserRepository ( IUnitOfWork unit ) { ctx = unit as TemplateEntities ; } public User GetUser ( string username ) { return ( from u in ctx.Users where u.UserName == username select u ) .SingleOrDefault ( ) ; } public string GetUserNameByEmail ( string email ) { return ( from u in ctx.Users where u.Email == email select u.UserName ) .SingleOrDefault ( ) ; } public void AddUser ( User userToAdd ) { ctx.Users.AddObject ( userToAdd ) ; } public void UpdateUser ( User userToUpdate ) { ctx.Users.Attach ( userToUpdate ) ; ctx.ObjectStateManager.ChangeObjectState ( userToUpdate , System.Data.EntityState.Modified ) ; } public void DeleteUser ( User userToDelete ) { ctx.Users.Attach ( userToDelete ) ; ctx.ObjectStateManager.ChangeObjectState ( userToDelete , System.Data.EntityState.Deleted ) ; } public void Dispose ( ) { if ( ctx ! = null ) ctx.Dispose ( ) ; } } public class BogusMembership : MembershipProvider { public MembershipCreateStatus CreateUser ( string username , string password , string email , bool autoemail , string fullname ) { IUnitOfWork ctx = new TemplateEntities ( ) ; using ( UserRepository rep = new UserRepository ( ctx ) ) { using ( TransactionScope tran = new TransactionScope ( ) ) { if ( rep.GetUser ( username ) ! = null ) return MembershipCreateStatus.DuplicateUserName ; if ( requiresUniqueEmail & & ! String.IsNullOrEmpty ( rep.GetUserNameByEmail ( email ) ) ) return MembershipCreateStatus.DuplicateEmail ; User userToCreate = new User { UserName = username , PassWord = EncodePassword ( password ) , FullName = fullname , Email = email , AutoEmail = autoemail } ; try { rep.AddUser ( userToCreate ) ; ctx.Save ( ) ; tran.Complete ( ) ; return MembershipCreateStatus.Success ; } catch { return MembershipCreateStatus.UserRejected ; } } } } } public MembershipCreateStatus CreateUser ( string username , string password , string email , bool autoemail , string fullname ) { using ( TransactionScope tran = new TransactionScope ( ) ) { using ( TemplateEntities ctx = new TemplateEntities ( ) ) { UserRepository rep = new UserRepository ( ctx ) ; //OtherRepository rep2 = new OtherRepository ( ctx ) ; if ( rep.GetUser ( username ) ! = null ) return MembershipCreateStatus.DuplicateUserName ; if ( requiresUniqueEmail & & ! String.IsNullOrEmpty ( rep.GetUserNameByEmail ( email ) ) ) return MembershipCreateStatus.DuplicateEmail ; User userToCreate = new User { UserName = username , PassWord = EncodePassword ( password ) , FullName = fullname , Email = email , AutoEmail = autoemail } ; try { rep.AddUser ( userToCreate ) ; ctx.SaveChanges ( ) ; tran.Complete ( ) ; return MembershipCreateStatus.Success ; } catch { return MembershipCreateStatus.UserRejected ; } } } } | Am i using correctly Unit of Work here ? ( Entityi Framework 4 POCO ) |
C_sharp : output ( 32 bit ) : output ( 64 bit ) : Storing the ints alone ( in an array ) would require about 80000 . <code> long b = GC.GetTotalMemory ( true ) ; SortedDictionary < int , int > sd = new SortedDictionary < int , int > ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { sd.Add ( i , i+1 ) ; } long a = GC.GetTotalMemory ( true ) ; Console.WriteLine ( ( a - b ) ) ; int reference = sd [ 10 ] ; 280108 480248 | Why does sortedDictionary need so much overhead ? |
C_sharp : I 'm trying to make if-else working in IL by System.Reflection and System.Reflection.Emit . This is the code which I currently have : Now , on line where I 'm marking label it throws me this exception : Object reference not set to an instance of an object.But I think it 's stupidity because that label is associated with new Label object.Does anybody know how can I solve this problem ? Thanks . <code> Label inequality = new System.Reflection.Emit.Label ( ) ; Label equality = new System.Reflection.Emit.Label ( ) ; Label end = new System.Reflection.Emit.Label ( ) ; var method = new DynamicMethod ( `` dummy '' , null , Type.EmptyTypes ) ; var g = method.GetILGenerator ( ) ; g.Emit ( OpCodes.Ldstr , `` string '' ) ; g.Emit ( OpCodes.Ldstr , `` string '' ) ; g.Emit ( OpCodes.Call , typeof ( String ) .GetMethod ( `` op_Equality '' , new Type [ ] { typeof ( string ) , typeof ( string ) } ) ) ; g.Emit ( OpCodes.Ldc_I4 , 0 ) ; g.Emit ( OpCodes.Ceq ) ; g.Emit ( OpCodes.Brtrue_S , inequality ) ; g.MarkLabel ( inequality ) ; //HERE it throws exceptiong.Emit ( OpCodes.Ldstr , `` Specified strings are different . `` ) ; g.Emit ( OpCodes.Call , typeof ( Console ) .GetMethod ( `` WriteLine '' , new Type [ ] { typeof ( string ) } ) ) ; g.Emit ( OpCodes.Br_S , end ) ; g.Emit ( OpCodes.Brfalse_S , equality ) ; g.MarkLabel ( equality ) ; g.Emit ( OpCodes.Ldstr , `` Specified strings are same . `` ) ; g.Emit ( OpCodes.Call , typeof ( Console ) .GetMethod ( `` WriteLine '' , new Type [ ] { typeof ( string ) } ) ) ; g.Emit ( OpCodes.Br_S , end ) ; g.MarkLabel ( end ) ; g.Emit ( OpCodes.Ret ) ; var action = ( Action ) method.CreateDelegate ( typeof ( Action ) ) ; action ( ) ; Console.Read ( ) ; | C # if else exception |
C_sharp : I 've gotten to a point now where I can receive responses from a client website I 've made ( for internal use in the company I work at ) on my WCF Webservice . But whenever I get a response it 's always null.I 've look around for various solutions and none of them seems to fix this issue . I have the following : And implemented : Just to test that it works . I set a breakpoint at the above function to read the jsonObject string and see what it looks like . When I read it though , it 's null . Always null.Here is the JavaScript : Anyone have any idea why it returns null ? UPDATEI used Fiddler and the information that leaves the website to the web service is correct . It 's a JSON String that Fiddler can read . But the web service still receives a null object . <code> [ OperationContract ] [ WebInvoke ( Method = `` POST '' , RequestFormat = WebMessageFormat.Json , ResponseFormat = WebMessageFormat.Json , BodyStyle = WebMessageBodyStyle.WrappedRequest , UriTemplate = `` /AddNewActivity '' ) ] String AddNewActivity ( String jsonObject ) ; public String AddNewActivity ( String jsonObject ) { return JsonConvert.SerializeObject ( `` Success '' ) ; } function OnModalCreateNewActivityBtnClick ( ) { var modal = $ ( ' # new-activity-modal-body ' ) ; var activityMap = { status : modal.find ( ' # new-activity-modal-status-dropdown ' ) .val ( ) , name : modal.find ( ' # new-activity-modal-name-field ' ) .val ( ) , responsible : modal.find ( ' # new-activity-modal-responsible-field ' ) .val ( ) , department : modal.find ( ' # new-activity-modal-department-dropdown ' ) .val ( ) , startTime : modal.find ( ' # new-activity-modal-datepicker-start ' ) .val ( ) , endTime : modal.find ( ' # new-activity-modal-datepicker-end ' ) .val ( ) , description : modal.find ( ' # editor ' ) .cleanHtml ( ) , axAccounts : modal.find ( ' # new-activity-modal-ax-account-numbers-field ' ) .val ( ) } ; var jsonObject = ' { `` String '' : ' + JSON.stringify ( activityMap ) + ' } ' ; $ .ajax ( { type : 'POST ' , url : 'http : //localhost:52535/PUendeligService.svc/AddNewActivity ' , data : jsonObject , contentType : 'application/json ; charset=utf-8 ' , dataType : 'json ' , processData : true , success : function ( data , status , jqXHR ) { alert ( `` Success : `` + data ) ; } , error : function ( xhr ) { console.log ( xhr.responseText ) ; alert ( `` Error : `` + xhr.responseText ) ; } } ) ; } | Client Website always return Null Json String |
C_sharp : I am looking at some C # code written by someone else . Whenever a form is instantiated and then shown , the following is done . Is this correct ? Why would you use `` using '' in this context ? Additional question : Could the following code be substituted ? <code> MyForm f ; using ( f = new MyForm ( ) ) { f.ShowDialog ( ) ; } using ( MyForm f = new MyForm ( ) ) { f.ShowDialog ( ) ; } | C # : `` using '' when instantiating a form ? |
C_sharp : I would like to enable multisampling when drawing triangles like on the following picture : I found a way to do with SlimDX in another question but it does n't work in exclusive mode.Here is my code : The last line alway crashs with a D3DERR_INVALIDCALL error even if the CheckDeviceMultisampleType return always true with no error and 8 for multisampleQuality.It works if I use the windowed mode or if I remove the multisample option.Can someone tell me what 's wrong ? <code> void Form1_Load ( object sender , EventArgs e ) { Direct3D d3d = new Direct3D ( ) ; PresentParameters presentParams ; presentParams.Windowed = false ; presentParams.BackBufferFormat = Format.X8R8G8B8 ; presentParams.BackBufferWidth = 800 ; presentParams.BackBufferHeight = 600 ; presentParams.FullScreenRefreshRateInHertz = 60 ; presentParams.SwapEffect = SwapEffect.Copy ; presentParams.BackBufferCount = 1 ; presentParams.PresentationInterval = PresentInterval.One ; int multisampleQuality ; Result result ; if ( d3d.CheckDeviceMultisampleType ( adaptor , DeviceType.Hardware , Format.X8R8G8B8 , false , MultisampleType.FourSamples , out multisampleQuality , out result ) ) { if ( multisampleQuality > 4 ) { presentParams.Multisample = multisampleType ; presentParams.MultisampleQuality = 4 ; } } // Device creation Device device = new Device ( d3d , adaptor , DeviceType.Hardware , this.Handle , CreateFlags.HardwareVertexProcessing , presentParams ) ; } | Multisampling does n't work in exclusive mode |
C_sharp : Accidently I actually wrote this method : It is working as suspected , but I was very surprised that is it allowed to use the new keyword in the return type of the method . Is there any effect/difference if i put there new or not ? Or what is the new used for ? And is this also possible in other OO-languages ? <code> public static new iTextSharp.text.Color ITextFocusColor ( ) { return new iTextSharp.text.Color ( 234 , 184 , 24 ) ; } | Whats the effect of new keyword in return type of a C # method ? |
C_sharp : I have been very intriuged by design patterns lately , and specifically following correct design patterns in my classes that implement one or several interfaces.Let 's take an example . When a class implement IDisposable you should follow a specific pattern to make sure that your resources are properly cleaned up , by creating a private Dispose ( bool disposing ) method that differentiates between if it 's called by the finalizer , or if it 's called from the public Dispose method . Also , a finalizer should be implemented in this case , and you might also need a private bool variable called isDisposed that is set by the Dispose method , so that any method called after th object is Disposed will call a Exception making it clear that this object is already disposed , instead of the code inside the method crashing because some of the required resouces are disposed , and thereby no longer available.There are also a lot of other interfaces I routinely implement , but it 's not all of them I am sure if the way I implement them is the preferred way of doing it , and I might find out later on that it causes a subtle bug that is hard to find , that would probably have been non-existant if I had followed the proper pattern in the first place . some examples of interfaces I would like to know the best way of implementing are ISerializable , IComparable , IComparable < > , ICloneable , IEnumerable < > , and so on . All interfaces from the Framework are interesting here , so it should not be limited to those I have listed above.What I 'm after is for different interfaces , the preferred way and hopefully also a link to resource on the internet that explains how and also why a specific pattern should be followed.I hope to get a good collection of these patterns , as I know that they can greatly improve my code and make it more correct , and follow best-practicesIt would be great if there are several patterns for the same interface so we can discuss which one is preferred . That might also cause some of you to maybe move over to a new pattern , or make modifications to your existing patterns to improve your code even further , and that would be great ! EditAfter reading Grzenios comment , I would also urge everyone to give the context the pattern should be applied for . For example the IDIsposable pattern should only be followed if you have some unmanaged resources inside your class that you need to dispose , and not if all the objects you need to dispose implements IDisposable themselves.Edit 2I should probably start this myself , since I put the question out here . So I 'll describe one pattern I know well , and that is the IDisposable pattern.This pattern should only be used if your class contain one or more unmanaged resources inside your class , and you hav eto make sure that they get Disposed . in this case in addition to the Dispose method we will need a finalizer in case the user of your class forget to dispose it.So first thing first . Your class should implement the IDisposable interface , and you will have to define the public Dispose method as goverend by the interface . This method should look like this : This will call the protected Dispose ( bool ) method that takes care of the actual cleanup.Also , include a vaiable in your class to indicate if the class is disposed or not : GC.SuppressFinalize tells the garbage collector that this item does not need to be finalized even if it has a finalizer.Then you need the protected Dispose method . Make it protected instead of private in case any derived class needs to override it : The finalizer should also call Dispose ( bool ) if the user forgets to clean up : If some method require a disposed resource to function , make the function like this : That 's it . This will make sure that the resources gets cleaned up . Preferable by the user of your class calling Dispose , but by adding a Finalizer as a fallback method . <code> public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } private bool alreadyDisposed = false ; protected virtual void Dispose ( bool isDisposing ) { if ( alreadyDisposed ) { return ; } if ( isDisposing ) { // free all managed resources here } // free all unmanaged resources here . alreadyDisposed = true ; } ~SomeClass ( ) { Dispose ( false ) ; } public void SomeMethod ( ) { if ( alreadyDisposed ) throw new ObjectDisposedException ( `` SomeClass '' , `` Called SomeMethod on Disposed object '' ) ; // Method body goes here } | Using specific patterns to implement interfaces |
C_sharp : I 'd like to create a component , which consist from a board and its surrounding corner . The size of the board ( and therefore also of the border ) is defined at run-time . Some examples ( board is bright and border is dark ) : alt text http : //img340.imageshack.us/img340/3862/examplegw.pngThe board consists of objects of the type BoardCell and the border consists of objects of the type BorderCell . Data structure for the board is BoardCell [ , ] - a simple two-dimensional array . How can I represent the border ? I started with something like this : I do n't like this representation of the border , can you suggest something better ? Additional : I 'd like to have a method SetSomethingForTheCell on the border object : but with my current data structure I do n't know what to pass as a parameter . <code> public BorderCell TopLeft // top left corner cellpublic BorderCell TopRight // top right corner cellpublic BorderCell BottomRight // bottom right corner cellpublic BorderCell BottomLeft // bottom left corner cellpublic BorderCell [ ] Top // top border ( without corners ) public BorderCell [ ] Bottom // bottom border ( without corners ) public BorderCell [ ] Left // left border ( without corners ) public BorderCell [ ] Right // right border ( without corners ) public void SetSomethingForTheCell ( ... ) | What data structure to use in my example |
C_sharp : I have following two approaches for same functionality - one with `` if ” condition and one with `` ? ? and casting '' . Which approach is better ? Why ? Code : UPDATEBased on the answers , following are the benefits of ? ? Increased readabilityDecreased branching deapth of program flow ( reduced cyclomatic complexity ) Note : Cost of casting as object is negligible.REFERENCENull-Coallescing Operator - Why Casting ? <code> Int16 ? reportID2 = null ; //Other code //Approach 1 if ( reportID2 == null ) { command.Parameters.AddWithValue ( `` @ report_type_code '' , DBNull.Value ) ; } else { command.Parameters.AddWithValue ( `` @ report_type_code '' , reportID2 ) ; } //Approach 2 command.Parameters.AddWithValue ( `` @ report_type_code '' , ( ( object ) reportID2 ) ? ? DBNull.Value ) ; | Is “ If ” condition better than ? ? and casting |
C_sharp : If i have some code like this and an error occurs in the second using statement , will the dispose method on 1st using not be called ? -- EDIT -- Also is it better to write Try / Finally block or using statement . Internally compilter will generate Try / Finally for using statement but as per coding standards which one is better ? <code> using ( System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection ( cnstr ) ) { cn.Open ( ) ; using ( SqlTransaction tran = cn.BeginTransaction ( IsolationLevel.Serializable ) ) { | nested using statements - which one wont get disposed |
C_sharp : Out of curiosity : This code is valid and executes : See it working on .NET FiddleBut this doesn´t even compile ( unassigned local variable ) : See it ( not ) working on .NET FiddleDateTime is a non nullable value type , so it doesn´t need to be assigned and initialized to have a value , it has a default one.So why the compiler allows the DateTime field version compile and doesn´t let the local variable version compile ? When the code is compiled to IL , what prevents an value type local variable from being used ? <code> public class Program { private static DateTime date ; public static void Main ( ) { Console.WriteLine ( date.ToString ( `` o '' ) ) ; } } public class Program { public static void Main ( ) { DateTime date ; Console.WriteLine ( date.ToString ( `` o '' ) ) ; } } | C # Compiler - Unassigned Field and Local Variable Initial Value |
C_sharp : I 'm still trying to get my FxCop rule working.As part of this , i need to work out what methods a method calls . Previously i was using CallGraph.CallersFor ( ) ( doing it in reverse , which is my final aim anyway ) , however it appears to have the same issue i describe below.As an alternative to using the CallGraph class i tried visiting all method calls to build a dictionary , based on this code : However , it turns out that if the called method is on a derived class that overrides a base class ' method , then the BoundMember is the base class ' method , not the child class ' method ( which is the one that will actually be called ) .Question : How can i get the method that will be called in the case of a callvirt IL instruction in FxCop ? <code> public override void VisitMethodCall ( MethodCall call ) { Method CalledMethod = ( call.Callee as MemberBinding ) .BoundMember as Method ; // ... . } | How to get the method actually called by the callvirt IL instruction within FxCop |
C_sharp : Lets say I have items and have ordering : [ 2 , 3 , 1 ] to get an enumerable I expect it to be something in the lines ofbut is there a cleaner solution ? Following I have verified that work ( HimBromBeere , Domysee , qxg ) Fwi , this was for verification test : <code> items : [ { id:1 , ... } , { id:2 , ... } , { id:3 , ... } ] items : [ { id:2 , ... } , { id:3 , ... } , { id:1 , ... } ] items.Select ( o = > new { key = ordering [ i++ ] , value = o } ) .OrderBy ( k = > k.key ) .Select ( o = > o.value ) var expectedOrder = ordering.Select ( x = > result.First ( o = > o.Id == x ) ) ; var expectedOrder = result.OrderBy ( item = > Array.FindIndex ( ordering , i = > i == item.Id ) ) ; var expectedOrder = result.OrderBy ( item = > ordering.ToList ( ) .FindIndex ( i = > i == item.Id ) ) ; var expectedOrder = from o in ordering join i in result on o equals i.Id select i ; [ Test ] [ TestCase ( 1 , 2 , 3 ) ] [ TestCase ( 1 , 3 , 2 ) ] [ TestCase ( 2 , 1 , 3 ) ] [ TestCase ( 2 , 3 , 1 ) ] [ TestCase ( 3 , 1 , 2 ) ] public void Test_Should_Fail_If_GetMessages_Does_Not_Return_Sorted_By_Sent_Then_By_Id_Result ( params int [ ] ordering ) { var questions = GetQuestionsData ( ) ; Mock.Get ( _questionService ) .Setup ( o = > o.GetQuestions ( ) ) .Returns ( questions ) ; var result = _mailboxService.GetMessages ( ) ; var expectedOrder = ordering.Select ( x = > result.First ( o = > o.Id == x ) ) ; // Act Action sortOrder = ( ) = > expectedOrder.Should ( ) .BeInDescendingOrder ( o = > o.Sent ) .And.BeInDescendingOrder ( o = > o.Id ) ; // Assert sortOrder.ShouldThrow < AssertionException > ( ) ; } | How to sort based on ordering |
C_sharp : If I had a non-anonymous class like this , I know I can use DisplayNameAttribute like this.but I haveand I use records for DataSource for a DataGrid . The column headers show up as Foo and Bar but they have to be The Foo and The Bar . I can not create a concrete class for a few different internal reasons and it will have to be an anonymous class . Given this , is there anyway I can set DisplayNameAttrubute for members of this anonymous class ? I triedbut it wo n't compile.Thanks . <code> class Record { [ DisplayName ( `` The Foo '' ) ] public string Foo { get ; set ; } [ DisplayName ( `` The Bar '' ) ] public string Bar { get ; set ; } } var records = ( from item in someCollection select { Foo = item.SomeField , Bar = item.SomeOtherField , } ) .ToList ( ) ; [ DisplayName ( `` The Foo '' ) ] Foo = item.SomeField | DisplayNameAttribute for anonymous class |
C_sharp : [ this question is in the realm of Reactive Extensions ( Rx ) ] A subscription that needs to continue on application restartNow I need to serialize and deserialize the state of this subscription so that next time the application is started the buffer count does NOT start from zero , but from whatever the buffer count got to before application exit . How could you persist the state of IObservable.Subscribe ( ) in this case and later load it ? Is there a general solution to saving observer state in Rx ? From Answer to SolutionBased on Paul Betts approach , here 's a semi-generalizable implementation that worked in my initial testingUseExtension methodsNotesThis will not work for storing states that depend on time-intervals between the values producedYou need a serializer implementation that supports serializing T_alreadyRecording is needed if you subscribe to myRecordableStream more than once_alreadyRecording is a static boolean , very ugly , and prevents the extension methods from being used in more than one place if needing parallel subscriptions - needs to be re-implemented for future use <code> int nValuesBeforeOutput = 123 ; myStream.Buffer ( nValuesBeforeOutput ) .Subscribe ( i = > Debug.WriteLine ( `` Something Critical on Every 123rd Value '' ) ) ; int nValuesBeforeOutput = 123 ; var myRecordableStream = myStream.Record ( serializer ) ; myRecordableStream.Buffer ( nValuesBeforeOutput ) .ClearRecords ( serializer ) .Subscribe ( i = > Debug.WriteLine ( `` Something Critical on Every 123rd Value '' ) ) ; private static bool _alreadyRecording ; public static IObservable < T > Record < T > ( this IObservable < T > input , IRepositor repositor ) { IObservable < T > output = input ; List < T > records = null ; if ( repositor.Deserialize ( ref records ) ) { ISubject < T > history = new ReplaySubject < T > ( ) ; records.ForEach ( history.OnNext ) ; output = input.Merge ( history ) ; } if ( ! _alreadyRecording ) { _alreadyRecording = true ; input.Subscribe ( i = > repositor.SerializeAppend ( new List < T > { i } ) ) ; } return output ; } public static IObservable < T > ClearRecords < T > ( this IObservable < T > input , IRepositor repositor ) { input.Subscribe ( i = > repositor.Clear ( ) ) ; return input ; } | store retrieve IObservable subscription state in Rx |
C_sharp : For instance , along the lines of : vsWhich is better both for clarity , ease of use , and most importantly performance . <code> public bool Intersect ( Ray ray , out float distance , out Vector3 normal ) { } public IntersectResult Intersect ( Ray ray ) { } public class IntersectResult { public bool Intersects { get ; set ; } public float Distance { get ; set ; } public Vector3 Normal { get ; set ; } } | Is it better to use out for multiple output values or return a combined value type ? |
C_sharp : I am working with a code that contains following overloaded method in generic class : When parametrizing the class for string do I lose the possibility to call the version with generic parameter ? <code> public class A < T > { public void Process ( T item ) { /*impl*/ } public void Process ( string item ) { /*impl*/ } } var a = new A < string > ( ) ; a.Process ( `` '' ) ; //Always calls the non-generic Process ( string ) | Method overloading in generic class |
C_sharp : Consider following interfaces : I have implemented IPowerSwitch in a class like this : Now I want to implement IHeatingElement interface in this class . IHeatingElement has the same methods as IPowerSwitch . So how I can implement the SwitchOn and SwitchOff of IHeatingElement.If I try to implement something like IPowerSwitch.SwitchOff ( ) , I get error 'IPowerSwitch.SwitchOff ' in explicit interface declaration is not a member of interface.What I want to do is that , when Power switch on event is raised Heating On event should be raised after that . And when heating is switched off , Power switch Off event should be raised . This is my first question here , so please guide me if something is wrong in the question.Thanks for your help in advance . <code> public interface IComponent { } public interface ISwitch : IComponent { bool IsOn { get ; } event EventHandler SwitchedOff ; event EventHandler SwitchedOn ; } public interface ISwitchable : ISwitch , IComponent { void SwitchOff ( ) ; void SwitchOn ( ) ; } public interface IPowerSwitch : ISwitchable , ISwitch , IComponent { } public interface IHeatingElement : ISwitchable , ISwitch , IComponent { } public class Kettle : IPowerSwitch { event EventHandler PowerOnEvent ; event EventHandler PowerOffEvent ; object objectLock = new Object ( ) ; public bool IsPowerOn ; public Kettle ( ) { IPowerSwitch p = ( IPowerSwitch ) this ; p.SwitchedOn += new EventHandler ( On_PowerOn_Press ) ; p.SwitchedOff += new EventHandler ( On_PowerOff_Press ) ; } void ISwitchable.SwitchOff ( ) { EventHandler handler = PowerOffEvent ; if ( handler ! = null ) { handler ( this , new EventArgs ( ) ) ; } } void ISwitchable.SwitchOn ( ) { EventHandler handler = PowerOnEvent ; if ( handler ! = null ) { handler ( this , new EventArgs ( ) ) ; } } bool ISwitch.IsOn { get { return IsPowerOn ; } } event EventHandler ISwitch.SwitchedOff { add { lock ( objectLock ) { PowerOffEvent += value ; } } remove { lock ( objectLock ) { PowerOffEvent -= value ; } } } event EventHandler ISwitch.SwitchedOn { add { lock ( objectLock ) { PowerOnEvent += value ; } } remove { lock ( objectLock ) { PowerOnEvent -= value ; } } } protected void On_PowerOn_Press ( object sender , EventArgs e ) { if ( ! ( ( IPowerSwitch ) sender ) .IsOn ) { Console.WriteLine ( `` Power Is ON '' ) ; ( ( Kettle ) sender ) .IsPowerOn = true ; ( ( IPowerLamp ) this ) .SwitchOn ( ) ; } else { Console.WriteLine ( `` Already ON '' ) ; } } protected void On_PowerOff_Press ( object sender , EventArgs e ) { if ( ( ( IPowerSwitch ) sender ) .IsOn ) { Console.WriteLine ( `` Power Is OFF '' ) ; ( ( Kettle ) sender ) .IsPowerOn = false ; ( ( IPowerLamp ) this ) .SwitchOff ( ) ; } else { Console.WriteLine ( `` Already OFF '' ) ; } } } | How to implement multiple interfaces with same methods inhereted from parent interfaces |
C_sharp : I am trying to learn the threading in C # . Today I sow the following code at http : //www.albahari.com/threading/ : In Java unless you define the `` done '' as volatile the code will not be safe . How does C # memory model handles this ? Guys , Thanks all for the answers . Much appreciated . <code> class ThreadTest { bool done ; static void Main ( ) { ThreadTest tt = new ThreadTest ( ) ; // Create a common instance new Thread ( tt.Go ) .Start ( ) ; tt.Go ( ) ; } // Note that Go is now an instance method void Go ( ) { if ( ! done ) { done = true ; Console.WriteLine ( `` Done '' ) ; } } } | Is the following C # code thread safe ? |
C_sharp : Consider this scenario.You have a repository that allows certain calls to be made on it . These calls use LINQ and could be relatively expensive in terms of the amount of data returned.Given that in my case , it 's not overly bad if the data is old - one could implement a cache , so that the large and expensive query was n't executed every call . Hey , we could even implement some caching policies to determine when to execute that query again based on time or useage.The thing I 'm trying to wrap my head around , is how to key that in a cache . One way would be to simply say : And then key the cache by a simple string . But , given we 're doing LINQ , could we potentially key the cache by the LINQ expression itself ? I understand the performance indications but is there anyway to compare whether two LINQ expressions are the same ? <code> `` querytype1 '' = Particular LINQ expression '' querytype2 '' = Particular LINQ expression | Caching LINQ expressions by equality |
C_sharp : I have a .NET Core console app that downloads files from an FTP server and processes them . I moved the app onto a new server , and it stopped working . Disabling Windows Firewall on the new server solves the problem , but obviously I do n't want to leave it wide open - I need a targeted way of enabling this app . FTP traffic seems to already be allowed ( inbound and outbound ) by the default firewall rules , so I do n't know which additional ports could be opened ( I think I 'm using active FTP , which can use a broad port range AFAIK ) . I would prefer to whitelist the application , but it is not an .exe file , so I 'm not exactly sure which application to allow.I run the application using a shortcut to a .bat file . The bat file contains just the following line : The code on which the application fails is : Is it possible to allow the application through the firewall ? Do I allow dotnet.exe , or the .bat file , or the .dll file , or is there an alternate way of doing this ? Thanks in advance for any help ! <code> dotnet `` C : \path\my-application.dll '' FtpWebRequest request = ( FtpWebRequest ) FtpWebRequest.Create ( ftpServerUri ) ; request.UseBinary = true ; request.Credentials = new NetworkCredential ( ftpUser , ftpPsw ) ; request.Method = WebRequestMethods.Ftp.ListDirectory ; request.Proxy = null ; request.KeepAlive = false ; request.UsePassive = false ; // hangs here forever unless Windows Firewall is turned offFtpWebResponse response = ( FtpWebResponse ) await request.GetResponseAsync ( ) ; | How do I allow a .NET Core console app FTP connection through Windows Firewall ? |
C_sharp : First , an example of something that works as expected : ( all code was executed in VS2008 immediate window ) So far so good . Now let 's try on an object where the interface is inherited via a base type : In the immediate window : No surprises here either . How come the following code does n't show any interfaces then : How can all of the above be true at the same time ? ( edit : added wcfChannel is ICommunicationObject above , which is at this time unexplained by the answer that explains how wcfChannel is IMyServiceApi is true . ) <code> 25 is IComparable > > true25.GetType ( ) .GetInterfaces ( ) > > { System.Type [ 5 ] } > > [ 0 ] : { Name = `` IComparable '' FullName = ... > > [ 1 ] : { Name = `` IFormattable '' FullName = ... > > ... class TestBase : IComparable { public int CompareTo ( object obj ) { throw new NotImplementedException ( ) ; } } class TheTest : TestBase { } ( new TheTest ( ) ) is IComparable > > true ( new TheTest ( ) ) .GetType ( ) .GetInterfaces ( ) > > { System.Type [ 1 ] } > > [ 0 ] : { Name = `` IComparable '' FullName = `` System.IComparable '' } wcfChannel = ChannelFactory < IMyServiceApi > .CreateChannel ( binding , endpointAddress ) ; wcfChannel is IMyServiceApi & & wcfChannel is ICommunicationObject > > truetypeof ( IMyServiceApi ) .IsInterface & & typeof ( ICommunicationObject ) .IsInterface > > truewcfChannel.GetType ( ) .GetInterfaces ( ) > > { System.Type [ 0 ] } | Why does this object 's type show no interfaces via reflection , despite implementing at least two ? |
C_sharp : I am teaching myself C # ( I do n't know much yet ) . In this simple example : Intuitively I understand why the GetType ( ) method would throw an exception . The instance n is null which would explain that but , why do n't I get an exception for the same reason when using n.GetHashCode ( ) and ToString ( ) ? Thank you for your help , John . <code> bool ? n = null ; Console.WriteLine ( `` n = { 0 } '' , n ) ; Console.WriteLine ( `` n.ToString ( ) = { 0 } '' , n.ToString ( ) ) ; Console.WriteLine ( `` n.GetHashCode ( ) = { 0 } '' , n.GetHashCode ( ) ) ; // this next statement causes a run time exceptionConsole.WriteLine ( `` n.GetType ( ) = { 0 } '' , n.GetType ( ) ) ; | why does n.GetHashCode ( ) work but n.GetType ( ) throws and exception ? |
C_sharp : I just saw this question : Is it safe to use static methods on File class in C # ? . To summarize OP has an IOException because file is in use in this ASP.NET code snippet : My first thought has been it 's a simple concurrent access issue because of multiple ASP.NET overlapping requests . Something I 'd solve centralizing I/O into a synchronized thread-safe class ( or dropping files in favor of something else ) . I read both answers and when I was about to downvote one of them then I saw who those users are and I thought what the h* and stopped.I 'll cite them both ( then please refer to original answers for more context ) .For this OP paragraph : I am guessing that the file read operation sometimes is not closing the file before the write operation happens [ ... ] An answer says : Correct . File systems do not support atomic updates well [ ... ] Using FileStream does not help [ ... ] File has no magic inside . It just uses FileStream wrapped for your convenience.However I do n't see any expectancy for an atomic operation ( read + subsequent write ) and parallel ( because of partially overlapping multi-threaded requests ) may cause concurrent accesses . Even an atomic I/O operation ( read + write ) will have exactly same issue . OK FileStream may be asynchronous but it 's not how File.ReadAllText ( ) and File.WriteAllText ( ) use it.The other answer made me much more perplex , it says : Although according to the documentation the file handle is guaranteed to be closed by this method , even if exceptions are raised , the timing of the closing is not guaranteed to happen before the method returns : the closing could be done asynchronously.What ? MSDN says method will open , read and close file ( also in case of exceptions ) . Is it ever possible that such method will close file asynchronously ? Will OS defer CloseHandle ( ) ? In which cases ? Why ? In short : is it just a misunderstanding or CloseHandle ( ) is asynchronous ? I 'm missing something extremely important ? <code> var text= File.ReadAllText ( `` path-to-file.txt '' ) ; // Do something with textFile.WriteAllText ( `` path-to-file.txt '' ) ; | Is `` sequential '' file I/O with System.IO.File helper methods safe ? |
C_sharp : Hi I am trying to send a simple HTTP message from Flex to C # server , but it seems that I am getting tow calls , first is the real one and the second is an empty one.Why is that and how can I handle it ? This is my C # code : this is the SocketHandler : And this is my flex code : I am always getting 2 calls.The line : called twice.What am I missing ? Edit 1 : I can tell you for sure that the second call is empty , it 's not even seen in chrome JavaScript console , it 's like flex opening a connection , and waiting for some response or I do n't know what ... but it sending no data.Edit 2 : I been trying to send a true HTTP response a notice another thing , the second call is coming without waiting for the first call , if I am putting the response thread to short sleep ( 100 milliseconds in my test ) then I am getting the second call before I been able to response for the first one.P.SUsing Flex 4.6 , Visual Studio 2010 <code> TcpListener listener = new TcpListener ( IPAddress.Any , 9400 ) ; listener.Start ( ) ; Console.WriteLine ( `` Server started '' ) ; Socket client ; while ( true ) { client = listener.AcceptSocket ( ) ; // client.Available is an expensive call so it 's just for testing Console.WriteLine ( `` Client accepted `` + client.Connected + `` `` + client.Available ) ; SocketHandler handler = new SocketHandler ( ) ; ThreadPool.QueueUserWorkItem ( handler.handleSocket , client ) ; } public void handleSocket ( object socketObjeck ) { try { socket = ( Socket ) socketObjeck ; byte [ ] buffer = new byte [ 1024 ] ; SocketSettings.setSocket ( socket ) ; //blocker ... try { socket.Receive ( buffer ) ; } catch ( Exception e ) { Console.WriteLine ( `` Error\nFaild reading from socket\n '' + e.Message ) ; socket.Close ( ) ; return ; } parseData ( buffer ) ; socket.Close ( 3 ) ; } catch ( Exception e ) { Console.WriteLine ( `` Error\nError \n '' + e.Message + `` \n '' + e.StackTrace ) ; } } var request : URLRequest = new URLRequest ( ) ; request.data = `` Hello from flex '' ; request.url = URL ; request.method = URLRequestMethod.POST ; loader.load ( request ) ; Console.WriteLine ( `` Client accepted `` + client.Connected + `` `` + client.Available ) ; | Handle http fired by Flex in C # server |
C_sharp : I am writing a small logger and I want to open the log file once , keep writing reactively as log messages arrive , and dispose of everything on program termination.I am not sure how I can keep the FileStream open and reactively write the messages as they arrive.I would like to update the design from my previous solution where I had a ConcurrentQueue acting as a buffer , and a loop inside the using statements that consumed the queue.Specifically , I want to simultaneously take advantage of the using statement construct , so I do n't have to explicitly close the stream and writer , and of the reactive , loopless programming style . Currently I only know how to use one of these constructs at once : either the using/loop combination , or the explicit-stream-close/reactive combination.Here 's my code : <code> BufferBlock < LogEntry > _buffer = new BufferBlock < LogEntry > ( ) ; // CONSTRUCTOR public DefaultLogger ( string folder ) { var filePath = Path.Combine ( folder , $ '' { DateTime.Now.ToString ( `` yyyy.MM.dd '' ) } .log '' ) ; _cancellation = new CancellationTokenSource ( ) ; var observable = _buffer.AsObservable ( ) ; using ( var stream = File.Create ( _filePath ) ) using ( var writer = new StreamWriter ( stream ) ) using ( var subscription = observable.Subscribe ( entry = > writer.Write ( GetFormattedString ( entry ) ) ) ) { while ( ! _cancellation.IsCancellationRequested ) { // what do I do here ? } } } | Write to open FileStream using reactive programming |
C_sharp : I was looking through some code today and saw something like the following : When I asked why it was so , since Resharper confirmed that all the casts are redundant , I was told that the Designer done it that way and they had copied that.I had a look and sure enough the Designer generates code the same as above when setting a property to a custom colour.Does anyone know why the Designer would do this ? It does n't appear to make sense on the face of it , unless I am missing something ? <code> var colour = Color.FromArgb ( ( ( int ) ( ( ( byte ) ( 227 ) ) ) ) , ( ( int ) ( ( ( byte ) ( 213 ) ) ) ) , ( ( int ) ( ( ( byte ) ( 193 ) ) ) ) ) ; | Why does the Windows Forms Designer cast int to byte then back to int for FromArgb ? |
C_sharp : I have a simple loop for : I would like to do DoSomething ( 1 ) in processor thread 1 , DoSomething ( 2 ) in thread 2 ... DoSomething ( 8 ) in thread 8 . Is it possible ? If yes than how ? Thanks for answers . <code> for ( int i = 1 ; i < = 8 ; i++ ) { DoSomething ( i ) ; } int nopt = 8 ; //number of processor threads | Using Multi-core ( -thread ) processor for FOR loop |
C_sharp : So I just came across this very odd scenario and was wondering if anyone might know what the problem is . I have the following EF Linq query.When I inspect that query in the debugger it shows the following SQLIf I run that in SQL Server Management Studio substituding @ p__linq__0 with the value of dashboardId . I get these results.However the results from iterating the EF query are as follows.Notice that the fifth row has a ParentId of NULL instead of 5 . This is how I worked around the problem.The odd thing here is that this results in a IGrouping with a Key value of 5 , but the ParentId of the single object in that group is null.I 'm attempting to creat a lookup from that query and wanted to just doBut since the actually ParentId does n't seem to always have the correct value and I have to do the group by I end up having to do the followingTo make matters even stranger , if I remove the AsEnumerable from the end of the query before doing the SelectMany and ToLookup it will still result in the entity that should have a ParentId of 5 being grouped under null.Is this some type of bug with EF or am I just missing something here ? BTW I 'm using EF 6.1.3 . <code> var hierarchies = ( from hierarchy in ctx.PolygonHierarchyViews where hierarchy.DashboardId == dashboardId select hierarchy ) ; SELECT [ Extent1 ] . [ DashboardId ] AS [ DashboardId ] , [ Extent1 ] . [ CurrentId ] AS [ CurrentId ] , [ Extent1 ] . [ PolygonTypeId ] AS [ PolygonTypeId ] , [ Extent1 ] . [ DisplayName ] AS [ DisplayName ] , [ Extent1 ] . [ ParentId ] AS [ ParentId ] FROM [ dbo ] . [ PolygonHierarchyView ] AS [ Extent1 ] WHERE [ Extent1 ] . [ DashboardId ] = @ p__linq__0 DashboardId CurrentId Type Name ParentId4 5 1 Region NULL4 6 2 Market NULL4 7 3 SubMarket 64 8 4 ZipCode 74 6 2 Market 54 7 3 SubMarket 64 8 4 ZipCode 7 DashboardId CurrentId Type Name ParentId4 5 1 Region NULL4 6 2 Market NULL4 7 3 SubMarket 64 8 4 ZipCode 74 6 2 Market NULL4 7 3 SubMarket 64 8 4 ZipCode 7 var hierarchies = ( from hierarchy in ctx.PolygonHierarchyViews where hierarchy.DashboardId == dashboardId group hierarchy by hierarchy.ParentId into grp select grp ) .AsEnumerable ( ) ; var lookup = hierarchies.ToLookup ( h = > h.ParentId ) ; var lookup = hierarchies.SelectMany ( x = > x.Select ( y = > new { x.Key , View = y } ) ) .ToLookup ( h = > h.Key , h = > h.View ) ; | EF returning different values than query |
C_sharp : I am going to create a `` long '' ( Int64 ) surrogate which has to be atomic , so its copy in a concurrent application will be inherently safe . I can not use an Int32 because it spans too short as range.I know that the atomicity should be guarantee as long the involved data can fit in a double-word ( 32 bits ) . No matter whether the OS is 32 or 64 bits.Now , consider the following `` long '' surrogate ... NOTE : I 've omitted several methods because I do n't need them . In this case I need only the basic conversion to/from a real long.Well , it seems working perfectly as I expect.Here is a small test : The SizeOf function yields always 4 bytes as the size of my surrogate . Does this value guarantees the atomicity of a copy SafeLong-to-SafeLong , or the 4 bytes should be interpreted as `` real physical double-word '' ? No matter the NON-atomicity of the long < -- > SafeLong : it will be enclosed in a safe context.Thanks a lot in advance . <code> public struct SafeLong : IConvertible { public SafeLong ( long value ) { unchecked { var arg = ( ulong ) value ; this._data = new byte [ ] { ( byte ) arg , ( byte ) ( arg > > 8 ) , ( byte ) ( arg > > 16 ) , ( byte ) ( arg > > 24 ) , ( byte ) ( arg > > 32 ) , ( byte ) ( arg > > 40 ) , ( byte ) ( arg > > 48 ) , ( byte ) ( arg > > 56 ) , } ; } } private byte [ ] _data ; private long Value { get { unchecked { var lo = this._data [ 0 ] | this._data [ 1 ] < < 8 | this._data [ 2 ] < < 16 | this._data [ 3 ] < < 24 ; var hi = this._data [ 4 ] | this._data [ 5 ] < < 8 | this._data [ 6 ] < < 16 | this._data [ 7 ] < < 24 ; return ( long ) ( ( uint ) lo | ( ulong ) ( uint ) hi < < 32 ) ; } } } public static implicit operator long ( SafeLong value ) { return value.Value ; // implicit conversion } public static explicit operator SafeLong ( long value ) { return new SafeLong ( value ) ; // explicit conversion } # region IConvertible implementation public TypeCode GetTypeCode ( ) { return Type.GetTypeCode ( typeof ( SafeLong ) ) ; } public object ToType ( Type conversionType , IFormatProvider provider ) { return Convert.ChangeType ( this.Value , conversionType ) ; } public long ToInt64 ( IFormatProvider provider ) { return this.Value ; } // ... OMISSIS ( not implemented ) ... # endregion } class Program { static void Main ( string [ ] args ) { var sla = ( SafeLong ) 12345678987654321L ; var la = ( long ) sla ; Console.WriteLine ( la ) ; var slb = ( SafeLong ) ( -998877665544332211L ) ; var lb = ( long ) slb ; Console.WriteLine ( lb ) ; Console.WriteLine ( Marshal.SizeOf ( typeof ( SafeLong ) ) ) ; Console.WriteLine ( Marshal.SizeOf ( sla ) ) ; Console.WriteLine ( Marshal.SizeOf ( slb ) ) ; long lc = new SafeLong ( 556677 ) ; var slc = slb ; Console.WriteLine ( slc ) ; slc = ( SafeLong ) lc ; Console.WriteLine ( slc ) ; Console.WriteLine ( slb ) ; Console.Write ( `` Press any key ... '' ) ; Console.ReadKey ( ) ; } } | Is it atomic this `` Int64 '' surrogate ? |
C_sharp : We have an application running with .Net Framework 4.6.1 that access to Linkedin calling to the endpoint : It was working until past 2020/07/14 after that it started failing in all of our environments with the following error : An error occurred while sending the request.The underlying connection was closed : An unexpected error > occurred on a send.Unable to read data from the transport connection : An existing connection was forcibly > closed by the remote host.An existing connection was forcibly closed by the remote hostWe 've been running some tests and we found that we can reproduce the error with the following command in PowerShell : After some research , we realized that we can force PowerShell to use TLS 1.2 using the following command : But it did n't work in our IIS Servers . In other servers that do n't have IIS installed the command works and we can access Linkedin URL properly.We also tried to do the equivalent in C # with the same results : Seems that the error is related with Tls12 so we started taking a look with Wireshark and we found that the connection is reset during the handshake after the HELLO : The relevant part of the hello is : We also have another workflow where we use Twitter which , like Linkedin , only allows TLS 1.2 and it is working properly . So , besides our research , we are not really sure that the problem came from TLS.This application is running under a Windows Server 2012 R2 and an IIS 8 . And no updates have been applied during the last weeks that can affect this behavior.Does anybody know what could be the cause to this issue ? <code> https : //www.linkedin.com/oauth/v2/accessToken Invoke-WebRequest -Uri https : //www.linkedin.com [ Net.ServicePointManager ] : :SecurityProtocol = [ Net.SecurityProtocolType ] : :Tls12 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 ; Handshake Protocol : Client Hello Handshake Type : Client Hello ( 1 ) Length : 153 Version : TLS 1.2 ( 0x0303 ) Random : 5f1536566faf9700973045f3e502909a269ec62f2df23243… Session ID Length : 0 Cipher Suites Length : 32 Cipher Suites ( 16 suites ) Cipher Suite : TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 ( 0xc028 ) Cipher Suite : TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 ( 0xc027 ) Cipher Suite : TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ( 0xc014 ) Cipher Suite : TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA ( 0xc013 ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 ( 0xc02c ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ( 0xc02b ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 ( 0xc024 ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 ( 0xc023 ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ( 0xc00a ) Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA ( 0xc009 ) Cipher Suite : TLS_RSA_WITH_AES_256_GCM_SHA384 ( 0x009d ) Cipher Suite : TLS_RSA_WITH_AES_128_GCM_SHA256 ( 0x009c ) Cipher Suite : TLS_RSA_WITH_AES_256_CBC_SHA256 ( 0x003d ) Cipher Suite : TLS_RSA_WITH_AES_128_CBC_SHA256 ( 0x003c ) Cipher Suite : TLS_RSA_WITH_AES_256_CBC_SHA ( 0x0035 ) Cipher Suite : TLS_RSA_WITH_AES_128_CBC_SHA ( 0x002f ) Compression Methods Length : 1 Compression Methods ( 1 method ) Extensions Length : 80 Extension : server_name ( len=21 ) Extension : supported_groups ( len=8 ) Extension : ec_point_formats ( len=2 ) Extension : signature_algorithms ( len=20 ) Extension : session_ticket ( len=0 ) Extension : extended_master_secret ( len=0 ) Extension : renegotiation_info ( len=1 ) | Underlying connection was closed with linkedin |
C_sharp : While writing some code handling assemblies in C # I noticed inconsistencies in field values of Assembly object ( example of System assembly ) : but when accessing CultureName field of AssemblyName object directly , its value is an empty string : When I run the same test on Linux ( mono 3.99 ) I got another result : Why does .NET behaves that way ? I could n't find any information on msdn regarding default value of CultureName field in AssemblyName class or meaning of anempty string . Does an empty string always refers to `` neutral '' culture name ? <code> > typeof ( string ) .Assembly.FullName '' mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' > typeof ( string ) .Assembly.GetName ( ) .CultureName '' '' > typeof ( string ) .Assembly.GetName ( ) .CultureName '' neutral '' | CultureName of System assembly in .NET |
C_sharp : i wanted to try the following code : but it occured runtime error occasionly in following situation i. m.terms == null ii . m.terms ! = null , but m.terms [ 0 ] does not intialized . iii . m.terms ! = null , and m.terms [ 0 ] has been exist but m.terms [ 0 ] .label does not initialized ... .so i did modify it to like this : is it the best way ? <code> //all arrays are List < T > type.if ( m.terms [ 0 ] ! = null & & m.terms [ 0 ] .labels ! = null & & m.terms [ 0 ] .labels [ 0 ] .title == `` Part-of-speech '' ) { result = true ; } if ( m.terms [ 0 ] ! = null ) { if ( m.terms [ 0 ] .labels ! = null ) { if ( m.terms [ 0 ] .labels [ 0 ] .title == `` Part-of-speech '' ) { result = true ; } } } | more short code about if statement |
C_sharp : I have an array of tasks and I am awaiting them with Task.WhenAll . My tasks are failing frequently , in which case I inform the user with a message box so that she can try again . My problem is that reporting the error is delayed until all tasks are completed . Instead I would like to inform the user as soon as the first task has thrown an exception . In other words I want a version of Task.WhenAll that fails fast . Since no such build-in method exists I tried to make my own , but my implementation does not behave the way I want . Here is what I came up with : This generally throws faster than the native Task.WhenAll , but usually not fast enough . A faulted task # 2 will not be observed before the completion of task # 1 . How can I improve it so that it fails as fast as possible ? Update : Regarding cancellation , it is not in my requirements right now , but lets say that for consistency the first cancelled task should stop the awaiting immediately . In this case the combining task returned from WhenAllFailFast should have Status == TaskStatus.Canceled.Clarification : Τhe cancellation scenario is about the user clicking a Cancel button to stop the tasks from completing . It is not about cancelling automatically the incomplete tasks in case of an exception . <code> public static async Task < TResult [ ] > WhenAllFailFast < TResult > ( params Task < TResult > [ ] tasks ) { foreach ( var task in tasks ) { await task.ConfigureAwait ( false ) ; } return await Task.WhenAll ( tasks ) .ConfigureAwait ( false ) ; } | How can I await an array of tasks and stop waiting on first exception ? |
C_sharp : I need to calculate PI with predefined precision using this formula : So I ended up with this solution.So this works correct , but I faced the problem with efficiency . It 's very slow with precision values 8 and higher.Is there a better ( and faster ! ) way to calculate PI using that formula ? <code> private static double CalculatePIWithPrecision ( int presicion ) { if ( presicion == 0 ) { return PI_ZERO_PRECISION ; } double sum = 0 ; double numberOfSumElements = Math.Pow ( 10 , presicion + 2 ) ; for ( double i = 1 ; i < numberOfSumElements ; i++ ) { sum += 1 / ( i * i ) ; } double pi = Math.Sqrt ( sum * 6 ) ; return pi ; } | Calculate PI using sum of inverse squares |
C_sharp : I 'm trying to create an Rx operator that seems pretty useful , but I 've suprisingly not found any questions on Stackoverflow that match precisely . I 'd like to create a variation on Throttle that lets values through immediately if there 's been a period of inactivity . My imagined use case is something like this : I have a dropdown that kicks off a web request when the value is changed . If the user holds down the arrow key and cycles rapidly through the values , I do n't want to kick off a request for each value . But if I throttle the stream then the user has to wait out the throttle duration every time they just select a value from the dropdown in the normal manner.So whereas a normal Throttle looks like this : I want to create ThrottleSubsequent that look like this : Note that marbles 1 , 2 , and 6 are passed through without delay because they each follow a period of inactivity.My attempt at this looks like the following : This seems to work , but I 'm having a difficult time reasoning about this , and I get the feeling there are some edge cases here where things might get screwy with duplicate values or something . I 'd like to get some feedback from more experienced Rx-ers as to whether or not this code is correct , and/or whether there is a more idiomatic way of doing this . <code> public static IObservable < TSource > ThrottleSubsequent < TSource > ( this IObservable < TSource > source , TimeSpan dueTime , IScheduler scheduler ) { // Create a timer that resets with each new source value var cooldownTimer = source .Select ( x = > Observable.Interval ( dueTime , scheduler ) ) // Each source value becomes a new timer .Switch ( ) ; // Switch to the most recent timer var cooldownWindow = source.Window ( ( ) = > cooldownTimer ) ; // Pass along the first value of each cooldown window immediately var firstAfterCooldown = cooldownWindow.SelectMany ( o = > o.Take ( 1 ) ) ; // Throttle the rest of the values var throttledRest = cooldownWindow .SelectMany ( o = > o.Skip ( 1 ) ) .Throttle ( dueTime , scheduler ) ; return Observable.Merge ( firstAfterCooldown , throttledRest ) ; } | Custom Rx operator for throttling only when there 's a been a recent value |
C_sharp : In the following I get a compile time error that says `` Use of unassigned local variable 'match ' '' if I just enter string match ; but it works when I use string match = null ; So what is the difference and in general , if a string is not being assigned a value right away should I be assigning to null like this ? <code> string question = `` Why do I need to assign to null '' ; char [ ] delim = { ' ' } ; string [ ] strArr = question.Split ( delim ) ; //Throws Errorstring match ; //No Error//string match = null ; foreach ( string s in strArr ) { if ( s == `` Why '' ) { match = `` Why '' ; } } Console.WriteLine ( match ) ; | What does assigning variable to null do ? |
C_sharp : I am using VS2010 SP1.After creating a demo project for C # Form application , my solution structure has the following informationHere is the question , I can see the Form1 is a partial class . However , how does the compiler know where to find the another part of it ? *In other words , is there a binding between the file Form1.cs and Form1.Designer.cs ? * Here , as you can see , the other part is defined inside Form1.Designer.cs . I assume there are hints out there so that the compiler can quickly find all implementation code for a partial class . Please correct me.Thank you <code> Form1.cs Form1.Designer.cs Form1.resx// File Form1.csnamespace WinFormApp { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } } } // File Form1.Designer.csnamespace WinFormApp { partial class Form1 { private void InitializeComponent ( ) { ... } ... } } | C # - How does the compiler find the another part of the partial class ? |
C_sharp : Below is a simple program that with a small change , makes a significant performance impact and I do n't understand why.What the program does is not really relevant , but it calculates PI in a very convoluted way by counting collisions between two object of different mass and a wall . What I noticed as I was changing the code around was a quite large variance in performance.The rows in question are the commented ones which are mathematically equivalent . Using the slow version makes the entire program take roughly twice as long as using the fast version . My intuition says that because the fast version has 7 operations compared to 4 operations of the slow one , the slow one should be faster , but it is not.I disassembled the program using .NET Reflector which shows that they are mostly equal , as expected , except for the part shown below . The code before and after an identicalThis also shows that more code is executing with the fast version which also would lead me to expect it to be slower . The only guess I have right now is that the slow version causes more cache misses , but I do n't know how to measure that ( a guide would be welcome ) . Other than that I am at a loss.EDIT 1.As per the request of @ EricLippert here is the disassembly from the JIT for the inner while loop where the difference is.EDIT 2.Solved how to break in the release program and updated the disassembly so now there seems to be some difference . I got these results by running the release version , stopping the program in the same function with a ReadKey , attaching the debugger , making the program continue execution , breaking on the next row , going into disassembly window ( ctrl+alt+d ) EDIT 3.Change the code to an updated example base on all the suggestions . <code> int iterations = 0 ; for ( int i = 4 ; i < 9 ; i++ ) { Stopwatch s = Stopwatch.StartNew ( ) ; double ms = 1.0 ; double mL = Math.Pow ( 100.0 , i ) ; double uL = 1.0 ; double us = 0.0 ; double msmLInv = 1d / ( ms + mL ) ; long collisions = 0 ; while ( ! ( uL < 0 & & us < = 0 & & uL < = us ) ) { Debug.Assert ( ++iterations > 0 ) ; ++collisions ; double vs = ( 2 * mL * uL + us * ( ms - mL ) ) * msmLInv ; //double vL = ( 2 * ms * us - uL * ( ms - mL ) ) * msmLInv ; //fast double vL = uL + ( us - vs ) / mL ; //slow Debug.Assert ( Math.Abs ( ( ( 2 * ms * us - uL * ( ms - mL ) ) * msmLInv ) - ( uL + ( us - vs ) / mL ) ) < 0.001d ) ; //checks equality between fast and slow if ( vs > 0 ) { ++collisions ; vs = -vs ; } us = vs ; uL = vL ; } s.Stop ( ) ; Debug.Assert ( collisions.ToString ( ) == `` 314159265359 '' .Substring ( 0 , i + 1 ) ) ; //check the correctness Console.WriteLine ( $ '' i : { i } , T : { s.ElapsedMilliseconds / 1000f } , PI : { collisions } '' ) ; } Debug.Assert ( iterations == 174531180 ) ; //check that we dont skip loopsConsole.Write ( `` Waiting ... '' ) ; Console.ReadKey ( ) ; //slowldloc.s uLldloc.2 ldloc.s usldloc.s vssub mul ldloc.3 div add //fastldc.r8 2ldloc.2 mul ldloc.s usmul ldloc.s uLldloc.2 ldloc.3 sub mul sub ldloc.2 ldloc.3 add div //slow 78 : 79 : vs = ( 2 * mL * uL + us * ( ms - mL ) ) / ( ms + mL ) ; 00C10530 call CA9AD013 00C10535 fdiv st , st ( 3 ) 00C10537 faddp st ( 2 ) , st 80 : 81 : //double vL = ( 2 * ms * us - uL * ( ms - mL ) ) / ( ms + mL ) ; //fast 82 : double vL = uL + ms * ( us - vs ) / mL ; //slow00C10539 fldz 00C1053B fcomip st , st ( 1 ) 00C1053D jp 00C10549 00C1053F jae 00C10549 00C10541 add ebx,1 00C10544 adc edi,0 00C10547 fchs 00C10549 fld st ( 1 ) 73 : 74 : while ( ! ( uL < 0 & & us < = 0 & & uL < = us ) ) 00C1054B fldz 00C1054D fcomip st , st ( 3 ) 00C1054F fstp st ( 2 ) 00C10551 jp 00C10508 00C10553 jbe 00C10508 00C10555 fldz 00C10557 fcomip st , st ( 1 ) 00C10559 jp 00C10508 00C1055B jb 00C10508 00C1055D fxch st ( 1 ) 00C1055F fcomi st , st ( 1 ) 00C10561 jnp 00C10567 00C10563 fxch st ( 1 ) 00C10565 jmp 00C10508 00C10567 jbe 00C1056D 00C10569 fxch st ( 1 ) 00C1056B jmp 00C10508 00C1056D fstp st ( 1 ) 00C1056F fstp st ( 0 ) 00C10571 fstp st ( 0 ) 92 : } 93 : 94 : s.Stop ( ) ; 00C10573 mov ecx , esi 00C10575 call 71880260 95 : 96 : Console.WriteLine ( $ '' i : { i } , T : { s.ElapsedMilliseconds / 1000f } , PI : { collisions } '' ) ; 00C1057A mov ecx,725B0994h 00C1057F call 00B930C8 00C10584 mov edx , eax 00C10586 mov eax , dword ptr [ ebp-14h ] 00C10589 mov dword ptr [ edx+4 ] , eax 00C1058C mov dword ptr [ ebp-34h ] , edx 00C1058F mov ecx,725F3778h 00C10594 call 00B930C8 00C10599 mov dword ptr [ ebp-38h ] , eax 00C1059C mov ecx,725F2C10h 00C105A1 call 00B930C8 00C105A6 mov dword ptr [ ebp-3Ch ] , eax 00C105A9 mov ecx , esi 00C105AB call 71835820 00C105B0 push edx 00C105B1 push eax 00C105B2 push 0 00C105B4 push 2710h 00C105B9 call 736071A0 00C105BE mov dword ptr [ ebp-48h ] , eax 00C105C1 mov dword ptr [ ebp-44h ] , edx 00C105C4 fild qword ptr [ ebp-48h ] 00C105C7 fstp dword ptr [ ebp-40h ] 00C105CA fld dword ptr [ ebp-40h ] 00C105CD fdiv dword ptr ds : [ 0C10678h ] 00C105D3 mov eax , dword ptr [ ebp-38h ] 00C105D6 fstp dword ptr [ eax+4 ] 00C105D9 mov edx , dword ptr [ ebp-38h ] 00C105DC mov eax , dword ptr [ ebp-3Ch ] 00C105DF mov dword ptr [ eax+4 ] , ebx 00C105E2 mov dword ptr [ eax+8 ] , edi 00C105E5 mov esi , dword ptr [ ebp-3Ch ] 00C105E8 lea edi , [ ebp-30h ] 00C105EB xorps xmm0 , xmm0 00C105EE movq mmword ptr [ edi ] , xmm0 00C105F2 movq mmword ptr [ edi+8 ] , xmm0 00C105F7 push edx 00C105F8 push esi 00C105F9 lea ecx , [ ebp-30h ] 00C105FC mov edx , dword ptr [ ebp-34h ] 00C105FF call 724A2ED4 00C10604 lea eax , [ ebp-30h ] 00C10607 push dword ptr [ eax+0Ch ] 00C1060A push dword ptr [ eax+8 ] 00C1060D push dword ptr [ eax+4 ] 00C10610 push dword ptr [ eax ] 00C10612 mov edx , dword ptr ds : [ 3832310h ] 00C10618 xor ecx , ecx 00C1061A call 72497A00 00C1061F mov ecx , eax 00C10621 call 72571934 61 : for ( int i = 4 ; i < 9 ; i++ ) 00C10626 inc dword ptr [ ebp-14h ] 00C10629 cmp dword ptr [ ebp-14h ] ,9 00C1062D jl 00C10496 97 : } 98 : 99 : Console.WriteLine ( loops ) ; 00C10633 mov ecx , dword ptr [ ebp-10h ] 00C10636 call 72C583FC 100 : Console.Write ( `` Waiting ... '' ) ; 00C1063B mov ecx , dword ptr ds : [ 3832314h ] 00C10641 call 724C67F0 00C10646 lea ecx , [ ebp-20h ] 00C10649 xor edx , edx 00C1064B call 72C57984 00C10650 lea esp , [ ebp-0Ch ] 00C10653 pop ebx 00C10654 pop esi 00C10655 pop edi 00C10656 pop ebp 00C10657 ret //fast 80 : 81 : double vL = ( 2 * ms * us - uL * ( ms - mL ) ) / ( ms + mL ) ; //fast02FD0550 or al,83h 80 : 81 : double vL = ( 2 * ms * us - uL * ( ms - mL ) ) / ( ms + mL ) ; //fast02FD0552 ret 02FD0553 add dword ptr [ ebx-3626FF29h ] , eax 02FD0559 fchs 02FD055B fxch st ( 1 ) 02FD055D fld st ( 0 ) 73 : 74 : while ( ! ( uL < 0 & & us < = 0 & & uL < = us ) ) 02FD055F fldz 02FD0561 fcomip st , st ( 2 ) 02FD0563 fstp st ( 1 ) 02FD0565 jnp 02FD056B 02FD0567 fxch st ( 1 ) 02FD0569 jmp 02FD050B 02FD056B ja 02FD0571 02FD056D fxch st ( 1 ) 02FD056F jmp 02FD050B 02FD0571 fldz 02FD0573 fcomip st , st ( 2 ) 02FD0575 jnp 02FD057B 02FD0577 fxch st ( 1 ) 02FD0579 jmp 02FD050B 02FD057B jae 02FD0581 02FD057D fxch st ( 1 ) 02FD057F jmp 02FD050B 02FD0581 fcomi st , st ( 1 ) 02FD0583 jnp 02FD0589 02FD0585 fxch st ( 1 ) 02FD0587 jmp 02FD050B 02FD0589 jbe 02FD0592 02FD058B fxch st ( 1 ) 02FD058D jmp 02FD050B 02FD0592 fstp st ( 1 ) 02FD0594 fstp st ( 0 ) 92 : } 93 : 94 : s.Stop ( ) ; 02FD0596 mov ecx , esi 02FD0598 call 71880260 95 : 96 : Console.WriteLine ( $ '' i : { i } , T : { s.ElapsedMilliseconds / 1000f } , PI : { collisions } '' ) ; 02FD059D mov ecx,725B0994h 02FD05A2 call 013830C8 02FD05A7 mov edx , eax 02FD05A9 mov eax , dword ptr [ ebp-14h ] 02FD05AC mov dword ptr [ edx+4 ] , eax 02FD05AF mov dword ptr [ ebp-3Ch ] , edx 02FD05B2 mov ecx,725F3778h 02FD05B7 call 013830C8 02FD05BC mov dword ptr [ ebp-40h ] , eax 02FD05BF mov ecx,725F2C10h 02FD05C4 call 013830C8 02FD05C9 mov dword ptr [ ebp-44h ] , eax 02FD05CC mov ecx , esi 02FD05CE call 71835820 02FD05D3 push edx 02FD05D4 push eax 02FD05D5 push 0 02FD05D7 push 2710h 02FD05DC call 736071A0 02FD05E1 mov dword ptr [ ebp-50h ] , eax 02FD05E4 mov dword ptr [ ebp-4Ch ] , edx 02FD05E7 fild qword ptr [ ebp-50h ] 02FD05EA fstp dword ptr [ ebp-48h ] 02FD05ED fld dword ptr [ ebp-48h ] 02FD05F0 fdiv dword ptr ds : [ 2FD06A8h ] 02FD05F6 mov eax , dword ptr [ ebp-40h ] 02FD05F9 fstp dword ptr [ eax+4 ] 02FD05FC mov edx , dword ptr [ ebp-40h ] 02FD05FF mov eax , dword ptr [ ebp-44h ] 02FD0602 mov dword ptr [ eax+4 ] , ebx 02FD0605 mov dword ptr [ eax+8 ] , edi 02FD0608 mov esi , dword ptr [ ebp-44h ] 02FD060B lea edi , [ ebp-38h ] 02FD060E xorps xmm0 , xmm0 02FD0611 movq mmword ptr [ edi ] , xmm0 02FD0615 movq mmword ptr [ edi+8 ] , xmm0 02FD061A push edx 02FD061B push esi 02FD061C lea ecx , [ ebp-38h ] 02FD061F mov edx , dword ptr [ ebp-3Ch ] 02FD0622 call 724A2ED4 02FD0627 lea eax , [ ebp-38h ] 02FD062A push dword ptr [ eax+0Ch ] 02FD062D push dword ptr [ eax+8 ] 02FD0630 push dword ptr [ eax+4 ] 02FD0633 push dword ptr [ eax ] 02FD0635 mov edx , dword ptr ds : [ 4142310h ] 02FD063B xor ecx , ecx 02FD063D call 72497A00 02FD0642 mov ecx , eax 02FD0644 call 72571934 61 : for ( int i = 4 ; i < 9 ; i++ ) 02FD0649 inc dword ptr [ ebp-14h ] 02FD064C cmp dword ptr [ ebp-14h ] ,9 02FD0650 jl 02FD0496 97 : } 98 : 99 : Console.WriteLine ( loops ) ; 02FD0656 mov ecx , dword ptr [ ebp-10h ] 02FD0659 call 72C583FC 100 : Console.Write ( `` Waiting ... '' ) ; 02FD065E mov ecx , dword ptr ds : [ 4142314h ] 02FD0664 call 724C67F0 02FD0669 lea ecx , [ ebp-28h ] 02FD066C xor edx , edx 02FD066E call 72C57984 02FD0673 lea esp , [ ebp-0Ch ] 02FD0676 pop ebx 02FD0677 pop esi 02FD0678 pop edi 02FD0679 pop ebp 02FD067A ret | Surprisingly different performance of simple C # program |
C_sharp : While I am testing post increment operator in a simple console application , I realized that I did not understand full concept . It seems weird to me : The output has been false . I have expected that it would be true . AFAIK , at line 2 , because of the post increment , compiler does comparison and assigned b to true , after i incremented by one . But obviously I am wrong.After that I modify the code like that : This time output has been true . What did change from first sample ? <code> int i = 0 ; bool b = i++ == i ; Console.WriteLine ( b ) ; int i = 0 ; bool b = i == i++ ; Console.WriteLine ( b ) ; | C # Post Increment |
C_sharp : I have a need to keep track of a task and potentially queue up another task after some delay so the way I 'm thinking of doing it looks something like this : My question is , if I do something like this , creating potentially long chains of tasks is will the older tasks be disposed or will they end up sticking around forever because the ContinueWith takes the last task as a parameter ( so it 's a closure ) . If so , how can I chain tasks while avoiding this problem ? Is there a better way to do this ? <code> private Task lastTask ; public void DoSomeTask ( ) { if ( lastTask == null ) { lastTask = Task.FromResult ( false ) ; } lastTask = lastTask.ContinueWith ( t = > { // do some task } ) .ContinueWith ( t = > Task.Delay ( 250 ) .Wait ( ) ) ; } | Chaining tasks with delays |
C_sharp : The implementation of Volatile.Read merely inserts a memory barrier after the read : Thus , usage of the method like so ... ... would be equivalent to : Given the above , would n't the resulting behavior be identical if the parameter was not a ref ? I guess that the ref parameter was used simply to prevent programmers from passing things other than variables , such as Volatile.Read ( 2 + 3 ) . Can anyone see any other reason for the ref when variables are passed in ? <code> public static int Read ( ref int location ) { var value = location ; Thread.MemoryBarrier ( ) ; return value ; } return Volatile.Read ( ref _a ) + Volatile.Read ( ref _b ) ; var a = _a ; Thread.MemoryBarrier ( ) ; var b = _b ; Thread.MemoryBarrier ( ) ; return a + b ; public static int Read ( int value ) { Thread.MemoryBarrier ( ) ; return value ; } | Why does Volatile.Read take ref parameter ? |
C_sharp : Suppose I am developing an application for a product distributor in C # .The distributor does the following 3 types of transactions : ( 1 ) Indent ( 2 ) Sell ( 3 ) StockI am designing my classes as follows : Now if I want to save these three types of information in three separate tables then how should I design my DA layer ? Should I build separate DA classes like or a single class TransactionDA and perform CRUD operations by checking their types by using as/is operators ? Or what else can I do ? Any suggestions ? <code> public abstract class Transaction { } public class Indent : Transaction { } public class Sell : Transaction { } public class Stock : Transaction { } ( 1 ) IndentDA ( 2 ) SellDA ( 3 ) StockDA | OO Design vs Database Design |
C_sharp : Note : This is more of a logic/math problem than a specific C # problem.I have my own class called Number - it very simply contains two separate byte arrays called Whole and Decimal . These byte arrays each represent essentially an infinitely large whole number , but , when put together the idea is that they create a whole number with a decimal part.The bytes are stored in a little-endian format , representing a number . I 'm creating a method called AddNumbers which will add two of these Numbers together.This method relies on another method called PerformAdd , which just adds two arrays together . It simply takes in a pointer to the final byte array , a pointer to one array to add , and a pointer to the second array to add - as well as the length of each of them . The two arrays are just named `` larger '' and `` smaller '' . Here is the code for this method : This method is n't where the problem lies - the problem is with how I use it . It 's the AddNumbers method that uses it . The way it works is fine - it organizes the two separate byte arrays into the `` larger '' ( larger meaning having a higher length of bytes ) and `` smaller '' . And then it creates pointers , it does this both for Whole and Decimal separately . The problem is with the decimal part.Let 's say we 're adding the numbers 1251 and 2185 together , in this situation you would get 3436 - so that works perfectly ! Take another example as well : You have the numbers 4.6 and add 1.2 - once again , this works fine , and you get 5.8 . The problem comes with the next example.We have 15.673 and 1.783 , you would expect 17.456 , however , actually , this returns : 16.1456 , and the reason for that is because it does n't carry the `` 1 '' .So , this is my problem : How would I implement a way that knows when and how to do this ? Here 's the code for my AddNumbers method : <code> private static unsafe void PerformAdd ( byte* finalPointer , byte* largerPointer , byte* smallerPointer , int largerLength , int smallerLength ) { int carry = 0 ; // Go through all the items that can be added , and work them out . for ( int i = 0 ; i < smallerLength ; i++ ) { var add = *largerPointer -- + *smallerPointer -- + carry ; // Stick the result of this addition in the `` final '' array . *finalPointer -- = ( byte ) ( add & 0xFF ) ; // Now , set a carry from this . carry = add > > 8 ; } // Now , go through all the remaining items ( which do n't need to be added ) , and add them to the `` final '' - still working with the carry . for ( int i = smallerLength ; i < largerLength ; i++ ) { var wcarry = *largerPointer -- + carry ; // Stick the result of this addition in the `` final '' array . *finalPointer -- = ( byte ) ( wcarry & 0xFF ) ; // Now , set a carry from this . carry = wcarry > > 8 ; } // Now , if we have anything still left to carry , carry it into a new byte . if ( carry > 0 ) *finalPointer -- = ( byte ) carry ; } public static unsafe Number AddNumbers ( Number num1 , Number num2 ) { // Store the final result . Number final = new Number ( new byte [ num1.Whole.Length + num2.Whole.Length ] , new byte [ num1.Decimal.Length + num2.Decimal.Length ] ) ; // We 're going to figure out which number ( num1 or num2 ) has more bytes , and then we 'll create pointers to smallest and largest . fixed ( byte* num1FixedWholePointer = num1.Whole , num1FixedDecPointer = num1.Decimal , num2FixedWholePointer = num2.Whole , num2FixedDecPointer = num2.Decimal , finalFixedWholePointer = final.Whole , finalFixedDecimalPointer = final.Decimal ) { // Create a pointer and figure out which whole number has the most bytes . var finalWholePointer = finalFixedWholePointer + ( final.Whole.Length - 1 ) ; var num1WholeLarger = num1.Whole.Length > num2.Whole.Length ? true : false ; // Store the larger/smaller whole number lengths . var largerLength = num1WholeLarger ? num1.Whole.Length : num2.Whole.Length ; var smallerLength = num1WholeLarger ? num2.Whole.Length : num1.Whole.Length ; // Create pointers to the whole numbers ( the largest amount of bytes and smallest amount of bytes ) . var largerWholePointer = num1WholeLarger ? num1FixedWholePointer + ( num1.Whole.Length - 1 ) : num2FixedWholePointer + ( num2.Whole.Length - 1 ) ; var smallerWholePointer = num1WholeLarger ? num2FixedWholePointer + ( num2.Whole.Length - 1 ) : num1FixedWholePointer + ( num1.Whole.Length - 1 ) ; // Handle decimal numbers . if ( num1.Decimal.Length > 0 || num2.Decimal.Length > 0 ) { // Create a pointer and figure out which decimal has the most bytes . var finalDecPointer = finalFixedDecimalPointer + ( final.Decimal.Length - 1 ) ; var num1DecLarger = num1.Decimal.Length > num2.Decimal.Length ? true : false ; // Store the larger/smaller whole number lengths . var largerDecLength = num1DecLarger ? num1.Decimal.Length : num2.Decimal.Length ; var smallerDecLength = num1DecLarger ? num2.Whole.Length : num1.Decimal.Length ; // Store pointers for decimals as well . var largerDecPointer = num1DecLarger ? num1FixedDecPointer + ( num1.Decimal.Length - 1 ) : num2FixedDecPointer + ( num2.Decimal.Length - 1 ) ; var smallerDecPointer = num1DecLarger ? num2FixedDecPointer + ( num2.Decimal.Length - 1 ) : num1FixedDecPointer + ( num1.Decimal.Length - 1 ) ; // Add the decimals first . PerformAdd ( finalDecPointer , largerDecPointer , smallerDecPointer , largerDecLength , smallerDecLength ) ; } // Add the whole number now . PerformAdd ( finalWholePointer , largerWholePointer , smallerWholePointer , largerLength , smallerLength ) ; } return final ; } | How to carry number from decimal to whole byte array |
C_sharp : I noticed a few questions about finding the nth occurrence of a character in a string . Since I was curious ( and have several uses for this in an application , but mainly out of curiosity ) , I coded and benchmarked two of these methods in Visual Studio 2010 , and I 'm wondering why method 1 ( FindNthOccurrence ) is much slower than method 2 ( IndexOfNth ) . The only reasons I could think of were : A problem with my benchmarking codeA problem with my algorithm ( s ) The fact that indexOf is a in-built .NET method and is therefore already optimisedI 'm leaning toward # 2 , but I 'd still like to know . This is the relevant code . CodeSample OutputEvery result outputs times similar to this ( milliseconds / elapsed ticks ) : <code> class Program { static void Main ( string [ ] args ) { char searchChar = ' a ' ; Random r = new Random ( UnixTimestamp ( ) ) ; // Generate sample data int numSearches = 100000 , inputLength = 100 ; List < String > inputs = new List < String > ( numSearches ) ; List < int > nth = new List < int > ( numSearches ) ; List < int > occurrences = new List < int > ( numSearches ) ; for ( int i = 0 ; i < numSearches ; i++ ) { inputs.Add ( GenerateRandomString ( inputLength , `` abcdefghijklmnopqrstuvwxyz '' ) ) ; nth.Add ( r.Next ( 1 , 4 ) ) ; } // Timing of FindNthOccurrence Stopwatch timeFindNth = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < numSearches ; i++ ) occurrences.Add ( FindNthOccurrence ( inputs [ i ] , searchChar , nth [ i ] ) ) ; timeFindNth.Stop ( ) ; Console.WriteLine ( String.Format ( `` FindNthOccurrence : { 0 } / { 1 } '' , timeFindNth.ElapsedMilliseconds , timeFindNth.ElapsedTicks ) ) ; // Cleanup occurrences.Clear ( ) ; // Timing of IndexOfNth Stopwatch timeIndexOf = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < numSearches ; i++ ) occurrences.Add ( IndexOfNth ( inputs [ i ] , searchChar , nth [ i ] ) ) ; timeIndexOf.Stop ( ) ; Console.WriteLine ( String.Format ( `` IndexOfNth : { 0 } / { 1 } '' , timeIndexOf.ElapsedMilliseconds , timeIndexOf.ElapsedTicks ) ) ; Console.Read ( ) ; } static int FindNthOccurrence ( String input , char c , int n ) { int len = input.Length ; int occurrences = 0 ; for ( int i = 0 ; i < len ; i++ ) { if ( input [ i ] == c ) { occurrences++ ; if ( occurrences == n ) return i ; } } return -1 ; } static int IndexOfNth ( String input , char c , int n ) { int occurrence = 0 ; int pos = input.IndexOf ( c , 0 ) ; while ( pos ! = -1 ) { occurrence++ ; if ( occurrence == n ) return pos ; pos = input.IndexOf ( c , pos + 1 ) ; } return -1 ; } // Helper methods static String GenerateRandomString ( int length , String legalCharacters = `` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '' ) { if ( length < 0 ) throw new ArgumentOutOfRangeException ( `` length '' , `` length can not be less than zero . `` ) ; if ( string.IsNullOrEmpty ( legalCharacters ) ) throw new ArgumentException ( `` allowedChars may not be empty . `` ) ; const int byteSize = 0x100 ; var legalCharSet = new HashSet < char > ( legalCharacters ) .ToArray ( ) ; if ( byteSize < legalCharSet.Length ) throw new ArgumentException ( String.Format ( `` allowedChars may contain no more than { 0 } characters . `` , byteSize ) ) ; // Guid.NewGuid and System.Random are not particularly random . By using a // cryptographically-secure random number generator , the caller is always // protected , regardless of use . using ( var rng = new System.Security.Cryptography.RNGCryptoServiceProvider ( ) ) { StringBuilder result = new StringBuilder ( ) ; var buf = new byte [ 128 ] ; while ( result.Length < length ) { rng.GetBytes ( buf ) ; for ( var i = 0 ; i < buf.Length & & result.Length < length ; ++i ) { // Divide the byte into legalCharSet-sized groups . If the // random value falls into the last group and the last group is // too small to choose from the entire legalCharSet , ignore // the value in order to avoid biasing the result . var outOfRangeStart = byteSize - ( byteSize % legalCharSet.Length ) ; if ( outOfRangeStart < = buf [ i ] ) continue ; result.Append ( legalCharSet [ buf [ i ] % legalCharSet.Length ] ) ; } } return result.ToString ( ) ; } } static int UnixTimestamp ( ) { TimeSpan ts = ( System.DateTime.UtcNow - new System.DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 ) ) ; return ( int ) ts.TotalSeconds ; } } FindNthOccurrence : 27 / 79716IndexOfNth : 12 / 36492 | Why is one method for finding the position of the nth occurrence of a character in a string much faster than another ? |
C_sharp : I have a linq query for project euler problem 243 : The problem is , for prime factors 2 and 3 , it produces the y = { 6 , 6 } where it needs to just be { 6 } .Is there a way to do this without calling y.Distinct ( ) or y.Contains ( ) multiple times ? I also thought about using two foreach loops , but the problem is - I ca n't use indexing so it 'd just be cumbersome and awkward . <code> var y = from n in factors from m in factors where m ! = n select n * m ; | Linq query that automatically excludes duplicates ( one-liner ) |
C_sharp : I am using CultureInfo.CurrentCulture when formating my strings using string.formatTo quote this blog This just has the implication that if you are using CurrentCulture a lot , it might be worth reading it into a private variable rather than making lots of calls to CultureInfo.CurrentCulture , otherwise you 're using up clock cycles needlessly.so as per this authoris better thanas per MSDN , CultureInfo.CurrentCulture is a propertyIs there a performance penalty associated when accessing a property multiple times ? ? Also I did some emperical analysis and my tests show me that using a local variable is more expensive than using the property directly.Result : My tests show that using CultureInfo.CurrentCulture property is better than using local variable ( which contradicts with the authors view ) . Or am I missing something here ? Edit : I was not resetting the stopwatch before teh second iteration . hence the difference . resetting stopwatch , updating iteration count and result in this edit <code> var culture = CultureInfo.CurrentCulturestring.Format ( culture , '' { 0 } some format string '' , '' some args '' ) ; string.Format ( culture , '' { 0 } some format string '' , '' some other args '' ) ; string.Format ( CultureInfo.CurrentCulture , '' { 0 } some format string '' , '' some args '' ) ; string.Format ( CultureInfo.CurrentCulture , '' { 0 } some format string '' , '' some other args '' ) ; Stopwatch watch = new Stopwatch ( ) ; int count = 100000000 ; watch.Start ( ) ; for ( int i=0 ; i < count ; i++ ) { string.Format ( CultureInfo.CurrentCulture , `` { 0 } is my name '' , `` ram '' ) ; } watch.Stop ( ) ; //EDIT : Reset watch watch.Reset ( ) ; Console.WriteLine ( watch.Elapsed ) ; Console.WriteLine ( watch.ElapsedMilliseconds ) ; Console.WriteLine ( watch.ElapsedTicks ) ; Console.WriteLine ( `` -- -- -- -- -- -- -- -- -- -- '' ) ; var culture = CultureInfo.CurrentCulture ; watch.Start ( ) ; for ( int i=0 ; i < count ; i++ ) { string.Format ( culture , `` { 0 } is my name '' , `` ram '' ) ; } watch.Stop ( ) ; Console.WriteLine ( watch.Elapsed ) ; Console.WriteLine ( watch.ElapsedMilliseconds ) ; Console.WriteLine ( watch.ElapsedTicks ) ; 00:00:29.61163062961168922550970 -- -- -- -- -- -- -- -- -- -- 00:00:27.35781162735763676674390 | performance consideration when using properties multiple times |
C_sharp : I was wondering what were the best practices for making a query in sql with a dynamic value , lets say i have a Value ( nvarchar ( max ) ) value : `` 912345678 '' value : `` Michael '' value : `` Street number 10 '' This approuches are a bit slow since searching for a number that has 9 digits would be faster without % like thisI use a EDMX to make a connection to an external database in C # , like this : How can i increase performance ? <code> select * from AllDatawhere Number like ' % 912345678 % ' select * from AllDatawhere Name like ' % Michael % ' select * from AllDatawhere Address like ' % Street number 10 % ' select * from AllDatawhere Number like '912345678 ' var Result = EDMXEntity.Entities.Where ( x = > ( SqlFunctions.PatIndex ( `` % '' + Value.ToLower ( ) + '' % '' , x.Name.ToString ( ) .ToLower ( ) ) > 0 ) || ( SqlFunctions.PatIndex ( `` % '' + Value.ToLower ( ) + '' % '' , x.Number.ToString ( ) .ToLower ( ) ) > 0 ) || ( SqlFunctions.PatIndex ( `` % '' + Value.ToLower ( ) + '' % '' , x.Address.ToString ( ) .ToLower ( ) ) > 0 ) ) .Take ( 50 ) .ToList ( ) ; | SQL Server and performance for dynamic searches |
C_sharp : This code does not compile with the latest C # compiler : When you attempt to compile it , it raises ( 3,22,3,29 ) : Error CS0119 : 'IntEnum ' is a type , which is not valid in the given contextStrangely , changing the casted value to a positive number ( such as 4 ) , or using a const value ( such as int.MinValue ) , or even surrounding the value with parentheses like ( IntEnum ) ( -1 ) will compile and work just fine . However , the above sample does not.Is there any reason for this ? Is it possible that Roslyn is perhaps parsing the code incorrectly , and that 's why an error is getting raised ? <code> public class Program { public static void Main ( ) { IntEnum a = ( IntEnum ) -1 ; } } public enum IntEnum : int { } | Why is n't the C # compiler able to cast a literal negative value to an enum ? |
C_sharp : I 'm trying to query an Elasticsearch index from C # via Elasticsearch.net ( not NEST ) . Specifically , I need to get all documents with a status of `` success '' that have been created since a specific date . In an attempt to do this , I have : I 'm not sure what to use for the range part . In fact , I 'm not even sure if my syntax for the query is correct . I do n't really understand how the C # syntax maps to the Query DSL in Elasticsearch . Any help is appreciated.Thank you ! <code> var query = new { query = new { match = new { field= '' status '' , query= '' success '' } } , range = new { ? } } ; | Elasticsearch.net - Range Query |
C_sharp : Would the following method ensure that only one thread can read an ID at a time ? I have a parallel process which uses the following method and I need it to return unique IDs . Unfortunately I can not change the way the ID is structured . <code> private static int Seq = 0 ; private static long dtDiff = 0 ; private static object thisLock = new object ( ) ; private static object BuildClientID ( string Code ) { lock ( thisLock ) { object sReturn = `` '' ; Seq++ ; dtDiff++ ; if ( Seq == 1000 ) { Seq = 0 ; dtDiff = DateAndTime.DateDiff ( DateInterval.Second , DateTime.Parse ( `` 1970-01-01 '' ) , DateTime.Now ) ; } sReturn = dtDiff.ToString ( ) + Code + Seq.ToString ( `` 000 '' ) ; return sReturn ; } } | Lock an object that creates ID |
C_sharp : Using Identity Serve 4 with .Net Core 3.1 , razor pages . Also using Cookie AuthenticationProblem -In a web application John logged-in 2 times1st Login on Chrome2nd Login on edgeSo , if John again trying to logged-in on 3rd time on Firefox without logout from previous browsers , then I want to logout John from 1st Login on Chrome forcefully.I can keep the track of logins in a Session table including Session Id , User Id etc.But I don ’ t know how logout user from a particular session using Session Id.Please help.Thanks <code> services.AddAuthentication ( CookieAuthenticationDefaults.AuthenticationScheme ) | How to Logout user from a particular session Identity Server 4 , .Net Core ? |
C_sharp : I have a class Person , and created an equality comperer class derived from EqualityComparer < Person > . Yet the default EqualityComparer does n't call the Equals function of my equality comparerAccording to MSDN EqualityComparer < T > .Default property : The Default property checks whether type T implements the System.IEquatable interface and , if so , returns an EqualityComparer that uses that implementation . Otherwise , it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.In the ( simplified ) example below , class Person does not implement implement System.IEquatable < Person > . So I 'd expect that PersonComparer.Default would return an instance of PersonComparer.Yet PersonComparer.Equals is not called . There is no debug output and the returned value is false.Question : What am I doing wrong ? In case you might wonder why I do n't want to implement IEquatable < Person > .My problem is comparable with the comparison of strings . Sometimes you want two strings to be equal if they are exactly the same strings , sometimes you want to ignore case , and sometimes you want to treat characters as óò etc all as if they are the character o.In my case : I store a Person in something , which might be a database , but it might as well be a File or a MemoryStream . Upon return I get an identifier , which in case of a database is of course the primary key . With this key I am able to retrieve an object with the same values . I want to test this in a unit Test : I you put something in it , you should get a key that can be used to retrieve the item . Alas , the database does n't return the same Person , but a derived class of Person ( At least when using EF 6 ) . So I ca n't use the normal IEquatable , which should return false if the objects are not of the same type . That 's why I wanted to use a special comparer , one that declares two Persons equal if they have the same values for the properties , even if they are both different derived classes from Person . Very comparable as a string comparer that accepts O and o and ó to be equal <code> public class Person { public string Name { get ; set ; } } public class PersonComparer : EqualityComparer < Person > { public override bool Equals ( Person x , Person y ) { Debug.WriteLine ( `` PersonComparer.Equals called '' ) ; return true ; } public override int GetHashCode ( Person obj ) { Debug.WriteLine ( `` PersonComparer.GetHasCode called '' ) ; return obj.Name.GetHashCode ( ) ; } } public static void Main ( ) { Person x = new Person ( ) { Name = `` x '' } ; Person y = new Person ( ) { Name = `` x '' } ; bool b1 = PersonComparer.Default.Equals ( x , y ) ; } | EqualityComparer < T > .Default does n't return the derived EqualityComparer |
C_sharp : I used this pattern in a few projects , ( this snipped of code is from CodeCampServer ) , I understand what it does , but I 'm really interesting in an explanation about this pattern . Specifically : Why is the double check of _dependenciesRegistered.Why to use lock ( Lock ) { } .Thanks . <code> public class DependencyRegistrarModule : IHttpModule { private static bool _dependenciesRegistered ; private static readonly object Lock = new object ( ) ; public void Init ( HttpApplication context ) { context.BeginRequest += context_BeginRequest ; } public void Dispose ( ) { } private static void context_BeginRequest ( object sender , EventArgs e ) { EnsureDependenciesRegistered ( ) ; } private static void EnsureDependenciesRegistered ( ) { if ( ! _dependenciesRegistered ) { lock ( Lock ) { if ( ! _dependenciesRegistered ) { new DependencyRegistrar ( ) .ConfigureOnStartup ( ) ; _dependenciesRegistered = true ; } } } } } | Explain the code : c # locking feature and threads |
C_sharp : If an object realizes IDisposable in C # one can writeI 've always wondered why the using looks like a C # keyword , but requires an interface defined in the .Net framework . Is using a keyword ( in this context , obviously it is for defining your library imports ) , or has Microsoft overloaded it 's use in Visual Studio/.Net framework ? I would n't have expected a C # keyword to depend on a library . <code> using ( DisposableFoo foo = new DisposableFoo ( ) ) | Is 'using ' a C # keyword ? |
C_sharp : i try to confirm a sale and i need sum information about the product..my Viewi tryed with the ' $ .getJSON ' like this : and on the controllerbut i dont know how to return it to the onclick confirm msg or into my ViewModel..any help ? <code> @ using ( Html.BeginForm ( ) ) { @ Html.ValidationSummary ( true ) < fieldset > < legend > Card < /legend > < div class= '' editor-label '' > @ Html.LabelFor ( model = > model.CardModel.SerialNumber , `` Serial No '' ) < /div > < div class= '' editor-field '' > @ Html.EditorFor ( model = > model.CardModel.SerialNumber , new { id = `` sn '' } ) @ Html.ValidationMessageFor ( model = > model.CardModel.SerialNumber ) < /div > < p > < input type= '' submit '' value= '' CardSale '' id= '' btnSubmit '' onclick= '' if ( confirm ( 'The owner dealer price is : ** @ Model.OwnerPrice** . Are you sure ? ' ) ) { return true ; } else { return false ; } '' / > < /p > < /fieldset > } < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( `` # btnSubmit '' ) .click ( function ( ) { var serial = $ ( `` # sn '' ) ; var price = `` '' ; var url = `` '' ; url = `` @ Url.Action ( `` GetOwnerPrice '' , '' Card '' ) / '' +serial ; $ .getJSON ( url , function ( data ) { alert ( data.Value ) ; } ) ; } ) ; } ) ; public ActionResult GetOwnerPrice ( int sn ) { var owner = db.Dealers.Single ( s = > s.DealerID == db.Dealers.Single ( o = > o.UserName == User.Identity.Name ) .OwnerDealerID ) ; var ownerPrice = owner.ProductToSale.Single ( pr = > pr.ProductID == sn ) .SalePrice ; return Json ( ownerPrice , JsonRequestBehavior.AllowGet ) ; } | Getting information from my controller into onclick confirm ( alert ) |
C_sharp : I recently asked a question here , and someone provided this answer : What is that = > doing ? It 's the first time I 'm seeing this . <code> private void button1_Click ( object sender , EventArgs e ) { var client = new WebClient ( ) ; Uri X = new Uri ( `` http : //www.google.com '' ) ; client.DownloadStringCompleted += ( s , args ) = > //THIS , WHAT IS IT DOING ? { if ( args.Error == null & & ! args.Cancelled ) { MessageBox.Show ( ) ; } } ; client.DownloadStringAsync ( X ) ; } | What is the symbol `` = > '' doing after my method in this C # code ? |
C_sharp : EDIT Additional options and a slightly extended question below.Consider this contrived and abstract example of a class body . It demonstrates four different ways of performing a `` for '' iteration.EDIT : Addition of some options from answers and research.My question comes in two parts . Have I missed some significant option ? Which option is the best choice , considering readability but primarily performance ? Please indicate if the complexity of the SomeClass implementation , or the Count of someList would effect this choice.EDIT : With such a dizzying array of options , I would n't like my code to be spoilt by choice . To add a thrid part to my question , If my list could be any length should I default to a parallel option ? As a straw man . I suspect that over all implementations of SomeClass and all lengths of someList option //E . ParallelEnumerable would offer the best average performance , given the prevalanece of multi processor architechtures . I have n't done any testing to prove this.Note : The parallel extensions will require the use of the System.Threading.Tasks namespace . <code> private abstract class SomeClass { public void someAction ( ) ; } void Examples ( ) { List < SomeClass > someList = new List < SomeClass > ( ) ; //A . for for ( int i = 0 ; i < someList.Count ( ) ; i++ ) { someList [ i ] .someAction ( ) ; } //B . foreach foreach ( SomeClass o in someList ) { o.someAction ( ) ; } //C . foreach extension someList.ForEach ( o = > o.someAction ( ) ) ; //D . plinq someList.AsParallel ( ) .ForAll ( o = > o.someAction ( ) ) ; //E . ParallelEnumerable ParallelEnumerable.Range ( 0 , someList.Count - 1 ) .ForAll ( i = > someList [ i ] .someAction ( ) ) ; //F . ForEach Parallel Extension Parallel.ForEach ( someList , o = > o.someAction ( ) ) ; //G . For Parallel Extension Parallel.For ( 0 , someList.Count - 1 , i = > someList [ i ] .someAction ( ) ) } | When to use which for ? |
C_sharp : In the spirit of polygenelubricants ' efforts to do silly things with regular expressions , I currently try to get the .NET regex engine to multiplicate for me.This has , of course , no practical value and is meant as a purely theoretical exercise.So far , I 've arrived at this monster , that should check if the number of 1s multiplied by the number of 2s equals the number of 3s in the string.Unfortunately , its not working , and I am at a loss why . I commented it to show you what I think the engine should be doing , but I may be off here.Examples of output : Any thought are welcome ! <code> Regex regex = new Regex ( @ '' ^ ( 1 ( ? < a > ) ) * # increment a for each 1 ( 2 ( ? < b > ) ) * # increment b for each 2 ( ? ( a ) # if a > 0 ( ( ? < -a > ) # decrement a ( 3 ( ? < c-b > ) ) * # match 3 's , decrementing b and incrementing c until # there are no 3 's left or b is zero ( ? ( b ) ( ? ! ) ) # if b ! = 0 , fail ( ? < b-c > ) * # b = c , c = 0 ) ) * # repeat ( ? ( a ) ( ? ! ) ) # if a ! = 0 , fail ( ? ( c ) ( ? ! ) ) # if c ! = 0 , fail $ '' , RegexOptions.IgnorePatternWhitespace ) ; regex.IsMatch ( `` 123 '' ) // true , correctregex.IsMatch ( `` 22 '' ) // true , correctregex.IsMatch ( `` 12233 '' ) // false , incorrectregex.IsMatch ( `` 11233 '' ) ; // true , correct | Multiplication with .NET regular expressions |
C_sharp : For ex : <code> public static Domain.Recruitment.Recruitment Map ( this Data.Recruitment dv ) { //some code return new Domain.Recruitment.Recruitment { } } | Why do we put `` this '' in front of a parameter ? |
C_sharp : I 'm trying to make instance of class EndpointAddress where parameter contains German umlaut . For example : It always throws exception that given uri can not be parsed . I have tried to replace the umlaut with an encoded value , but I get same exception : Invalid URI : The hostname could not be parsed.Did anyone had same problem before ? Thank you in advance . <code> EndpointAddress endpointAddress = new EndpointAddress ( `` net.tcp : //süd:8001/EmployeeService '' ) ; | German umlauts in EndpointAddress with net.tcp |
C_sharp : I 'm creating an application that enables a user to insert , update and delete data that has been entered and then shown in a data-grid ( CRUD operations ) .In my View Model , it contains properties which are bound to the xaml ( Firstname for example ) . It also contains a navigation property as well as validation attributes.Furthermore , it contains commands for the xaml to execute , which creates an instance of the CRUD operation ; And lastly , it contains the CRUD operations as well . Such as the Insert , Update and Delete.Which leads me to my question . if I want to implement the correct MVVM way , is all this code too much for the view model to contain ? Should I use the model and create a collection within my View-model and bound that to my xaml ? Would this be the correct way of doing it ? Should I use a Repository system for the CRUD operations ? If so , how would I pass the data from the text fields through to the model to get updated ? Im new to WPF , MVVM and finding it hard to adapt without proper guidance . <code> [ Required ( ErrorMessage = `` First Name is a required field '' ) ] [ RegularExpression ( @ '' ^ [ a-zA-Z '' -'\s ] { 1,20 } $ '' , ErrorMessage = `` First Name must contain no more then 20 characters and contain no digits . '' ) ] public string FirstName { get { return _FirstName ; } set { if ( _FirstName == value ) return ; _FirstName = value ; OnPropertyChanged ( `` FirstName '' ) ; } } private void UpdateFormExecute ( ) { var org = new OrganisationTypeDetail ( ) ; UpdateOrganisationTypeDetail ( org ) ; } | Is this correct way to implement MVVM ? |
C_sharp : The following raises complaints : but I ca n't imagine where this would n't be type-safe . ( snip* ) Is this the reason why this is disallowed , or is there some other case which violates type safety which I 'm not aware of ? * My initial thoughts were admittedly convoluted , but despite this , the responses are very thorough , and @ Theodoros Chatzigiannakis even dissected my initial assumptions with impressive accuracy . Alongside a good slap from retrospect , I realize that I had falsely assumed that the type signature of ICovariant : :M remains a Func < IInvariant < Derived > > when its ICovariant < Derived > is assigned to a ICovariant < Base > . Then , assigning that M to Func < IInvariant < Base > > would look fine coming from an ICovariant < Base > , but would of course be illegal . Why not just ban this last , obviously-illegal cast ? ( so I thought ) I feel this false and tangential guess detracts from the question , as Eric Lippert also points out , but for historical purposes , the snipped part : The most intuitive explanation to me is that , taking ICovariant as an example , the covariant TCov implies that the method IInvariant < TCov > M ( ) could be cast to some IInvariant < TSuper > M ( ) where TSuper super TCov , which violates the invariance of TInv in IInvariant . However , this implication does n't seem necessary : the invariance of IInvariant on TInv could easily be enforced by disallowing the cast of M . <code> interface IInvariant < TInv > { } interface ICovariant < out TCov > { IInvariant < TCov > M ( ) ; // The covariant type parameter ` TCov ' // must be invariantly valid on // ` ICovariant < TCov > .M ( ) ' } interface IContravariant < in TCon > { void M ( IInvariant < TCon > v ) ; // The contravariant type parameter // ` TCon ' must be invariantly valid // on ` IContravariant < TCon > .M ( ) ' } | Why does the variance of a class type parameter have to match the variance of its methods ' return/argument type parameters ? |
C_sharp : There is a table called UserFriends that holds records for users ' friendships.For each friendship , there is just one record , which is equal in terms of business logic tobut both ca n't happen for one pair.What is the most efficient ( yet readable and not involving plain SQL ) Entity Framework query to determine if user A is a friend of user B , considering we do n't know which of them is in first or second column ? My attempt is plain and obvious : Is there a better way than || here ? <code> User1ID User2ID IsConfirmed1 2 true User1ID User2ID IsConfirmed2 1 true public bool AreFriends ( int user1Id , int user2Id ) { return MyObjectContext.UserFriends .Any ( uf = > uf.IsConfirmed & & ( ( uf.UserID == user1Id & & uf.FriendUserID == user2Id ) || ( uf.UserID == user2Id & & uf.FriendUserID == user1Id ) ) ) ; } | What is an efficient Entity Framework query to check if users are friends ? |
C_sharp : When trying to get properties accessors from derived properties or use CanRead / CanWrite , for some reason base auto-properties are not taken into account.CanRead and CanWrite return values based only on the derived type , also GetMethod and SetMethod do n't contain methods from base type.However when writing code accessors from base type can be used ( so that we can read overridden auto-property with only setter defined in derived type ) .Here is the code to reproduce it written as an unit test : I expected last two tests to pass , what am I missing ? <code> using System.Reflection ; using NUnit.Framework ; [ TestFixture ] public class PropertiesReflectionTests { public class WithAutoProperty { public virtual object Property { get ; set ; } } public class OverridesOnlySetter : WithAutoProperty { public override object Property { set = > base.Property = value ; } } private static readonly PropertyInfo Property = typeof ( OverridesOnlySetter ) .GetProperty ( nameof ( OverridesOnlySetter.Property ) ) ; // This one is passing [ Test ] public void Property_ShouldBeReadable ( ) { var overridesOnlySetter = new OverridesOnlySetter { Property = `` test '' } ; Assert.AreEqual ( overridesOnlySetter.Property , `` test '' ) ; } // This one is failing [ Test ] public void CanRead_ShouldBeTrue ( ) { Assert.True ( Property.CanRead ) ; } // And this is failing too [ Test ] public void GetMethod_ShouldBeNotNull ( ) { Assert.NotNull ( Property.GetMethod ) ; } } | Why do CanRead and CanWrite return false in C # for properties with overridden accessors ? |
C_sharp : I have the following C # Code ( I reduced it to the bare minimum to simplify it ) . Visual Studio 2019 , .NET Framework 4.7.2.From my understanding , there is nothing wrong about it . The function may fail ( I do n't want to catch it ) but before leaving , it will report successful execution to another method . When debugging , it does exactly what it should.Interestingly , Visual Studio 2019 will report the following : When I follow the suggestion by choosing `` Remove redundant assignment '' , it will remove the line success = true ; , effectively changing the outcome ! Now what is the switch/case for , you 'd ask ? When removing it , the recommendation disappears : Is there any reason for that , or is it a bug in Visual Studio ? <code> public void Demo ( ) { ReportStart ( ) ; var success = false ; try { int no = 1 ; switch ( no ) { case 1 : default : break ; } DoSomething ( ) ; success = true ; } finally { ReportEnd ( success ) ; } } | Visual Studio IDE0059 C # Unnecessary assignment of a value bug ? |
C_sharp : The String.Contains method looks like this internallyThe IndexOf overload that is called looks like thisHere another call is made to the final overload , which then calls the relevant CompareInfo.IndexOf method , with the signatureTherefore , calling the final overload would be the fastest ( albeit may be considered a micro optimization in most cases ) . I may be missing something obvious but why does the Contains method not call the final overload directly considering that no other work is done in the intermediate call and that the same information is available at both stages ? Is the only advantage that if the signature of the final overload changes , only one change needs to be made ( that of the intermediate method ) , or is there more to the design than that ? Edit from the comments ( see update 2 for speed difference explanation ) To clarify the performance differences I 'm getting in case I 've made a mistake somewhere : I ran this benchmark ( looped 5 times to avoid jitter bias ) and used this extension method to compare against the String.Contains methodwith the loop looking like this In the benchmark test , QuickContains seems about 50 % faster than String.Contains on my machine.Update 2 ( performance difference explained ) I 've spotted something unfair in the benchmark which explains a lot . The benchmark itself was to measure case-insensitive strings but since String.Contains can only perform case-sensitive searches , the ToUpper method was included . This would skew the results , not in terms of final output , but at least in terms of simply measuring String.Contains performance in non case-sensitive searches.So now , if I use this extension methoduse StringComparison.Ordinal in the 2 overload IndexOf call and remove ToUpper , the QuickContains method actually becomes the slowest . IndexOf and Contains are pretty much on par in terms of performance . So clearly it was the ToUpper call skewing the results of why there was such a discrepancy between Contains and IndexOf . Not sure why the QuickContains extension method has become the slowest . ( Possibly related to the fact that Contains has the [ __DynamicallyInvokable , TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] attribute ? ) .Question still remains as to why the 4 overload method is n't called directly but it seems performance is n't impacted ( as Adrian and delnan pointed out in the comments ) by the decision . <code> public bool Contains ( string value ) { return this.IndexOf ( value , StringComparison.Ordinal ) > = 0 ; } public int IndexOf ( string value , StringComparison comparisonType ) { return this.IndexOf ( value , 0 , this.Length , comparisonType ) ; } public int IndexOf ( string value , int startIndex , int count , StringComparison comparisonType ) public static bool QuickContains ( this string input , string value ) { return input.IndexOf ( value , 0 , input.Length , StringComparison.OrdinalIgnoreCase ) > = 0 ; } for ( int i = 0 ; i < 1000000 ; i++ ) { bool containsStringRegEx = testString.QuickContains ( `` STRING '' ) ; } sw.Stop ( ) ; Console.WriteLine ( `` QuickContains : `` + sw.ElapsedMilliseconds ) ; public static bool QuickContains ( this string input , string value ) { return input.IndexOf ( value , 0 , input.Length , StringComparison.Ordinal ) > = 0 ; } | Why does n't String.Contains call the final overload directly ? |
C_sharp : Being mainly a Java developer , I was a bit surprised by the result when I one day accidentally used new keyword instead of override.It appears that the new keyword removes the `` virtualness '' of the method at that level in the inheritance tree , so that calling a method on an instance of child class that is downcasted to the parent class , will not resolve to the method implementation in the child class.What are the practical use cases for this behavior ? Clarification : I understand the use of new when parent is not virtual . I 'm more curious why the compiler allows new and virtual to be combined.The following example illustrates the difference : This produces the following output : <code> using System ; public class FooBar { public virtual void AAA ( ) { Console.WriteLine ( `` FooBar : AAA '' ) ; } public virtual void CCC ( ) { Console.WriteLine ( `` FooBar : CCC '' ) ; } } public class Bar : FooBar { public new void AAA ( ) { Console.WriteLine ( `` Bar : AAA '' ) ; } public override void CCC ( ) { Console.WriteLine ( `` Bar : CCC '' ) ; } } public class TestClass { public static void Main ( ) { FooBar a = new Bar ( ) ; Bar b = new Bar ( ) ; Console.WriteLine ( `` Calling FooBar : AAA '' ) ; a.AAA ( ) ; Console.WriteLine ( `` Calling FooBar : CCC '' ) ; a.CCC ( ) ; Console.WriteLine ( `` Calling Bar : AAA '' ) ; b.AAA ( ) ; Console.WriteLine ( `` Calling Bar : CCC '' ) ; b.CCC ( ) ; Console.ReadLine ( ) ; } } Calling FooBar : AAAFooBar : AAACalling FooBar : CCCBar : CCCCalling Bar : AAABar : AAACalling Bar : CCCBar : CCC | What is the use case for C # allowing to use new on a virtual method ? |
C_sharp : Given these type declarations , what part of the C # specification explains why the last line of the following code fragment prints `` True '' ? Can developers rely on this behavior ? Note that if the T type parameter in ICloneable were not declared out , then both lines would print `` False '' . <code> interface ICloneable < out T > { T Clone ( ) ; } class Base : ICloneable < Base > { public Base Clone ( ) { return new Base ( ) ; } } class Derived : Base , ICloneable < Derived > { new public Derived Clone ( ) { return new Derived ( ) ; } } Derived d = new Derived ( ) ; Base b = d ; ICloneable < Base > cb = d ; Console.WriteLine ( b.Clone ( ) is Derived ) ; // `` False '' : Base.Clone ( ) is calledConsole.WriteLine ( cb.Clone ( ) is Derived ) ; // `` True '' : Derived.Clone ( ) is called | Does I < D > re-implement I < B > if I < D > is convertible to I < B > by variance conversion ? |
C_sharp : Consider the following code : If you run this code inside a .NET 4.7.2 console application , you will get the following output : I do understand that the differences in the output arise from the fact that SetValueInAsyncMethod is not really a method , but a state machine executed by AsyncTaskMethodBuilder which captures ExecutionContext internally and SetValueInNonAsyncMethod is just a regular method . But even with this understanding in mind I still have some questions : Is this a bug / missing feature or an intentional design decision ? Do I need to worry about this behavior while writing code that depends on AsyncLocal ? Say , I want to write my TransactionScope-wannabe that flows some ambient data though await points . Is AsyncLocal enough here ? Are there any other alternatives to AsyncLocal and CallContext.LogicalGetData / CallContext.LogicalSetData in .NET when it comes down to preserving values throughout the `` logical code flow '' ? <code> private static async Task Main ( string [ ] args ) { await SetValueInAsyncMethod ( ) ; PrintValue ( ) ; await SetValueInNonAsyncMethod ( ) ; PrintValue ( ) ; } private static readonly AsyncLocal < int > asyncLocal = new AsyncLocal < int > ( ) ; private static void PrintValue ( [ CallerMemberName ] string callingMemberName = `` '' ) { Console.WriteLine ( $ '' { callingMemberName } : { asyncLocal.Value } '' ) ; } private static async Task SetValueInAsyncMethod ( ) { asyncLocal.Value = 1 ; PrintValue ( ) ; await Task.CompletedTask ; } private static Task SetValueInNonAsyncMethod ( ) { asyncLocal.Value = 2 ; PrintValue ( ) ; return Task.CompletedTask ; } SetValueInAsyncMethod : 1Main : 0SetValueInNonAsyncMethod : 2Main : 2 | ExecutionContext does not flow up the call stack from async methods |
C_sharp : So I have the following code in C # : The app.Use ( ) is defined as Owin.AppBuilderUserExtensions.Use ( ) and looks like this : public static IAppBuilder Use ( this IAppBuilder app , Func < IOwinContext , Func < Task > , Task > handler ) ; The VB equivalent is as follows : For some reason , in the VB version , the app.Use ( ) does n't use the extension function that 's available and simply uses IAppBuilder.Use ( ) instead , as follows : Function Use ( middleware As Object , ParamArray args ( ) As Object ) As IAppBuilderWhy does the VB code not use the same extension function that C # does and how can I make it use that ? EditFor clarity , the extension methods are not my own . They are from the Owin 3rd party library . So there is no option of renaming the extension methods . <code> public Container ConfigureSimpleInjector ( IAppBuilder app ) { var container = new Container ( ) ; container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle ( ) ; container.RegisterPackages ( ) ; app.Use ( async ( context , next ) = > { using ( AsyncScopedLifestyle.BeginScope ( container ) ) { await next ( ) ; } } ) ; container.Verify ( ) ; return container ; } Public Function ConfigureSimpleInjector ( app As IAppBuilder ) As Container Dim container = New Container ( ) container.Options.DefaultScopedLifestyle = New AsyncScopedLifestyle ( ) container.RegisterPackages ( ) app.Use ( Async Sub ( context , [ next ] ) Using AsyncScopedLifestyle.BeginScope ( container ) Await [ next ] ( ) End Using End Sub ) container.Verify ( ) Return containerEnd Function | C # function uses extension function but VB equivalent does not ? |
C_sharp : I was recently looking at wrapper classes and googled the following page ... http : //wiki.developerforce.com/page/Wrapper_ClassWhile I understood wrapper classes , I was baffled by the following ... and in particular ... What is that select and from ? Where can I look at more info for this in the foreach ? I know about LINQ and the select , from , where , etc ... . but I never seen _this_ syntax before . What is it and how do I research more about this syntax ? <code> public List < cContact > getContacts ( ) { if ( contactList == null ) { contactList = new List < cContact > ( ) ; for ( Contact c : [ select Id , Name , Email , Phone from Contact limit 10 ] ) { // As each contact is processed we create a new cContact object and add it to the contactList contactList.add ( new cContact ( c ) ) ; } } return contactList ; } for ( Contact c : [ select Id , Name , Email , Phone from Contact limit 10 ] ) { ... } | Foreach with a select/from in square brackets ? |
C_sharp : I 'm trying to apply Specification pattern to my validation logic . But I have some problems with async validation.Let 's say I have an entity AddRequest ( has 2 string property FileName and Content ) that need to be validated.I need to create 3 validators : Validate if FileName does n't contains invalid charactersValidate if Content is correctAsync validate if file with FileName is exists on the database . In this case I should have something like Task < bool > IsSatisfiedByAsyncBut how can I implement both IsSatisfiedBy and IsSatisfiedByAsync ? Should I create 2 interfaces like ISpecification and IAsyncSpecification or can I do that in one ? My version of ISpecification ( I need only And ) AndSpecificationTo validate if file exists I should use : How can I write IsSatisfiedBy for that check if I really need do that async ? For example here my validator ( 1 ) for FileNameI need to create FileExistsSpecification and use like : But how can I create FileExistsSpecification if I need async ? <code> public interface ISpecification { bool IsSatisfiedBy ( object candidate ) ; ISpecification And ( ISpecification other ) ; } public class AndSpecification : CompositeSpecification { private ISpecification leftCondition ; private ISpecification rightCondition ; public AndSpecification ( ISpecification left , ISpecification right ) { leftCondition = left ; rightCondition = right ; } public override bool IsSatisfiedBy ( object o ) { return leftCondition.IsSatisfiedBy ( o ) & & rightCondition.IsSatisfiedBy ( o ) ; } } await _fileStorage.FileExistsAsync ( addRequest.FileName ) ; public class FileNameSpecification : CompositeSpecification { private static readonly char [ ] _invalidEndingCharacters = { ' . ' , '/ ' } ; public override bool IsSatisfiedBy ( object o ) { var request = ( AddRequest ) o ; if ( string.IsNullOrEmpty ( request.FileName ) ) { return false ; } if ( request.FileName.Length > 1024 ) { return false ; } if ( request.FileName.Contains ( '\\ ' ) || _invalidEndingCharacters.Contains ( request.FileName.Last ( ) ) ) { return false ; } return true } } var validations = new FileNameSpecification ( ) .And ( new FileExistsSpecification ( ) ) ; if ( validations.IsSatisfiedBy ( addRequest ) ) { ... } | Specification pattern async |
C_sharp : I want to write a regexp to get multiple matches of the first character and next three digits . Some valid examples : A123 , V322 , R333.I try something like thatbut it gets me just the first match ! Could you possibly show me , how to rewrite this regexp to get multiple results ? Thank you so much and Have a nice day ! <code> [ a-aA-Z ] ( 1 ) \d3 | RegExp multiply matches in text |
C_sharp : I 'm working on a LightSwitch custom control that is able ( well , at least this is intended ... ) to bind to and edit various different properties , based on a discriminating value.Let me explain a bit further . The table looks like this : Now , based on the value of Datenformat , the control binds itself dynamically to ErgebnisBool , ErgebnisDatum and so on and selects the appropriate DataTemplate from the control 's xaml.ErgebnisAnzeige is a computed text property that holds a read-only display string.The control 's xaml is as follows : The MtTemplateSelector class simply returns the appropriate DataTemplate for the current format , nothing special here.The control itself ( ProzessErgebnisEdit ) is also very simple . It does nothing than binding the entity instance ( called RootEntity ) : Last not least I have this control factory that returns a display-only DataTemplate , when appropriate : Everything works fine so far : When the cell is not focused , the display-only text appears ( e.g . Wahr/Falsch/ -- ) , and when I click to edit a cell , it switches to the approriate DataTemplate ( e.g . a Checkbox ) . And there is always the correct value displayed , which tells me that the databinding generally works.The only problem is that the controls are always read-only , and I 'm not able to make them editable via code or xaml or whatever . So far I tried to intercept the grid 's OnPrepareCellEditing event and then setting the IsReadOnly property of the respective column manually to false , and I also tried the same with the control 's DataContext.IsReadOnly property . No luck ... What am I missing ? Is my entire approach flawed ? What 's going on here ? I ca n't figure out a reason for this behavior , I do n't even see a direction for searching ... Edit : On the german identifiersSome of the identifiers are in German und thus might not be immediately clear to everyone . But in the end , it 's as simple as this : Ergebnis is German for Result . This expression appears frequently in the table because the value to display is the result of a physical production process which can be of various data types such as bool , string , datetime etc . ( nothing fancy here ) . This information is the content of the Datenformat column , which would be something like DataType in English.Edit2 : The template selector : <code> < UserControl x : Class= '' EuvControlsExtension.Presentation.Controls.ProzessErgebnisEdit '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : framework = '' clr-namespace : Microsoft.LightSwitch.Presentation.Framework ; assembly=Microsoft.LightSwitch.Client '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : sdk= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation/sdk '' xmlns : ct= '' clr-namespace : System.Windows.Controls ; assembly=System.Windows.Controls.Data.Input '' xmlns : multi= '' clr-namespace : EuvControlsExtension.Presentation.Controls '' xmlns : toolkit= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit '' mc : Ignorable= '' d '' x : Name= '' HostControl '' > < multi : MtTemplateSelector x : Name= '' MyTemplateSelector '' Content= '' { Binding Path=RootEntity , Mode=TwoWay , ElementName=HostControl , UpdateSourceTrigger=Default } '' HorizontalContentAlignment= '' Stretch '' VerticalContentAlignment= '' Center '' IsHitTestVisible= '' False '' > < ! -- Zahl -- > < multi : MtTemplateSelector.ZahlTemplate > < DataTemplate > < TextBox HorizontalAlignment= '' Stretch '' Text= '' { Binding Path=RootEntity.ErgebnisZahl , ElementName=HostControl , Mode=TwoWay , UpdateSourceTrigger=Default , ValidatesOnExceptions=True , NotifyOnValidationError=True } '' / > < /DataTemplate > < /multi : MtTemplateSelector.ZahlTemplate > < ! -- Bool -- > < multi : MtTemplateSelector.BoolTemplate > < DataTemplate > < CheckBox IsThreeState= '' True '' Content= '' { Binding Path=RootEntity.ErgebnisBool , ElementName=HostControl , Mode=TwoWay , UpdateSourceTrigger=Default , ValidatesOnExceptions=True , NotifyOnValidationError=True } '' / > < /DataTemplate > < /multi : MtTemplateSelector.BoolTemplate > < /multi : MtTemplateSelector > < /UserControl > public partial class ProzessErgebnisEdit : UserControl { public ProzessErgebnisEdit ( ) { InitializeComponent ( ) ; BindProperties ( ) ; } private void BindProperties ( ) { var binding = new Binding ( `` DataSourceRoot.RootObject '' ) { Mode = BindingMode.TwoWay } ; this.SetBinding ( RootEntityProperty , binding ) ; } public object RootEntity { get { return GetValue ( RootEntityProperty ) ; } set { SetValue ( RootEntityProperty , value ) ; } } public static readonly DependencyProperty RootEntityProperty = DependencyProperty.Register ( `` RootEntity '' , typeof ( object ) , typeof ( ProzessErgebnisEdit ) , new PropertyMetadata ( null ) ) ; } [ Export ( typeof ( IControlFactory ) ) ] [ ControlFactory ( `` EuvControlsExtension : ProzessErgebnisEdit '' ) ] internal class ProzessErgebnisEditFactory : IControlFactory { private DataTemplate dataTemplate ; private DataTemplate displayModeDataTemplate ; public DataTemplate DataTemplate { get { return this.dataTemplate ? ? ( this.dataTemplate = XamlReader.Load ( ControlTemplate ) as DataTemplate ) ; } } public DataTemplate GetDisplayModeDataTemplate ( IContentItem contentItem ) { return this.displayModeDataTemplate ? ? ( this.displayModeDataTemplate = XamlReader.Load ( DisplayModeControlTemplate ) as DataTemplate ) ; } private const string DisplayModeControlTemplate = `` < DataTemplate '' + `` xmlns='http : //schemas.microsoft.com/winfx/2006/xaml/presentation ' > '' + `` < Border Background='GreenYellow ' > '' + `` < TextBlock Text= ' { Binding Path=DataSourceRoot.RootObject.ErgebnisAnzeige } ' Margin= ' 3 ' Foreground='Red ' `` + `` TextAlignment=\ '' { Binding Properties [ Microsoft.LightSwitch : RootControl/TextAlignment ] } \ '' '' + `` VerticalAlignment=\ '' { Binding Properties [ Microsoft.LightSwitch : RootControl/VerticalAlignment ] } \ '' / > '' + `` < /Border > '' + `` < /DataTemplate > '' ; private const string ControlTemplate = `` < DataTemplate '' + `` xmlns=\ '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation\ '' '' + `` xmlns : x=\ '' http : //schemas.microsoft.com/winfx/2006/xaml\ '' '' + `` xmlns : ctl=\ '' clr-namespace : EuvControlsExtension.Presentation.Controls ; assembly=EuvControlsExtension.Client\ '' > '' + `` < ctl : ProzessErgebnisEdit/ > '' + `` < /DataTemplate > '' ; } public class MtTemplateSelector : DataTemplateSelector { public DataTemplate UnknownTemplate { get ; set ; } public DataTemplate ZahlTemplate { get ; set ; } public DataTemplate FreitextTemplate { get ; set ; } public DataTemplate AuswahlTemplate { get ; set ; } public DataTemplate BoolTemplate { get ; set ; } public DataTemplate DatumTemplate { get ; set ; } public DataTemplate MessungTemplate { get ; set ; } public DataTemplate DateiPfadTemplate { get ; set ; } public DataTemplate OrdnerPfadTemplate { get ; set ; } public override DataTemplate SelectTemplate ( object item , DependencyObject container ) { switch ( GetDatenFormatEnum ( item ) ) { case DatenformatEnum.Zahl : return ZahlTemplate ; ... | Why is my custom control always read-only ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.