text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : Entity Framework Core introduced the methods HasServiceTier and HasPerformanceLevel to change the edition of an Azure SQL server . You can use them in OnModelCreating like this : If you use Add-Migration Add-Migration you get a migration like this : This seems to work fine but when I try to apply this migration to a local non-Azure DB for development purposes I get the following error : I assume the commands are not valid for non-Azure DBs . So the question is : How can I prevent these commands to be executed on non-Azure DBs ? <code> protected override void OnModelCreating ( ModelBuilder modelBuilder ) { base.OnModelCreating ( modelBuilder ) ; modelBuilder.HasServiceTier ( `` Basic '' ) ; modelBuilder.HasPerformanceLevel ( `` Basic '' ) ; } public partial class ChangedDatabaseServiceTierToBasic : Migration { protected override void Up ( MigrationBuilder migrationBuilder ) { migrationBuilder.AlterDatabase ( ) .Annotation ( `` SqlServer : EditionOptions '' , `` EDITION = 'Basic ' , SERVICE_OBJECTIVE = 'Basic ' '' ) ; } protected override void Down ( MigrationBuilder migrationBuilder ) { migrationBuilder.AlterDatabase ( ) .OldAnnotation ( `` SqlServer : EditionOptions '' , `` EDITION = 'Basic ' , SERVICE_OBJECTIVE = 'Basic ' '' ) ; } } Microsoft.EntityFrameworkCore.Migrations [ 20402 ] Applying migration '20200413102908_ChangedDatabaseServiceTierToBasic'.Applying migration '20200413102908_ChangedDatabaseServiceTierToBasic'.fail : Microsoft.EntityFrameworkCore.Database.Command [ 20102 ] Failed executing DbCommand ( 3ms ) [ Parameters= [ ] , CommandType='Text ' , CommandTimeout='30 ' ] BEGIN DECLARE @ db_name NVARCHAR ( MAX ) = DB_NAME ( ) ; EXEC ( N'ALTER DATABASE ' + @ db_name + ' MODIFY ( EDITION = `` Basic '' , SERVICE_OBJECTIVE = `` Basic '' ) ; ' ) ; ENDFailed executing DbCommand ( 3ms ) [ Parameters= [ ] , CommandType='Text ' , CommandTimeout='30 ' ] BEGINDECLARE @ db_name NVARCHAR ( MAX ) = DB_NAME ( ) ; EXEC ( N'ALTER DATABASE ' + @ db_name + ' MODIFY ( EDITION = `` Basic '' , SERVICE_OBJECTIVE = `` Basic '' ) ; ' ) ; ENDMicrosoft.Data.SqlClient.SqlException ( 0x80131904 ) : Incorrect syntax near '. ' . at Microsoft.Data.SqlClient.SqlConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) at Microsoft.Data.SqlClient.TdsParser.TryRun ( RunBehavior runBehavior , SqlCommand cmdHandler , SqlDataReader dataStream , BulkCopySimpleResultSet bulkCopyHandler , TdsParserStateObject stateObj , Boolean & dataReady ) at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds ( String methodName , Boolean isAsync , Int32 timeout , Boolean asyncWrite ) at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery ( TaskCompletionSource ` 1 completion , Boolean sendToPipe , Int32 timeout , Boolean & usedCache , Boolean asyncWrite , Boolean inRetry , String methodName ) at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery ( ) at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery ( RelationalCommandParameterObject parameterObject ) at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery ( IRelationalConnection connection , IReadOnlyDictionary ` 2 parameterValues ) at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery ( IEnumerable ` 1 migrationCommands , IRelationalConnection connection ) at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate ( String targetMigration ) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase ( String targetMigration , String contextType ) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl ( String targetMigration , String contextType ) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase. < > c__DisplayClass0_0. < .ctor > b__0 ( ) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute ( Action action ) ClientConnectionId : d9f92b81-9916-48ee-9686-6d0f567ab86fError Number:102 , State:1 , Class:15Incorrect syntax near ' . ' .
Specify Azure SQL server edition in EF Core without breaking local development
C_sharp : I have the exact situation described in this question : Device Hub communication with printer queueDue to the question having neither an accepted , nor an acceptable answer , I am asking the question again.I have configured DeviceHub with Acumatica , and my printer is shown . I am sending the print job via a PXAction . Upon executing the action , DeviceHub logs the successful reception of the job , but the printer queue never receives it.Here 's my code , because this is StackOverflow : Could someone point me in a helpful direction ? EDIT : Upon further testing , I found the following : Acumatica will print successfully to my DeviceHub printer using the built in printing processes . However , when printing one of those jobs , the DeviceHub logs show a POLL event . When attempting to print from my code , DeviceHub records an NT event , which never makes it to the printer queue.Upon further testing , in 2019 R1 the logs have changed slightly . Printing Invoices from Acumatica results in an NT event as well . However , there is one line different from a job created in Acumatica versus a job created in code.Green = job from AcumaticaOrange = job from codeThe line Printer DYMOLABEL - printing PDF to \\*printer* is missing in the job sent from code . <code> public PXAction < PX.Objects.CR.BAccount > PrintAddressLabel ; [ PXButton ( CommitChanges=true ) ] [ PXUIField ( DisplayName = `` Print Label '' ) ] protected void printAddressLabel ( ) { BAccount baccount = Base.Caches [ typeof ( BAccount ) ] .Current as BAccount ; string bAccountID = baccount.BAccountID.ToString ( ) ; Dictionary < string , string > parameters = new Dictionary < string , string > ( ) ; parameters [ `` BAccountID '' ] = bAccountID ; PXReportRequiredException ex = null ; ex = PXReportRequiredException.CombineReport ( ex , `` ZRCRADDR '' , parameters ) ; SMPrintJobMaint.CreatePrintJobGroup ( `` DYMOLABEL '' , ex , `` Address Label '' ) ; }
Printer fails to receive job from DeviceHub
C_sharp : I have the following ActionLink : yet when I hover over the link , the url displayed in the browser is http : //localhost:44334/Upload . Where is the controller in this url ? Strangely , clicking the url takes me to my File/Upload view , and yet stranger , the url displayed in the browser 's address bar is https : //localhost:44334/Upload.The ActionLink is on page Home/Explorer , so AFAIK a controller name is normally necessary.Why is the ActionLink helper leaving out the controller name , and why is the link still working ? I have tried refreshing the page with cache clearing , with no difference . I do n't know what else do besides leave it alone because it works , but I 'm concerned this is some quirk and it will no longer work when I deploy my site.My routing is still standard , out-of-box , in the Startup class 's Configure method : Strangely enough , I have now added a Download link each row of an HTML table of files , looking like this : and this link also renders without the controller name , e.g : <code> @ Html.ActionLink ( `` Upload '' , `` Upload '' , `` File '' ) app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ; @ Html.ActionLink ( `` Download '' , `` Download '' , `` File '' , new { filePath = file.Path } ) https : //localhost/Download ? filePath= ... .
I 'm seeing strange ActionLink behaviour , why is the url displayed in the browser not displaying the seemingly correct controller ?
C_sharp : I have the feeling I 'm not looking at this issue from the right angle here , and I 'm just not thinking of other solution.Assuming this generic class ; It is used to define `` ports '' in a graph-node editor . A port can transfer a object/value from one node to another , but they also need to be `` type-safe '' , which means I can not plug any port to another of the wrong type ( at least not without some conversion ) .The node `` owns '' a port and give it a delegate towards one of its method so when another node `` pull '' on a value , the port simply invokes it and returns the proper value.My issue starts when I 'm trying to call Pull ( ) from a non-generic collection . Obviously , I could make a non-generic base method , but then Pull could not return T , it would need to return object . Also , each nodes have collection accessors for their ports so the other items can get them . That collect has to be non-generic because a node can have many ports of many type . The moment the non-generic type get into play , everything generic become inaccessible . If only Port < > [ ] would be a thing.I 'm feeling like I 'm missing something ... <code> public abstract class Port < T > { public delegate T PullDelegate ( ) ; private PullDelegate pull ; public Port ( PullDelegate pull ) { this.pull = pull ; } public T Pull ( ) { return pull ( ) ; } } public abstract Port [ ] Inputs { get ; } public abstract Port [ ] Outputs { get ; } public abstract Port [ ] Entries { get ; } public abstract Port [ ] Exits { get ; }
Invoking generic method/delegate from a non-generic base class
C_sharp : I need some help . I am creating a SelectItem class like this : I would like the following code to be validInstead of having to do this : How can I accomplish this ? <code> public class SelectItem < T > where T : class { public bool IsChecked { get ; set ; } public T Item { get ; set ; } } SelectItem < String > obj = new SelectItem < String > { Item = `` Value '' } ; obj.IsChecked = true ; String objValue = obj ; String objValue = obj.Item ;
Implicit operator ?
C_sharp : I hit a bizarre problem earlier which I have replicated in a new console application . I wonder , can anyone explain why this occurs ? You get an error on the DoSomething line : Error 1 The call is ambiguous between the following methods or properties : 'DoSomething ( int ? ) ' and 'DoSomething ( MyEnum ) ' However if you change the zero to any other number , there is no such problem . <code> static void Main ( string [ ] args ) { DoSomething ( 0 ) ; Console.Read ( ) ; } public static void DoSomething ( int ? value ) { Console.WriteLine ( `` Do Something int ? called '' ) ; } public static void DoSomething ( MyEnum value ) { Console.WriteLine ( `` Do Something MyEnum called '' ) ; } public static enum MyEnum : int { test } }
Can anyone explain this interesting C # problem ?
C_sharp : Imagine the code above being used in the following case : It looks like it 's perfectly safe to inline y , but it 's actually not . This inconsistency in the language itself is counter-intuitive and is plain dangerous . Most programmers would simply inline y , but you 'd actually end up with an integer overflow bug . In fact , if you write code such as the above , you 'd easily have the next person working on the same piece of code inline y without even thinking twice.I argue that this is a very counter-productive language design issue of C # .First question , where is this behaviour defined in the C # specs and why was it designed this way ? Second question , 1.GetType ( ) / ( -1 ) .GetType ( ) gives System.Int32 . Why then is it behaving differently to const int y=-1 ? Third question , if it implicitly gets converted to uint , then how do we explicitly tell the compiler it 's a signed integer ( 1i is n't a valid syntax ! ) ? Last question , this ca n't be a desired behaviour intended by the language design team ( Eric Lippert to chime in ? ) , can it ? <code> using System ; public class Tester { public static void Main ( ) { const uint x=1u ; const int y=-1 ; Console.WriteLine ( ( x+y ) .GetType ( ) ) ; // Let 's refactor and inline y ... oops ! Console.WriteLine ( ( x-1 ) .GetType ( ) ) ; } } public long Foo ( uint x ) { const int y = -1 ; var ptr = anIntPtr.ToInt64 ( ) + ( x + y ) * 4096 ; return ptr ; }
Integral type promotion inconsistency
C_sharp : BackgroundOur site is a press site and is viewed by many people around the globe . Obviously this means that we will be localising the site in as many languages as possible . A professional translator will be hired for each language.How our site works currentlyThe way we have planned to do this is by storing a translation for each element of the page in the database linked by a Guid . So when the page loads the strings are pulled out of the database using the Guid and the language preferences of the user.We have several documents in our project that contain english translations . Such as this : Everytime we create a page we make sure the buttons use these Tokens instead of manually writing the text . So if we decide we need a new button we will add a new token in the file below and when the site is run for the first time it will check if it exists in the database and if not it will be created.So when it comes to the translating we will send these tokens off to the translators and they will change the text only . This will then be added into the site in the relevant language and the page will call the correct translation dependant on the language selected.Problem/QuestionOur translation tokens have the default text as strings , but I 'm concerned that the server has to load all of these text strings into memory at start up . They 're actually only ever used to store the translation in the db and never otherwise used in code , so I believe it might be a bit wasteful . Instead I believe we could call these translations separately when required , perhaps from some kind of look-up table that 's not in-memory.So the question is . Is the way we are currently doing this going to cause performance issues ? If so can anyone suggest any better solutions ? In total there are 1000 's of these tokens in our site.Google has not been very helpful to me on this occasion so any advice would be much appreciated . I have tried as hard as i can to word this so that it makes sense . Its not an easy one to explain.Thanks in advance for any help people can provide . <code> public class StandardButtonToken : LocalisationToken { protected StandardButtonToken ( string defaultText , Guid key ) : base ( defaultText , key ) { } public static readonly LocalisationToken Update = new StandardButtonToken ( `` Update '' , Guid.Parse ( `` 8a999f5b-7ca1-466d-93ca-377321e6de00 '' ) ) ; public static readonly LocalisationToken Go = new StandardButtonToken ( `` Go '' , Guid.Parse ( `` 7a013ecc-0772-4f87-9f1f-da6a878a3c99 '' ) ) ; public static readonly LocalisationToken Edit = new StandardButtonToken ( `` Edit '' , Guid.Parse ( `` c31be427-5016-475d-997a-96fa5ff8b51f '' ) ) ; public static readonly LocalisationToken New = new StandardButtonToken ( `` New '' , Guid.Parse ( `` f72d365c-b18f-4f01-a6e4-b0cd930dc730 '' ) ) ; public static readonly LocalisationToken More = new StandardButtonToken ( `` More '' , Guid.Parse ( `` bd4da7df-afd2-481e-b6b6-b4a989324758 '' ) ) ; public static readonly LocalisationToken Delete = new StandardButtonToken ( `` Delete '' , Guid.Parse ( `` ab00ec14-4414-4cda-a8e2-4f03c9e7c5a8 '' ) ) ; public static readonly LocalisationToken Add = new StandardButtonToken ( `` Add '' , Guid.Parse ( `` 01e44600-a556-4a07-8a2a-e69a1ea79629 '' ) ) ; public static readonly LocalisationToken Confirm = new StandardButtonToken ( `` Confirm '' , Guid.Parse ( `` 4c50e91e-3e2f-42fa-97aa-9f1f6f077f09 '' ) ) ; public static readonly LocalisationToken Send = new StandardButtonToken ( `` Send '' , Guid.Parse ( `` 24121766-f424-4d73-ac58-76f90d58b95c '' ) ) ; public static readonly LocalisationToken Continue = new StandardButtonToken ( `` Continue '' , Guid.Parse ( `` dd2ca0e5-8a35-4128-b2e8-db68a64a6fe5 '' ) ) ; public static readonly LocalisationToken OK = new StandardButtonToken ( `` OK '' , Guid.Parse ( `` 9a359f93-7c23-44ad-b863-e53c5eadce90 '' ) ) ; public static readonly LocalisationToken Accept = new StandardButtonToken ( `` Accept '' , Guid.Parse ( `` 3206a76b-1cd7-4dc3-9fff-61dfb0992c75 '' ) ) ; public static readonly LocalisationToken Reject = new StandardButtonToken ( `` Reject '' , Guid.Parse ( `` f99c6a9c-6a55-4f55-ac4b-9581e56d18d3 '' ) ) ; public static readonly LocalisationToken RequestMoreInfo = new StandardButtonToken ( `` Request more info '' , Guid.Parse ( `` 19f3d76b-dafa-47ae-8416-b7d61546b03d '' ) ) ; public static readonly LocalisationToken Cancel = new StandardButtonToken ( `` Cancel '' , Guid.Parse ( `` 75617287-5418-466b-9373-cc36f8298859 '' ) ) ; public static readonly LocalisationToken Publish = new StandardButtonToken ( `` Publish '' , Guid.Parse ( `` efd87fd4-e7f1-4071-9d26-a622320c366b '' ) ) ; public static readonly LocalisationToken Remove = new StandardButtonToken ( `` Remove '' , Guid.Parse ( `` f7db5d81-5af8-42bf-990f-778df609948e '' ) ) ; }
Does the way we translate our website result in performance issues ?
C_sharp : I 'm writing a desktop application in C # that should be able to access all users on a Google Apps `` account '' an retrieve calendar-events for each user . I have added the Calendar API and the Admin SDK to my `` project '' .Both methods ( below ) works fine on their own but when I want to authorize my app for both APIs I get the following permission errors.Insufficient Permission [ 403 ] invalid_grant '' , Description : '' Token has been revoked.This made me wonder if it was possible to ask for all permissions when the application starts , instead of authorizing the `` features '' separately ? <code> static string [ ] CalendarScopes = { CalendarService.Scope.CalendarReadonly } ; static string [ ] DirectoryScopes = { DirectoryService.Scope.AdminDirectoryUserReadonly } ; private static void GoogleCalendar ( ) { UserCredential credential ; using ( var stream = new FileStream ( `` client_secret.json '' , FileMode.Open , FileAccess.Read ) ) { string credPath = Environment.GetFolderPath ( Environment.SpecialFolder.Personal ) ; credPath = Path.Combine ( credPath , `` .credentials '' ) ; credential = GoogleWebAuthorizationBroker.AuthorizeAsync ( GoogleClientSecrets.Load ( stream ) .Secrets , CalendarScopes , `` user '' , CancellationToken.None , new FileDataStore ( credPath , true ) ) .Result ; } // Create Google Calendar API service . var service = new CalendarService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = ApplicationName , } ) ; // Define parameters of request . EventsResource.ListRequest request = service.Events.List ( `` primary '' ) ; request.TimeMin = DateTime.Now ; request.ShowDeleted = false ; request.SingleEvents = true ; //request.MaxResults = 10 ; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime ; // List events . Events events = request.Execute ( ) ; Console.WriteLine ( `` Upcoming events : '' ) ; if ( events.Items ! = null & & events.Items.Count > 0 ) { foreach ( var eventItem in events.Items ) { string when = eventItem.Start.DateTime.ToString ( ) ; if ( String.IsNullOrEmpty ( when ) ) { when = eventItem.Start.Date ; } Console.WriteLine ( `` { 0 } ( { 1 } ) '' , eventItem.Summary , when ) ; } } else { Console.WriteLine ( `` No upcoming events found . `` ) ; } Console.Read ( ) ; } private static void GoogleDirectory ( ) { UserCredential credential ; using ( var stream = new FileStream ( `` client_secret.json '' , FileMode.Open , FileAccess.Read ) ) { string credPath = Environment.GetFolderPath ( Environment.SpecialFolder.Personal ) ; credPath = Path.Combine ( credPath , `` .credentials '' ) ; credential = GoogleWebAuthorizationBroker.AuthorizeAsync ( GoogleClientSecrets.Load ( stream ) .Secrets , DirectoryScopes , `` user '' , CancellationToken.None , new FileDataStore ( credPath , true ) ) .Result ; Console.WriteLine ( `` Credential file saved to : `` + credPath ) ; } // Create Directory API service . var service = new DirectoryService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = ApplicationName , } ) ; // Define parameters of request . UsersResource.ListRequest request = service.Users.List ( ) ; request.Customer = `` my_customer '' ; request.MaxResults = 10 ; request.OrderBy = UsersResource.ListRequest.OrderByEnum.Email ; // List users . IList < User > users = null ; try { users = request.Execute ( ) .UsersValue ; } catch ( Exception ex ) { throw ; } Console.WriteLine ( `` Users : '' ) ; if ( users ! = null & & users.Count > 0 ) { foreach ( var userItem in users ) { Console.WriteLine ( `` { 0 } ( { 1 } ) '' , userItem.PrimaryEmail , userItem.Name.FullName ) ; } } else { Console.WriteLine ( `` No users found . `` ) ; } Console.Read ( ) ; }
Multiple Google access permissions for a desktop application
C_sharp : I 've been struggling a lot lately to find decent solution which has authentication mechanism for server and client API's.I put alot of effort trying to find working ( ! ) code samples , but could n't find any.The code from DotNetOpenAuth does n't work for me - im using vs 2010 .net 4 webformAnyway , I ca n't seems to find a solution which covers an overall API for all parameters/providers and it seems that I have to build it from scratch.For example — ( google ) : Every solution I 've found provides only the info that the basic url is : Also , i do n't know if this usage is going to work since I 've heard that the service is deprecated : But this will never work alone , since I have to append URL parameters : Why do I have to build/encode it by myself ? Now , I do n't have a problem with the parameters filling , I have a problem with the fact that I ca n't find full API for both client ( js ) and server side ( .net ) .It seems that I have to build the url + encoded values by myself QuestionIs there any solution which will take as param my plain values , and will provide final valid URL ? ( both for C # and js/jq and for many providers ) <code> https : //accounts.google.com/o/oauth2/auth https : //accounts.google.com/o/oauth2/auth ? scope=email % 20profile & state= % 2Fprofile & redirect_uri=https % 3A % 2F % 2Foauth2-login-demo.appspot.com % 2Foauthcallback & response_type=token & client_id=812741506391.apps.googleusercontent.com
OpenID API for both asp.net and JavaScript support ?
C_sharp : List < T > derives from the following interfaces : I just wonder , why it needs all these interfaces ( in the class declaration ) ? IList itself already derives from ICollection < T > , IEnumerable < T > und IEnumerable.So why is the following not enough ? I hope you can solve my confusion . <code> public class List < T > : IList < T > , ICollection < T > , IEnumerable < T > , IList , ICollection , IEnumerable public class List < T > : IList < T > , IList
Why does List < T > implement so many interfaces ?
C_sharp : I have following LINQ statement and I want to rewrite it using extension methods.One possible solution is : However this is everything but elegant . Do you any idea how to improve beauty of second expression ? <code> from x in efrom y in efrom z in eselect new { x , z } e.Join ( e , x = > 42 , y = > 42 , ( x , y ) = > new { x , y } ) Join ( e , _ = > 42 , z = > 42 , ( _ , z ) = > new { _.x , z } ) ;
What 's elegant way to rewrite following LINQ statement using extension methods ?
C_sharp : I 'm finding that ValueTuples evaluate differently when I access their properties from a collection.Why do these two highlighted lines evaluate differently and how can I change `` MyList [ 0 ] .c '' to get the value correctly ? <code> public static List < Tuple < string , bool > > MyTupleList = new List < Tuple < string , bool > > { new Tuple < string , bool > ( `` test '' , true ) } ; public static List < ( string b , bool c ) > MyList = new List < ( string b , bool c ) > { ( `` test '' , true ) } ;
Why does the Visual Studio watch window show wrong values for ValueTuples in a collection ?
C_sharp : I have two functions that have different enough logic but pretty much the same exception handling : It is not possible to use a single entry point for DoIt1 and DoIt2 , because they are called in from outside.Is Copy/Pase ( for the exception block ) the best approach ? <code> public void DoIt1 // DoIt2 has different logic but same exception handling { try ... DoIt1 logic catch ( MySpecialException myEx ) { Debug.WriteLine ( myEx.MyErrorString ) ; throw ; } catch ( Exception e ) { Debug.WriteLine ( e.ToString ( ) ) ; throw ; } }
What is the best way to re-use exception handling logic in C # ?
C_sharp : I am developing a WinRT app using XAML and MVVM Light . This app is meant to make it easier to do data collection while the users are out in the field . I have a section of my app where users will need to enter in a bunch of information about several different items . These items are defined as classes that inherit from a GenericAsset class . The GenericAsset has fields such as this : And the sub classes look something like this : Currently I have 15 SubAssets ( and will have many more in the future ) and I am looking for a way to create one data entry view/viewmodel ( if possible ) so that I do n't have to create a separate view for each asset . Also , if I can get the generic view/viewmodel working , how would I go about loading in the custom data entry controls ( the inputs specific to each sub asset ) while maintaining the proper two-way data binding to the appropriate sub asset ? <code> public class GenericAsset { public string AssetId { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } public string Make { get ; set ; } public string Model { get ; set ; } } public class SubAsset1 : GenericAsset { public string RecordNumber { get ; set ; } public int SizeDiameter { get ; set ; } public string MaterialType { get ; set ; } } public class SubAsset2 : GenericAsset { public string Type { get ; set ; } public int Size { get ; set ; } public string PlanRef { get ; set ; } public string InteriorMaterial { get ; set ; } }
Multiple input forms with same xaml file and different DataContexts
C_sharp : I 'm creating a reusable library that targets several platforms ( .NET 4.0 , .NET 4.5 , .NETStandard 1.0 and .NETStandard 1.3 ) . The .NET 4.5 version of this project contains some features that are not available under the .NET 4.0 version . The unit test project that references this library project has one single target platform , namely NET 4.5.1 . This test project obviously contains some code that tests the .NET 4.5 specific features of the core library.Unfortunately however , the test project does not compile , because Visual Studio seems to reference the .NETStandard 1.0 version , which obviously does not contain this feature.To demonstrate my problem , I reduced this to the following two projects : Core library : Code file : Test library : Code : What should I change to allow my unit test project to compile and test the specific .NET 4.5 features ? <code> { `` version '' : `` 1.0.0-* '' , `` frameworks '' : { `` netstandard1.0 '' : { `` dependencies '' : { `` NETStandard.Library '' : `` 1.6.0 '' } } , `` net40 '' : { } , `` net45 '' : { } } } namespace CoreLibrary { # if NETSTANDARD1_0 public class ClassNetStandard { } # endif # if NET40 public class ClassNet40 { } # endif # if NET45 public class ClassNet45 { } # endif } { `` version '' : `` 1.0.0-* '' , `` dependencies '' : { `` CoreLibrary '' : { `` target '' : `` project '' } } , `` frameworks '' : { `` net451 '' : { } } } // This compilesnew CoreLibrary.ClassNetStandard ( ) ; // This doesn't.// error : Type or namespace 'ClassNet40 ' does not exist in namespace 'CoreLibrary'new CoreLibrary.ClassNet40 ( ) ; // error : Type or namespace 'ClassNet45 ' does not exist in namespace 'CoreLibrary'new CoreLibrary.ClassNet45 ( ) ;
How to let a Visual Studio 2015 xproject ( project.json ) reference the highest framework of a depending project
C_sharp : I have a class called Message which overloads these operators : I want the == and ! = operators keep comparing references of the types other than String and Message but , gives me this : The call is ambiguous between the following methods or properties : 'Message.operator == ( Message , Message ) ' and 'Message.operator == ( Message , string ) ' I know it 's because both Message and String are reference types and they both can be null , but I want to be able to use == opreator for checking whether the message is null.Can I overload == for null values ? I tried overloading it for object and call object.ReferenceEquals ( object , object ) in the overload but that did n't help . <code> public static bool operator == ( Message left , Message right ) public static bool operator ! = ( Message left , Message right ) public static bool operator == ( Message left , string right ) public static bool operator ! = ( Message left , string right ) public static bool operator == ( string left , Message right ) public static bool operator ! = ( string left , Message right ) var message = new Message ( ) ; var isNull = message == null ;
Overloading == operator for null
C_sharp : I have came across this question : What does the [ Flags ] Enum Attribute mean in C # ? And one thing I have been wondering , using the accepted answer 's example , what will happen if I declare : Will the following steps in that example resulting an error ? If no , how can I get to MyColors.Red ? <code> [ Flags ] public enum MyColors { Yellow = 1 , Green = 2 , Red = 3 , Blue = 4 }
What happens if we declare [ Flags ] enum in order ?
C_sharp : My OM has a 'product ' object.Each product has a 'manufacturer id ' ( property , integer ) .When I have a list of products to display , the first three are displayed as the 'featured products'.The list is already sorted in a specific sort order , putting the 'featured ' products first in the list . However , I now need to ensure the featured products in the listing are from different Manufacturers . I want to have a method to call to do this re-sorting . Trying to utilize LINQ to to the querying of the input 'products ' and the 'results'Thanks in advance.Clarification : The original list is in a specific order : the 'best selling ' , highest first ( descending order ) . The resulting list should remain in this order with the exception of adjusting or moving 'up ' items so that the differing manufacturers are seen the top n features . If the first n ( numberOfFeatures ) of items all have different manufacturers , then the listing does not need to be altered at all.e.g . If numberOfFeatures = 3Product 1 - Manufacturer A ( 1st feature ) Product 2 - Manufacturer B ( 2nd feature ) Product 3 - Manufacturer C ( 3rd feature ) Product 4 - Manufacturer A ( ... not checked ... ) Product 5 - Manufacturer A ( ... not checked ... ) e.g . Case to adjust ... for example ... INPUT ListProduct 1 - Manufacturer AProduct 2 - Manufacturer AProduct 3 - Manufacturer BProduct 4 - Manufacturer AProduct 5 - Manufacturer F ( ... we would want ... ) Product 1 - Manufacturer A ( 1st feature ) Product 3 - Manufacturer B ( 2nd feature ... moved up ) Product 5 - Manufacturer F ( 3rd feature ... moved up ) Product 2 - Manufacturer A ( ... pushed down the list ... ) Product 4 - Manufacturer A ( ... pushed down the list ... ) <code> public List < Product > SetFeatures ( List < Product > products , int numberOfFeatures ) { List < Product > result ; // ensure the 2nd product is different manufacturer than the first ... . // ensure the 3rd product is a different manufacturer than the first two ... // ... etc ... for the numberOfFeatures return result ; }
LINQ Sorting - First three need to be different manufacturers
C_sharp : This is a very uncommon problem and there are definetly many workarounds , but I would like to understand what is actually going on and why it 's not working.So I have 3 assemblies in a test solution , first assembly has type ClassA : Second assembly references first assembly and has ClassB : which has an explicit operator to cast to type ClassA . Let 's say that we can not use inheritance for some reason and just using casting as a convenient way of transforming one type to another.Now , the last assembly references second assembly ( and not the first one ! ) and has type ClassC : which uses explicit cast operator for same reason as ClassB.Now the interesting part : if I try to cast from ClassC to ClassB in my code , like this : I get the following error : Error 1 The type 'FirstAssembly.ClassA ' is defined in an assembly that is not referenced . You must add a reference to assembly 'FirstAssembly , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null'.I could easily create new instance of ClassB and just initialize it with values from ClassC instance ( like I do inside explicit cast operator ) , and it would work fine . So what is wrong here ? <code> public class ClassA { public string Name { get ; set ; } } public class ClassB { public string Name { get ; set ; } public static explicit operator ClassA ( ClassB objB ) { return new ClassA { Name = objB.Name } ; } } public class ClassC { public string Name { get ; set ; } public static explicit operator ClassB ( ClassC objC ) { return new ClassB { Name = objC.Name } ; } } ClassC objC = new ClassC ( ) ; ClassB objB = ( ClassB ) objC ;
Explicit cast operator fails with `` assembly is not referenced '' error
C_sharp : I have a x64 crash dump of a managed ( C # ) application that p/invokes to native code . The dump was taken after the native code attempted to dereference a bad memory location , and after the .NET marshaler had turned it into an AccessViolationException . As a result , the stack frame where the error occurred is no longer available , and the thread where the exception occurred is now hijacked by the CLR exception handler : And .exr -1 ( display most recent exception ) returns : The call to user32 ! ZwUserMessageCall is at the top of the stack of thread 0 , not 17 where the native exception occurred , so I can only assume it 's not pointing to my exception.I can dump the access violation exception to get some info about the native error : From this I see the instruction address that failed ( 7fedad179f4 ) and the address that the code tried to dereference ( fffffffc2ab22078 ) . It appears to be a sign extension or overflow bug somehow , but it 's not obvious in the code how that might have happened . The instruction referenced is : To debug this further , I need the register context from when the native code crashed to see what was in r12 and rax . Is this possible to retrieve ? Edit : I tried to get information about the parameters to ExceptionHijackWorker , but the values do n't make sense to me . The function signature according to @ S.T . 's link isSo a first parameter of 0000000a does n't make sense as a pointer . And dumping the second parameter 000000002ab23e30 yields nonsensical data for the EXCEPTION_RECORD:0x19 and 0x19 for the ExceptionCode and ExceptionFlags do n't make sense ; there is no code with that value and the flag is documented as being zero or EXCEPTION_NONCONTINUABLE , which is defined as 1.Am I misinterpreting anything here ? <code> 0:017 > kb # RetAddr : Args to Child : Call Site00 000007fe ` fd3b10dc : 00000000 ` 0402958b 00000000 ` 20000002 00000000 ` 00000e54 00000000 ` 00000e4c : ntdll ! NtWaitForSingleObject+0xa01 000007fe ` ea9291eb : 00000000 ` 00000000 00000000 ` 00000cdc 00000000 ` 00000000 00000000 ` 00000cdc : KERNELBASE ! WaitForSingleObjectEx+0x7902 000007fe ` ea929197 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : clr ! CLREventWaitHelper2+0x3803 000007fe ` ea929120 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : clr ! CLREventWaitHelper+0x1f04 000007fe ` ead8cae5 : 00000000 ` 29cbc7c0 00000000 ` 3213ce40 00000000 ` 00000000 00000000 ` ffffffff : clr ! CLREventBase : :WaitEx+0x7005 000007fe ` ead8c9d0 : 00000000 ` 29cbc7c0 00000000 ` 00000000 00000000 ` 0002b228 00000000 ` 0002b228 : clr ! Thread : :WaitSuspendEventsHelper+0xf506 000007fe ` eacf2145 : 00000000 ` 007ea060 000007fe ` ea924676 00000000 ` 00000000 000007fe ` fd3b18da : clr ! Thread : :WaitSuspendEvents+0x1107 000007fe ` eaccc00c : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : clr ! Thread : :RareEnablePreemptiveGC+0x33a90508 000007fe ` eae2c762 : 00000000 ` 00000000 00000000 ` 007cbce0 00000000 ` 29cbc7c0 00000000 ` 00000001 : clr ! Thread : :RareDisablePreemptiveGC+0x31b40c09 000007fe ` eaf662d4 : 00000000 ` 00000000 00000000 ` 007cbce0 00000000 ` 29cbc7c0 00000000 ` 00000000 : clr ! EEDbgInterfaceImpl : :DisablePreemptiveGC+0x220a 000007fe ` eaf66103 : 00000000 ` 29cb0100 00000000 ` 00000000 00000000 ` 3213cf80 00000000 ` 29cbca20 : clr ! Debugger : :SendExceptionHelperAndBlock+0x1740b 000007fe ` eaf65d0d : ffffffff ` ffffffff 00000000 ` 29cbca20 00000000 ` 29cbc700 000007fe ` eaf62100 : clr ! Debugger : :SendExceptionEventsWorker+0x3430c 000007fe ` eaf61bd8 : 00000000 ` 00000100 00000000 ` 00000000 00000000 ` 00000019 00000000 ` 3213dd01 : clr ! Debugger : :SendException+0x15d0d 000007fe ` eadac75d : 00000000 ` 007cbce0 00000000 ` 3213d258 00000000 ` 3213d1e8 00000000 ` 00000001 : clr ! Debugger : :LastChanceManagedException+0x1f80e 000007fe ` eaf698c7 : 000075ce ` 2b30e018 00000000 ` 00000000 00000000 ` 00000001 00000000 ` 00000000 : clr ! NotifyDebuggerLastChance+0x6d0f 000007fe ` eaf6af20 : 00000000 ` 00000000 000007fe ` 8cf40020 000007fe ` 8cfa200c 4328fffe ` 43e0fffe : clr ! Debugger : :UnhandledHijackWorker+0x1a710 000007fe ` eaaacbf0 : 00000000 ` 0000000a 00000000 ` 2ab23e30 00000000 ` 00000001 00000000 ` 00000000 : clr ! ExceptionHijackWorker+0xc011 00000000 ` 3213d8c0 : 00000000 ` 3213ddb0 00000000 ` 00000001 00000000 ` 00000000 00000000 ` 0000000b : clr ! ExceptionHijack+0x3012 00000000 ` 3213ddb0 : 00000000 ` 00000001 00000000 ` 00000000 00000000 ` 0000000b 00000000 ` 0035578c : 0x3213d8c013 00000000 ` 00000001 : 00000000 ` 00000000 00000000 ` 0000000b 00000000 ` 0035578c ffffffff ` 00000002 : 0x3213ddb014 00000000 ` 00000000 : 00000000 ` 0000000b 00000000 ` 0035578c ffffffff ` 00000002 00000000 ` 00350268 : 0x1 0:017 > .exr -1ExceptionAddress : 00000000771d685a ( user32 ! ZwUserMessageCall+0x000000000000000a ) ExceptionCode : 80000004 ( Single step exception ) ExceptionFlags : 00000000NumberParameters : 0 0:017 > ! DumpObj /d 0000000012175640Name : System.AccessViolationExceptionMethodTable : 000007fee9a61fe8EEClass : 000007fee9528300Size : 176 ( 0xb0 ) bytesFile : C : \Windows\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dllFields : MT Field Offset Type VT Attr Value Name000007fee9a50e08 4000002 8 System.String 0 instance 000000001217b538 _className000007fee9a5b218 4000003 10 ... ection.MethodBase 0 instance 0000000000000000 _exceptionMethod000007fee9a50e08 4000004 18 System.String 0 instance 0000000000000000 _exceptionMethodString000007fee9a50e08 4000005 20 System.String 0 instance 0000000012179818 _message000007fee9a61f18 4000006 28 ... tions.IDictionary 0 instance 0000000000000000 _data000007fee9a51038 4000007 30 System.Exception 0 instance 0000000000000000 _innerException000007fee9a50e08 4000008 38 System.String 0 instance 0000000000000000 _helpURL000007fee9a513e8 4000009 40 System.Object 0 instance 0000000012179ad0 _stackTrace000007fee9a513e8 400000a 48 System.Object 0 instance 0000000012179c68 _watsonBuckets000007fee9a50e08 400000b 50 System.String 0 instance 0000000000000000 _stackTraceString000007fee9a50e08 400000c 58 System.String 0 instance 0000000000000000 _remoteStackTraceString000007fee9a53980 400000d 88 System.Int32 1 instance 0 _remoteStackIndex000007fee9a513e8 400000e 60 System.Object 0 instance 0000000000000000 _dynamicMethods000007fee9a53980 400000f 8c System.Int32 1 instance -2147467261 _HResult000007fee9a50e08 4000010 68 System.String 0 instance 0000000000000000 _source000007fee9a54a00 4000011 78 System.IntPtr 1 instance 0 _xptrs000007fee9a53980 4000012 90 System.Int32 1 instance -532462766 _xcode000007fee9a02d50 4000013 80 System.UIntPtr 1 instance 0 _ipForWatsonBuckets000007fee9a3d210 4000014 70 ... ializationManager 0 instance 0000000012179900 _safeSerializationManager000007fee9a513e8 4000001 0 System.Object 0 shared static s_EDILock > > Domain : Value 00000000007e09b0 : NotInit < < 000007fee9a54a00 400018a 98 System.IntPtr 1 instance 7fedad179f4 _ip000007fee9a54a00 400018b a0 System.IntPtr 1 instance fffffffc2ab22078 _target000007fee9a53980 400018c 94 System.Int32 1 instance 0 _accessType 0:017 > u 7fedad179f4MYDLL ! _interpolate+0x174 [ c : \my\source\file.c @ 85 ] :000007fe ` dad179f4 f3450f59548404 mulss xmm10 , dword ptr [ r12+rax*4+4 ] void STDCALL ExceptionHijackWorker ( T_CONTEXT * pContext , EXCEPTION_RECORD * pRecord , EHijackReason : :EHijackReason reason , void * pData ) ; 0:017 > dd 000000002ab23e3000000000 ` 2ab23e30 00000019 00000019 2ab23e40 0000000000000000 ` 2ab23e40 42b8f800 42b8de00 42b89b00 42b8500000000000 ` 2ab23e50 42b81b00 42b7a000 42b72600 42b6fa0000000000 ` 2ab23e60 42b6a000 42b67a00 42b63600 42b59c0000000000 ` 2ab23e70 42b4fc00 42b4da00 42b49e00 42b46a0000000000 ` 2ab23e80 42b38e00 42b31c00 42b2d600 42b2900000000000 ` 2ab23e90 42b2ec00 42b2fa00 42b2a000 42b27a0000000000 ` 2ab23ea0 42b23e00 42b6e800 42b6ab00 42b66c80
How do I retrieve Register Context from AccessViolationException ?
C_sharp : A part of my ( C # 3.0 .NET 3.5 ) application requires several lists of strings to be maintained . I declare them , unsurprisingly , as List < string > and everything works , which is nice.The strings in these Lists are actually ( and always ) Fund IDs . I 'm wondering if it might be more intention-revealing to be more explicit , e.g. : ... and this works as well . Are there any obvious drawbacks to this , either technically or philosophically ? <code> public class FundIdList : List < string > { }
Are there drawbacks to creating a class that encapsulates Generic Collection ?
C_sharp : I have the following code snippet in C # : It 's running fine , but I am not getting the result I expect.Actual result9,9,9Expected result1,4,9Why am I not getting the result I expect ? <code> var actions = new List < Func < int > > ( ) ; IEnumerable < int > values = new List < int > { 1 , 2 , 3 } ; foreach ( int value in values ) { actions.Add ( ( ) = > value * value ) ; } foreach ( var action in actions ) { Console.WriteLine ( action ( ) ) ; ; } Console.ReadLine ( ) ;
Why am I getting wrong results when calling Func < int > ?
C_sharp : I am working with ComboBox elements that often contain very large quantities of data ; ~250000 data entries.This works fine when a ComboBox is set up a little like this.However , some custom modifications of the ComboBox I am working with require the ComboBoxItem elements to not be focusable . I achieved this by using a setter in the ComboBox.ItemContainerStyle.But there is a problem with this . It works fine until an object has been selected . Then when a user tries to open the ComboBox again , it crashes the program.My question is , how can the ComboBox be set up so all its ComboBoxItem elements are not focusable , but it does not crash the program.Example CodeXAMLC # <code> < ComboBox ItemsSource= '' { Binding Items } '' > < ComboBox.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /ItemsPanelTemplate > < /ComboBox.ItemsPanel > < /ComboBox > < ComboBox ItemsSource= '' { Binding Items } '' > < ComboBox.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /ItemsPanelTemplate > < /ComboBox.ItemsPanel > < ComboBox.ItemContainerStyle > < Style TargetType= '' ComboBoxItem '' > < Setter Property= '' Focusable '' Value= '' False '' / > < /Style > < /ComboBox.ItemContainerStyle > < /ComboBox > < Window x : Class= '' FocusableTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 450 '' Width= '' 800 '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' / > < ColumnDefinition Width= '' 2* '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' 2* '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < Viewbox Stretch= '' Uniform '' Grid.ColumnSpan= '' 3 '' > < Label Content= '' Welcome '' FontWeight= '' Bold '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Viewbox > < StackPanel Grid.Row= '' 1 '' Grid.Column= '' 1 '' > < ComboBox ItemsSource= '' { Binding Items } '' > < ComboBox.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /ItemsPanelTemplate > < /ComboBox.ItemsPanel > < ComboBox.ItemContainerStyle > < Style TargetType= '' ComboBoxItem '' > < Setter Property= '' Focusable '' Value= '' False '' / > < /Style > < /ComboBox.ItemContainerStyle > < /ComboBox > < /StackPanel > < /Grid > < /Window > using System.Collections.ObjectModel ; using System.Security.Cryptography ; using System.Text ; namespace FocusableTest { public partial class MainWindow { public MainWindow ( ) { for ( int i = 0 ; i < 250000 ; i++ ) { Items.Add ( GetUniqueKey ( ) ) ; } InitializeComponent ( ) ; DataContext = this ; } public ObservableCollection < string > Items { get ; } = new ObservableCollection < string > ( ) ; private static string GetUniqueKey ( int maxSize = 20 ) { char [ ] chars = `` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '' .ToCharArray ( ) ; byte [ ] data = new byte [ 1 ] ; using ( RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider ( ) ) { crypto.GetNonZeroBytes ( data ) ; data = new byte [ maxSize ] ; crypto.GetNonZeroBytes ( data ) ; } StringBuilder result = new StringBuilder ( maxSize ) ; foreach ( byte b in data ) { result.Append ( chars [ b % ( chars.Length ) ] ) ; } return result.ToString ( ) ; } } }
None focusable ComboBoxItem
C_sharp : I want to capture the selected date on my DropDown list , where there are five days will display on DropdownList.I 'm usually putting the default value on DropDown , but not this time because in the drop down list I want it always display the current date and the next five days . But I do n't know how to capture the data . <code> < asp : DropDownList ID= '' ddldate '' runat= '' server '' > < /asp : DropDownList > protected void Page_Load ( object sender , EventArgs e ) { List < ListItem > items = new List < ListItem > ( ) ; for ( int i = 0 ; i < 5 ; i++ ) { items.Add ( new ListItem ( DateTime.Now.AddDays ( i ) .ToShortDateString ( ) , DateTime.Now.AddDays ( i ) .ToShortDateString ( ) ) ) ; } ddldate.DataSource = items ; ddldate.DataBind ( ) ; ddldate.Items [ 0 ] .Selected = true ; } protected void Button1_Click ( object sender , EventArgs e ) { string deliverytime = ddldate.SelectedValue.ToString ( ) ; lbltest.Text = deliverytime ; }
Capture a value from a dropdownlist where the display dropdownlist is not default
C_sharp : I am using an asp.net webapi controller , and in my project I have a dll that I built myself . The dll is being used to validate if the person that the user is typing in actually exists.Here is my controller method : Now the two conditional statements above that have EmpData.. EmpData is from my dll.Here is the ajax code in my view : Now , in the controller when I purposefully test to get the error message concering the end date being before the start date , I receive error.modelState . But when I purposefully test to get the error message saying that a person does not exist ... I do not get error.modelState.. that returns as undefined.Does returning ModelState not work when using custom DLL ? Any help is appreciated . <code> // POST : api/EventsAPI [ ResponseType ( typeof ( Event ) ) ] public IHttpActionResult PostEvent ( Event @ event ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } if ( @ event.DateEndOfEvent < @ event.DateOfEvent ) // successfully returns error.modelState ( in view code ) { ModelState.AddModelError ( `` DateEndOfEvent '' , `` End Date Can not Be Before Start Date ! `` ) ; return BadRequest ( ModelState ) ; } if ( ! EmpData.IsValid ( @ event.PersonWorkedOne ) ) // returns error.modelState as undefined ( in view code ) { ModelState.AddModelError ( `` PersonWorkedOne '' , `` This person does not exist ! `` ) ; return BadRequest ( ModelState ) ; } if ( ! string.IsNullOrWhiteSpace ( @ event.PersonWorkedTwo ) ) { if ( ! EmpData.IsValid ( @ event.PersonWorkedTwo ) ) // returns error.modelState as undefined ( in view code ) { ModelState.AddModelError ( `` PersonWorkedTwo '' , `` This persondoes not exist ! `` ) ; return BadRequest ( ModelState ) ; } } db.Event.Add ( @ event ) ; db.SaveChanges ( ) ; return CreatedAtRoute ( `` DefaultApi '' , new { id = @ event.Id } , @ event ) ; } $ ( `` form '' ) .data ( `` validator '' ) .settings.submitHandler = function ( form ) { $ .ajax ( { method : `` POST '' , url : infoGetUrl , data : $ ( `` form '' ) .serialize ( ) , success : function ( ) { toastr.options = { onHidden : function ( ) { window.location.href = newUrl ; } , timeOut : 3000 } toastr.success ( `` Event successfully created . `` ) ; } , error : function ( jqXHR , textStatus , errorThrown ) { var status = capitalizeFirstLetter ( textStatus ) ; var error = $ .parseJSON ( jqXHR.responseText ) ; var modelState = error.modelState ; console.log ( modelState ) ; $ .each ( modelState , function ( key , value ) { var id = `` '' ; if ( key === `` $ id '' ) { id = `` # '' + key.replace ( ' $ ' , `` ) .substr ( 0 , 1 ) .toUpperCase ( ) + key.substr ( 2 ) ; } else { id = `` # '' + key.replace ( ' $ ' , `` ) .substr ( 0 , 1 ) .toUpperCase ( ) + key.substr ( 1 ) ; var status = capitalizeFirstLetter ( textStatus ) ; console.log ( key ) ; toastr.error ( status + `` - `` + modelState [ key ] ) ; } var input = $ ( id ) ; console.log ( id ) ; // result is # id if ( input ) { // if element exists input.addClass ( 'input-validation-error ' ) ; } } ) ; } } ) ; }
AJAX error not returning jqXHR.responseText.modelState when using custom dll
C_sharp : Okay I have a derived class that has an overload to a method that 's on my base class . I call what I think would match the method signature of the base class but instead my derived classes implementation is called . ( The code below always prints out `` MyDerived '' ) Why is this ? <code> public class MyBase { public void DoSomething ( int a ) { Console.WriteLine ( `` MyBase '' ) ; } } public class MyDerived : MyBase { public void DoSomething ( long a ) { Console.WriteLine ( `` MyDerived '' ) ; } } Main ( ) { MyDerived d = new MyDerived ( ) ; d.DoSomething ( ( int ) 5 ) ; }
Compiler picking the wrong overload
C_sharp : I am trying to call IEnumerable.Contains ( ) with a dynamic argument , but I am getting the error 'IEnumerable ' does not contain a definition for 'Contains ' and the best extension method overload 'Queryable.Contains ( IQueryable , TSource ) ' has some invalid argumentsI 've noticed that I can either cast the argument to the correct type , or use an underlying collection type to fix the issue . But I 'm not sure why I ca n't just pass in the argument directly . <code> dynamic d = `` test '' ; var s = new HashSet < string > ( ) ; IEnumerable < string > ie = s ; s.Contains ( d ) ; // Worksie.Contains ( d ) ; // Does not workie.Contains ( ( string ) d ) ; // Works
Why do I need to cast a dynamic object when calling IEnumerable.Contains ( ) ?
C_sharp : Just wondering why Enumerable.Range implements IDisposable.I understand why IEnumerator < T > does , but IEnumerable < T > does n't require it . ( I discovered this while playing with my .Memoise ( ) implementation , which has statement like in its `` source finished '' method that I had placed a breakpoint on out of curiousity , and was triggered by a test . ) <code> if ( enumerable is IDisposable ) ( ( IDisposable ) enumerable ) .Dispose ( ) ;
Why does Enumerable.Range Implement IDisposable ?
C_sharp : Is there way to do something along these lines ? I do n't care about the type of the properties , I just need the properties to be available . This does n't have to be implemented with an interface , just using that as an example . <code> interface Iface { [ anytype ] Prop1 { get ; } [ anytype ] Prop2 { get ; } } class Class1 : Iface { public string Prop1 { get ; } public int Prop2 { get ; } } class Class2 : Iface { public int Prop1 { get ; } public bool ? Prop2 { get ; } }
C # Interface without static typing
C_sharp : I 've got something like this : I have to make SomeDataBlob public so that it can be used as a member of the public interface method ExternalPlugin.DoStuff . However , I would not like to allow clients to inherit from that class and thus be susceptible to the brittle base class problem . ( All derivatives of that class should be kept in the same assembly ) Marking the class sealed goes too far because I believe removing sealed is a breaking API change ; and even if that is n't , once I ship SomeDataBlobV2 clients could still do the wrong thing and inherit from SomeDataBlob directly.Is there a way to enforce this kind of pattern ? <code> // This gets implemented by plugin authors to get callbacks about various things.public interface ExternalPlugin { // This gets called by the main application to tell the plugin some data // is available or similar . void DoStuff ( SomeDataBlob blob ) ; } // Data blob for v1 of APIpublic class SomeDataBlob { internal SomeDataBlob ( string prop ) { Prop = prop ; } // Some piece of data that V1 plugins need public string Prop { get ; private set ; } } // FUTURE ! // Data blob API v2 of APIpublic class SomeDataBlobV2 : SomeDataBlob { // Can be passed to clients expecting SomeDataBlob no problem . internal SomeDataBlobV2 ( string prop , string prop2 ) : base ( prop ) { Prop2 = prop2 ; } // Some piece of data that V2 plugins need . V2 plugins can cast to this from // SomeDataBlob , but still can load successfully into older versions that support // only V1 of the API public string Prop2 { get ; private set ; } }
Can I disallow other assemblies from inheriting from a class ?
C_sharp : I am migrating a project from .Net 4.6.2 into .Net Core 2.0 . What is the replacement for RoleProvider in Net Core ? The type or namespace name 'RoleProvider ' could not be found ( are you missing a using directive or an assembly reference ? ) New code looks like this , received errorUpdate : Answer from John Kenney looks great , hopefully someone can add more into his answer as edit . <code> public class CustomerRoleProvider : RoleProvider { public override string CustomerName { get ; set ; } public override void AddUsersToRoles ( string [ ] usernames , string [ ] roleNames ) { Using the generic type 'RoleManager < TRole > ' requires 1 type arguments// Error first line : Using the generic type 'RoleManager < TRole > ' requires 1 type argumentspublic class CustomerRoleProvider : RoleManager { public string ApplicationName { get ; set ; } public void CreateRole ( IServiceProvider serviceProvider , string roleName ) { var RoleManager = serviceProvider.GetRequiredService < RoleManager < IdentityRole > > ( ) ; throw new NotImplementedException ( ) ; }
Net Core : Type or namespace name 'RoleProvider ' could not be found
C_sharp : In this threadHow to get null instead of the KeyNotFoundException accessing Dictionary value by key ? in my own answer I used explicit interface implementation to change the basic dictionary indexer behaviour not to throw KeyNotFoundException if the key was not present in the dictionary ( since it was convinient for me to obtain null in such a case right inline ) .Here it is : Since in a real application I had a list of dictionaries , I needed a way to access the dictionaries from the collection as an interface . I used simple int indexer to acess each element of the list.The easiest thing was to do something like this : The question raised when I decided to try to use covariance feature to have a collection of interfaces to use instead . So I needed an interface with covariant type parameter for the cast to work . The 1st thing that came to my mind was IEnumerable < T > , so the code would look like this : Not that nice at all , besides ElementAt instead of an indexer is way worse.The indexer for List < T > is defined in IList < T > , and T there is not covariant.What was I to do ? I decided to write my own : Well , few lines of code ( I do n't even need to write anything in ExtendedList < T > ) , and it works as I wanted : Finally the question : can this covariant cast be somehow achieved without creating an extra collection ? <code> public interface INullValueDictionary < T , U > where U : class { U this [ T key ] { get ; } } public class NullValueDictionary < T , U > : Dictionary < T , U > , INullValueDictionary < T , U > where U : class { U INullValueDictionary < T , U > .this [ T key ] { get { if ( ContainsKey ( key ) ) return this [ key ] ; else return null ; } } } var list = new List < NullValueDictionary < string , string > > ( ) ; int index = 0 ; // ... list [ index ] [ `` somekey '' ] = `` somevalue '' ; var idict = ( INullValueDictionary < string , string > ) list [ index ] ; string value = idict [ `` somekey '' ] ; IEnumerable < INullValueDictionary < string , string > > ilist = list ; string value = ilist.ElementAt ( index ) [ `` somekey '' ] ; public interface IIndexedEnumerable < out T > { T this [ int index ] { get ; } } public class ExtendedList < T > : List < T > , IIndexedEnumerable < T > { } var elist = new ExtendedList < NullValueDictionary < string , string > > ( ) ; IIndexedEnumerable < INullValueDictionary < string , string > > ielist = elist ; int index = 0 ; // ... elist [ index ] [ `` somekey '' ] = `` somevalue '' ; string value = ielist [ index ] [ `` somekey '' ] ;
Is there a built-in generic interface with covariant type parameter returned by an indexer ?
C_sharp : The issue I 'm currently facing is that I 'm unable to get my C # program to write the file I want to send in the response ( I 'm writing the bytes of the file ) and have a valid HTTP response , the browser I 'm testing it with is saying ERR_INVALID_HTTP_RESPONSE if I have appended the file to the response.Originally I was using a HttpListener but this was requiring me to run my IDE as admin every time so I decided to move away from it and start using a TcpListener.This is just a simple web server that is running entirely off of C # and utilizes the TcpListener from System.Net . So far I 've tried using the BaseStream from the StreamWriter to write the bytes of the file into the response . I have been searching around to look for other ways to send a file via TCP / HTTP however it seems two things are apparent , its not brilliantly documented on how to properly do it and nobody seems to have asked the same question for this specific scenario . So far the code that handles the response to the incoming connection is as follows.The expected result is that the browser will show the image much like you 'd see from an imgur link , basically the same format as I will use to show the screenshot of the current result is the expected result . <code> StreamReader sr = new StreamReader ( client.GetStream ( ) ) ; StreamWriter sw = new StreamWriter ( client.GetStream ( ) ) ; string request = sr.ReadLine ( ) ; if ( request ! = null ) { //byte [ ] testData = Encoding.UTF8.GetBytes ( `` Test '' ) ; string [ ] tokens = request.Split ( `` `` ) ; try { FileInfo file = files [ tokens [ 1 ] ] ; byte [ ] fileBytes = File.ReadAllBytes ( file.FullName ) ; sw.WriteLine ( `` HTTP/1.0 200 OK\n '' ) ; sw.BaseStream.Write ( fileBytes , 0 , fileBytes.Length ) ; sw.Flush ( ) ; } catch { sw.WriteLine ( `` HTTP/1.0 404 OK\n '' ) ; sw.Write ( `` < h1 > Error 404 < /h1 > < p > The file you were looking for does not exist < /p > '' ) ; sw.Flush ( ) ; } } client.Close ( ) ;
C # How do you send a file via TCP for HTTP ?
C_sharp : I have found huge amounts of information ( ie , this ) on how to handle unexpected errors in ASP.NET , using the Page_Error and Application_Error methods as well as the customErrors directive in Web.config.However , my question is what is the best way to handle EXPECTED errors . For example , I have a page to display a record . Each record has a specific list of users who are allowed to see it . Since many users may have the `` View Records '' role that are not on said list , I have to write some code on the page to filter them.What are the best practices for handling this kind of error ? I can think of a few possibilities : Redirect to an error page.Put a label on every page called `` lblErrorText '' . Leave it blank unless there is an error.Raise an exception and let the standard error handling deal with it.This feels like a basic question and for that I apologize , but just about everything I 've found has been in reference to unexpected exceptions . It 's not that any of the above possibilities are hard to implement , but I 'd like to use a standard , recommended method if possible.NOTE : Thanks everyone for the answers . I want to clarify that users would NOT have the ability to click links to records they 're allowed allowed to view . This question is more in the interest of being defensive . For example , since the record ID is in the URL someone could potentially enter the ID of a forbidden record in the address bar . Or User A who is allowed might e-mail a link to User B who is not . It seems I may not be using the words `` exception '' and `` error '' in the correct way , but hopefully the scenario makes sense . <code> protected void Page_Load ( object sender , EventArgs e ) { var user = Membership.GetUser ( ) ; if ( ! CanUserViewThisRecord ( Request [ `` id '' ] , user.Username ) { // Display an error to the user that says , // `` You are not allowed to view this message '' , and quit . } else { // Display the page . } }
Displaying expected errors to users in ASP.NET
C_sharp : I 've got a DataGridView that is backed by a SortableBindingList as described by this article.This is essentially a BindingList whose Data source is a list of custom objects . The underlying custom objects are updated programatically.My SortableBindingList allows me to sort each column in Ascending or Descending order . I 've done this by overloading the ApplySortCore method This works well for sorting when the column header is clicked on but wo n't sort automatically when cell in that column is programatically updated.Has anyone else come up with a good solution for keeping a DataGridView sorted from programmatic updates of its underlying data source ? <code> protected override void ApplySortCore ( PropertyDescriptor prop , ListSortDirection direction )
Keeping a DataGridView autosorted
C_sharp : I have a generic class which could use a generic OrderBy argumentthe class is as followsThe orderBy could be of various typese.g . The goal is to make the orderBy an argument rather than bake it inany ideas ? <code> class abc < T > where T : myType { public abc ( ... .. , orderBy_Argument ) { ... } void someMethod ( arg1 , arg2 , bool afterSort = false ) { IEnumerable < myType > res ; if ( afterSort & & orderBy_Argument ! = null ) res = src.Except ( tgt ) .OrderBy ( ... . ) ; else res = src.Except ( tgt ) ; } } .OrderBy ( person = > person.FirstName ) .OrderBy ( person = > person.LastName ) .OrderBy ( person = > person.LastName , caseInsensitive etc )
Linq and order by
C_sharp : Given the following C # code : And its counterpart in VB.NET : It appears that VB.NET is able to correctly infer type of a = Object ( ) , while C # complains until the above is fixed to : Is there a way to auto-infer type in C # for the above scenario ? EDIT : Interesting observation after playing with different types in a C # sandbox - type is correctly inferred if all elements have common parent in the inheritance tree , and that parent is not an Object , or if elements can be cast into a wider type ( without loss of precision , for example Integer - > Double ) . So both of these would work : I think this behavior is inconsistent in C # , because all types inherit from Object , so it 's not a much different ancestor than any other type . This is probably a by-design , so no point to argue , but if you know the reason , would be interesting to know why . <code> var a = new [ ] { `` 123 '' , `` 321 '' , 1 } ; //no best type found for implicitly typed array Dim a = { `` 123 '' , `` 321 '' , 1 } 'no errors var a = new object [ ] { `` 123 '' , `` 321 '' , 1 } ; var a = new [ ] { 1 , 1.0 } ; //will infer double [ ] var a = new [ ] { new A ( ) , new B ( ) } ; //will infer A [ ] , if B inherits from A
Type inference in C # not working ?
C_sharp : I came across the following code , all in a single file/class . I 'm leaving out the details , its the construct I 'm interested in . Why are there two different declarations for the same class and how are they different ? What 's the purpose of the syntax for the second declaration ? <code> public abstract class MyClass { ... } public abstract class MyClass < TMyClass > : MyClass where TMyClass : MyClass < TMyClass > { ... }
What is this C # construct doing and why ? MyClass < TMyClass > : MyClass where
C_sharp : First time poster here , but I have been using stackoverflow this entire quarter to help me along in my intro to C # class . Generally , I can find what I 'm looking for if I look hard enough , but I have been unable to find anyone that has already answered my question.I have an assignment that wants me to display random numbers in a 5x10 array.I then need to calculate the sum of the numbers and the average , but I 'll worry about that later.Randomized numbers should be < 0 and < =100 . The console output should look something like thisjust with 10 rows instead of 5.However , my current code is listing the random numbers next to each other and wrapping lines once it reaches the end of the line like thisWhat can I do to get it to align correctly ? I have pretty much exhausted my ability to use format modifiers , so when you see { 0 , 5 } , that 's just my most recent attempt , but far from my only . I 'm extremely new to C # , so any advanced techniques would be out of the question , as I would n't understand how to properly use them . Any thoughts S.O. ? ! Hopefully this does n't screw with the code snippet ... . I know I could do some crap like this but that would get me a very poor score on the assignment . <code> x x x x xx x x x xx x x x xx x x x xx x x x x x x x x x x x x x x x x x x x x xx x x x x x x x x x x x x x x x xx x x x ... etc using System ; namespace DilleyHW7 { class Array2d { static void Main ( ) { const int ROWS = 10 ; const int COLS = 5 ; const int MAX = 100 ; int [ , ] numbers = new int [ 10 , 5 ] ; Random rand = new Random ( ) ; for ( int i = 0 ; i < ROWS ; ++i ) { for ( int j = 0 ; j < COLS ; ++j ) { numbers [ i , j ] = rand.Next ( 0 , 101 ) ; Console.Write ( `` { 0 , 5 } '' , numbers [ i , j ] ) ; } } } } } int [ , ] numbers = { { random.Next ( 1,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) } , { random.Next ( 1,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) } , { random.Next ( 1,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) } , { random.Next ( 1,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) } , { random.Next ( 1,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) , random.Next ( 0,100 ) } } ;
How to properly align a 5x10 2-d array with random data in console ?
C_sharp : This is the first time I face a problem like this . Not being this my profession but only my hobby , I have no previous references.In my program I have added one by one several functions to control a machine . After I added the last function ( temperature measurement ) , I have started experiencing problems on other functions ( approx . 8 of them running all together . The problem I am experiencing is on a chart ( RPM of a motor ) that is not related to this function but is affected by it . You see the difference between these two charts with and without the temperature measurement running . The real speed of the motor is the same in both charts but in the second one I loose pieces on the fly because the application slows down.Without the temperature function.With the temperature functionParticularly this function is disturbing the above control and I think is because the work load is becoming heavy for the application and or because I need sampling so there is some time waiting to get them : I am wondering if running this function on a different thread would solve the problem and how I can do that ? Or if there is a different way to solve the problem.Sample code will be appreciated.Update , added method call.This is how I call the method AddTThis is how I receive the data from the serial and pass it to the class that strips out unwonted chars and return values to the different variables.This is the class that strips out the unwonted chars and return the values.And this is how I manage the serial incoming data . Please do not laugh at me after seeing my coding . I do a different job and I am learning on my own . <code> private void AddT ( decimal valueTemp ) { sumTemp += valueTemp ; countTemp += 1 ; if ( countTemp > = 20 ) //take 20 samples and make average { OnAvarerageChangedTemp ( sumTemp / countTemp ) ; sumTemp = 0 ; countTemp = 0 ; } } private void OnAvarerageChangedTemp ( decimal avTemp ) { float val3 = ( float ) avTemp ; decimal alarm = avTemp ; textBox2.Text = avTemp.ToString ( `` F '' ) ; if ( alarm > 230 ) { System.Media.SoundPlayer player = new System.Media.SoundPlayer ( ) ; player.Stream = Properties.Resources.alarma ; player.Play ( ) ; timer4.Start ( ) ; } else { timer4.Stop ( ) ; panel2.BackColor = SystemColors.Control ; } } if ( b ! = `` '' ) { decimal convTemp ; //corrente resistenza decimal.TryParse ( b , out convTemp ) ; AddT ( convTemp ) ; }
Multithreading or something different
C_sharp : I 'm forwarding type definitions for our legacy support . I 'm using following syntax to do so : problem I 'm having is that I ca n't find correct syntax for generic type definitions ( it should be possible based on Eric Lippert 's post and many other places ) .What I would expect as working solution isAny idea how write that correctly please ? Thanks . <code> [ assembly : TypeForwardedTo ( typeof ( NamespaceA.TypeA ) ) ] [ assembly : TypeForwardedTo ( typeof ( NamespaceA.TypeA < T > ) ) ]
Forward generic type definition
C_sharp : I have a vertically and horizontally scrollable DataGridView on a form.I use virtual mode because the underlying datatable is huge.When I scroll right , if the last column is not fully shown in the view , then I see repeated calls to CellValueNeeded.How can I fix this ? My thoughts : Why is CellValueNeed being repeatedly called for a partially visible column anyway ? Perhaps I can fix the cause of this.Within CelValueNeeded - can I detect it is partially visible and return without processing ? Both `` Displayed '' and `` Visible '' are true when I check the cell values.My code : EDIT1 : After Digitalsa1nt 's answer I found a way to fix the issue . It is complicated because the first column is treated differently to the last column . AND it makes a difference if you are setting RowHeaders.In CellValueNeed above , I now return if the following function is true . <code> private void grid_Data_CellValueNeeded ( object sender , DataGridViewCellValueEventArgs e ) { Console.WriteLine ( `` CellValue : `` + e.RowIndex + `` `` + e.ColumnIndex ) ; if ( e.RowIndex > Grid.Rows.Count - 1 ) return ; DataGridView gridView = sender as DataGridView ; e.Value = Grid.Rows [ e.RowIndex ] [ e.ColumnIndex ] ; gridView.Rows [ e.RowIndex ] .HeaderCell.Value = ( e.RowIndex ) .ToString ( ) ; } private bool IsPartiallyVisible ( DataGridView gridView , DataGridViewCellValueEventArgs e ) { if ( gridView.FirstDisplayedScrollingColumnIndex == e.ColumnIndex ) { if ( gridView.FirstDisplayedScrollingColumnHiddenWidth ! = 0 ) { return true ; } } bool sameWidth = gridView.GetColumnDisplayRectangle ( e.ColumnIndex , false ) .Width == gridView.GetColumnDisplayRectangle ( e.ColumnIndex , true ) .Width ; return ! sameWidth ; }
Repeated calls to CellValueNeeded
C_sharp : I am trying to serialize a List to a file in C # with JSON.NET.I want to be able to add values to the list and serialize that change.I do not want to serialize the list all over again , since it can grow pretty big.Is something like that possible with JSON.NET ? this way it would only be possible to `` Reserialize '' the whole list , not add changes to the file . <code> using ( FileStream fs = File.Open ( @ '' c : \list.json '' , FileMode.CreateNew ) ) using ( StreamWriter sw = new StreamWriter ( fs ) ) using ( JsonWriter jw = new JsonTextWriter ( sw ) ) { jw.Formatting = Formatting.Indented ; JsonSerializer serializer = new JsonSerializer ( ) ; serializer.Serialize ( jw , list ) ; }
continuous serialization of a list with JSON.NET
C_sharp : Here 's the Lambda expression I am using to try and include the User table , which throws an error.The include statement gives this error The Include path expression must refer to a navigation property defined on the type . Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.The model in questionHow do I include the User table for the ProjectDoc of type Cover ? UPDATE : Per the answer . I updated the model for Cover to looks like this and removed the include that I said was causing the error . I can now get the data : <code> ICollection < Activity > activity = db.Activities .Include ( i = > i.Project.ProjectDoc.OfType < Cover > ( ) .Select ( v = > v.User ) ) .Where ( u = > u.UserID == WebSecurity.CurrentUserId ) .OrderByDescending ( d = > d.DateCreated ) .ToList ( ) ; public abstract class ProjectDoc { public int ProjectDocID { get ; set ; } public int ProjectID { get ; set ; } public string DocTitle { get ; set ; } public string Status { get ; set ; } public string Access { get ; set ; } public DateTime DateCreated { get ; set ; } public virtual ProjectDocAccess ProjectDocAccess { get ; set ; } public virtual Project Project { get ; set ; } public virtual ICollection < Comment > Comment { get ; set ; } public ICollection < ProjectDocVote > ProjectDocVote { get ; set ; } } public class Segment : ProjectDoc { public string Content { get ; set ; } } public class Cover : ProjectDoc { public string CoverURL { get ; set ; } public int UserID { get ; set ; } public User User { get ; set ; } } public class Cover : ProjectDoc { public string CoverURL { get ; set ; } public int UserID { get ; set ; } public virtual User User { get ; set ; } }
Include Derived Models Related Class
C_sharp : What I want to do is combine lambda syntax with `` params '' to carry out an action on a series of object.Let 's say I want to make a bunch of controls invisible.After a bit of fiddling I ended up with an extension method : and then I can create an action : and then call it : This is n't very nice syntax though - it feels horribly clumsy.I can create a method `` Apply '' in my base class : and then call it like this : But that means repeating the method in every base class I need it in , and I lose the advantage of type inference.Is there a less clumsy way of doing this ? Edit : The nicest method I 've seen so far is the fluent approach , which ( with a couple of tweaks ) would allow me to write : This is 91 characters , compared to 107 for using a simple `` foreach '' . Which leads me to believe that `` foreach '' might actually be the best approach after all ! <code> public static void On < T > ( this Action < T > actionToCarryOut , params T [ ] listOfThings ) { foreach ( var thing in listOfThings ) { actionToCarryOut ( thing ) ; } } Action < Control > makeInvisible = c = > c.Visible = false ; makeInvisible.On ( control1 , control2 , control3 , control4 ) ; protected void Apply < T > ( Action < T > action , params T [ ] appliedTo ) { foreach ( var item in appliedTo ) { action ( item ) ; } } Apply < Control > ( c = > c.Visible = false , control1 , control2 , control3 , ) ; Apply.Method ( ( Control c ) = > c.Visible = false ) .To ( control1 , control2 , control3 , control4 } ;
C # syntax for applying an action to a varying number of objects
C_sharp : I have the follwoing code and I would like to write it in a way that I have minimum lines of code and the work is done the same way . How can I do that ? <code> List < Category > categoryList = new List < Category > ( ) ; categoryList = Category.LoadForProject ( project.ID ) .ToList ( ) ; List < string > categories = new List < string > ( Categories ) ; IList < Category > currentCategories = Category.LoadForProject ( project.ID ) .ToList ( ) ; if ( currentCategories ! = null ) { foreach ( var existingCategories in currentCategories ) { if ( categories.Contains ( existingCategories.Name ) ) categories.Remove ( existingCategories.Name ) ; else existingCategories.Delete ( Services.UserServices.User ) ; } foreach ( string item in categories ) { Category category = new Category ( project , item.ToString ( ) ) ; category.Project = project ; category.Save ( ) ; } } List < string > priorities = new List < string > ( Priorities ) ; IList < Priority > currentPriorities = Priority.LoadForProject ( project.ID ) .ToList ( ) ; if ( currentPriorities ! = null ) { foreach ( var existingPriorities in currentPriorities ) { if ( priorities.Contains ( existingPriorities.Name ) ) priorities.Remove ( existingPriorities.Name ) ; else existingPriorities.Delete ( Services.UserServices.User ) ; } foreach ( string item in priorities ) { Priority priority = new Priority ( project , item.ToString ( ) ) ; priority.Project = project ; priority.Save ( ) ; } }
How can I avoid code duplication
C_sharp : I am reading some x and y coordinates from an XML file.The coordinates look like this 3.47 , -1.54 , .. and so on.When I assign the value to a double variable byThe Value becomes 3470.00Why is this the case ? <code> double x , y ; x = Convert.ToDouble ( reader [ `` X '' ] ) ; // X Value : 3.47
Why does Convert.ToDouble change my Value by factor 1000 ?
C_sharp : I want to create a copy my object in my DB with using Entity Frameworkfirst I got my `` Book '' from DBthen , I tried to add this object as a new objectAlso I trid to initilize EntityKey of Bookit didnt workIs there any way doing this without creating new Book and copy properties from old one ? Thanks <code> var entity1 = new testEntities ( ) ; var book= entity1.Books.First ( ) ; entity1.Dispose ( ) ; var entity2 = new testEntities ( ) ; book.Id = 0 ; entity2.SaveChanges ( ) ; entity2.Dispose ( ) ;
How to Add existing entity as a new Entity with Entity Framework
C_sharp : I am converting a codebase to C # 8 with nullable reference types . I came across the a method similar to the one in this question but async.T may be any type , including nullable reference types or nullable value types.To be clear , I understand WHY this method triggers a warning . What I 'd like to know is what annotations can be used to resolve it.I know I can use # nullable disable or default ( T ) ! , but I was hoping for something that 's less of a `` hammer '' .I know I ca n't use [ return : MaybNull ] because that would apply to the Task itself , not the T.Is there any other attribute/annotation I can apply to make the compiler happy , or is default ( T ) ! my only option ? <code> public async Task < T > GetAsync < T > ( ) { // sometimes returns default ( T ) ; = > warning CS8603 Possible null reference return }
Proper nullable annotation for async generic method that may return default ( T )
C_sharp : The BackgroundI have converted the C # code below ( found in TreeViewAdv file TreeColumn.cs ) into VB.net code using the converter found at DeveloperFusion.com . C # VBThe ProblemAccess to TreeColumn.TreeColumnConverter in this line of the C # code is fine . [ TypeConverter ( typeof ( TreeColumn.TreeColumnConverter ) ) , DesignTimeVisible ( false ) , ToolboxItem ( false ) ] However , VB.Net does not allow access to that member in the converted line : The error description reads : Aga.Controls.Tree.TreeColumn.TreeColumnConverter ' is not accessible in this context because it is 'Private ' . However , in both cases TreeColumn.TreeColumnConverter is declared Private.The Question ( s ) 1 . ) The Why . As this is a learning project for me , I would like to know WHY the scopes are acting differently among the two languages . This is the more important question among the 2 of them.2 . ) The How . What is the best way ( s ) to change the VB code to allow access of TreeColumnConverter to the identified line of code without opening up the scope to the point that it potentially creates naming confusions elsewhere ? I COULD just declare it Public , but I imagine there is a more correct approach to this.Things To Keep In Mind When Answering1 . ) I know that in VB.net Private members are not available external to the object in which they were declared . So telling me this will not be helpful and in my mind is not an answer . <code> using System ; // ... ( other using calls ) namespace Aga.Controls.Tree { [ TypeConverter ( typeof ( TreeColumn.TreeColumnConverter ) ) , DesignTimeVisible ( false ) , ToolboxItem ( false ) ] public class TreeColumn : Component { private class TreeColumnConverter : ComponentConverter { public TreeColumnConverter ( ) : base ( typeof ( TreeColumn ) ) { } public override bool GetPropertiesSupported ( ITypeDescriptorContext context ) { return false ; } } } //…Some , I believe , unrelated code } Imports System.Collections.Generic ‘ ... ( other Imports calls ) Namespace Aga.Controls.Tree < TypeConverter ( GetType ( TreeColumn.TreeColumnConverter ) ) , DesignTimeVisible ( False ) , ToolboxItem ( False ) > _ Public Class TreeColumn Inherits Component Private Class TreeColumnConverter Inherits ComponentConverter Public Sub New ( ) MyBase.New ( GetType ( TreeColumn ) ) End Sub Public Overrides Function GetPropertiesSupported ( ByVal context As ITypeDescriptorContext ) As Boolean Return False End Function End Class ‘ ... some , I believe , unrelated codeEnd Class
`` Private '' visibility modifier - how to handle differences when converting C # to VB ?
C_sharp : What I basically wish to do is design a generic interface that , when implemented , results in a class that can behave exactly like T , except that it has some additional functionality . Here is an example of what I 'm talking about : And this is all well and good , but in order to use CoolInt , I need to do something like this : I 'd much rather , in terms of assignment at least , that CoolInt works just like int . In other words : To achieve this , I added these two conversion operators to my CoolInt class : Works awesomely . Now , I would prefer it if I could add these two overloads to the interface , so that implementers of the interface are forced to implement these operators . The problem is , the prototypes of these operators refer directly to CoolInt.C # has a lot of `` placeholder '' names for things that are implicitly defined or have yet to be defined . The T that is conventionally used in generic programming is one example . I suppose the value keyword , used in Properties , is another . The `` this '' reference could be considered another . I am hoping that there 's another symbol I can use in my interface to denote `` the type of the class that is implementing this interface '' , e.g . `` implementer '' .Is this possible ? <code> public interface ICoolInterface < T > { T Value { get ; set ; } T DoSomethingCool ( ) ; } public class CoolInt : ICoolInterface < int > { private int _value ; public CoolInt ( int value ) { _value = value ; } public int Value { get { return _value ; } set { _value = value ; } } public int DoSomethingCool ( ) { return _value * _value ; // Ok , so that was n't THAT cool } } CoolInt myCoolInt = new CoolInt ( 5 ) ; int myInt = myCoolInt.Value ; CoolInt myCoolInt = 5 ; int myInt = myCoolInt ; public static implicit operator CoolInt ( int val ) { return new CoolInt ( val ) ; } public static implicit operator int ( CoolInt obj ) { return obj.Value ; } public static implicit operator implementer ( int val ) { return new IntVal ( val ) ; } public static implicit operator int ( implementer obj ) { return obj.Value ; }
C # Interfaces : Is it possible to refer to the type that implements the interface within the interface itself ?
C_sharp : To my surprise , this one compiles and runs : The method is public whereas the default value `` redirects '' to a constant private variable.My question : What is/was the idea behind this `` concept '' ? My understanding ( until today ) was , that something public can only be used if all other `` referenced '' elements are also public.Update : I just ILSpy-decompiled my class to find : So if the private constant as a default parameter is being done in e.g . a library , the user of the library still sees the default parameter . <code> class Program { static void Main ( ) { DoSomething ( ) ; } private const int DefaultValue = 2 ; // < -- Here , private . public static void DoSomething ( int value = DefaultValue ) { Console.WriteLine ( value ) ; } } static class Program { private static void Main ( ) { Program.DoSomething ( 2 ) ; } private const int DefaultValue = 2 ; public static void DoSomething ( int value = 2 ) { Console.WriteLine ( value ) ; } }
What 's the idea behind allowing private constant to be used as default parameters for public methods ?
C_sharp : What happens if I pass a data member by reference to a function , and while that function is running , the Garbage Collector starts running and moves the object containing the data member in memory ? How does the CLR make sure reference parameters do n't become invalid during Garbage Collection ? Are they adjusted just like class references ? <code> class SomeClass { int someDataMember ; void someMethod ( ) { SomeClass.someFunction ( ref someDataMember ) ; } static void someFunction ( ref int i ) { i = 42 ; int [ ] dummy = new int [ 1234567890 ] ; // suppose the Garbage Collector kicks in here i = 97 ; } }
passing data members by reference
C_sharp : I have a little C # problem . I have two classes ClassA and ClassB defined in this way : As you can see , ClassA has an instance of ClassB.The thing is , from a list of ClassA instances , I want to access to a list of the corresponding ClassB instances . I suppose it would look like this : The solution is probably obvious but I ca n't figure it out by myself.Any help would be appreciated ! <code> public class ClassA { private ClassB b ; ClassB B ; { get { return b ; } set { b = value ; } } } public class ClassB { /* some stuff */ } IList < ClassA > listA = ... ; IList < ClassB > listB = listA. ? ? ? .B ;
Class associations and lists
C_sharp : I was browsing the source of the PluralizationService when I noticed something odd . In the class there are a couple of private dictionaries reflecting different pluralisation rules . For example : What are the groups of four dashes in the strings ? I did not them see handled in the code , so they 're not some kind of a template . The only thing I can think of is that those are censored expletives ( 'ch -- -- is ' would be 'chassis ' ) , which in this case is actually hurting the readability . Did anyone else come across this ? If I were to be interested in the actual full list , how would I view it ? <code> private string [ ] _uninflectiveWordList = new string [ ] { `` bison '' , `` flounder '' , `` pliers '' , `` bream '' , `` gallows '' , `` proceedings '' , `` breeches '' , `` graffiti '' , `` rabies '' , `` britches '' , `` headquarters '' , `` salmon '' , `` carp '' , `` -- -- '' , `` scissors '' , `` ch -- -- is '' , `` high-jinks '' , `` sea-bass '' , `` clippers '' , `` homework '' , `` series '' , `` cod '' , `` innings '' , `` shears '' , `` contretemps '' , `` jackanapes '' , `` species '' , `` corps '' , `` mackerel '' , `` swine '' , `` debris '' , `` measles '' , `` trout '' , `` diabetes '' , `` mews '' , `` tuna '' , `` djinn '' , `` mumps '' , `` whiting '' , `` eland '' , `` news '' , `` wildebeest '' , `` elk '' , `` pincers '' , `` police '' , `` hair '' , `` ice '' , `` chaos '' , `` milk '' , `` cotton '' , `` pneumonoultramicroscopicsilicovolcanoconiosis '' , `` information '' , `` aircraft '' , `` scabies '' , `` traffic '' , `` corn '' , `` millet '' , `` rice '' , `` hay '' , `` -- -- '' , `` tobacco '' , `` cabbage '' , `` okra '' , `` broccoli '' , `` asparagus '' , `` lettuce '' , `` beef '' , `` pork '' , `` venison '' , `` mutton '' , `` cattle '' , `` offspring '' , `` molasses '' , `` shambles '' , `` shingles '' } ;
What are the groups of four dashes in the .NET reference source code ?
C_sharp : Is there a mechanism for the new c # 8 using statement to work without a local variable ? Given ScopeSomething ( ) returns a IDisposable ( or null ) ... Previously : However in C # 8 with the using statement , it requires a variable name : The _ here is not treated as a discard.I would have expected this to have worked : <code> using ( ScopeSomething ( ) ) { // ... } using var _ = ScopeSomething ( ) ; using ScopeSomething ( ) ;
using statement in C # 8 without a variable
C_sharp : What happens when I add a method to existing delegate ? I mean when I added the method1 to del , del holds the address of method1 . When I add method2 afterwards , del still points to Method1 and Method 2 address is inserted on the bottom of it . Does n't this mean I changed the delegate ? If I can change this why in the books it is told `` delegates are immutable '' ? <code> MyDel del = method1 ; del += method2 ; del += method3 ;
Delegates are immutable but how ?
C_sharp : I 'm running into a problem where as I have an implied unsigned hexadecimal number as a string , provided from user input , that needs to be converted into a BigInteger.Thanks to the signed nature of a BigInteger any input where the highest order bit is set ( 0x8 / 1000b ) the resulting number is treated as negative . This issue however ca n't be resolved by simply checking the sign bit and multiplying by -1 or getting the absolute value due to ones 's complement which will not respect the underlying notation e.g . treating all values 0xF* as a -1.As follows are some example input/outputWhat is the proper way to construct a BigInteger from an implied unsigned hexadecimal string ? <code> var style = NumberStyles.HexNumber | NumberStyles.AllowHexSpecifier ; BigInteger.TryParse ( `` 6 '' , style ) == 6 // 0110 binBigInteger.TryParse ( `` 8 '' , style ) == -8 // 1000 binBigInteger.TryParse ( `` 9 '' , style ) == -7 // 1001 binBigInteger.TryParse ( `` A '' , style ) == -6 // 1010 bin ... BigInteger.TryParse ( `` F '' , style ) == -1 // 1111 bin ... BigInteger.TryParse ( `` FA '' , style ) == -6 // 1111 1010 binBigInteger.TryParse ( `` FF '' , style ) == -1 // 1111 1111 bin ... BigInteger.TryParse ( `` FFFF '' , style ) == -1 // 1111 1111 1111 1111 bin
What is the proper way to construct a BigInteger from an implied unsigned hexadecimal string ?
C_sharp : In my WPF application I have a sort of node graph . I have added a ContextMenu to these nodes , which appears when I right-click on stuff and so on.The commands in the context menu come from a Service ( Microsoft.Practices.ServiceLocation.ServiceLocator ) with DelegateCommands , and those commands are updated with RaiseCanExecuteChanged ( ) . The node that was right-clicked on is passed to this command service , which is used in the various CanExecute methods for the commands.The nodes all have some properties which are used in these conditions , like whether it can be renamed or deleted , etc.in IMenuCommandService : My ContextMenu ( inside a DataTrigger & Setter ) : My problem is that when I right click one of these nodes , the context menu that is displayed looks like it was configured for the previous node selected . Like if I right-click a deleteable node and then a non-deleteable node , the `` Delete '' command on the context menu will still be clickable . ( If I then right-click the non-deleteable node , the context menu will then be correct and the `` Delete '' command is greyed out . ) So it looks like there 's some sort of delay from when the changes made after RaiseCanExecuteChanged ( ) is actually there for the contextmenu to `` pick up '' . I could do a crude fix and only show the contextmenu after they have been updated ( i.e . their CanExecute methods have been called ) , but I 'd like to keep the two parts relatively separate.Is there something obvious I 'm missing , am I going about this in the wrong way , or does anyone have any other suggestions ? Thanks <code> private void ContextMenu_ContextMenuOpening ( object sender , RoutedEventArgs e ) { ServiceLocator.Current.GetInstance < IMenuCommandService > ( ) .ReloadICommandConditions ( ) ; } public void ReloadICommandConditions ( ) { ( ( DelegateCommand < Node > ) MyCommand ) .RaiseCanExecuteChanged ( ) ; } < ContextMenu > < MenuItem Header= '' Rename '' Command= '' { Binding MenuCommandService.Rename } '' CommandParameter= '' { Binding Node } '' / > < MenuItem Header= '' Delete '' Command= '' { Binding MenuCommandService.Delete } '' CommandParameter= '' { Binding Node } '' / > ... < /ContextMenu >
RaiseCanExecuteChanged delay with ContextMenu
C_sharp : I am trying to write the following : I would like to write a method `` A '' which takes as parameter another method `` B '' as well as an unknown number of parameters for this method B . ( params object [ ] args ) . Now , inside method A i would like to make a call to B with the parameters args . B will now return an object which I would like A to return as well.This all sounds a bit strange , therefore I will add some example code : The problem is , that Func does not work like that . Does anyone know a way of doing this ? Regards , Christian <code> public object A ( Func < object > B , params object [ ] args ) { object x = B.Method.Invoke ( args ) ; return x ; }
C # Method that executes a given Method
C_sharp : I was surprised that there would be any runtime difference between these two delegates ( fn1 and fn2 ) : But apparently the second lambda is treated like an instance method , because its Target property is non-null . And it was treated differently before I switched to Visual Studio 2015 ( in VS2012 , I am pretty sure it was treated as a static method ) .Is there a reason why a lambda with no closures is treated as a closed delegate ( i.e . an instance method ) in C # ? I thought perhaps it 's the debugger adding some stuff , but it also happens in release builds . ( Clarification ) The point is , I had a method like this which created a generic delegate for quickly converting from enums to ints ( without boxing ) : and it did n't work in Roslyn anymore , because the `` instance '' lambda became incompatible with the delegate signature . So I had to use a static method instead , no big deal . But what worries me is that this was impossible to catch during compile-time . This thread describes similar issues , btw , now that I searched for `` Roslyn delegates '' . <code> static int SomeStaticMethod ( int x ) { return x ; } // fn1.Target == null in this caseFunc < int , int > fn1 = SomeStaticMethod ; // fn2.Target ! = null in this caseFunc < int , int > fn2 = x = > x ; private static Func < int , TEnum > CreateIntToEnumDelegate ( ) { Func < int , int > lambda = x = > x ; return Delegate.CreateDelegate ( typeof ( Func < int , TEnum > ) , lambda.Method ) as Func < int , TEnum > ; }
Lambda treated as a closed delegate in Roslyn
C_sharp : When running We see a difference when using different framework versions.vsAlso why would I see different a NumberFormat.CurrencyPositivePattern between machines . Is it framework specific or related to the OS ? 40,00 kr . vs kr . 20,00 <code> var x = 10.0M ; Console.WriteLine ( typeof ( Program ) .Assembly.ImageRuntimeVersion ) ; var culture = System.Globalization.CultureInfo.GetCultureInfo ( `` da-DK '' ) ; Console.WriteLine ( culture.NumberFormat.CurrencyPositivePattern ) ; Console.WriteLine ( x.ToString ( `` C '' , culture ) ) ; v2.0.50722kr 10,00 v4.0.30319310,00 kr .
What controls the CurrencyPositivePattern in .NET
C_sharp : I want to create a wrapper around this existing helper : How can I create a helper to wrap this and add a parameter to it ? My Controller has a property : I want to somehow reference this value from my controller and use it like : How can I do this ? Is the only way to add IsAdmin to my ViewModel ? <code> @ Content.Url ( `` ... '' ) public bool IsAdmin { get ; set ; } @ MyContent.Url ( `` ... '' , IsAdmin )
How to create a wrapper helper around Url.Content helper function ?
C_sharp : I have static e paper but i want to develop dynamic e-paper like below urlhttps : //epaper.dawn.com/ ? page=15_04_2019_001I have no idea to start e paper dynamic below is my whole html codei am not getting any idea to implement dynamic , i have to take repeater control or grid view control to achieve dynamic e paper . How to handle MAP and image redirection . <code> < ! doctype html > < html > < head > < meta charset= '' utf-8 '' > < meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge , chrome=1 '' > < meta name= '' viewport '' content= '' width=device-width , initial-scale=1 , shrink-to-fit=no '' > < title > q Times < /title > < link rel= '' stylesheet '' href= '' css/main.css '' > < link href= '' https : //www.jqueryscript.net/css/jquerysctipttop.css '' rel= '' stylesheet '' type= '' text/css '' > < style > body { background-color : # fafafa ; min-height : 100vh ; } .container { margin : 200px auto ; max-width : 600px ; } < /style > < script src= '' jquery.min.js '' > < /script > < script src= '' jquery.maphilight.min.js '' > < /script > < script > $ ( document ) .ready ( function ( ) { $ ( `` # prev-img , '' ) .click ( function ( ) { //alert ( $ ( ' # show-img ' ) .attr ( 'src ' ) ) ; var x= $ ( ' # show-img ' ) .attr ( 'src ' ) ; if ( x=='images/1.jpg ' ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper '' } else if ( x=='images/2.jpg ' ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper1 '' } } ) ; } ) < /script > < script > $ ( document ) .ready ( function ( ) { $ ( `` # next-img , '' ) .click ( function ( ) { //alert ( $ ( ' # show-img ' ) .attr ( 'src ' ) ) ; var x= $ ( ' # show-img ' ) .attr ( 'src ' ) ; if ( x=='images/1.jpg ' ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper '' } else if ( x=='images/2.jpg ' ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper1 '' } } ) ; } ) < /script > < script type= '' text/javascript '' > $ ( function ( ) { $ ( `` .map '' ) .maphilight ( ) $ ( `` .icon-right , .icon-left , # small-img-roll img '' ) .click ( function ( ) { $ ( `` div.map img '' ) .css ( `` opacity '' , 1 ) ; $ ( `` .map '' ) .maphilight ( ) < ! -- var x = document.getElementById ( `` 1 '' ) .useMap = `` # enewspaper '' ; -- > var value = $ ( this ) .attr ( `` usemap '' ) if ( value==1 ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper '' var x = document.getElementById ( `` show-img '' ) .useMap ; $ ( `` .map '' ) .maphilight ( ) } else if ( value==2 ) { document.getElementById ( `` show-img '' ) .useMap= '' # enewspaper1 '' var x = document.getElementById ( `` show-img '' ) .useMap ; $ ( `` .map '' ) .maphilight ( ) } } ) } ) < /script > < /head > < body > < div class= '' container '' style= '' margin-top:0px '' > < ! -- < div class= '' show '' href= '' images/1.png '' usemap= '' # enewspaper '' > -- > < img src= '' images/1.jpg '' id= '' show-img '' class= '' map '' usemap= '' # enewspaper '' > < map name= '' enewspaper '' > < area shape= '' rect '' alt= '' '' title= '' '' coords= '' 34,136,562,221 '' href= '' '' target= '' '' / > < area shape= '' rect '' alt= '' '' title= '' '' coords= '' 372,229,574,468 '' href= '' www.google.com '' target= '' '' / > < area shape= '' rect '' alt= '' '' title= '' '' coords= '' 104,227,368,469 '' href= '' www.fb.com '' target= '' _New '' / > < area shape= '' rect '' alt= '' '' title= '' '' coords= '' 105,472,230,677 '' href= '' www.kk.com '' target= '' '' / > < /map > < map name= '' enewspaper1 '' > < area shape= '' rect '' alt= '' '' title= '' '' coords= '' 34,136,562,221 '' href= '' '' target= '' '' / > < /map > < div class= '' small-img '' > < img src= '' images/online_icon_right @ 2x.png '' class= '' icon-left '' alt= '' '' id= '' prev-img '' > < div class= '' small-container '' > < div id= '' small-img-roll '' > < img src= '' images/1.jpg '' class= '' show-small-img '' alt= '' 1 '' usemap= '' 1 '' > < img src= '' images/2.jpg '' class= '' show-small-img '' alt= '' 2 '' usemap= '' 2 '' > < /div > < /div > < img src= '' images/online_icon_right @ 2x.png '' class= '' icon-right '' alt= '' '' id= '' next-img '' > < /div > < /div > < /div > < script src= '' scripts/zoom-image.js '' > < /script > < script src= '' scripts/main.js '' > < /script > < /body >
Trying to make epaper dynamic using C # asp.net web form
C_sharp : I do n't understand why it 's working ... The IL code : It compiles to bool Object.Equals ( Object , Object ) , but why ? <code> class Program { static void Main ( string [ ] args ) { IComparable.Equals ( 12 , 3 ) ; } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 21 ( 0x15 ) .maxstack 8 IL_0000 : nop IL_0001 : ldc.i4.s 12 IL_0003 : box [ mscorlib ] System.Int32 IL_0008 : ldc.i4.3 IL_0009 : box [ mscorlib ] System.Int32 IL_000e : call bool [ mscorlib ] System.Object : :Equals ( object , object ) IL_0013 : pop IL_0014 : ret } // end of method Program : :Main
IComparable magic - why it 's a valid statement ?
C_sharp : why does n't the element get swappedeven if the parameter is without a ref modifier the array does n't change.a copy of the reference is passed as a parameter right ? <code> public static void SwapArray ( int [ , ] arr ) { for ( int i = 0 ; i < arr.GetLength ( 0 ) ; i++ ) { for ( int j = 0 ; j < arr.GetLength ( 0 ) ; j++ ) { int temp = arr [ i , j ] ; arr [ i , j ] = arr [ j , i ] ; arr [ j , i ] = temp ; } } }
basic c # question
C_sharp : I am going through the Head First C # book and I ca n't figure out why they used the following way to create a property . It just seems inconsistent with the convention I 'm seeing everywhere else and in the book itself too . I understand that the pattern for creating properties is : Based on the above pattern I would have written my code like this : In the book it is presented like the following : Both codes work just fine in the program . What is the best practice to create such properties ? Is the decimal totalCost inside the property private ? If so , why is it not declared before creating the property instead ? Also , what is the point of creating two lines of code : when you can accomplish the exact same thing by writing : <code> private int myVar ; public int MyProperty { get { return myVar ; } set { myVar = value ; } } private decimal cost ; public decimal Cost { get { cost = CalculateCostOfDecorations ( ) + ( CalculateCostOfBeveragesPerPerson ( ) + CostOfFoodPerPerson ) * NumberOfPeople ; if ( HealthyOption ) { cost *= .95M ; } return cost ; } } public decimal Cost { get { decimal totalCost = CalculateCostOfDecorations ( ) ; totalCost += ( CalculateCostOfBeveragesPerPerson ( ) + CostOfFoodPerPerson ) *NumberOfPeople ; if ( HealthyOption ) { totalCost *= .95M ; } return totalCost ; } } decimal totalCost = CalculateCostOfDecorations ( ) ; totalCost += ( CalculateCostOfBeveragesPerPerson ( ) + CostOfFoodPerPerson ) *NumberOfPeople ; cost = CalculateCostOfDecorations ( ) + ( CalculateCostOfBeveragesPerPerson ( ) + CostOfFoodPerPerson ) * NumberOfPeople ;
Head First C # : strange way to create a read-only property
C_sharp : I have an application where you can select between different objects in a ListBox . When you select an object , it changes the viewmodel for a control . The control utlizes the Timeline Control from CodePlex , and because of this , I have the StartDate and EndDate for the timeline data bound to ViewModel . When the ViewModel is changed out , I sometimes get an error : This only occurs when I go from a later date to an earlier date . I am pretty sure that is due to the way the Properties are automatically updated to the view . This is the relevant XAML.The ViewModel has this : Is there a way around this problem ? Is there a way to tell WPF which order the parameters within an object should be updated ? Update : I ended up using a variation of @ colinsmith 's response : <code> ArgumentOutOfRangeException : MaxDateTime can not be less then MinDateTime MaxDateTime= '' { Binding Path=RecordingEnd } '' MinDateTime= '' { Binding Path=RecordingStart } '' CurrentDateTime= '' { Binding Path=CurrentDateTime , Mode=TwoWay } '' private int myObjectIndex ; public int MyObjectIndex { get { return myObjectIndex ; } set { myObjectIndex = value ; OnPropertyChanged ( `` MyObjectIndex '' ) ; MyObject = MyObjects [ myObjectIndex ] ; } } private MyObjectViewModel myObject=new MyObjectViewModel ( ) ; public MyObjectViewModel MyObject { get { return myObject ; } set { myObject= value ; OnPropertyChanged ( `` MyObject '' ) ; } } public MyObjectViewModel MyObject { get { return myObject ; } set { myObject= new MyObjectViewModel ( ) ; OnPropertyChanged ( `` MyObject '' ) ; myObject= value ; OnPropertyChanged ( `` MyObject '' ) ; } }
OnPropertyChange Firing Order
C_sharp : Is this kind of if-testing necessary when removing an item ? And , what about this test ? <code> if ( _items.Contains ( item ) ) { _items.Remove ( item ) ; } if ( ! _items.Contains ( item ) ) { _items.Add ( item ) ; }
C # List < T > Contains test
C_sharp : The code below is part of authorization . I am trying to mentally imaging what it actually does but could not somehow . Could anyone explain this lambda expression to me ? Thanks ! Edit : IsAuthorized is a delegate type . The previous programmer who code this seems want to keep it secret by putting delegate to the end of cs file.The actual code is : <code> IsAuthorized = ( ( x , y ) = > x.Any ( z = > y.Contains ( z ) ) ) ; public delegate bool IsAuthorized ( IEnumerable < Int32 > required , IEnumerable < Int32 > has ) ; IsAuthorized = ( ( x , y ) = > x.Any ( z = > y.Contains ( z ) ) ) ;
Could anyone explain this lambda expression to me ? It 's kind getting me crazy
C_sharp : Like there are many Applications which are just basic but you can have install add-ins for it which extends its functionality in that Application . For example : How do they design such applications and how does the application accept the module and how can it automatically integrate.Secondly I do not know if the above process is generic or some language or tool dependent . Can we make such application in WPF or Winforms ? <code> Fire Bug in Mozilla Firefox .
Designing Application that can accept add ins
C_sharp : I 've simple Linq2Sql query : The problem is that it seems that new SomeLinq2SqlEntity ( ) is executed only once for the sequence , so all instances of MyViewModelClass in result of the query share the link to one object.Update : Here is how I quickly check it : Using debugger I can check that MyField was set to 10 in all instances.When I replace LINQ query with foreach , it works as expected : I have n't found the root of the problem , but the post marked as asnwer provides good workaround . Check this asnwer for the detailed description : `` new '' inside concrete type projection is only called once <code> var result = from t in MyContext.MyItems select new MyViewModelClass ( ) { FirstProperty = t , SecondProperty = new SomeLinq2SqlEntity ( ) } result [ 0 ] .SecondProperty.MyField = 10 ; var result = from t in MyContext.MyItems select t ; var list = new List < MyViewModelClass > ( ) ; foreach ( var item in result ) { list.add ( new MyViewModelClass ( ) { FirstProperty = item , SecondProperty = new SomeLinq2SqlEntity ( ) } ) ; }
`` new '' inside concrete type projection is only called once
C_sharp : Does Linq use any sorting or other mechanisms to make a group join more efficient so it does n't have to loop through an entire collection for every unmatched item ? In other words , Is this : more efficient than this : <code> var x = listA.GroupJoin ( listB , a = > a.prop , b = > b.prop , ( a , b ) = > new { a , b } ) .Where ( ! x.b.Any ( ) ) .Select ( x = > x.a ) ; var x = listA.Where ( a = > listB.All ( b = > b.prop ! = a.prop ) ) ;
Efficiency of Linq GroupJoin vs. Linq All in Select
C_sharp : We 've got a slight performance issue in a section of code that 's using LINQ and it 's raised a question about how LINQ works in terms of lookupsMy question is this ( please note that I have changed all the code so this is an indicative example of the code , not the real scenario ) : GivenIf I had a list of say 100k Person objects and then a list of dates , say 1000 , and I ran this code : The resultant code would be an iteration of:100k ( the loop that needs to be done to find the users with the organisationID 123 ) multiplied by1000 ( the amount of dates in the list ) multiplied byx ( the amount of users who have the organisationID 123 to be checked against for the date ) This is a lot of iterations ! If I changed the code the personBirthdays to this : This should remove the 100k as a multiple by , and just do it once ? So you would have 100k + ( 1000 * x ) instead of ( 100k * 1000 * x ) .The question is that this seems too easy , and I 'm sure the LINQ is doing something clever somewhere that should mean that this does n't happen.If no one answers , I 'll run some tests and report back.Clarity update : We 're not considering Database lookups , the personList object is an In Memory list object . This all LINQ-to-Objects . <code> public class Person { int ID ; string Name ; DateTime Birthday ; int OrganisationID ; } var personBirthdays = from Person p in personList where p.OrganisationID = 123 select p.Birthday ; foreach ( DateTime d in dateList ) { if ( personBirthdays.Contains ( d ) ) Console.WriteLine ( string.Format ( `` Date : { 0 } has a Birthday '' , d.ToShortDateString ( ) ) ) ; } List < DateTime > personBirthdays = ( from Person p in personList where p.OrganisationID = 123 select p.Birthday ) .ToList ( ) ;
Does this LINQ code perform multiple lookups on the original data ?
C_sharp : Suppose we had the following : I am using Autofac to register all of my components that implement IFoo : When I later resolve my dependencies with : I should get all of the classes that implement IFoo except the contract class ( es ) . How do I prevent all of my contract classes from resolving without moving them to a separate assembly entirely ? I can do something like : But I would need to do this for each component registration . Something that affects all registrations would be nicer . Is it possible to have a global exclusion on types resolved from Autofac if they have the ContractClassForAttribute attribute ? <code> [ ContractClass ( typeof ( ContractClassForIFoo ) ) ] public interface IFoo { int DoThing ( string x ) ; } public class Foo : IFoo { ... } [ ContractClassFor ( typeof ( IFoo ) ) ] public class ContractClassForIFoo : IFoo { public int DoThing ( string x ) { Contract.Requires < ArgumentNullException > ( x ! = null ) ; return 0 ; } } builder.RegisterAssemblyTypes ( ThisAssembly ) .As < IFoo > ( ) ; var dependencies = container.Resolve < IFoo [ ] > ( ) ; builder.RegisterAssemblyTypes ( ThisAssembly ) .Where ( t= > t.GetCustomAttribute < ContractClassForAttribute > ( ) == null ) .As < IFoo > ( ) ;
Autofac and Contract classes
C_sharp : Here is my code which is used widely in project , and I 'm wondering can I refactor this somehow so I might avoid == null checks all the time ? Thanks guysCheers <code> ActiveCompany = admin.Company == null ? false : admin.Company.Active
How could I avoid == null checking ?
C_sharp : I have a simple object that looks like this : I tried this code I found somewhere on the net : But somehow the returning byte array has a size of 248 bytes.I would expect it to be 4 bytes x 4 fields = 16 bytes.QUESTION : What 's the cleanest way to convert a fixed object into a byte array ? And should the resulting array be 16 bytes in size in this case ? <code> public class Foo { public UInt32 One { get ; set ; } public UInt32 Two { get ; set ; } public UInt32 Three { get ; set ; } public UInt32 Four { get ; set ; } } public byte [ ] ObjectToByteArray ( Object obj ) { MemoryStream fs = new MemoryStream ( ) ; BinaryFormatter formatter = new BinaryFormatter ( ) ; formatter.Serialize ( fs , obj ) ; byte [ ] rval = fs.ToArray ( ) ; fs.Close ( ) ; return rval ; }
Fixed Object to Byte Array
C_sharp : Consider the following code ( for the sake of this test , it does n't do anything of particular use - it 's just to demonstrate the error that occurs ) I want to wrap Dictionary < string , dynamic > using inheritance : Here is the examle above using this derived class : This happens ... Any ideas on what is causing the issue , or how to solve it ? <code> Dictionary < string , dynamic > d = new Dictionary < string , dynamic > ( ) { { `` a '' , 123 } , { `` b '' , Guid.NewGuid ( ) } , { `` c '' , `` Hello World '' } } ; d.Where ( o = > o.Key.Contains ( `` b '' ) ) .ForEach ( i = > Console.WriteLine ( i.Value ) ) ; //retuns the Guid value , as expected . public class CustomDictionary : Dictionary < string , dynamic > { } CustomDictionary d = new CustomDictionary ( ) { { `` a '' , 123 } , { `` b '' , Guid.NewGuid ( ) } , { `` c '' , `` Hello World '' } } ; d.Where ( o = > o.Key.Contains ( `` b '' ) ) .ForEach ( i = > Console.WriteLine ( i.Value ) ) ;
C # compilation error with LINQ and dynamic inheritance
C_sharp : I have the following code : and when I run the test `` TestFoo ( ) '' , the console output is `` Foo - string '' . How does the compiler decide which method to call ? <code> [ TestMethod ] public void TestFoo ( ) { Foo ( null ) ; } private void Foo ( object bar ) { Console.WriteLine ( `` Foo - object '' ) ; } private void Foo ( string bar ) { Console.WriteLine ( `` Foo - string '' ) ; }
How does the compiler choose which method to call when a parameter type is ambiguous ?
C_sharp : Basically , is it better practice to store a value into a variable at the first run through , or to continually use the value ? The code will explain it better : or <code> TextWriter tw = null ; if ( ! File.Exists ( ConfigurationManager.AppSettings [ `` LoggingFile '' ] ) ) { // ... tw = File.CreateText ( ConfigurationManager.AppSettings [ `` LoggingFile '' ] ) ; } TextWriter tw = null ; string logFile = ConfigurationManager.AppSettings [ `` LoggingFile '' ] .ToString ( ) ; if ( ! File.Exists ( logFile ) ) { // ... tw = File.CreateText ( logFile ) ; }
Read a value multiple times or store as a variable first time round ?
C_sharp : I have the following code in my .Net 4 app : This givens me an ensures unproven warning at compile time : What is going on ? This works fine if S is an integer . It also works if I change the Ensure to S == Contract.OldValue ( S + `` 1 '' ) , but that 's not what I want to do . <code> static void Main ( string [ ] args ) { Func ( ) ; } static string S = `` 1 '' ; static void Func ( ) { Contract.Ensures ( S ! = Contract.OldValue ( S ) ) ; S = S + `` 1 '' ; } warning : CodeContracts : ensures unproven : S ! = Contract.OldValue ( S )
Why is this string-based Contract.Ensure call unproven ?
C_sharp : i have a path data that i coppy it from syncfusion program.i have a path with that data in my page and want to animate my object exact on path way ( in mid of path line ) but the problem is the object move on outline ( surroundings ) of path .here is code : Edit 1 : my animation go wrong way . i want my Rectangle move exact Inside and in middle of path line . see code in your pc u will see the problem .my question is how fix that problem ? Edit 2 : i change the animation with DoubleAnimationUsingPath same resultEdit 3 : <code> < Canvas ClipToBounds= '' False '' Margin= '' 435,58,279,445 '' Width= '' 70 '' Height= '' 70 '' > < Path Name= '' pp '' Data= '' M29.073618888855,0C29.1124091148376,1.1444091796875E-05 29.1515617370605,0.00176620483398438 29.1909990310669,0.00532913208007813 29.810998916626,0.0533294677734375 30.3119988441467,0.530315399169922 30.3919982910156,1.14829635620117L30.5836410522461,2.65130615234375 31.2817029953003,8.12605285644531 34.8569983541965,36.1663000583649 38.6119983196259,11.4410037994385C38.6989989280701,10.8670196533203 39.1539988517761,10.4180335998535 39.7279987335205,10.3390350341797 40.3039989471436,10.2600383758545 40.8659987449646,10.5700283050537 41.1039986610413,11.0990142822266L44.5239992141724,18.6847972869873 62.6889991760254,18.6847972869873C63.4129981994629,18.6847972869873 63.9999980926514,19.2727813720703 63.9999980926514,19.9957599639893 63.9999980926514,20.720739364624 63.4129981994629,21.3077239990234 62.6889991760254,21.3077239990234L43.6779985427856,21.3077239990234C43.1629986763,21.3077239990234,42.6949987411499,21.004732131958,42.4809985160828,20.5357456207275L40.5379986763,16.2248687744141 36.0409992933273,45.8410243988037C35.9439988136292,46.4820065498352,35.3929988443851,46.9559931755066,34.7459992468357,46.9559926986694L34.729998499155,46.9559926986694C34.0749988555908,46.9479932785034,33.5279988050461,46.4590072631836,33.4449987411499,45.8100252151489L28.5969982147217,7.7971076965332 19.7799987792969,38.5482323169708C19.6119985580444,39.1362158469856 19.0699996948242,39.5222048461437 18.4459991455078,39.4962055683136 17.8359985351563,39.4622065722942 17.3289985656738,39.0092194601893 17.2269992828369,38.4062369465828L13.6579990386963,17.2688388824463 10.7719993591309,23.3446655273438C10.5559997558594,23.8016519546509,10.0949993133545,24.0936441421509,9.58799934387207,24.0936441421509L1.31099700927734,24.0936441421509C0.587997436523438,24.0936441421509 0,23.5056610107422 0,22.7826805114746 0,22.0577011108398 0.587997436523438,21.4717178344727 1.31099700927734,21.4717178344727L8.75799942016602,21.4717178344727 13.0749988555908,12.3859767913818C13.3199996948242,11.8689918518066 13.8699989318848,11.57200050354 14.4389991760254,11.6499977111816 15.0059986114502,11.7299957275391 15.4579982757568,12.1669826507568 15.5519981384277,12.7309665679932L18.8509979248047,32.2744116783142 27.8319988250732,0.952301025390625C27.9913740158081,0.391693115234375,28.4917645454407 , -0.000171661376953125,29.073618888855,0z '' Stretch= '' Uniform '' Fill= '' White '' Width= '' 70 '' Height= '' 70 '' StrokeThickness= '' 0 '' / > < Rectangle Fill= '' # FFFF4600 '' RenderTransformOrigin= '' 0.5,0.5 '' Width= '' 4 '' Height= '' 4 '' Canvas.Top= '' 4 '' > < Rectangle.RenderTransform > < TransformGroup > < MatrixTransform x : Name= '' tt '' > < MatrixTransform.Matrix > < Matrix / > < /MatrixTransform.Matrix > < /MatrixTransform > < /TransformGroup > < /Rectangle.RenderTransform > < Rectangle.Triggers > < EventTrigger RoutedEvent= '' FrameworkElement.Loaded '' > < BeginStoryboard > < Storyboard > < MatrixAnimationUsingPath Duration= '' 0:0:10 '' Storyboard.TargetName= '' tt '' Storyboard.TargetProperty= '' Matrix '' AutoReverse= '' True '' DoesRotateWithTangent= '' True '' > < MatrixAnimationUsingPath.PathGeometry > < PathGeometry Figures= '' M29.073618888855,0C29.1124091148376,1.1444091796875E-05 29.1515617370605,0.00176620483398438 29.1909990310669,0.00532913208007813 29.810998916626,0.0533294677734375 30.3119988441467,0.530315399169922 30.3919982910156,1.14829635620117L30.5836410522461,2.65130615234375 31.2817029953003,8.12605285644531 34.8569983541965,36.1663000583649 38.6119983196259,11.4410037994385C38.6989989280701,10.8670196533203 39.1539988517761,10.4180335998535 39.7279987335205,10.3390350341797 40.3039989471436,10.2600383758545 40.8659987449646,10.5700283050537 41.1039986610413,11.0990142822266L44.5239992141724,18.6847972869873 62.6889991760254,18.6847972869873C63.4129981994629,18.6847972869873 63.9999980926514,19.2727813720703 63.9999980926514,19.9957599639893 63.9999980926514,20.720739364624 63.4129981994629,21.3077239990234 62.6889991760254,21.3077239990234L43.6779985427856,21.3077239990234C43.1629986763,21.3077239990234,42.6949987411499,21.004732131958,42.4809985160828,20.5357456207275L40.5379986763,16.2248687744141 36.0409992933273,45.8410243988037C35.9439988136292,46.4820065498352,35.3929988443851,46.9559931755066,34.7459992468357,46.9559926986694L34.729998499155,46.9559926986694C34.0749988555908,46.9479932785034,33.5279988050461,46.4590072631836,33.4449987411499,45.8100252151489L28.5969982147217,7.7971076965332 19.7799987792969,38.5482323169708C19.6119985580444,39.1362158469856 19.0699996948242,39.5222048461437 18.4459991455078,39.4962055683136 17.8359985351563,39.4622065722942 17.3289985656738,39.0092194601893 17.2269992828369,38.4062369465828L13.6579990386963,17.2688388824463 10.7719993591309,23.3446655273438C10.5559997558594,23.8016519546509,10.0949993133545,24.0936441421509,9.58799934387207,24.0936441421509L1.31099700927734,24.0936441421509C0.587997436523438,24.0936441421509 0,23.5056610107422 0,22.7826805114746 0,22.0577011108398 0.587997436523438,21.4717178344727 1.31099700927734,21.4717178344727L8.75799942016602,21.4717178344727 13.0749988555908,12.3859767913818C13.3199996948242,11.8689918518066 13.8699989318848,11.57200050354 14.4389991760254,11.6499977111816 15.0059986114502,11.7299957275391 15.4579982757568,12.1669826507568 15.5519981384277,12.7309665679932L18.8509979248047,32.2744116783142 27.8319988250732,0.952301025390625C27.9913740158081,0.391693115234375,28.4917645454407 , -0.000171661376953125,29.073618888855,0z '' > < /PathGeometry > < /MatrixAnimationUsingPath.PathGeometry > < /MatrixAnimationUsingPath > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < /Rectangle.Triggers > < /Rectangle > < /Canvas >
MatrixAnimationUsingPath animate on surroundings ( outline ) of path
C_sharp : I have been working a little bit with LINQ recently , and thanks to the help of some StackOverflowers I was able to get this statement working : However , I am confused because the piece that makes it work is the if ( traceJob.Count ( ) ==1 ) . If I remove that section , then I get an ObjectNullRef error saying that the enumeration of traceJob yielded no results.Now , to my knowledge , an if statement checking the count should not actually alter the results of the Linq statement right ? Can anyone explain to me why I am seeing this behavior ? <code> var traceJob = from jobDefinition in service.JobDefinitions where jobDefinition.Id == traceGuid select jobDefinition ; if ( traceJob ! = null & & traceJob.Count ( ) == 1 ) { traceJob.First ( ) .RunNow ( ) ; Console.WriteLine ( traceJob.First ( ) .DisplayName + `` Last Run Time : `` + traceJob.First ( ) .LastRunTime ) ; }
Why does an IF Statement effect the outcome of my LINQ Statement ?
C_sharp : I have this simple LINQ query , which executes for 8395 ms : Its IL : when it executes , it generates the following SQL query , which takes 661 ms to execute : What was Entity Framework ( version= '' 6.1.0.133 '' ) doing all that time ? Little change to the LINQ query , namely removing ToString ( ) call in the select part , makes it execute for 749 ms : with the following generated SQL query : I can see that cast to string has degraded performance of SQL execution , 1.8 times . But the performance of EF degraded 11.2 times . Why is this the case ? And if I really need to have ToString ( ) in my select section of the query , how can I avoid this performance penalty ? <code> var _context = new SurveyContext ( ) ; _context.Database.Log = Console.WriteLine ; ( from p in _context.Participants join row in _context.ListAnswerSelections on new { p.Id , QuestionId = 434 } equals new { Id = row.RelatedParticipantId , QuestionId = row.RelatedQuestionId } select new { V = row.NumericValue.ToString ( ) } ) .ToList ( ) .Select ( x = > new { R = x.V } ) .Count ( ) //This is just to see one number instead of whole result .Dump ( `` Results '' ) ; IL_0000 : nop IL_0001 : newobj Survey.Model.SurveyContext..ctorIL_0006 : stloc.0 // _contextIL_0007 : ldloc.0 // _contextIL_0008 : callvirt System.Data.Entity.DbContext.get_DatabaseIL_000D : ldnull IL_000E : ldftn System.Console.WriteLineIL_0014 : newobj System.Action < System.String > ..ctorIL_0019 : callvirt System.Data.Entity.Database.set_LogIL_001E : nop IL_001F : ldloc.0 // _contextIL_0020 : callvirt Survey.Model.SurveyContext.get_ParticipantsIL_0025 : ldloc.0 // _contextIL_0026 : callvirt Survey.Model.SurveyContext.get_ListAnswerSelectionsIL_002B : ldtoken Survey.Model.ParticipantIL_0030 : call System.Type.GetTypeFromHandleIL_0035 : ldstr `` p '' IL_003A : call System.Linq.Expressions.Expression.ParameterIL_003F : stloc.1 // CS $ 0 $ 0000IL_0040 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > ..ctorIL_0045 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_004A : call System.Reflection.MethodBase.GetMethodFromHandleIL_004F : castclass System.Reflection.ConstructorInfoIL_0054 : ldc.i4.2 IL_0055 : newarr System.Linq.Expressions.ExpressionIL_005A : stloc.2 // CS $ 0 $ 0001IL_005B : ldloc.2 // CS $ 0 $ 0001IL_005C : ldc.i4.0 IL_005D : ldloc.1 // CS $ 0 $ 0000IL_005E : ldtoken Survey.Model.ModelBase.get_IdIL_0063 : call System.Reflection.MethodBase.GetMethodFromHandleIL_0068 : castclass System.Reflection.MethodInfoIL_006D : call System.Linq.Expressions.Expression.PropertyIL_0072 : stelem.ref IL_0073 : ldloc.2 // CS $ 0 $ 0001IL_0074 : ldc.i4.1 IL_0075 : ldc.i4 B2 01 00 00 IL_007A : box System.Int32IL_007F : ldtoken System.Int32IL_0084 : call System.Type.GetTypeFromHandleIL_0089 : call System.Linq.Expressions.Expression.ConstantIL_008E : stelem.ref IL_008F : ldloc.2 // CS $ 0 $ 0001IL_0090 : ldc.i4.2 IL_0091 : newarr System.Reflection.MethodInfoIL_0096 : stloc.3 // CS $ 0 $ 0002IL_0097 : ldloc.3 // CS $ 0 $ 0002IL_0098 : ldc.i4.0 IL_0099 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > .get_IdIL_009E : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_00A3 : call System.Reflection.MethodBase.GetMethodFromHandleIL_00A8 : castclass System.Reflection.MethodInfoIL_00AD : stelem.ref IL_00AE : ldloc.3 // CS $ 0 $ 0002IL_00AF : ldc.i4.1 IL_00B0 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > .get_QuestionIdIL_00B5 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_00BA : call System.Reflection.MethodBase.GetMethodFromHandleIL_00BF : castclass System.Reflection.MethodInfoIL_00C4 : stelem.ref IL_00C5 : ldloc.3 // CS $ 0 $ 0002IL_00C6 : call System.Linq.Expressions.Expression.NewIL_00CB : ldc.i4.1 IL_00CC : newarr System.Linq.Expressions.ParameterExpressionIL_00D1 : stloc.s 04 // CS $ 0 $ 0003IL_00D3 : ldloc.s 04 // CS $ 0 $ 0003IL_00D5 : ldc.i4.0 IL_00D6 : ldloc.1 // CS $ 0 $ 0000IL_00D7 : stelem.ref IL_00D8 : ldloc.s 04 // CS $ 0 $ 0003IL_00DA : call System.Linq.Expressions.Expression.LambdaIL_00DF : ldtoken Survey.Model.ListAnswerSelectionIL_00E4 : call System.Type.GetTypeFromHandleIL_00E9 : ldstr `` row '' IL_00EE : call System.Linq.Expressions.Expression.ParameterIL_00F3 : stloc.1 // CS $ 0 $ 0000IL_00F4 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > ..ctorIL_00F9 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_00FE : call System.Reflection.MethodBase.GetMethodFromHandleIL_0103 : castclass System.Reflection.ConstructorInfoIL_0108 : ldc.i4.2 IL_0109 : newarr System.Linq.Expressions.ExpressionIL_010E : stloc.2 // CS $ 0 $ 0001IL_010F : ldloc.2 // CS $ 0 $ 0001IL_0110 : ldc.i4.0 IL_0111 : ldloc.1 // CS $ 0 $ 0000IL_0112 : ldtoken Survey.Model.ListAnswerSelection.get_RelatedParticipantIdIL_0117 : call System.Reflection.MethodBase.GetMethodFromHandleIL_011C : castclass System.Reflection.MethodInfoIL_0121 : call System.Linq.Expressions.Expression.PropertyIL_0126 : stelem.ref IL_0127 : ldloc.2 // CS $ 0 $ 0001IL_0128 : ldc.i4.1 IL_0129 : ldloc.1 // CS $ 0 $ 0000IL_012A : ldtoken Survey.Model.ListAnswerSelection.get_RelatedQuestionIdIL_012F : call System.Reflection.MethodBase.GetMethodFromHandleIL_0134 : castclass System.Reflection.MethodInfoIL_0139 : call System.Linq.Expressions.Expression.PropertyIL_013E : stelem.ref IL_013F : ldloc.2 // CS $ 0 $ 0001IL_0140 : ldc.i4.2 IL_0141 : newarr System.Reflection.MethodInfoIL_0146 : stloc.3 // CS $ 0 $ 0002IL_0147 : ldloc.3 // CS $ 0 $ 0002IL_0148 : ldc.i4.0 IL_0149 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > .get_IdIL_014E : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_0153 : call System.Reflection.MethodBase.GetMethodFromHandleIL_0158 : castclass System.Reflection.MethodInfoIL_015D : stelem.ref IL_015E : ldloc.3 // CS $ 0 $ 0002IL_015F : ldc.i4.1 IL_0160 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > .get_QuestionIdIL_0165 : ldtoken < > f__AnonymousType0 < System.Int32 , System.Int32 > IL_016A : call System.Reflection.MethodBase.GetMethodFromHandleIL_016F : castclass System.Reflection.MethodInfoIL_0174 : stelem.ref IL_0175 : ldloc.3 // CS $ 0 $ 0002IL_0176 : call System.Linq.Expressions.Expression.NewIL_017B : ldc.i4.1 IL_017C : newarr System.Linq.Expressions.ParameterExpressionIL_0181 : stloc.s 04 // CS $ 0 $ 0003IL_0183 : ldloc.s 04 // CS $ 0 $ 0003IL_0185 : ldc.i4.0 IL_0186 : ldloc.1 // CS $ 0 $ 0000IL_0187 : stelem.ref IL_0188 : ldloc.s 04 // CS $ 0 $ 0003IL_018A : call System.Linq.Expressions.Expression.LambdaIL_018F : ldtoken Survey.Model.ParticipantIL_0194 : call System.Type.GetTypeFromHandleIL_0199 : ldstr `` p '' IL_019E : call System.Linq.Expressions.Expression.ParameterIL_01A3 : stloc.1 // CS $ 0 $ 0000IL_01A4 : ldtoken Survey.Model.ListAnswerSelectionIL_01A9 : call System.Type.GetTypeFromHandleIL_01AE : ldstr `` row '' IL_01B3 : call System.Linq.Expressions.Expression.ParameterIL_01B8 : stloc.s 05 // CS $ 0 $ 0004IL_01BA : ldtoken < > f__AnonymousType1 < System.String > ..ctorIL_01BF : ldtoken < > f__AnonymousType1 < System.String > IL_01C4 : call System.Reflection.MethodBase.GetMethodFromHandleIL_01C9 : castclass System.Reflection.ConstructorInfoIL_01CE : ldc.i4.1 IL_01CF : newarr System.Linq.Expressions.ExpressionIL_01D4 : stloc.2 // CS $ 0 $ 0001IL_01D5 : ldloc.2 // CS $ 0 $ 0001IL_01D6 : ldc.i4.0 IL_01D7 : ldloc.s 05 // CS $ 0 $ 0004IL_01D9 : ldtoken Survey.Model.ListAnswerSelection.get_NumericValueIL_01DE : call System.Reflection.MethodBase.GetMethodFromHandleIL_01E3 : castclass System.Reflection.MethodInfoIL_01E8 : call System.Linq.Expressions.Expression.PropertyIL_01ED : ldtoken System.Int32.ToStringIL_01F2 : call System.Reflection.MethodBase.GetMethodFromHandleIL_01F7 : castclass System.Reflection.MethodInfoIL_01FC : ldc.i4.0 IL_01FD : newarr System.Linq.Expressions.ExpressionIL_0202 : call System.Linq.Expressions.Expression.CallIL_0207 : stelem.ref IL_0208 : ldloc.2 // CS $ 0 $ 0001IL_0209 : ldc.i4.1 IL_020A : newarr System.Reflection.MethodInfoIL_020F : stloc.3 // CS $ 0 $ 0002IL_0210 : ldloc.3 // CS $ 0 $ 0002IL_0211 : ldc.i4.0 IL_0212 : ldtoken < > f__AnonymousType1 < System.String > .get_VIL_0217 : ldtoken < > f__AnonymousType1 < System.String > IL_021C : call System.Reflection.MethodBase.GetMethodFromHandleIL_0221 : castclass System.Reflection.MethodInfoIL_0226 : stelem.ref IL_0227 : ldloc.3 // CS $ 0 $ 0002IL_0228 : call System.Linq.Expressions.Expression.NewIL_022D : ldc.i4.2 IL_022E : newarr System.Linq.Expressions.ParameterExpressionIL_0233 : stloc.s 04 // CS $ 0 $ 0003IL_0235 : ldloc.s 04 // CS $ 0 $ 0003IL_0237 : ldc.i4.0 IL_0238 : ldloc.1 // CS $ 0 $ 0000IL_0239 : stelem.ref IL_023A : ldloc.s 04 // CS $ 0 $ 0003IL_023C : ldc.i4.1 IL_023D : ldloc.s 05 // CS $ 0 $ 0004IL_023F : stelem.ref IL_0240 : ldloc.s 04 // CS $ 0 $ 0003IL_0242 : call System.Linq.Expressions.Expression.LambdaIL_0247 : call System.Linq.Queryable.JoinIL_024C : call System.Linq.Enumerable.ToListIL_0251 : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate2IL_0256 : brtrue.s IL_026BIL_0258 : ldnull IL_0259 : ldftn UserQuery. < Main > b__1IL_025F : newobj System.Func < < > f__AnonymousType1 < System.String > , < > f__AnonymousType2 < System.String > > ..ctorIL_0264 : stsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate2IL_0269 : br.s IL_026BIL_026B : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate2IL_0270 : call System.Linq.Enumerable.SelectIL_0275 : call System.Linq.Enumerable.CountIL_027A : ldstr `` Results '' IL_027F : call LINQPad.Extensions.DumpIL_0284 : pop IL_0285 : ret < Main > b__1 : IL_0000 : ldarg.0 IL_0001 : callvirt < > f__AnonymousType1 < System.String > .get_VIL_0006 : newobj < > f__AnonymousType2 < System.String > ..ctorIL_000B : stloc.0 // CS $ 1 $ 0000IL_000C : br.s IL_000EIL_000E : ldloc.0 // CS $ 1 $ 0000IL_000F : ret < > f__AnonymousType1 ` 1.get_V : IL_0000 : ldarg.0 IL_0001 : ldfld 16 00 00 0A IL_0006 : stloc.0 IL_0007 : br.s IL_0009IL_0009 : ldloc.0 IL_000A : ret < > f__AnonymousType1 ` 1.ToString : IL_0000 : newobj System.Text.StringBuilder..ctorIL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : ldstr `` { V = `` IL_000C : callvirt System.Text.StringBuilder.AppendIL_0011 : pop IL_0012 : ldloc.0 IL_0013 : ldarg.0 IL_0014 : ldfld 16 00 00 0A IL_0019 : box 02 00 00 1B IL_001E : callvirt System.Text.StringBuilder.AppendIL_0023 : pop IL_0024 : ldloc.0 IL_0025 : ldstr `` } '' IL_002A : callvirt System.Text.StringBuilder.AppendIL_002F : pop IL_0030 : ldloc.0 IL_0031 : callvirt System.Object.ToStringIL_0036 : stloc.1 IL_0037 : br.s IL_0039IL_0039 : ldloc.1 IL_003A : ret < > f__AnonymousType1 ` 1.Equals : IL_0000 : ldarg.1 IL_0001 : isinst 06 00 00 1B IL_0006 : stloc.0 IL_0007 : ldloc.0 IL_0008 : brfalse.s IL_0022IL_000A : call 10 00 00 0A IL_000F : ldarg.0 IL_0010 : ldfld 16 00 00 0A IL_0015 : ldloc.0 IL_0016 : ldfld 16 00 00 0A IL_001B : callvirt 11 00 00 0A IL_0020 : br.s IL_0023IL_0022 : ldc.i4.0 IL_0023 : nop IL_0024 : stloc.1 IL_0025 : br.s IL_0027IL_0027 : ldloc.1 IL_0028 : ret < > f__AnonymousType1 ` 1.GetHashCode : IL_0000 : ldc.i4 8B 15 0F EC IL_0005 : stloc.0 IL_0006 : ldc.i4 29 55 55 A5 IL_000B : ldloc.0 IL_000C : mul IL_000D : call 10 00 00 0A IL_0012 : ldarg.0 IL_0013 : ldfld 16 00 00 0A IL_0018 : callvirt 14 00 00 0A IL_001D : add IL_001E : stloc.0 IL_001F : ldloc.0 IL_0020 : stloc.1 IL_0021 : br.s IL_0023IL_0023 : ldloc.1 IL_0024 : ret < > f__AnonymousType1 ` 1..ctor : IL_0000 : ldarg.0 IL_0001 : call System.Object..ctorIL_0006 : ldarg.0 IL_0007 : ldarg.1 IL_0008 : stfld 16 00 00 0A IL_000D : ret < > f__AnonymousType2 ` 1.get_R : IL_0000 : ldarg.0 IL_0001 : ldfld 17 00 00 0A IL_0006 : stloc.0 IL_0007 : br.s IL_0009IL_0009 : ldloc.0 IL_000A : ret < > f__AnonymousType2 ` 1.ToString : IL_0000 : newobj System.Text.StringBuilder..ctorIL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : ldstr `` { R = `` IL_000C : callvirt System.Text.StringBuilder.AppendIL_0011 : pop IL_0012 : ldloc.0 IL_0013 : ldarg.0 IL_0014 : ldfld 17 00 00 0A IL_0019 : box 02 00 00 1B IL_001E : callvirt System.Text.StringBuilder.AppendIL_0023 : pop IL_0024 : ldloc.0 IL_0025 : ldstr `` } '' IL_002A : callvirt System.Text.StringBuilder.AppendIL_002F : pop IL_0030 : ldloc.0 IL_0031 : callvirt System.Object.ToStringIL_0036 : stloc.1 IL_0037 : br.s IL_0039IL_0039 : ldloc.1 IL_003A : ret < > f__AnonymousType2 ` 1.Equals : IL_0000 : ldarg.1 IL_0001 : isinst 07 00 00 1B IL_0006 : stloc.0 IL_0007 : ldloc.0 IL_0008 : brfalse.s IL_0022IL_000A : call 10 00 00 0A IL_000F : ldarg.0 IL_0010 : ldfld 17 00 00 0A IL_0015 : ldloc.0 IL_0016 : ldfld 17 00 00 0A IL_001B : callvirt 11 00 00 0A IL_0020 : br.s IL_0023IL_0022 : ldc.i4.0 IL_0023 : nop IL_0024 : stloc.1 IL_0025 : br.s IL_0027IL_0027 : ldloc.1 IL_0028 : ret < > f__AnonymousType2 ` 1.GetHashCode : IL_0000 : ldc.i4 21 74 32 1C IL_0005 : stloc.0 IL_0006 : ldc.i4 29 55 55 A5 IL_000B : ldloc.0 IL_000C : mul IL_000D : call 10 00 00 0A IL_0012 : ldarg.0 IL_0013 : ldfld 17 00 00 0A IL_0018 : callvirt 14 00 00 0A IL_001D : add IL_001E : stloc.0 IL_001F : ldloc.0 IL_0020 : stloc.1 IL_0021 : br.s IL_0023IL_0023 : ldloc.1 IL_0024 : ret < > f__AnonymousType2 ` 1..ctor : IL_0000 : ldarg.0 IL_0001 : call System.Object..ctorIL_0006 : ldarg.0 IL_0007 : ldarg.1 IL_0008 : stfld 17 00 00 0A IL_000D : ret SELECT [ Extent1 ] . [ Id ] AS [ Id ] , CAST ( [ Extent2 ] . [ NumericValue ] AS nvarchar ( max ) ) AS [ C1 ] FROM [ dbo ] . [ Participants ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ ListAnswerSelections ] AS [ Extent2 ] ON ( [ Extent1 ] . [ Id ] = [ Extent2 ] . [ ListAnswer_RelatedParticipantId ] ) AND ( 434 = [ Extent2 ] . [ ListAnswer_RelatedQuestionId ] ) -- Executing at 08-Oct-15 3:26:59 PM +03:00 -- Completed in 661 ms with result : SqlDataReader var _context = new SurveyContext ( ) ; _context.Database.Log = Console.WriteLine ; ( from p in _context.Participants join row in _context.ListAnswerSelections on new { p.Id , QuestionId = 434 } equals new { Id = row.RelatedParticipantId , QuestionId = row.RelatedQuestionId } select new { V = row.NumericValue } ) .ToList ( ) .Select ( x = > new { R = x.V.ToString ( ) } ) .Count ( ) .Dump ( `` Results '' ) ; SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent2 ] . [ NumericValue ] AS [ NumericValue ] FROM [ dbo ] . [ Participants ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ ListAnswerSelections ] AS [ Extent2 ] ON ( [ Extent1 ] . [ Id ] = [ Extent2 ] . [ ListAnswer_RelatedParticipantId ] ) AND ( 434 = [ Extent2 ] . [ ListAnswer_RelatedQuestionId ] ) -- Executing at 08-Oct-15 3:33:33 PM +03:00 -- Completed in 367 ms with result : SqlDataReader
Why does ToString ( ) degrade Entity Framework 's performance so dramatically
C_sharp : Why ca n't I use code like this ? 12And should write like this12PS : I can use if-else statement without { } . Why should I use them with try-catch ( -finally ) statement ? Is there any meaningful reason ? Is it only because that some people think that code is hard to read ? Several months ago I asked that question on russian programming forum but I got no satisfactory answer ... <code> int i = 0 ; try i = int.Parse ( `` qwerty '' ) ; catch throw ; try i = int.Parse ( `` qwerty '' ) ; catch ; finally Log.Write ( `` error '' ) ; int i = 0 ; try { i = int.Parse ( `` qwerty '' ) ; } catch { throw ; } try { i = int.Parse ( `` qwerty '' ) ; } catch { } finally { Log.Write ( `` error '' ) ; }
Why does it not allowed to use try-catch statement without { } ?
C_sharp : Possible Duplicate : “ new ” keyword in property declaration Pardon me if this is C # 101 , but I am trying to understand the code below : Why does the indexer have new in front of it ? By the way , Rabbit is a class defined in another file . Thanks ! <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Collections ; namespace Generics { class RabbitCollection : ArrayList { public int Add ( Rabbit newRabbit ) { return base.Add ( newRabbit ) ; } //collections indexer public new Rabbit this [ int index ] { get { return base [ index ] as Rabbit ; } set { base [ index ] = value ; } } } }
Why does this code have new in the collections indexer
C_sharp : Specifically , if you create an instance of a Timer in the local scope , and then return from that scope:1 ) Will the timer still execute ? 2 ) When would it be garbage collected ? I offer these two scenarios : And <code> Timer timer = new Timer ( new TimerCallback ( ( state ) = > { doSomething ( ) ; } ) ) ; timer.Change ( ( int ) TimeSpan.FromSeconds ( 30 ) , ( int ) TimeSpan.FromSeconds ( 30 ) ) ; return ; Timer timer = new Timer ( new TimerCallback ( ( state ) = > { doSomething ( ) ; } ) ) ; timer.Change ( ( int ) TimeSpan.FromSeconds ( 30 ) , Timeout.Infinite ) ; return ;
What is the expected behavior of a locally scoped Timer ?
C_sharp : I 'm stuck with a weird problem ( which is probably my lack of knowledge ) , I present the offending code : f and fTemp are FileInfo objects . So if I run this with code where f is a video file playing in a mediaplayer it throws the exception . That works fine and as expected . Now when I close the mediaplayer it deletes the file ! ? Even though my application is long closed . Even when I close Visual Studio it still deletes the file , when I close the mediaplayer . As if some callback is being setup somewhere to make sure the file gets deleted at some point . This offcourse in unwanted behaviour . But I ca n't figure out what exactly goes wrong ... Result for now : I know I still can do better between Delete and MoveTo , but I 'll take my changes for now , shotgun coding ... .. <code> try { f.Delete ( ) ; fTemp.MoveTo ( f.FullName ) ; Console.WriteLine ( `` INFO : Old file deleted new file moved in > { 0 } '' , f.FullName ) ; } catch ( IOException ex ) { Console.WriteLine ( `` ERROR : Output file has IO exception > { 0 } '' , f.FullName ) ; Environment.ExitCode = 1 ; } if ( ! IsFileLocked ( f ) ) { try { f.Delete ( ) ; fTemp.MoveTo ( f.FullName ) ; Console.WriteLine ( `` INFO : Old file deleted new file moved in > { 0 } '' , f.FullName ) ; } catch ( IOException ex ) { Console.WriteLine ( `` ERROR : Output file has IO exception > { 0 } '' , f.FullName ) ; Environment.ExitCode = 1 ; } catch ( UnauthorizedAccessException ex ) { Environment.ExitCode = 2 ; Console.WriteLine ( `` ERROR : Output file is locked > { 0 } '' , f.FullName ) ; } } else { Environment.ExitCode = 3 ; Console.WriteLine ( `` ERROR : Could n't delete file was locked '' ) ; }
Delete functions deletes even when calling app is closed
C_sharp : I 've this piece of code : If I build my application in Debug mode everything is ok , test index pre prints 12 and test index post prints 14. the same in Release mode with Optimize code unchecked . if i test with Optimize code checked test index post prints 18 instead of 14.Same result if I replace index += ethType.Length ; with index += 2 ; . seems only index++ ; index++ ; is working.I tried this code in an empty application and sums are ok.App is multithreading but there is n't no concurrency here.Decompiled code from DLL seems ok.Any ideas why this happen ? EDIT : Happens only when app is compiled for x64 . x86 is ok.EDIT 3 : some info of the build env : visual studio 15.0.0-RTW+26228.4framework 4.7.02053can trigger this issue on framework 4.6.2 and 4.7. other frameworks are n't tested.EDIT 5 : new , smaller example project . no dependencies needed.EDIT 6 : disassembly of the test project here . ( too long to post it here ) <code> private void AnswerToCe ( int currentBlock , int totalBlock = 0 ) { byte [ ] bufferToSend ; byte [ ] macDst = mac ; byte [ ] macSrc = ConnectionManager.SInstance.GetMyMAC ( ) ; byte [ ] ethType ; byte [ ] header ; if ( Function == FlashFunction.UPLOAD_APPL || Function == FlashFunction.UPLOAD_BITSTREAM ) { ethType = BitConverter.GetBytes ( ( ushort ) EthType.ETH_TYPE_UPLOAD ) ; ethType = new byte [ ] { ethType [ 1 ] , ethType [ 0 ] } ; header = Header.GetBytes ( ( ushort ) binaryBlocks.Count , ( ushort ) ( currentBlock + 1 ) , ( ushort ) binaryBlocks [ currentBlock ] .Length ) ; int index = 0 ; bufferToSend = new byte [ macDst.Length + macSrc.Length + ethType.Length + header.Length + binaryBlocks [ currentBlock ] .Length ] ; Array.Copy ( macDst , 0 , bufferToSend , index , macDst.Length ) ; index += macDst.Length ; Array.Copy ( macSrc , 0 , bufferToSend , index , macSrc.Length ) ; index += macSrc.Length ; Logger.SInstance.Write ( index.ToString ( ) , `` test index pre '' ) ; Array.Copy ( ethType , 0 , bufferToSend , index , ethType.Length ) ; index += ethType.Length ; Logger.SInstance.Write ( index.ToString ( ) , `` test index post '' ) ; Array.Copy ( header , 0 , bufferToSend , index , header.Length ) ; index += header.Length ; Array.Copy ( binaryBlocks [ currentBlock ] , 0 , bufferToSend , index , binaryBlocks [ currentBlock ] .Length ) ; }
RyuJIT C # wrong sum result with /optimize
C_sharp : Why is it when I turn on `` check for arithmetic underflow/overflow '' under C # Project Properties > Build > Advanced , that the following code runs faster ( 138 ms ) than if I turn the option off ( 141 ms ) ? Test Run # 1 : 138ms with checked arithmetic , 141ms withoutOn the other hand , if you comment out the if ( i == 1000 ) i *= 2 ; , then the checked code runs slower ( 120 ms ) than the unchecked code ( 116 ms ) .Test Run # 2 : 120ms with checked arithmetic , 116ms withoutProcess : Manually ran .exe outside Visual Studio from PowerShell prompt repeatedly until resulting timestamp was consistent ( ± 1 ms ) ; flipped between settings multiple times to ensure consistent results.Test Box Setup : Windows 8.1 Pro x64VS2013 Update 2Intel Core i7-4500default C # Console project templateRelease configuration <code> using System ; using System.Diagnostics ; class Program { static void Main ( string [ ] args ) { var s = new Stopwatch ( ) ; s.Start ( ) ; int a = 0 ; for ( int i = 0 ; i < 100000000 ; i += 3 ) { if ( i == 1000 ) i *= 2 ; if ( i % 35 == 0 ) ++a ; } s.Stop ( ) ; Console.WriteLine ( s.ElapsedMilliseconds ) ; Console.WriteLine ( a ) ; } } using System ; using System.Diagnostics ; class Program { static void Main ( string [ ] args ) { var s = new Stopwatch ( ) ; s.Start ( ) ; int a = 0 ; for ( int i = 0 ; i < 100000000 ; i += 3 ) { if ( i % 35 == 0 ) ++a ; } s.Stop ( ) ; Console.WriteLine ( s.ElapsedMilliseconds ) ; Console.WriteLine ( a ) ; } }
Why is checked arithmetic in .NET sometimes faster than unckecked ?
C_sharp : Let 's say you wrote a custom enumerator for the code below : And then in the client code , you did this : Then , set a break-point on the MoveNext method implementation of your StudentEnumerator class.Then when you run the code and the debugger breaks after constructing the query / IEnumerable in this case , and you expand the Results View like in the picture shown below , how does Visual Studio evaluate the sequence without breaking into its enumerator 's MoveNext ? I have always been curious about this . <code> public class School : IEnumerable < Student > static void Main ( string [ ] args ) { var school = CreateSchoolWithStudents ( ) ; var query = from student in school where student.Name.StartsWith ( `` S '' ) select student ; Debugger.Break ( ) ; } private static School CreateSchoolWithStudents ( ) { return new School { new Student { Name = `` Sathyaish '' } , new Student { Name = `` John '' } , new Student { Name = `` Carol '' } , new Student { Name = `` Peter '' } } ; }
How does Visual Studio evaluate the IEnumerable without breaking into its IEnumerator < T > 's MoveNext ?
C_sharp : Consider these two definitions for GetWindowText . One uses a string for the buffer , the other uses a StringBuilder instead : Here 's how you call them : They both seem to work correctly whether I pass in a string , or a StringBuilder . However , all the examples I 've seen use the StringBuilder variant . Even PInvoke.net lists that one.My guess is the thinking goes 'In C # strings are immutable , therefore use StringBuilder ' , but since we 're poking down to the Win32 API and messing with the memory locations directly , and that memory buffer is for all intents and purposes ( pre ) allocated ( i.e . reserved for , and being currently used by the string ) by the nature of it being assigned a value at its definition , that restriction does n't actually apply , hence string works just fine . But I 'm wondering if that assumption is wrong.I do n't think so because if you test this by increasing the buffer by say 10 , and change the character you 're initializing it with to say ' A ' , then pass in that larger buffer size to GetWindowText , the string you get back is the actual title , right-padded with the ten extra ' A 's that were n't overwritten , showing it did update that memory location of the earlier characters.So provided you pre-initialize the strings , ca n't you do this ? Could those strings ever 'move out from under you ' while using them because the CLR is assuming they 're immutable ? That 's what I 'm trying to figure out . <code> [ DllImport ( `` user32.dll '' , CharSet = CharSet.Auto , SetLastError = true ) ] public static extern int GetWindowText ( IntPtr hWnd , StringBuilder lpString , int nMaxCount ) ; [ DllImport ( `` user32.dll '' , CharSet = CharSet.Auto , SetLastError = true ) ] public static extern int GetWindowText ( IntPtr hWnd , string lpString , int nMaxCount ) ; var windowTextLength = GetWindowTextLength ( hWnd ) ; // You can use either of these as they both workvar buffer = new string ( '\0 ' , windowTextLength ) ; //var buffer = new StringBuilder ( windowTextLength ) ; // Add 1 to windowTextLength for the trailing null charactervar readSize = GetWindowText ( hWnd , buffer , windowTextLength + 1 ) ; Console.WriteLine ( $ '' The title is ' { buffer } ' '' ) ;
For C # , is there a down-side to using 'string ' instead of 'StringBuilder ' when calling Win32 functions such as GetWindowText ?
C_sharp : I have discovered that if i run following lines of code.No boxing is done , but if i call i.GetType ( ) ( another derived function from System.Object ) in place of GetHashCode ( ) , a boxing will be required to call GetType ( ) , Why its not possible to call GetType ( ) on primitive type instance directly , without boxing , while its possible to call GetHashCode ( ) without boxing ? <code> int i = 7 ; i.GetHashCode ( ) ; //where GetHashCode ( ) is the derived //function from System.Object
Why calling some functions of the Object class , on a primitive type instance , need boxing ?
C_sharp : As I do n't know how my problem is called , I can not guarantee , that nobody has asked the same question recently or at all.I did notice , however that there are quite a few threads with a similar title , but they do n't seem to be relevant to my problem.I have a custom list class , that implements Generics.I also have the classes : andNow , comes the relevant code : Even though appleList is a MyList ( Of Apple ) and Apple is Fruit , VisualStudio does n't accept MyList ( Of Apple ) as argument , when MyList ( Of Fruit ) is asked.However , if I were to declare the list like this : Then everything works again . What exactly did I do wrong ? An answer would be much appreciated , and thank you for taking the time to read , even without answering . <code> class MyList < T > { public void add ( T item ) // adds an item to the list { /* code */ } public void add ( MyList < T > list ) // attaches an existing list to the end of the current one { /* code */ } } class Apple : Fruit class Banana : Fruit MyList < Fruit > fruitList = new MyList < Fruit > ( ) ; // fill fruitListfruitList.add ( new Apple ( ) ) ; // works , of coursefruitList.add ( new Banana ( ) ) ; // works as well , of courseMyList < Apple > appleList = new MyList < Apple > ( ) ; // fill appleListfruitList.add ( appleList ) ; // does n't work . Why ? MyList < object > fruitList = new MyList < object > ( ) ;
About Generics and Inheritance ( forgive my bad title )
C_sharp : The following is a code snippet about covariance in C # . I have some understanding about how to apply covariance , but there is some detailed technical stuff that I have hard time grasping.Invoking IExtract < object > .Extract ( ) invokes IExtract < string > .Extract ( ) , as evidenced by the output . While I kind of expected this behavior , I am not able to tell myself why it behaved the way it did.IExtract < object > is NOT in the inheritance hierarchy containing IExtract < string > , except the fact that C # made IExtract < string > assignable to IExtract < object > . But IExtract < string > simply does NOT have a method named Extract ( ) that it inherits from IExtract < object > , unlike the normal inheritance . It does n't appear to make much sense to me at this time.Would it be sensible to say that IExtract < string > 's OWN coincidentally ( or by design ) similarly named Extract ( ) method hides IExtract < object > 's Extract ( ) method ? And that it is a kind of a hack ? ( Bad choice of word ! ) Thanks <code> using System ; namespace CovarianceExample { interface IExtract < out T > { T Extract ( ) ; } class SampleClass < T > : IExtract < T > { private T data ; public SampleClass ( T data ) { this.data = data ; } //ctor public T Extract ( ) // Implementing interface { Console.WriteLine ( `` The type where the executing method is declared : \n { 0 } '' , this.GetType ( ) ) ; return this.data ; } } class CovarianceExampleProgram { static void Main ( string [ ] args ) { SampleClass < string > sampleClassOfString = new SampleClass < string > ( `` This is a string '' ) ; IExtract < Object > iExtract = sampleClassOfString ; // IExtract < object > .Extract ( ) mapes to IExtract < string > .Extract ( ) ? object obj = iExtract.Extract ( ) ; Console.WriteLine ( obj ) ; Console.ReadKey ( ) ; } } } // Output : // The type where the executing method is declared : // CovarianceExample.SampleClass ` 1 [ System.String ] // This is a string
C # covariance confusion
C_sharp : I have a troublesome query to write . I 'm currently writing some nasty for loops to solve it , but I 'm curious to know if Linq can do it for me.I have : and a list that contains these structs . Let 's say it 's ordered this way : If you put the orderedList struct dates in a set they will always be contiguous with respect to the day.. that is if the latest date in the list was 2011/01/31 , and the earliest date in the list was 2011/01/01 , then you 'd find that the list would contain 31 items , one for each date in January.Ok , so what I want to do is group the list items such that : Each item in a group must contain the same Decimal A value and the same Decimal B valueThe date values in a group must form a set of contiguous dates , if the date values were in orderIf you summed up the sums of items in each group , the total would equal the number of items in the original list ( or you could say a struct with a particular date ca n't belong to more than one group ) Any Linq masters know how to do this one ? Thanks ! <code> struct TheStruct { public DateTime date { get ; set ; } // ( time portion will always be 12 am ) public decimal A { get ; set ; } public decimal B { get ; set ; } } List < TheStruct > orderedList = unorderedList.OrderBy ( x = > x.date ) .ToList ( ) ;
How can I use `` Linq to Objects '' to put a set of contiguous dates in one group ?
C_sharp : I have a .dll and a console app that uses the said .dll but does n't reference directly , it loads it via reflection . The console app calls a method of a class inside the .dll.The method signature is IEnumerable < Customer > GetAll ( ) ; In the .dll I have done this : In the Console app I 've done this : Now the question is , since GetAll returns IEnumerable < Customer > and my console appdoes n't `` know '' anything about MyDLL.dll ( I do n't reference it directly , so it does n't knows the Customer type ) .How can I access to the Customer list in order to access Customer ' a properties without having to make a reference to the .dll explicitly ? <code> class CustomerRepository : ICustomerRepository { public IEnumerable < Customer > GetAll ( ) { using ( var db = new DB02Context ( ) ) { List < Customer > list = new List < Customer > ( ) ; // some queries to fill the list return list ; } } } Assembly assembly = Assembly.LoadFrom ( pathToMyDLL ) ; Type t = assembly.GetType ( `` MyDLL.Models.CustomerRepository '' ) ; var methodInfo = t.GetMethod ( `` GetAll '' ) ; if ( methodInfo == null ) throw new Exception ( `` The method does n't exists '' ) ; var customerRepository = Activator.CreateInstance ( t ) ; // Invoke the GetAll ( ) methodvar customerList = methodInfo.Invoke ( customerRepository , null ) ;
Access to type T properties of IEnumerable < T > returned from a method called via reflection
C_sharp : The following codeThrows a run-time KeyNotFoundException , albeit that { 1 } is a perfectly well-formed array ( i.e . int [ ] a = { 1,2,3,4 } being valid code ) . Changing the TValue of the Dictionary to int [ ] , throws a compile-time CS1061 , but this does not ( note the added new [ ] array-allocation ) : Why does this happen ? <code> new Dictionary < string , List < int > > { [ `` a '' ] = { 1 } , } ; new Dictionary < string , IEnumerable < int > > { [ `` a '' ] = new [ ] { 1 } , } ;
Reason for KeyNotFoundException in Dictionary initialization
C_sharp : Do I need to add a lock block here if I want to be sure that instance will be created only 1 time ? Since there is only 1 instruction within the IF I 'm not 100 % sure . In a case like below , I 'm sure I 'd need it but I wanted to double check if the same applies for the code above.EDITYes , I assume multithreading <code> if ( instance==null ) { instance = new Class ( ) ; } if ( instance==null ) { int i = 5 ; int y = 78 ; instance = new Class ( i , y ) ; }
Do I need a lock here ?