lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Entity Framework Core introduced the methods HasServiceTier and HasPerformanceLevel to change the edition of an Azure SQL server . You can use them in OnModelCreating like this : If you use Add-Migration Add-Migration you get a migration like this : This seems to work fine but when I try to apply this migration to a lo...
protected override void OnModelCreating ( ModelBuilder modelBuilder ) { base.OnModelCreating ( modelBuilder ) ; modelBuilder.HasServiceTier ( `` Basic '' ) ; modelBuilder.HasPerformanceLevel ( `` Basic '' ) ; } public partial class ChangedDatabaseServiceTierToBasic : Migration { protected override void Up ( MigrationBu...
Specify Azure SQL server edition in EF Core without breaking local development
C#
I have the exact situation described in this question : Device Hub communication with printer queueDue to the question having neither an accepted , nor an acceptable answer , I am asking the question again.I have configured DeviceHub with Acumatica , and my printer is shown . I am sending the print job via a PXAction ....
public PXAction < PX.Objects.CR.BAccount > PrintAddressLabel ; [ PXButton ( CommitChanges=true ) ] [ PXUIField ( DisplayName = `` Print Label '' ) ] protected void printAddressLabel ( ) { BAccount baccount = Base.Caches [ typeof ( BAccount ) ] .Current as BAccount ; string bAccountID = baccount.BAccountID.ToString ( ) ...
Printer fails to receive job from DeviceHub
C#
I have the following ActionLink : yet when I hover over the link , the url displayed in the browser is http : //localhost:44334/Upload . Where is the controller in this url ? Strangely , clicking the url takes me to my File/Upload view , and yet stranger , the url displayed in the browser 's address bar is https : //lo...
@ Html.ActionLink ( `` Upload '' , `` Upload '' , `` File '' ) app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ; @ Html.ActionLink ( `` Download '' , `` Download '' , `` File '' , new { filePath = file.Path } ) https : //local...
I 'm seeing strange ActionLink behaviour , why is the url displayed in the browser not displaying the seemingly correct controller ?
C#
I have the feeling I 'm not looking at this issue from the right angle here , and I 'm just not thinking of other solution.Assuming this generic class ; It is used to define `` ports '' in a graph-node editor . A port can transfer a object/value from one node to another , but they also need to be `` type-safe '' , whic...
public abstract class Port < T > { public delegate T PullDelegate ( ) ; private PullDelegate pull ; public Port ( PullDelegate pull ) { this.pull = pull ; } public T Pull ( ) { return pull ( ) ; } } public abstract Port [ ] Inputs { get ; } public abstract Port [ ] Outputs { get ; } public abstract Port [ ] Entries { g...
Invoking generic method/delegate from a non-generic base class
C#
I need some help . I am creating a SelectItem class like this : I would like the following code to be validInstead of having to do this : How can I accomplish this ?
public class SelectItem < T > where T : class { public bool IsChecked { get ; set ; } public T Item { get ; set ; } } SelectItem < String > obj = new SelectItem < String > { Item = `` Value '' } ; obj.IsChecked = true ; String objValue = obj ; String objValue = obj.Item ;
Implicit operator ?
C#
I hit a bizarre problem earlier which I have replicated in a new console application . I wonder , can anyone explain why this occurs ? You get an error on the DoSomething line : Error 1 The call is ambiguous between the following methods or properties : 'DoSomething ( int ? ) ' and 'DoSomething ( MyEnum ) ' However if ...
static void Main ( string [ ] args ) { DoSomething ( 0 ) ; Console.Read ( ) ; } public static void DoSomething ( int ? value ) { Console.WriteLine ( `` Do Something int ? called '' ) ; } public static void DoSomething ( MyEnum value ) { Console.WriteLine ( `` Do Something MyEnum called '' ) ; } public static enum MyEnu...
Can anyone explain this interesting C # problem ?
C#
Imagine the code above being used in the following case : It looks like it 's perfectly safe to inline y , but it 's actually not . This inconsistency in the language itself is counter-intuitive and is plain dangerous . Most programmers would simply inline y , but you 'd actually end up with an integer overflow bug . I...
using System ; public class Tester { public static void Main ( ) { const uint x=1u ; const int y=-1 ; Console.WriteLine ( ( x+y ) .GetType ( ) ) ; // Let 's refactor and inline y ... oops ! Console.WriteLine ( ( x-1 ) .GetType ( ) ) ; } } public long Foo ( uint x ) { const int y = -1 ; var ptr = anIntPtr.ToInt64 ( ) + ...
Integral type promotion inconsistency
C#
BackgroundOur site is a press site and is viewed by many people around the globe . Obviously this means that we will be localising the site in as many languages as possible . A professional translator will be hired for each language.How our site works currentlyThe way we have planned to do this is by storing a translat...
public class StandardButtonToken : LocalisationToken { protected StandardButtonToken ( string defaultText , Guid key ) : base ( defaultText , key ) { } public static readonly LocalisationToken Update = new StandardButtonToken ( `` Update '' , Guid.Parse ( `` 8a999f5b-7ca1-466d-93ca-377321e6de00 '' ) ) ; public static r...
Does the way we translate our website result in performance issues ?
C#
I 'm writing a desktop application in C # that should be able to access all users on a Google Apps `` account '' an retrieve calendar-events for each user . I have added the Calendar API and the Admin SDK to my `` project '' .Both methods ( below ) works fine on their own but when I want to authorize my app for both AP...
static string [ ] CalendarScopes = { CalendarService.Scope.CalendarReadonly } ; static string [ ] DirectoryScopes = { DirectoryService.Scope.AdminDirectoryUserReadonly } ; private static void GoogleCalendar ( ) { UserCredential credential ; using ( var stream = new FileStream ( `` client_secret.json '' , FileMode.Open ...
Multiple Google access permissions for a desktop application
C#
I 've been struggling a lot lately to find decent solution which has authentication mechanism for server and client API's.I put alot of effort trying to find working ( ! ) code samples , but could n't find any.The code from DotNetOpenAuth does n't work for me - im using vs 2010 .net 4 webformAnyway , I ca n't seems to ...
https : //accounts.google.com/o/oauth2/auth https : //accounts.google.com/o/oauth2/auth ? scope=email % 20profile & state= % 2Fprofile & redirect_uri=https % 3A % 2F % 2Foauth2-login-demo.appspot.com % 2Foauthcallback & response_type=token & client_id=812741506391.apps.googleusercontent.com
OpenID API for both asp.net and JavaScript support ?
C#
List < T > derives from the following interfaces : I just wonder , why it needs all these interfaces ( in the class declaration ) ? IList itself already derives from ICollection < T > , IEnumerable < T > und IEnumerable.So why is the following not enough ? I hope you can solve my confusion .
public class List < T > : IList < T > , ICollection < T > , IEnumerable < T > , IList , ICollection , IEnumerable public class List < T > : IList < T > , IList
Why does List < T > implement so many interfaces ?
C#
I have following LINQ statement and I want to rewrite it using extension methods.One possible solution is : However this is everything but elegant . Do you any idea how to improve beauty of second expression ?
from x in efrom y in efrom z in eselect new { x , z } e.Join ( e , x = > 42 , y = > 42 , ( x , y ) = > new { x , y } ) Join ( e , _ = > 42 , z = > 42 , ( _ , z ) = > new { _.x , z } ) ;
What 's elegant way to rewrite following LINQ statement using extension methods ?
C#
I 'm finding that ValueTuples evaluate differently when I access their properties from a collection.Why do these two highlighted lines evaluate differently and how can I change `` MyList [ 0 ] .c '' to get the value correctly ?
public static List < Tuple < string , bool > > MyTupleList = new List < Tuple < string , bool > > { new Tuple < string , bool > ( `` test '' , true ) } ; public static List < ( string b , bool c ) > MyList = new List < ( string b , bool c ) > { ( `` test '' , true ) } ;
Why does the Visual Studio watch window show wrong values for ValueTuples in a collection ?
C#
I have two functions that have different enough logic but pretty much the same exception handling : It is not possible to use a single entry point for DoIt1 and DoIt2 , because they are called in from outside.Is Copy/Pase ( for the exception block ) the best approach ?
public void DoIt1 // DoIt2 has different logic but same exception handling { try ... DoIt1 logic catch ( MySpecialException myEx ) { Debug.WriteLine ( myEx.MyErrorString ) ; throw ; } catch ( Exception e ) { Debug.WriteLine ( e.ToString ( ) ) ; throw ; } }
What is the best way to re-use exception handling logic in C # ?
C#
I am developing a WinRT app using XAML and MVVM Light . This app is meant to make it easier to do data collection while the users are out in the field . I have a section of my app where users will need to enter in a bunch of information about several different items . These items are defined as classes that inherit fro...
public class GenericAsset { public string AssetId { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } public string Make { get ; set ; } public string Model { get ; set ; } } public class SubAsset1 : GenericAsset { public string RecordNumber { get ; set ; } public int SizeDiamet...
Multiple input forms with same xaml file and different DataContexts
C#
I 'm creating a reusable library that targets several platforms ( .NET 4.0 , .NET 4.5 , .NETStandard 1.0 and .NETStandard 1.3 ) . The .NET 4.5 version of this project contains some features that are not available under the .NET 4.0 version . The unit test project that references this library project has one single targ...
{ `` version '' : `` 1.0.0-* '' , `` frameworks '' : { `` netstandard1.0 '' : { `` dependencies '' : { `` NETStandard.Library '' : `` 1.6.0 '' } } , `` net40 '' : { } , `` net45 '' : { } } } namespace CoreLibrary { # if NETSTANDARD1_0 public class ClassNetStandard { } # endif # if NET40 public class ClassNet40 { } # en...
How to let a Visual Studio 2015 xproject ( project.json ) reference the highest framework of a depending project
C#
I have a class called Message which overloads these operators : I want the == and ! = operators keep comparing references of the types other than String and Message but , gives me this : The call is ambiguous between the following methods or properties : 'Message.operator == ( Message , Message ) ' and 'Message.operato...
public static bool operator == ( Message left , Message right ) public static bool operator ! = ( Message left , Message right ) public static bool operator == ( Message left , string right ) public static bool operator ! = ( Message left , string right ) public static bool operator == ( string left , Message right ) p...
Overloading == operator for null
C#
I have came across this question : What does the [ Flags ] Enum Attribute mean in C # ? And one thing I have been wondering , using the accepted answer 's example , what will happen if I declare : Will the following steps in that example resulting an error ? If no , how can I get to MyColors.Red ?
[ Flags ] public enum MyColors { Yellow = 1 , Green = 2 , Red = 3 , Blue = 4 }
What happens if we declare [ Flags ] enum in order ?
C#
My OM has a 'product ' object.Each product has a 'manufacturer id ' ( property , integer ) .When I have a list of products to display , the first three are displayed as the 'featured products'.The list is already sorted in a specific sort order , putting the 'featured ' products first in the list . However , I now need...
public List < Product > SetFeatures ( List < Product > products , int numberOfFeatures ) { List < Product > result ; // ensure the 2nd product is different manufacturer than the first ... . // ensure the 3rd product is a different manufacturer than the first two ... // ... etc ... for the numberOfFeatures return result...
LINQ Sorting - First three need to be different manufacturers
C#
This is a very uncommon problem and there are definetly many workarounds , but I would like to understand what is actually going on and why it 's not working.So I have 3 assemblies in a test solution , first assembly has type ClassA : Second assembly references first assembly and has ClassB : which has an explicit oper...
public class ClassA { public string Name { get ; set ; } } public class ClassB { public string Name { get ; set ; } public static explicit operator ClassA ( ClassB objB ) { return new ClassA { Name = objB.Name } ; } } public class ClassC { public string Name { get ; set ; } public static explicit operator ClassB ( Clas...
Explicit cast operator fails with `` assembly is not referenced '' error
C#
I have a x64 crash dump of a managed ( C # ) application that p/invokes to native code . The dump was taken after the native code attempted to dereference a bad memory location , and after the .NET marshaler had turned it into an AccessViolationException . As a result , the stack frame where the error occurred is no lo...
0:017 > kb # RetAddr : Args to Child : Call Site00 000007fe ` fd3b10dc : 00000000 ` 0402958b 00000000 ` 20000002 00000000 ` 00000e54 00000000 ` 00000e4c : ntdll ! NtWaitForSingleObject+0xa01 000007fe ` ea9291eb : 00000000 ` 00000000 00000000 ` 00000cdc 00000000 ` 00000000 00000000 ` 00000cdc : KERNELBASE ! WaitForSingl...
How do I retrieve Register Context from AccessViolationException ?
C#
A part of my ( C # 3.0 .NET 3.5 ) application requires several lists of strings to be maintained . I declare them , unsurprisingly , as List < string > and everything works , which is nice.The strings in these Lists are actually ( and always ) Fund IDs . I 'm wondering if it might be more intention-revealing to be more...
public class FundIdList : List < string > { }
Are there drawbacks to creating a class that encapsulates Generic Collection ?
C#
I have the following code snippet in C # : It 's running fine , but I am not getting the result I expect.Actual result9,9,9Expected result1,4,9Why am I not getting the result I expect ?
var actions = new List < Func < int > > ( ) ; IEnumerable < int > values = new List < int > { 1 , 2 , 3 } ; foreach ( int value in values ) { actions.Add ( ( ) = > value * value ) ; } foreach ( var action in actions ) { Console.WriteLine ( action ( ) ) ; ; } Console.ReadLine ( ) ;
Why am I getting wrong results when calling Func < int > ?
C#
I am working with ComboBox elements that often contain very large quantities of data ; ~250000 data entries.This works fine when a ComboBox is set up a little like this.However , some custom modifications of the ComboBox I am working with require the ComboBoxItem elements to not be focusable . I achieved this by using ...
< ComboBox ItemsSource= '' { Binding Items } '' > < ComboBox.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /ItemsPanelTemplate > < /ComboBox.ItemsPanel > < /ComboBox > < ComboBox ItemsSource= '' { Binding Items } '' > < ComboBox.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /It...
None focusable ComboBoxItem
C#
I want to capture the selected date on my DropDown list , where there are five days will display on DropdownList.I 'm usually putting the default value on DropDown , but not this time because in the drop down list I want it always display the current date and the next five days . But I do n't know how to capture the da...
< asp : DropDownList ID= '' ddldate '' runat= '' server '' > < /asp : DropDownList > protected void Page_Load ( object sender , EventArgs e ) { List < ListItem > items = new List < ListItem > ( ) ; for ( int i = 0 ; i < 5 ; i++ ) { items.Add ( new ListItem ( DateTime.Now.AddDays ( i ) .ToShortDateString ( ) , DateTime....
Capture a value from a dropdownlist where the display dropdownlist is not default
C#
I am using an asp.net webapi controller , and in my project I have a dll that I built myself . The dll is being used to validate if the person that the user is typing in actually exists.Here is my controller method : Now the two conditional statements above that have EmpData.. EmpData is from my dll.Here is the ajax co...
// POST : api/EventsAPI [ ResponseType ( typeof ( Event ) ) ] public IHttpActionResult PostEvent ( Event @ event ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } if ( @ event.DateEndOfEvent < @ event.DateOfEvent ) // successfully returns error.modelState ( in view code ) { ModelState.AddModelError...
AJAX error not returning jqXHR.responseText.modelState when using custom dll
C#
Okay I have a derived class that has an overload to a method that 's on my base class . I call what I think would match the method signature of the base class but instead my derived classes implementation is called . ( The code below always prints out `` MyDerived '' ) Why is this ?
public class MyBase { public void DoSomething ( int a ) { Console.WriteLine ( `` MyBase '' ) ; } } public class MyDerived : MyBase { public void DoSomething ( long a ) { Console.WriteLine ( `` MyDerived '' ) ; } } Main ( ) { MyDerived d = new MyDerived ( ) ; d.DoSomething ( ( int ) 5 ) ; }
Compiler picking the wrong overload
C#
I am trying to call IEnumerable.Contains ( ) with a dynamic argument , but I am getting the error 'IEnumerable ' does not contain a definition for 'Contains ' and the best extension method overload 'Queryable.Contains ( IQueryable , TSource ) ' has some invalid argumentsI 've noticed that I can either cast the argument...
dynamic d = `` test '' ; var s = new HashSet < string > ( ) ; IEnumerable < string > ie = s ; s.Contains ( d ) ; // Worksie.Contains ( d ) ; // Does not workie.Contains ( ( string ) d ) ; // Works
Why do I need to cast a dynamic object when calling IEnumerable.Contains ( ) ?
C#
Just wondering why Enumerable.Range implements IDisposable.I understand why IEnumerator < T > does , but IEnumerable < T > does n't require it . ( I discovered this while playing with my .Memoise ( ) implementation , which has statement like in its `` source finished '' method that I had placed a breakpoint on out of c...
if ( enumerable is IDisposable ) ( ( IDisposable ) enumerable ) .Dispose ( ) ;
Why does Enumerable.Range Implement IDisposable ?
C#
Is there way to do something along these lines ? I do n't care about the type of the properties , I just need the properties to be available . This does n't have to be implemented with an interface , just using that as an example .
interface Iface { [ anytype ] Prop1 { get ; } [ anytype ] Prop2 { get ; } } class Class1 : Iface { public string Prop1 { get ; } public int Prop2 { get ; } } class Class2 : Iface { public int Prop1 { get ; } public bool ? Prop2 { get ; } }
C # Interface without static typing
C#
I 've got something like this : I have to make SomeDataBlob public so that it can be used as a member of the public interface method ExternalPlugin.DoStuff . However , I would not like to allow clients to inherit from that class and thus be susceptible to the brittle base class problem . ( All derivatives of that class...
// This gets implemented by plugin authors to get callbacks about various things.public interface ExternalPlugin { // This gets called by the main application to tell the plugin some data // is available or similar . void DoStuff ( SomeDataBlob blob ) ; } // Data blob for v1 of APIpublic class SomeDataBlob { internal S...
Can I disallow other assemblies from inheriting from a class ?
C#
I am migrating a project from .Net 4.6.2 into .Net Core 2.0 . What is the replacement for RoleProvider in Net Core ? The type or namespace name 'RoleProvider ' could not be found ( are you missing a using directive or an assembly reference ? ) New code looks like this , received errorUpdate : Answer from John Kenney lo...
public class CustomerRoleProvider : RoleProvider { public override string CustomerName { get ; set ; } public override void AddUsersToRoles ( string [ ] usernames , string [ ] roleNames ) { Using the generic type 'RoleManager < TRole > ' requires 1 type arguments// Error first line : Using the generic type 'RoleManager...
Net Core : Type or namespace name 'RoleProvider ' could not be found
C#
In this threadHow to get null instead of the KeyNotFoundException accessing Dictionary value by key ? in my own answer I used explicit interface implementation to change the basic dictionary indexer behaviour not to throw KeyNotFoundException if the key was not present in the dictionary ( since it was convinient for me...
public interface INullValueDictionary < T , U > where U : class { U this [ T key ] { get ; } } public class NullValueDictionary < T , U > : Dictionary < T , U > , INullValueDictionary < T , U > where U : class { U INullValueDictionary < T , U > .this [ T key ] { get { if ( ContainsKey ( key ) ) return this [ key ] ; el...
Is there a built-in generic interface with covariant type parameter returned by an indexer ?
C#
The issue I 'm currently facing is that I 'm unable to get my C # program to write the file I want to send in the response ( I 'm writing the bytes of the file ) and have a valid HTTP response , the browser I 'm testing it with is saying ERR_INVALID_HTTP_RESPONSE if I have appended the file to the response.Originally I...
StreamReader sr = new StreamReader ( client.GetStream ( ) ) ; StreamWriter sw = new StreamWriter ( client.GetStream ( ) ) ; string request = sr.ReadLine ( ) ; if ( request ! = null ) { //byte [ ] testData = Encoding.UTF8.GetBytes ( `` Test '' ) ; string [ ] tokens = request.Split ( `` `` ) ; try { FileInfo file = files...
C # How do you send a file via TCP for HTTP ?
C#
I have found huge amounts of information ( ie , this ) on how to handle unexpected errors in ASP.NET , using the Page_Error and Application_Error methods as well as the customErrors directive in Web.config.However , my question is what is the best way to handle EXPECTED errors . For example , I have a page to display a...
protected void Page_Load ( object sender , EventArgs e ) { var user = Membership.GetUser ( ) ; if ( ! CanUserViewThisRecord ( Request [ `` id '' ] , user.Username ) { // Display an error to the user that says , // `` You are not allowed to view this message '' , and quit . } else { // Display the page . } }
Displaying expected errors to users in ASP.NET
C#
I 've got a DataGridView that is backed by a SortableBindingList as described by this article.This is essentially a BindingList whose Data source is a list of custom objects . The underlying custom objects are updated programatically.My SortableBindingList allows me to sort each column in Ascending or Descending order ...
protected override void ApplySortCore ( PropertyDescriptor prop , ListSortDirection direction )
Keeping a DataGridView autosorted
C#
I have a generic class which could use a generic OrderBy argumentthe class is as followsThe orderBy could be of various typese.g . The goal is to make the orderBy an argument rather than bake it inany ideas ?
class abc < T > where T : myType { public abc ( ... .. , orderBy_Argument ) { ... } void someMethod ( arg1 , arg2 , bool afterSort = false ) { IEnumerable < myType > res ; if ( afterSort & & orderBy_Argument ! = null ) res = src.Except ( tgt ) .OrderBy ( ... . ) ; else res = src.Except ( tgt ) ; } } .OrderBy ( person =...
Linq and order by
C#
Given the following C # code : And its counterpart in VB.NET : It appears that VB.NET is able to correctly infer type of a = Object ( ) , while C # complains until the above is fixed to : Is there a way to auto-infer type in C # for the above scenario ? EDIT : Interesting observation after playing with different types ...
var a = new [ ] { `` 123 '' , `` 321 '' , 1 } ; //no best type found for implicitly typed array Dim a = { `` 123 '' , `` 321 '' , 1 } 'no errors var a = new object [ ] { `` 123 '' , `` 321 '' , 1 } ; var a = new [ ] { 1 , 1.0 } ; //will infer double [ ] var a = new [ ] { new A ( ) , new B ( ) } ; //will infer A [ ] , i...
Type inference in C # not working ?
C#
I came across the following code , all in a single file/class . I 'm leaving out the details , its the construct I 'm interested in . Why are there two different declarations for the same class and how are they different ? What 's the purpose of the syntax for the second declaration ?
public abstract class MyClass { ... } public abstract class MyClass < TMyClass > : MyClass where TMyClass : MyClass < TMyClass > { ... }
What is this C # construct doing and why ? MyClass < TMyClass > : MyClass where
C#
First time poster here , but I have been using stackoverflow this entire quarter to help me along in my intro to C # class . Generally , I can find what I 'm looking for if I look hard enough , but I have been unable to find anyone that has already answered my question.I have an assignment that wants me to display rand...
x x x x xx x x x xx x x x xx x x x xx x x x x x x x x x x x x x x x x x x x x xx x x x x x x x x x x x x x x x xx x x x ... etc using System ; namespace DilleyHW7 { class Array2d { static void Main ( ) { const int ROWS = 10 ; const int COLS = 5 ; const int MAX = 100 ; int [ , ] numbers = new int [ 10 , 5 ] ; Random ran...
How to properly align a 5x10 2-d array with random data in console ?
C#
This is the first time I face a problem like this . Not being this my profession but only my hobby , I have no previous references.In my program I have added one by one several functions to control a machine . After I added the last function ( temperature measurement ) , I have started experiencing problems on other fu...
private void AddT ( decimal valueTemp ) { sumTemp += valueTemp ; countTemp += 1 ; if ( countTemp > = 20 ) //take 20 samples and make average { OnAvarerageChangedTemp ( sumTemp / countTemp ) ; sumTemp = 0 ; countTemp = 0 ; } } private void OnAvarerageChangedTemp ( decimal avTemp ) { float val3 = ( float ) avTemp ; decim...
Multithreading or something different
C#
I 'm forwarding type definitions for our legacy support . I 'm using following syntax to do so : problem I 'm having is that I ca n't find correct syntax for generic type definitions ( it should be possible based on Eric Lippert 's post and many other places ) .What I would expect as working solution isAny idea how wri...
[ assembly : TypeForwardedTo ( typeof ( NamespaceA.TypeA ) ) ] [ assembly : TypeForwardedTo ( typeof ( NamespaceA.TypeA < T > ) ) ]
Forward generic type definition
C#
I have a vertically and horizontally scrollable DataGridView on a form.I use virtual mode because the underlying datatable is huge.When I scroll right , if the last column is not fully shown in the view , then I see repeated calls to CellValueNeeded.How can I fix this ? My thoughts : Why is CellValueNeed being repeated...
private void grid_Data_CellValueNeeded ( object sender , DataGridViewCellValueEventArgs e ) { Console.WriteLine ( `` CellValue : `` + e.RowIndex + `` `` + e.ColumnIndex ) ; if ( e.RowIndex > Grid.Rows.Count - 1 ) return ; DataGridView gridView = sender as DataGridView ; e.Value = Grid.Rows [ e.RowIndex ] [ e.ColumnInde...
Repeated calls to CellValueNeeded
C#
I am trying to serialize a List to a file in C # with JSON.NET.I want to be able to add values to the list and serialize that change.I do not want to serialize the list all over again , since it can grow pretty big.Is something like that possible with JSON.NET ? this way it would only be possible to `` Reserialize '' t...
using ( FileStream fs = File.Open ( @ '' c : \list.json '' , FileMode.CreateNew ) ) using ( StreamWriter sw = new StreamWriter ( fs ) ) using ( JsonWriter jw = new JsonTextWriter ( sw ) ) { jw.Formatting = Formatting.Indented ; JsonSerializer serializer = new JsonSerializer ( ) ; serializer.Serialize ( jw , list ) ; }
continuous serialization of a list with JSON.NET
C#
Here 's the Lambda expression I am using to try and include the User table , which throws an error.The include statement gives this error The Include path expression must refer to a navigation property defined on the type . Use dotted paths for reference navigation properties and the Select operator for collection navi...
ICollection < Activity > activity = db.Activities .Include ( i = > i.Project.ProjectDoc.OfType < Cover > ( ) .Select ( v = > v.User ) ) .Where ( u = > u.UserID == WebSecurity.CurrentUserId ) .OrderByDescending ( d = > d.DateCreated ) .ToList ( ) ; public abstract class ProjectDoc { public int ProjectDocID { get ; set ;...
Include Derived Models Related Class
C#
What I want to do is combine lambda syntax with `` params '' to carry out an action on a series of object.Let 's say I want to make a bunch of controls invisible.After a bit of fiddling I ended up with an extension method : and then I can create an action : and then call it : This is n't very nice syntax though - it fe...
public static void On < T > ( this Action < T > actionToCarryOut , params T [ ] listOfThings ) { foreach ( var thing in listOfThings ) { actionToCarryOut ( thing ) ; } } Action < Control > makeInvisible = c = > c.Visible = false ; makeInvisible.On ( control1 , control2 , control3 , control4 ) ; protected void Apply < T...
C # syntax for applying an action to a varying number of objects
C#
I have the follwoing code and I would like to write it in a way that I have minimum lines of code and the work is done the same way . How can I do that ?
List < Category > categoryList = new List < Category > ( ) ; categoryList = Category.LoadForProject ( project.ID ) .ToList ( ) ; List < string > categories = new List < string > ( Categories ) ; IList < Category > currentCategories = Category.LoadForProject ( project.ID ) .ToList ( ) ; if ( currentCategories ! = null )...
How can I avoid code duplication
C#
I am reading some x and y coordinates from an XML file.The coordinates look like this 3.47 , -1.54 , .. and so on.When I assign the value to a double variable byThe Value becomes 3470.00Why is this the case ?
double x , y ; x = Convert.ToDouble ( reader [ `` X '' ] ) ; // X Value : 3.47
Why does Convert.ToDouble change my Value by factor 1000 ?
C#
I want to create a copy my object in my DB with using Entity Frameworkfirst I got my `` Book '' from DBthen , I tried to add this object as a new objectAlso I trid to initilize EntityKey of Bookit didnt workIs there any way doing this without creating new Book and copy properties from old one ? Thanks
var entity1 = new testEntities ( ) ; var book= entity1.Books.First ( ) ; entity1.Dispose ( ) ; var entity2 = new testEntities ( ) ; book.Id = 0 ; entity2.SaveChanges ( ) ; entity2.Dispose ( ) ;
How to Add existing entity as a new Entity with Entity Framework
C#
I am converting a codebase to C # 8 with nullable reference types . I came across the a method similar to the one in this question but async.T may be any type , including nullable reference types or nullable value types.To be clear , I understand WHY this method triggers a warning . What I 'd like to know is what annot...
public async Task < T > GetAsync < T > ( ) { // sometimes returns default ( T ) ; = > warning CS8603 Possible null reference return }
Proper nullable annotation for async generic method that may return default ( T )
C#
The BackgroundI have converted the C # code below ( found in TreeViewAdv file TreeColumn.cs ) into VB.net code using the converter found at DeveloperFusion.com . C # VBThe ProblemAccess to TreeColumn.TreeColumnConverter in this line of the C # code is fine . [ TypeConverter ( typeof ( TreeColumn.TreeColumnConverter ) )...
using System ; // ... ( other using calls ) namespace Aga.Controls.Tree { [ TypeConverter ( typeof ( TreeColumn.TreeColumnConverter ) ) , DesignTimeVisible ( false ) , ToolboxItem ( false ) ] public class TreeColumn : Component { private class TreeColumnConverter : ComponentConverter { public TreeColumnConverter ( ) : ...
`` Private '' visibility modifier - how to handle differences when converting C # to VB ?
C#
What I basically wish to do is design a generic interface that , when implemented , results in a class that can behave exactly like T , except that it has some additional functionality . Here is an example of what I 'm talking about : And this is all well and good , but in order to use CoolInt , I need to do something ...
public interface ICoolInterface < T > { T Value { get ; set ; } T DoSomethingCool ( ) ; } public class CoolInt : ICoolInterface < int > { private int _value ; public CoolInt ( int value ) { _value = value ; } public int Value { get { return _value ; } set { _value = value ; } } public int DoSomethingCool ( ) { return _...
C # Interfaces : Is it possible to refer to the type that implements the interface within the interface itself ?
C#
To my surprise , this one compiles and runs : The method is public whereas the default value `` redirects '' to a constant private variable.My question : What is/was the idea behind this `` concept '' ? My understanding ( until today ) was , that something public can only be used if all other `` referenced '' elements ...
class Program { static void Main ( ) { DoSomething ( ) ; } private const int DefaultValue = 2 ; // < -- Here , private . public static void DoSomething ( int value = DefaultValue ) { Console.WriteLine ( value ) ; } } static class Program { private static void Main ( ) { Program.DoSomething ( 2 ) ; } private const int D...
What 's the idea behind allowing private constant to be used as default parameters for public methods ?
C#
What happens if I pass a data member by reference to a function , and while that function is running , the Garbage Collector starts running and moves the object containing the data member in memory ? How does the CLR make sure reference parameters do n't become invalid during Garbage Collection ? Are they adjusted just...
class SomeClass { int someDataMember ; void someMethod ( ) { SomeClass.someFunction ( ref someDataMember ) ; } static void someFunction ( ref int i ) { i = 42 ; int [ ] dummy = new int [ 1234567890 ] ; // suppose the Garbage Collector kicks in here i = 97 ; } }
passing data members by reference
C#
I have a little C # problem . I have two classes ClassA and ClassB defined in this way : As you can see , ClassA has an instance of ClassB.The thing is , from a list of ClassA instances , I want to access to a list of the corresponding ClassB instances . I suppose it would look like this : The solution is probably obvi...
public class ClassA { private ClassB b ; ClassB B ; { get { return b ; } set { b = value ; } } } public class ClassB { /* some stuff */ } IList < ClassA > listA = ... ; IList < ClassB > listB = listA. ? ? ? .B ;
Class associations and lists
C#
I was browsing the source of the PluralizationService when I noticed something odd . In the class there are a couple of private dictionaries reflecting different pluralisation rules . For example : What are the groups of four dashes in the strings ? I did not them see handled in the code , so they 're not some kind of ...
private string [ ] _uninflectiveWordList = new string [ ] { `` bison '' , `` flounder '' , `` pliers '' , `` bream '' , `` gallows '' , `` proceedings '' , `` breeches '' , `` graffiti '' , `` rabies '' , `` britches '' , `` headquarters '' , `` salmon '' , `` carp '' , `` -- -- '' , `` scissors '' , `` ch -- -- is '' ...
What are the groups of four dashes in the .NET reference source code ?
C#
Is there a mechanism for the new c # 8 using statement to work without a local variable ? Given ScopeSomething ( ) returns a IDisposable ( or null ) ... Previously : However in C # 8 with the using statement , it requires a variable name : The _ here is not treated as a discard.I would have expected this to have worked...
using ( ScopeSomething ( ) ) { // ... } using var _ = ScopeSomething ( ) ; using ScopeSomething ( ) ;
using statement in C # 8 without a variable
C#
What happens when I add a method to existing delegate ? I mean when I added the method1 to del , del holds the address of method1 . When I add method2 afterwards , del still points to Method1 and Method 2 address is inserted on the bottom of it . Does n't this mean I changed the delegate ? If I can change this why in t...
MyDel del = method1 ; del += method2 ; del += method3 ;
Delegates are immutable but how ?
C#
I 'm running into a problem where as I have an implied unsigned hexadecimal number as a string , provided from user input , that needs to be converted into a BigInteger.Thanks to the signed nature of a BigInteger any input where the highest order bit is set ( 0x8 / 1000b ) the resulting number is treated as negative . ...
var style = NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier ; BigInteger.TryParse ( `` 6 '' , style ) == 6 // 0110 binBigInteger.TryParse ( `` 8 '' , style ) == -8 // 1000 binBigInteger.TryParse ( `` 9 '' , style ) == -7 // 1001 binBigInteger.TryParse ( `` A '' , style ) == -6 // 1010 bin ... BigInteger.TryPars...
What is the proper way to construct a BigInteger from an implied unsigned hexadecimal string ?
C#
In my WPF application I have a sort of node graph . I have added a ContextMenu to these nodes , which appears when I right-click on stuff and so on.The commands in the context menu come from a Service ( Microsoft.Practices.ServiceLocation.ServiceLocator ) with DelegateCommands , and those commands are updated with Rais...
private void ContextMenu_ContextMenuOpening ( object sender , RoutedEventArgs e ) { ServiceLocator.Current.GetInstance < IMenuCommandService > ( ) .ReloadICommandConditions ( ) ; } public void ReloadICommandConditions ( ) { ( ( DelegateCommand < Node > ) MyCommand ) .RaiseCanExecuteChanged ( ) ; } < ContextMenu > < Men...
RaiseCanExecuteChanged delay with ContextMenu
C#
I am trying to write the following : I would like to write a method `` A '' which takes as parameter another method `` B '' as well as an unknown number of parameters for this method B . ( params object [ ] args ) . Now , inside method A i would like to make a call to B with the parameters args . B will now return an o...
public object A ( Func < object > B , params object [ ] args ) { object x = B.Method.Invoke ( args ) ; return x ; }
C # Method that executes a given Method
C#
I was surprised that there would be any runtime difference between these two delegates ( fn1 and fn2 ) : But apparently the second lambda is treated like an instance method , because its Target property is non-null . And it was treated differently before I switched to Visual Studio 2015 ( in VS2012 , I am pretty sure i...
static int SomeStaticMethod ( int x ) { return x ; } // fn1.Target == null in this caseFunc < int , int > fn1 = SomeStaticMethod ; // fn2.Target ! = null in this caseFunc < int , int > fn2 = x = > x ; private static Func < int , TEnum > CreateIntToEnumDelegate ( ) { Func < int , int > lambda = x = > x ; return Delegate...
Lambda treated as a closed delegate in Roslyn
C#
When running We see a difference when using different framework versions.vsAlso why would I see different a NumberFormat.CurrencyPositivePattern between machines . Is it framework specific or related to the OS ? 40,00 kr . vs kr . 20,00
var x = 10.0M ; Console.WriteLine ( typeof ( Program ) .Assembly.ImageRuntimeVersion ) ; var culture = System.Globalization.CultureInfo.GetCultureInfo ( `` da-DK '' ) ; Console.WriteLine ( culture.NumberFormat.CurrencyPositivePattern ) ; Console.WriteLine ( x.ToString ( `` C '' , culture ) ) ; v2.0.50722kr 10,00 v4.0.3...
What controls the CurrencyPositivePattern in .NET
C#
I want to create a wrapper around this existing helper : How can I create a helper to wrap this and add a parameter to it ? My Controller has a property : I want to somehow reference this value from my controller and use it like : How can I do this ? Is the only way to add IsAdmin to my ViewModel ?
@ Content.Url ( `` ... '' ) public bool IsAdmin { get ; set ; } @ MyContent.Url ( `` ... '' , IsAdmin )
How to create a wrapper helper around Url.Content helper function ?
C#
I have static e paper but i want to develop dynamic e-paper like below urlhttps : //epaper.dawn.com/ ? page=15_04_2019_001I have no idea to start e paper dynamic below is my whole html codei am not getting any idea to implement dynamic , i have to take repeater control or grid view control to achieve dynamic e paper . ...
< ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge , chrome=1 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 , shrink-to-fit=no '' > < title > q Times < /title > < link rel= '' stylesheet '' href= '' css/main...
Trying to make epaper dynamic using C # asp.net web form
C#
I do n't understand why it 's working ... The IL code : It compiles to bool Object.Equals ( Object , Object ) , but why ?
class Program { static void Main ( string [ ] args ) { IComparable.Equals ( 12 , 3 ) ; } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 21 ( 0x15 ) .maxstack 8 IL_0000 : nop IL_0001 : ldc.i4.s 12 IL_0003 : box [ mscorlib ] System.Int32 IL_0008 : ldc.i4.3 IL_0009 ...
IComparable magic - why it 's a valid statement ?
C#
why does n't the element get swappedeven if the parameter is without a ref modifier the array does n't change.a copy of the reference is passed as a parameter right ?
public static void SwapArray ( int [ , ] arr ) { for ( int i = 0 ; i < arr.GetLength ( 0 ) ; i++ ) { for ( int j = 0 ; j < arr.GetLength ( 0 ) ; j++ ) { int temp = arr [ i , j ] ; arr [ i , j ] = arr [ j , i ] ; arr [ j , i ] = temp ; } } }
basic c # question
C#
I am going through the Head First C # book and I ca n't figure out why they used the following way to create a property . It just seems inconsistent with the convention I 'm seeing everywhere else and in the book itself too . I understand that the pattern for creating properties is : Based on the above pattern I would ...
private int myVar ; public int MyProperty { get { return myVar ; } set { myVar = value ; } } private decimal cost ; public decimal Cost { get { cost = CalculateCostOfDecorations ( ) + ( CalculateCostOfBeveragesPerPerson ( ) + CostOfFoodPerPerson ) * NumberOfPeople ; if ( HealthyOption ) { cost *= .95M ; } return cost ;...
Head First C # : strange way to create a read-only property
C#
I have an application where you can select between different objects in a ListBox . When you select an object , it changes the viewmodel for a control . The control utlizes the Timeline Control from CodePlex , and because of this , I have the StartDate and EndDate for the timeline data bound to ViewModel . When the Vie...
ArgumentOutOfRangeException : MaxDateTime can not be less then MinDateTime MaxDateTime= '' { Binding Path=RecordingEnd } '' MinDateTime= '' { Binding Path=RecordingStart } '' CurrentDateTime= '' { Binding Path=CurrentDateTime , Mode=TwoWay } '' private int myObjectIndex ; public int MyObjectIndex { get { return myObjec...
OnPropertyChange Firing Order
C#
Is this kind of if-testing necessary when removing an item ? And , what about this test ?
if ( _items.Contains ( item ) ) { _items.Remove ( item ) ; } if ( ! _items.Contains ( item ) ) { _items.Add ( item ) ; }
C # List < T > Contains test
C#
The code below is part of authorization . I am trying to mentally imaging what it actually does but could not somehow . Could anyone explain this lambda expression to me ? Thanks ! Edit : IsAuthorized is a delegate type . The previous programmer who code this seems want to keep it secret by putting delegate to the end ...
IsAuthorized = ( ( x , y ) = > x.Any ( z = > y.Contains ( z ) ) ) ; public delegate bool IsAuthorized ( IEnumerable < Int32 > required , IEnumerable < Int32 > has ) ; IsAuthorized = ( ( x , y ) = > x.Any ( z = > y.Contains ( z ) ) ) ;
Could anyone explain this lambda expression to me ? It 's kind getting me crazy
C#
Like there are many Applications which are just basic but you can have install add-ins for it which extends its functionality in that Application . For example : How do they design such applications and how does the application accept the module and how can it automatically integrate.Secondly I do not know if the above...
Fire Bug in Mozilla Firefox .
Designing Application that can accept add ins
C#
I 've simple Linq2Sql query : The problem is that it seems that new SomeLinq2SqlEntity ( ) is executed only once for the sequence , so all instances of MyViewModelClass in result of the query share the link to one object.Update : Here is how I quickly check it : Using debugger I can check that MyField was set to 10 in ...
var result = from t in MyContext.MyItems select new MyViewModelClass ( ) { FirstProperty = t , SecondProperty = new SomeLinq2SqlEntity ( ) } result [ 0 ] .SecondProperty.MyField = 10 ; var result = from t in MyContext.MyItems select t ; var list = new List < MyViewModelClass > ( ) ; foreach ( var item in result ) { lis...
`` new '' inside concrete type projection is only called once
C#
Does Linq use any sorting or other mechanisms to make a group join more efficient so it does n't have to loop through an entire collection for every unmatched item ? In other words , Is this : more efficient than this :
var x = listA.GroupJoin ( listB , a = > a.prop , b = > b.prop , ( a , b ) = > new { a , b } ) .Where ( ! x.b.Any ( ) ) .Select ( x = > x.a ) ; var x = listA.Where ( a = > listB.All ( b = > b.prop ! = a.prop ) ) ;
Efficiency of Linq GroupJoin vs. Linq All in Select
C#
We 've got a slight performance issue in a section of code that 's using LINQ and it 's raised a question about how LINQ works in terms of lookupsMy question is this ( please note that I have changed all the code so this is an indicative example of the code , not the real scenario ) : GivenIf I had a list of say 100k P...
public class Person { int ID ; string Name ; DateTime Birthday ; int OrganisationID ; } var personBirthdays = from Person p in personList where p.OrganisationID = 123 select p.Birthday ; foreach ( DateTime d in dateList ) { if ( personBirthdays.Contains ( d ) ) Console.WriteLine ( string.Format ( `` Date : { 0 } has a ...
Does this LINQ code perform multiple lookups on the original data ?
C#
Suppose we had the following : I am using Autofac to register all of my components that implement IFoo : When I later resolve my dependencies with : I should get all of the classes that implement IFoo except the contract class ( es ) . How do I prevent all of my contract classes from resolving without moving them to a ...
[ ContractClass ( typeof ( ContractClassForIFoo ) ) ] public interface IFoo { int DoThing ( string x ) ; } public class Foo : IFoo { ... } [ ContractClassFor ( typeof ( IFoo ) ) ] public class ContractClassForIFoo : IFoo { public int DoThing ( string x ) { Contract.Requires < ArgumentNullException > ( x ! = null ) ; re...
Autofac and Contract classes
C#
Here is my code which is used widely in project , and I 'm wondering can I refactor this somehow so I might avoid == null checks all the time ? Thanks guysCheers
ActiveCompany = admin.Company == null ? false : admin.Company.Active
How could I avoid == null checking ?
C#
I have a simple object that looks like this : I tried this code I found somewhere on the net : But somehow the returning byte array has a size of 248 bytes.I would expect it to be 4 bytes x 4 fields = 16 bytes.QUESTION : What 's the cleanest way to convert a fixed object into a byte array ? And should the resulting arr...
public class Foo { public UInt32 One { get ; set ; } public UInt32 Two { get ; set ; } public UInt32 Three { get ; set ; } public UInt32 Four { get ; set ; } } public byte [ ] ObjectToByteArray ( Object obj ) { MemoryStream fs = new MemoryStream ( ) ; BinaryFormatter formatter = new BinaryFormatter ( ) ; formatter.Seri...
Fixed Object to Byte Array
C#
Consider the following code ( for the sake of this test , it does n't do anything of particular use - it 's just to demonstrate the error that occurs ) I want to wrap Dictionary < string , dynamic > using inheritance : Here is the examle above using this derived class : This happens ... Any ideas on what is causing the...
Dictionary < string , dynamic > d = new Dictionary < string , dynamic > ( ) { { `` a '' , 123 } , { `` b '' , Guid.NewGuid ( ) } , { `` c '' , `` Hello World '' } } ; d.Where ( o = > o.Key.Contains ( `` b '' ) ) .ForEach ( i = > Console.WriteLine ( i.Value ) ) ; //retuns the Guid value , as expected . public class Cust...
C # compilation error with LINQ and dynamic inheritance
C#
I have the following code : and when I run the test `` TestFoo ( ) '' , the console output is `` Foo - string '' . How does the compiler decide which method to call ?
[ TestMethod ] public void TestFoo ( ) { Foo ( null ) ; } private void Foo ( object bar ) { Console.WriteLine ( `` Foo - object '' ) ; } private void Foo ( string bar ) { Console.WriteLine ( `` Foo - string '' ) ; }
How does the compiler choose which method to call when a parameter type is ambiguous ?
C#
Basically , is it better practice to store a value into a variable at the first run through , or to continually use the value ? The code will explain it better : or
TextWriter tw = null ; if ( ! File.Exists ( ConfigurationManager.AppSettings [ `` LoggingFile '' ] ) ) { // ... tw = File.CreateText ( ConfigurationManager.AppSettings [ `` LoggingFile '' ] ) ; } TextWriter tw = null ; string logFile = ConfigurationManager.AppSettings [ `` LoggingFile '' ] .ToString ( ) ; if ( ! File.E...
Read a value multiple times or store as a variable first time round ?
C#
I have the following code in my .Net 4 app : This givens me an ensures unproven warning at compile time : What is going on ? This works fine if S is an integer . It also works if I change the Ensure to S == Contract.OldValue ( S + `` 1 '' ) , but that 's not what I want to do .
static void Main ( string [ ] args ) { Func ( ) ; } static string S = `` 1 '' ; static void Func ( ) { Contract.Ensures ( S ! = Contract.OldValue ( S ) ) ; S = S + `` 1 '' ; } warning : CodeContracts : ensures unproven : S ! = Contract.OldValue ( S )
Why is this string-based Contract.Ensure call unproven ?
C#
i have a path data that i coppy it from syncfusion program.i have a path with that data in my page and want to animate my object exact on path way ( in mid of path line ) but the problem is the object move on outline ( surroundings ) of path .here is code : Edit 1 : my animation go wrong way . i want my Rectangle move ...
< Canvas ClipToBounds= '' False '' Margin= '' 435,58,279,445 '' Width= '' 70 '' Height= '' 70 '' > < Path Name= '' pp '' Data= '' M29.073618888855,0C29.1124091148376,1.1444091796875E-05 29.1515617370605,0.00176620483398438 29.1909990310669,0.00532913208007813 29.810998916626,0.0533294677734375 30.3119988441467,0.530315...
MatrixAnimationUsingPath animate on surroundings ( outline ) of path
C#
I have been working a little bit with LINQ recently , and thanks to the help of some StackOverflowers I was able to get this statement working : However , I am confused because the piece that makes it work is the if ( traceJob.Count ( ) ==1 ) . If I remove that section , then I get an ObjectNullRef error saying that th...
var traceJob = from jobDefinition in service.JobDefinitions where jobDefinition.Id == traceGuid select jobDefinition ; if ( traceJob ! = null & & traceJob.Count ( ) == 1 ) { traceJob.First ( ) .RunNow ( ) ; Console.WriteLine ( traceJob.First ( ) .DisplayName + `` Last Run Time : `` + traceJob.First ( ) .LastRunTime ) ;...
Why does an IF Statement effect the outcome of my LINQ Statement ?
C#
I have this simple LINQ query , which executes for 8395 ms : Its IL : when it executes , it generates the following SQL query , which takes 661 ms to execute : What was Entity Framework ( version= '' 6.1.0.133 '' ) doing all that time ? Little change to the LINQ query , namely removing ToString ( ) call in the select p...
var _context = new SurveyContext ( ) ; _context.Database.Log = Console.WriteLine ; ( from p in _context.Participants join row in _context.ListAnswerSelections on new { p.Id , QuestionId = 434 } equals new { Id = row.RelatedParticipantId , QuestionId = row.RelatedQuestionId } select new { V = row.NumericValue.ToString (...
Why does ToString ( ) degrade Entity Framework 's performance so dramatically
C#
Why ca n't I use code like this ? 12And should write like this12PS : I can use if-else statement without { } . Why should I use them with try-catch ( -finally ) statement ? Is there any meaningful reason ? Is it only because that some people think that code is hard to read ? Several months ago I asked that question on ...
int i = 0 ; try i = int.Parse ( `` qwerty '' ) ; catch throw ; try i = int.Parse ( `` qwerty '' ) ; catch ; finally Log.Write ( `` error '' ) ; int i = 0 ; try { i = int.Parse ( `` qwerty '' ) ; } catch { throw ; } try { i = int.Parse ( `` qwerty '' ) ; } catch { } finally { Log.Write ( `` error '' ) ; }
Why does it not allowed to use try-catch statement without { } ?
C#
Possible Duplicate : “ new ” keyword in property declaration Pardon me if this is C # 101 , but I am trying to understand the code below : Why does the indexer have new in front of it ? By the way , Rabbit is a class defined in another file . Thanks !
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Collections ; namespace Generics { class RabbitCollection : ArrayList { public int Add ( Rabbit newRabbit ) { return base.Add ( newRabbit ) ; } //collections indexer public new Rabbit this [ int index ] { get { return...
Why does this code have new in the collections indexer
C#
Specifically , if you create an instance of a Timer in the local scope , and then return from that scope:1 ) Will the timer still execute ? 2 ) When would it be garbage collected ? I offer these two scenarios : And
Timer timer = new Timer ( new TimerCallback ( ( state ) = > { doSomething ( ) ; } ) ) ; timer.Change ( ( int ) TimeSpan.FromSeconds ( 30 ) , ( int ) TimeSpan.FromSeconds ( 30 ) ) ; return ; Timer timer = new Timer ( new TimerCallback ( ( state ) = > { doSomething ( ) ; } ) ) ; timer.Change ( ( int ) TimeSpan.FromSecond...
What is the expected behavior of a locally scoped Timer ?
C#
I 'm stuck with a weird problem ( which is probably my lack of knowledge ) , I present the offending code : f and fTemp are FileInfo objects . So if I run this with code where f is a video file playing in a mediaplayer it throws the exception . That works fine and as expected . Now when I close the mediaplayer it delet...
try { f.Delete ( ) ; fTemp.MoveTo ( f.FullName ) ; Console.WriteLine ( `` INFO : Old file deleted new file moved in > { 0 } '' , f.FullName ) ; } catch ( IOException ex ) { Console.WriteLine ( `` ERROR : Output file has IO exception > { 0 } '' , f.FullName ) ; Environment.ExitCode = 1 ; } if ( ! IsFileLocked ( f ) ) { ...
Delete functions deletes even when calling app is closed
C#
I 've this piece of code : If I build my application in Debug mode everything is ok , test index pre prints 12 and test index post prints 14. the same in Release mode with Optimize code unchecked . if i test with Optimize code checked test index post prints 18 instead of 14.Same result if I replace index += ethType.Len...
private void AnswerToCe ( int currentBlock , int totalBlock = 0 ) { byte [ ] bufferToSend ; byte [ ] macDst = mac ; byte [ ] macSrc = ConnectionManager.SInstance.GetMyMAC ( ) ; byte [ ] ethType ; byte [ ] header ; if ( Function == FlashFunction.UPLOAD_APPL || Function == FlashFunction.UPLOAD_BITSTREAM ) { ethType = Bit...
RyuJIT C # wrong sum result with /optimize
C#
Why is it when I turn on `` check for arithmetic underflow/overflow '' under C # Project Properties > Build > Advanced , that the following code runs faster ( 138 ms ) than if I turn the option off ( 141 ms ) ? Test Run # 1 : 138ms with checked arithmetic , 141ms withoutOn the other hand , if you comment out the if ( i...
using System ; using System.Diagnostics ; class Program { static void Main ( string [ ] args ) { var s = new Stopwatch ( ) ; s.Start ( ) ; int a = 0 ; for ( int i = 0 ; i < 100000000 ; i += 3 ) { if ( i == 1000 ) i *= 2 ; if ( i % 35 == 0 ) ++a ; } s.Stop ( ) ; Console.WriteLine ( s.ElapsedMilliseconds ) ; Console.Writ...
Why is checked arithmetic in .NET sometimes faster than unckecked ?
C#
Let 's say you wrote a custom enumerator for the code below : And then in the client code , you did this : Then , set a break-point on the MoveNext method implementation of your StudentEnumerator class.Then when you run the code and the debugger breaks after constructing the query / IEnumerable in this case , and you e...
public class School : IEnumerable < Student > static void Main ( string [ ] args ) { var school = CreateSchoolWithStudents ( ) ; var query = from student in school where student.Name.StartsWith ( `` S '' ) select student ; Debugger.Break ( ) ; } private static School CreateSchoolWithStudents ( ) { return new School { n...
How does Visual Studio evaluate the IEnumerable without breaking into its IEnumerator < T > 's MoveNext ?
C#
Consider these two definitions for GetWindowText . One uses a string for the buffer , the other uses a StringBuilder instead : Here 's how you call them : They both seem to work correctly whether I pass in a string , or a StringBuilder . However , all the examples I 've seen use the StringBuilder variant . Even PInvoke...
[ DllImport ( `` user32.dll '' , CharSet = CharSet.Auto , SetLastError = true ) ] public static extern int GetWindowText ( IntPtr hWnd , StringBuilder lpString , int nMaxCount ) ; [ DllImport ( `` user32.dll '' , CharSet = CharSet.Auto , SetLastError = true ) ] public static extern int GetWindowText ( IntPtr hWnd , str...
For C # , is there a down-side to using 'string ' instead of 'StringBuilder ' when calling Win32 functions such as GetWindowText ?
C#
I have discovered that if i run following lines of code.No boxing is done , but if i call i.GetType ( ) ( another derived function from System.Object ) in place of GetHashCode ( ) , a boxing will be required to call GetType ( ) , Why its not possible to call GetType ( ) on primitive type instance directly , without box...
int i = 7 ; i.GetHashCode ( ) ; //where GetHashCode ( ) is the derived //function from System.Object
Why calling some functions of the Object class , on a primitive type instance , need boxing ?
C#
As I do n't know how my problem is called , I can not guarantee , that nobody has asked the same question recently or at all.I did notice , however that there are quite a few threads with a similar title , but they do n't seem to be relevant to my problem.I have a custom list class , that implements Generics.I also hav...
class MyList < T > { public void add ( T item ) // adds an item to the list { /* code */ } public void add ( MyList < T > list ) // attaches an existing list to the end of the current one { /* code */ } } class Apple : Fruit class Banana : Fruit MyList < Fruit > fruitList = new MyList < Fruit > ( ) ; // fill fruitListf...
About Generics and Inheritance ( forgive my bad title )
C#
The following is a code snippet about covariance in C # . I have some understanding about how to apply covariance , but there is some detailed technical stuff that I have hard time grasping.Invoking IExtract < object > .Extract ( ) invokes IExtract < string > .Extract ( ) , as evidenced by the output . While I kind of ...
using System ; namespace CovarianceExample { interface IExtract < out T > { T Extract ( ) ; } class SampleClass < T > : IExtract < T > { private T data ; public SampleClass ( T data ) { this.data = data ; } //ctor public T Extract ( ) // Implementing interface { Console.WriteLine ( `` The type where the executing metho...
C # covariance confusion
C#
I have a troublesome query to write . I 'm currently writing some nasty for loops to solve it , but I 'm curious to know if Linq can do it for me.I have : and a list that contains these structs . Let 's say it 's ordered this way : If you put the orderedList struct dates in a set they will always be contiguous with res...
struct TheStruct { public DateTime date { get ; set ; } // ( time portion will always be 12 am ) public decimal A { get ; set ; } public decimal B { get ; set ; } } List < TheStruct > orderedList = unorderedList.OrderBy ( x = > x.date ) .ToList ( ) ;
How can I use `` Linq to Objects '' to put a set of contiguous dates in one group ?
C#
I have a .dll and a console app that uses the said .dll but does n't reference directly , it loads it via reflection . The console app calls a method of a class inside the .dll.The method signature is IEnumerable < Customer > GetAll ( ) ; In the .dll I have done this : In the Console app I 've done this : Now the quest...
class CustomerRepository : ICustomerRepository { public IEnumerable < Customer > GetAll ( ) { using ( var db = new DB02Context ( ) ) { List < Customer > list = new List < Customer > ( ) ; // some queries to fill the list return list ; } } } Assembly assembly = Assembly.LoadFrom ( pathToMyDLL ) ; Type t = assembly.GetTy...
Access to type T properties of IEnumerable < T > returned from a method called via reflection
C#
The following codeThrows a run-time KeyNotFoundException , albeit that { 1 } is a perfectly well-formed array ( i.e . int [ ] a = { 1,2,3,4 } being valid code ) . Changing the TValue of the Dictionary to int [ ] , throws a compile-time CS1061 , but this does not ( note the added new [ ] array-allocation ) : Why does th...
new Dictionary < string , List < int > > { [ `` a '' ] = { 1 } , } ; new Dictionary < string , IEnumerable < int > > { [ `` a '' ] = new [ ] { 1 } , } ;
Reason for KeyNotFoundException in Dictionary initialization
C#
Do I need to add a lock block here if I want to be sure that instance will be created only 1 time ? Since there is only 1 instruction within the IF I 'm not 100 % sure . In a case like below , I 'm sure I 'd need it but I wanted to double check if the same applies for the code above.EDITYes , I assume multithreading
if ( instance==null ) { instance = new Class ( ) ; } if ( instance==null ) { int i = 5 ; int y = 78 ; instance = new Class ( i , y ) ; }
Do I need a lock here ?