lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 technic...
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 ...
Can Scala collection 's seq/par/view/force be seen as a violation of the uniform return type principle ?
C#
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 ....
IEmployeeServiceIDepartmentServiceIOrderService ... public EmployeeService : IEmployeeService { private readonly IOrderService _orderSvc ; private readonly IDepartmentService _deptSvc ; private readonly IEmployeeRepository _empRep ; public EmployeeService ( IOrderService orderSvc , IDepartmentService deptSvc , IEmploye...
Why not lump all service classes into a Factory method ( instead of injecting interfaces ) ?
C#
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 fun...
protected override void OnStartup ( StartupEventArgs e ) { base.OnStartup ( e ) ; TestWindow t = new TestWindow ( ) ; t.ShowDialog ( ) ; }
Why would Window.Close event propagate ?
C#
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 ...
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#
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 tr...
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#
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 ( )...
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#
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 signatu...
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.Co...
Creating a generic retrieval method to return 1 record
C#
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 ...
< 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 : ...
How do I bind an ObservableCollection to an AvalonDock DocumentPaneGroup ?
C#
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 d...
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...
Roles , Abstract Pattern , Loose Coupling
C#
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 wh...
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 acce...
How to augment anonymous type object in C #
C#
( 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 retaine...
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 ) ]...
NamedScope and garbage collection
C#
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...
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 < ...
LINQ : How to force a value based reference ?
C#
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...
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 ( ) { v...
Behavior of Reset method of List < T > .Enumerator
C#
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-su...
-- -- -- 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#
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 pr...
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#
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 comma...
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 ) ) { Curr...
Ca n't read root
C#
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 ...
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 > ( ...
C # Dependency Injection problem
C#
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 valu...
[ 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 ...
Simple WCF service , not all parameters from client making through to the service
C#
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 n...
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 ) ''...
Why overloading does not work ?
C#
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 :
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++ ) { ...
What is the WPF equivalent of displaying an Image on a Canvas using ImageData in Java SWT
C#
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 befo...
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 ( strin...
Can not cast a generic type to list in C #
C#
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 ! ?
var ( mult , sum ) = MultSum ( a , b ) ; var ( _ , sum ) = MultSum ( a , b ) ;
Are there any performance benefits in C # discards ?
C#
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 wou...
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 = myUp...
Unboxing nullable types - workaround ?
C#
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...
public void Run ( ) { while ( ! StopRequested ) DoWork ( ) ; }
Options for informing a Thread to stop
C#
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 ...
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 ) ; v...
Am i using correctly Unit of Work here ? ( Entityi Framework 4 POCO )
C#
output ( 32 bit ) : output ( 64 bit ) : Storing the ints alone ( in an array ) would require about 80000 .
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#
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 wit...
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.E...
C # if else exception
C#
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 im...
[ OperationContract ] [ WebInvoke ( Method = `` POST '' , RequestFormat = WebMessageFormat.Json , ResponseFormat = WebMessageFormat.Json , BodyStyle = WebMessageBodyStyle.WrappedRequest , UriTemplate = `` /AddNewActivity '' ) ] String AddNewActivity ( String jsonObject ) ; public String AddNewActivity ( String jsonObje...
Client Website always return Null Json String
C#
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 ?
MyForm f ; using ( f = new MyForm ( ) ) { f.ShowDialog ( ) ; } using ( MyForm f = new MyForm ( ) ) { f.ShowDialog ( ) ; }
C # : `` using '' when instantiating a form ?
C#
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 wi...
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.FullScreenRefreshRateInHert...
Multisampling does n't work in exclusive mode
C#
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 ?
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#
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 ...
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 ...
Using specific patterns to implement interfaces
C#
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 objec...
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 ( ...
What data structure to use in my example
C#
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 ...
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 '' , ( ...
Is “ If ” condition better than ? ? and casting
C#
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...
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#
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...
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#
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 c...
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#
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 :
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 ) ) ; ...
How to sort based on ordering
C#
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 ha...
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....
DisplayNameAttribute for anonymous class
C#
[ 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 g...
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 ( ser...
store retrieve IObservable subscription state in Rx
C#
For instance , along the lines of : vsWhich is better both for clarity , ease of use , and most importantly performance .
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#
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 ?
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#
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 IPower...
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 , ICompone...
How to implement multiple interfaces with same methods inhereted from parent interfaces
C#
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 .
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#
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 w...
`` querytype1 '' = Particular LINQ expression '' querytype2 '' = Particular LINQ expression
Caching LINQ expressions by equality
C#
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 ...
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 = fals...
How do I allow a .NET Core console app FTP connection through Windows Firewall ?
C#
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...
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 ( ) ; } } clas...
Why does this object 's type show no interfaces via reflection , despite implementing at least two ?
C#
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 ...
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#
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 centraliz...
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#
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 :...
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....
Handle http fired by Flex in C # server
C#
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 soluti...
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 ( )...
Write to open FileStream using reactive programming
C#
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 se...
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#
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 .
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#
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 t...
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...
EF returning different values than query
C#
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 ma...
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 ) ...
Is it atomic this `` Int64 '' surrogate ?
C#
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 unexpe...
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 : Clie...
Underlying connection was closed with linkedin
C#
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 : Wh...
> 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#
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 t...
//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 '' ) {...
more short code about if statement
C#
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 fi...
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#
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 ?
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 ) ; retu...
Calculate PI using sum of inverse squares
C#
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...
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 ...
Custom Rx operator for throttling only when there 's a been a recent value
C#
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 ?
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#
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 f...
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#
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 t...
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 ( ++iteratio...
Surprisingly different performance of simple C # program
C#
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 ...
int i = 0 ; bool b = i++ == i ; Console.WriteLine ( b ) ; int i = 0 ; bool b = i == i++ ; Console.WriteLine ( b ) ;
C # Post Increment
C#
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 f...
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#
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 ...
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.Memor...
Why does Volatile.Read take ref parameter ?
C#
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 l...
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#
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 w...
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 -- + *smallerPoint...
How to carry number from decimal to whole byte array
C#
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 m...
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 ...
Why is one method for finding the position of the nth occurrence of a character in a string much faster than another ?
C#
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 - ...
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#
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 u...
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 ( Cu...
performance consideration when using properties multiple times
C#
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 % ...
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.ToLo...
SQL Server and performance for dynamic searches
C#
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 ) , o...
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#
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 su...
var query = new { query = new { match = new { field= '' status '' , query= '' success '' } } , range = new { ? } } ;
Elasticsearch.net - Range Query
C#
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 .
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 , DateT...
Lock an object that creates ID
C#
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 Logi...
services.AddAuthentication ( CookieAuthenticationDefaults.AuthenticationScheme )
How to Logout user from a particular session Identity Server 4 , .Net Core ?
C#
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 Syste...
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 ( `` Pers...
EqualityComparer < T > .Default does n't return the derived EqualityComparer
C#
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 .
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...
Explain the code : c # locking feature and threads
C#
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 Stud...
using ( DisposableFoo foo = new DisposableFoo ( ) )
Is 'using ' a C # keyword ?
C#
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 ?
@ 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 ...
Getting information from my controller into onclick confirm ( alert )
C#
I recently asked a question here , and someone provided this answer : What is that = > doing ? It 's the first time I 'm seeing this .
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.DownloadS...
What is the symbol `` = > '' doing after my method in this C # code ?
C#
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 ...
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 . ...
When to use which for ?
C#
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...
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...
Multiplication with .NET regular expressions
C#
For ex :
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#
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 s...
EndpointAddress endpointAddress = new EndpointAddress ( `` net.tcp : //süd:8001/EmployeeService '' ) ;
German umlauts in EndpointAddress with net.tcp
C#
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 attr...
[ 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 ) ...
Is this correct way to implement MVVM ?
C#
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 t...
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 // ...
Why does the variance of a class type parameter have to match the variance of its methods ' return/argument type parameters ?
C#
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 u...
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#
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 acc...
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 ...
Why do CanRead and CanWrite return false in C # for properties with overridden accessors ?
C#
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 de...
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#
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 ...
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 , StringC...
Why does n't String.Contains call the final overload directly ?
C#
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 downcast...
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 ( ) { Cons...
What is the use case for C # allowing to use new on a virtual method ?
C#
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 '' .
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 ; Consol...
Does I < D > re-implement I < B > if I < D > is convertible to I < B > by variance conversion ?
C#
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 capture...
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 callingMemberN...
ExecutionContext does not flow up the call stack from async methods
C#
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....
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 ( ) ...
C # function uses extension function but VB equivalent does not ?
C#
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 abou...
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 ...
Foreach with a select/from in square brackets ?
C#
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 charactersVali...
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 , ISpecificati...
Specification pattern async
C#
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 ...
[ a-aA-Z ] ( 1 ) \d3
RegExp multiply matches in text
C#
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 ...
< 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 ; ass...
Why is my custom control always read-only ?