lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Consider the following code block : The output is : 3,2 . I 'm trying to understand what happens behind the scenes when this code is running.The compiler generates this new class : The question if how does the x variable get 's changed . How does the x inside < > _DiplayClass1 is changing the x inside Program class . I...
int x = 1 ; D foo = ( ) = > { Console.WriteLine ( x ) ; x = 2 ; } ; x = 3 ; foo ( ) ; Console.WriteLine ( x ) ; var temp = new < > c_DisplayClass1 ( ) ; temp.x = this.x ; temp. < Main > b_0 ( ) ; this.x = temp.x ;
Deep diving into the implementation of closures
C#
I have an application that works but after a while when I debug on my iPhone it hangs the phone and the only way I can recover is a hard reset of the button on the side and the home button . First of all , could that be because my application has a memory leak ? Here 's the code for the application . In particular , I ...
namespace Japanese { public partial class PhrasesFrame : Frame { CancellationTokenSource cts = new CancellationTokenSource ( ) ; public PhrasesFrame ( PhrasesPage phrasesPage ) { InitializeComponent ( ) ; this.phrasesPage = phrasesPage ; AS.phrasesFrame = this ; Device.BeginInvokeOnMainThread ( ( ) = > ShowCards ( cts....
Could a BeginInvokeOnMainThread method be looping and causing a memory leak ?
C#
Is it possible to check if a type is part of a namespace without using harcoded strings ? I 'm trying to do something like : orto avoidThese examples do n't compile but should give an idea of what I 'm trying to achieve.I ca n't use nameof ( System.Data ) because it only returns `` Data '' .I would like to find a way t...
Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == System.Data.ToString ( ) ) { ... } Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == System.Data ) { ... } Type type = typeof ( System.Data.Constraint ) ; if ( type.Namespace == `` System.Data '' ) { ... }
Check if a type belongs to a namespace without hardcoded strings
C#
I 've been studying Tasks in .net 4.0 and their cancellation . I like the fact that TPL tries to deal with cancellation correctly in cooperative manner.However , what should one do in situation where a call inside a task is blocking and takes a long time ? For examle IO/Network.Obviously cancelling writes would be dang...
Task.Factory.StartNew ( ( ) = > WebClient client = new WebClient ( ) ; client.DownloadFile ( url , localPath ) ; ) ;
What would be a good way to Cancel long running IO/Network operation using Tasks ?
C#
I have this simple LINQ queryHere DesignationID is a nullable field : In objectcontext the query is translated to : While the same query in dbcontext it is translated to : Why does objectcontext handle NULL differently than dbcontext ?
from e in Employees where e.DesignationID ! =558select e SELECT [ Extent1 ] . [ EmployeeID ] AS [ EmployeeID ] , [ Extent1 ] . [ EmployeeCode ] AS [ EmployeeCode ] , [ Extent1 ] . [ EmployeeName ] AS [ EmployeeName ] , [ Extent1 ] . [ DesignationID ] AS [ DesignationID ] FROM [ dbo ] . [ setupEmployees ] AS [ Extent1 ]...
NULL handling in dbcontext and objectcontext
C#
In the software I am writing I will read some data from an external device ( connected via USB ) . The drivers I have been given ( dll file ) are not thread safe and only one instance can be used at a time . I have to write a wrapper to these drivers in C # . Given that I have a multi-threaded application , I would lik...
using System ; using System.Runtime.InteropServices ; namespace Philips.Research.Myotrace.DataReading.Devices { class MyDevice : IDisposable { private static volatile MyDeviceInstance ; private static object SyncRoot = new Object ( ) ; private bool disposed = false ; private MyDevice ( ) { //initialize unmanaged resour...
How to make sure we have only one instance , and it is disposed in a correct way
C#
what happens when I include the same field twice , meaningly I take from db an entity and I use the EF .include option . What I mean is this : I have : This is the model : so by including ( by mistake ) the student twice ( since my person has ONLY a student ) , is there an issue ? P.S . I only want it included ONCE ! s...
.Include ( x = > x.Student ) .Include ( x = > x.Car ) .Include ( x = > x.Student ) Person has a StudentPerson has a car
Behaviour when including the same field twice in entity framework linq
C#
I have code that creates a cancellation tokenCode that uses it : and code that later cancels this Cancellation Token if the user moves away from the screen where the code above is running : Regarding cancellation , is this the correct way to cancel the token when it 's being used in a Task ? In particular I checked thi...
public partial class CardsTabViewModel : BaseViewModel { public CancellationTokenSource cts ; public async Task OnAppearing ( ) { cts = new CancellationTokenSource ( ) ; // < < runs as part of OnAppearing ( ) await GetCards ( cts.Token ) ; public async Task GetCards ( CancellationToken ct ) { while ( ! ct.IsCancellatio...
Is the correct way to cancel a cancellation token used in a task ?
C#
These two methods exhibit repetition : How can I refactor to eliminate this repetition ? UPDATE : Oops , I neglected to mention an important point . FooEditDto is a subclass of FooDto .
public static Expression < Func < Foo , FooEditDto > > EditDtoSelector ( ) { return f = > new FooEditDto { PropertyA = f.PropertyA , PropertyB = f.PropertyB , PropertyC = f.PropertyC , PropertyD = f.PropertyD , PropertyE = f.PropertyE } ; } public static Expression < Func < Foo , FooListDto > > ListDtoSelector ( ) { re...
Refactor To Eliminate Repetition In Lambda Expression
C#
I have noticed this piece of code : What is the purpose of @ ? Are there other uses ?
FileInfo [ ] files =new DirectoryInfo ( @ '' C : \ '' ) .GetFiles ( ) ;
What are all the usages of ' @ ' in C # ?
C#
With the following one-to-one models , both with navigation properties : -Foo has an optional Bar.Bar has a required Foo.I have the following mapping on Bar : -Which creates the foreign key on the Bar table named 'FooId'.All this works fine , except it generates the sql for Foo with a 'Left Outer Join ' to Bar on all q...
public class Foo { public int Id { get ; set ; } public virtual Bar Bar { get ; set ; } } public class Bar { public int Id { get ; set ; } public virtual Foo Foo { get ; set ; } } HasRequired ( x = > x.Foo ) .WithOptional ( x = > x.Bar ) .Map ( x = > x.MapKey ( `` FooId '' ) ) ; SELECT .. [ Extent2 ] . [ Id ] AS [ Id1 ...
EF - WithOptional - Left Outer Join ?
C#
When inheriting an inherited class , the new / override behaviour is not what I would expect : As class C overrides the sayHi ( ) method I would expect the output to be From C. Why does the B class 's new modifier take precedence here ? What is the use case for that ? Especially as it breaks the obvious use case of hav...
$ cat Program.csusing System ; class A { public virtual void SayHi ( ) { Console.WriteLine ( `` From A '' ) ; } } class B : A { public new virtual void SayHi ( ) { Console.WriteLine ( `` From B '' ) ; } } class C : B { public override void SayHi ( ) { Console.WriteLine ( `` From C '' ) ; } } public class Program { publ...
What is the use case for this inheritance idiosyncrasy ?
C#
This seems very strange to me , if I do then it works perfectly fine , but if I dothen the scripts section will not get rendered and I would get `` The following sections have been defined but have not been rendered for the layout page `` ~/Views/Shared/_Layout.cshtml '' : `` scripts '' . '' errorAny idea why RenderSec...
@ RenderSection ( `` scripts '' , required : false ) @ { RenderSection ( `` scripts '' , required : false ) ; }
Razor : Render does not work inside code block
C#
I have a method like so : ... now , the variables a , b , c , and d will never be `` unassigned '' by the point where they would be referenced , but the compiler does n't see it that way . Is there a way I can force the compiler to just `` build it anyway '' ? It seems silly to initialize these values ahead of time .
public static long ? FromIpv4ToLong ( this string ipAddress ) { var octets = ipAddress.Split ( IpSplitChar ) ; if ( octets.Length ! = 4 ) return null ; var success = long.TryParse ( octets [ 0 ] , out long a ) & & long.TryParse ( octets [ 1 ] , out long b ) & & long.TryParse ( octets [ 2 ] , out long c ) & & long.TryPa...
Suppress `` Use of unassigned local variable '' error ?
C#
I have an object with properties names that exactly name the field names inside the DB table but I 'm not sure how to insert it . The only thing different is the DB table name . So it 's an object with a name of different model/mapped table but I want it to be inserted into a table with a different name than the model ...
var val = info.FooBarObj ; conn.Execute ( `` insert DBInformation ( val ) values ( @ val ) '' , new { val = val } ) ;
Inserting object that should be mapped into different DB table depending on scenario
C#
I tried to generate IL for recursive method using following strategy , Firstly I defined type using following code snippetNext I started to generate IL for recursive method as given below.For calling method itself inside the method body I used following construct , Finally save generated assembly using following method...
private void InitializeAssembly ( string outputFileName ) { AppDomain appDomain = AppDomain.CurrentDomain ; AssemblyName assemblyName = new AssemblyName ( outputFileName ) ; assemblyBuilder = appDomain.DefineDynamicAssembly ( assemblyName , AssemblyBuilderAccess.Save ) ; moduleBuilder = assemblyBuilder.DefineDynamicMod...
Generating IL for Recursive Methods
C#
I 'm trying to return a strongly typed Enumeration value from a string . I 'm sure there is a better way to do this . This just seems like way too much code for a simple thing like this : Ideas ? Based on the feedback I got from the community , I have decided to use a method extension that converts a string to an enume...
public static DeviceType DefaultDeviceType { get { var deviceTypeString = GetSetting ( `` DefaultDeviceType '' ) ; if ( deviceTypeString.Equals ( DeviceType.IPhone.ToString ( ) ) ) return DeviceType.IPhone ; if ( deviceTypeString.Equals ( DeviceType.Android.ToString ( ) ) ) return DeviceType.Android ; if ( deviceTypeSt...
How to return a Enum value from a string ?
C#
In CLR via C # , Richter notes that initializing fields in a class declaration , like soresults in inserting statements at the beginning of each constructor that set the fields to the provided values . As such , the line int x = 3 ; above will be responsible for two separate initializations -- one in the parameterless ...
class C { int x = 3 ; int y = 4 ; public C ( ) { ... } public C ( int z ) { ... } ... }
What is a real-life example of detrimental code explosion caused by field initializations ?
C#
I had a discussion in another thread , and found out that class methods takes precedence over extension methods with the same name and parameters . This is good as extension methods wo n't hijack methods , but assume you have added some extension methods to a third party library : Works as expected : ThirdParty.MyMetho...
public class ThirdParty { } public static class ThirdPartyExtensions { public static void MyMethod ( this ThirdParty test ) { Console.WriteLine ( `` My extension method '' ) ; } } public class ThirdParty { public void MyMethod ( ) { Console.WriteLine ( `` Third party method '' ) ; } } public static class ThirdPartyExte...
Extension methods overridden by class gives no warning
C#
I have a code in PCL that I want to migrate to .NetStandard . Unfortunately tho , my code is dependent on .Net reflection and I cant find some of the methods previously available . So here is the list of methods or properties that I cant find under .NetStandard . Can any one point me in right direction about how to ref...
Type.IsInstanceOfType ( ) Type.IsAssignableFrom ( ) Type.GetNestedTypes ( ) Type.GetConstructors ( ) Type.IsClassType.IsEnumType.IsValueType
.NetStandard : Missing Type Methods and Properties
C#
In the snippet below , a task creates two child tasks using the TaskCreationOptions.AttachedToParent , which means the parent task will wait for the child tasks to finish . Question is - why does n't the parent task return correct value [ 102 ] ? Does it first determine its return value and then wait for the child task...
void Main ( ) { Console.WriteLine ( `` Main start . `` ) ; int i = 100 ; Task < int > t1 = new Task < int > ( ( ) = > { Console.WriteLine ( `` In parent start '' ) ; Task c1 = Task.Factory.StartNew ( ( ) = > { Thread.Sleep ( 1000 ) ; Interlocked.Increment ( ref i ) ; Console.WriteLine ( `` In child 1 : '' + i ) ; } , T...
Returning value from Parent-Child tasks
C#
I 'm a big fan of CodeRush and their philosophy around templates . At my current job , we 'll be doing a large amount of pairing and the consensus is a preference for ReSharper ( v6 ) , which pretty much puts me in a place where I MUST use it.I 'm not looking to start a CodeRush/Resharper war here . There are plenty of...
public String MyStringProperty { get ; set ; }
CodeRush style typed templates for ReSharper
C#
I have a .sql file with stored procedures definitions.I need to write a small program in C # that reads the file and obtains a list with the stored procedures signatures . For example , this list should look like this : Is there a way to do this using Regex ? What is the best approach ?
[ dbo ] . [ procedureOne ] ( int , int , varchar ( 250 ) out , nvarchar ) [ dbo ] . [ procedureTwo ] ( int , varchar ( 255 ) ) [ dbo ] . [ procedureThree ] ( ) [ dbo ] . [ amazingSP ] ( datetime , datetime )
How to parse a stored procedure signature in C # from plain text
C#
To avoid old-fashioned non-generic syntax when searching for attributes of a known type , one usually uses the extension methods in System.Reflection.CustomAttributeExtensions class ( since .NET 4.5 ) .However this appears to fail if you search for an attribute on the return parameter of an overridden method ( or an ac...
using System ; using System.Reflection ; namespace ReflectionTrouble { class B { // [ return : MyMark ( `` In base class '' ) ] // uncommenting does not help public virtual int M ( ) = > 0 ; } class C : B { [ return : MyMark ( `` In inheriting class '' ) ] // commenting away attribute does not help public override int ...
Reflection with generic syntax fails on a return parameter of an overridden method
C#
Why do n't we get compile errors on inline code errors in asp.net mvc views f.eksThe code above will build just fine . Wrong spelling in webform controls will give you an error so I ca n't see why this is n't supported in asp.net mvcEDIT : Luckily there seem to be a fix included in the first RC for asp.net mvchttp : //...
< h1 > < % = ViewData.Model.Title.Tostrig ( ) % > < /h1 >
Build does not catch errors in the View in asp.net mvc
C#
The following program does not compile , because in the line with the error , the compiler chooses the method with a single T parameter as the resolution , which fails because the List < T > does not fit the generic constraints of a single T. The compiler does not recognize that there is another method that could be us...
namespace Test { using System.Collections.Generic ; public interface SomeInterface { } public class SomeImplementation : SomeInterface { } public static class ExtensionMethods { // comment out this line , to make the compiler chose the right method on the line that throws an error below public static void Method < T > ...
Generic extension method resolution fails
C#
I 'm a C # developer who is working through `` Real World Haskell '' in order to truly understand functional programming , so that when I learn F # , I 'll really grok it and not just `` write C # code in F # '' , so to speak.Well , today I came across an example which I thought I understood 3 different times , only to...
data List a = Cons a ( List a ) | Nil defining Show *Main > Cons 0 NilCons 0 Nil*Main > Cons 1 itCons 1 ( Cons 0 Nil ) *Main >
Please confirm or correct my `` English interpretation '' of this Haskell code snippet
C#
I have a list of recipes obtained from a database that looks like this : RecipeNode , among other things , has a property that references one or more tags ( Such as Dinner , Breakfast , Side , Vegetarian , Holiday , and about 60 others ) .Finding a random recipe from _recipeList in O ( 1 ) would of course be easy , how...
List < RecipeNode > _recipeList ; public sealed class RecipeNode { public Guid RecipeId ; public Byte [ ] Tags ; //Tags such as 1 , 5 , 6 , 8 , 43 // ... More stuff } List < RecipeNode > [ ] _recipeListByTag ;
How to pick a random element from an array that matches a certain criteria in O ( 1 )
C#
I 've created an EF Core model from an existing database and all operations on entities work EXCEPT for updates ; on updates EF Core is using an incorrect database name . eg . When I perform an update I get a SqlException : Invalid object name 'BirdBrain.dbo.services'.. BirdBrainContext is the name of my DbContext , bu...
Server=**** ; Database=BirdBrain_test ; User Id=**** ; Password=**** ; Trusted_Connection=False ; Multisubnetfailover=true ; public class BirdBrainContextFactory { private readonly string _connectionString ; public BirdBrainContextFactory ( string connectionString ) { _connectionString = connectionString ; } public Bir...
Entity Framework throws exception on updates only - Invalid object name 'dbo.BirdBrain.service '
C#
Just out of curiousity ( not really expecting a measurable result ) which of the following codes are better in case of performance ? In the first example I use char , while in the second using strings in Contains ( ) and Replace ( ) Would the first one have better performance because of the less memory-consuming `` cha...
private void ReplaceChar ( ref string replaceMe ) { if ( replaceMe.Contains ( ' a ' ) ) { replaceMe=replaceMe.Replace ( ' a ' , ' b ' ) ; } } private void ReplaceString ( ref string replaceMe ) { if ( replaceMe.Contains ( `` a '' ) ) { replaceMe=replaceMe.Replace ( `` a '' , `` b '' ) ; } }
Performance char vs string
C#
When I use code with generic : where TParent : IEnityI catch the exception : The member 'Id ' is not supported in the 'Where ' Mobile Services query expression 'Convert ( prnt ) .Id'.But if I change the generic to type : I have normal result.Why ? And how can I use generic ?
var parenttable = MobileService.GetTable < TParent > ( ) ; var testid = await parenttable.Where ( prnt = > prnt.Id == 20 ) .ToListAsync ( ) ; public interface IEnity { int Id { get ; set ; } } var parenttable = MobileService.GetTable < Category > ( ) ; var testid = await parenttable.Where ( prnt = > prnt.Id == 20 ) .To...
Mobile Services query exception
C#
IntroductionConsider this simple ( and bad ) C # class : Both methods M and L have serious issues.In M , we ask if a value of the non-nullable struct DateTime is equal to null via the lifted == operator ( which exists since DateTime overloads operator == ) . This is always falls , and the compiler can tell at compile-t...
using System ; namespace N { static class C { static void M ( DateTime d ) { if ( d == null ) Console.WriteLine ( `` Yes '' ) ; else Console.WriteLine ( `` No '' ) ; } static void L ( object o ) { if ( o is Nullable ) Console.WriteLine ( `` Yes '' ) ; else Console.WriteLine ( `` No '' ) ; } } } csc.exe /features : stri...
How to specify the equivalent of /features : strict ( of csc.exe ) to msbuild.exe or in the .csproj file ?
C#
I am trying to get certain bytes to write on an Image , for example : `` །༉ᵒᵗᵗ͟ᵋༀ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ . . . `` When I display it on an image but I am getting the following instead ... Image : I have tried changing the Encoding Type of the string , when I receive the bytes and there is no set font but...
string text = `` [ rotten4pple ] །༉ᵒᵗᵗ͟ᵋༀ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ ͟ . . . `` ; var font = new Font ( `` Arial '' , 8 , FontStyle.Regular ) ; var bitmap = new Bitmap ( 1 , 1 ) ; var size = Graphics.FromImage ( bitmap ) .MeasureString ( text , font ) ; bitmap = new Bitmap ( ( int ) size.Width + 4 , ( int ) s...
Drawing Bytes on an Image
C#
I am using this action-link to send a route value id to controller but my id value like this config.xmland here is my action-link The question is when I want to click this link browser understand this as a url that ends with config.xml like this and does n't go to the controller it returns 404 - not found.How to preven...
@ Html.ActionLink ( `` Destroy '' , `` DeleteFile '' , `` Files '' , new { id = `` config.xml '' } ) http : //localhost:12380/Files/DeleteFile/config.xml routes.MapRoute ( name : `` delete files '' , url : `` Files/DeleteFile/ { id } '' , defaults : new { controller = `` Files '' , action = `` DeleteFile '' , id= UrlPa...
ActionLink route values containing specific characters
C#
I 'm making a GenericTable as a custom implementation of GridView that will display the values of any list of objects that 's inserted.To use the control on an aspx page it needs to be a UserControl , so the GridView is included as a component in the GenericTable : This works fine for the first use of my control , it '...
< % @ Control Language= '' C # '' AutoEventWireup= '' true '' CodeBehind= '' GenericTable.ascx.cs '' Inherits= '' CASH.WebApplication.Controls.GenericTable '' % > < div style= '' width : 100 % ; overflow : scroll '' > < asp : GridView ID= '' grid '' runat= '' server '' > < /asp : GridView > < /div > var data = table.Ne...
Why are components of my custom control not initiated ?
C#
I am trying to write a single macro method in Kentico ( v8.2.x , or v9.0 ) that is cached appropriately , and exposes a POCO with a few public members.Debugging in Visual Studio , I can see that the query is running fine , and an object instance is returned exactly how I want . Furthermore , inspecting the cached items...
{ % CurrentUser.ClientStatus ( ) % } /// < summary > /// A class containing custom user-extension macros./// < /summary > [ assembly : RegisterExtension ( typeof ( CustomUserMacros ) , typeof ( CurrentUserInfo ) ) ] public class CustomUserMacros : MacroMethodContainer { /// < summary > /// Retrieves data regarding user...
Accessing nested properties in a Kentico custom object macro method
C#
I ’ m trying to adhere to good OO design principles and design patterns and such . So while developing this C # application of mine I can often find multiple solutions to design and architecture issues , I always want to find and implement the more “ canonical ” one in the hopes of building highly maintainable and flex...
abstract class Weapon { public string Name { get ; set ; } } abstract class Character { public Weapon weapon { get ; set ; } } class Sword : Weapon { public void Draw ( ) { } } class Warrior : Character { public Warrior ( ) { weapon = new Sword ( ) ; } }
Enforcing type safety of inherited members in inherited classes
C#
How is it possible to read the values , let 's say : '99 ' from an assembly containing this code ? What I have done so farThe method in ILDASM : The compiler created the struct < PrivateImplementationDetails > { 975506E6-7C24-4C2B-8956-C1B9CF8B80C4 } with the field $ $ method0x6000001-1 for the initialization value and...
using Sytem ; public class Class1 { public Class1 ( ) { // array initializer , want to read '99 ' , '100 ' ... from assembly var a = new double [ , ] { { 1 , 2 , 3 } , { 99 , 100 , 101 } } ; // ... } } .method /*06000001*/ public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed// SIG : 20 00 01 {...
How to read array initializer values from .NET assembly
C#
For my application I 'd like to use all the built in manipulation possibilities , like e.g . zoom . But if the user presses 3 fingers on the screen I 'd like to show a specific UI element . So what is the best way to check if the user has pressed 3 fingers at the same time and next to each other on the screen ? ( witho...
private void OnContactDown ( object sender , ContactEventArgs e ) { if ( this.ContactsOver.Count == 3 ) { Console.WriteLine ( `` 3 contacts down . Check proximity '' ) ; if ( areNear ( this.ContactsOver ) ) { Console.WriteLine ( `` 3 fingers down ! `` ) ; } } } private Boolean areNear ( ReadOnlyContactCollection contac...
How to check if 3 fingers are placed on the screen
C#
I have run into a strange performance issue , and it would be great with an explanation to the behavior I 'm experiencing . I 'm using System.Drawing.Region.IsVisible ( PointF ) to determine if a point is inside a polygon . This usually works very well , but yesterday I noticed that the performance of the IsVisible met...
using System ; using System.Diagnostics ; using System.Drawing ; using System.Drawing.Drawing2D ; using System.Linq ; namespace PerformanceTest { class Program { static void Main ( string [ ] args ) { // Create complex polygon with large x and y values float [ ] xValues = { 1.014498E+07f , 1.016254E+07f , 1.019764E+07f...
Region.IsVisible ( PointF ) has very slow performance for large floating point values
C#
I 'm new to LINQ and PLINQ , and I 'm building a project to test them.Stub : StubCollection : then I have some methods to iterate the stubcollection and count how many stubs have the boolean set to true : foreach : it workslinq : it works ( little slower than foreach ) plinq:100 % CPU , no resultwhy ? the only differen...
class Stub { private Boolean mytf ; public Stub ( ) { Random generator = new Random ( ) ; if ( generator.NextDouble ( ) < 0.5 ) { mytf = false ; } else mytf = true ; } public Boolean tf { get { return mytf ; } } } class StubCollection : IEnumerable { Stub [ ] stubs ; public StubCollection ( int n ) { stubs = new Stub [...
Application hangs using PLINQ AsParallel ( ) . No problems with LINQ
C#
I 'm trying to convert some VB.net code to C # . I used SharpDevelop to do the heavy lifting ; but the code it generated is breaking on some of the enum manipulation and I 'm not sure how to fix it manually.Original VB.net code : generated C # code : Resharper suggests adding the [ Flags ] attribute to the enum ; but d...
Enum ePlacement Left = 1 Right = 2 Top = 4 Bottom = 8 TopLeft = Top Or Left TopRight = Top Or Right BottomLeft = Bottom Or Left BottomRight = Bottom Or RightEnd EnumPrivate mPlacement As ePlacement '' ... mPlacement = ( mPlacement And Not ePlacement.Left ) Or ePlacement.Right public enum ePlacement { Left = 1 , Right =...
C # equivalent to `` Not MyEnum.SomeValue ''
C#
I am trying to automate some of our processes , one includes logging in to an external web page , clicking a link to expand details , then grab all details displayed.I have got the process logging in , and can grab all of the details once they are expanded.The problem is with clicking the link . The link is defined lik...
< a id= '' form : SummarySubView : closedToggleControl '' onclick= '' A4J.AJAX.Submit ( ... ) ; return false ; '' href= '' # '' > < img ... / > < /a > void browser_DocumentCompleted ( object sender , WebBrowserDocumentCompletedEventArgs e ) { WebBrowser browser = ( WebBrowser ) sender ; HtmlElement expandDetails = brow...
Screen scraping web page containing button with AJAX
C#
I have some code that maps strongly-typed business objects into anonymous types , which are then serialized into JSON and exposed via an API.After restructuring my solution into separate projects , some of my tests started to fail . I 've done a bit of digging and it turns out that Object.Equals behaves differently on ...
[ TestFixture ] public class Tests { [ Test ] public void BothInline ( ) { var a = new { name = `` test '' , value = 123 } ; var b = new { name = `` test '' , value = 123 } ; Assert.That ( Object.Equals ( a , b ) ) ; // passes } [ Test ] public void FromLocalMethod ( ) { var a = new { name = `` test '' , value = 123 } ...
Why does Object.Equals ( ) return false for identical anonymous types when they 're instantiated from different assemblies ?
C#
I 'm trying to find a way to delay all code that takes place after I make a service call . The reason for this delay is that my service returns code necesarry for the following functions and the result I pass is to these following functions is undefined.I have tried attaching the setTimeout ( ) to the function that is ...
public bool GetSpreadsheetStatusForAdmin ( string cacId ) { SpreadSheetStatus result = new SpreadSheetStatus ( ) ; List < Data.Spreadsheet > spreadsheets = SpreadsheetManager.GetUserSpreadsheets ( GetCurrent.Identity ) ; if ( spreadsheets.Count ! = 0 ) { foreach ( Data.Spreadsheet spreadsheet in spreadsheets ) { if ( s...
Jquery Delay Function Calls
C#
So now that we have generic Covariance and Contravariance on interfaces and delegates in C # , I was just curious if given a Type , you can figure out the covariance/contravariance of its generic arguments . I started trying to write my own implementation , which would look through all of the methods on a given type an...
public interface IFoo < T > { void DoSomething ( T item ) ; } public interface IFoo < in T > { void DoSomething ( T item ) ; }
Is there a way to determine the Variance of an Interface / Delegate in C # 4.0 ?
C#
I have a problem in the following code : I just want to get Exception from new started task MainTask . But the result was not what I was expected.As you can see the result , task finishes before `` Waiting Ended ! ! '' console log.I do n't have a clue that why MainTask ended even if in MainTask has await command inside...
static void Main ( string [ ] args ) { Task newTask = Task.Factory.StartNew ( MainTask ) ; newTask.ContinueWith ( ( Task someTask ) = > { Console.WriteLine ( `` Main State= '' + someTask.Status.ToString ( ) + `` IsFaulted= '' + someTask.IsFaulted+ '' isComplete= '' +someTask.IsCompleted ) ; } ) ; while ( true ) { } } s...
Why Task finishes even in await
C#
I am looking at some code and I do n't understand what a particular constraint means in the following class definition : I do n't understand what this implies about parameter type T .
internal abstract class Entity < T > : Entity where T : Entity < T > { ... }
What does this parameter type constraint mean ?
C#
I need to apply In-Memory Cache on my website with.NetFramework 4.5.2 but I get this exception : Unity.Exceptions.ResolutionFailedException : 'Resolution of the dependency failed , type = 'Tranship.UI.Areas.Portal.Controllers.SearchResultController ' , name = ' ( none ) ' . Exception occurred while : while resolving . ...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using Tranship.Business.Core ; using Tranship.Business.Interface ; using Tranship.DataAccess.UnitOfWork ; using Tranship.Domain.Context ; using Tranship.Domain.Model ; using Tranship.DomainService.In...
InvalidOperationException in Asp.Net MVC while using In-Memory Cache
C#
Possible Duplicate : Does C # support return type covariance ? I 'm not sure if I 'm just being stupid ... If I have an interface : Why ca n't I implement it like so ( I guess this would use implicit Covariance ? ) Any instance of MoopImplementor would meet the contract specified by IMoop , so it seems like this should...
public interface IMoop { object Moop ( ) ; } public class MoopImplementor : IMoop { string Moop ( ) ; }
Why ca n't I implement an Interface this way ?
C#
I have the following extension methods for my MessageBus : which compiles fine . However when I try to use it : I get the error that neither of the two candidate methodsare most specific . However I thought that Maybe < T > wouldbe more specific than T or is that not correct ? EDITIt gets curiouser because if I call th...
public static class MessageBusMixins { public static IDisposable Subscribe < T > ( this IObservable < T > observable , MessageBus bus ) where T : class { ... } public static IDisposable Subscribe < T > ( this IObservable < Maybe < T > > observable , MessageBus bus ) { ... } } IObservable < Maybe < string > > source = ....
C # specialization of generic extension methods
C#
I 'm exploring the feasibility of running a C # Kinect Visual Gesture Program ( something like Continuous Gesture Basics project https : //github.com/angelaHillier/ContinuousGestureBasics-WPF ) inside of a Docker for Windows container.Is this even theoretically possible ( run C # Kinect in a Docker for Windows containe...
FROM microsoft/dotnet-framework:4.7ADD . /home/gestureWORKDIR /home/gesture $ docker build -t kinect . $ docker run -dit -- name kinectContainer kinect $ docker exec -it kinectContainer powershell Unhandled Exception : System.BadImageFormatException : Could not load file or assembly 'Microsoft.Kinect , Version=2.0.0.0 ...
Is it possible to run Kinect V2 inside a Docker container ?
C#
Int32 struct does n't define operator overload method for == operator , so why does n't the code cause compile time error :
if ( 1 == null ) ... ;
Should n't if ( 1 == null ) cause an error ?
C#
As far as I know making class sealed gets rid of look up in VTable or am I wrong ? If I make a class sealed does this mean that all virtual methods in class hierarchy are also marked sealed ? For example :
public class A { protected virtual void M ( ) { ... ... .. } protected virtual void O ( ) { ... ... .. } } public sealed class B : A { // I guess I can make this private for sealed class private override void M ( ) { ... ... .. } // Is this method automatically sealed ? In the meaning that it does n't have to look in V...
How to get rid of virtual table ? Sealed class
C#
I have seen so many times developers using a disposable object inline , here for instance . By inline I mean : I know that the Dispose method wo n't be called , but since no reference is held to the object , how will the garbage collector handle it ? Is it safe to use a disposable object like that ? I used a DataTable ...
var result = new DataTable ( ) .Compute ( `` 1 + 4 * 7 '' , null ) ;
Is it safe to create and use a disposable object inline ?
C#
Warning : This is merely an exercise for those whose are passionate about breaking stuff to understand their mechanics.I was exploring the limits of what I could accomplish in C # and I wrote a ForceCast ( ) function to perform a brute-force cast without any type checks . Never consider using this function in productio...
Casted Original to LikeOriginal1300246376 , 5421300246376 , 542added 3Casted LikeOriginal back to Original1300246379 , 545 using System ; using System.Runtime.InteropServices ; namespace BreakingStuff { public class Original { public int a , b ; public Original ( int a , int b ) { this.a = a ; this.b = b ; } public voi...
Why does casting a struct to a similar class sort-of work ?
C#
I am working on a Universal Windows ( UWP ) app and I want to add some page NavigationTransitions to my pages . I know that I can use default NavigationThemeTransition like the code below : but I want to create my own Navigation Transition , I searched many times but no result . I also tried to get definitions of defau...
< Page.Transitions > < TransitionCollection > < NavigationThemeTransition > < NavigationThemeTransition.DefaultNavigationTransitionInfo > < CommonNavigationTransitionInfo/ > < /NavigationThemeTransition.DefaultNavigationTransitionInfo > < /NavigationThemeTransition > < /TransitionCollection > < /Page.Transitions > usin...
Create customized NavigationTransitionInfo for Page Navigation Transitions in UWP
C#
Understanding the C # Language Specification on overload resolution is clearly hard , and now I am wondering why this simple case fails : This gives compile-time error CS0121 , The call is ambiguous between the following methods or properties : followed by my two Method function members ( overloads ) .What I would have...
void Method ( Func < string > f ) { } void Method ( Func < object > f ) { } void Call ( ) { Method ( ( ) = > { throw new NotSupportedException ( ) ; } ) ; } void Call ( ) { Method ( null ) ; // OK ! }
Why ca n't the compiler tell the better conversion target in this overload resolution case ? ( covariance )
C#
I am currently teaching a colleague .Net and he asked me a question that stumped me.Why do we have to declare ? if var is implicit typing , why do we have to even declare ? becomescould become The implicit typing would still mean that this is a statically typed variable.If two different types are assigned to the variab...
Animal animal = new Animal ( ) ; var animal = new Animal ( ) ; animal = new Animal ( ) ;
Why are declarations necessary
C#
I am using an object initializer for a st object : The second initializer line gives the error : The name 'ContainedItem ' does not exist in the current context . Invalid initializer member declarator.and suggests declaring ContainedItem somewhere in local scope.Now as the first line works it can be seen that Contained...
public class Container { public Container ( ) { ContainedItem = new Item ; } public Item ContainedItem { get ; set ; } } public class Item { public string Value { get ; set ; } } var MyContainer = new Container ( ) { // I want to populate the the property Value of the property Item // with the second line rather than t...
Why does n't name exist in the current context of shorthand member initialisation ?
C#
Initially I faced this issue when I was testing my code with UnitTest framework using Assert.AreEqual methods . I noticed that for UInt32 and UInt64 types different overload of AreEqual was selected ( AreEqual ( object , object ) instead of AreEqual < T > ( T , T ) ) . I did some research and got the following simple c...
public struct MyInteger { public SByte SByte { get ; set ; } public Byte Byte { get ; set ; } public UInt16 UInt16 { get ; set ; } public UInt32 UInt32 { get ; set ; } public UInt64 UInt64 { get ; set ; } public Int16 Int16 { get ; set ; } public Int32 Int32 { get ; set ; } public Int64 Int64 { get ; set ; } } public c...
UInt32 and UInt64 types can not be inferred from the usage when used along with Int32 type in generic method
C#
I can not use a specific DLL in SSIS script-task . In c # console-project anything is fine . SSIS throws the error : Error : The Type `` Microsoft.SharePoint.Client.ClientRuntimeContext '' in assembly `` Microsoft.SharePoint.Client , Version=14.0.0.0 , Culture=neutral PublicKeyToken= ... . '' could not be loaded.I am r...
static void Main ( string [ ] args ) { using ( ClientContext clientContext = new ClientContext ( `` urltomysite.com '' ) ) { } Console.WriteLine ( `` finished '' ) ; } public void Main ( ) { //Loading assemblies extra AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler ( CurrentDomain_AssemblyResolve ) ;...
SSIS how to execute dll in script-task ( SharePoint function not found )
C#
How can I pass thru from one instantiator to another ? Suppose we had this class . How do I pass from foo ( string , string ) to foo ( Uri ) ?
public foo { string path { get ; private set ; } string query { get ; private set ; } public foo ( Uri someUrl ) { // ... do stuff here } public foo ( string path , string query ) { Uri someUrl = new Uri ( String.Concat ( path , query ) ; // ... do stuff here to pass thru to foo ( someUrl ) } }
Constructor chaining passing computed values for parameters
C#
In AutoMapper 2.0 I used Profiles to configure my mapping . I useSourceMemberNameTransformer and DestinationMemberNameTransformer to match my source and destination property names.In 2.1.265 these properties are no longer on Profile . Does anyone know why they were removed ? But more importantly , how can I duplicate t...
SourceMemberNameTransformer = name = > name.Replace ( `` _ '' , `` '' ) .ToUpper ( ) DestinationMemberNameTransformer = name = > name.ToUpper ( ) public interface INamingConvention { Regex SplittingExpression { get ; } string SeparatorCharacter { get ; } }
Missing member in AutoMapper 2.1.265
C#
I have a .NET Core 2.1 Web API service and I wish to retrieve the connection string from the appsettings.json file and use it in a separate database class I wrote . I do n't need or want to use Entity Framework , unfortunately , all MS docs only show EF examples . I 've tried about 10 different techniques , though ca n...
{ `` Logging '' : { `` LogLevel '' : { `` Default '' : `` Warning '' } } , `` AllowedHosts '' : `` * '' , `` ConnectionStrings '' : { `` DefaultConnection '' : `` Server=MAXIMUS,61433 ; Database=Geolocation ; Trusted_Connection=True ; MultipleActiveResultSets=true '' } } using System ; using System.Collections.Generic ...
How to retrieve connection string in class from .NET Core 2.1 Web API w/o Entity Framework
C#
I need help understanding Unity and how IOC works.I have this in my UnityContainerThen in my Web API controller , I understand that IService is injected by Unity because it was a registered type.My Service InterfaceMy Service Implementation has its own constructor that takes an EntityFramework DBContext object . ( EF6 ...
var container = new UnityContainer ( ) ; // Register types container.RegisterType < IService , Service > ( new HierarchicalLifetimeManager ( ) ) ; config.DependencyResolver = new UnityResolver ( container ) ; public class MyController : ApiController { private IService _service ; // -- -- -- - Inject dependency - from ...
Web API with Unity IOC - How is my DBContext Dependecy resolved ?
C#
Is there a way to change the code generated by a quick-fix in Resharper ? It does n't seem to be in the live templates.I 'd like the 'Create Property ' quickfix for an unrecognized symbol to generate Instead of :
public int MyProperty { get ; set ; } protected int MyProperty { get { throw new NotImplementedException ( ) ; } set { throw new NotImplementedException ( ) ; } }
Resharper quick-fix templates
C#
I 'm having an issue getting data out of a c # array serialized class with python . I have two files containing the classes . The first I am able to loop though the array and grab the public variables . However in the second file I see the class but am Unable to access any of the variables . It 's been 10+ years since ...
from System.Runtime.Serialization.Formatters.Binary import BinaryFormatterfrom System.IO import FileStream , FileMode , FileAccess , FileSharefrom System.Collections.Generic import *def read ( name ) : bformatter = BinaryFormatter ( ) file_stream = FileStream ( name , FileMode.Open , FileAccess.Read , FileShare.Read ) ...
python open a serialized C # file
C#
I have read many posts with the same issue , but none help , so apologies for the duplicate question : ( Ive followed the simple sample on the JQueryUI site by hard coding values and the autocomplete works , but I need it to come from my Database.View : JS : EDIT : I added an alert on success , and the alert is being c...
@ Html.TextBoxFor ( model = > model.Position , new { @ type = `` text '' , @ id = `` jobtitle '' , @ name = `` jobtitle '' , @ placeholder = `` Job Title '' } ) < script > $ ( function ( ) { $ ( `` # jobtitle '' ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : ' @ Url.Action ( `` JobsAut...
JQuery UI Autocomplete not reaching ActionResult C # MVC
C#
I 'm developing a project that will use ASP.NET Web API as the data service , and a Xamarin portable app as client.I 'm trying to enable migrations in the web app , but I get the following error : As you can see , I 've tried specifying the start up project explicitly but does n't look like the enable-migrations comman...
Enable-Migrations -enableautomaticmigrations -ContextTypeName MyProject.Models.ApplicationDbContext -ProjectName MyProject -StartupProjectName MyProject.App -VerboseUsing StartUp project 'MyProject.App'.Exception calling `` SetData '' with `` 2 '' argument ( s ) : `` Type 'Microsoft.VisualStudio.ProjectSystem.VS.Implem...
VS 2015 ASP.NET Web API ( EF6 ) & Xamarin Enable-Migrations fails
C#
I am trying to write my first customer Html Helper extension method following the formatAnd there seem to be several different ways to access the property name and value from the expressionandand alsoCan somebody explain the difference between these methods ? Are there any situations where one is superior to the others...
public static MvcHtmlString < TModel , TProperty > MyHelperFor ( this HtmlHelper < TModel > helper , Expression < Func < TModel , TProperty > > expression ) var body = expression.Body as MemberExpression ; var propertyName = body.Member.Name ; var propertyInfo = typeof ( TModel ) .getProperty ( propertyName ) var prope...
Difference between HtmlHelper methods for accessing properties from lambda expression
C#
UPDATE This looks to be a bug in Windows 7 . I tested the same scenario with Windows 8 and I can not replicate this there . Please see the MS Bug Report that I posted on this issue if you want more information . Thank you again to all that helped.UPDATE 2 The error happens on Server 2008 R2 as well ( Kind of expected t...
String.Format ( `` { 0 : MM/dd/yy } '' , dt ) ; //the result is 06 04 13 , notice the spaces String.Format ( `` { 0 : MM/dd/yy } '' , dt ) ; //the result is 06/04/13 , this time it has forward slashes
C Sharp DateTime Format
C#
I have been mucking around with XMLs for entity Framework . I tried to create a type of entity that could have properties injected at runtime , First I created DynamicEntity object that is dynamic then entity inherits from thispublic partial class QUOTE_HOUSE : DynamicEntity ( and it does seem to work when I set proper...
public class DynamicEntity : DynamicObject { Dictionary < string , object > dynamicMembers = new Dictionary < string , object > ( ) ; public override bool TrySetMember ( SetMemberBinder binder , object value ) { dynamicMembers [ binder.Name ] = value ; return true ; } public override bool TryGetMember ( GetMemberBinder...
Entity Framework entity is not in DataSpace.OSpace ( _workspace.GetItemCollection ( DataSpace.OSpace ) ) but is in DataSpace.CSpace
C#
I 've stumbled upon this code : where path is a string and the return value should be a string as well.Allthough path.Contains ' intellisense suggests a parameter , it works fine without one.How does this work exactly ? Is there any way to copy this behavior in vb.net ?
var knownSeparators = new [ ] { `` \\ '' , `` / '' , `` | '' , `` . '' } ; return knownSeparators.FirstOrDefault ( path.Contains ) ;
String.Contains does n't require parameters in c # ?
C#
I am creating Traces for a method and want it to use with a custom attribute . I will decorate each method with TraceMethod.eg : So here , How to call StartTrace ( ) before the SomeMethod start executing and EndTrace ( ) after the execution of SomeMethod ends ? Is it possible ?
[ TraceMethod ( ) ] public void SomeMethod ( ) { } public class TraceMethod : Attribute { public void StartTrace ( ) { } public void EndTrace ( ) { } }
Identity Start and End of a method
C#
This is what I am trying to getThis is how I get Foo typeThis is what I tried but could n't make it successfullyand also this ; this is method where I am trying to implement
( IList < Foo > ) listPropertyInfo.GetValue ( item ) listPropertyInfo.GetValue ( item ) .GetType ( ) .GenericTypeArguments [ 0 ] Convert.ChangeType ( listPropertyInfo.GetValue ( item ) , IList < listPropertyInfo.GetValue ( item ) .GetType ( ) .GenericTypeArguments [ 0 ] > ) ( ( typeof ( IList < > ) .MakeGenericType ( l...
Changing Type at Runtime with GenericTypeArgument
C#
I have two pieces of code that are identical in C # and Java . But the Java one goes twice as fast . I want to know why . Both work with the same principal of using a big lookup table for performance.Why is the Java going 50 % faster than C # ? Java code : It just enumerates through all possible 7 card combinations . T...
int h1 , h2 , h3 , h4 , h5 , h6 , h7 ; int u0 , u1 , u2 , u3 , u4 , u5 ; long time = System.nanoTime ( ) ; long sum = 0 ; for ( h1 = 1 ; h1 < 47 ; h1++ ) { u0 = handRanksj [ 53 + h1 ] ; for ( h2 = h1 + 1 ; h2 < 48 ; h2++ ) { u1 = handRanksj [ u0 + h2 ] ; for ( h3 = h2 + 1 ; h3 < 49 ; h3++ ) { u2 = handRanksj [ u1 + h3 ...
C # is half as slow than Java in memory access with loops ?
C#
Is there a property in some class that can tell me if the current culture is actually the default culture.Similar to how localization works with winforms . It states in a form if the language is default.lets say if i am in en-US - how can i tell via code if en.US is the actual default ? I need to implement some localiz...
nameofxml.default.xml ( this is the default local ) nameofXml.de-de.xml ( this is german )
c # : In a dotnet class is there a property that states if the `` Current '' culture is actual the default culture ?
C#
Is it possible to create a list of anonymous delegates in C # ? Here is code I would love to write but it does n't compile :
Action < int > method ; List < method > operations = new List < method > ( ) ;
Is List < T > where T is an anonymous delegate possible ?
C#
I new to C # and have a question regarding the use of `` var '' When I use the following code everything works greatBut when I change DataGridViewRow to var I get and error that states 'object ' does not contain definition for 'Cells ' and no extension method 'Cells ' accepting a first argument of type 'object ' could ...
foreach ( DataGridViewRow row in myGrid.Rows ) { if ( row.Cells [ 2 ] .Value.ToString ( ) .Contains ( `` 51000 '' ) ) { row.Cells [ 0 ] .Value = `` X '' ; } }
var wo n't work with DataGridViewRow
C#
( while trying to analyze how decimal works ) & & after reading @ jonskeet article and seeing msdn , and thinking for the last 4 hours , I have some questions : in this link they say something very simple : 1.5 x 10^2 has 2 significant figures 1.50 x 10^2 has 3 significant figures.1.500 x 10^2 has 4 significant figures...
sign * mantissa / 10^exponent ^ _ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^___ ^^^^^ 1 _ 96 5 ±79228162514264337593543950335 × 10^0 128-102 = 26
decimal in c # misunderstanding ?
C#
One feature of coming C # 9 is so called top-level programs . So that you could just write the following without classes.and dotnet run will launch it for you.It works for me , but only if I also add a .csproj file like the one belowIs there a way to skip .csproj from the picture ? : ) So that there 's just a single Pr...
using System ; Console.WriteLine ( `` Hello World ! `` ) ; < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > net5.0 < /TargetFramework > < /PropertyGroup > < /Project >
C # 9 top-level programs without csproj ?
C#
I have lots of code like this : As you can see , I use the usual way of doing async operations . how do I change this code to use async await ? Preferably something like this :
var feed = new DataFeed ( host , port ) ; feed.OnConnected += ( conn ) = > { feed.BeginLogin ( user , pass ) ; } ; feed.OnReady += ( f ) = > { //Now I 'm ready to do stuff . } ; feed.BeginConnect ( ) ; public async void InitConnection ( ) { await feed.BeginConnect ( ) ; await feed.BeginLogin ( user , pass ) ; //Now I '...
How to convert this code to async await ?
C#
I have a method that returns an object and also has an out parameter . The method calls another method that takes in the same out paramter as another out paramter . This gives a build error on the return statement : The out parameter 'param1 ' must be assigned to before control leaves the current methodThe code looks l...
public TypeA Method1 ( TypeA param1 , out bool param2 ) { / ... some logic here ... / SubMethod ( out param2 ) ; / ... some logic here ... / return param1 ; }
How to assign out parameter in function ?
C#
I created an API wrapper class library for consuming a rest API from a 3rd party.It was all working until they recently updated the API in the latest version of their product and added a namespace to the root element , now my deserialization code is failing.An example of one of my classes : If I set the Namespace prope...
[ Serializable ] [ XmlRootAttribute ( ElementName = `` exit_survey_list '' ) ] public class SupportExitSurveyCollection : ApiResult { ... . }
C # deserializing xml with multiple possible namespaces
C#
{ 0 , -12 } is the part i 'm curious about..I 'm looking at this example Cheers : )
Console.WriteLine ( `` { 0 , -12 } { 1 } '' , sqlReader.GetName ( 0 ) , sqlReader.GetName ( 1 ) ) ;
Can someone tell me what this means WriteLine ( `` { 0 , -12 } '' )
C#
I have two following methodsShould second method be marked with async/await keywords or not ?
public async Task < bool > DoSomething ( CancellationToken.token ) { //do something async } //overload with None token public /*async*/ Task < bool > DoSomething ( ) { return /*await*/ DoSomething ( CancellationToken.None ) ; }
Should method that get Task and passes it away await it ?
C#
In my current project , a method I do n't control sends me an object of this type : I display those data in a TreeView , but I would like to display only the path ending with SampleClass objects having their Type property set to type3 , no matter the depth of this leaf.I have absolutely no clue on how to do that , can ...
public class SampleClass { public SampleClass ( ) ; public int ID { get ; set ; } public List < SampleClass > Items { get ; set ; } public string Name { get ; set ; } public SampleType Type { get ; set ; } } public enum SampleType { type1 , type2 , type3 }
How to filter a recursive object ?
C#
Could someone please explain to me what the following lines of code do ? I 've searched the msdn library , but could n't really understand what it did.This is n't the full code , but I undertand the rest , it is just this part that I 'm struggling with .
dynamic shellApplication = Activator.CreateInstance ( Type.GetTypeFromProgID ( `` Shell.Application '' ) ) ; string path = System.IO.Path.GetDirectoryName ( filePath ) ; string fileName = System.IO.Path.GetFileName ( filePath ) ; dynamic directory = shellApplication.NameSpace ( path ) ; dynamic link = directory.ParseNa...
What is this code doing ?
C#
I have the following code where I 'm printing values before the Main ( ) method gets called by using a static constructor . How can I print another value after Main ( ) has returned , without modifying the Main ( ) method ? I want output like : The `` base '' code I use : I added a static constructor to Myclass for dis...
1st 2nd 3rd class Myclass { static void Main ( string [ ] args ) { Console.WriteLine ( `` 2nd '' ) ; } } class Myclass { static Myclass ( ) { Console.WriteLine ( `` 1st '' ) ; } //it will print 1st static void Main ( string [ ] args ) { Console.WriteLine ( `` 2nd '' ) ; // it will print 2nd } }
How do i print any value after Main ( ) method gets called ?
C#
Continuing my F # performance testing . For some more background see here : f # NativePtr.stackalloc in Struct ConstructorF # NativePtr.stackalloc Unexpected Stack OverflowNow I 've got stack arrays working in F # . However , for some reason the equivalent C # is approximately 50x faster . I 've included the ILSpy deco...
# nowarn `` 9 '' open Microsoft.FSharp.NativeInteropopen Systemopen System.Diagnostics open System.Runtime.CompilerServices [ < MethodImpl ( MethodImplOptions.NoInlining ) > ] let stackAlloc x = let mutable ints : nativeptr < byte > = NativePtr.stackalloc x ( ) [ < EntryPoint > ] let main argv = printfn `` % A '' argv ...
F # NativePtr.stackalloc slower then C # stackalloc - Decompiled Code Included
C#
I have created a sample project . I am serializing the following types : Program code ( console app for simplicity ) : The result of serialization is just perfect : result string contains all the data I 've putted to the tree before . However , deserialization of that string with the same serializer settings is incorre...
[ JsonObject ( IsReference = true , ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize ) ] public class SampleTree : Dictionary < string , SampleTree > { [ JsonProperty ( ReferenceLoopHandling = ReferenceLoopHandling.Serialize ) ] public SampleClass Value { get ; set ; } [ JsonProperty ( IsReference = true , R...
Serializing and deserializing of type T , derived from Dictionary < string , T > , using Json.NET
C#
I need to use Dictionary < long , string > collections that given two instances d1 and d2 where they each have the same KeyValuePair < long , string > contents , which could be inserted in any order : ( d1 == d2 ) evaluates to trued1.GetHashCode ( ) == d2.GetHashCode ( ) The first requirement was achieved most easily b...
public override int GetHashCode ( ) { StringBuilder str = new StringBuilder ( ) ; foreach ( var item in this ) { str.Append ( item.Key ) ; str.Append ( `` _ '' ) ; str.Append ( item.Value ) ; str.Append ( `` % % '' ) ; } return str.ToString ( ) .GetHashCode ( ) ; }
Implementation of Dictionary where equivalent contents are equal and return the same hash code regardless of order of insertion
C#
While testing the performance of floats in .NET , I stumbled unto a weird case : for certain values , multiplication seems way slower than normal . Here is the test case : Results : Why are the results so different for param = 0.9f ? Test parameters : .NET 4.5 , Release build , code optimizations ON , x86 , no debugger...
using System ; using System.Diagnostics ; namespace NumericPerfTestCSharp { class Program { static void Main ( ) { Benchmark ( ( ) = > float32Multiply ( 0.1f ) , `` \nfloat32Multiply ( 0.1f ) '' ) ; Benchmark ( ( ) = > float32Multiply ( 0.9f ) , `` \nfloat32Multiply ( 0.9f ) '' ) ; Benchmark ( ( ) = > float32Multiply (...
Inconsistent multiplication performance with floats
C#
I am very new to MVVM and I am stuck with data binding . I have a button on my view page which dynamically creates text boxes but I can not see how I bind these textboxes to my List in ViewModel . In my view i have : The code behind the button is : In my ViewModel i have : I am struggling to see how I get the website t...
< Button x : Name= '' btWebsite '' Grid.ColumnSpan= '' 2 '' Width= '' 50 '' Height= '' 50 '' Click= '' btWebsite_Click '' Margin= '' 23,245,259,202 '' > < StackPanel x : Name= '' pnWebsiteButton '' Orientation= '' Horizontal '' > < Image x : Name= '' imgWebsite '' Source= `` Images/webIcon.jpg '' Stretch= '' Fill '' Ho...
Dynamic textbox binding to a list
C#
I would like to determine the impact that a code change within on override of Equals ( ) in my class would have on the code.When I do Shift-F12 to find all references , Visual Studio returns 126,703 places where I am calling object.Equals ( ) .Is there a way to skip overrides of Equals ( ) method when looking for refer...
public override bool Equals ( object obj ) { // My code to be changed return true ; }
How to skip overrides of a method when looking for all references
C#
I have this simple code : So when I 'm creating a Data class : The list was filled with strings `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' even if it had no set.Why is this happening ?
public static void Main ( String [ ] args ) { Data data = new Data { List = { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } } ; foreach ( var str in data.List ) Console.WriteLine ( str ) ; Console.ReadLine ( ) ; } public class Data { private List < String > _List = new List < String > ( ) ; public List < String > List { get ...
Why am I allowed to modify properties which are readonly with object initializers ?
C#
I have a BackgroundWorker and a single ProgressBar . When working , the BackgroundWorker runs through a triple for-loop and reports progress to the ProgressBar.Currently , the progress that is being reported is only that of the outter-most loop ( xProgress ) , which works , but does not run smoothly . The goal is for t...
private void bgw_DoWork ( object sender , DoWorkEventArgs e ) { int xMax , yMax , zMax ; xMax = 10 ; for ( int x = 1 ; x < = xMax ; x++ ) { yMax = 5 ; for ( int y = 1 ; y < = yMax ; y++ ) { zMax = new Random ( ) .Next ( 50 , 100 ) ; for ( int z = 1 ; z < = zMax ; z++ ) { Thread.Sleep ( 5 ) ; /// The process double xPro...
How can I report progress based on multiple variables in a nested loop ( for a progress bar ) ?
C#
I 'm trying to draw a Polyline whose opacity gradually fades out as the trail progresses , mimicking the effect of a highlighter that runs out of ink . I first took a naive approach with a LinearGradientBrush.As you can see on the image below , that did n't quite work out for me . I drew two polylines starting from the...
LinearGradientBrush lgb = new LinearGradientBrush ( ) ; lgb.GradientStops.Add ( new GradientStop ( Color.FromArgb ( 255 , 255 , 0 , 0 ) , 0.0 ) ) ; lgb.GradientStops.Add ( new GradientStop ( Color.FromArgb ( 0 , 255 , 0 , 0 ) , 1.0 ) ) ; line.Stroke = lgb ;
Drawing a Polyline that gradually fades out
C#
I 've created a C # ASP.NET method which simply takes a string property containing JSON , both inside the same class . My issue is that whenever I type the .Deserialize method ( the commented line ) Visual Studio 2013 crashes with an `` Unhandled Exception '' in event logs.If I write the line in comments ( as above ) t...
public object JSONAsObject ( ) { object obj = new object ( ) ; JavaScriptSerializer js = new JavaScriptSerializer ( ) ; // obj = js.Deserialize < object > ( this._json ) ; return obj ; } Application : devenv.exeFramework Version : v4.0.30319Description : The process was terminated due to an unhandled exception.Exceptio...
VS 2013 Crash When Using JSON Deserialize Method