lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I 'm using this code with .NET 3.0but when i tried it in .NET 2.0 , I think Action has type parameter like this : How to implement the first code in .NET 2.0 ?
Action xx = ( ) = > button1.Text = `` hello world '' ; this.Invoke ( xx ) ; Action < T >
Update control from another thread in C # 2.0
C#
Could I have something like this : So , one method returning different types based on T. Of course , there would be logic inside the method to ensure it was returning the correct thing.I can never get something like this to run . It complains that it ca n't cast the return value to T :
int x = MyMethod < int > ( ) ; string y = MyMethod < string > ( ) ; public static T MyMethod < T > ( ) { if ( typeof ( T ) == typeof ( Int32 ) ) { return 0 ; } else { return `` nothing '' ; } }
Using generic methods , is it possible to get different types back from the same method ?
C#
In my application I have method looks like this : And each of the internal methods looks like this : For example , DoFirstSubOperation ( ) and DoSecondSubOperation ( ) complete successfully , but DoThirdSubOperation ( ) fails.How do I rollback the changes made by the first two functions ? This approach has not brought ...
public static bool DoLargeOperation ( ) { bool res = true ; res = res & & DoFirstSubOperation ( ) ; res = res & & DoSecondSubOperation ( ) ; res = res & & DoThirdSubOperation ( ) ; return res ; } public static bool DoFirstSubOperation ( ) { using ( var context = new EntityFrameworkContext ( ) ) { // data modification ....
How to use transactions for different contexts ?
C#
I have enum lets say for example : And have two classes . which have property of enum.Now in Windows Forms Designer , I want to hide the red flag only from the Color enumeration for ClassB only.I know that I can create a separated enum . but why duplicate values ? I gave a simple example only . Something I guess might ...
public enum Color { red , green , blue } public class ClassA { public Color Color { get ; set ; } } public class ClassB { [ InvisibleFlag ( Color.red ) ] // I want something like that public Color Color { get ; set ; } }
Is there a way for hiding some enum values for specific property of class ?
C#
I tried disassembling a C # created executable , but I could n't come to a conclusion . What I 'd like to know is that if for the CLR c # 's delegates are really special entities or just a compiler sugar ? I ask this because I 'm implementing a language that compiles to C # , and it would be much more interesting for m...
void Main ( ) { Func < int , int , int > add = delegate ( int a , int b ) { return a + b ; } ; } class AnonFuncion__1219023 : Fun3 { public override int invoke ( int a , int b ) { return a + b ; } } class Program { static int add ( int a , int b ) { return a + b ; } static void Main ( ) { Func < int , int , int > add =...
Are Delegates more lightweight than classes ?
C#
I was recently going through a garbage collection article and decided to play along and attempt to gain a greater understanding . I coded the following , playing around with the using statement , but was surprised with the results ... I expected e.Parent.Name outside of the using block to go ka-blooey.What exactly is g...
static void Main ( string [ ] args ) { Employee e = new Employee ( ) ; using ( Parent p = new Parent ( ) ) { p.Name = `` Betsy '' ; e.Parent = p ; Console.WriteLine ( e.Parent.Name ) ; } Console.WriteLine ( e.Parent.Name ) ; Console.ReadLine ( ) ; } public class Employee { public Parent Parent ; } public class Parent :...
C # Memory allocation/de-allocation question regarding scope
C#
I have a tray icon that needs to display two icons : If there is network connectivity , display a green circle with a check markIf there is n't network connectivity , display a red circle with an XSo what I have is : So I 'm thinking of starting a new thread or using the background worker progress because the tray icon...
using System.Net.NetworkInformation ; bool isConnected = NetworkInterface.GetIsNetworkAvailable ( ) Form.Invoke ( delegate , object [ ] ) while ( true ) { System.Threading.Thread.Sleep ( 1000 ) ; isConnected = NetworkInterface.GetIsNetworkAvailable ( ) ; if ( isConnected ) notifyIcon.Icon = `` ConnectedIcon.ico '' ; el...
C # threading and polling
C#
I want to create a list of methods to execute . Each method has the same signature.I thought about putting delegates in a generic collection , but I keep getting this error : 'method ' is a 'variable ' but is used like a 'method'In theory , here is what I would like to do : Any ideas on how to accomplish this ? Thanks ...
List < object > methodsToExecute ; int Add ( int x , int y ) { return x+y ; } int Subtract ( int x , int y ) { return x-y ; } delegate int BinaryOp ( int x , int y ) ; methodsToExecute.add ( new BinaryOp ( add ) ) ; methodsToExecute.add ( new BinaryOp ( subtract ) ) ; foreach ( object method in methodsToExecute ) { met...
Can I use a List < T > as a collection of method pointers ? ( C # )
C#
If I have : And then : Would 12 get boxed ? I ca n't imagine it would , I 'd just like to ask the experts .
void Foo ( dynamic X ) { } Foo ( 12 ) ;
C # - Are Dynamic Parameters Boxed
C#
I 've seen several references to WebServiceHost2Factory as the class to use to effectively handle errors in WCF Rest services . Apparently with that class , I just had to throw a WebProtocolException and the body of the response would contain pertinent information . That class seems to have fallen out of favor now . Is...
[ Description ( `` Performs a full enroll and activation of the member into the Loyalty program '' ) ] [ OperationContract ] [ WebInvoke ( Method = `` POST '' , UriTemplate = `` /fullenroll/ { clientDeviceId } '' , BodyStyle = WebMessageBodyStyle.Bare , RequestFormat = WebMessageFormat.Json , ResponseFormat = WebMessag...
Now that WebServiceHost2Factory is dead , how do I return error text from a WCF rest service ?
C#
I use var whenever I can since it 's easier not to have to explicitly define the variable.But when a variable is defined within an if or switch statement , I have to explicitly define it . Is there a way to use var even if the variable is defined inside an if or switch construct ?
string message ; //var message ; < -- - gives errorif ( error ) { message = `` there was an error '' ; } else { message = `` no error '' ; } Console.WriteLine ( message ) ;
Is there a way to use var when variable is defined in an if/else statement ?
C#
Consider this code : I want write this code with switch case : But we ca n't write this in C # .What is the clear way for write the above code , knowing that results is a long [ ] ?
if ( results.Contains ( 14 ) ) { //anything } else if ( results.Contains ( 15 ) ) { //anything } else if ( results.Contains ( 16 ) ) { //anything } switch ( results ) { case results.Contains ( 14 ) : }
Clear way to write if statement
C#
I get a file loader exception ( first chance ) at the InitializeComponent-method or the debugger breaks at the x : Class attribute of the xaml-root of multiple WPF user controls . Everything works fine despite the fact that the exceptions slow down navigation by a lot.This is the exception message : Could not load file...
Assembly manager loaded from : C : \Windows\Microsoft.NET\Framework\v4.0.30319\clr.dllRunning under executable D : \Development\Product\Main\src\Company.Product \bin\Debug\Product.vshost.exe -- - A detailed error log follows . === Pre-bind state information ===LOG : DisplayName = Company.Product .UserInterface , Versio...
FileLoadException At InitializeComponent or x : Class=
C#
According to below link when you do a 'Response.Redirect ' during any posts inside update panel , it would send a HTTPResponseCode of 200 and Ajax javascripty libraries will take over from there to redirect the user to a page.https : //connect.microsoft.com/VisualStudio/feedback/details/542238/redirecting-during-ajax-r...
HttpApplication app = ( HttpApplication ) sender ; if ( app.Response.StatusCode == 302 & & ! app.Response.RedirectLocation.Contains ( `` MyValue '' ) ) { // Add MyValue to URL }
Intercept redirects from UpdatePanel Posts
C#
I realize this is partially subjective , but I 'm generally curious as to community opinion and have not been able to successfully find an existing question that tackles this issue.I am in a somewhat religious debate with a fellow coworker about a particular Select statement in a L2EF query.Caveats : This is Linq-to-En...
.Select ( r = > { r.foo.Bar = r.bar ; r.foo.Bar.BarType = r.Alpha ; if ( r.barAddress ! = null ) { r.foo.Bar.Address = r.barAddress ; r.foo.Bar.Address.State = r.BarState ; } if ( r.baz ! = null ) { r.foo.Bar.Baz = r.baz ; if ( r.bazAddress ! = null ) { r.foo.Bar.Baz.Address = r.bazAddress ; r.foo.Bar.Baz.Address.State...
When does a lambda in an extension method do too much ?
C#
First off , I 'm new to LINQ , so I do n't really know the ins and outs of it . I 'm attempting to use it in some code at the minute , and according to my diagnostics it appears to be about as fast as using a for loop in the same way . However , I 'm not sure how well this would scale as the lists which I am working wi...
partial class Actor { public virtual bool checkActorsForCollision ( Vector2 toCheck ) { Vector2 floored=new Vector2 ( ( int ) toCheck.X , ( int ) toCheck.Y ) ; if ( ! causingCollision ) // skip if this actor does n't collide return false ; foreach ( Actor actor in from a in GamePlay.actors where a.causingCollision==tru...
New to LINQ : Is this the right place to use LINQ ?
C#
I am running Ubuntu 64bit linux.andI create a folder named `` test '' .I cd into test.I then run : The console returns : I am not sure what to do to remedy this .
No LSB modules are available.Distributor ID : UbuntuDescription : Pop ! _OS 18.10Release : 18.10Codename : cosmic dotnet version : 3.0.100 dotnet new consoledotnet run *** stack smashing detected *** : < unknown > terminated
dotnet run gives me `` *** stack smashing detected *** : < unknown > terminated ''
C#
We have a Grid that 's bound to a List < T > of items . Whenever the user hits `` Refresh '' , changes are obtained from the database , and the bound list is updated . I 'm running into a problem where duplicate items are being added to the grid , and I can not figure out why.The database call returns two values : a Li...
public void FindUpdates ( IList < MyClass > existingRecords , IList < MyClass > updatedRecords , List < int > updatedIds , out IDictionary < int , int > existing , out IDictionary < int , int > updated , out List < int > updates , out List < int > removes , out List < int > adds ) { updates = new List < int > ( ) ; rem...
Is there any reason an existing item would not be found in List < T > in this code block ?
C#
I need to programmatically open the android contacts app using an intent with Xamarin Forms/Android . When the Add New Contact activity/screen comes up , I would like to pre-populate it with the following fields : Name ( this is populating ) Phone ( this is populating ) Street ( Not populating ) City ( Not populating )...
public void AddContact ( string name , string [ ] phoneNumbers , string streetAddress , string city , string state , string postalCode , CountryValues countrycode ) { // get current activity var activity = CrossCurrentActivity.Current.Activity ; // create add contact intent var intent = new Intent ( Intent.ActionInsert...
How to insert contacts with city , street , postal code , country in Xamarin Android using intent and activity ?
C#
I noticed this strange behavior yesterday when putting together a demo application for WP . Usually I never pass in plain items , and never the ‘ same ’ - but this time I did.When bound to an observablecollection of type int or string , if the value is the same , the control will add first one item , then two , then th...
< phone : PhoneApplicationPagex : Class= '' Bug.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' xmlns : shell= '' clr-namespace : ...
Why does the LongListSelector add extra items if the collection values are identical ?
C#
I 'm trying to use Autofac to find the most greedy constructor in a referenced dll.It 's not finding it and only finds the one parameterless constructor.These are the two ctors : Now this is how I register the stuff with autofac : nothing too complex.But this is the only weird thing I can think of.typeof ( MvcApplicati...
public SimpleAuthenticationController ( ) { .. } public SimpleAuthenticationController ( IAuthenticationCallbackProvider callbackProvider ) : this ( ) var builder = new ContainerBuilder ( ) ; builder.RegisterType < SampleMvcAutoAuthenticationCallbackProvider > ( ) .As < IAuthenticationCallbackProvider > ( ) ; builder.R...
Autofac not finding the most greedy constructor
C#
I have a method which can be written pretty neatly through method chaining : However I 'd like to be able to do some checks at each point as I wish to provide helpful diagnostics information if any of the chained methods returns unexpected results.To achieve this , I need to break up all my chaining and follow each cal...
return viewer.ServerReport.GetParameters ( ) .Single ( p = > p.Name == Convention.Ssrs.RegionParamName ) .ValidValues .Select ( v = > v.Value ) ; return viewer.ServerReport.GetParameters ( ) .Assert ( result = > result.Any ( ) , `` The report contains no parameter '' ) .SingleOrDefault ( p = > p.Name == Convention.Ssrs...
LINQ method chaining and granular error handling
C#
in my application I 've got three interfaces ICapture < T > , IDecoder < T , K > , and IBroadcaster < K > .Now I implement for example a VideoCapture class inheriting from Capture < IntPtr > ( IntPtr is the raw data produced by the class ) . When data is generated by an object of VideoCapture , I firstly want to decode...
var data = videoCapture.GetData ( ) ; var decoded = decoder.Decode ( data ) ; broadcaster.Broadcast ( decoded ) ; var handler1 = new CaptureHandler ( ) ; var handler2 = new DecodeHandler ( ) ; handler1.SetNext ( handler2 ) ; handler1.Handle ( object ) ;
Object manipulation chaining
C#
This is the code I have but it 's to slow , any way to do it faster..the number range I 'm hitting is 123456789 but I ca n't get it below 15 seconds , and I need it to get below 5 seconds..sum = ( n ( n+1 ) ) /2 is not giving me the results I need , not calculating properly..For N = 12 the sum is 1+2+3+4+5+6+7+8+9+ ( 1...
long num = 0 ; for ( long i = 0 ; i < = n ; i++ ) { num = num + GetSumOfDigits ( i ) ; } static long GetSumOfDigits ( long n ) { long num2 = 0 ; long num3 = n ; long r = 0 ; while ( num3 ! = 0 ) { r = num3 % 10 ; num3 = num3 / 10 ; num2 = num2 + r ; } return num2 ; } [ Test ] public void When123456789_Then4366712385 ( ...
Get sum of each digit below n as long
C#
I am looking for a way to hold big 3d sparse array structure into memory without waste a lot of memory . Here I 've done an experiment with arrays of longs : If you want to test it set the COMPlus_gcAllowVeryLargeObjects environment variable ( Project Properties - > Debug ) to 1 or change the JMAX . And this is the out...
using System ; using System.Diagnostics ; using System.Runtime ; namespace ConsoleApp4 { public class Program { static Process proc = Process.GetCurrentProcess ( ) ; const int MB = 1024 * 1024 ; const int IMAX = 5 ; const int JMAX = 100000000 ; public static void ShowTextWithMemAlloc ( string text ) { proc.Refresh ( ) ...
How a big array allocates memory ?
C#
I have 9 GB of data , and I want only 10 rows . When I do : I get an OutOfMemoryException . I would like to use an OrderByAndTake method , optimized for lower memory consumption . It 's easy to write , but I guess someone already did . Where can I find it.Edit : It 's Linq-to-objects . The data comes from a file . Each...
data.OrderBy ( datum = > datum.Column1 ) .Take ( 10 ) .ToArray ( ) ;
Memory optimized OrderBy and Take ?
C#
I had very simple code which worked fine for me : I 've updated OAuth 's NuGet packages and rewrite the code this way : but PrepareRequestUserAuthorizationAsync throws exception `` Attempt by method 'DotNetOpenAuth.OAuth2.WebServerClient+d__3.MoveNext ( ) ' to access method 'System.Collections.Generic.List ` 1..ctor ( ...
var url = System.Web.HttpContext.Current.Request.Url ; Uri callbackUrl = new System.Uri ( url , `` oAuth2CallBack '' ) ; var ub = new UriBuilder ( callbackUrl ) ; // decodes urlencoded pairs from uri.Query to varvar httpValueCollection = HttpUtility.ParseQueryString ( callbackUrl.Query ) ; httpValueCollection.Add ( Url...
PrepareRequestUserAuthorizationAsync fails
C#
I 'm working on a regex for validating urls in C # . Right now , the regex I need must not match other http : // but the first one inside the url . This was my first try : But this regex does not work ( even removing ( ? ! https ? : \/\/ ) ) . Take for example this input string : Here is my first doubt : why does not t...
( https ? : \/\/.+ ? ) \/ ( .+ ? ) ( ? ! https ? : \/\/ ) http : //test.test/notwork.http : //test ( https ? : \/\/.+ ? ) \/ ( ( ? : ( ? ! https ? : \/\/ ) . ) * )
Lazy quantifier and lookahead
C#
In C # how can I create an IEnumerable < T > class with different types of objectsFor example : I want to do some thing like :
Public class Animals { Public class dog { } Public class cat { } Public class sheep { } } Foreach ( var animal in Animals ) { Print animal.nameType }
In C # how can I create an IEnumerable < T > class with different types of objects >
C#
I came about something rather baffling in C # just recently . In our code base , we have a TreeNode class . When changing some code , I found that it was impossible to assign a variable to the Nodes property . On closer inspection it became clear that the property is read-only and this behavior is to be expected . What...
using System.Collections.Generic ; namespace ReadOnlyProperty { public class TreeNode { private readonly IList < TreeNode > _nodes = new List < TreeNode > ( ) ; public IList < TreeNode > Nodes { get { return _nodes ; } } } public class TreeBuilder { public IEnumerable < TreeNode > AddSomeNodes ( ) { yield return new Tr...
Setting a read-only property with anonymous type
C#
Before you answer , look at this post.Getting an answer for that first may resolve the issue below.This is a problem that just started with Windows 10 ( Universal Apps ) . In Windows 8.1 , and every other XAML technology , this technique worked flawlessly . Here 's the setup in a blank universal app project:1 . Static ...
public static class MySettings { public static Brush GetAccentBrush ( DependencyObject d ) { return ( Brush ) d.GetValue ( AccentBrushProperty ) ; } public static void SetAccentBrush ( DependencyObject d , Brush value ) { d.SetValue ( AccentBrushProperty , value ) ; } public static readonly DependencyProperty AccentBru...
How can I bind to a null value inside a template in a Universal Windows App ?
C#
Can anyone explain , why we can do such thing and why we need thisWhy we need public inner whatever : struct , class , enum or static class ? I think that if it is inner then it must be only private or protected .
public class OuterClass { public class InnerClass { } }
public inner classes
C#
I have a game ( based on MonoGame / XNA ) with an update method like so : I would like to convert this to the Reactive pattern . My current solution is : I am new to Rx so I am still learning the best way of doing things . I read that Subject should be avoided and Observable.Create should be used instead . Is Subject a...
public void Update ( GameTime gameTime ) { component.Update ( gameTime ) ; } public void Initialize ( ) { updateSubject = new Subject < GameTime > ( ) ; component = new Component ( ) ; updateSubject.Subscribe ( ( gameTime ) = > component.Update ( gameTime ) ) ; } public void Update ( GameTime gameTime ) { updateSubject...
How do I turn a polling system into an Rx.Net IObservable ?
C#
There are some C style functions in an Objective C library I 'm binding to that I need access to in my application . Is it possible to add these into the bindings in any way so I can access them in my C # application ? EXAMPLE from Cocos2d : EDITLink to header with functions I 'm trying to import : http : //www.cocos2d...
void ccGLActiveTexture ( GLenum textureEnum ) { # if CC_ENABLE_GL_STATE_CACHE NSCAssert1 ( ( textureEnum - GL_TEXTURE0 ) < kCCMaxActiveTexture , @ '' cocos2d ERROR : Increase kCCMaxActiveTexture to % d ! `` , ( textureEnum-GL_TEXTURE0 ) ) ; if ( ( textureEnum - GL_TEXTURE0 ) ! = _ccCurrentActiveTexture ) { _ccCurrentAc...
Is it possible to add C references to an objective c binding ?
C#
We 're trying to figure out when exactly an Entity Framework Database Initializer runs . MSDN says initializion happens the `` first time '' we access the database . When is `` first time '' ? MSDN contradicts itself , stating that initialization runs the first time an instance of a DbContext is used but also the first...
public HttpResponseMessage PostEvent ( EventDTO eventDTO ) { var ev = new Event ( ) { Id = eventDTO.Id , Name = eventDTO.Name } ; using ( AttendanceContext db = new AttendanceContext ( ) ) { db.Events.Add ( ev ) ; db.SaveChanges ( ) ; } return Ok ( ) ; }
When exactly is the `` first time '' a DbContext accesses the database ?
C#
Here is what i have so far : it works on my LocalHost Database , and I can load my Data from it.however , I have a server , installed sqlserver with my database on that , basicaly when i change my sqlcommands connecting string this work but in some part of my program I used entity framework and have no idea how to chan...
< add name= '' gymEntities1 '' connectionString= '' metadata=res : //*/DateModel.csdl|res : //*/DateModel.ssdl|res : //*/DateModel.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source= . ; initial catalog=gym ; user id=sa ; password=xxxx ; MultipleActiveResultSets=True ; App=EntityFra...
Change Entity Framework Connecting String To Server
C#
I am building a simple Guard API to protect against illegal parameters being passed to functions and so on.I have the following code : At the moment the code can be used in a similar way to ( note this is just a dumb example ) : This all works fine . What I want to be able to do now is extend the API to include child p...
public static class Guard { public static GuardArgument < T > Ensure < T > ( T value , string argumentName ) { return new GuardArgument < T > ( value , argumentName ) ; } } public class GuardArgument < T > { public GuardArgument ( T value , string argumentName ) { Value = value ; Name = Name ; } public T Value { get ; ...
How to build a Fluent Nested Guard API
C#
Im trying to see how the fence is applied.I have this code ( which Blocks indefinitely ) : Writing volatile bool _complete ; solve the issue .Acquire fence : An acquire-fence prevents other reads/writes from being moved before the fence ; But if I illustrate it using an arrow ↓ ( Think of the arrowhead as pushing every...
static void Main ( ) { bool complete = false ; var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! complete ) toggle = ! toggle ; } ) ; t.Start ( ) ; Thread.Sleep ( 1000 ) ; complete = true ; t.Join ( ) ; // Blocks indefinitely } var t = new Thread ( ( ) = > { bool toggle = false ; while ( ! complete ) ↓↓↓↓↓...
Volatile fence demo ?
C#
I have the following domain model : I implemented IUserType so I can map each name to a single database column with the full name.Queries like this work : But I ca n't query like this : Can I make NHibernate work with this ?
public class Name { private readonly string fullName ; public Name ( string fullName ) { this.fullName = fullName } public string FullName { get { return fullName ; } } public string FirstName { get { /* ... */ } } public string MiddleNames { get { /* ... */ } } public string LastName { get { /* ... */ } } public stati...
Can I query a UserType with several properties mapped to a single column ?
C#
If an object has a Single Responsibility , can the following be acceptable : i.e . using a supplied collaborator ( which also helps to stop the domain model being anemic ) .Or should it be :
public class Person { public string Name ; public DateTime DateOfBirth ; private IStorageService _storageService ; public Person ( IStorageService storageService ) { _storageService = storageService } public void Save ( ) { _storageService.Persist ( this ) ; } } public class Person { public string Name ; public DateTim...
Single Responsibility and dependencies
C#
Is there any chance that this statement would return truecan a very fast machine return true for this statement , I tried on several machines and its always false ?
DateTime.Now == DateTime.Now
DateTime.Now retrieval speed
C#
I am having a problem understanding how polymorphism works when using generics . As an example , I have defined the following program : I can then do this , which works just fine : I have many classes that implement MyInterface . I would like to write a method that can accept all MyContainer objects : Now , I 'd like t...
public interface IMyInterface { void MyMethod ( ) ; } public class MyClass : IMyInterface { public void MyMethod ( ) { } } public class MyContainer < T > where T : IMyInterface { public IList < T > Contents ; } MyContainer < MyClass > container = new MyContainer < MyClass > ( ) ; container.Contents.Add ( new MyClass ( ...
Please help me understand polymorphism when using generics in c #
C#
i see this Question best-way-to-clear-contents-of-nets-stringbuilder/the answerers set the length to zero and also worries about capacity ? does it really matter to set capacity ? f we dis-assemble .net 4.5 Library , navigate to System.Text.StringBuilderis it really matters to set capacity when we already set its lengt...
/// < summary > /// Removes all characters from the current < see cref= '' T : System.Text.StringBuilder '' / > instance . /// < /summary > /// /// < returns > /// An object whose < see cref= '' P : System.Text.StringBuilder.Length '' / > /// is 0 ( zero ) . /// < /returns > [ __DynamicallyInvokable ] public StringBuil...
is Capacity property of Stringbuilder really matters when we set its length to zero ?
C#
When creating webservices , in c # , I have found it very useful to pass back jagged arrays , i.e . string [ ] [ ] I also found a neat trick to build these in a simple way in my code , which was to create a List and convert it by doing a ToArray ( ) call.e.g.I would like to be able to employ a similar solution , but I ...
public string [ ] [ ] myws ( ) { List < string [ ] > output = new List < string [ ] > ( ) ; return output.ToArray ( ) ; }
converting List < List < string [ ] > > into string [ ] [ ] [ ] in c #
C#
It is very unpredictable result of code for me.I did not expect this code to produce such a result.So , I read Jeffrey Richter 's book ( clr ia c # ) and there is a example with this code.And , as some of you can suggest we can see in console four names.So , my question is : How do we get our names , if they are going ...
internal class ClassRoom { private List < String > _students = new List < string > ( ) ; public List < String > Students { get { return _students ; } } } ClassRoom classRoom = new ClassRoom { Students = { `` Mike '' , `` Johny '' , `` Vlad '' , `` Stas '' } } ; foreach ( var some in classRoom.Students ) { Console.Write...
Why does collection initializer work with getter-only property ?
C#
I develop a system with plugins , which loads assemblies at runtime . I have a common interface library , which i share between server and its plugins . But , when i perform LoadFrom for plugin folder and try to find all types , which implement common interface IServerModule i get runtime exception : The type 'ServerCo...
foreach ( var dll in dlls ) { var assembly = Assembly.LoadFrom ( dll ) ; var modules = assembly.GetExportedTypes ( ) .Where ( type = > ( typeof ( IServerModule ) ) .IsAssignableFrom ( type ) & & ! type.IsAbstract & & ! type.IsGenericTypeDefinition ) .Select ( type = > ( IServerModule ) Activator.CreateInstance ( type )...
How to load assembly correctly
C#
I am using asp.net web api 2 and Entity Framework 6.Original pseudo codeModified codeBefore my change everything ran synchronously.After my change the call to a remote service which is calling again a database is done the async-await way.Then I do a sync call to a rendering library which offers only sync methods . The ...
public IHttpActionResult GetProductLabel ( int productId ) { var productDetails = repository.GetProductDetails ( productId ) ; var label = labelCalculator.Render ( productDetails ) ; return Ok ( label ) ; } public async Task < IHttpActionResult > GetProductLabel ( int productId ) { var productDetails = await repository...
async await calling long running sync AND async methods
C#
My entity `` Progetto '' map a view with name VW_AMY_PRG_WCS_LookupProgetto has five navigations property : ClienteDiFatturazione , ClienteDiLavorazione , PercentualeSuccesso , Agente having multiplicity 0..1 and DocumentiWcs having mupltiplicity *When I run this simple statement in LINQPadthe sql generated isI wonder ...
var prj = Progetti.AsQueryable ( ) ; prj.ToList ( ) ; SELECT [ Extent1 ] . [ IdProgetto ] AS [ IdProgetto ] , [ Extent1 ] . [ IdSerie_Progetto ] AS [ IdSerie_Progetto ] , [ Extent1 ] . [ Importo ] AS [ Importo ] , [ Extent1 ] . [ Data_Prevista_Chiusura ] AS [ Data_Prevista_Chiusura ] , [ Extent1 ] . [ IdStato ] AS [ Id...
EF Linq to Entities calling ToList ( ) on entity set generates SQL command containing multiple left outer join
C#
Since I have another method where the only difference is the expression in the return statement , how to pass Expression.OrElse as a parameter to the method ( my other method uses AndAlso ) ? Since the methods are close to identical I would like one common method with the expression passed as a parameter.I 've tried pa...
public static Expression < Func < T , bool > > OrElse < T > ( this Expression < Func < T , bool > > expr1 , Expression < Func < T , bool > > expr2 ) { ParameterExpression parameter = Expression.Parameter ( typeof ( T ) ) ; ReplaceExpressionVisitor leftVisitor = new ReplaceExpressionVisitor ( expr1.Parameters [ 0 ] , pa...
Passing a BinaryExpression as parameter
C#
I 'm programming an apartment & house rental site . Since there are never more than 10'000 properties for rent , it 's no problem to load em all into memory . Now , when a users want to search for a specific one , he can define very much filters for price , room , escalator etc.Every property has a very different set o...
namespace Test { class Program { static void Main ( string [ ] args ) { PropertyList p = new PropertyList ( ) ; long startTime = DateTime.Now.Ticks ; for ( int i = 0 ; i < 100 ; i++ ) { p.Search ( ) ; } Console.WriteLine ( ( DateTime.Now.Ticks - startTime ) / 10000 ) ; } } class PropertyList { List < Property > propert...
V8-like Hashtable for C # ?
C#
I 've written the following LINQ query : The objective is to retrieve a list of the countries represented by the competitors found in the system . 'countries ' is an array of ISOCountry objects explicitly created and returned as an IQueryable < ISOCountry > ( ISOCountry is an object of just two strings , isoCountryCode...
IQueryable < ISOCountry > entries = ( from e in competitorRepository.Competitors join c in countries on e.countryID equals c.isoCountryCode where ! e.Deleted orderby c.isoCountryCode select new ISOCountry ( ) { isoCountryCode = e.countryID , Name = c.Name } ) .Distinct ( ) ; public class ISOCountry { public string isoC...
Tracking down a stack overflow error in my LINQ query
C#
I 'd like to implement a sort of Factory Pattern for XAML . I created an app for WinRT where I defined two xaml style files . Basically , what I 'd like to achieve ( if possible ) is to load one of the the two xaml file when the application starts.in the solution explorer I have this : CustomStyles foder contains the s...
public enum Style { Style_1 , Style_2 } < Style x : Key= '' Attribute_Label '' TargetType= '' TextBlock '' > < Setter Property= '' FontFamily '' Value= '' Segoe UI '' / > < Setter Property= '' Foreground '' Value= '' # 78CAB3 '' / > < Setter Property= '' FontSize '' Value= '' 15 '' / > < Setter Property= '' FontWeight ...
XAML WinRT - Factory Pattern for Custom Styles
C#
I 'm working on some test cases at the moment , and I 'm regularly finding that I 'm ending up with multiple asserts in each case . For example ( over-simplified and comments stripped for brevity ) : This looks acceptable in principle , but the point of the test is to verify that when the the class is instantiated with...
[ Test ] public void TestNamePropertyCorrectlySetOnInstantiation ( ) { MyClass myInstance = new MyClass ( `` Test name '' ) ; Assert.AreEqual ( `` Test Name '' , myInstance.Name ) ; } [ Test ] public void TestNamePropertyCorrectlySetOnInstantiation ( ) { MyClass myInstance ; string namePropertyValue ; Assert.DoesNotThr...
How to prevent 'over-testing ' in a test case ? ( C # /nUnit )
C#
I have following DbContext and I want to migrate it using Entity FramworkI ran the statement in the Package Manager Console to generate the configuration.But the generation has compilation errors because following namespaces/classes ca n't be found : .Any solutions on how the configuration could compile so I can add th...
public class TestDbContext : DbContext { public DbSet < State > States { get ; set ; } public DbSet < StateType > StateTypes { get ; set ; } public DbSet < Measure > Measures { get ; set ; } public DbSet < Priority > Priorities { get ; set ; } public DbSet < Task > Tasks { get ; set ; } public DbSet < TaskType > TaskTy...
EF Migration for Universal Windows Platform
C#
Whilst browsing through some legacy code , I was surprised to encounter an abstract override of a member that was abstract by itself . Basically , something like this : Is n't the distinction between a virtual or abstract member always available to the compiler ? Why does C # support this ? ( This question is not a dup...
public abstract class A { public abstract void DoStuff ( ) ; } public abstract class B : A { public override abstract void DoStuff ( ) ; // < -- - Why is this supported ? } public abstract class C : B { public override void DoStuff ( ) = > Console.WriteLine ( `` ! `` ) ; }
Why does C # support abstract overrides of abstract members ?
C#
I have a requirement to create some objects that implement a given interface , where the type of concrete implementation being created is based on an Enum value.I run into trouble when the different concrete implementations require different parameters at runtime.This example ( C # ) is fine : However , what happens if...
public enum ProductCategory { Modem , Keyboard , Monitor } public class SerialNumberValidatorFactory ( ) { public ISerialNumberValidator CreateValidator ( ProductCategory productCategory ) { switch ( productCategory ) { case ProductCategory.Modem : return new ModemSerialNumberValidator ( ) ; case ProductCategory.Keyboa...
Will the Factory Pattern solve my problem ?
C#
I have two download file methods , so I wanted to extract part which actually hits the disk to some helper/service class , but I struggle with returning that file to controller and then to userHow can I return from class that does not derives from Controller a file with that easy-to-work method from Mvc.ControllerBase....
public ( bool Success , string ErrorMessage , IActionResult File ) TryDownloadFile ( string FilePath , string FriendlyName ) { try { var bytes = File.ReadAllBytes ( FilePath ) ; if ( FilePath.EndsWith ( `` .pdf '' ) ) { return ( true , `` '' , new FileContentResult ( bytes , `` application/pdf '' ) ) ; } else { return ...
How to return ActionResult ( file ) from class that does not derive from Controller ?
C#
I am trying to pass multiple paths as arguments to a console application but am getting an `` Illegal characters in path '' error . It appears that something is mistaking the last two characters of the argument `` C : \test\ '' for an escaped double-quote.For example , if I create a new empty console application in C #...
static void Main ( string [ ] args ) { Console.WriteLine ( args [ 0 ] ) ; Console.ReadLine ( ) ; }
Why does C # appear to partially un-escape command line arguments ?
C#
I 'm confused is it possible to create a sdk-style .net framework project in Visual Studio ( to be more specific I use the latest VS2019 ) . Or it still requires manual manipulations ? I 'm interested in creating a new project not in migrating existed project from old .csproj file style to the new .csproj sdk-style.I '...
< Project Sdk= '' Microsoft.NET.Sdk '' >
How to create a sdk-style .net framework project in VS ?
C#
I have noticed a new tendency in .NET 4.0 , specifically in potentially multi-threaded scenarios , which is avoiding events , and providing subscriber methods instead.For example , System.Threading.Tasks.Task and Task < TResult > have ContinueWith ( ) methods instead of a Completed or Finished event . Another example i...
public event EventHandler Finished ; // orpublic IDisposable OnFinished ( Action continuation )
Subscriber method vs event
C#
Possible Duplicate : using statement with multiple variables I have several disposable object to manage . The CA2000 rule ask me to dispose all my object before exiting the scope . I do n't like to use the .Dispose ( ) method if I can use the using clause . In my specific method I should write many using in using : Is ...
using ( Person person = new Person ( ) ) { using ( Adress address = new Address ( ) ) { // my code } } using ( Person person = new Person ( ) ; Adress address = new Address ( ) )
How write several using instructions ?
C#
Apparently , Constrained Execution Region guarantees do not apply to iterators ( probably because of how they are implemented and all ) , but is this a bug or by design ? [ See the example below. ] i.e . What are the rules on CERs being used with iterators ? ( Code mostly stolen from here . )
using System.Runtime.CompilerServices ; using System.Runtime.ConstrainedExecution ; class Program { static bool cerWorked ; static void Main ( string [ ] args ) { try { cerWorked = true ; foreach ( var v in Iterate ( ) ) { } } catch { System.Console.WriteLine ( cerWorked ) ; } System.Console.ReadKey ( ) ; } [ Reliabili...
Do C # try-finally CERs break in iterators ?
C#
I 'm using Entity Framework 6.1 , and I have a code like this : And this generates : Find method returns a single result but it generates a TOP ( 2 ) query instead of 1 . Why ? Note : I 'm sure I 'm passing correct Id to the method , and yes , Id is the primary key .
Brand b ; using ( var ctx = new KokosEntities ( ) ) { try { b = ctx.Brands.Find ( _brands [ brandName ] .Id ) ; return b ; } catch ( Exception ex ) { _logger.Log ( LogLevel.Error , ex ) ; } } N'SELECT TOP ( 2 ) [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Name ] AS [ Name ] , [ Extent1 ] . [ OpenCartId ] AS [ OpenC...
Why Find method generates a TOP ( 2 ) query ?
C#
I want a single Regex expression to match 2 groups of lowercase , uppercase , numbers or special characters . Length needs to also be grater than 7.I currently have this expressionIt , however , forces the string to have lowercase and uppercase and digit or special character.I currently have this implemented using 4 di...
^ ( ? =.* [ ^a-zA-Z ] ) ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } $ class Program { private static readonly Regex [ ] Regexs = new [ ] { new Regex ( `` [ a-z ] '' , RegexOptions.Compiled ) , //Lowercase Letter new Regex ( `` [ A-Z ] '' , RegexOptions.Compiled ) , // Uppercase Letter new Regex ( @ '' \d '' , RegexOp...
Regex match 2 out of 4 groups
C#
I have a class that initializes a collection to a default state . When I load the object from some saved JSON it appends the values rather than overwriting the collection . Is there a way to have the JSON.Net replace the collection when deserializing rather than append the values ?
void Main ( ) { string probMatrix = `` { \ '' Threshold\ '' :0.0276 , \ '' Matrix\ '' : [ [ -8.9,23.1,4.5 ] , [ 7.9,2.4,4.5 ] , [ 9.4,1.4,6.3 ] ] } '' ; var probabiltyMatrix = JsonConvert.DeserializeObject < ProbabiltyMatrix > ( probMatrix ) ; probabiltyMatrix.Dump ( ) ; } // Define other methods and classes herepublic...
JSON.Net Collection initialized in default constructor not overwritten from deserialized JSON
C#
I am trying to use the new C # 7 pattern matching feature in this line of codeBut for some reason Resharper/Visual Studio 2017 is giving me a warning under is Customer with the following message The source expression is always of pattern 's type , matches on all non-null valuesBut customer can also be null right ? Can ...
if ( Customers.SingleOrDefault ( x = > x.Type == CustomerType.Company ) is Customer customer ) { ... }
Getting warning `` The source expression is always of pattern 's type , matches on all non-null values ''
C#
I 'm moving a object over a bunch of Buttons , and when this object is over a button I change the color of the border . This is no problem , I can do this through bindings , storyboards or style setters/Visual state . When I run this on my emulator it works nice and smooth , but when I run it on my windows phone , ther...
< Button x : Name= '' Button1 '' BorderThickness= '' 0 '' BorderBrush= '' Transparent '' > < Button.Template > < ControlTemplate x : Name= '' Control '' > < Path x : Name= '' CountryUser '' Style= '' { StaticResource style_ColorButton } '' Data= '' { Binding UserView.buttonData } '' Fill= '' { StaticResource ButtonBack...
Lag when changing color of button border on WP8
C#
I 'm currently looking at a copy-on-write set implementation and want to confirm it 's thread safe . I 'm fairly sure the only way it might not be is if the compiler is allowed to reorder statements within certain methods . For example , the Remove method looks like : Where hashSet is defined asSo my question is , give...
public bool Remove ( T item ) { var newHashSet = new HashSet < T > ( hashSet ) ; var removed = newHashSet.Remove ( item ) ; hashSet = newHashSet ; return removed ; } private volatile HashSet < T > hashSet ; public IEnumerator < T > GetEnumerator ( ) { return hashSet.GetEnumerator ( ) ; } var newHashSet = new HashSet < ...
Reordering of operations around volatile
C#
This is a little spooky.I 'm thinking there must be a setting somewhere that explains why this is happening.In our solution there are about 50 different projects . For the most part , the libraries start with the namespace OurCompany.We have OurComany.This.That and OurCompany.Foo.Bar ... etc.There is a namespace/class ...
OurCompany.Foo.Bar OurCompany.Some.Location.Foo Error 75 The type or namespace name 'MethodName ' does not exist in thenamespace 'OurCompany.Foo ' ( are you missing an assembly reference ? ) OurCompany.Some.Location.Foo.MethodName ( ) ; //OurCompany is redundant Some.Location.Foo.MethodName ( ) ; //Leaving out OurCompa...
C # : Why is First namespace redundant ?
C#
I am trying to get logging up and running in my C # console app based on .NET Core 2.1.I added the following code to my DI declaration : I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services , but I am getting the following error : Unhandled Exc...
var sc = new ServiceCollection ( ) ; sc.AddLogging ( builder = > { builder.AddFilter ( `` Microsoft '' , LogLevel.Warning ) ; builder.AddFilter ( `` System '' , LogLevel.Warning ) ; builder.AddFilter ( `` Program '' , LogLevel.Warning ) ; builder.AddConsole ( ) ; builder.AddEventLog ( ) ; } ) ; at Microsoft.Extensions....
Why does .NET Core DI container not inject ILogger ?
C#
There are many different ways to create objects in Powershell . I am posting this as a challenge to create objects purely in Powerhell . I am looking for a way to create objects using Add-Type that pass these requirements : Strongly-Typed object propertiesInstantiated , using : New-Object , [ My.Object ] : :New ( ) , [...
PS C : \ > $ memberDef = @ '' public String myString { get ; set ; } public int myInt { get ; set ; } '' @ PS C : \ > Add-Type -Namespace `` My.Namespace '' -Name `` Object '' -MemberDefinition $ memberDefPS C : \ > $ myObj = [ My.Namespace.Object ] @ { 'myString'='Foo ' ; 'myInt'=42 } PS C : \ > $ myObjmyString myInt ...
Defining Custom Powershell Objects
C#
After reading `` Odd query expressions '' by Jon Skeet , I tried the code below.I expected the LINQ query at the end to translate to int query = proxy.Where ( x = > x ) .Select ( x = > x ) ; which does not compile because Where returns an int . The code compiled and prints `` Where ( x = > x ) '' to the screen and quer...
using System ; using System.Linq.Expressions ; public class LinqProxy { public Func < Expression < Func < string , string > > , int > Select { get ; set ; } public Func < Expression < Func < string , string > > , int > Where { get ; set ; } } class Test { static void Main ( ) { LinqProxy proxy = new LinqProxy ( ) ; pro...
Why does this LINQ query compile ?
C#
I 've been scratching my head for a while with this . On my MainWindow I have an an Image who 's ToolTip should pop up the image at it 's actual size ( or with a height no larger than the MainWindow itself ) : ( MainWindow 's x : name is 'MW ' ) In another class elsewhere I am loading a BitmapImage into this image cont...
< Image x : Name= '' ss1 '' Grid.Column= '' 0 '' Grid.Row= '' 0 '' Margin= '' 0 '' > < Image.ToolTip > < ToolTip DataContext= '' { Binding PlacementTarget , RelativeSource= { RelativeSource Self } } '' > < Border BorderBrush= '' Black '' BorderThickness= '' 1 '' Margin= '' 5,7,5,5 '' > < Image Source= '' { Binding Sour...
WPF Image as ToolTip - DPI issue
C#
I have a string that has special characters like this example : 12345678912\rJ\u0011 because I need to have access to this special chars to configure my application . I want to display this string exactly like this in a TextBox field so everything I have tried so far results in a string where the character \u0011 tries...
string result = Regex.Replace ( ToLiteral ( this.Buffer ) , `` [ ^\x00-\x7Fd ] '' , c = > string.Format ( `` \\u { 0 : x4 } '' , ( int ) c.Value [ 0 ] ) ) .Replace ( @ '' \ '' , @ '' \\ '' ) ; public static string ToLiteral ( string input ) { using ( var writer = new StringWriter ( ) ) { using ( var provider = CodeDomP...
Render special character C #
C#
Case 1 : can be simplified asCase 2 : can not be simplified asQuestion : For the second case , why can not we just use [ ] [ ] instead of int [ ] [ ] ?
int [ ] data1 = new int [ ] { 1 , 2 , 3 } ; int [ ] data2 = new [ ] { 1 , 2 , 3 } ; int [ ] [ ] table1 = new int [ ] [ ] { new int [ ] { } , new int [ ] { 1 , 2 } } ; int [ ] [ ] table2 = new [ ] [ ] { new int [ ] { } , new int [ ] { 1 , 2 } } ;
Why can not we just use [ ] [ ] instead of int [ ] [ ] ?
C#
I have an issue with a navigation property in an entity framework project . Here is the class MobileUser : The relevant part is this navigation property : This is the class MobileDeviceInfo : As you can see , it implements IEquatable < MobileDeviceInfo > and overrides also Equals and GetHashCode from System.Object.I ha...
[ DataContract ] [ Table ( `` MobileUser '' ) ] public class MobileUser : IEquatable < MobileUser > { // constructors omitted ... . /// < summary > /// The primary-key of MobileUser . /// This is not the VwdId which is stored in a separate column /// < /summary > [ DataMember , Key , Required , DatabaseGenerated ( Data...
Why ICollection < > .Contains ignores my overridden Equals and the IEquatable < > interface ?
C#
I am currently trying to run some code when the debugger detaches from a process . It is easy to find out if a debugger is attached : My question is if there is a way ( preferable one that works for .NET , Windows Phone , WinRT ) to get an event when the debugger gets detached ( mostly when the application is killed ) ...
System.Diagnostics.Debugger.IsAttached ;
Running code when C # debugger detaches from process
C#
DTC is disabled on my machine . It is my understanding that this code should fail , because it uses two data contexts in the same transaction . So , why does it work ? ( Note : I tried this using .NET 3.5 and .NET 4.0 . ) Here are the DAL methods that get called :
using ( TransactionScope transactionScope = new TransactionScope ( ) ) { UpdateEta ( ) ; UpdateBin ( ) ; transactionScope.Complete ( ) ; } public static void UpdateBin ( Bin updatedBin ) { using ( DevProdDataDataContext dataContext = new DevProdDataDataContext ( ConnectionString ) ) { BinRecord binRecord = ( from bin i...
Why is n't my transaction escalating to DTC ?
C#
I 'm creating a Code Fix which turns the access modifier of detected methods public . The implementation is straightforward : remove all existing access modifiers and add public at the front . Afterwards I replace the node and return the solution . This however results in a modifier list that looks like this : publicvi...
[ TestClass ] public class MyClass { [ TestMethod ] publicvirtual void Method ( ) { } } var formattedMethod = Formatter.Format ( newMethod , newMethod.Modifiers.Span , document.Project.Solution.Workspace , document.Project.Solution.Workspace.Options ) ; [ TestClass ] public class MyClass { [ TestMethod ] public virtual...
Formatting a method signature loses indentation
C#
Well I am not sure if this questions asked before but I have no idea how the search for it . Well this is not an Entity Framework specified question but I am gon na give example using it.So in EF we need to use .Include ( `` Related Object '' ) to include related data . However what I want to is that write a method tha...
public List < Entity > GetAll ( List < string > includes > ) { List < Entity > entites = context.Entites ; foreach ( string s in includes ) { entites.Include ( s ) ; } return entites ; }
How to dynamically generate Includes in entity framework
C#
I 've got the following class : I 've searched for a while and it appears that an argument passed with the ref keyword ca n't be stored . Trying to add the source argument to a list or to assign it to a field variable does n't allow it to keep a reference to the actual delegate 's original reference ; so my questions a...
public class Terminal : IDisposable { readonly List < IListener > _listeners ; public Terminal ( IEnumerable < IListener > listeners ) { _listeners = new List < IListener > ( listeners ) ; } public void Subscribe ( ref Action < string > source ) { source += Broadcast ; //Store the reference somehow ? } void Broadcast (...
Unsubscribe from delegate passed through ref keyword to the subscription method ?
C#
so in my program I have parts where I use try catch blocks like thisOf course I probably could do checks to see if the string is valid path ( regex ) , then I would check if directory exists , then I could catch various exceptions to see why my routine failed and give more info ... But in my program it 's not really ne...
try { DirectoryInfo dirInfo = new DirectoryInfo ( someString ) ; //I do n't know if that directory exists //I do n't know if that string is valid path string ... it could be anything //Some operations here } catch ( Exception iDontCareWhyItFailed ) { //Did n't work ? great ... we will say : somethings wrong , try again...
Is it bad programming style to have a single , maybe common , generic exception ?
C#
I want to convert a binary file to a string which could be then converted back to the binary file.I tried this : but it 's too slow , it takes about 20 seconds to convert 5KB on i5 CPU.I noticed that notepad does the same in much less time.Any ideas on how to do it ? Thanks
byte [ ] byteArray = File.ReadAllBytes ( @ '' D : \pic.png '' ) ; for ( int i = 0 ; i < byteArray.Length ; i++ ) { textBox1.Text += ( char ) byteArray [ i ] ; }
converting bytes to a string C #
C#
I have the problem where I need to do dynamic dispatch based on an object type . The types based on which I need to dispatch are known at compile time - in my example they are 17.My initial guess was to use a Dictionary < Type , Action < Object > > for the dispatching and to use obj.GetType ( ) to find out the appropri...
public class Program { private static readonly Object Value = Guid.NewGuid ( ) ; private static readonly Dictionary < Type , Action < Object > > Dictionary = new Dictionary < Type , Action < Object > > ( ) { [ typeof ( Byte ) ] = x = > Empty ( ( Byte ) x ) , [ typeof ( Byte [ ] ) ] = x = > Empty ( ( Byte [ ] ) x ) , [ ...
Unexpected performance results when comparing dictionary lookup vs multiple is operators in .NET 4.7
C#
I 'm trying to ditch Windows Forms , and learn to use WPF professionally from now on . Pictured above is a form done in Windows Forms that I 'd like to recreate in WPF.Here is the XAML I have so far : Is this even the right approach , I mean using a Rectangle . In my Windows Forms example , I used a Panel and gave it a...
< Window x : Class= '' PizzaSoftware.UI.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 297 '' Width= '' 466 '' > < Grid ShowGridLines= '' True '' > < Grid.ColumnDefinitions > < Colu...
New to WPF , how would I create these colored bars in my form ?
C#
I want to test for object references held improperly and wrote a test that always failed . I simplified the test to the following behaviour : This test however , which does the same without using , passes : The used stub class is simple enough : Can someone please explain me that behaviour or - even better - has an ide...
[ Test ] public void ScopesAreNotLeaking ( ) { WeakReference weakRef ; Stub scope = null ; using ( scope = new Stub ( ) ) { weakRef = new WeakReference ( scope ) ; } scope = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.That ( weakRef.Target , Is.Null ) ; } [ Test ] public void ScopesAreNotLeaking ( ...
Garbage collector wo n't collect an object created with using
C#
I 've recently been developing an RTF Editor which is only a simple UserControl that has a RichTextBox with a couple Events like PreviewTextInput and PreviewMouseUp.I noticed something slightly annoying though.The Performance of the RichTextBox is absolutely terrible whenever the UI is being resized and the RichTextBox...
< RichTextBox/ > richTextBox1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible ; richTextBox1.Document.PageWidth = 1000 ;
RichTextBox - UI Resize causes huge CPU Load
C#
In PersonBusiness.GetQuery method , the PersonEntity is peppered all over code and there are a lot of other entity types that will implement this method similarly.I want to use generic parameters in PersonBusiness to lessen usage of specific entity type because there will be implementations like this one with other ent...
public class Entities : DbContext { public virtual DbSet < PersonEntity > PersonSet { get ; set ; } } public class PersonEntity { public int Id { get ; set ; } public string FullName { get ; set ; } } public class BaseBusiness { public Entities Db = > new Entities ( ) ; } public abstract class BaseBusiness < T > : Base...
Using generics with entities
C#
I 'm just wondering why I get this output : OUTPUTc But in MonoOUTPUTfSo why is the output c ? not d ? How does the compiler choose c ? If I change the code like this : OUTPUTc again ! Another example : OUTPUTc
enum MyEnum { a=1 , b=2 , c=3 , d=3 , f=d } Console.WriteLine ( MyEnum.f.ToString ( ) ) ; enum MyEnum { a=1 , b=2 , c=3 , d=3 , k=3 } Console.WriteLine ( MyEnum.k.ToString ( ) ) ; enum MyEnum { a=3 , b=3 , c=3 , d=3 , f=d , } MessageBox.Show ( MyEnum.f.ToString ( ) ) ;
Values of Enum types
C#
Having this extension wanted it to accept IEnumerable and casting to array if needed inside the extension , but I do n't know how to use the params keyword for that.Tryed : but this generates a compile-time error : The parameter array must be a single dimensional arrayIs there any way to make the extension method suppo...
public static bool In < T > ( this T t , params T [ ] values ) { return values.Contains ( t ) ; } public static bool In < T > ( this T t , params IEnumerable < T > values ) { return values.Contains ( t ) ; }
C # How can I make an extension accept IEnumerable instead of array for params
C#
I 'm dealing with a code base that makes generous use of Generics with class types . I 've been pushing to use interfaces ( for a variety of reasons ) . In my work of slowly converting things , I 've hit the following and I ca n't get past it.Put simply ( and minimally ) , the problem I 'm facing is the following : As ...
private static IList < IDictionary < int , string > > exampleFunc ( ) { //The following produces a compile error of : // Can not implicitly convert type 'System.Collections.Generic.List < System.Collections.Generic.Dictionary < int , string > > ' to // 'System.Collections.Generic.IList < System.Collections.Generic.IDic...
Conversion of Generic using Interfaces
C#
I 'm using C # in Visual Studio 2010 with the framework 4.0.In my project , in two different forms , there are two FileSystemWatchers with the property EnableRaisingEvent set to false . If I close Visual Studio , when I reopen it I get in both FileSystemWatcher the property EnableRaisingEvent set to true.In both my for...
private void InitializeComponent ( ) { this.components = new System.ComponentModel.Container ( ) ; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager ( typeof ( Form1 ) ) ; this.fileSystemWatcher1 = new System.IO.FileSystemWatcher ( ) ; ( ( System.ComponentMode...
Each time I open Visual Studio the FileSystemWatcher EnableRaisingEvent changes
C#
Consider two iterator methods with the same bodies : Is there any circumstance where calling It2 is different from calling It1.GetEnumerator ( ) ? Is there ever a good reason to define an iterator as IEnumerator < T > over IEnumerable < T > ? The only one I can think of is when you are implementing IEnumerable < T > .G...
public static IEnumerable < int > It1 ( ) { ... } public static IEnumerator < int > It2 ( ) { ... }
Is there any difference between iterator methods returning IEnumerable < T > and IEnumerator < T > ?
C#
I 've been digging through ExpressionVisitor in .NET and I found this for loop , Now is there any particular reason why is that : i = 0 , n = nodes.Count ; i < n ? Is there any performance gain from this that is not in i = 0 ; i < nodes.Count ?
for ( int i = 0 , n = nodes.Count ; i < n ; i++ ) { Expression node = Visit ( nodes [ i ] ) ; if ( newNodes ! = null ) { newNodes [ i ] = node ; } else if ( ! object.ReferenceEquals ( node , nodes [ i ] ) ) { newNodes = new Expression [ n ] ; for ( int j = 0 ; j < i ; j++ ) { newNodes [ j ] = nodes [ j ] ; } newNodes [...
For loop variable declaration for the condition in .NET Source code
C#
I am developing a compiler that emits IL code . It is important that the resulting IL is JIT'ted to the fastest possible machine codes by Mono and Microsoft .NET JIT compilers . My questions are : Does it make sense to optimize patterns like : and such , or are the JIT 's smart enough to take care of these ? Is there a...
'stloc.0 ; ldloc.0 ; ret ' = > 'ret ' 'ldc.i4.0 ; conv.r8 ' = > 'ldc.r8.0 '
IL optimization for JIT compilers
C#
There are a hundred examples in blogs , etc . on how to implement a background worker that logs or gives status to a foreground GUI element . Most of them include an approach to handle the race condition that exists between spawning the worker thread , and creating the foreground dialog with ShowDialog ( ) . However , ...
public override void Log ( string s ) { form.BeginInvoke ( logDelegate , s ) ; } public SimpleProgressDialog ( ) { var h = form.Handle ; // dereference the handle }
Need second ( and third ) opinions on my fix for this Winforms race condition
C#
Do you think that C # will support something like ? ? = operator ? Instead of this : It might be possible to write : Now , I could use ( but it seems to me not well readable ) :
if ( list == null ) list = new List < int > ( ) ; list ? ? = new List < int > ( ) ; list = list ? ? new List < int > ( ) ;
What do you think about ? ? = operator in C # ?
C#
I have two BlockingCollection < T > objects , collection1 and collection2 . I want to consume items from these collections giving priority to items in collection1 . That is , if both collections have items , I want to take items from collection1 first . If none of them have items , I want to wait for an item to be avai...
public static T Take < T > ( BlockingCollection < T > collection1 , BlockingCollection < T > collection2 ) where T : class { if ( collection1.TryTake ( out var item1 ) ) { return item1 ; } T item2 ; try { BlockingCollection < T > .TakeFromAny ( new [ ] { collection1 , collection2 } , out item2 ) ; } catch ( ArgumentExc...
How to take an item from any two BlockingCollections with priority to the first collection ?
C#
Is it possible to use the ref returns feature in C # 7.0 define a generic function that can do both comparison and update of a field in two instances of an Object ? I am imagining something like this : Example intended usage : Is there any way to specify a Func type or any kind of generic type restriction that would ma...
void UpdateIfChanged < TClass , TField > ( TClass c1 , TClass c2 , Func < TClass , TField > getter ) { if ( ! getter ( c1 ) .Equals ( getter ( c2 ) ) { getter ( c1 ) = getter ( c2 ) ; } } Thing thing1 = new Thing ( field1 : 0 , field2 : `` foo '' ) ; Thing thing2 = new Thing ( field1 : -5 , field2 : `` foo '' ) ; Updat...
Generic functions and ref returns in C # 7.0
C#
I was reading about SynchronizationContext and its use with the async/await methods ( link ) . From my understanding , in a Console application where the SynchronizationContext is null , the continuation of an awaited method ( Task ) will be scheduled with the default scheduler which would be the ThreadPool.But if I ru...
class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` MainThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; Method1 ( ) .ContinueWith ( t = > { Console.WriteLine ( `` After Method1 . ThreadId= '' + Thread.CurrentThread.ManagedThreadId ) ; } ) ; Console.ReadKey ( ) ; } public static async T...
Task continuation was not scheduled on thread-pool thread