lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | This is my Table : PupilNutritionMy another table Nutrition : This is one field to store final Rate : Case 1 : Operation field with Value 0 and Batch Id 1Case 2 : Now for operation field with Value 1 and Batch Id 1Case 3 : Now for operation field with Value 0 and Batch Id 2Case 4 : Now for operation field with Value 2 ... | Id PupilId NutritionId1 10 100 2 10 101 Id Nutritioncategory BatchId NutritionRate NutritionId Operation1 A 1 9000 100 12 B 1 5000 100 03 C 1 5000 100 14 D 2 6000 101 2 5 E 2 7000 101 2 6 F 2 8000 101 0 decimal Rate= 0 ; Rate= Rate + NutritionRate ( i.e 5000 because for batch id 1 with condition 0 only 1 record is ther... | Simplify process with linq query |
C# | It seems exceptionally heavy handed but going by the rule anything publicly available should be tested should auto-implemented properties be tested ? Customer ClassTested by | public class Customer { public string EmailAddr { get ; set ; } } [ TestClass ] public class CustomerTests : TestClassBase { [ TestMethod ] public void CanSetCustomerEmailAddress ( ) { //Arrange Customer customer = new Customer ( ) ; //Act customer.EmailAddr = `` foo @ bar.com '' ; //Assert Assert.AreEqual ( `` foo @ b... | Is there value in unit testing auto implemented properties |
C# | Today while coding , visual studio notified me that my switch case could be optimized . But the code that I had vs the code that visual studio generated from my switch case does not result in the same outcome.The Enum I Used : After the following code runs the value is equal to 2147483647.But when visual studio optimiz... | public enum State { ExampleA , ExampleB , ExampleC } ; State stateExample = State.ExampleB ; double value ; switch ( stateExample ) { case State.ExampleA : value = BitConverter.ToSingle ( BitConverter.GetBytes ( ( long ) 2147483646 ) , 0 ) ; break ; case State.ExampleB : value = BitConverter.ToUInt32 ( BitConverter.Get... | Unexpected results after optimizing switch case in Visual Studio with C # 8.0 |
C# | I am relatively new to custom controls ( writing control from scratch in code - not merely styling existing controls ) . I am having a go at replicating the YouTube video control , you know the one ... To start with I want to develop the `` timeline '' ( the transparent grey bar , which displays the current position of... | [ ToolboxItem ( true ) ] [ DisplayName ( `` VideoTimeline '' ) ] [ Description ( `` Controls which allows the user navigate video media . In addition is can display a `` + `` waveform repesenting the audio channels for the loaded video media . `` ) ] // [ TemplatePart ( Name = `` PART_ThumbCanvas '' , Type = typeof ( C... | WPF Video Transport Control |
C# | I have a method that currently takes a Func < Product , string > as a parameter , but I need it to be an Expression < Func < Product , string > > . Using AdventureWorks , here 's an example of what I 'd like to do using the Func.I would like it to look something like this : However , the problem I 'm running into is th... | private static void DoSomethingWithFunc ( Func < Product , string > myFunc ) { using ( AdventureWorksDataContext db = new AdventureWorksDataContext ( ) ) { var result = db.Products.GroupBy ( product = > new { SubCategoryName = myFunc ( product ) , ProductNumber = product.ProductNumber } ) ; } } private static void DoSo... | Refactoring Func < T > into Expression < Func < T > > |
C# | I 'm trying to use SQLXMLBulkLoader4 from C # code into an SQL 2008 DB . But for some reason it does n't insert any rows at all despite not throwing any error . I 've made use of the bulkloads own ErrorLog file , ( to check for any errors that might not cause it to crash ) , but no error is reported.I have a XML file t... | public void Bulkload ( string schemaFile , string xmlFile , string source ) { SQLXMLBULKLOADLib.SQLXMLBulkLoad4 bulkload = new SQLXMLBULKLOADLib.SQLXMLBulkLoad4 ( ) ; try { bulkload.ConnectionString = `` Provider=sqloledb ; server=X ; database=X ; uid=X ; pwd=X '' ; bulkload.ErrorLogFile = k_ArticleInfoDirectory + sour... | SQLXML BulkLoader not throwing any error but no data is inserted |
C# | I 'm using IdentityServer4 with ASP.NET Core 2.2 . On the Post Login method I have applied the ValidateAntiForgeryToken . Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page . If you look at Postman Console you get a 400 Bad Request message . I then s... | [ HttpPost ] [ ValidateAntiForgeryToken ] public async Task < IActionResult > Login services.AddAntiforgery ( options = > { options.Cookie.Expiration = TimeSpan.FromDays ( 90 ) ; } ) ; | AntiForgeryToken Expiration Blank Page |
C# | Update : This is called a de Brujin torus , but I still need to figure out a simple algoritm in C # .http : //en.wikipedia.org/wiki/De_Bruijn_torushttp : //datagenetics.com/blog/october22013/index.htmlI need to combine all values of a 3x3 bit grid as densely as possible . By a 3x3 bit grid , I mean a 3x3 grid where eac... | XXX .X . ... XXX .X . .X.XXX .X . ... ... ... ..X.XXX ... ... ... X.XXX..X.XXX..X.XXX ... ... .. X ... X.XXX . // ( 8+2 bits ) Exhausts all values in the same problem with 1-Dimension..X.XXX . // ( 5+2 bits ) The above simplifies when the center bit must be on . ... ..XX..XX ... .. ... ..AG..HH ... .. ... .XX.XX ? ? ? ... | Find a NxM grid that contains all possible 3x3 bit patterns |
C# | I 'm learning TDD . I know about dependency injection whereby you place the class 's dependencies in the constructor 's parameters and have them passed in , passing in default implementations from the default constructor eg ; RepositoryFactory is a simple static class that returns the chosen implementations for the cur... | public AccountController ( ) : this ( RepositoryFactory.Users ( ) ) { } public AccountController ( IUserRepository oUserRepository ) { m_oUserRepository = oUserRepository ; } protected override void Initialize ( RequestContext requestContext ) { if ( FormsService == null ) { FormsService = new FormsAuthenticationServic... | Are the unit test classes in ASP.NET MVC web project a good example ? |
C# | I was astounded to find that the System.Numerics.Complex data type in .NET does n't yield mathematically accurate results.Instead of ( 0 , 1 ) , I get ( 6.12303176911189E-17 , 1 ) , which looks a lot like a rounding error.Now I realize that floating point arithmetic will lead to results like this sometimes , but usuall... | Complex.Sqrt ( -1 ) ! = Complex.ImaginaryOne | Why is .NET 's Complex type broken ? |
C# | To be more specific : will the Linq extension method Any ( IEnumerable collection , Func predicate ) stop checking all the remaining elements of the collections once the predicate has yielded true for an item ? Because I do n't want to spend to much time on figuring out if I need to do the really expensive parts at all... | if ( lotsOfItems.Any ( x = > x.ID == target.ID ) ) //do expensive calculation here var candidate = lotsOfItems.FirstOrDefault ( x = > x.ID == target.ID ) if ( candicate ! = null ) //do expensive calculation here if ( ! lotsOfItems.All ( x = > x.ID ! = target.ID ) ) | Does Any ( ) stop on success ? |
C# | I 'm trying to figure out if there 's any way to avoid getting an `` Unreachable code '' warning for something that 's caused by the preprocessor . I do n't want to suppress all such warnings , only those which will be dependent on the preprocessor , e.g.And later on there 's code that goes : One of those two sections ... | # if WINDOWS public const GamePlatform platform = GamePlatform.PC ; # else public const GamePlatform platform = GamePlatform.MAC ; # endif if ( platform == GamePlatform.PC ) { ... } else { ... } | Avoid `` Unreachable code '' warning for preprocessor-dependent code |
C# | Using MYSQL , with EF 5.x and MVC3 . I have a table with around 3.2 million rows which has city , country combo . I have a autocomplete textbox on the client side that takes city 's search term and sends back suggestions using jQuery/ajax.The challenge that I am facing is that I cache this table into my memory when its... | CityData = DataContext.Citys.OrderBy ( v = > v.Country ) .ToList ( ) ; if ( CityData.Any ( ) ) { // Put this data into the cache for 30 minutes Cache.Set ( `` Citys '' , CityData , 30 ) ; } | Cache Static Tables Mysql |
C# | Many years ago , I was admonished to , whenever possible , release resources in reverse order to how they were allocated . That is : I imagine on a 640K MS-DOS machine , this could minimize heap fragmentation . Is there any practical advantage to doing this in a C # /.NET application , or is this a habit that has outli... | block1 = malloc ( ... ) ; block2 = malloc ( ... ) ; ... do stuff ... free ( block2 ) ; free ( block1 ) ; | C # : Is there an Advantage to Disposing Resources in Reverse Order of their Allocation ? |
C# | NOTE : Right before posting this question it occurred to me there 's a better way of doing what I was trying to accomplish ( and I feel pretty stupid about it ) : So OK , yes , I already realize this . However , I 'm posting the question anyway , because I still do n't quite get why what I was ( stupidly ) trying to do... | IEnumerable < string > checkedItems = ProductTypesList.CheckedItems.Cast < string > ( ) ; filter = p = > checkedItems.Contains ( p.ProductType ) ; private Func < Product , bool > GetProductTypeFilter ( ) { // if nothing is checked , display nothing Func < Product , bool > filter = p = > false ; foreach ( string pt in P... | What am I missing in this chain of predicates ? |
C# | What ( if any ) is the C # equivalent of Python 's itertools.chain method ? Python Example : Results:1234 Note that I 'm not interested in making a new list that combines my first two and then processing that . I want the memory/time savings that itertools.chain provides by not instantiating this combined list . | l1 = [ 1 , 2 ] l2 = [ 3 , 4 ] for v in itertools.chain ( l1 , l2 ) : print ( v ) | C # Equivalent of Python 's itertools.chain |
C# | Hi I have this code using generic and nullable : Please note the TInput constraint , one is class , the other one is struct . Then I use them in : It cause an Ambiguos error . But I also have the another pair : This one compiles successfullyI got no clues why this happen . The first one seems Ok , but compiles error . ... | // The first one is for classpublic static TResult With < TInput , TResult > ( this TInput o , Func < TInput , TResult > evaluator ) where TResult : class where TInput : class// The second one is for struct ( Nullable ) public static TResult With < TInput , TResult > ( this Nullable < TInput > o , Func < TInput , TResu... | Generic type parameter and Nullable method overload |
C# | So I 've notice that this code works : In particular , I 'm curious about the using block , since : fails with a compiler error . Obviously , the class that yield return returns is IDisposable while a regular array enumerator is not . So now I 'm curious : what exactly does yield return create ? | class Program { public static void Main ( ) { Int32 [ ] numbers = { 1,2,3,4,5 } ; using ( var enumerator = Data ( ) .GetEnumerator ( ) ) { } } public static IEnumerable < String > Data ( ) { yield return `` Something '' ; } } Int32 [ ] numbers = { 1 , 2 , 3 , 4 , 5 , 6 } ; using ( var enumerator = numbers.GetEnumerator... | What kind of class does yield return return |
C# | I have .net core WEB API application with MassTransit ( for implement RabbitMQ message broker ) . RabbitMQ-MassTransit configuration is simple and done in few line code in Startup.cs file.I am using dependency injection in my project solution for better code standard . Publish messages are works fine with controller de... | services.AddMassTransit ( x = > { x.AddConsumer < CustomLogConsume > ( ) ; x.AddBus ( provider = > Bus.Factory.CreateUsingRabbitMq ( cfg = > { var host = cfg.Host ( new Uri ( `` rabbitmq : //rabbitmq/ '' ) , h = > { h.Username ( `` guest '' ) ; h.Password ( `` guest '' ) ; } ) ; cfg.ExchangeType = ExchangeType.Fanout ;... | Middleware with Masstransit publish |
C# | I 'm trying to drag one or more files from my application to an outlook mail-message . If I drag to my desktop the files are copied to the desktop as expected , but when dragging into a new outlook 2013 mail message , nothing happens ... Only when I drag explicitly to the 'attachments textbox ' do they appear , this is... | private void Form1_MouseDown ( object sender , MouseEventArgs e ) { var _files = new string [ ] { @ '' E : \Temp\OR_rtftemplates.xml '' , @ '' E : \Temp\Tail.Web_Trace.cmd '' } ; var fileDragData = new DataObject ( DataFormats.FileDrop , _files ) ; ( sender as Form ) .DoDragDrop ( fileDragData , DragDropEffects.All ) ;... | How to drag files from c # winforms app to outlook message |
C# | I just created the following method in one of my classesAnd a friend of mine , reviewing my code , said that I should n't create methods that 'extend the List class ' , since that violates the open/closed principle.If I want to extend the class List I should create a new class that inherits from List and implement my `... | public static bool Assimilate ( this List < Card > first , List < Card > second ) { // Trivial if ( first.Count == 0 || second.Count == 0 ) { return false ; } // Sort the lists , so I can do a binarySearch first.Sort ( ) ; second.Sort ( ) ; // Copia only the new elements int index ; for ( int i = 0 ; i < second.Count ;... | Extending List < T > and Violating The Open/Closed Principle |
C# | I recently started to make video games using the XNA game studio 4.0 . I have made a main menu with 4 sprite fonts using a button list . They change color from White to Yellow when I press the up and down arrows.My problem is that when I scroll through it goes from the top font to the bottom font really fast and goes s... | public void Update ( GameTime gameTime ) { keyboard = Keyboard.GetState ( ) ; if ( CheckKeyboard ( Keys.Up ) ) { if ( selected > 0 ) { selected -- ; } } if ( CheckKeyboard ( Keys.Down ) ) { if ( selected < buttonList.Count - 1 ) { selected++ ; } } keyboard = prevKeyboard ; } public bool CheckKeyboard ( Keys key ) { ret... | Main Menu navigation / keyboard input speed is too fast |
C# | I am working on a class that needs run a different process method based on the type of object I pass in . I thought that overloading might work here , but I have a question . Lets say I have two interfaces : and and a class to process these objects : My question is , being that ISpecialEmail inherits from IEmail , are ... | public interface IEmail { Some properties ... } public interface ISpecialEmail : IEmail { Some more properties ... . } public class EmailProcessor { public void ProcessEmail ( IEmail email ) { do stuff ; } public void ProcessEmail ( ISpecialEmail email ) { do different stuff } } | C # inheritance and method signatures |
C# | My program have a pluginManager module , it can load a DLL file and run DLL 's methods , but I need read the DLL properties before Assembly.LoadFile ( ) . What should I do ? I readed about Assembly documents , they read properties after Assembly.LoadFile ( ) , you know Assembly no UnLoad ( ) Method , so I must read pro... | private void ImprotZip ( string path ) { /* 1、create tempDir , uppackage to tempDir 2、Load Plugin DLL , Load plugin dependent lib DLL */ string tempDirectory = CreateRuntimeDirectory ( path ) ; string [ ] dllFiles = Directory.GetFiles ( tempDirectory ) ; ///Load DlL foreach ( string dll in dllFiles ) { ImprotDll ( dll ... | How to read properties from DLL before Assembly.LoadFile ( ) |
C# | In my system I have tasks , which can optionally be assigned to contacts . So in my business logic I have the following code : If no contact was specified , the contact variable is null . This is supposed to null out the contact relationship when I submit changes , however I have noticed this is n't happening 99 % of t... | if ( _contactChanged ) { task.Contact = contact ; } { System.Data.Entity.DynamicProxies.Contact_4DF70AA1AA8A6A94E9377F65D7B1DD3A837851FD3442862716FA7E966FFCBAB9 } | Why does my EF4.1 relationship not get set to null upon assignment of a null value ? |
C# | For some of my code I use a method which looks like this : and I want to use it like this ( simple example ) : now , obviously , I know that there is no way MyMethod could never return anything , because it will always ( indirectly ) throw an exception.But of course I get the compiler value `` not all paths return a va... | public static void Throw < TException > ( string message ) where TException : Exception { throw ( TException ) Activator.CreateInstance ( typeof ( TException ) , message ) ; } public int MyMethod ( ) { if ( ... ) { return 42 ; } ThrowHelper.Throw < Exception > ( `` Test '' ) ; // I would have to put `` return -1 ; '' o... | Is there something like [ [ noreturn ] ] in C # to indicate the compiler that the method will never return a value ? |
C# | I have the below string I need the output asAs can be make out that it can be easily done by splitting by `` , '' but the problem comes when it is MAV # ( X , , ) or MOV # ( X,12,33 ) type.Please help | P , MV , A1ZWR , MAV # ( X , , ) , PV , MOV # ( X,12,33 ) , LO PMVA1ZWRMAV # ( X , , ) PVMOV # ( X,12,33 ) LO | String Splitter in .NET |
C# | I 'm profiling some C # code . The method below is one of the most expensive ones . For the purpose of this question , assume that micro-optimization is the right thing to do . Is there an approach to improve performance of this method ? Changing the input parameter to p to ulong [ ] would create a macro inefficiency . | static ulong Fetch64 ( byte [ ] p , int ofs = 0 ) { unchecked { ulong result = p [ 0 + ofs ] + ( ( ulong ) p [ 1 + ofs ] < < 8 ) + ( ( ulong ) p [ 2 + ofs ] < < 16 ) + ( ( ulong ) p [ 3 + ofs ] < < 24 ) + ( ( ulong ) p [ 4 + ofs ] < < 32 ) + ( ( ulong ) p [ 5 + ofs ] < < 40 ) + ( ( ulong ) p [ 6 + ofs ] < < 48 ) + ( ( ... | Optimize C # Code Fragment |
C# | instead ofAm I correct in thinking that the first line of code will always perform an assignment ? Also , is this a bad use of the null-coalescing operator ? | myFoo = myFoo ? ? new Foo ( ) ; if ( myFoo == null ) myFoo = new Foo ( ) ; | Bad Use of Null Coalescing Operator ? |
C# | Entity framework has synchronous and asynchronous versions of the same IO-bound methods such as SaveChanges and SaveChangesAsync . How can I create new methods that minimally accomplish the same task without `` duplicating '' code ? | public bool SaveChanges ( ) { //Common code calling synchronous methods context.Find ( ... ) ; //Synchronous Save return context.SaveChanges ( ) ; } public async Task < bool > SaveChangesAsync ( ) { //Common code asynchronous methods await context.FindAsync ( ... ) ; //Asynchronous Save return await context.SaveChanges... | How can I easily support duplicate async/sync methods ? |
C# | I am creating a C # TBB . I have the XML code as shown below.C # TBB code : In the XML code `` body '' tag is occured multiple times . I need to extract the each and every `` body '' tag content . For that purpose I am using HTML agility pack . To make it work in the C # TBB , How to add the HTML agility pack DLL to th... | < content > < ah > 123 < /ah > < ph > 456 < /ph > < body > < sc > hi < /sc > < value > aa < /value > < value > bb < /value > < value > cc < /value > < value > dd < /value > < value > dd < /value > < /body > < body > < sc > hello < /sc > < value > ee < /value > < value > ddff < /value > < /body > < /content > using ( Me... | How to add third party dll in Tridion for C # TBB ? |
C# | Consider the following code : Will the compiler optimize the calls to Test.OptionOne.ToString ( ) or will it call it for each item in the testValues collection ? | enum Test { OptionOne , OptionTwo } List < string > testValues = new List < string > { ... } // A huge collection of stringsforeach ( var val in testValues ) { if ( val == Test.OptionOne.ToString ( ) ) // **Here** { // Do something } } | Will the C # compiler optimize calls to a same method inside a loop ? |
C# | I remember few weeks ago when I reorgnized our code and created some namespaces in our project I got error and the system did not allow me to create a companyName.projectName.System namespace , I had to change it to companyName.projectName.Systeminfo . I do n't know why . I know there is a System namespace but it is no... | Error 7 The type or namespace name 'Windows ' does not exist in the namespace 'MyCompany.SystemSoftware.System ' ( are you missing an assembly reference ? ) C : \workspace\SystemSoftware\SystemSoftware\obj\Release\src\startup\App.g.cs 39 39 SystemSoftware | C # : why can I not create a system namespace ? |
C# | We have developed a WPF Application with C # and are using RestSharp to communicate with a simple Web Service like this : It all worked great until we received calls that on some machines ( most work ) the app ca n't connect to the service.A direct call to the service method with fiddler worked . Then we extracted a sm... | Client = new RestClient ( serviceUri.AbsoluteUri ) ; Client.Authenticator = new NtlmAuthenticator ( SvcUserName , SvcPassword.GetString ( ) ) ; RestClient Client = new RestClient ( `` https : //mysvc.mycorp.com/service.svc '' ) ; Client.Authenticator = new NtlmAuthenticator ( `` corp\\svc_account '' , `` mypassword '' ... | 401 when calling Web Service only on particular machines |
C# | I 'm wrestling with a weird , at least for me , method overloading resolution of .net . I 've written a small sample to reproduce the issue : Will print : Basically the overload called is different depending on the value ( 0 , 1 ) instead of the given data type.Could someone explain ? UpdateI should have pointed out th... | class Program { static void Main ( string [ ] args ) { var test = new OverloadTest ( ) ; test.Execute ( 0 ) ; test.Execute ( 1 ) ; Console.ReadLine ( ) ; } } public class OverloadTest { public void Execute ( object value ) { Console.WriteLine ( `` object overload : { 0 } '' , value ) ; } public void Execute ( MyEnum va... | Method overload resolution unexpected behavior |
C# | I have a pair of libraries that both use the same COM interface . In one library I have a class that implements that interface . The other library requires an object that implements the interface.However both libraries have their own definition of the interface . Both are slightly different but essentially the same int... | Library2.Interface intf = ( Library2.Interface ) impl ; Library1.Interface intf = ( Library1.Interface ) impl ; | Converting between 2 different libraries using the same COM interface in C # |
C# | Let 's say there 's a class that with one public constructor , which takes one parameter . In addition , there are also multiple public properties I 'd like to set . What would be the syntax for that in F # ? For instance in C # In F # I can get this done using either the constructor or property setters , but not both ... | public class SomeClass { public string SomeProperty { get ; set ; } public SomeClass ( string s ) { } } //And associated usage.var sc = new SomeClass ( `` '' ) { SomeProperty = `` '' } ; let sc1 = new SomeClass ( `` '' , SomeProperty = `` '' ) let sc2 = new SomeClass ( s = `` '' , SomeProperty = `` '' ) let sc3 = new S... | In F # , what is the object initializer syntax with a mandatory constructor parameter ? |
C# | I 've got this code in my App.xaml.cs : I would like to do something similar for the InitializedEvent.Here 's my failed attempt : Is the InitializedEvent somewhere else ? Is this even possible ? I 've tried using the LoadedEvent : It only fired for Windows and not the controls inside the Windows . I did realize though ... | protected override void OnStartup ( StartupEventArgs e ) { EventManager.RegisterClassHandler ( typeof ( TextBox ) , TextBox.TextChangedEvent , new RoutedEventHandler ( TextBox_TextChangedEvent ) ) ; } private void TextBox_TextChangedEvent ( object sender , RoutedEventArgs e ) { // Works } protected override void OnStar... | How do I assign a global initialized event ? |
C# | i am reading Accelerated C # i do n't really understand the following code : in the last line what is x referring to ? and there 's another : How do i evaluate this ? ( y ) = > ( x ) = > func ( x , y ) what is passed where ... it does confusing . | public static Func < TArg1 , TResult > Bind2nd < TArg1 , TArg2 , TResult > ( this Func < TArg1 , TArg2 , TResult > func , TArg2 constant ) { return ( x ) = > func ( x , constant ) ; } public static Func < TArg2 , Func < TArg1 , TResult > > Bind2nd < TArg1 , TArg2 , TResult > ( this Func < TArg1 , TArg2 , TResult > func... | Need help understanding lambda ( currying ) |
C# | I just updated Visual Studio 2013 and I noticed that in the project template for an MVC application the ApplicationDbContext class now has a static method that just calls the constructor : This seems like clutter to me but I imagine that there is some semantic reason that I should now start using ApplicationDbContext.C... | public static ApplicationDbContext Create ( ) { return new ApplicationDbContext ( ) ; } | Is there any benefit ( semantic or other ) to using a static method that calls a constructor ? |
C# | I am trying to use the stack exchange MiniProfiler in my asp MVC project , but getting a really annoying error message in my view , where I am callingandon the RenderIncludes line , VS complains that The type 'MiniProfiler ' exists in both 'MiniProfiler.Shared , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b44f93... | @ using StackExchange.Profiling @ MiniProfiler.RenderIncludes ( ) < Reference Include= '' MiniProfiler , Version=3.2.0.157 , Culture=neutral , PublicKeyToken=b44f9351044011a3 , processorArchitecture=MSIL '' > < HintPath > ..\packages\MiniProfiler.3.2.0.157\lib\net40\MiniProfiler.dll < /HintPath > < /Reference > < packa... | The type MiniProfiler exists in both Miniprofiler.Shared and MiniProfiler |
C# | I have a fairly complex thing stuffed into a T4 template . Basically I take something like { =foo= } more text ... and convert it into a class ( view ) like so : The code generated is of course much more complicated than this . Anyway , the T4 template is over 600 lines of code right now and really becoming unmanageabl... | public class MyView { public string foo { get ; set ; } public string Write ( ) { return foo+ @ '' more text ... '' ; } } | Is there anything out there to make T4 code more ... clean ? |
C# | Thanks for looking . I 'm kind of new to Ninject and like it so far . I get the part where you bind one thing in debug mode and bind another in release mode . Those are global bindings where you have to declare that every Samurai will have a sword or a dagger , using Ninjects example code . It 's not either/or , it 's ... | using System ; using Ninject ; namespace NinjectConsole { class Program { //here is where we have to choose which weapon ever samurai must use ... public class BindModule : Ninject.Modules.NinjectModule { public override void Load ( ) { //Bind < IWeapon > ( ) .To < Sword > ( ) ; Bind < IWeapon > ( ) .To < Shuriken > ( ... | One samurai with a sword and one with a dagger |
C# | So I have some code in VB that I am trying to convert to C # . This code was written by someone else and I am trying to understand it but with some difficulty . I have some bitwise operator and enum comparison to do but keep throwing an error out : I can not say that i have used a lot of these syntaxes before and am ba... | Flags = Flags And Not MyEnum.Value ' Flags is of type int Flags = Flags & ! MyEnum.Value ; // Flags is of type int | Operator ' ! ' can not be applied to operand of type x |
C# | I 'm reading Effective C # ( Second Edition ) and it talks about method inlining.I understand the principle , but I do n't see how it would work based on the 2 examples in the book . The book says : Inlining means to substitute the body of a function for the function call.Fair enough , so if I have a method , and its c... | public string SayHiTo ( string name ) { return `` Hi `` + name ; } public void Welcome ( ) { var msg = SayHiTo ( `` Sergi '' ) ; } public void Welcome ( ) { var msg = `` Hi `` + `` Sergi '' ; } // readonly name propertypublic string Name { get ; private set ; } // access : string val = Obj.Name ; string val = `` Defaul... | How does method inlining work for auto-properties in C # ? |
C# | Using Entity-Framework 6 I 'm able to set up the configuration through Fluent Api like this : Source from this questionUsing the attribute approach I 'm able to know what 's the property roles by reflection , but I wonder how can I retrieve these configurations , like Key for example , with Fluent Api approach ? There ... | public class ApplicationUserConfiguration : EntityTypeConfiguration < ApplicationUser > { public ApplicationUserConfiguration ( ) { this.HasKey ( d = > d.Id ) ; this.Ignore ( d = > d.UserId ) ; } } | How to retrieve Entity Configuration from Fluent Api |
C# | Having a list of structs OR maybe an array List each with 3 elements , likeI want to get rid of items that have 2 common subitems in list , in the example I would like to removeSo using structs approach I am thinking in sorting the list by element A , then looping and comparing elements , in a way that If current eleme... | 12 8 75 1 07 3 210 6 56 2 18 4 36 1 57 2 68 3 79 4 811 7 613 9 811 6 1012 7 1113 8 1214 9 13 5 1 06 2 16 1 57 3 27 2 68 4 38 3 7 has 2 same items as row 7,3,29 4 8 has 2 same items as row 8,4,310 6 511 7 611 6 10 has 2 same items as row 11,7,612 7 11 has 2 same items as row 11,7,1012 8 713 8 1213 9 814 9 13 has 2 same ... | How to remove elements of list of array/structs that have 2 common elements |
C# | When the C # compiler interprets a method invocation it must use ( static ) argument types to determine which overload is actually being invoked . I want to be able to do this programmatically.If I have the name of a method ( a string ) , the type that declares it ( an instance of System.Type ) , and a list of argument... | class MyClass { public void myFunc ( BaseClass bc ) { } ; public void myFunc ( DerivedClass dc ) { } ; } MethodInfo methodToInvoke = typeof ( MyClass ) .GetOverloadedMethod ( `` myFunc '' , new System.Type [ ] { typeof ( BaseClass ) } ) ; | How can I programmatically do method overload resolution in C # ? |
C# | I 'm trying to obfuscate a string , but need to preserve a couple patterns . Basically , all alphanumeric characters need to be replaced with a single character ( say ' X ' ) , but the following ( example ) patterns need to be preserved ( note that each pattern has a single space at the beginning ) QQQ '' RRR '' I 've ... | var test = @ '' '' '' SOME TEXT AB123 12XYZ QQQ '' '' '' '' empty '' '' '' '' empty '' '' 1A2BCDEF '' ; var regex = new Regex ( @ '' ( ( ? ! QQQ ) ( ? < ! \sQ { 1,3 } ) ) [ 0-9a-zA-Z ] '' ) ; var result = regex.Replace ( test , `` X '' ) ; `` XXXX XXXX XXXXX XXXXX QQQ '' '' XXXXX '' '' XXXXX '' XXXXXXXX `` XXXX XXXX XX... | Replace all alphanumeric characters in a string except pattern |
C# | What should IEquatable < T > .Equals ( T obj ) do when this == null and obj == null ? 1 ) This code is generated by F # compiler when implementing IEquatable < T > . You can see that it returns true when both objects are null:2 ) Similar code can be found in the question `` in IEquatable implementation is reference che... | public sealed override bool Equals ( T obj ) { if ( this == null ) { return obj == null ; } if ( obj == null ) { return false ; } // Code when both this and obj are not null . } public sealed override bool Equals ( T obj ) { if ( obj == null ) { return false ; } // Code when obj is not null . } | Result of calling IEquatable < T > .Equals ( T obj ) when this == null and obj == null ? |
C# | Let 's say I have these two methods : The following were the results I got : I understand that PLINQ has some overhead because of the threads setup , but with such a big n I was expecting PLINQ to be faster.Here is another result : | public BigInteger PFactorial ( int n ) { return Enumerable.Range ( 1 , n ) .AsParallel ( ) .Select ( i = > ( BigInteger ) i ) .Aggregate ( BigInteger.One , BigInteger.Multiply ) ; } public BigInteger Factorial ( int n ) { BigInteger result = BigInteger.One ; for ( int i = 1 ; i < = n ; i++ ) result *= i ; return result... | Why is PLINQ slower than for loop ? |
C# | This is my C # Code : HTML Code : Javascript Code : I want show 'username ' in text field but when form will be post I want to send 'ID ' . Instead of that I am getting username . | public JsonResult FillUsers ( string term ) { var Retailers = from us in db.Users join pi in db.UserPersonalInfoes on us.ID equals pi.UserID into t from rt in t.DefaultIfEmpty ( ) where us.Status == true select new { ID = us.ID , Username = us.Username + `` : ( `` + ( rt == null ? String.Empty : rt.FirstName ) + `` ) '... | How to post value from autocomplete instead of text ? |
C# | I have on my winform two panels : on the first panel I have an usercontrol that can be multiplied dynamically . I want , on the second panel , to be displayed the usercontrol that is selected by the user . The idea is that , I want , if I change the text at runtime of my usercontrol , these changes to be displayed on t... | public string TextName { get { return textname.Text ; } set { textname.Text = value ; } } public string Task { get { return checkboxTip.Text ; } set { checkboxTip.Text = value ; } } ... ... . and on my winform.cs I created an event for all properties : private void PropertiesChange_Click ( object sender , EventArgs e )... | Display control on another panel |
C# | Given a function async Task < ( Boolean result , MyObject value ) > TryGetAsync ( ) , I can doBut if I try to use declare the types or use deconstruction get an error `` a declaration is not allowed in this context '' : How can I avoid using the first option var ret in this scenario ? My issue with this is that the typ... | if ( ( await TryGetAsync ( ) ) is var ret & & ret.result ) { //use ret.value } //declaration . errorif ( ( await TryGetAsync ( ) ) is ( Boolean result , MyObject value ) ret & & ret.result ) { //use ret.value } //deconstruction , also error.if ( ( await TryGetAsync ( ) ) is ( Boolean result , MyObject value ) & & resul... | Deconstruct tuple for pattern matching |
C# | I have to unit test my BlogController 's CreatePost action method . I am passing SavePostViewModel without some fields like Author , Subject , and Postdate which are required field to test CreatePost action method should returns `` Invalid Input '' which is in ( ! ModelState.IsValid ) logic . But it 's always return tr... | public class SavePostViewModel : ISavePostDto { public SavePostViewModel ( ) { PostDate = Helper.LocalDateToday ; CategoryIds = new List < int > ( ) ; } [ DisplayName ( `` Post ID '' ) ] public int ? Id { get ; set ; } [ DisplayName ( `` Post Date '' ) ] [ Required ( ErrorMessage = `` { 0 } is required '' ) ] public Da... | Why ModelState.IsValid always return true ? |
C# | My colleague was getting an error with a more complex query using LINQ to SQL in .NET 4.0 , but it seems to be easily reproducible in more simpler circumstances . Consider a table named TransferJob with a synthetic id and a bit field.If we make the following queryAn invalid cast exception is thrown where noted . But st... | using ( var ctx = DBDataContext.Create ( ) ) { var withOutConstant = ctx.TransferJobs.Select ( x = > new { Id = x.TransferJobID , IsAuto = x.IsFromAutoRebalance } ) ; var withConstant = ctx.TransferJobs.Select ( x = > new { Id = x.TransferJobID , IsAuto = true } ) ; //note we 're putting a constant value in this one va... | Odd behavior in LINQ to SQL with anonymous objects and constant columns |
C# | I 'm using automatic globalization on an ASP MVC website . It works fine until it reached a parallel block : What is the best way to make the parallel block inherit the culture ? apart from this solution : | public ActionResult Index ( ) { // Thread.CurrentThread.CurrentCulture is automatically set to `` fr-FR '' // according to the requested `` Accept-Language '' header Parallel.Foreach ( ids , id = > { // Not every thread in this block has the correct culture . // Some of them still have the default culture `` en-GB '' }... | How to correctly inherit thread culture in a parallel block ? |
C# | In MVC 6 source code I saw some code lines that has strings leading with $ signs.As I never saw it before , I think it is new in C # 6.0 . I 'm not sure . ( I hope I 'm right , otherwise I 'd be shocked as I never crossed it before.It was like : | var path = $ '' ' { pathRelative } ' '' ; | What does ' $ ' sign do in C # 6.0 ? |
C# | I am writing a small application that prints some stickers to a special printer.When I use MS Word to print some text to that printer ( and to an XPS file ) , the result looks excellent . When I print from C # code with the Graphics object , the text appears to be over-pixelized or over-smoothed.I tried the following h... | System.Drawing.Drawing2D.SmoothingMode.AntiAliasSystem.Drawing.Text.TextRenderingHint.AntiAliasGridFitSystem.Drawing.Text.TextRenderingHint.AntiAliasSystem.Drawing.Text.TextRenderingHint.ClearTypeGridFitInterpolationMode.NearestNeighborCompositingQuality.HighQuality | Achieving MS Word print quality in C # |
C# | Sorry if this sounds simple , but I 'm looking for some help to improve my code : ) So I currently have the following implementation ( which I also wrote ) : Then I have technology-specific concrete classes : Now I 'm trying to add a generic optimizer , one that optimizes for conditions other than priority , so my atte... | public interface IOptimizer { void Optimize ( ) ; string OptimizerName { get ; } } public abstract AbstractOptimizer : IOptimizer { public void Optimize ( ) { // General implementation here with few calls to abstract methods } } public abstract AbstractPriorityOptimizer : AbstractOptimizer { // Optimize according to pr... | Refactoring abstract class in C # |
C# | For testing purposes , I need to mock a Task-returning method on an interface handing back a task that never runs the continuation . Here 's the code I have so far : Here , I 've created a custom awaitable type that simply ignores the continuation handed to it -- await new StopAwaitable ( ) has essentially the same eff... | // FooTests.cs [ Test ] public void Foo ( ) { var yielder = Substitute.For < IYielder > ( ) ; yielder.YieldAsync ( ) .Returns ( ThreadingUtilities.NeverReturningTask ) ; ... } // ThreadingUtilities.csusing System.Diagnostics ; using System.Threading.Tasks ; namespace Repository.Editor.Android.UnitTests.TestInternal.Thr... | What 's the most concise way to create a Task that never returns ? |
C# | I made a form and extended the glass in it like in the image below . But when I move the window so not all of it is visible on screen , the glass rendering is wrong after I move it back : How can I handle this so the window is rendered correctly ? This is my code : | [ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmExtendFrameIntoClientArea ( IntPtr hWnd , ref Margins mg ) ; [ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmIsCompositionEnabled ( out bool enabled ) ; public struct Margins { public int Left ; public int Right ; public int Top ; public ... | Glass is not rendered right |
C# | I 've this code : I want to have the same name for my two methods . Is this even possible ? My problems : I have to write two different methods because of the return type ( I want it to be null if the request failed or a value if the request succeed ) which is Nullable < T > if T is a value type , and an instance of T ... | public async static Task < T ? > RequestValue1 < T > ( Command requestCommand ) where T : struct { // Whatever } public async static Task < T > RequestValue2 < T > ( Command requestCommand ) where T : class { // Whatever } | Generics , Nullable , Type inference and function signature conflict |
C# | I am using the MVVM Light library . From this library I use RelayCommand < T > to define commands with an argument of type T. Now I have defined a RelayCommand that requires an argument of type Nullable < bool > : How can I assign the CommandParameter from my XAML code ? I 've tried to pass a boolean value , but that c... | private RelayCommand < bool ? > _cmdSomeCommand ; public RelayCommand < bool ? > CmdSomeCommand { get { if ( _cmdSomeCommand == null ) { _cmdSomeCommand = new RelayCommand < bool ? > ( new Action < bool ? > ( ( val ) = > { /* do work */ } ) ) ; } return _cmdSomeCommand ; } } public static class BooleanHelper { public s... | How do I pass Nullable < Boolean > value to CommandParameter ? |
C# | I have 2 classes , each returns itself in all of the function : I want to enable this kind of API : SetName can not be accessed since SetId returns Parent and SetName is on the Child.How ? | public class Parent { public Parent SetId ( string id ) { ... return this } } public class Child : Parent { public Child SetName ( string id ) { ... return this } } new Child ( ) .SetId ( `` id '' ) .SetName ( `` name '' ) ; | C # Object oriented return type `` this '' on child call |
C# | I 'm trying to figure out what 's the difference between these two rules ? MergeSequentialChecksMergeSequentialChecksWhenPossibleThe documentation does n't say anything about the second one.https : //www.jetbrains.com/help/resharper/2016.1/MergeSequentialChecks.htmlAnd it 's not quire clear for me what does it mean Whe... | public class Person { public string Name { get ; set ; } public IList < Person > Descendants { get ; set ; } } public static class TestReSharper { // Here ` MergeSequentialChecks ` rule is triggered for both ` & & ` operands . public static bool MergeSequentialChecks ( Person person ) { return person ! = null & & perso... | What 's the difference between ReSharper ` MergeSequentialChecks ` and ` MergeSequentialChecksWhenPossible ` ? |
C# | I 'm in the process of converting my Microsoft SDK Beta code to the Microsoft SDK Official Release that was released February 2012 . I added a generic PauseKinect ( ) to pause the Kinect . My pause will really only remove the event handler that updated the image Pros : No Reinitialization ( 30+ second wait time ) Cons ... | internal void PauseColorImage ( bool isPaused ) { if ( isPaused ) { _Kinect.ColorFrameReady -= ColorFrameReadyEventHandler ; //_Kinect.ColorStream.Disable ( ) ; } else { _Kinect.ColorFrameReady += ColorFrameReadyEventHandler ; //_Kinect.ColorStream.Enable ( ColorImageFormat.RgbResolution640x480Fps30 ) ; } } public void... | Pause Kinect Camera - Possible error in SDK reguarding event handler |
C# | Here 's a simple test demonstrating the problem : I need a comparing method which will determine that these two properties are actually represent the same property . What is the correct way of doing this ? In particular I want to check if property actually comes from base class and not altered in any way like overriden... | class MyBase { public int Foo { get ; set ; } } class MyClass : MyBase { } [ TestMethod ] public void TestPropertyCompare ( ) { var prop1 = typeof ( MyBase ) .GetProperty ( `` Foo '' ) ; var prop2 = typeof ( MyClass ) .GetProperty ( `` Foo '' ) ; Assert.IsTrue ( prop1 == prop2 ) ; // fails //Assert.IsTrue ( prop1.Equal... | How to compare same PropertyInfo with different ReflectedType values ? |
C# | When a method has two overloads , one accepting IDictionary and another accepting IDictionary < TKey , TValue > , passing new Dictionary < string , int > ( ) to it is considered ambigous . However , if the two overloads are changed to accept IEnumerable and IEnumerable < KeyValuePair < TKey , TValue > > , the call is n... | using System ; using System.Collections ; using System.Collections.Generic ; namespace AmbigousCall { internal class Program { static void Main ( string [ ] args ) { var dic = new Dictionary < string , int > ( ) ; FooDic ( dic ) ; // Error : The call is ambiguous FooEnum ( dic ) ; // OK : The generic method is called C... | Ambiguous call when a method has overloads for IDictionary and IDictionary < TKey , TValue > |
C# | Using c # HttpClient to POST data , hypothetically I 'm also concerned with the returned content . I 'm optimizing my app and trying to understand the performance impact of two await calls in the same method . The question popped up from the following code snippet , Assume I have error handling in there : ) I know awai... | public static async Task < string > AsyncRequest ( string URL , string data = null ) { using ( var client = new HttpClient ( ) ) { var post = await client.PostAsync ( URL , new StringContent ( data , Encoding.UTF8 , `` application/json '' ) ) .ConfigureAwait ( false ) ; post.EnsureSuccessStatusCode ( ) ; var response =... | Double await operations during POST |
C# | Does the line fixed ( int* pArray = & array [ 0 ] ) from the example below pin the whole array , or just array [ 0 ] ? | int array = new int [ 10 ] ; unsafe { fixed ( int* pArray = & array [ 0 ] ) { } // or just 'array ' } | How to pin the whole array in C # using the keyword fixed |
C# | I just relfected over WindowsBase.dll > > System.Windows.UncommonField < T > and I wondered about the usage of this class ... E.g . it 's used in the Button-class : So what is the use of this `` wrapper '' ? | public class Button : ButtonBase { private static readonly UncommonField < KeyboardFocusChangedEventHandler > FocusChangedEventHandlerField = new UncommonField < KeyboardFocusChangedEventHandler > ( ) ; } | The use of UncommonField < T > in WPF |
C# | Is there a way to have a common logic to retrieve the file size on disk regardless of the underlying operating system ? The following code works for windows but obviously does n't for Linux.Alternatively , I 'm looking for a similar implementation that would work on Linux . Can anyone point me in the right direction ? ... | public static long GetFileSizeOnDisk ( string file ) { FileInfo info = new FileInfo ( file ) ; uint dummy , sectorsPerCluster , bytesPerSector ; int result = GetDiskFreeSpaceW ( info.Directory.Root.FullName , out sectorsPerCluster , out bytesPerSector , out dummy , out dummy ) ; if ( result == 0 ) throw new Win32Except... | C # .net Core - Get file size on disk - Cross platform solution |
C# | I 'm using method overloading in Assembly A : When I try to call the second overload from Assembly B , VS produces the following compile-time error : The type 'System.Data.Entity.DbContext ' is defined in an assembly that is not referenced . You must add a reference to assembly 'EntityFramework , Version=6.0.0.0 , Cult... | public static int GetPersonId ( EntityDataContext context , string name ) { var id = from ... in context ... where ... select ... ; return id.First ( ) ; } public static int GetPersonId ( SqlConnection connection , string name ) { using ( var context = new EntityDataContext ( connection , false ) ) { return GetPersonId... | Weird `` assembly not referenced '' error when trying to call a valid method overload |
C# | hi everybody I want used shortcut key ( using left and right key ) in wpf and tabcontrol to navigation between tabitem I set code in Window_KeyDown ( object sender , System.Windows.Input.KeyEventArgs e ) like this : but it 's not do anything I want navigation between tabitem with left and right keythanks | switch ( e.Key ) { case Key.Right : if ( tbControl.TabIndex == 0 ) tbControl.TabIndex = 1 ; break ; case Key.Left : if ( tbControl.TabIndex == 0 ) tbControl.TabIndex = 1 ; break ; } | how to navigate between tabitem with Left and Right Key in WPF |
C# | First of all , this will not be a post about Database Transactions . I want to know more about the TransactionModel in .NET 2.0 and higher . Since I am developing against .NET 3.5 newer models are apprechiated.Now , what I would like to acheive is something like the followingWhich would mean that when the Money is less... | public void Withdraw ( double amount ) { using ( TransactionScope scope = new TransactionScope ( ) ) { Money -= amount ; if ( Money > 0 ) scope.Complete ( ) ; } } ImportantObject obj = new ImportantObject ( 1 ) ; Console.WriteLine ( obj.Money ) ; obj.Withdraw ( 101 ) ; Console.WriteLine ( obj.Money ) ; | Transactions in C # |
C# | If I have an IOrderedEnumberable < Car > , I sort it and then do a projecting query ... is the order preserved in the projection ? For example , does this scenario work ? Does the name of the top3FastestCarManufacturers variable convey the meaning of what has really happened in the code ? | IOrderedEnumberable < Car > allCarsOrderedFastestToSlowest = GetAllCars ( ) .OrderByDescending ( car= > car.TopSpeed ) ; var top3FastestCarManufacturers = allCarsOrderedFastestToSlowest .Select ( car= > car.Manufacturer ) .Distinct ( ) .Take ( 3 ) ; | In LINQ , do projections off an IOrderedEnumerable < T > preserve the order ? |
C# | I know that 's not possible as written , and as far as I understand it 's just simply not allowed ( although I would love nothing more than to be wrong about that ) . The first solution that comes to mind is to use an object initializer , but let 's suppose that 's a last resort because it would conflict with other oop... | class MyClass < T > where T : new ( ) { public Test ( ) { var t = new T ( ) ; var t = new T ( `` blah '' ) ; // < - How to do this ? } } | Instantiating a generic type with an overloaded constructor |
C# | I was reading `` CLR via C # '' and it seems that in this example , the object that was initially assigned to 'obj ' will be eligible for Garbage Collection after line 1 is executed , not after line 2.That 's because local variable lifespan defined not by scope in which it was defined , but by last time you read it.So ... | void Foo ( ) { Object obj = new Object ( ) ; obj = null ; } class TestProgram { public static void main ( String [ ] args ) { TestProgram ref = new TestProgram ( ) ; System.gc ( ) ; } @ Override protected void finalize ( ) { System.out.println ( `` finalized '' ) ; } } public static void Main ( string [ ] args ) { var ... | Objects lifespan in Java vs .Net |
C# | I am trying to learn ASP.NET 5 . I am using it on Mac OS X . At this time , I have a config.json file that looks like the following : config.jsonI am trying to figure out how to load these settings into a configuration file in Startup.cs . Currently , I have a file that looks like this : Configuration.csThen , in Start... | { `` AppSettings '' : { `` Environment '' : '' dev '' } , `` DbSettings '' : { `` AppConnectionString '' : `` ... '' } , `` EmailSettings '' : { `` EmailApiKey '' : `` ... '' } , } public class AppConfiguration { public AppSettings AppSettings { get ; set ; } public DbSettings DbSettings { get ; set ; } public EmailSet... | ASP.NET 5 ( vNext ) - Configuration |
C# | Why does new List < string > ( ) .ToString ( ) ; return the following : ? Why would n't it just bring back System.Collections.Generic.List < System.String > . What 's with the strange non C # syntax ? | System.Collections.Generic.List ` 1 [ System.String ] | Why does ToString ( ) on generic types have square brackets ? |
C# | I found this link to make full-text search work through linq . However , the code seems to be targeting database first approach . How to make it work with Database First Approach ? Relevant part of code : As seen above the function OnModelCreating is only called in Code First Approach . I wonder what needs to change to... | public class NoteMap : EntityTypeConfiguration < Note > { public NoteMap ( ) { // Primary Key HasKey ( t = > t.Id ) ; } } public class MyContext : DbContext { static MyContext ( ) { DbInterception.Add ( new FtsInterceptor ( ) ) ; } public MyContext ( string nameOrConnectionString ) : base ( nameOrConnectionString ) { }... | EF6 : Full-text Search with Database First Approach |
C# | Error : The type arguments for method GraphMLExtensions.SerializeToGraphML < TVertex , TEdge , TGraph > ( TGraph , XmlWriter ) can not be inferred from the usage.The code is copied from QuickGraph 's documentation . However when I write it explicitly it works : Edit : I saw some related questions , but they are too adv... | using System.Xml ; using QuickGraph ; using QuickGraph.Serialization ; var g = new AdjacencyGraph < string , Edge < string > > ( ) ; ... . add some vertices and edges ... .using ( var xwriter = XmlWriter.Create ( `` somefile.xml '' ) ) g.SerializeToGraphML ( xwriter ) ; using ( var xwriter = XmlWriter.Create ( `` somef... | Extension method does n't work ( Quick Graph Serialization ) |
C# | I 'm creating a service that will monitor a specific folder and print any file that is put in this folder . I 'm having difficulties with the various file types that could be sent to the folder to be printed.My first attempt is with Microsoft Office files . What I 'm trying to do is start the office to print the file .... | ProcessStartInfo info = new ProcessStartInfo ( myDocumentsPath ) ; info.Verb = `` Print '' ; info.CreateNoWindow = true ; info.WindowStyle = ProcessWindowStyle.Hidden ; Process.Start ( info ) ; | Printing any file type |
C# | If one of the strings is n't 10 characters long I 'd get an ArgumentOutOfRangeException . In this case its fairly trivial to find out and I know I can do With more complex object construction errors like this are n't always easy to see though . Is there a way to see what string was n't long enough via exception handlin... | var trimmed = myStringArray.Select ( s = > s.Substring ( 0 , 10 ) ) ; s.Substring ( 0 , Math.Min ( 10 , s.Length ) ) | LINQ Iterator Exception Handling |
C# | I try to write System Tests in NUnit and I want to Invoke the UI using the UI Automation from ms.For some reason my Invokes fail - I found some hints online that got me to a state where I can write a compiling test but my assertion fails.Here is a compileable minimal example . My problem is the failing test in the exam... | < Application x : Class= '' InvokeTest.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : InvokeTest '' Startup= '' Application_Startup '' / > using System.Windows ; namespace InvokeTest { publ... | How to Invoke a setter for a WPF Textbox in an NUnit Test |
C# | I have a co-worker who uses a C # refactoring tool . The tool for some reason perfers : overNow we 've asked him to turn it off simply because it 's annoying to have all the code re-written automatically , but that 's not the point.Am I missing something , or is this just wrong ? Why on earth would I want this.Foo ( ) ... | this.Foo ( ) Foo ( ) | Foo ( ) vs this.Foo ( ) |
C# | As described in my previous question : Asp.net web API 2 separation Of Web client and web server development In order to get full separation of client and server , I want to set a variable to hold the end point for client requests . When client side is developed , the requests will be sent to a `` stub server '' that r... | gulp.task ( 'setEndPoint ' , function ( ) { var branchName = // How do I get it ? if ( branchName == `` Project.Testing '' ) endPoint = `` localhost/2234 '' if ( branchName == `` Project.Production '' ) endPoint = `` localhost/2235 '' } ) ; | Web api - Use Gulp task to dynamically set end point address |
C# | I 've found a difference in overload resolution between the C # and the VB-compiler . I 'm not sure if it 's an error or by design : Note that it does n't matter if the overloaded Foo-methods are defined in VB or not . The only thing that matters is that the call site is in VB.The VB-compiler will report an error : Ove... | Public Class Class1 Public Sub ThisBreaks ( ) ' These work ' Foo ( Of String ) ( Function ( ) String.Empty ) 'Expression overload ' Foo ( String.Empty ) 'T overload ' ' This breaks ' Foo ( Function ( ) String.Empty ) End Sub Public Sub Foo ( Of T ) ( ByVal value As T ) End Sub Public Sub Foo ( Of T ) ( ByVal expression... | Is this an error in the VB.NET compiler or by design ? |
C# | What is happening below ? i is being converted to string in both cases . I am confusing myself with the idea of operator precedence ( although this example does n't show much of that ) and evaluation direction . Sometimes evaluation happens from left-to-right or vice versa . I do n't exactly know the science of how the... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; public class DotNetPad { public static void Main ( string [ ] args ) { int i = 10 ; string k = `` Test '' ; Console.WriteLine ( i+k ) ; Console.WriteLine ( k+i ) ; } } | Why is the integer converted to string in this case ? |
C# | I have a little C # app that is extracting text from a Microsoft Publisher file via the COM Interop API.This works fine , but I 'm struggling if I have multiple styles in one section . Potentially every character in a word could have a different font , format , etc.Do I really have to compare character after character ... | foreach ( Microsoft.Office.Interop.Publisher.Shape shp in pg.Shapes ) { if ( shp.HasTextFrame == MsoTriState.msoTrue ) { text.Append ( shp.TextFrame.TextRange.Text ) ; for ( int i = 0 ; i < shp.TextFrame.TextRange.WordsCount ; i++ ) { TextRange range = shp.TextFrame.TextRange.Words ( i+1 , 1 ) ; string test = range.Tex... | Get different style sections in Microsoft Publisher via Interop |
C# | I 'm working on an MVC page that requires conditional validation.When a user selects a country from a dropdownlist , if they select one of two specific countries , then a box is displayed containing two text boxes which are required . I would like validation to activate in this case , and if they select any other count... | new ValidatePresence ( `` countryId '' ) { ErrorMessageFormat = `` Please supply a country for delivery to '' } | ASP.net MVC conditional validation |
C# | 1 ) If one operand is of type ulong , while the other operand is of type sbyte/short/int/long , then compile-time error occurs . I fail to see the logic in this . Thus , why would it be bad idea for both operands to instead be promoted to type double or float ? b ) Compiler implicitly converts int literal into byte typ... | long L = 100 ; ulong UL = 1000 ; double d = L + UL ; // error saying + operator ca n't be applied to operands of type ulong and long byte b = 1 ; long L = 1000UL ; | Instead of error , why do n't both operands get promoted to float or double ? |
C# | Sorry about the stupid title , had no idea how to word thisI 'm creating a class that has two lists of the same type . It 's used to copy a reference to a object in the first list to the second list.While both lists will be of the same type ( hold the same type of object ) it can be different each time this class is in... | public partial class SubsetSelectionLists : UserControl { public static DependencyProperty SetCollectionProperty = DependencyProperty.Register ( `` SetCollection '' , typeof ( `` Need a abstract list type here '' ) , typeof ( SubsetSelectionLists ) ) ; public static DependencyProperty SubsetCollectionProperty = Depende... | C # : Implementation of two abstract lists within a non-generic class ? |
C# | I 've noticed that static methods seem more popular in F # than C # . In C # , you 'd always add an element to a collection by calling an instance method : But in F # there is usually an equivalent static method : And I 've seen the latter form quite often in samples . Both appear to me completely identical both semant... | mySet.Add ( elem ) ; mySet.Add ( elem ) // ORSet.Add elem mySet | F # coding style - static vs instance methods |
C# | Here 's a code reproducing the behavior I 'm expecting to get : The behavior is the same for any VS starting from VS2008 ( did not check on earlier versions ) .If you run it under debug ( using a standard debugging settings ) you 're not allowed to continue until you fix the code ( using the EnC ) . Hitting F5 will jus... | static void Main ( string [ ] args ) { // try // # 2 { string x = null ; // # 1 AssertNotNull ( x , nameof ( x ) ) ; } // catch ( ArgumentNullException ) { } // # 2 Console.WriteLine ( `` Passed . `` ) ; Console.ReadKey ( ) ; } [ DebuggerHidden ] public static void AssertNotNull < T > ( T arg , string argName ) where T... | Visual Studio : edit-and-continue on handled exceptions ? |
C# | After installing Visual Studio 2015 Update 1 on my machine I saw that some of my unit tests failed . After doing some investigation I was able to reduce the problem to this line of code : When hovering over the expression variable the results were different in the versions of Visual Studio : VS 2015 : VS 2015 Update 1 ... | Expression < Func < GameObject , bool > > expression = t = > t.X == 0 & & t.Y == 0 & & t.GameObjectType == GameObjectType.WindMill ; class Program { static void Main ( string [ ] args ) { var gameObjects = new List < GameObject > { new GameObject { X = 0 , Y = 0 , GameObjectType = GameObjectType.WindMill } , new GameOb... | Expressions breaking code when compiled using VS2015 Update 1 |
C# | I 'm getting recurring word counts in StringBuilder ( sb ) with this code which i 've found on internet and according to writer it 's really consistent like Word 's word counter.This is my sample text : The green algae ( singular : green alga ) are a large , informal grouping of algae consisting of the Chlorophyte and ... | StringBuilder wordBuffer = new StringBuilder ( ) ; int wordCount = 0 ; // 1 . Build the list of words used . Consider `` ' ( apostrophe ) and '- ' ( hyphen ) a word continuation character . Dictionary < string , int > wordList = new Dictionary < string , int > ( ) ; foreach ( char c in sb.ToString ( ) ) { if ( char.IsL... | How to find recurring word groups in text with C # ? |
C# | I 'm new to LINQ . I understand it 's purpose . But I ca n't quite figure it out . I have an XML set that looks like the following : I have loaded this XML into an XDocument as such : Now , I 'm trying to get the results into POCO format . In an effort to do this , I 'm currently using : How do I get a collection of Re... | < Results > < Result > < ID > 1 < /ID > < Name > John Smith < /Name > < EmailAddress > john @ example.com < /EmailAddress > < /Result > < Result > < ID > 2 < /ID > < Name > Bill Young < /Name > < EmailAddress > bill @ example.com < /EmailAddress > < /Result > < /Results > string xmlText = GetXML ( ) ; XDocument xml = X... | LINQ to XML via C # |
C# | This is a bit difficult to describe , but I need to mock/stub a method to return an instance of T based on inputs.The message signature looks like : Here is the code within the SUT : Here is what the setup should look like in my unit test : This does n't compile because x is an Action.Is what I 'm trying to do possible... | T DoSomething < T > ( Action < T > action ) ; var myEvent = _service.DoSomething < IMyEvent > ( y = > { y.Property1 = localProperty1 ; y.Property2 = localProperty2 ; } ) ; service.Setup ( x = > x.DoSomething < IMyEvent > ( It.IsAny < Action < IMyEvent > > ( ) ) ) .Returns ( ( ( Action < IMyEvent > x ) = > { return new ... | Mocking Action < T > to Return Value Based on Parameters |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.