text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have a parent object that has a reference to a child object and additionally the parent has an event handler that listens to an event of the child object.If all references to the parent object will be released , will the memory used through the parent and the child be freed through GC ? ( Assuming that no more references neither to the child nor to the parent exist ) .Please note , I 'm aware that GC does not react immediately . My question is not if the memory is freed immediatly after releasing the parent object . My question is , if the memory is released anyhow.UpdateFor me it seems that the answer is a clear yes , GC is able to resolve this circular reference . But for all who read this post and have a similar question , take care to not leave event-registration open . It 's only a special example in which the registration is no problem . In other cases , event-registrations may cause serious memory leaks.A very good resource covering this question was provided by vilx : http : //www.interact-sw.co.uk/iangblog/2004/07/07/circulareventrefs <code> class ParentClass { ChildClass _childClass ; public ParentClass ( ChildClass childClass ) { _childClass = childClass ; childClass.SomeEvent += ChildClass_SomeEvent ; } void ChildClass_SomeEvent ( object sender , SomeEventArgs e ) { } }
Will GC release used memory
C_sharp : I 'm working on a game here , and found this rather intriguing bug . Suppose you have this enum : a base classand two instances of it : This is what happened to me : The first instance 's type would remain as pre-initialized in the base class , even though I specified in its constructor that I want the type to be Food.The 2nd instance 's type would be set correctly to Tools.IF , I added a new enum value BEFORE Food , such as : Then the 1st instance 's type would be , as expected , Food . The 2nd instance 's type would also be correct.What could have caused this behavior ? To describe it in short , all instances whose Type had been set in the constructor to the first value of the enum , would actually go back to the value they had in the BaseItem definition.Adding an extra value before the first enum value solved the problem , apparently ; but it IS wrong , so I 'd like to know what could have caused the issue.Thanks ! -- - Later Edit -- -In case this helps : not doing any initialization to the `` Type '' field inside of BaseItem , and leaving only the braces constructor do the initialization , everything works fine without adding the `` Nothing '' value to the enum.Sorry about this ; after some more digging , it seems it 's an Unity-only bug . Some other people encountered it too . I have solved the problem ; everyone gets a vote up from me , and I 'll add my own answer ; maybe some other Unity users will find it . Thanks a lot for your help and interest ! <code> public enum ItemType { Food , Weapon , Tools , Written , Misc } ; public class BaseItem { public string Name = `` Default Name '' ; public ItemType Type = ItemType.Misc ; } Ins1 = new BaseItem { Name = `` Something '' , Type = ItemType.Food } ; Ins2 = new BaseItem { Name = `` Something too '' , Type = ItemType.Tools } public enum ItemType { Nothing , Food , Weapon , Tools , Written , Misc } ;
Strange behavior with C # enums
C_sharp : Just wondered why the discrepancy really . : -/ <code> //okAction < int > CallbackWithParam1 = delegate { } ; //error CS1593 : Delegate 'System.Action < int > ' does not take 0 argumentsAction < int > CallbackWithParam2 = ( ) = > { } ;
Why can anonymous delegates omit arguments , but lambdas ca n't ?
C_sharp : I 'm trying my hand at behavior driven development and I 'm finding myself second guessing my design as I 'm writing it . This is my first greenfield project and it may just be my lack of experience . Anyway , here 's a simple spec for the class ( s ) I 'm writing . It 's written in NUnit in a BDD style instead of using a dedicated behavior driven framework . This is because the project targets .NET 2.0 and all of the BDD frameworks seem to have embraced .NET 3.5.None of the interfaces used by MainPresenter have any real implementations yet . AccountService will be responsible for creating new accounts . There can be multiple implementations of IAccount defined as separate plugins . At runtime , if there is more than one then the user will be prompted to choose which account type to create . Otherwise AccountService will simply create an account.One of the things that has me uneasy is how many mocks are required just to write a single spec/test . Is this just a side effect of using BDD or am I going about this thing the wrong way ? [ Update ] Here 's the current implementation of MainPresenter.AddAccountAny tips , suggestions or alternatives welcome . <code> [ TestFixture ] public class WhenUserAddsAccount { private DynamicMock _mockMainView ; private IMainView _mainView ; private DynamicMock _mockAccountService ; private IAccountService _accountService ; private DynamicMock _mockAccount ; private IAccount _account ; [ SetUp ] public void Setup ( ) { _mockMainView = new DynamicMock ( typeof ( IMainView ) ) ; _mainView = ( IMainView ) _mockMainView.MockInstance ; _mockAccountService = new DynamicMock ( typeof ( IAccountService ) ) ; _accountService = ( IAccountService ) _mockAccountService.MockInstance ; _mockAccount = new DynamicMock ( typeof ( IAccount ) ) ; _account = ( IAccount ) _mockAccount.MockInstance ; } [ Test ] public void ShouldCreateNewAccount ( ) { _mockAccountService.ExpectAndReturn ( `` Create '' , _account ) ; MainPresenter mainPresenter = new MainPresenter ( _mainView , _accountService ) ; mainPresenter.AddAccount ( ) ; _mockAccountService.Verify ( ) ; } } public void AddAccount ( ) { IAccount account ; if ( AccountService.AccountTypes.Count == 1 ) { account = AccountService.Create ( ) ; } _view.Accounts.Add ( account ) ; }
Is this a poor design ?
C_sharp : System.Array serves as the base class for all arrays in the Common Language Runtime ( CLR ) . According to this article : For each concrete array type , [ the ] runtime adds three special methods : Get/Set/Address.and indeed if I disassemble this C # code , into CIL I get , where the calls to the aforementioned Get and Set methods can be clearly seen . It seems the arity of these methods is related to the dimensionality of the array , which is presumably why they are created by the runtime and are not pre-declared . I could n't locate any information about these methods on MSDN and their simple names makes them resistant to Googling . I 'm writing a compiler for a language which supports multidimensional arrays , so I 'd like to find some official documentation about these methods , under what conditions I can expect them to exist and what I can expect their signatures to be.In particular , I 'd like to know whether its possible to get a MethodInfo object for Get or Set for use with Reflection.Emit without having to create an instance of the array with correct type and dimensionality on which to reflect , as is done in the linked example . <code> int [ , ] x = new int [ 1024,1024 ] ; x [ 0,0 ] = 1 ; x [ 1,1 ] = 2 ; x [ 2,2 ] = 3 ; Console.WriteLine ( x [ 0,0 ] ) ; Console.WriteLine ( x [ 1,1 ] ) ; Console.WriteLine ( x [ 2,2 ] ) ; IL_0000 : ldc.i4 0x400IL_0005 : ldc.i4 0x400IL_000a : newobj instance void int32 [ 0 ... ,0 ... ] : :.ctor ( int32 , int32 ) IL_000f : stloc.0IL_0010 : ldloc.0IL_0011 : ldc.i4.0IL_0012 : ldc.i4.0IL_0013 : ldc.i4.1IL_0014 : call instance void int32 [ 0 ... ,0 ... ] : :Set ( int32 , int32 , int32 ) IL_0019 : ldloc.0IL_001a : ldc.i4.1IL_001b : ldc.i4.1IL_001c : ldc.i4.2IL_001d : call instance void int32 [ 0 ... ,0 ... ] : :Set ( int32 , int32 , int32 ) IL_0022 : ldloc.0IL_0023 : ldc.i4.2IL_0024 : ldc.i4.2IL_0025 : ldc.i4.3IL_0026 : call instance void int32 [ 0 ... ,0 ... ] : :Set ( int32 , int32 , int32 ) IL_002b : ldloc.0IL_002c : ldc.i4.0IL_002d : ldc.i4.0IL_002e : call instance int32 int32 [ 0 ... ,0 ... ] : :Get ( int32 , int32 ) IL_0033 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0038 : ldloc.0IL_0039 : ldc.i4.1IL_003a : ldc.i4.1IL_003b : call instance int32 int32 [ 0 ... ,0 ... ] : :Get ( int32 , int32 ) IL_0040 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0045 : ldloc.0IL_0046 : ldc.i4.2IL_0047 : ldc.i4.2IL_0048 : call instance int32 int32 [ 0 ... ,0 ... ] : :Get ( int32 , int32 ) IL_004d : call void [ mscorlib ] System.Console : :WriteLine ( int32 )
Where can I find information on the Get , Set and Address methods for multidimensional System.Array instances in .NET ?
C_sharp : Given event store with fields : AggregateId : integerPayload : blobVersion : integerWhich contains events based on : ... and then has further events added with an updated structure : When this historical data is retrieved ( for analysis , etc ) , how do you reconstruct binary payload into meaningful data ? Note : the code above is not an example of a good event/event store implementation . I just want to know how this scenario should be handled . <code> public class OrderLineAdded { int Id ; short Quantity ; } public class OrderLineAdded { int ProductId ; // field name has changed int Quantity ; // field datatype has changed }
How to retrieve historical events after changes to Domain Event structure
C_sharp : How can I get Visual Studio to provide controller and action syntax highlighting like it offers for its own object for controller and action strings in the following ? When you use : Visual Studio provides additional highlighting on the controller and action , it even tries to detect which ones are available and will present it as an option.Notice in the image below how it give me options for the actions based upon the controller that I 've entered . This is what I would like to happen for my custom code.I have perfectly working HtmlHelper extension method similar to the following : My extension methods are getting picked up by intellisense in the regard that it knows I need a few strings . When you look at Microsoft 's code , the parameters for action and controller are strings , but Visual Studio knows whether those controllers and actions exists and provide additional intellisense support . How does the tooling pick up on it ? <code> Html.Action ( `` Index '' , `` Home '' ) ; public static MvcHtmlString Action ( this HtmlHelper htmlHelper , string actionName , string controllerName , string myAwesomeField ) { return Action ( htmlHelper , actionName , controllerName , null /* routeValues */ , myAwesomeField ) ; }
How to get syntax highlighting of controllers and actions on HtmlHelper extension method ?
C_sharp : I 'm trying to create a Generic Action Delegate andand here is my callerand here is the business objectand here is the error what i get during compilationMy GetSetterAction is returning ActionPerdicate where as here T is busPerson and i am trying to store it in ActionPredicate keeping in mind about Contravariance . But it fails . i dont know how to proceed further . Please Help.. ! <code> delegate void ActionPredicate < in T1 , in T2 > ( T1 t1 , T2 t2 ) ; public static ActionPredicate < T , string > GetSetterAction < T > ( string fieldName ) { ParameterExpression targetExpr = Expression.Parameter ( typeof ( T ) , `` Target '' ) ; MemberExpression fieldExpr = Expression.Property ( targetExpr , fieldName ) ; ParameterExpression valueExpr = Expression.Parameter ( typeof ( string ) , `` value '' ) ; MethodCallExpression convertExpr = Expression.Call ( typeof ( Convert ) , `` ChangeType '' , null , valueExpr , Expression.Constant ( fieldExpr.Type ) ) ; UnaryExpression valueCast = Expression.Convert ( convertExpr , fieldExpr.Type ) ; BinaryExpression assignExpr = Expression.Assign ( fieldExpr , valueCast ) ; var result = Expression.Lambda < ActionPredicate < T , string > > ( assignExpr , targetExpr , valueExpr ) ; return result.Compile ( ) ; } ActionPredicate < busBase , string > act = DelegateGenerator.GetSetterAction < busPerson > ( `` FirstName '' ) ; public abstract class busBase { } public class busPerson : busBase { public string FirstName { get ; set ; } public string LastName { get ; set ; } public int Age { get ; set ; } public string GetFullName ( ) { return string.Format ( `` { 0 } { 1 } '' , FirstName , LastName ) ; } } Can not implicitly convert type 'BusinessObjects.ActionPredicate < BusinessObjects.busPerson , string > ' to 'BusinessObjects.ActionPredicate < BusinessObjects.busBase , string > ' . An explicit conversion exists ( are you missing a cast ? )
Contravariance in Expressions
C_sharp : I thought that ^ did that.I expected : What I 'm gettingthe actual code isreplacing exp for 0 , 1 , and 2What does the ^ operator do ? <code> 10^0=110^1=1010^2=100 10^0=1010^1=1110^2=8 int value = 10 ^ exp ;
What does ^ operator do ?
C_sharp : I came across this situation where the following plinq statement inside static constructor gets deadlocked : It happens only when a constructor is static.Can someone explain this to me please.Is it TPL bug ? Compiler ? Me ? <code> static void Main ( string [ ] args ) { new Blah ( ) ; } class Blah { static Blah ( ) { Enumerable.Range ( 1 , 10000 ) .AsParallel ( ) .Select ( n = > n * 3 ) .ToList ( ) ; } }
Plinq statement gets deadlocked inside static constructor
C_sharp : Total OO noob question here . I have these two methods in a class And when I call StoreSessionSpecific with dbSession being of type LateSession ( LateSession inherits Session ) I expected the top one to be called . Since dbSession is of type LateSession . @ Paolo Tedesco This is how the classes are defined . <code> private void StoreSessionSpecific ( LateSession dbSession , SessionViewModel session ) { session.LateSessionViewModel.Guidelines = dbSession.Guidelines.ToList ( ) ; } private void StoreSessionSpecific ( Session dbSession , SessionViewModel session ) { // nothing to do yet ... } var dbSession = new LateSession ( ) ; StoreSessionSpecific ( dbSession , session ) ; public class Session { public int ID { get ; set ; } public int SessionTypeId { get ; set ; } public virtual SessionType SessionType { get ; set ; } [ Required ] public DateTime StartTime { get ; set ; } [ Required ] public DateTime EndTime { get ; set ; } // Session duration in minutes // public int SessionDuration { get ; set ; } public virtual ICollection < Attendee > Attendees { get ; set ; } } public class LateSession : Session { public int MaxCriticalIncidentsPerUser { get ; set ; } public int MaxResultCriticalIncidents { get ; set ; } public virtual ICollection < Guideline > Guidelines { get ; set ; } }
Why is n't the most specific method called based on type of parameter
C_sharp : My ultimate goal here is to turn the following string into JSON , but I would settle for something that gets me one step closer by combining the fieldname with each of the values.Sample Data : Using Regex.Replace ( ) , I need it to at least look like this : Ultimately , this result would be awesome if it can be done via Regex in a single call.I 've tried many different variations of this pattern , but ca n't seem to get it right : Only one other example I could find that is doing something similar , but just enough differences that I ca n't quite put my finger on it.Regex to repeat a capture across a CDL ? Here 's my solution . I 'm not going to post it as a `` Solution '' because I want to give credit to one that was posted by others . In the end , I took a piece from each of the posted solutions and came up with this one . Thanks to everyone who posted . I gave credit to the solution that compiled , executed fastest and had the most accurate results . <code> Field1 : abc ; def ; Field2 : asd ; fgh ; Field1 : abc , Field1 : def , Field2 : asd , Field2 : fgh { `` Field1 '' : '' abc '' , '' Field2 '' : '' asd '' } , { `` Field1 '' : '' def '' , '' Field2 '' : '' fgh '' } ( ? : ( \w+ ) : ) * ? ( ? : ( [ ^ : ; ] + ) ; ) EDIT : string hbi = `` Field1 : aaa ; bbb ; ccc ; ddd ; Field2:111 ; 222 ; 333 ; 444 ; '' ; Regex re = new Regex ( @ '' ( \w+ ) : ( ? : ( [ ^ : ; ] + ) ; ) + '' ) ; MatchCollection matches = re.Matches ( hbi ) ; SortedDictionary < string , string > dict = new SortedDictionary < string , string > ( ) ; for ( int x = 0 ; x < matches.Count ; x++ ) { Match match = matches [ x ] ; string property = match.Groups [ 1 ] .Value ; for ( int i = 0 ; i < match.Groups [ 2 ] .Captures.Count ; i++ ) { string key = i.ToString ( ) + x.ToString ( ) ; dict.Add ( key , string.Format ( `` \ '' { 0 } \ '' : \ '' { 1 } \ '' '' , property , match.Groups [ 2 ] .Captures [ i ] .Value ) ) ; } } Console.WriteLine ( string.Join ( `` , '' , dict.Values ) ) ;
Need some help on a Regex match / replace pattern
C_sharp : Conversion failed when converting the varchar value 'DADE ' to data type int.SQL command which i use is this : My code is : <code> SELECT * FROM p_details WHERE LOWER ( name ) LIKE ' % has % ln % ' AND CODE = 13 AND T_CODE= ' H ' SqlDataReader drr = com4.ExecuteReader ( ) ; DataTable dt = new DataTable ( ) ; dt.Load ( drr ) ; < -- error lineGridView7.DataSource = dt ; GridView7.DataBind ( ) ;
Error when data is bind into data table or gridview
C_sharp : I 've been having this problem for awhile in Visual Studio 2013 . It does n't seem to understand how to apply the indentation rules properly to lambda expressions when they 've been lined up incorrectly . Here is a simplified example : In the second and third row , the indent is only 3 spaces instead of 4 ( the real code example is much , much larger with the inner expression spanning hundreds of lines - this was checked in by my colleague and I 'm trying to fix it ) . I 've tried every combination of reformat code , document , re-creating the curly brace , etc . Nothing seems to work . It refuses to automatically update the indentation properly.I normally would n't bother with it , but it causes all the code inside to be off by 1 character as well . When I 'm typing lines in the middle , the tab/shift+tab markers are 1 character off from the lines above and below and I constantly have to adjust to get things lined up again . The closest thing I can find to reference this issue is this Connect Feedback from 2013 that is supposedly fixed , but I 'm on Update 4 ( released Nov 2014 ) and still experiencing the issue.Short of manually going through and updating the indentation for every line in the lambda expression , does anyone have an idea how I can quickly fix this code ? <code> var s = new Action ( ( ) = > { } ) ;
Incorrect Lambda Expression Indentation
C_sharp : We have an entity in our system called an `` identity program . '' That is also our sharding boundary , every identity program is stored in its own shard , so the identifier of the shard is the identifier of the identity program.We are in the process of implementing the ability to physically delete an identity program . As part of that process we want to clean up the shard map . To do so I 've written the following : The problem is that when it hits the DeleteMapping call it gets an exception : ShardManagementException : Mapping referencing shard ' [ shard-connection-string ] ' in the shard map 'IdentityProgramIdListShardMap ' does not exist . Error occurred while executing stored procedure '__ShardManagement.spBulkOperationShardMappingsGlobalBegin ' for operation 'RemovePointMapping ' . This can occur if another concurrent user has already removed the mapping.But the mapping has n't been removed , because right after that I execute : And I can see that the shardmap entry is still there , and is marked Offline.If I remove the call to MarkMappingOffline I get an exception stating that the shard mapping ca n't be removed because it is online.So I seem to have a catch-22 . If I mark it offline it thinks the shard mapping is gone and wo n't let me delete it . If I do n't mark it as offline it tells me it has to be offline . <code> var shardKey = new Guid ( `` E03F1DC0-5CA9-45AE-B6EC-0C90529C0062 '' ) ; var connectionString = @ '' shard-catalog-connection-string '' ; var shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager ( connectionString , ShardMapManagerLoadPolicy.Lazy ) ; var shardMap = shardMapManager.GetListShardMap < Guid > ( `` IdentityProgramIdListShardMap '' ) ; if ( shardMap.TryGetMappingForKey ( shardKey , out PointMapping < Guid > mapping ) ) { if ( mapping.Status == MappingStatus.Online ) { shardMap.MarkMappingOffline ( mapping ) ; } shardMap.DeleteMapping ( mapping ) ; } mappings = shardMap.GetMappings ( ) ; foreach ( var mapping in mappings ) { Console.WriteLine ( mapping.Value ) ; }
Can not delete shard mapping using Azure SQL Elastic Scale
C_sharp : I have an method that throws exception : I 'm using this method in more than 100 places in my code , the problem is when i use this method in another method that must return a value Re-sharper dose not understands that there is no need for returning a value , for example : is there any way to tell Re-sharper that MyMethod is an exception just like this : <code> public void MyMethod ( ) { // do some logging throw new Exception ( `` My Text '' ) ; } public int AnotherMethod ( ) { // some stuff MyMethod ( ) ; // < = it always throws exception return 0 ; // i have to put this code , while it never executes } public int AnotherMethod ( ) { // some stuff throw new Exception ( ) ; // < = it always throws exception //return 0 ; < = this line is no more needed }
How could i let Resharper or Intellisense know that a method allwayse throws exception ?
C_sharp : First some information about my development environment : .Net Framework 4.5Moq 4.10Autofac 4.2NUnit 3.11I try to mock a function that takes some string arguments and I would like to use It.IsAny < string > ( ) to setup . Normally I would to that like this : But now I would like to call a fucntion that makes the setup , so I do not have to copy paste the code above and make my unit tests a little bit `` better looking '' . I imagine something like this : Does someone know a solution for that ? I when I use string or even var as Unknown type the variable anyString hold the value null after UnknownType anyString = It.IsAny < string > ( ) ; . Thanks in advance for your answers.Further description : I need to specify different values for every argument . So It could look like this : <code> using ( AutoMock mock = AutoMock.GetLoose ( ) ) { mock.Mock < SomeInterface > ( ) .Setup ( x = > x.someFunction ( It.IsAny < string > ( ) , It.IsAny < string > ( ) , It.IsAny < string > ( ) ) ) ; // ... } using ( AutoMock mock = AutoMock.GetLoose ( ) ) { UnknownType anyString = It.IsAny < string > ( ) ; setup ( mock , anyString ) ; // ... } void setup ( Automock mock , UnknownType anyString ) { mock.Mock < SomeInterface > ( ) .Setup ( x = > x.someFunction ( anyString , anyString , anyString ) ) ; } using ( AutoMock mock = AutoMock.GetLoose ( ) ) { UnknownType string1 = It.IsAny < string > ; UnknownType string2 = It.Is < string > ( s = > s.Equals ( `` Specific string '' ) ) ; UnknownType string3 = It.IsAny < string > ; setup ( mock , string1 , string2 , string3 ) ; // ... } private static void setup ( AutoMock mock , UnknownType string1 , UnknownType string2 , UnknownType string3 ) { mock.Mock < SomeInterface > ( ) .Setup ( x = > x.someFunction ( string1 , string2 , string3 ) ) ; }
Passing Moqs It.IsAny < string > as method argument
C_sharp : I 'm tring to create a class which does all sorts of low-level database-related actions but presents a really simple interface to the UI layer.This class represents a bunch of data all within a particular aggregate root , retrieved by a single ID int.The constructor takes four parameters : The UI layer accesses this class through the interface IAssetRegister . Castle Windsor can supply the ILawbaseAssetRepository and IAssetChecklistKctcPartRepository parameters itself , but the UI code needs to supply the other two using an anonymous type like this : From the API design point of view , this is rubbish . The UI layer developer has no way of knowing that the IAssetRegister requires an integer and a User . They need to know about the implementation of the class in order to use it.I know I must have some kind of design issue here . Can anyone give me some pointers ? <code> public AssetRegister ( int caseNumber , ILawbaseAssetRepository lawbaseAssetRepository , IAssetChecklistKctcPartRepository assetChecklistKctcPartRepository , User user ) { _caseNumber = caseNumber ; _lawbaseAssetRepository = lawbaseAssetRepository ; _assetChecklistKctcPartRepository = assetChecklistKctcPartRepository ; _user = user ; LoadChecklists ( ) ; } int caseNumber = 1000 ; User user = GetUserFromPage ( ) ; IAssetRegister assetRegister = Moose.Application.WindsorContainer.Resolve < IAssetRegister > ( new { caseNumber , user } ) ;
Architecture problem : use of dependency injection resulting in rubbish API
C_sharp : The following F # code declares base and descendant classes . The base class has a virtual method 'Test ' with a default implementaion . The descendant class overrides the base class method and also adds a new overloaded 'Test ' method . This code compiles fine and presents no issues when accessing either of the descendant 'Test ' methods.F # Code : However , attempting to invoke the descendant 's override of 'Test ' from C # results in a compilation error : var result = td.Test ( 3 ) ; < - No overload for method 'Test ' takes 1 argumentsThe full C # Code : The strange thing is that VisualStudio 's intellisense sees the two overloaded functions , and provides correct signatures for both . It gives no warnings or errors before the build fails , and only highlights the line afterwards . I have re-implemented this scenario fully in C # and did not run into the same problem . Anyone have any ideas what 's going on here ? <code> module OverrideTest [ < AbstractClass > ] type Base ( ) = abstract member Test : int - > int default this.Test x = x + 1 type Descendant ( ) = inherit Base ( ) override this.Test x = x - 1 member this.Test ( x , y ) = x - y using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Client { class Program { static void Main ( string [ ] args ) { var td = new OverrideTest.Descendant ( ) ; var result = td.Test ( 3 ) ; Console.WriteLine ( result ) ; Console.ReadKey ( ) ; } } }
Can not resolve an F # method that has been both overridden and overloaded from C #
C_sharp : I 'm trying to create a MediaComposition . I have succeeded in combining multiple png images into a single video ; however , the files that 's created has a black background . At first I thought this might be because the files were png files , but the same bevaviour occurs for jpgs . The following is how I 'm saving the image : It saves the image fine , but the background is alpha . What this means is that when I try and chain these together into a media composition , there is no background , and it renders as black . I have tried using overlays when creating the MediaComposition to correct this : But to no avail . My suspicion is that I 'm misunderstanding the meaning of the term overlay in this case . So , my questions are : is it possible to overlay the video at composition time and , if so , how ? Alternatively , if this needs to be done in the image itself , how can I save the image with a background ? EDIT : I 've made progress ( ? ) with this ; the following compiles and runs , but creates a solid black image : EDIT : I found this answer , which sort of solves the problem by using the Win2D library ; although it does n't address my actual issue , it lets me let around it . Hopefully there is a better solution out there . <code> public async Task < bool > Save ( InkCanvas canvas , StorageFile file ) { if ( canvas ! = null & & canvas.InkPresenter.StrokeContainer.GetStrokes ( ) .Count > 0 ) { if ( file ! = null ) { using ( IRandomAccessStream stream = await file.OpenAsync ( FileAccessMode.ReadWrite ) ) { await canvas.InkPresenter.StrokeContainer.SaveAsync ( stream ) ; } } Clear ( canvas ) ; return true ; } return false ; } MediaClip overlayVideoClip = MediaClip.CreateFromColor ( Colors.White , new TimeSpan ( 0 , 1 , 0 ) ) ; MediaOverlay mo = new MediaOverlay ( overlayVideoClip ) ; MediaOverlayLayer mol = new MediaOverlayLayer ( ) ; mol.Overlays.Add ( mo ) ; composition.OverlayLayers.Add ( mol ) ; public async Task TestSave ( InkCanvas canvas , StorageFile file ) { RenderTargetBitmap rtb = new RenderTargetBitmap ( ) ; PixelFormats.Pbgra32 ) ; await rtb.RenderAsync ( canvas ) ; var pixelBuffer = await rtb.GetPixelsAsync ( ) ; using ( IRandomAccessStream stream = await file.OpenAsync ( FileAccessMode.ReadWrite ) ) { BitmapEncoder encoder = await BitmapEncoder.CreateAsync ( BitmapEncoder.PngEncoderId , stream ) ; encoder.SetPixelData ( BitmapPixelFormat.Bgra8 , BitmapAlphaMode.Straight , ( uint ) rtb.PixelWidth , ( uint ) rtb.PixelHeight , 96d , 96d , pixelBuffer.ToArray ( ) ) ; await encoder.FlushAsync ( ) ; } }
Add a background colour to a MediaComposition
C_sharp : I have a function that makes a list of animals , some of which are dogs , and some of which are just animals . That function returns that list to a different function that wants to extract out just the dogs , which is possible because the Animal class has a bool isDog . My question is , is it possible to extract the dog-specific ( child-specific ) data from the animal ( parent ) class , aka . can an animal still be a dog under the hood ? Things I have tried : Extracting out the dogs using the isDog bool and then calling the Dogconstructor to make a new one outside of the function that returns alist of animalsGiving the dog class a constructor that takes in an animal , but stillno way to preserve tail lengthI have these two interfacesand these two implementationsand this is the current state of the two functionsThanks <code> public interface IAnimal { string eyeColor ; int numLegs ; } public interface IDog : IAnimal { double tailLength ; } public class Animal : IAnimal { public string eyeColor { get ; set } public int numLegs { get ; set ; } public bool isDog ; public Animal ( string eyes , int legs ) { this.eyeColor = eyes ; this.numLegs = legs this.isDog = false ; } } public class Dog : Animal , IDog { public double tailLength { get ; set ; } public Dog ( double tail , string eyes ) { this.tailLength = tail ; this.eyeColor = eyes ; this.numLegs = 4 ; this.isDog = true ; } } List < Animal > getAnimals ( ) { List < Animal > animals ; Animal a1 = new Animal ( `` Blue '' , 4 ) ; animals.Add ( a1 ) ; Animal a2 = new Animal ( `` Green '' , 2 ) ; animals.Add ( a2 ) ; Dog d1 = new Dog ( 2.3 , `` Brown '' ) ; animals.Add ( d1 ) ; Dog d2 = new Dog ( 3.5 , `` Black '' ) ; animals.Add ( d2 ) ; return animals ; } void foo ( ) { IEnumerable < IAnimal > sample = getAnimals ( ) ; var x = totalTailLength ( sample.Where ( d = > d.isDog ) ) ; } double totalTailLength ( IEnumerable < IDog > dogs ) { return dogs.Sum ( d = > d.tailLength ) ; }
When a Child class is added to a List < parent > , is the child-specific data lost ?
C_sharp : I have following entity : What I need is to create optional-to-optional relationship within the same entity using PreviousRevision as a navigation property and PreviousRevisionId as a foreign key Id for it.I know that it can be done by annotating PreviousRevisionId property with [ ForeignKey ( `` PreviousRevision '' ) ] attribute , but what about fluent api ? I tried : , but doing migration I 'm getting error : PreviousRevisionId : Name : Each property name in a type must be unique . Property name 'PreviousRevisionId ' is already defined.So , basically , it looks impossible with fluent API . But I thought that annotation functionalty is a subset of fluent API functionality , is n't it ? <code> public class Revision { public int Id { get ; set ; } ... public int ? PreviousRevisionId { get ; set ; } public virtual Revision PreviousRevision { get ; set ; } } HasOptional ( c = > c.PreviousRevision ) .WithOptionalDependent ( ) .Map ( m = > m.MapKey ( `` PreviousRevisionId '' ) ) ;
EF6.1 optional-to-optional with fluent api mapping
C_sharp : First - a disclaimer : If you 're reading this because you want to use both a binding for IsChecked and a RelayCommand to change things , you probably are doing it wrong . You should be working off of the IsChecked binding 's Set ( ) call.The question : I have a ToggleButton in which there 's both a binding for IsChecked and for a Command : Yes - I know , tsk tsk . Could n't be helped.When the user clicks the ToggleButton , which these two is going to fire first ? Is the Command going to be executed , or is the IsChecked binding going to update the bound property ? Or - is this actually similar to the post on social in which it creates a race condition ? <code> < ToggleButton IsChecked= '' { Binding BooleanBackedProperty } '' Command= '' { Binding SomeCommand , RelativeSource= { RelativeSource FindAncestor , AncestorType= { x : Type Window } } } '' CommandParameter= '' { Binding } '' / >
What executes first : ToggleButton.IsChecked binding update , or Command binding ?
C_sharp : I was trying to find out if setting the capacity of a list in the constructor could flatten the already negligible performance differences between using List < T > ( IEnumerable < T > ) vs List < T > ( ) + AddRange ( IEnumerable < T > ) .I found out setting the capacity before AddRange ( ) actually leads to roughly the same performance of constructing the list with an initial collection.But there 's more . What if you use Add ( ) instead of AddRange ( ) ? For some reason it seems like the performance improves by a 32 % .So what if I use Add ( ) without initializing the constructor of the list with a initial capacity ? It seems like the performance are worst than the previous Add ( ) approach , but still better than AddRange ( ) approach : there 's a performance boost of a 26 % .This is strange enough for me to wonder if my test was a valid one ; so I post the tests I did ( run in release mode without debugger ) .Can anybody confirm this ? RESULTS : 13400 - constructor initialized with collection 13423 - constructor initialized with capacity + AddRange ( collection ) 14857 - parameterless constructor + AddRange ( collection ) 9003 - constructor initialized with capacity + Add ( item ) 9841 - parameterless constructor + Add ( item ) <code> int items = 100000 ; int cycles = 10000 ; var collectionToCopy = Enumerable.Range ( 0 , items ) ; var sw0 = new Stopwatch ( ) ; sw0.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( collectionToCopy ) ; } sw0.Stop ( ) ; Console.WriteLine ( sw0.ElapsedMilliseconds ) ; var sw1 = new Stopwatch ( ) ; sw1.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( items ) ; list.AddRange ( collectionToCopy ) ; } sw1.Stop ( ) ; Console.WriteLine ( sw1.ElapsedMilliseconds ) ; var sw4 = new Stopwatch ( ) ; sw4.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( ) ; list.AddRange ( collectionToCopy ) ; } sw4.Stop ( ) ; Console.WriteLine ( sw4.ElapsedMilliseconds ) ; var sw2 = new Stopwatch ( ) ; sw2.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( items ) ; foreach ( var item in collectionToCopy ) list.Add ( item ) ; } sw2.Stop ( ) ; Console.WriteLine ( sw2.ElapsedMilliseconds ) ; var sw3 = new Stopwatch ( ) ; sw3.Start ( ) ; for ( int i = 0 ; i < cycles ; i++ ) { List < int > list = new List < int > ( ) ; foreach ( var item in collectionToCopy ) list.Add ( item ) ; } sw3.Stop ( ) ; Console.WriteLine ( sw3.ElapsedMilliseconds ) ;
Performance difference with various List initialization and population techniques
C_sharp : I have a method that is looping through a list of values , what I would like to do is when I open the page to be able to see the values changing without refreshing the current view . I 've tried something like the code bellow.The actual thing is I want it to read this values even if I close the form . I presume I would need to assign a Task in order to do this , but I was wandering if there is any better way of doing it since it 's a MVC application ? <code> public static int myValueReader { get ; set ; } public static void ValueGenerator ( ) { foreach ( var item in myList ) { myValue = item ; Thread.Sleep ( 1000 ) ; } }
How to display different values without refreshing the page MVC C #
C_sharp : for access control purposes in a intensive DB use system I had to implement an objectset wrapper , where the AC will be checked.The main objective is make this change preserving the existing code for database access , that is implemented with linq to entities all over the classes ( there is no centralized layer for database ) .The ObjectSetWrapper created is like that : It 's really simple and works for simple queries , like that : But when I have subqueries like that : I get NotSupportedException , saying I ca n't create a constant value of my inner query entity type : Unable to create a constant value of type 'MyNamespace.Model.Sale ' . Only primitive types or enumeration types are supported in this context.How can I get my queries working ? I do n't really need to make my wrapper an ObjectSet type , I just need to use it in queries.UpdatedI have changed my class signature . Now it 's also implementing IObjectSet < > , but I 'm getting the same NotSupportedException : <code> public class ObjectSetWrapper < TEntity > : IQueryable < TEntity > where TEntity : EntityObject { private IQueryable < TEntity > QueryableModel ; private ObjectSet < TEntity > ObjectSet ; public ObjectSetWrapper ( ObjectSet < TEntity > objectSetModels ) { this.QueryableModel = objectSetModels ; this.ObjectSet = objectSetModels ; } public ObjectQuery < TEntity > Include ( string path ) { return this.ObjectSet.Include ( path ) ; } public void DeleteObject ( TEntity @ object ) { this.ObjectSet.DeleteObject ( @ object ) ; } public void AddObject ( TEntity @ object ) { this.ObjectSet.AddObject ( @ object ) ; } public IEnumerator < TEntity > GetEnumerator ( ) { return QueryableModel.GetEnumerator ( ) ; } public Type ElementType { get { return typeof ( TEntity ) ; } } public System.Linq.Expressions.Expression Expression { get { return this.QueryableModel.Expression ; } } public IQueryProvider Provider { get { return this.QueryableModel.Provider ; } } public void Attach ( TEntity entity ) { this.ObjectSet.Attach ( entity ) ; } public void Detach ( TEntity entity ) { this.ObjectSet.Detach ( entity ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return this.QueryableModel.GetEnumerator ( ) ; } } //db.Product is ObjectSetWrapper < Product > var query = ( from item in db.Product where item.Quantity > 0 select new { item.Id , item.Name , item.Value } ) ; var itensList = query.Take ( 10 ) .ToList ( ) ; //db.Product is ObjectSetWrapper < Product > var query = ( from item in db.Product select new { Id = item.Id , Name = item.Name , SalesQuantity = ( from sale in db.Sale where sale.ProductId == item.Id select sale.Id ) .Count ( ) } ) .OrderByDescending ( x = > x.SalesQuantity ) ; var productsList = query.Take ( 10 ) .ToList ( ) ; public class ObjectSetWrapper < TEntity > : IQueryable < TEntity > , IObjectSet < TEntity > where TEntity : EntityObject
ObjectSet wrapper not working with linqToEntities subquery
C_sharp : I 'm trying to fill a data grid view in my windows form application but nothing is being returned from the database when I execute the select query . I 've looked at other questions about this topic on this site but can not find anything that addresses my problem . The name of the data view table is qbcMemDataView and the data source is a sqlite dataset called sqlite_dbDataSet1Here is the code I have in place : Also , here is a screenshot of the program running that might help better explain the issue I am having : http : //imgur.com/j9ffeViI know there is data inside the table , I just do n't know why it is not appearing in the data grid when the btnSelect_tbl_Click method is executed.Any help would be appreciated.Thanks ! <code> public Form1 ( ) { InitializeComponent ( ) ; dbConnection = new SQLiteConnection ( `` Data Source=sqlite_db.sqlite ; Version=3 '' ) ; dbConnection.Open ( ) ; string [ ] restrictions = new string [ 4 ] ; restrictions [ 2 ] = `` test_table_mom '' ; using ( DataTable dTbl = dbConnection.GetSchema ( `` Tables '' , restrictions ) ) { for ( int i = 0 ; i < dTbl.Rows.Count ; i++ ) { tblChooser.Items.Add ( dTbl.Rows [ i ] .ItemArray [ dTbl.Columns.IndexOf ( `` TABLE_NAME '' ) ] .ToString ( ) ) ; } if ( tblChooser.Items.Count > 0 ) { tblChooser.SelectedIndex = 0 ; } } } private void btnSelect_tbl_Click ( object sender , EventArgs e ) { string sql = `` SELECT id , name FROM test_table_mom '' ; using ( SQLiteDataAdapter dbAdapter = new SQLiteDataAdapter ( sql , dbConnection ) ) { DataTable dataTbl = new DataTable ( ) ; dbAdapter.Fill ( dataTbl ) ; qbcMemDataView.DataSource = dataTbl ; } }
SQLite Data Adapter not displaying data
C_sharp : I have a question regarding the symbol that separates days from hours in TimeSpan.ToString output.The standard TimeSpan format strings produce different separator symbols : '' c '' produces a period ( `` . '' ) character '' g '' and `` G '' produce a colon ( `` : '' ) characterExample : Does anybody know what 's the logic behind it ? However TimeSpan.Parse parses all of these string successfully . <code> // Constant formatConsole.WriteLine ( TimeSpan.FromDays ( 42 ) .ToString ( `` c '' , CultureInfo.InvariantCulture ) ) ; // Output : 42.00:00:00 ( period character between days and hours ) // General short formatConsole.WriteLine ( TimeSpan.FromDays ( 42 ) .ToString ( `` g '' , CultureInfo.InvariantCulture ) ) ; // Output : 42:0:00:00 ( colon character between days and hours ) // General long formatConsole.WriteLine ( TimeSpan.FromDays ( 42 ) .ToString ( `` G '' , CultureInfo.InvariantCulture ) ) ; // Output : 42:00:00:00.0000000 ( colon character between days and hours )
Strange TimeSpan.ToString output
C_sharp : I am looking for a way to ensure that only serializable objects are stored into a Dictionary in C # .To be more specific I 'm looking to do something similar to this : The problem with this is that I can not store primitive types like integers , booleans , or strings.Is there a way to ensure that my Dictionary contains only objects which can be serialized ? <code> Dictionary < String , ISerializable > serialDict = new Dictionary < String , ISerializable > ( ) ;
Dictionary containing with only Serializable objects
C_sharp : I am using Dapper to call a stored procedure which have a mandatory parameter @ idProjectthis is my code fragment : Should work but raise an exception : An exception of type 'System.Data.SqlClient.SqlException ' occurred in System.Data.dll but was not handled in user code Additional information : Procedure or function 'xxxGetPage ' expects parameter ' @ idProject ' , which was not supplied.Why ? <code> using ( var c = _connectionWrapper.DbConnection ) { var result = c.Query < Xxx > ( `` dbo.xxx_xxxGetPage '' , new { @ idProject = 1 } ) .AsList ( ) ; return result ; }
Mandatory parameters , Dapper and System.Data.SqlClient.SqlException
C_sharp : I 'm working on a relatively straight forward C # project that connects an Access Database via OleDb with various functions such as adding , deleting and editing records . Now , everything has worked fine up until trying to implement a database search . The following line ( in the searchbox code ) throws up the exception during debug , but I am unsure what is actually a null value that is causing it to break.So the goal is to search through the 'Movies ' table in the database and find movies based on the user 's input ( stored in the 'Search ' string ) .The search box 's code can be found below , and the database initialisation and connection is provided at the bottom.For some context here is the main database initialisation/connection and the form load events : <code> ReturnedResults = DBDataSet.Tables [ `` Movies '' ] .Select ( `` Title like ' % '' + Search + `` % ' '' ) ; private void SearchTextBox_Changed ( object sender , EventArgs e ) { string SearchString = SearchTextBox.Text.ToString ( ) ; int Results = 0 ; DataRow [ ] ReturnedResults ; ReturnedResults = DataSet.Tables [ `` Movies '' ] .Select ( `` Title like ' % '' + SearchString + `` % ' '' ) ; Results = ReturnedResults.Length ; if ( Results > 0 ) { SearchResultsBox.Items.Clear ( ) ; for ( int i = 0 ; i < = Results ; i++ ) { DataRow Row ; Row = ReturnedResults [ i ] ; SearchResultsBox.Items.Add ( Row [ `` Title '' ] .ToString ( ) ) ; } } else { SearchResultsBox.Items.Clear ( ) ; MessageBox.Show ( `` Error ! No items found . `` ) ; } } public partial class BaseForm : Form { System.Data.OleDb.OleDbConnection Connection ; DataSet DataSet ; System.Data.OleDb.OleDbDataAdapter DataAdapter ; int MaxRows = 0 ; int CurrentRow = 0 ; public BaseForm ( ) { InitializeComponent ( ) ; } private void BaseForm_Load ( object sender , EventArgs e ) { Connection = new System.Data.OleDb.OleDbConnection ( ) ; Connection.ConnectionString = `` Provider=Microsoft.ACE.OLEDB.12.0 ; DataSource=Movies.accdb '' ; Connection.Open ( ) ; DataSet = new DataSet ( ) ; string sq1 = `` SELECT * From Movies '' ; DataAdapter = new System.Data.OleDb.OleDbDataAdapter ( sq1 , DBConnection ) ; DataAdapter.Fill ( DBDataSet ) ; MaxRows = DataSet.Tables [ 0 ] .Rows.Count ; DisplayRecord ( ) ; }
NullReferenceException error when searching database table for entries
C_sharp : I 'm trying to understand this RegEx statement in details . It 's supposed to validate filename from ASP.Net FileUpload control to allow only jpeg and gif files . It was designed by somebody else and I do not completely understand it . It works fine in Internet Explorer 7.0 but not in Firefox 3.6 . <code> < asp : RegularExpressionValidator id= '' FileUpLoadValidator '' runat= '' server '' ErrorMessage= '' Upload Jpegs and Gifs only . '' ValidationExpression= '' ^ ( ( [ a-zA-Z ] : ) | ( \\ { 2 } \w+ ) \ $ ? ) ( \\ ( \w [ \w ] . * ) ) ( .jpg|.JPG|.gif|.GIF ) $ '' ControlToValidate= '' LogoFileUpload '' > < /asp : RegularExpressionValidator >
Understand this RegEx statement
C_sharp : I want to split a border attribute from CSS into its constituent parts i.e : IntoI have split off the border : and semi-colon before this , so I simply need to parse the value section of the attributeNow in CSS you can have any combination of the 3 above attributes present soAll are legal so I need to account for that.What I have so far isWhich works fine for the normal case , but fails on the `` 1px Solid '' case as Solid is put into the 3rd capturing group , not the 2nd . I am not a regex expert so I may be making very basic mistakes , but any help would be greatly appreciated . I am working with C # ( but have mainly been testing in http : //gskinner.com/RegExr/ so any differences might have been the problem ) <code> .someClass { border : 1px solid black ; } border-width : 1pxborder-style : solid ; border-color : black ; border : 1px solid ; border : solid Gold ; border : 1em ; border : 1mm # 000000 ; border : 1px inset rgb ( 12 , 44 , 199 ) ; ( [ 0-9 ] + [ a-zA-Z| % ] + ) * * ( [ a-zA-Z ] * ) * ( . * )
Regex for splitting CSS border attribute into its parts
C_sharp : I have a list of bugs MyBugList created using the following classI wanted to group these bugs based on State and Severity . I used the following code to achieve it.This linq query gives me output like the followingHowever I would like to get an output like belowIs it possible to get this via a LINQ query on MyBugList or on BugListGroup I would like to get the output as a list so that I can be make it source a data grid . Note : State and Severity values are dynamic and can not be hard codedBelow is my implementation with the help of answer provided by Dmitriy ZapevalovOutput in the data grid will look like <code> internal class BugDetails { public int Id { get ; set ; } public string State { get ; set ; } public string Severity { get ; set ; } } var BugListGroup = ( from bug in MyBugList group bug by new { bug.State , bug.Severity } into grp select new { BugState = grp.Key.State , BugSeverity = grp.Key.Severity , BugCount = grp.Count ( ) } ) .OrderBy ( x= > x.BugState ) .ToList ( ) ; Closed Critical 40Active Critical 167Closed Medium 819Closed Low 323Resolved Medium 61Resolved Low 11Closed High 132Active Low 17Active Medium 88Active High 38Resolved High 4Resolved Critical 22Deferred High 11 Critical High Medium TotalClosed 3 4 5 12Active 5 4 5 14Resolved 6 4 5 15Deferred 1 4 5 10Total 15 16 20 51 private void button1_Click ( object sender , EventArgs e ) { var grouped = MyBugList.GroupBy ( b = > b.State ) .Select ( stateGrp = > stateGrp.GroupBy ( b = > b.Severity ) ) ; //Setting DataGrid properties dataGridBug.Rows.Clear ( ) ; dataGridBug.Columns.Clear ( ) ; dataGridBug.DefaultCellStyle.NullValue = `` 0 '' ; dataGridBug.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter ; //Declaring DataGrid Styles var gridBackColor = Color.AliceBlue ; var gridFontStyle = new Font ( Font , FontStyle.Bold | FontStyle.Italic ) ; //Declaring column and row Ids const string stateColumnId = `` State '' ; const string totalColumnId = `` Total '' ; const string totalRowId = `` Total '' ; //Adding first column dataGridBug.Columns.Add ( stateColumnId , stateColumnId ) ; dataGridBug.Columns [ 0 ] .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft ; //Adding other columns foreach ( var strSeverity in MyBugList.Select ( b = > b.Severity ) .Distinct ( ) ) { dataGridBug.Columns.Add ( strSeverity , strSeverity ) ; } //Adding Total Column var totColPos = dataGridBug.Columns.Add ( totalColumnId , totalColumnId ) ; var totCol = dataGridBug.Columns [ totColPos ] ; //Adding data to grid foreach ( var state in grouped ) { var nRow = dataGridBug.Rows.Add ( ) ; var severities = state as IList < IGrouping < string , BugDetails > > ? ? state.ToList ( ) ; dataGridBug.Rows [ nRow ] .Cells [ 0 ] .Value = severities.First ( ) .First ( ) .State ; var sevCount = 0 ; foreach ( var severity in severities ) { dataGridBug.Rows [ nRow ] .Cells [ severity.Key ] .Value = severity.Count ( ) ; sevCount += severity.Count ( ) ; } dataGridBug.Rows [ nRow ] .Cells [ totalColumnId ] .Value = sevCount ; } //Adding total row var totRowPos = dataGridBug.Rows.Add ( totalRowId ) ; var totRow = dataGridBug.Rows [ totRowPos ] ; //Adding data to total row for ( var c = 1 ; c < dataGridBug.ColumnCount ; c++ ) { var sum = 0 ; for ( var i = 0 ; i < dataGridBug.Rows.Count ; ++i ) { sum += Convert.ToInt32 ( dataGridBug.Rows [ i ] .Cells [ c ] .Value ) ; } dataGridBug.Rows [ totRowPos ] .Cells [ c ] .Value = sum ; } //Styling total column totCol.DefaultCellStyle.BackColor = gridBackColor ; totCol.DefaultCellStyle.Font = gridFontStyle ; //Styling total row totRow.DefaultCellStyle.BackColor = gridBackColor ; totRow.DefaultCellStyle.Font = gridFontStyle ; }
LINQ query on an object list to get distribution based on multiple fields
C_sharp : I have some doubts regarding the using statement : I have a class called MyJob which is Disposable . Then i also have a property on MyJob JobResults that is also Disposable.MY code : MY First question is : In this case after the using block are both MyJob and MyJob.Results disposed or only MyJob and NOT MyJob.Results ? I am also performing parallel processing w.r.t Tasks in C # : My second q , in the code above , what is the proper way to ensure to dispose off objects correctly when handling exceptions in tasks ? Sorry if my questions are too naive or confusing , as i am still trying to learn and understand C # . Thanks guys ! <code> using ( MyJob job = new MyJob ( ) ) { //do something . FormatResults ( job.JobResults ) } public string FormatResuls ( JobResuts results ) { } Tasks allTasks = List < Tasks > try { foreach ( Task t in allTasks ) { // Each tasks makes use of an IDisposable object . t.Start ( ) ; } Task.WaitAll ( allTasks ) ; } catch ( AggregateExecption aex ) { /// How do I ensure that all IDisposables are disposed properly if an exception happens in any of the tasks ? }
using statement usage in C #
C_sharp : I was cleaning up some code and removed an if statement that was no longer necessary . However , I realized I forgot to remove the brackets . This of course is valid and just created a new local scope . Now this got me thinking . In all my years of C # development , I have never come across a reason to use them . In fact , I kind of forgot I could do it . Is there any actual benefit to defining a local scope ? I understand I can define variables in one scope and then define the same ones again in an unrelated scope ( for , foreach , etc . ) like below : What 's the true point of defining a local scope ? Can there actually be any sort of performance gain ( or potentially a loss ) ? I know you could do this in C++ and was part of helping you manage memory , but because this is .NET , would there really be a benefit ? Is this just a bi-product of the language that let 's us define random scopes even though there is no true benefit ? <code> void SomeMethod ( ) { { int i = 20 ; } int i = 50 ; //Invalid due to i already being used above . } void SomeMethod2 ( ) { { int i = 20 ; } { int i = 50 ; //Valid due to scopes being unrelated . } { string i = `` ABCDEF '' ; } }
Explicit Local Scopes - Any True Benefit ?
C_sharp : I 'm trying to wrap my head around what the C # compiler does when I 'm chaining linq methods , particularly when chaining the same method multiple times.Simple example : Let 's say I 'm trying to filter a sequence of ints based on two conditions.The most obvious thing to do is something like this : But we could also chain the where methods , with a single condition in each : I had a look at the IL in Reflector ; it is obviously different for the two methods , but analysing it further is beyond my knowledge at the moment : ) I would like to find out : a ) what the compiler does differently in each instance , and why.b ) are there any performance implications ( not trying to micro-optimize ; just curious ! ) <code> IEnumerable < int > Method1 ( IEnumerable < int > input ) { return input.Where ( i = > i % 3 == 0 & & i % 5 == 0 ) ; } IEnumerable < int > Method2 ( IEnumerable < int > input ) { return input.Where ( i = > i % 3 == 0 ) .Where ( i = > i % 5 == 0 ) ; }
Understanding how the C # compiler deals with chaining linq methods
C_sharp : Env : C # , VStudio 2013 , 4.5 Framework , WinformsGoal : Getting the number of files ( Count ) in a folder and subfolder that match extensions stored in an array of string . The array of extension can be with the `` . '' of not . { `` .dat '' , '' txt '' , '' .msg '' } What i 've done so far : When I 'm having the `` . '' in the array of extensions , everything is working : { `` .dat '' , '' .txt '' , '' .msg '' } I have tried the Replace but it 's always returning 0.The working code ( Only if always with the `` . '' in array of string ) : The not working code ( always return 0 ) : <code> string [ ] ext= new string [ ] { `` .txt '' , `` .msg '' , `` .dat '' } ; totalFilesInTN = Directory.EnumerateFiles ( dlg1.SelectedPath , `` * . * '' , SearchOption.AllDirectories ) .Count ( s = > ext.Any ( s1 = > s1 == Path.GetExtension ( s ) ) ) ; string [ ] ext= new string [ ] { `` txt '' , `` .msg '' , `` dat '' } ; totalFilesInTN = Directory.EnumerateFiles ( dlg1.SelectedPath , `` * . * '' , SearchOption.AllDirectories ) .Count ( s = > ext.Any ( s1 = > s1 == Path.GetExtension ( s ) .Replace ( `` . `` , `` '' ) ) ) ;
Count of files in C # with LINQ
C_sharp : Which way can I decide the computer has a wifi adapter ? When I test my code it works , but I am uncertain , will it always work ? <code> private bool hasWifi ( ) { try { WlanClient wlanclient = new WlanClient ( ) ; } catch ( System.ComponentModel.Win32Exception except ) { return false ; } return true ; }
How to determine if the computer has a wifi adapter ?
C_sharp : I 'm trying to set up CSP in an asp.net core webapp , and the CSP part works fine , I can see the violations in the browser console as they are sent to the report-uri endpoint.However , I can not seem to create the correct method in a controller to receive these messages ! I create a method in the controller as : and it will be called , but the 'request ' parameter is always null . Some searching reveals that I need to use the [ FromBody ] attribute to read the data from the body , but once I put that in , it no longer gets called . ( CspReportRequest is a class with properties matching the csp-report payload , but it does n't work with string type either . ) So further reading suggests I add a handler for the 'application/csp-report ' content-type that the body is being sent as : But this does n't seem to make a difference . So - how do I make the correct controller signature , and/or the correct service handler options to receive the data . <code> [ HttpPost ] [ AllowAnonymous ] public IActionResult UriReport ( CspReportRequest request ) { _log.LogError ( `` CSP violation : `` + request ) ; return Ok ( ) ; } services.Configure < MvcOptions > ( options = > { options.InputFormatters.OfType < JsonInputFormatter > ( ) .First ( ) .SupportedMediaTypes.Add ( new MediaTypeHeaderValue ( `` application/csp-report '' ) ) ; } ) ;
csp-report endpoint in asp.net core
C_sharp : What is the proper XML-comment syntax to refer to the SingleOrDefault extension method on the IEnumerable interface ? My latest attempt is : The warning is : XML comment on 'yourMethod ' has cref attribute 'IEnumerable.SingleOrDefault ( ) ' that could not be resolved <code> < see cref= '' IEnumerable { T } .SingleOrDefault { T } ( ) '' / >
How to refer to an extension method of a generic class in XML comments
C_sharp : So I have the following block of code inside a method : ( all variables are local ) As you can see , the two try statements are different , but the two sets of catch statements are exactly the same . I 've been trying to think of a way that it might be possible to not repeat myself here , but I have n't really thought of a way that would n't be significantly slower or just as terrible looking . Wondering if anyone has any ideas . <code> // ... try { if ( postXml ! = null ) using ( StreamWriter writer = new StreamWriter ( req.GetRequestStream ( ) ) ) writer.Write ( postXml.ToString ( ) ) ; } catch ( WebException ex ) { HttpWebResponse response = ex.Response as HttpWebResponse ; if ( response ! = null ) result = HandleOtherResponse ( response , out status ) ; else result = HandleBadResponse ( ex.ToString ( ) , out status ) ; } catch ( Exception ex ) { result = HandleBadResponse ( ex.ToString ( ) , out status ) ; } if ( result == null ) { try { HttpWebResponse response = req.GetResponse ( ) as HttpWebResponse ; result = HandleOtherResponse ( response , out status ) ; } catch ( WebException ex ) { HttpWebResponse response = ex.Response as HttpWebResponse ; if ( response ! = null ) result = HandleOtherResponse ( response , out status ) ; else result = HandleBadResponse ( ex.ToString ( ) , out status ) ; } catch ( Exception ex ) { result = HandleBadResponse ( ex.ToString ( ) , out status ) ; } } // ...
DRY With Different Try Statements and Identical Catch Statements
C_sharp : Given an async method : And calling it through an intermediate method , should the intermediate method await the async method IntermediateA or merely return the Task IntermediateB ? As best I can tell with the debugger , both appear to work exactly the same , but it seems to me that IntermediateB should perform better by avoiding one more await entry in the state machine.Is that right ? <code> public async Task < int > InnerAsync ( ) { await Task.Delay ( 1000 ) ; return 123 ; } public async Task < int > IntermediateA ( ) { return await InnerAsync ( ) ; } private Task < int > IntermediateB ( ) { return InnerAsync ( ) ; }
Call chain for async/await ... await the awaitable or return the awaitable ?
C_sharp : I have seen code with the following logic in a few places : What is the point of setting foo to null in the dictionary before removing it ? I thought the garbage collection cares about the number of things pointing to whatever *foo originally was . If that 's the case , would n't setting myDictonary [ `` foo '' ] to null simply decrease the count by one ? Would n't the same thing happen once myDictonary.Remove ( `` foo '' ) is called ? What is the point of _myDictonary [ `` foo '' ] = null ; edit : To clarify - when I said `` remove the count by one '' I meant the following : - myDictonary [ `` foo '' ] originally points to an object . That means the object has one or more things referencing it.- Once myDictonary [ `` foo '' ] is set to null it is no longer referencing said object . This means that object has one less thing referencing it . <code> public void func ( ) { _myDictonary [ `` foo '' ] = null ; _myDictionary.Remove ( `` foo '' ) ; }
Can someone explain what the point of nulling an object before it goes out of scope is ?
C_sharp : There is library A calling library B using a C # extension method.I got a weird error from the C # compiler : The type 'System.Windows.Forms.Control ' is defined in an assembly that is not referenced . You must add a reference to assembly 'System.Windows.Forms , Version=4.0.0.0None of the libraries A or B are dependent on System.Windows.Forms.Control , nor has any dependency of A a dependency on System.Windows.Forms.Control . System.Windows.Forms.Control is only referenced from another project in the same solution.The weird thing is that if I change the call syntax to static method , it compiles successfully.The extension method looks like : So you see there is no problem with detecting which extension to use . LeadSystem is an enum , SourceLeadConfiguration is a class.I have Visual Studio 2013 update 5 , .NET Framework 4.0 . <code> //static method syntax works finevar leads = SourceLeadConfigurationHelper.GetLeads ( enLeadSystem ) ; //extension method syntax cause error//error The type 'System.Windows.Forms.Control ' is defined in an assembly that is not referenced . var leads = enLeadSystem.GetLeads ( ) ; public static class SourceLeadConfigurationHelper { public static IList < ChannelID > GetLeads ( this LeadSystem leadSystem ) ; public static IList < ChannelID > GetLeads ( this SourceLeadConfiguration slc ) ; public static IList < ChannelID > GetLeads ( LeadSystem leadSystem , bool throwException ) ; }
Extension method call does not compile , but static method call to same code does compile
C_sharp : Consider the following code : To my surprise , this outputs 47 ; in other words , the explicit operator long is called even though the cast is to decimal.Is there something in the C # spec that explicitly says that this should happen ( if so , where exactly ) or is this the result of some other rule ( s ) I ’ m missing ? <code> class Program { public static explicit operator long ( Program x ) { return 47 ; } static int Main ( string [ ] args ) { var x = new Program ( ) ; Console.WriteLine ( ( decimal ) x ) ; } }
Why does an explicit cast to ‘ decimal ’ call an explicit operator to ‘ long ’ ?
C_sharp : I have this XAML : Is there some way to shift that unicode character & # x24D8 ; into a shared resource ( like a constant or a StaticResource ) ? What I have triedMethod 1This works fine , but it requires a valid binding to work : And in code behind : Method 2This method seems like it might work , but no luck : <code> < TextBlock Text= '' Message with unicode char : & # x24D8 ; '' / > < Grid > < Grid.Resources > < system : String x : Key= '' ToolTipChar '' > { 0 } & # x24D8 ; < /system : String > < /Grid.Resources > < TextBlock Text= '' { Binding MyText , StringFormat= { StaticResource ToolTipChar } } '' / > < /Grid > public string MyText { get ; set ; } = `` Message with unicode char : `` ; < Grid > < Grid.Resources > < system : String x : Key= '' ToolTipChar '' > { 0 } & # x24D8 ; < /system : String > < /Grid.Resources > < TextBlock Text= '' { Binding Nothing , FallbackValue='Message with unicode char : ' , StringFormat= { StaticResource ToolTipChar } } '' / > < /Grid >
WPF : How to shift Unicode character into a shared resource ?
C_sharp : The grid in WPF currently has a grid system like this : Is there a way to make it behave like this : Ideally I would like the RowSpan to extend an item upwards instead of downwards . Example : My datasource stores a cube on the map as 0,0 with the intent of it being displayed on the bottom left corner . However the grid in WPF will put that cube on the top left . The other problem is the datasource gives me a 2x2 with the position of the bottom left `` anchor '' position with a width and height . The width and height are bound to ColSpan and RowSpan . The RowSpan is an issue because it will be expanded down the grid and not up . <code> Cols + + + + + | 0 | 1 | 2 | 3 | + -- + -- -| -- -| -- -| -- -| -- - 0 | | | | |+ -- + -- -| -- -| -- -| -- -| -- - Rows 1 | | | | | + -- + -- -| -- -| -- -| -- -| -- - 2 | | | | | + -- + -- -| -- -| -- -| -- -| -- - Cols + + + + + | 0 | 1 | 2 | 3 | + -- + -- -| -- -| -- -| -- -| -- - 2 | | | | |+ -- + -- -| -- -| -- -| -- -| -- - Rows 1 | | | | | + -- + -- -| -- -| -- -| -- -| -- - 0 | | | | | + -- + -- -| -- -| -- -| -- -| -- -
Change Grid Coordinate System
C_sharp : I have been trying to draw equilateral triangles on the sides of a larger triangle . The first triangle is drawn by a separate method setting points A , B and C. So far I have just started with two sides , I am able to find the first two points of the smaller triangles , but I am unable to determine the correct formula for the third . I have tried refreshing my memory of trigonometry but I am at an impasse.This may be a question for the math subsection , but I thought I would try here first . What I need is the formula for p3.X and p3.Y Any help would be greatly appreciated.EDIT : changing `` a '' to float a = Convert.ToSingle ( 60 * Math.PI / 180 ) ; results in this : FINAL EDIT : Using MBo 's answer : <code> float a =0 ; Point p = new Point ( pnlDisplay.Width / 2 - ( pnlDisplay.Width / 2 ) /3 , 200 ) ; Triangle t = new Triangle ( p , pnlDisplay.Width / 3 , 0 ) ; drawEqTriangle ( e , t ) ; Point p1 = new Point ( ) ; Point p2 = new Point ( ) ; Point p3 = new Point ( ) ; p1.X = Convert.ToInt32 ( A.X + t.size / 3 ) ; p1.Y = Convert.ToInt32 ( A.Y ) ; p2.X = Convert.ToInt32 ( A.X + ( t.size - t.size / 3 ) ) ; p2.Y = Convert.ToInt32 ( A.Y ) ; ////////////////////////////// p3.X = Convert.ToInt32 ( ( A.X - t.size / 3 ) * Math.Sin ( a ) ) ; p3.Y = Convert.ToInt32 ( ( A.Y - t.size / 3 ) * Math.Cos ( a ) ) ; drawTriangle ( e , p1 , p2 , p3 ) ; p1.X = Convert.ToInt32 ( ( B.X - t.size / 3 * Math.Cos ( t.angle + Math.PI / 3 ) ) ) ; p1.Y = Convert.ToInt32 ( ( B.Y + t.size / 3 * Math.Sin ( t.angle+ Math.PI / 3 ) ) ) ; p2.X = Convert.ToInt32 ( ( B.X - ( t.size - t.size / 3 ) * Math.Cos ( t.angle + Math.PI / 3 ) ) ) ; p2.Y = Convert.ToInt32 ( ( B.Y + ( t.size - t.size / 3 ) * Math.Sin ( t.angle + Math.PI / 3 ) ) ) ; ////////////////////////////// p3.X = Convert.ToInt32 ( ( B.X - t.size / 3 ) * Math.Cos ( a ) ) ; p3.Y = Convert.ToInt32 ( ( B.Y - t.size / 3 ) * Math.Tan ( a ) ) ; drawTriangle ( e , p1 , p2 , p3 ) ;
C # Drawing equilateral triangles on the sides of another equilateral triangle
C_sharp : Possible Duplicate : Define a generic that implements the + operator I am recently working on a C # class library implementing an algorithm . The point is that I would like the users of the library to be able to choose the machine precision ( single or double ) the algorithm should operate with , and I 'm trying to do it with generics . So , for instance : orThus , the type parameter for the generic classes is meant to be a decimal number ( because in the algorithm code I need to use + , * , / , - ) , but I do n't know which kind of type constraint to impose on it . I have thought about building an interface with all the operators but , unfortunately , this is not allowed . Any ideas ? Otherwise , is it possible to obtain in C # something similar to template specialization in C++ ? Thank youTommaso <code> Algorithm < double > a = new Algorithm < double > ( ) ; /** Some initializations here */ double result = a.Solve ( ) ; Algorithm < float > a = new Algorithm < float > ( ) ; /** Some initializations here */ float result = a.Solve ( ) ;
How to impose , in a C # generic type parameter , that some operators are supported ?
C_sharp : I can type In fact , I expect I could keep going adding dimensions to Int.MaxValue though I have no idea how much memory that would require.How could I implement this variable indexing feature in my own class ? I want to encapsulate a multi dimensional array of unknown dimensions and make it available as a property thus enabling indexing in this manner . Must I always know the size in which case how does Array work ? EDITThanks for the comments , here is what I ended up with - I did think of params but did n't know where to go after that not knowing about GetValue . TBH I do n't really need this now . I was just looking for a way to extend Array to initialize its elements having resolved to avoid for loop initialization code outside the class whenever I was using a multi array ( mainly in unit tests ) . Then I hit intellisense and saw the Initialize method ... though it restricts me to a default constructor and value types . For reference types an extension method would be required . Still I learnt something and yes , there was a runtime error when I tried an array with more than 32 dimensions . <code> Square [ , , , ] squares = new Square [ 3 , 2 , 5 , 5 ] ; squares [ 0 , 0 , 0 , 1 ] = new Square ( ) ; class ArrayExt < T > { public Array Array { get ; set ; } public T this [ params int [ ] indices ] { get { return ( T ) Array.GetValue ( indices ) ; } set { Array.SetValue ( value , indices ) ; } } } ArrayExt < Square > ext = new ArrayExt < Square > ( ) ; ext.Array = new Square [ 4 , 5 , 5 , 5 ] ; ext [ 3 , 3 , 3 , 3 ] = new Square ( ) ;
How to implement Array indexer in C #
C_sharp : I am trying the code to find out whether the user has already signed in or not ? Even if the user has already logged in , it returns Unknown . What is the problem with this ? <code> LiveAuthClient LCAuth = new LiveAuthClient ( ) ; LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync ( ) ;
LiveLoginResult.Status is Unknown ?
C_sharp : How would I convert this to HttpClient ? What I 'm looking to do is submit a Tweet to the Twitter api and get the response as Json . The HttpWebRequest is working fine but I just want to port it to HttpClient . I made an attempt at it in the second code example , but it 's not actually sending or receiving the response.This is what I 've tried to get it work : I 've tried to add another parameter to the request and it 's always coming back as 401 unauthorized . I 'm trying to create a Twitter thread . If I remove the in_reply_to_status_id then it 's fine.The Twitter API describes it here https : //developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update <code> HttpWebRequest request = null ; WebResponse response = null ; string responseCode = String.Empty ; try { string postBody = `` status= '' + EncodingUtils.UrlEncode ( status ) ; request = ( HttpWebRequest ) HttpWebRequest.Create ( resource_url ) ; request.ServicePoint.Expect100Continue = true ; request.UseDefaultCredentials = true ; request.PreAuthenticate = true ; request.Credentials = CredentialCache.DefaultCredentials ; request.ServicePoint.ConnectionLimit = 1 ; request.Headers.Add ( `` Authorization '' , authHeader ) ; request.Method = `` POST '' ; request.ContentType = `` application/x-www-form-urlencoded '' ; using ( Stream stream = request.GetRequestStream ( ) ) { using ( StreamWriter writer = new StreamWriter ( stream ) ) { writer.Write ( postBody ) ; } } using ( response = request.GetResponse ( ) ) { response.ContentType = `` application/json '' ; responseCode = ( ( HttpWebResponse ) response ) .StatusCode.ToString ( ) ; } } catch ( WebException ex ) { if ( ex.Status ! = WebExceptionStatus.NameResolutionFailure ) { request.Abort ( ) ; request = null ; } throw ex ; } return responseCode ; private async Task < string > MakeWebRequest1 ( string status , string resource_url , string authHeader ) { HttpClientHandler clientHandler = new HttpClientHandler ( ) ; clientHandler.Credentials = CredentialCache.DefaultCredentials ; clientHandler.PreAuthenticate = true ; clientHandler.AllowAutoRedirect = true ; string responseCode = `` '' ; string postBody = `` status= '' + EncodingUtils.UrlEncode ( status ) ; var request = new HttpRequestMessage ( ) { RequestUri = new Uri ( resource_url ) , Method = HttpMethod.Post , } ; request.Headers.Add ( `` Authorization '' , authHeader ) ; // request.Content.Headers.ContentType = new MediaTypeHeaderValue ( `` application/x-www-form-urlencoded '' ) ; request.Content = new StringContent ( postBody , Encoding.UTF8 , '' application/x-www-form-urlencoded '' ) ; //CONTENT-TYPE header using ( HttpClient client = new HttpClient ( clientHandler ) ) { client.DefaultRequestHeaders.Accept.Add ( new MediaTypeWithQualityHeaderValue ( `` application/x-www-form-urlencoded '' ) ) ; // Stream stuff = await client.GetStreamAsync ( resource_url ) ; using ( HttpResponseMessage response = await client.SendAsync ( request ) ) { response.Content.Headers.ContentType = new MediaTypeHeaderValue ( `` application/json '' ) ; if ( response.StatusCode == HttpStatusCode.OK ) { responseCode = `` OK '' ; } } } clientHandler.Dispose ( ) ; return responseCode ; } enter code here data = new Dictionary < string , string > { [ `` status '' ] = `` @ username + status , [ `` in_reply_to_status_id '' ] = `` 1167588690929115136 '' } ;
Refactor HttpWebRequest to HttpClient ?
C_sharp : I 'm receiving several bit fields from hardware.My code was originally : Then I remembered the flags enum and am considering changing it to : and so on.Which is best practice and what if any are the pros and cons of each approach ? EDIT : I 'm interested to know if there are any practical differences between the two approaches , particularly in regards to performance . I 'm not wishing to solicit opinion on coding styles ( unless it comes from Microsoft guidelines ) as that would see the question closed as unconstructive . Thanks . <code> public readonly byte LowByte ; public bool Timer { get { return ( LowByte & 1 ) == 1 ; } } [ Flags ] public enum LowByteReasonValues : byte { Timer = 1 , DistanceTravelledExceeded = 2 , Polled = 4 , GeofenceEvent = 8 , PanicSwitchActivated = 16 , ExternalInputEvent = 32 , JourneyStart = 64 , JourneyStop = 128 } public readonly LowByteReasonValues LowByte ; public bool Timer { get { return ( LowByte & LowByteReasonValues.Timer ) == LowByteReasonValues.Timer ; } }
What are the pros and cons of using a flags enum ?
C_sharp : Take a look at the code : I want to remove all whitespace from the original string and then get the individual characters.The result surprized me.The variable exprCharsNoWhitespace contains , as expected , no whitespace , but unexpectedly , only almost all of the other characters . The last occurence of ' & ' is missing , the Count of the list is 12.Whereas exprCharsNoWhitespace_2 is completely as expected : Count is 13 , all characters other than whitespace are contained.The framework used was .NET 4.0.I also just pasted this to csharppad ( web-based IDE/compiler ) and got the same results.Why does this happen ? EDIT : Allright , I was unaware that Except is , as pointed out by Ryan O'Hara , a set operation . I had n't used it before . <code> string expression = `` x & ~y - > ( s + t ) & z '' ; var exprCharsNoWhitespace = expression.Except ( new [ ] { ' ' , '\t ' } ) .ToList ( ) ; var exprCharsNoWhitespace_2 = expression.Replace ( `` `` , `` '' ) .Replace ( `` \t '' , `` '' ) .ToList ( ) ; // output for examinationConsole.WriteLine ( exprCharsNoWhitespace.Aggregate ( `` '' , ( a , x ) = > a+x ) ) ; Console.WriteLine ( exprCharsNoWhitespace_2.Aggregate ( `` '' , ( a , x ) = > a+x ) ) ; // Output : // x & ~y- > ( s+t ) z// x & ~y- > ( s+t ) & z // So I 'll continue just using something like this : expression.Where ( c = > c ! = ' ' & & c ! ='\t ' ) // or for more characters this can be shorter : expression.Where ( c = > ! new [ ] { ' a ' , ' b ' , ' c ' , 'd ' } .Contains ( c ) ) .
Why is one character missing in the query result ?
C_sharp : I used to be a C++ programer on Windows.I know that the compiler will optimizes the ternary operator in C++.C++ code : Because of the pipeline stuff , the generated native code is shown as below ( of course Release model ) : C # code : I looked up the native code JIT generated , but there is no optimization at all ( still two jump instructions ) .Why does n't the C # JIT compiler make the same optimization as C++ compiler does ? What 's the story behind this ? Any information will be appreciated.Hi there , I have modified the C # program and run it with release model.BeforeNowBut the result is still the same.There still two jump instruction exist.I will appreciate it if there is any further more information . <code> # include `` stdafx.h '' int _tmain ( int argc , _TCHAR* argv [ ] ) { int result = argc > 3 ? 1 : 5 ; printf ( `` % d '' , result ) ; return 0 ; } int result = argc > 3 ? 1 : 5 ; 00B21003 xor eax , eax 00B21005 cmp dword ptr [ argc ] ,300B21009 setle al 00B2100C lea eax , [ eax*4+1 ] namespace TernaryOperatorCSharp { static void Main ( string [ ] args ) { int argc = args.Length ; int result = argc > 1 ? 2 : 5 ; System.Console.WriteLine ( result ) ; } } int result = argc > 1 ? 2 : 5 ; 0000002f cmp dword ptr [ ebp-4 ] ,1 00000033 jg 0000003F 00000035 nop 00000036 mov dword ptr [ ebp-0Ch ] ,5 0000003d jmp 00000046 0000003f mov dword ptr [ ebp-0Ch ] ,2 00000046 mov eax , dword ptr [ ebp-0Ch ] 00000049 mov dword ptr [ ebp-8 ] , eax System.Console.WriteLine ( result ) ; 0000004c mov ecx , dword ptr [ ebp-8 ] 0000004f call 6A423CBC int result = args.Length > 1 ? 2 : 5 ; int argc = args.Length ; int result = argc > 1 ? 2 : 5 ;
C # vs C++ ternary operator
C_sharp : I 've struggled a lot with how to show a modal panel on click on a button inside a grid view.To context : I have a data row with a string field that can contain a simple text or a base 64 encoded image , so I 'm using a custom template to define when to show the raw content or a button `` View Image '' . This image will be opened on a modal panel that should rise up on button click.This is the Panel I 've created as a control ( ascx ) : And this is the page and ASPxGridView where I wan na use it : Codebihind : The ButtonColumn template creation : The method 's call at the click of btnShowImage button works fine . But when I do the same call by one ImageButton ( or button ) inside the gridview it does n't work . Both calls reach the ShowImage method.Any help would be appreciated . Thank you all.EDIT 1 : The GridView is encapsulated in GridViewWrapper ( there I build the columns dynamically using a combination of class 's properties gotten by reflection and stored metadata ) , this class have too much code to share here and I do not think it 's the reason . Also , I 've executed in debug mode and passed thru it step by step every relevant method inside this one . The column add method : I 've made sure the ShowImage method is being hitten , but it behaves like the UpdatePanel1 is n't have been updated <code> < asp : Panel ID= '' pnlModalOverlay '' runat= '' server '' Visible= '' true '' CssClass= '' Overlay '' > < asp : Panel ID= '' pnlModalMainContent '' runat= '' server '' Visible= '' true '' CssClass= '' ModalWindow '' > < div class= '' WindowTitle '' > < asp : Label ID= '' lbTitle '' runat= '' server '' / > < /div > < div class= '' WindowBody '' > < asp : Panel ID= '' pnlContent '' runat= '' server '' Visible= '' true '' > < asp : Image ID= '' imgContent '' runat= '' server '' CssClass= '' ImageView '' / > < /asp : Panel > < div class= '' Button '' > < asp : Button ID= '' btnOk '' runat= '' server '' class= '' btn btn-default `` Text= '' Close '' OnClientClick= '' loadingPanel.Show ( ) ; '' / > < /div > < /div > < /asp : Panel > < /asp : Panel > < asp : UpdatePanel ID= '' UpdatePanel1 '' runat= '' server '' UpdateMode= '' Conditional '' ChildrenAsTriggers= '' true '' > < ContentTemplate > < div style= '' margin-top : 12px ; '' > < asp : Button type= '' button '' ID= '' btnShowImage '' AutoPostBack= '' true '' class= '' btn btn-default navbar-right '' Text= '' Show Image '' runat= '' server '' Style= '' margin-left : 5px ; '' OnClientClick= '' loadingGridPanel.Show ( ) ; '' / > < /div > < ! -- Some data filter controls -- > < MyWorkspace : AlertModal ID= '' alertModal '' runat= '' server '' Visible= '' false '' / > < MyWorkspace : ImageModal ID= '' imageModal '' runat= '' server '' Visible= '' false '' / > < /ContentTemplate > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' mainGrid '' / > < /Triggers > < /asp : UpdatePanel > < MyWorkspace : GridViewWrapper ID= '' mainGrid '' runat= '' server '' Visible= '' true '' / > public partial class MyPage : System.Web.UI.Page { protected override void OnInit ( EventArgs e ) { base.OnInit ( e ) ; btnShowImage.Click += new EventHandler ( ShowImage ) ; // This call works fine } protected void Page_Load ( object sender , EventArgs e ) { try { if ( ! IsPostBack ) { mainGrid.CanEditItems = true ; mainGrid.CustomTemplates.Add ( new CustomColumnTemplate { columnName = `` Id '' , template = new LinkColumn ( CreateParentLink , `` Go to parent '' ) } ) ; mainGrid.CustomTemplates.Add ( new CustomColumnTemplate { columnName = `` Value '' , template = new ButtonColumn ( ShowImage , `` View Image '' ) } ) ; // This one does n't works } } catch ( Exception ex ) { modalAlerta.Show ( `` Page_Load '' , ex.Message , false , false , `` '' ) ; } } void ShowImage ( ) { modalImagem.Show ( ) ; // Set Modal 's Visible property to True // UpdatePanel1.Update ( ) ; < -- Tryin ' force it to work with no success } } public class ButtonColumn : System.Web.UI.ITemplate { private Action action ; private string controlId ; private string tooltip ; public ButtonColumn ( Action onClick , string toolTip ) { this.action = onClick ; this.controlId= `` btnShowImage '' ; this.tooltip = toolTip ; } public void InstantiateIn ( System.Web.UI.Control container ) { GridViewDataItemTemplateContainer gridContainer = ( GridViewDataItemTemplateContainer ) container ; if ( System.Text.RegularExpressions.Regex.IsMatch ( gridContainer.Text , `` ^ ( [ A-Za-z0-9+/ ] { 4 } ) * ( [ A-Za-z0-9+/ ] { 4 } | [ A-Za-z0-9+/ ] { 3 } =| [ A-Za-z0-9+/ ] { 2 } == ) $ '' ) ) { ImageButton button = new ImageButton ( ) ; button.ID = idControle ; button.ImageUrl = `` /Images/html5_badge_64.png '' ; button.Width = 20 ; button.Height = 20 ; button.ToolTip = tooltip ; button.Click += ( s , a ) = > { if ( onClick ! = null ) onClick ( ) ; } ; container.Controls.Add ( button ) ; } else { Label label = new Label ( ) { Text = gridContainer.Text , ToolTip = tooltip } ; container.Controls.Add ( label ) ; } } } CustomColumnTemplate customTemplate = CustomTemplates.FirstOrDefault ( f = > f.columnName == metadata.ColumnIdName ) ; gridView.Columns.Add ( new GridViewDataColumn ( ) { FieldName = metadata.ColumnIdName , VisibleIndex = GetVisibleIndexByColumnIdName ( metadata.ColumnIdName ) , Caption = metadata.Caption , Width = new Unit ( DefaultColumnWidth , UnitType.Pixel ) , DataItemTemplate = customTemplate == null ? null : customTemplate.template } ) ;
Modal Panel Doesn ’ t Appear When Called by Button Inside a Grid View ’ s Cell
C_sharp : I have the following structureOn the code behind I get the repeater ItemDataBound event , get the control using var button1 = e.Item.FindControl ( `` Button1 '' ) as LinkButton ; then I assign a CommandArgument with the ID of the current element.This is being executed immediately after the CreateChildControls method.This method just change the view ... The problem is that the view does n't change . When I click the LinkButton it executes the CreateChildControls and after it calls the event ItemCommand , the event calls the BuildSingleView , the ActiveViewIndex is changed but nothing happens on the page.I do n't understand why it does n't change . Is it a problem with the order of events ? What could I do to change the view when I click a LinkButton ? Here is the full code-behind code ( the Initialize method is the method that executes immediately after CreateChildControls ) http : //pastebin.com/2qwrKNxfAnd here the full ascx file http : //pastebin.com/P8RSbY9U <code> < asp : UpdatePanel ID= '' MyUpdatePanel '' runat= '' server '' > < ContentTemplate > < asp : MultiView ID= '' MyViews '' runat= '' server '' > < asp : View ID= '' List '' runat= '' server '' > < asp : Repeater runat= '' server '' ID= '' Repeater1 '' > < ItemTemplate > < asp : LinkButton ID= '' Button1 '' runat= '' server '' Text= '' Button1 '' CommandName= '' View '' / > < /ItemTemplate > < /asp : Repeater > < /asp : View > < asp : View ID= '' Single '' runat= '' server '' > < asp : LinkButton ID= '' Button2 '' runat= '' server '' Text= '' Button2 '' / > < /asp : View > < /asp : MultiView > < /ContentTemplate > < /asp : UpdatePanel > Repeater1.ItemDataBound += ( s , e ) = > { if ( e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item ) { var Button1 = e.Item.FindControl ( `` Button1 '' ) as LinkButton ; Button1.CommandArgument = item.ID.ToString ( ) ; } } ; Repeater1.ItemCommand += ( s , e ) = > { if ( e.CommandName == `` View '' ) { var item = provider.Get ( Convert.ToInt64 ( e.CommandArgument ) ) ; BuildSingleView ( item ) ; } } ; public void BuildSingleView ( var item ) { MyViews.ActiveViewIndex = 1 ; /* Edit I 've tried to call here Initialize ( ) , EnsureChildControls ( ) , CreateChildControls ( ) but it was a useless try . I also tried to catch exceptions , but none happened . */ }
How to change a View with a button on a Repeater ?
C_sharp : ContextWe have a C # program , that deals with time.We have clients in France , so we convert times to and from France 's timezone.In our C # code : we use Central European Standard Time as a time zone for France.It describes a timezone , which follows DST changes : on the last sunday of march ( 3 AM ) , clocks swicth to summer time are moved forward 1hon the last sunday of october ( 3 AM ) , clocks switch to winter time and are moved backward 1hOur situationThe thing is : France aligned with CEST in 1996 ; before that date , France would switch from summer time to winter time on the last sunday of september.Window 's CEST timezone describes ( accurately ) CEST , which happens to not be 100 % equivalent to France 's timezone for dates before october 1995.When testing the IANA database ( in Windows subsystem for linux ) , it turns out the Europe/Paris timezone accurately switches time at the end of september for dates < 1995.Questionis there either : a representation of Europe/Paris timezone in Window 's list of standard timezones ? a way to use the IANA database ( and Europe/Paris ) from C # ? Sample code we use to convert time to UTC : <code> using System ; using System.Globalization ; namespace TestingApp { class Program { static void Main ( string [ ] args ) { var tz = TimeZoneInfo.FindSystemTimeZoneById ( `` Central European Standard Time '' ) ; string [ ] times = { // In 1995 : // last sunday in september was sept. 24th // last sunday in october was oct. 29th `` 1995/09/23 12:00:00 '' , `` 1995/09/24 12:00:00 '' , `` 1995/10/28 12:00:00 '' , `` 1995/10/29 12:00:00 '' , } ; foreach ( var t in times ) { var utc = DateTime.ParseExact ( t , `` yyyy/MM/dd HH : mm : ss '' , CultureInfo.InvariantCulture , DateTimeStyles.None ) ; utc = TimeZoneInfo.ConvertTime ( utc , tz , TimeZoneInfo.Utc ) ; Console.WriteLine ( String.Format ( `` Paris : { 0 } - > UTC : { 1 } '' , t , utc.ToString ( ) ) ) ; } } } } // Output : // Paris : 1995/09/23 12:00:00 - > UTC : 23/09/1995 10:00:00// Paris : 1995/09/24 12:00:00 - > UTC : 24/09/1995 10:00:00 < - instead of 11:00:00 UTC// Paris : 1995/10/28 12:00:00 - > UTC : 28/10/1995 10:00:00 < - instead of 11:00:00 UTC// Paris : 1995/10/29 12:00:00 - > UTC : 29/10/1995 11:00:00
What timezone should I use for France to support old and new daylight saving adjustments ?
C_sharp : In C # when an Task or Task < T > method is returned from within a using statement is there any risk of the cleanup not properly occurring , or is this a poor practice ? What concerns are there as it pertains to the closure of the variable in the using block ? Consider the following : In the example above the asynchronous operation is represented by the client.GetStringAsync ( url ) , I 'm simply returning that Task < string > for the consumer to await . What happens to the client as it is in a using - does it get cleaned up before it is awaited or garbage collected , or does it cause other issues ? Would it be better to use async and await in the cause of using statements like this , if so why ? OrWhat is the difference ? <code> public Task < string > GetAsync ( string url ) { using ( var client = new HttpClient ( ) ) { return client.GetStringAsync ( url ) ; } } public async Task < string > GetAsync ( string url ) { string response = string.Empty ; using ( var client = new HttpClient ( ) ) { response = await client.GetStringAsync ( url ) ; } return response ; } public async Task < string > GetAsync ( string url ) { using ( var client = new HttpClient ( ) ) { return await client.GetStringAsync ( url ) ; } }
C # Task returning method in using block
C_sharp : I ’ m writing console application which does some work by scheduler and write output to console . Everything is good but when I click on the console it stops working and waits for my right click . After that it continues working.I thought that it simply doesn ’ t write text to console and does what it needs to do but no , it waits my interaction . I can rewrite this code to WinForms or WPF but I think it can be solved in another way . Here my codeAfter clicking on console it stops appending time to file log.txt . Any ideas how to fix that ? Thanks . <code> static void Main ( string [ ] args ) { Console.WriteLine ( `` Started ... '' ) ; var timer = new System.Timers.Timer ( 1000 ) ; timer.Elapsed += timer_Elapsed ; timer.Start ( ) ; Console.ReadLine ( ) ; } static void timer_Elapsed ( object sender , ElapsedEventArgs e ) { Console.WriteLine ( `` Writing to file `` + DateTime.Now.ToString ( ) ) ; System.IO.File.AppendAllLines ( @ '' C : \Temp\log.txt '' , new [ ] { DateTime.Now.ToString ( ) } ) ; }
Console application ( C # ) is stuck while interaction
C_sharp : Is there a way to put the GC on hold completely for a section of code ? The only thing I 've found in other similar questions is GC.TryStartNoGCRegion but it is limited to the amount of memory you specify which itself is limited to the size of an ephemeral segment.Is there a way to bypass that completely and tell .NET `` allocate whatever you need , do n't do GC period '' or to increase the size of segments ? From what I found it is at most 1GB on a many core server and this is way less than what I need to allocate yet I do n't want GC to happen ( I have up to terabytes of free RAM and there are thousands of GC spikes during that section , I 'd be more than happy to trade those for 10 or even 100 times the RAM usage ) .Edit : Now that there 's a bounty I think it 's easier if I specify the use case . I 'm loading and parsing a very large XML file ( 1GB for now , 12GB soon ) into objects in memory using LINQ to XML . I 'm not looking for an alternative to that . I 'm creating millions of small objects from millions of XElements and the GC is trying to collect non-stop while I 'd be very happy keeping all that RAM used up . I have 100s of GBs of RAM and as soon as it hits 4GB used , the GC starts collecting non-stop which is very memory friendly but performance unfriendly . I do n't care about memory but I do care about performance . I want to take the opposite trade-off.While i ca n't post the actual code here is some sample code that is very close to the end code that may help those who asked for more information : <code> var items = XElement.Load ( `` myfile.xml '' ) .Element ( `` a '' ) .Elements ( `` b '' ) // There are about 2 to 5 million instances of `` b '' .Select ( pt = > new { aa = pt.Element ( `` aa '' ) , ab = pt.Element ( `` ab '' ) , ac = pt.Element ( `` ac '' ) , ad = pt.Element ( `` ad '' ) , ae = pt.Element ( `` ae '' ) } ) .Select ( pt = > new { aa = new { aaa = double.Parse ( pt.aa.Attribute ( `` aaa '' ) .Value ) , aab = double.Parse ( pt.aa.Attribute ( `` aab '' ) .Value ) , aac = double.Parse ( pt.aa.Attribute ( `` aac '' ) .Value ) , aad = double.Parse ( pt.aa.Attribute ( `` aad '' ) .Value ) , aae = double.Parse ( pt.aa.Attribute ( `` aae '' ) .Value ) } , ab = new { aba = double.Parse ( pt.aa.Attribute ( `` aba '' ) .Value ) , abb = double.Parse ( pt.aa.Attribute ( `` abb '' ) .Value ) , abc = double.Parse ( pt.aa.Attribute ( `` abc '' ) .Value ) , abd = double.Parse ( pt.aa.Attribute ( `` abd '' ) .Value ) , abe = double.Parse ( pt.aa.Attribute ( `` abe '' ) .Value ) } , ac = new { aca = double.Parse ( pt.aa.Attribute ( `` aca '' ) .Value ) , acb = double.Parse ( pt.aa.Attribute ( `` acb '' ) .Value ) , acc = double.Parse ( pt.aa.Attribute ( `` acc '' ) .Value ) , acd = double.Parse ( pt.aa.Attribute ( `` acd '' ) .Value ) , ace = double.Parse ( pt.aa.Attribute ( `` ace '' ) .Value ) , acf = double.Parse ( pt.aa.Attribute ( `` acf '' ) .Value ) , acg = double.Parse ( pt.aa.Attribute ( `` acg '' ) .Value ) , ach = double.Parse ( pt.aa.Attribute ( `` ach '' ) .Value ) } , ad1 = int.Parse ( pt.ad.Attribute ( `` ad1 '' ) .Value ) , ad2 = int.Parse ( pt.ad.Attribute ( `` ad2 '' ) .Value ) , ae = new double [ ] { double.Parse ( pt.ae.Attribute ( `` ae1 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae2 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae3 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae4 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae5 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae6 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae7 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae8 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae9 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae10 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae11 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae12 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae13 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae14 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae15 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae16 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae17 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae18 '' ) .Value ) , double.Parse ( pt.ae.Attribute ( `` ae19 '' ) .Value ) } } ) .ToArray ( ) ;
Put GC on hold during a section of code
C_sharp : We have entity framework implemented in our Web API 2.0 code . To call database entities , we are using store procedure calls . Our entire application is hosted in Microsoft Azure cloud . Here are the two exception which we are facing.Message : An error occurred while executing the command definition . See the inner exception for details.InnerException : Timeout expired . The timeout period elapsed prior to completion of the operation or the server is not responding . This failure occured while attempting to connect to the Principle server.One more exception we are facing is like : Message : The underlying provider failed on Open.InnerException : The connection was not closed . The connection 's current state is connecting.Note : Code is in C # Web API 2.0 . We are using Entity Framework to call Store Procedure . Database is in SQL Server 2012 . In web.config , the connection string looks like below : Also , this errors are not continuous , we guess this might be happening either network issues or while heavy traffic . But we are still not having any firm cause about this.Please guide us with a solution for the same . <code> < add name= '' *****Entities '' connectionString= '' metadata=res : //*/Models.Database.*****.csdl|res : //*/Models.Database.*****.ssdl|res : //*/Models.Database . *****.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source=***** ; Failover Partner=***** ; initial catalog=***** ; user id=***** ; password=******** ; MultipleActiveResultSets=True ; Pooling=false ; Connection Lifetime=2 ; App=EntityFramework & quot ; '' providerName= '' System.Data.EntityClient '' / >
SQL Connection Errors in Microsoft Azure
C_sharp : How can I bind a control inside a usercontrol resource to a property ? Alternatively , can I find the control from the code behind and get & set the value from there ? Here is my markup . I 've stripped it down to just the relevant part : Salesmen.xaml : And here 's my property . Despite the two-way binding it is always null : Salesmen.xaml.cs : I 've heard about the VisualTreeHelper and the LogicalTreeHelper . These might enable another approach - finding the control and getting and them manually . However , VisualTreeHelper only sees the LayoutRoot and it 's children ( not UserControl.Resources ) , and LogicalTreeHelper does not seem to be available ( it 's a SilverLight 5 project ; I do n't know what framework is used by Silverlight 5 . I understand that LogicalTreeHelper is only available in 4.5 and later ) Thank you for you assistance . Note : this question will get a +50 bounty . The system requires me to wait for 2 days to put a bounty , so I will put the bounty and accept the answer after 2 days . I will let you know if your answer works before that . <code> < UserControl.Resources > < ControlTemplate x : Key= '' EditAppointmentTemplate1 '' TargetType= '' local : SchedulerDialog '' x : Name= '' ControlTemplate '' > < ScrollViewer HorizontalScrollBarVisibility= '' Auto '' VerticalScrollBarVisibility= '' Auto '' > < Grid > < Grid Name= '' grdTotal '' Grid.Row= '' 4 '' Visibility= '' { Binding ResourceTypesVisibility } '' > < TextBox x : Name= '' totalSalesmen '' Grid.Row= '' 0 '' Grid.Column= '' 1 '' Margin= '' 3 '' Width= '' 120 '' Text= '' { Binding Parent.totalSalesmen , ElementName=LayoutRoot , Mode=TwoWay } '' / > < /Grid > < /ScrollViewer > < /ControlTemplate > < Style x : Key= '' EditAppointmentDialogStyle1 '' TargetType= '' local : SchedulerDialog '' > < Setter Property= '' Template '' Value= '' { StaticResource EditAppointmentTemplate1 } '' / > < /Style > < /UserControl.Resources > < Grid x : Name= '' LayoutRoot '' Background= '' White '' HorizontalAlignment= '' Left '' Margin= '' 10,10,0,0 '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < StackPanel Orientation= '' Vertical '' > < ScrollViewer HorizontalScrollBarVisibility= '' Auto '' VerticalScrollBarVisibility= '' Auto '' BorderBrush= '' Transparent '' > < telerik : RadCalendar Name= '' RadCalendar '' SelectedDate= '' { Binding CurrentDate , ElementName=RadScheduleViewTests , Mode=TwoWay } '' IsTodayHighlighted= '' True '' telerik : StyleManager.Theme= '' Metro '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' FirstDayOfWeek= '' Sunday '' Margin= '' 0,0,15,0 '' SelectionChanged= '' RadCalendar_SelectionChanged_1 '' > < /telerik : RadCalendar > < /ScrollViewer > < /StackPanel > < telerik : RadScheduleView Name= '' RadScheduleViewTests '' MinAppointmentWidth= '' 100 '' Tag= '' { Binding Path=Context , ElementName=TestDayPage } '' telerik : StyleManager.Theme= '' Metro '' Grid.Column= '' 1 '' EditAppointmentDialogStyle= '' { StaticResource EditAppointmentDialogStyle1 } '' AppointmentCreating= '' RadScheduleViewTests_AppointmentCreating_1 '' AppointmentEditing= '' RadScheduleViewTests_AppointmentEditing_1 '' AppointmentDeleting= '' RadScheduleViewTests_AppointmentDeleting_1 '' FirstDayOfWeek= '' Sunday '' ShowDialog= '' RadScheduleViewTests_ShowDialog_1 '' AppointmentEdited= '' RadScheduleViewTests_AppointmentEdited_1 '' > < telerik : RadScheduleView.DragDropBehavior > < examiners : CustomDragDropBehaviour/ > < /telerik : RadScheduleView.DragDropBehavior > < telerik : RadScheduleView.SchedulerDialogHostFactory > < test : CustomScheduleViewDialogHostFactory / > < /telerik : RadScheduleView.SchedulerDialogHostFactory > < telerik : RadScheduleView.ViewDefinitions > < telerik : DayViewDefinition/ > < telerik : WeekViewDefinition/ > < telerik : MonthViewDefinition/ > < telerik : TimelineViewDefinition/ > < /telerik : RadScheduleView.ViewDefinitions > < /telerik : RadScheduleView > < /Grid > string totalSalesmen { get ; set ; }
How can I bind or otherwise get & set a value of a control in a resource ?
C_sharp : I have defined the following classes and methods : This compiles fine . Woo hoo ! Half-way there . Then , I try to use it later with code like this : This , however , dies with the following error message The type ToolStripStatusLabel can not be used as type parameter C in the generic type or method Something < T > .Do < C , S > ( C , Expression < Func < C , S > > ) . There is no implicit reference conversion from ToolStripStatusLabel to Control.It seems to me that the C # compiler has failed in this case though the two methods do not create a set of ambiguous method declarations . Control and ToolStripStatusLabel exist as siblings in the inheritance tree of Component . I would think that the compiler would have enough information to correctly bind the method invocation in the client code.However , if I do the same thing with my own sibling classes , then everything compiles fine.Can anyone shed light on what I have done wrong , if anything ? <code> using System ; using System.Linq.Expressions ; using System.Windows.Forms ; public class ReturnValue < T , S > { } public class Something < T > { // Sorry about the odd formatting . Trying to get it to fit nicely ... public ReturnValue < T , C > Do < C , S > ( C control , Expression < Func < C , S > > controlProperty ) where C : Control { return new ReturnValue < T , C > ( ) ; } public ReturnValue < T , ToolStripItem > Do < S > ( ToolStripItem control , Expression < Func < ToolStripItem , S > > controlProperty ) { return new ReturnValue < T , ToolStripItem > ( ) ; } } var toolStripItem = new ToolStripStatusLabel ( ) ; var something = new Something < string > ( ) ; something.Do ( toolStripItem , t = > t.Text ) ; // Does not compile public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Something2 < T > { public ReturnValue < T , C > Do < C , S > ( C control , Expression < Func < C , S > > controlProperty ) where C : Child1 { return new ReturnValue < T , C > ( ) ; } public ReturnValue < T , Child2 > Do < S > ( Child2 control , Expression < Func < Child2 , S > > controlProperty ) { return new ReturnValue < T , Child2 > ( ) ; } } var child2 = new Child2 ( ) ; var something2 = new Something2 < string > ( ) ; something2.Do ( child2 , c = > c.GetType ( ) ) ; // Compiles just fine
Why Does C # Not Bind Correctly to Generic Overridden Methods ?
C_sharp : is evaluated to 108 . Why ? IMO the ( int ) -cast should be evaluated after the multiplication . <code> ( int ) ( ( float ) 10.9 * 10 )
Understanding the given calculation ( cast + multiplication )
C_sharp : I 'm writing a program that writes C # that eventually gets compiled into an application . I would like each of the generated types to provide a `` deep clone '' function which copies the entire tree of data . That is , I want someone to be able to do : instead ofHowever , C # does n't allow you to do this in a simple override ; the overrides must return the same type as the declared type on the base.Since I 'm writing code that stamps out boilerplate anyway , is there something I can generate to allow the first block to compile ? I tried something similar to the following : but this does not compile because the overrides do n't match . I also tried overriding the method from the base and hiding it with the `` new '' keyword , but this did n't work either . <code> var x = new Base ( ) ; // Base has public virtual Base DeepClone ( ) { ... } var y = new Derived ( ) ; // Derived overrides DeepCloneBase a = x.DeepClone ( ) ; Base b = y.DeepClone ( ) ; // Derived c = x.DeepClone ( ) ; // Should not compileDerived d = y.DeepClone ( ) ; // Does not compile , DeepClone returns Base var x = new Base ( ) ; var y = new Derived ( ) ; Base a = x.DeepClone ( ) ; Base b = y.DeepClone ( ) ; // Derived c = x.DeepClone ( ) ; // Should not compileDerived d = ( Derived ) y.DeepClone ( ) ; abstract class Base { public abstract Base DeepClone ( ) ; } class Base2 : Base { int Member { get ; set ; } public Base2 ( ) { /* empty on purpose */ } public Base2 ( Base2 other ) { this.Member = other.Member ; } public override Base2 DeepClone ( ) { return new Base2 ( this ) ; } } sealed class Derived : Base2 { string Member2 { get ; set ; } public Derived ( ) { /* empty on purpose */ } public Derived ( Derived other ) : base ( other ) { this.Member2 = other.Member2 ; } public override Derived DeepClone ( ) { return new Derived ( this ) ; } }
Is it possible to implement the `` virtual constructor '' pattern in C # without casts ?
C_sharp : I 'm trying to update a project which makes heavy use of comparison against SyntaxToken.Kind . This property appears to have disappeared in newer versions of Roslyn and I wondered if there an alternative method or an extension method I could write to get the same functionality ? The code has many references such as : Any ideas ? <code> if ( expression.OperatorToken.Kind == SyntaxKind.PlusEqualsToken )
How to get the SyntaxToken.Kind in current version of Roslyn ?
C_sharp : I am still new to overloading operators . I thought i was doing a great job until i hit this problem . NullReferenceException is thrown on the ! = operator . I assume its using it in the CompareTo method but i 'm not totally sure . If anyone can point me in the right direction i would be very grateful.When i comment out the binaory operators the program functions as intended . My question is how can i protect my binary operators from null references so i can keep them for manual comparisons ? Thank you for your time . <code> using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; List < Task > tasks = new List < Task > ( ) ; tasks.Add ( new Task ( `` first '' , DateTime.Now.AddHours ( 2 ) ) ) ; tasks.Add ( new Task ( `` second '' , DateTime.Now.AddHours ( 4 ) ) ) ; tasks.TrimExcess ( ) ; tasks.Sort ( ) ; } } public class Task : IComparable { public Task ( ) { } public Task ( string nameIn , DateTime dueIn ) { nameOfTask = nameIn ; dateDue = dueIn ; } DateTime dateDue ; string nameOfTask ; public static bool operator < ( Task t1 , Task t2 ) { return ( t1.dateDue < t2.dateDue ) ; } public static bool operator > ( Task t1 , Task t2 ) { return ( t1.dateDue > t2.dateDue ) ; } public static bool operator == ( Task t1 , Task t2 ) { return ( t1.dateDue == t2.dateDue ) ; } public static bool operator ! = ( Task t1 , Task t2 ) { return ( t1.dateDue ! = t2.dateDue ) ; } public override int GetHashCode ( ) { return Int32.Parse ( this.dateDue.ToString ( `` yyyymmddhhmmss '' ) ) ; } public override bool Equals ( System.Object obj ) { if ( obj == null ) return false ; Task t = obj as Task ; if ( ( System.Object ) t == null ) return false ; return ( this.dateDue == t.dateDue ) ; } int IComparable.CompareTo ( object obj ) { if ( obj == null ) return 1 ; Task t = obj as Task ; if ( t ! = null ) { return this.dateDue.CompareTo ( t.dateDue ) ; } else throw new ArgumentException ( `` Object is not a Task '' ) ; } } }
How to properly override equality ?
C_sharp : Consider the following class : This is what the compiler generates ( in a slightly less readable way ) : This way the delegate passed with the first call is initialized once and reused on multiple Test calls.However , the expression tree passed with the second call is not reused - a new lambda expression is initialized on each Test call.Provided it does n't capture anything and expression trees being immutable , what would be the problem with caching the expression tree as well ? EditI think I need to clarify why I think the expression trees are fit to be cached.The resulting expression tree is known at the compilation time ( well , it is created by the compiler ) .They are immutable . So , unlike the array example given by X39 below , an expression tree ca n't be modified after it 's initialized and therefore , is safe to be cached.There can be only so many expression trees in a code-base - Again , I 'm talking about the ones that can be cached , i.e . the ones that are initialized using lambda expressions ( not the ones that are created manually ) without capturing any outside state/variable . Auto-interning of string literals would be a similar example.They are meant to be traversed - They can be compiled to create a delegate , but that 's not their main function . If someone wants a compiled delegate , they can just accept one ( a Func < T > , instead of an Expression < Func < T > > ) . Accepting an expression tree indicates that it 's going to be used as a data structure . So , `` they should be compiled first '' is not a sensible argument against caching of expression trees.What I 'm asking is the potential drawbacks of caching these expression trees . Memory requirements mentioned by svick is a more likely example . <code> class Program { static void Test ( ) { TestDelegate < string , int > ( s = > s.Length ) ; TestExpressionTree < string , int > ( s = > s.Length ) ; } static void TestDelegate < T1 , T2 > ( Func < T1 , T2 > del ) { /* ... */ } static void TestExpressionTree < T1 , T2 > ( Expression < Func < T1 , T2 > > exp ) { /* ... */ } } class Program { static void Test ( ) { // The delegate call : TestDelegate ( Cache.Func ? ? ( Cache.Func = Cache.Instance.FuncImpl ) ) ; // The expression call : var paramExp = Expression.Parameter ( typeof ( string ) , `` s '' ) ; var propExp = Expression.Property ( paramExp , `` Length '' ) ; var lambdaExp = Expression.Lambda < Func < string , int > > ( propExp , paramExp ) ; TestExpressionTree ( lambdaExp ) ; } static void TestDelegate < T1 , T2 > ( Func < T1 , T2 > del ) { /* ... */ } static void TestExpressionTree < T1 , T2 > ( Expression < Func < T1 , T2 > > exp ) { /* ... */ } sealed class Cache { public static readonly Cache Instance = new Cache ( ) ; public static Func < string , int > Func ; internal int FuncImpl ( string s ) = > s.Length ; } }
Why do n't non-capturing expression trees that are initialized using lambda expressions get cached ?
C_sharp : I am working on a library of COM Add-in and Excel Automation Add-in , whose core codes are written in C # . I 'd like to set an optional argument for the function and I know that this is legal for both C # and VBA , and even Excel WorksheetFunction . But I find that finally the optional argument works exclusively for COM and Automation add-in , meaning that if one add-in is run first , then works well but the optional argument of the other one will not work.Below please see the example : In the VS 2013 solution , I have two projects : one is called TestVBA and another one is called TestExcel.TestVBA is for the COM add-in and built through the `` Excel 2013 Add-in '' and there are two .cs files : ThisAddIn.csThis file is generated automatically and modified a little bit . The codes areTestVBA.csThis file is the main calculation file of COM add-in . The codes areAnother TestExcel is for the Excel Automation add-in and built through the C # `` Class Library '' and there are two .cs files either : BaseUDF.csThis file defines the decoration of two attributes . The codes areTestExcel.csThis file is the main calculation file of Excel Automation add-in . The codes areAfter building , the two add-ins have been registered in the system and in Excel we can use them successfully.For the Automation add-in , we call them in the spreadsheet as =TestAddExcel ( 2,3 ) and =TestAddExcel ( ) both of them work very well and give the right result 5 and 2 . However , when I try to call the COM add-in viaThe first call with all arguments existing works well , but for the second one with arguments missing shows the error Type mismatch.The interesting thing is , when I close the test excel file and open it again , this time I test the COM add-in first , still via the above VBA codes , both two calls work very well . Then when I test the two spreadsheet functions which used to work well , only the first one is good , the second one with arguments missing =TestAddExcel ( ) fails with # VALUE ! .It would be very nice if someone can help with this strange issue . <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Xml.Linq ; using Excel = Microsoft.Office.Interop.Excel ; using Office = Microsoft.Office.Core ; using Microsoft.Office.Tools.Excel ; namespace TestVBA { public partial class ThisAddIn { private void ThisAddIn_Startup ( object sender , System.EventArgs e ) { } private void ThisAddIn_Shutdown ( object sender , System.EventArgs e ) { } private ExcelVBA oExcelVBA ; protected override object RequestComAddInAutomationService ( ) { if ( oExcelVBA == null ) { oExcelVBA = new ExcelVBA ( ) ; } return oExcelVBA ; } # region VSTO generated code /// < summary > /// Required method for Designer support - do not modify /// the contents of this method with the code editor . /// < /summary > private void InternalStartup ( ) { this.Startup += new System.EventHandler ( ThisAddIn_Startup ) ; this.Shutdown += new System.EventHandler ( ThisAddIn_Shutdown ) ; } # endregion } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Runtime.InteropServices ; using Excel = Microsoft.Office.Interop.Excel ; using System.Reflection ; namespace TestVBA { [ ComVisible ( true ) ] [ ClassInterface ( ClassInterfaceType.AutoDual ) ] public class ExcelVBA { public int TestAddVBA ( int a = 1 , int b = 1 ) { return a + b ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Runtime.InteropServices ; using Microsoft.Win32 ; namespace BaseUDF { [ ClassInterface ( ClassInterfaceType.AutoDual ) ] [ ComVisible ( true ) ] public abstract class BaseUDF { [ ComRegisterFunctionAttribute ] public static void RegisterFunction ( Type type ) { // Add the `` Programmable '' registry key under CLSID . Registry.ClassesRoot.CreateSubKey ( GetSubKeyName ( type , `` Programmable '' ) ) ; // Register the full path to mscoree.dll which makes Excel happier . RegistryKey key = Registry.ClassesRoot.OpenSubKey ( GetSubKeyName ( type , `` InprocServer32 '' ) , true ) ; key.SetValue ( `` '' , System.Environment.SystemDirectory + @ '' \mscoree.dll '' , RegistryValueKind.String ) ; } [ ComUnregisterFunctionAttribute ] public static void UnregisterFunction ( Type type ) { // Remove the `` Programmable '' registry key under CLSID . Registry.ClassesRoot.DeleteSubKey ( GetSubKeyName ( type , `` Programmable '' ) , false ) ; } private static string GetSubKeyName ( Type type , string subKeyName ) { System.Text.StringBuilder s = new System.Text.StringBuilder ( ) ; s.Append ( @ '' CLSID\ { `` ) ; s.Append ( type.GUID.ToString ( ) .ToUpper ( ) ) ; s.Append ( @ '' } \ '' ) ; s.Append ( subKeyName ) ; return s.ToString ( ) ; } // Hiding these methods from Excel . [ ComVisible ( false ) ] public override string ToString ( ) { return base.ToString ( ) ; } [ ComVisible ( false ) ] public override bool Equals ( object obj ) { return base.Equals ( obj ) ; } [ ComVisible ( false ) ] public override int GetHashCode ( ) { return base.GetHashCode ( ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using Microsoft.Win32 ; using System.Runtime.InteropServices ; using Excel = Microsoft.Office.Interop.Excel ; using Extensibility ; namespace TestExcel { [ Guid ( `` 7127696E-AB87-427a-BC85-AB3CBA301CF3 '' ) ] [ ClassInterface ( ClassInterfaceType.AutoDual ) ] [ ComVisible ( true ) ] public class TestExcel : BaseUDF.BaseUDF { public int TestAddExcel ( int a = 1 , int b = 1 ) { return a + b ; } } } Sub TestVBA_Click ( ) Dim addIn As COMAddInDim TesthObj As ObjectSet addIn = Application.COMAddIns ( `` TestVBA '' ) Set TestObj = addIn.ObjectRange ( `` Output '' ) .Value2 = TestObj.TestAddVBA ( 2 , 3 ) Range ( `` Output '' ) .Offset ( 1 , 0 ) .Value2 = TestObj.TestAddVBA ( ) End Sub
Optional Argument of COM Add-in vs Automation Add-in Written in C #
C_sharp : Possible Duplicates : confused with the scope in c # C # Variable Scoping I am curious about the design considerations behind the scope of variables which are declared in the initialization part of for-loops ( etc ) . Such variables neither seem to be in-scope or out-of scope or am I missing something ? Why is this and when is this desired ? Ie : <code> for ( int i = 0 ; i < 10 ; i++ ) { } i = 12 ; //CS0103 : The name ' i ' does not exist in the current contextint i = 13 ; //CS0136 : A local variable named ' i ' can not be declared in this scope //because it would give a different meaning to ' i ' , which is already //used in a 'child ' scope to denote something else
C # : Definition of the scope of variables declared in the initialization part of for-loops ?
C_sharp : For a project I 'm busy with the Google Adwords api ( client library = C # ) . I show the visitor an estimate of traffic based on keywords and locality/city currently . It 's using following methodhttps : //developers.google.com/adwords/api/docs/guides/traffic-estimator-serviceI want to add an extra requirement : the estimate must contain a proximity ( radius ) of 15 kilometers around locality/city s. I tried to add the proximity to the campaignestimator object , but then an error occured based on the response.Part of the programcodeException : Does anyone know how to solve this ? Do I need another method ? Thanks a lot.Jordy <code> var proximity = new Proximity { radiusDistanceUnits = ProximityDistanceUnits.KILOMETERS , radiusInUnits = seaConfigurationModel.Proximity , geoPoint = new GeoPoint ( ) { latitudeInMicroDegrees = 43633941 , longitudeInMicroDegrees = -79398718 } } ; campaignEstimateRequest.criteria = new Criterion [ ] { languageCriterion , proximity } ; Unmarshalling Error : cvc-elt.4.2 : Can not resolve 'q2 : Proximity ' to a type definition for element 'criteria ' .
How add a radius / proximity around a city for estimating traffic ( Google Adwords ) ?
C_sharp : I 'm trying to create a simple program with MonoGame in Xamarin Studio 4.0.10 ( build 5 ) .But when I try to load some textures using Content.Load method , I receive an exception System.MissingMethodException with a message The actual lines of code I am using are : I did some googling and found out that this happens because of some API changes , which Xamarin Studio have n't yet implemented ( at least that 's what I understood ) . So my question is : How can I fix this problem ? <code> Method not found : 'MonoMac.AppKit.NSImage.AsCGImage ' . protected override void LoadContent ( ) { //some stuff here Texture2D freezeTexts = new Texture2D [ 5 ] ; for ( int i = 0 ; i < 5 ; i++ ) { freezeTexts [ i ] = Content.Load < Texture2D > ( `` freeze '' +i ) ; // exception here } //some other stuff here }
How to fix MissingMethodException during Content.Load < Texture2D > in Xamarin Studio on MacOS X ?
C_sharp : I have a class project a.dll which is compiled in C # . It contains the following code.from a C # project I can call these functions like thisBut how can I call this from a VB.Net Project ? I am not in a position to use Visual Studio right now . So its very helpful if someone will provide an answer.EDIT 1I am having a VB.NET project and I need to add the reference of a C # dll ( say dll contains MyClass ) .So that I can call two methods ( Add ( int , int ) , add ( int , int ) ) . But in VB.NET this is case sensitive . Is there any way to achieve this ? EDIT 2Suppose I added reference to the dll and so I can able to call the functions.If this code works how the compiler identify the correct function ? <code> public class MyClass { public int Add ( int i , int j ) { return ( i+j ) ; } public int add ( int i , int j ) { return ( i+j ) *2 ; } } public class MyOtherClass { MyClass mcls=new MyClass ( ) ; mcls.Add ( 1,2 ) ; mcls.add ( 2.3 ) ; } Dim myObj as New MyClassmyObj.Add ( 1,2 ) myObj.add ( 1,2 )
How to call a function defined in C # with same params , return type and same name but in different case from a VB.NET project
C_sharp : After Windows has updated , some calculated values have changed in the last digit , e.g . from -0.0776529085243926 to -0.0776529085243925 . The change is always down by one and both even and odd numbers are affected . This seems to be related to KB4486153 , as reverting this update changes the values back to the previous ones.This change can be seen already when debugging in Visual Studio and hovering over the variable . The value is later written to an output file and changes therein as well ( without running the debugger ) .Minimal reproducible exampleBackgroundThe calculated value comes from Disregarding the loss of precision in floating-point arithmetic , I can do the calculation in the Immediate window and get -0.07765290852439255 both before and after the upgrade . However , when hovering over the output variable , I see { [ 2011-01-12 00:00:00 , -0.0776529085243926 ] } before the upgrade and { [ 2011-01-12 00:00:00 , -0.0776529085243925 ] } after , and this difference is also propagated to an output file.It seems like the calculated value is the same before and after the update , but its representation is rounded differently.The input values are Target framework is set to .NET Framework 4.6.1QuestionIs there something I can do to get the previous behaviour while keeping the updates ? I know about loss of precision in floating-point calculations , but why does this change happen after an update and how can we guarantee that future updates do n't change the representation of values ? KB4486153 is an update for Microsoft .NET Framework 4.8 , see https : //support.microsoft.com/en-us/help/4486153/microsoft-net-framework-4-8-on-windows-10-version-1709-windows-10-vers <code> var output = -0.07765290852439255 ; Trace.WriteLine ( output ) ; // This printout changes with the update.var dictionary = new Dictionary < int , double > ( ) ; dictionary [ 0 ] = output ; // Hover over dictionary to see the change in debug mode output [ date ] = input [ date ] / input [ previousDate ] - 1 ; { [ 2011-01-11 00:00:00 , 0.983561000400506 ] } { [ 2011-01-12 00:00:00 , 0.907184628008246 ] }
Rounding of last digit changes after Windows .NET update
C_sharp : This is for Project Euler , problem 8.I am trying to foreach through the array of numbers , each time skipping the last number and pulling the next 13 adjacent numbers in the array.My code : The problem I 'm running into is , every time it enumerates through the array , it subtracts the amount that x is , from how many times it goes through the list , which is 13.So when x is 5 , it only goes through the array 8 times.How do I fix it where it traverses 13 numbers at a time ? <code> for ( int x = 0 ; x < 987 ; x++ ) { foreach ( int number in numbers.Take ( 13 ) .Skip ( x ) ) { hold = hold * number ; adjacent [ index ] = number ; index++ ; } if ( hold > product ) { product = hold ; } Array.Clear ( adjacent , 0 , adjacent.Length ) ; index = 0 ; hold = 1 ; }
array.Take ( 13 ) .Skip ( x ) is subtracting the take
C_sharp : We have a WEB API project that recently was moved to a new server . I 'm running my project after making some additions to its ' payload , but it suddenly throws the following error : Unable to cast object of type 'System.Net.Http.Formatting.JsonContractResolver ' to type 'Newtonsoft.Json.Serialization.DefaultContractResolver'.The offending line of code is in global.asax : I believe this code was added because the default output of the API was XML , and we need it to be JSON instead . Highlighting ( DefaultContractResolver ) brings up a tooltip indicating it references NewtonSoft.JSon.Serialization.DefaultContractResolver . Highlighting serializersettings.ContractResolver references IContractResolver JSonSerializerSettings.ContractResolver . The code has been on this machine for some time , and the only thing I can think I changed was installing a newer version of .NET . What could cause this line of code to suddenly throw an error ? And how can I resolve it ? Thanks ! Edit : As per request in the comments , my serialization code consists of something like the following : Edit2 : We 're now running .NET 4.5 . To the best of my knowledge , we ran 4.2 prior , but seeing it 's been a few months , I can not be sure . As per comment by Dominick , I tried changing the cast to DefaultContractResolver to the following : This , however , then ends up in the API returning the following error : { `` Message '' : '' The requested resource does not support http method 'GET ' . '' } <code> protected void Application_Start ( ) { GlobalConfiguration.Configure ( WebApiConfig.Register ) ; var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings ; var contractResolver = ( DefaultContractResolver ) serializerSettings.ContractResolver ; contractResolver.IgnoreSerializableAttribute = true ; } json += `` { \ '' employeename\ '' : \ '' '' + Convert.ToString ( reader [ `` Employee '' ] ) + `` \ '' } , '' ; return JsonConvert.DeserializeObject < OrgChartModel > ( json ) ; var contractResolver = ( IContractResolver ) serializerSettings.ContractResolver ;
`` Unable to cast object of type 'System.Net.Http.Formatting.JsonContractResolver ' to type 'Newtonsoft.Json.Serialization.DefaultContractResolver ' . ''
C_sharp : I have an object o that is known to be a boxed int or uint : I do n't know what 's in the box , all I care about is that there 's 4 bytes in there that I want to coerce to an int or uint . This works fine in an unchecked context when I have values ( instead of boxes ) : Note : By default everything in C # is unchecked , the unchecked context is only necessary here because we are dealing with literals and the compiler wants to know if we really want to shoot ourselves in the foot.The problem is now that I do n't know whats inside the box ( besides it 's 4 bytes ) , but the runtime does so when I try to unbox to the wrong type I get an InvalidCastException . I know this is reasonable runtime behavior , but in this case I know what I 'm doing and want a `` unchecked unbox '' . Does something like that exist ? I know I could catch and retry , so that does n't count as an answer . <code> object o = int.MinValueobject o = ( uint ) int.MinValue // same bytes as above unchecked { int a = ( int ) 0x80000000u ; // will be int.MinValue , the literal is a uint uint b = ( uint ) int.MinValue ; }
Unboxing uint/int without knowing what 's inside the box
C_sharp : I an having Two Lists . I want to get the matched and unmatched values based on ID and add the results to another List . I can get both of these using Intersect/Except . But I can get only ID in the resultant variables ( matches and unmatches ) . I need all the properties in the Template . <code> List < Template > listForTemplate = new List < Template > ( ) ; List < Template1 > listForTemplate1 = new List < Template1 > ( ) ; var matches = listForTemplate .Select ( f = > f.ID ) .Intersect ( listForTemplate1 .Select ( b = > b.ID ) ) ; var ummatches = listForTemplate .Select ( f = > f.ID ) .Except ( listForTemplate1.Select ( b = > b.ID ) ) ; public class Template { public string ID { get ; set ; } public string Name { get ; set ; } public string Age { get ; set ; } public string Place { get ; set ; } public string City { get ; set ; } public string State { get ; set ; } public string Country { get ; set ; } } public class Template1 { public string ID { get ; set ; } }
How to copy a List < > to another List < > with Comparsion in c #
C_sharp : I wanted to mock an entityframwork DbSet using Foq . It goes something like : I tried coercing and casting x to an IQueryable at some places but that does n't work.As you can see here in the docs for DbSet it does implement the IQueryable interface via DbQuery , but does so by `` explicitly '' implementing the properties.Is Moq there is a Function As so you can tell it to treat it as a IQueryable that looks like : <code> let patients = ( [ Patient ( Guid `` 00000000-0000-0000-0000-000000000001 '' ) ; Patient ( Guid `` 00000000-0000-0000-0000-000000000002 '' ) ; Patient ( Guid `` 00000000-0000-0000-0000-000000000003 '' ) ; ] ) .AsQueryable ( ) let mockPatSet = Mock < DbSet < Patient > > .With ( fun x - > < @ // This is where things wrong . x does n't have a property Provider x.Provider -- > patients.Provider @ > ) var mockSet = new Mock < DbSet < Blog > > ( ) ; mockSet.As < IQueryable < Blog > > ( ) .Setup ( m = > m.Provider ) .Returns ( data.Provider ) ;
Mocking a class with an explicitly implemented interface using Foq
C_sharp : I have these extension methods and enum type : The first if below compiles ; the second does not : They only vary by the extra set of parentheses . Why do I have to do this ? At first I suspected it was doing a double implicit cast from bool ? to bool and then back to bool ? , but when I remove the first extension method , it complains there is no implicit cast from bool to bool ? . I then checked the IL and there were no casts . Decompiling back to C # yields something that looks like : which is fine for the version of the CLR I 'm running , and what I expect . What I did n't expect is that x.Y ? .Color.IsOneOf ( Color.Red , Color.Green ) does n't compile.What is going on ? Is it simply the way the language was implemented that it requires the ( ) ? UpdateHere 's a screen cap showing the error in context . This is getting even more confusing to me . The error actually makes sense ; but what does n't ( in my mind now ) is why line 18 would n't have the same problem . <code> public static bool IsOneOf < T > ( this T thing , params T [ ] things ) { return things.Contains ( thing ) ; } public static bool IsOneOf < T > ( this T ? thing , params T [ ] things ) where T : struct { return thing.HasValue & & things.Contains ( thing.Value ) ; } public enum Color { Red , Green , Blue } if ( ( x.Y ? .Color ) .IsOneOf ( Color.Red , Color.Green ) ) ; if ( x.Y ? .Color.IsOneOf ( Color.Red , Color.Green ) ) ; if ( ! ( y ! = null ? new Color ? ( y.Color ) : new Color ? ( ) ) .IsOneOf < Color > ( new Color [ 2 ] { Color.Red , Color.Green } ) ) ;
Why do I have to place ( ) around null-conditional expression to use the correct method overload ?
C_sharp : I 've normally been creating Prism Events used by the EventAggregator like : public class SomeEvent : CompositePresentationEvent < SomeEventArgs > { } But while looking at a co-workers code I noticed they did : I guess my first question is why does this even compile ? It seems to me that it 's implementing a class that is n't defined yet . And second , does it negatively affect the application at all , is it negligible , or better ? <code> public class SomeEventArgs { public string Name { get ; set ; } } public class SomeEvent : CompositePresentationEvent < SomeEvent > { public string Name { get ; set ; } }
Define class with itself as generic implementation . Why/how does this work ?
C_sharp : I am trying to clear all items from a ToolStripDropDownButton.Since they are disposable , I call the dispose method on each of them.But I see that after calling the dispose ( ) method , the IsDisposed property still returns false.Why is that and how can I check if Dispose ( ) is called on any object ? It is not a problem ( I hope ) in my current project , but I would really like to know what is going on here ... my code so far : <code> private void ClearDropDownAccessConnections ( ) { ToolStripItem button = null ; for ( int i = toolStripDropDownButtonAccess.DropDownItems.Count - 1 ; i > 0 ; i -- ) { button = toolStripDropDownButtonAccess.DropDownItems [ i ] as ToolStripItem ; if ( ( button.Tag ! = null ) & & ( ( int ) button.Tag == 10 ) ) { toolStripDropDownButtonAccess.DropDownItems.Remove ( button ) ; button.Dispose ( ) ; //IF I CHECk HERE THEN button.IsDisposed IS STILL FALSE } } }
Why does IsDisposed return false after calling Dispose ( ) ?
C_sharp : I am college student ( computer science ) and have just started a C # programming class.For our assignments I have been using a class called `` Display '' where I put any console output that could be used several times throughout a project . For example , a request to continue or exit program . Instead of typing it out several times in Main ( ) I just call the method from the Display class.Another student in a higher level class has told me that I should not do this . That it is poor coding practice and that I should just include all methods within the primary class ( containing Main ( ) ) and only use other class when absolutely needed.I am just looking for some input and advice.I was asked to include code . I was going to originally , but did n't want to make this post too long . I have chosen one assignment that is fairly short . I want to clarify that I am just learning so the code is not as elegant as many of you can write . Constructive criticism is very much welcome.Ultimately I am just playing with the use of classes . I know that some of the methods in the Display class could just as easily be in Main ( ) .This is the Program class that contains Main ( ) This is the Display classThis is the Request classThat is it . Would this be considered an inefficeint way to code ? How can I improve it ? Thanks for all the input so far . It is very valuable to me . <code> namespace Chapter_6_10 { class Program { static void Main ( ) { string triangle = `` '' , result = `` `` ; ; char printingCharacter = ' ' ; int peakNumber = 0 ; Display.Instructions ( ) ; Display.Continue ( ) ; // perform a do ... while loop to build triangle up to peak do { Console.Clear ( ) ; Request.UserInput ( out printingCharacter , out peakNumber ) ; int counter = 1 , rowCounter = 0 ; do { do { triangle += printingCharacter ; rowCounter++ ; } while ( rowCounter < counter ) ; counter++ ; rowCounter = 0 ; triangle += `` \n '' ; } while ( counter ! = peakNumber ) ; // perform a do ... while loop to build triangle from peak to base do { do { triangle += printingCharacter ; rowCounter++ ; } while ( rowCounter < counter ) ; counter -- ; rowCounter = 0 ; triangle += `` \n '' ; } while ( counter ! = 0 ) ; Console.Clear ( ) ; Console.WriteLine ( triangle ) ; // display triangle Display.DoAgain ( out result ) ; // see if user wants to do another or quit triangle = `` '' ; } while ( result ! = `` q '' ) ; } } namespace Chapter_6_10 { // This class displays various outputs required by programclass Display { // This method display the instructions for the user public static void Instructions ( ) { Console.WriteLine ( `` \nThis program will ask you to enter a character to be used `` + `` to create triangle . '' + `` \nThen you will be asked to enter a number that will represent the '' + `` \ntriangles peak . '' + `` \nAfter your values have been received a triangle will be drawn . `` ) ; } // This method displays the choice to continue public static void Continue ( ) { Console.WriteLine ( `` \n\nPress the enter key when you are ready to continue ... '' ) ; Console.ReadLine ( ) ; } // This method displays an error message public static void Error ( string ErrorType ) { Console.WriteLine ( `` \nYou have entered \ '' { 0 } \ '' , which is a value that is not valid ! '' + `` \nThis is not rocket science . '' + `` \n\nTry agian ... '' , ErrorType ) ; } // This method will ask user to press enter to do again or ' q ' to quit public static void DoAgain ( out string Result ) { string input = `` `` ; Console.WriteLine ( `` \nPress enter to run program again '' + `` \nor type the letter ' q ' to close the application . `` ) ; input = Console.ReadLine ( ) ; // convert input to lowercase so that only one test needed Result = input.ToLower ( ) ; } } namespace Chapter_6_10 { // This class is used to get user inputclass Request { public static void UserInput ( out char PrintingCharacter , out int PeakNumber ) { string input = `` `` ; char testCharacter = ' ' ; int testNumber = 0 ; // a do ... while loop to get Printing Character from user // use TryParse ( ) to test for correct input format do { Console.Write ( `` \nPlease enter a character to be used to build triangle : `` ) ; input = Console.ReadLine ( ) ; bool result = char.TryParse ( input , out testCharacter ) ; if ( result ) { } else { Console.Clear ( ) ; Display.Error ( input ) ; input = `` `` ; } } while ( input == `` `` ) ; // a do ... while loop to get number from user // use TryParse ( ) to test for correct input format do { Console.Write ( `` \nPlease enter a number < between 1 and 10 > for the peak of the triangle : `` ) ; input = Console.ReadLine ( ) ; bool result = int.TryParse ( input , out testNumber ) ; if ( result ) { if ( ( testNumber > 0 ) & & ( testNumber < 11 ) ) { } else { Console.Clear ( ) ; Display.Error ( testNumber.ToString ( ) ) ; input = `` `` ; } } else { Console.Clear ( ) ; Display.Error ( input ) ; input = `` `` ; } } while ( input == `` `` ) ; // assigned received values to 'outs ' of method PrintingCharacter = testCharacter ; PeakNumber = testNumber ; } }
correct use of classes ?
C_sharp : I 'm downloading an Excel file ( dynamically created in a Winforms app and saved to a database ) in a Web API project using this method : This works just fine ( except that there is no downloading action visible , such as the file 's icon dropping to the taskbar , as is normally the case when downloading files from the Internet - the file simply winds up in the location indicated ) .My assumption is that this only works because I am running the ASP.NET Web API project locally and so my file system is considered `` fair game '' for writing.How can I accomplish the same thing ( preferably with the visible downloading heretofore mentioned ) on any remote user 's machine ( obviously , I ca n't just place the file anywhere , not only for security reasons , but also because I do n't know which folders they might have ) ? UPDATEI was going to try this : ... adapted from here , but none of those properties or methods are part of HttpResponseMessage 's milieau . I even tried a raw `` Response.Buffer '' in place of `` httprm.Buffer '' , hoping the undeclared `` Response '' object ( not declared in the sample code , either ) would at least afford me resolvability , but no such serendipity shone on me.UPDATE 2I am going to bountify the accepted answer ASAP ; it was one of the most helpful ones I 've ever gotten . I combined that wisdom with other bits and pieces to compile ( no pun intended ) a tip that shows how to save Excel data and then read it out again from a Web API app and download it here . <code> [ Route ( `` api/deliveryperformance/ { unit } / { begindate } / { enddate } '' ) ] public HttpResponseMessage Get ( string unit , string begindate , string enddate ) { // adapted the first part of this code from http : //stackoverflow.com/questions/11176066/how-do-i-insert-retrieve-excel-files-to-varbinarymax-column-in-sql-server-2008 byte [ ] excelContents ; string selectStmt = `` SELECT BinaryData FROM ReportsGenerated WHERE FileBaseName = @ fileBaseName '' ; string fbn = string.Format ( `` deliveryperformance/ { 0 } / { 1 } / { 2 } '' , unit , begindate , enddate ) ; using ( SqlConnection connection = new SqlConnection ( ProActWebReportsConstsAndUtils.CPSConnStr ) ) using ( SqlCommand cmdSelect = new SqlCommand ( selectStmt , connection ) ) { cmdSelect.Parameters.Add ( `` @ fileBaseName '' , SqlDbType.VarChar ) .Value = fbn ; connection.Open ( ) ; excelContents = ( byte [ ] ) cmdSelect.ExecuteScalar ( ) ; connection.Close ( ) ; } string excelFileName = `` C : \\Misc\\TestFile2.xlsx '' ; File.WriteAllBytes ( excelFileName , excelContents ) ; String HtmlToDisplay = GetDownloadSuccessMessage ( excelFileName ) ; return new HttpResponseMessage ( ) { Content = new StringContent ( HtmlToDisplay , Encoding.UTF8 , `` text/html '' ) } ; } internal static string GetDownloadSuccessMessage ( string excelFileName ) { return string.Format ( `` < h1 > Excel spreadsheed downloaded to { 0 } < /h1 > '' , excelFileName ) ; } HttpResponseMessage httprm = new HttpResponseMessage ( ) ; httprm.Buffer = true ; httprm.Charset = `` '' ; httprm.Cache.SetCacheability ( HttpCacheability.NoCache ) ; httprm.ContentType = `` application/vnd.ms-excel '' ; httprm.AddHeader ( `` content-disposition '' , `` attachment ; filename=\ '' Funk49.xlsx\ '' '' ) ; httprm.BinaryWrite ( bytes ) ; httprm.Flush ( ) ; httprm.End ( ) ;
How can I download a file to a remote machine the same or similarly to how I 'm doing it to my own machine ?
C_sharp : how can i optimized this code ? i dont like to have case statement , is there a way i can improve this code ? <code> protected void ddlFilterResultBy_SelectedIndexChanged ( object sender , EventArgs e ) { string selVal = ddlFilterResultBy.SelectedValue.ToString ( ) .ToLower ( ) ; switch ( selVal ) { case `` date '' : pnlDate.Visible = true ; pnlSubject.Visible = false ; pnlofficer.Visible = false ; pnlCIA.Visible = false ; pnlMedia.Visible = false ; pnlStatus.Visible = false ; break ; case `` subject '' : pnlDate.Visible = false ; pnlSubject.Visible = true ; pnlofficer.Visible = false ; pnlCIA.Visible = false ; pnlMedia.Visible = false ; pnlStatus.Visible = false ; break ; case `` officer '' : pnlDate.Visible = false ; pnlSubject.Visible = false ; pnlofficer.Visible = true ; pnlCIA.Visible = false ; pnlMedia.Visible = false ; pnlStatus.Visible = false ; break ; case `` status '' : pnlDate.Visible = false ; pnlSubject.Visible = false ; pnlofficer.Visible = false ; pnlCIA.Visible = false ; pnlMedia.Visible = false ; pnlStatus.Visible = true ; break ; default : pnlDate.Visible = false ; pnlSubject.Visible = false ; pnlofficer.Visible = false ; pnlCIA.Visible = false ; pnlMedia.Visible = false ; pnlStatus.Visible = false ; break ; } }
how can i make this code more optimized
C_sharp : What would be the best way to override the GetHashCode function for the case , whenmy objects are considered equal if there is at least ONE field match in them.In the case of generic Equals method the example might look like this : Still , I 'm confused about making a good GetHashCode implementation for this case.How should this be done ? Thank you . <code> public bool Equals ( Whatever other ) { if ( ReferenceEquals ( null , other ) ) return false ; if ( ReferenceEquals ( this , other ) ) return true ; // Considering that the values ca n't be 'null ' here . return other.Id.Equals ( Id ) || Equals ( other.Money , Money ) || Equals ( other.Code , Code ) ; }
C # GetHashCode question
C_sharp : With Moq , it is possible to verify that a method is never called with certain arguments ( that is , arguments satisfying certain predicates ) using Times.Never.But how to verify that , no mater how many times a method is called , it is always called with certain arguments ? The default appears to be Times.AtLeastOnce.There is no Times.Always . Am I missing something obvious ? Thanks ! Edit : I posted a suggestion to the Moq mailing list last week , but it does n't look like it 's been moderated yet . I 'll post any updates here.Edit : an example . Say I am testing a class which generates XML documents . I want to ensure that only valid documents are generated . In other words , test that the writer dependency is only ever given valid documents , with a valid sequence number , to write . <code> should_only_write_valid_xml_documentsMock.Get ( this.writer ) .Verify ( w = > w.Write ( It.Is < XDocument > ( doc = > XsdValidator.IsValid ( doc ) ) , It.Is < int > ( n = > n < 3 ) ) , Times.Always ) ;
Why is n't there a Times.Always in Moq ?
C_sharp : I thought it would be a good idea to use CancellationToken in my controller like so : The issue is that now Azure Application Insights shows a bunch of exceptions of type System.Threading.Tasks.TaskCancelledException : A Task was canceled . as well as the occasional Npgsql.PostgresException : 57014 : canceling statement due to user request . This is noise that I do n't need.Application Insights is registered as a service using the standard method - services.AddApplicationInsightsTelemetry ( Configuration ) ; .Attempted SolutionI thought I could jack into the application pipeline and catch the above Exceptions , converting them to normal Responses . I put the code below in various places . It catches any exceptions and if IsCancellationRequested , it returns a dummy response . Otherwise it rethrows the caught exception.This code works in that it changes the response . However exceptions are still getting sent to Application Insights.RequirementsI would like to have a solution that uses RequestAborted.IsCancellationRequested over trying to catch specific exceptions . The reason being that if I 've already discovered one implementation that throws an exception not derived from OperationCanceledException the possibility exists there are others that will do the same.It does n't matter if dependency failures still get logged , just that the exceptions thrown as a result of the request getting canceled don't.I do n't want to have a try/catch in every controller method . It needs to be put in place in one spot.ConclusionI wish I understood Application Insights mechanism of reporting exceptions . After experimenting I feel like trying to catch errors in the Application pipeline is n't the correct approach . I just do n't know what is . <code> [ HttpGet ( `` things '' , Name = `` GetSomething '' ) ] public async Task < ActionResult > GetSomethingAsync ( CancellationToken ct ) { var result = await someSvc.LoadSomethingAsync ( ct ) ; return Ok ( result ) ; } app.Use ( async ( ctx , next ) = > { try { await next ( ) ; } catch ( Exception ex ) { if ( ctx.RequestAborted.IsCancellationRequested ) { ctx.Response.StatusCode = StatusCodes.Status418ImATeapot ; } else { throw ; } } } ) ;
Stop Exception generated by CancellationToken from getting Reported by ApplicationInsights
C_sharp : I 've just started with AutoMapper in C # . I 've succesfully created a mapping like this : I 've also found a way to add some logic to specific properties , like formatting a date ( in InputTypeA ) to a string in a specific format ( in OutputTypeA ) .Now I need to do the same for a number of float properties , but I 'm wondering if there is a short/easy way to do this , except copying a piece of code like the one above for every property that needs to follow this rule.I 've found that I can create a new map like this for mapping floats to strings : This works , but is too generic , because I also have a mapping for another type ( let 's call it InputTypeB ) , that also contains float properties , which need to be treated differently . How can I make the float-to-string mapping part of the first mapping only ? <code> Mapper.CreateMap < InputTypeA , OutputTypeA > ( ) .ForMember ( dest = > dest.MyDateProperty , opt = > opt.ResolveUsing ( src = > String.Format ( `` { 0 : yyyy-MM-dd } '' , src.MyDateProperty ) ) ) ; Mapper.CreateMap < float , string > ( ) .ConvertUsing ( src = > String.Format ( CultureInfo.InvariantCulture.NumberFormat , `` { 0:0.00 } '' , src ) ) ; Mapper.CreateMap < InputTypeB , OutputTypeB > ( )
Special treatment for float properties in some but not all AutoMapper mappings
C_sharp : Earlier today , as I was coding a method and it struck me that I was n't sure exactly why the idiom I was implementing compiles . If everything else is abstracted away , it would look something like this : You have an explicitly infinite loop , and some set of conditions inside the loop that cause the loop to end with a return statement . Let 's ignore for the time being why I was doing this as opposed to checking for a termination condition in the while clause as the answer is convoluted and irrelevant -- what I want to know is why the compiler does n't flag this with a `` Not all paths return a value . '' error , as , strictly speaking not all paths do return a value . The case in which the while loop is never entered ( which , of course , never happens ) does n't return anything.Now , there are two reasons I can imagine it happening : this is a side effect of optimization that 's occurring for other reasons , or this case is explicitly being handled by the compiler to allow this idiom . My instinct is that it 's probably the first case . It does n't surprise me at all , for instance , that this compiles : Because the compiler sees a constant true in the if , and optimizes the conditional away . I do n't really get why this would `` fix '' the first example , though . Oh , and even more weirdly , if some optimization that gets rid of the loop is in play , this compiles : I would think that the entire inner loop would be optimized away , getting rid of all of the valid returns . What 's actually going on here at the bytecode/compiler level that makes this all make sense ? <code> private int Example ( ) { while ( true ) { if ( some condition ) { return 1 ; } } } private int Example2 ( ) { if ( true ) return 1 ; } private int Example3 ( ) { while ( true ) { if ( false ) { return 1 ; } } }
Are explicitly Infinite Loops handled in .NET as a special case ?
C_sharp : I know that multiple objects of same type can be used inside a using clause.Cant i use different types of objects inside the using clause ? Well i tried but although they were different names and different objects , they acted the same = had the same set of methodsIs there any other way to use the using class with different types ? If not , what is the most appropriate way to use it ? <code> using ( Font font3 = new Font ( `` Arial '' , 10.0f ) , font4 = new Font ( `` Arial '' , 10.0f ) ) { // Use font3 and font4 . }
Can i have different type of objects in a C # *using* block ?
C_sharp : What 's the easiest/straight-forward way of setting a default value for a C # public property ? // how do I set a default for this ? Please do n't suggest that I use a private property & implement the get/set public properties . Trying to keep this concise , and do n't want to get into an argument about why that 's so much better . Thanks . <code> public string MyProperty { get ; set ; }
C # Automatic Properties -- setting defaults
C_sharp : When I am invoking a number of methods to a Dispatcher , say the Dispatcher of the UI Thread , like herewill those methods be executed in the same order as I have invoked them ? <code> uiDispatcher.BeginInvoke ( new Action ( insert_ ) , DispatcherPriority.Normal ) ; uiDispatcher.BeginInvoke ( new Action ( add_ ) , DispatcherPriority.Normal ) ; uiDispatcher.BeginInvoke ( new Action ( insert_ ) , DispatcherPriority.Normal ) ;
Execution order of asynchronously invoked methods
C_sharp : The definition System.Linq.ILookUp readsSince IEnumerable is covariant in IGrouping < TKey , TElement > , IGrouping < TKey , TElement > is covariant in TElement and the interface only exposes TElement as a return type , I would assume that ILookup is also covariant in TElement . Indeed , the definitioncompiles without problems.So , what might be the reason why the out keyword is missing in the original definition ? Might it be added future versions of Linq ? <code> interface ILookup < TKey , TElement > : IEnumerable < IGrouping < TKey , TElement > > , IEnumerable { int Count { get ; } IEnumerable < TElement > this [ TKey key ] { get ; } bool Contains ( TKey key ) ; } interface IMyLookup < TKey , out TElement > : IEnumerable < IGrouping < TKey , TElement > > , IEnumerable { int Count { get ; } IEnumerable < TElement > this [ TKey key ] { get ; } bool Contains ( TKey key ) ; }
Should n't ILookup < TKey , TElement > be ( declared ) covariant in TElement ?
C_sharp : I have a problem where I want a group type to be strongly typed but if I do it does n't group correctly . See the code below ... The output : I would expect the result to be the same regardless of using an explicit type nor not i.e . should only be one group with 3 items not 3 groups with 1 item . What is going on here ? UpdateI added an IEqualityComparer and it works now ! See below : Output : This pretty much confirms the answer given by JaredPar ! <code> using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication35 { class Program { static void Main ( string [ ] args ) { List < Foo > foos = new List < Foo > ( ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; var groups = foos.GroupBy < Foo , dynamic > ( entry = > new { GroupKey = entry.Key } ) ; Console.WriteLine ( groups.Count ( ) ) ; groups = foos.GroupBy < Foo , dynamic > ( entry = > new GroupingKey ( ) { GroupKey = entry.Key } ) ; Console.WriteLine ( groups.Count ( ) ) ; } public class Foo { public string Key { get ; set ; } } public class GroupingKey { public string GroupKey { get ; set ; } } } } 13Press any key to continue . . . using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication35 { class Program { static void Main ( string [ ] args ) { List < Foo > foos = new List < Foo > ( ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; foos.Add ( new Foo ( ) { Key = `` Test '' } ) ; var groups = foos.GroupBy < Foo , dynamic > ( entry = > new //GroupingKey ( ) { GroupKey = entry.Key } ) ; Console.WriteLine ( groups.Count ( ) ) ; groups = foos.GroupBy < Foo , GroupingKey > ( entry = > new GroupingKey ( ) { GroupKey = entry.Key } , new GroupingKeyEqualityComparer ( ) ) ; Console.WriteLine ( groups.Count ( ) ) ; } public class Foo { public string Key { get ; set ; } } public class GroupingKey { public string GroupKey { get ; set ; } } public class GroupingKeyEqualityComparer : IEqualityComparer < GroupingKey > { # region IEqualityComparer < GroupingKey > Members public bool Equals ( GroupingKey x , GroupingKey y ) { return x.GroupKey == y.GroupKey ; } public int GetHashCode ( GroupingKey obj ) { return obj.GroupKey.GetHashCode ( ) ; } # endregion } } } 11Press any key to continue . . .
Why does using anonymous type work and using an explicit type not in a GroupBy ?
C_sharp : I have used the three fields in the program and got the difference in usage but I am little confused where does these fields are getting stored ? either in data segment ( stack or heap ? ) or code segment ? in ILDASM the the fields are described as the followingfor static : .field private static int32 afor constant : .field private static literal int32 b = int32 ( 0x000004D3 ) for readonly : .field private initonly int32 c <code> static int a ; const int b=1235 ; readonly int c ;
Where does the memory is allocated for static , constant and readonly fields ?
C_sharp : Using WindowsForms technology , I 'm trying to copy a file that is locally stored on the hard drive ( C : \ ) to a folder stored on a connected smartphone device via USB.The folder `` path '' is represented using friendly names as MyPCName\MyName\Card\Android in the Explorer navigation bar , and as : : { 20D04FE0-3AEA-1069-A2D8-08002B30309D } \\\ ? \usb # vid_04e8 & pid_6860 & ms_comp_mtp & samsung_android # 6 & 612ff8b & 1 & 0000 # { 6ac27878-a6fa-4155-ba85-f98f491d4f33 } \SID- { 20002 , SECZ9519043CHOHB01,31426543616 } \ { 01A00139-011B-0124-3301-29011C013501 } internally in Windows . I obtained that `` internal path '' by using the COM Shell.BrowseForFolder method then checking the FolderItem.Path property of the returned object.Then after getting the path I tried both the CopyFile and CopyFileEx Win32 functions to copy the file but they did n't work . They seemed to be unable to recognize the directory path.The syntax I used was like this : In that code the CopyFile ( ) function returns False and the Marshal.GetLastWin32Error ( ) function returns a 0x3 Win32 error code . The CopyFile/CopyFileEx definitions I used were the same as those published on the Pinvoke.net website ( C # versions ) : http : //www.pinvoke.net/default.aspx/kernel32/CopyFile.htmlhttp : //www.pinvoke.net/default.aspx/kernel32.copyfileexIf a user can copy the file just dragging it from an Explorer instance to the smartphone directory , then I think it is obvious that this can be reproduced programmatically just finding and using the same Win32 functions that Windows uses itself to perform that kind of copy operation from the UI side . Then what am I doing wrong ? Why can CopyFile/CopyFileEx not copy the file ? And how can I copy it ? Note that I 'm looking for a solution written in C # or else VB.NET that can be solved just using managed code or else employing unmanaged code P/Invoking the Win32 functions , except the usage of COM libraries like the Shell COM objects ( that provides a CopyHere ( ) method ) . I would like to learn and to understand how I could do this kind of file copy operation using the Win32 API members . <code> Dim dirPath As String = `` : : { 20D04FE0-3AEA-1069-A2D8-08002B30309D } \\\ ? \usb # vid_04e8 & pid_6860 & ms_comp_mtp & samsung_android # 6 & 612ff8b & 1 & 0000 # { 6ac27878-a6fa-4155-ba85-f98f491d4f33 } \SID- { 20002 , SECZ9519043CHOHB01,31426543616 } \ { 01A00139-011B-0124-3301-29011C013501 } '' NativeMethods.CopyFile ( `` C : \MyFile.ext '' , dirPath & `` \MyFile.ext '' , failIfExists : =True )
Which Win32 function must I use to copy a file to a smartphone folder ?
C_sharp : C # 5.0 Language Specification 7.6.10.2 Object initializers states that A member initializer that specifies an object initializer after the equals sign is a nested object initializer , i.e . an initialization of an embedded object . Instead of assigning a new value to the field or property , the assignments in the nested object initializer are treated as assignments to members of the field or property . Nested object initializers can not be applied to properties with a value type , or to read-only fields with a value type.While I understand read-only fields can not be modified by the initializers after the constructor is run , I do not have a clue about the restriction on properties.The following is a code sample I used to test this restriction on properties : I commented on the code where it was supposed to generate a compiler error based on the specification . But it compiles successfully . What am I missing here ? Thanks <code> using System ; namespace ObjectCollectionInitializerExample { struct MemberStruct { public int field1 ; public double field2 ; } class ContainingClass { int field ; MemberStruct ms ; public int Field { get { return field ; } set { field = value ; } } public MemberStruct MS { get { return ms ; } set { ms = value ; } } } class Program { static void Main ( string [ ] args ) { // Nested object initializer applied to a property of value type compiles ! ContainingClass cc = new ContainingClass { Field = 1 , MS = new MemberStruct { field1 = 1 , field2 = 1.2 } } ; Console.ReadKey ( ) ; } } }
C # nested object initializer