lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I 'm a student and i 'm new around here . I have a course project to make a Paint-like program . I have a base class Shape with DrawSelf , Contains ect . methods and classes for Rectangle , Ellipse and Triangle for now . Also i have two other classed DisplayProccesor which is class for drawing , and DialogProcessor , w... | public class DisplayProcessor { public DisplayProcessor ( ) { } /// < summary > /// List of shapes /// < /summary > private List < Shape > shapeList = new List < Shape > ( ) ; public List < Shape > ShapeList { get { return shapeList ; } set { shapeList = value ; } } /// < summary > /// Redraws all shapes in shapeList /... | When rotating shape , it stays together with the rotated one |
C# | On my production server I have set environment variable by adding the following to /etc/environment : I checked it has recorded with printenv ASPNETCORE_ENVIRONMENT after a reboot.My server is Ubuntu 14.04 and I am using asp.net core 1.1.It is loading my appsettings.Development.json instead of appsettings.Production.js... | ASPNETCORE_ENVIRONMENT=Production public Startup ( IHostingEnvironment env ) { var builder = new ConfigurationBuilder ( ) .SetBasePath ( env.ContentRootPath ) .AddJsonFile ( `` appsettings.json '' , optional : false , reloadOnChange : true ) .AddJsonFile ( $ '' appsettings . { env.EnvironmentName } .json '' , optional ... | Ca n't set production server to production |
C# | Is it true that if i use the following , it will take less resources and the cleanup will be faster ? as compared to : | using ( TextReader readLogs = File.OpenText ( `` C : \\FlashAuto\\Temp\\log.txt '' ) ) { //my stuff } TextReader readLogs = new StreamReader ( `` C : \\FlashAuto\\Temp\\log.txt '' ) ; //my stuffreadLogs.Close ( ) ; readLogs.Dispose ( ) ; | using keyword takes less space ? |
C# | There are several options when one class must have a container ( collection ) of some sort of objects and I was wondering what implementation I shall prefer.Here follow the options I found : Pros : AClass is not dependent on a concrete implementation of a collection ( in this case List ) .Cons : AClass does n't have in... | public class AClass : IEnumerable < string > { private List < string > values = new List < string > ( ) IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } public IEnumerator < T > GetEnumerator ( ) { return values.GetEnumerator ( ) ; } } public class AClass : ICollection < string > { private List ... | Having a collection in class |
C# | We have a problem with AppFabric that is causing the below error to occur : This error happens infrequently in our test environment ( we have not found a scenario to reproduce the issue on demand ) , but seems to always happen in our production environment just after each deployment . Our deployments are automated and ... | Exception type : ArgumentException Exception message : An item with the same key has already been added . at System.Collections.Generic.Dictionary ` 2.Insert ( TKey key , TValue value , Boolean add ) at Microsoft.ApplicationServer.Caching.DataCacheFactory.CreateRoutingClient ( String cacheName , NamedCacheConfiguration... | AppFabric CreateRoutingClient Error |
C# | I have IdentityServer4 with Angular . Every 5 minutes the token is silent refreshed . But after 30minutes the user is automatically logged out . I was trying to set lifetime cookies somehow , without any success . This is my current configuration : @ EDITIf I will addThen it working fine , but I bet this is not correct... | public void ConfigureServices ( IServiceCollection services ) { services.AddDbContext < AppIdentityDbContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` Identity '' ) ) ) ; services.AddIdentity < AppUser , IdentityRole > ( options = > { options.Password.RequiredLength = 6 ; options.Pas... | IdentityServer4 automatically logout after 30 minutes |
C# | Hey , I 'm self-learning about bitwise , and I saw somewhere in the internet that arithmetic shift ( > > ) by one halfs a number . I wanted to test it : Another Example : Thanks . | 44 > > 1 returns 22 , ok22 > > 1 returns 11 , ok11 > > 1 returns 5 , and not 5.5 , why ? 255 > > 1 returns 127127 > > 1 returns 63 and not 63.5 , why ? | Why arithmetic shift halfs a number only in SOME incidents ? |
C# | I have a .NET Core worker project and want to add a library providing several HTTP endpoints . I have to stay with the worker project , I ca n't change it to a Web API project . What I have done so far : I created a worker projectI created a library projectI added a reference to the library in the worker projectIn the ... | public static class IApplicationBuilderExtensions { public static IApplicationBuilder AddLibrary ( this IApplicationBuilder applicationBuilder ) { applicationBuilder.UseRouting ( ) ; applicationBuilder.UseEndpoints ( endpoints = > { endpoints.MapControllers ( ) ; } ) ; return applicationBuilder ; } } public static clas... | register Web API controller from class library |
C# | I am trying to convert the ffg : ,This Worksinto this , which does not work , It gives me an error that it can not find `` COLUMNS '' .While debugging , it seems that rs is picking up all the return methods and private variables in the SELECT class it just is not picking up the method like COLUMNS in the SELECT class a... | IResultSEt rs = db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) .FROM ( data.ToString ( ) ) .Execute ( ) ; dynamic rs = db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) ; rs = rs.FROM ( data.ToString ( ) ) ; rs = rs.Execute ( ) ; public class Database { private Dictionary < stri... | Dynamic object not showing its methods |
C# | I work in C # , so I 've posted this under C # although this may be a question that can be answered in any programming language.Sometimes I will create a method that will do something such as log a user into a website . Often times I return a boolean from the method , but this often causes problems because a boolean re... | public bool LoginToTwitter ( String username , String password ) { // Some code to log the user in } if ( http.LoginToTwitter ( username , password ) ) { // Logged in } else { // Not Logged in } | Methods that return meaningful return values |
C# | Consider the following code : I 'm trying to keep an instance of a generic class in a property for later usage , but as you know : Properties , events , constructors etc ca n't be generic - only methods and types can be generic . Most of the time that 's not a problem , but I agree that sometimes it 's a pain ( Jon Ske... | public dynamic DataGrid { get ; private set ; } public DataGridForm < TData , TGrid > GridConfig < TData , TGrid > ( ) where TData : class { return DataGrid = new DataGridForm < TData , TGrid > ( ) ; } | Using dynamic type instead of none-possible generic properties |
C# | How does the compiler handle interpolated strings without an expressions ? Will it still try to format the string ? How does the compiled code differ from that of one with an expression ? | string output = $ '' Hello World '' ; | How does C # string interpolation without an expression compile ? |
C# | Anyone have any ideas why this does n't work ( C # or VB.NET or other .NET language does n't matter ) . This is a very simplified example of my problem ( sorry for VB.NET ) : If you do : You will be surprised at the result . It will print `` Nothing '' . Anyone have any idea why it does n't print `` Something '' Here '... | Private itsCustomTextFormatter As String Public Property CustomTextFormatter As String Get If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not ' Return itsCustomTextFormatter End Get Set ( ByVal value As String ) If value Is Nothing Th... | Interesting Property Behavior |
C# | Say I have a rather expensive assertion : If I test this assertion with : Will IsCompatible be executed in release builds ? My understanding is that Debug.Assert being marked as [ Conditional ( `` DEBUG '' ) ] , calls to it will only be emitted in debug builds . I 'm thinking that this wo n't prevent the expression fro... | bool IsCompatible ( Object x , Object y ) { // do expensive stuff here } Debug.Assert ( IsCompatible ( x , y ) ) ; # if DEBUGDebug.Assert ( IsCompatible ( x , y ) ) ; # endif | Will the expression provided to Debug.Assert be evaluated in a release build ? |
C# | This code fails only in Release mode at Assert.Fail ( ) line despite the fact relay variable is still in scope and thus we still have strong reference to the instance , so WeakReference must not be dead yet.UPD : To clarify a bit : I realize that it can be 'optimized away ' . But depending on this optimization indicato... | [ TestFixture ] public class Tests { private class Relay { public Action Do { get ; set ; } } [ Test ] public void OptimizerStrangeness ( ) { var relay = new Relay ( ) ; var indicator = 0 ; relay.Do = ( ) = > indicator++ ; var weak = new WeakReference ( relay ) ; GC.Collect ( ) ; var relayNew = weak.Target as Relay ; i... | Is it really a bug in JIT optimization or am I missing something ? |
C# | There are multiple questions ( 1,2,3,4 etc . etc . ) called `` Why is n't this exception caught '' . Sadly , none of these solutions work for me ... So I am stuck with a truly uncatchable exception.I have a piece of code ( .NET 4.0 ) that checks a large textfile for digits and numbers . Whilst testing I got a runtime e... | //Code called from the UISystem.Threading.Tasks.Task.Factory.StartNew ( ( ) = > { //Create a new task and use this task to catch any exceptions System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew ( MethodWithException ) ; try { task.Wait ( ) ; } catch ( Exception ) { MessageBox.Show ( `` Cau... | Moby Dick of exceptions |
C# | I 'm new to C # and working on a snake project . I 'm trying to make it rainbow coloured , is there a better way to switch between six colours and then repeat ? Any suggestions ? | public Brush Colour ( int i ) { Brush snakeColour ; switch ( i ) { case 0 : case 6 : case 12 : case 18 : case 24 : snakeColour = Brushes.HotPink ; break ; case 1 : case 7 : case 13 : case 19 : case 25 : snakeColour = Brushes.Orange ; break ; case 2 : case 8 : case 14 : case 20 : case 26 : snakeColour = Brushes.PeachPuf... | Better way to switch Brush colours ? |
C# | When using extremely short-lived objects that I only need to call one method on , I 'm inclined to chain the method call directly to new . A very common example of this is something like the following : The point here is that I have no need for the Regex object after I 've done the one replacement , and I like to be ab... | string noNewlines = new Regex ( `` \\n+ '' ) .Replace ( `` `` , oldString ) ; | Any reason not to use ` new object ( ) .foo ( ) ` ? |
C# | Compiler warning CS4014 ( calling async method without awaiting result ) is not emitted as a warning during build when the called method is in a referenced assembly.When the called method is in the same assembly the warning is correctly emitted.The compiler warning is signaled in Visual Studio when both projects are co... | public class Class1 { public static async Task < string > DoSomething ( ) { return await Task.FromResult ( `` test '' ) ; } } public class Class2 { public void CallingDoSomething ( ) { Class1.DoSomething ( ) ; } } | Compiler warning CS4014 not emitted during build |
C# | Most of the Q & A I found on StackOverflow is how Binding work but x : Bind does n't which usually solved by Bindings.Update ( ) . However , my issue is , inside a GridView , ItemSource= '' { x : Bind _myList } '' works but ItemSource= '' { Binding _myList } '' does n't . Why ? And how do I make Binding work ? ( instea... | public class MyClass { public string prop1 { get ; set ; } public string prop2 { get ; set ; } } public class MyList : List < MyClass > { public void Populate ( ) // Add items } public MyList _myList = new MyList ( ) ; _myList.Populate ( ) ; DataContext = this ; Bindings.Update ( ) ; < GridView ItemSource= '' { Binding... | x : Bind works but Binding does n't ( opposite to most Q & A found ) |
C# | If you compile the following code : And then decompile it ( I used dotPeek ) and examine the all-important MoveNext method , you will see a bool variable declared near the beginning ; dotPeek chose `` flag '' for me.In this case , you will see one subsequent consumer of that variable , in the default case statement aft... | private async Task < int > M ( ) { return await Task.FromResult ( 0 ) ; } bool flag = true ; if ( ! awaiter.IsCompleted ) { this.\u003C\u003E1__state = 0 ; this.\u003C\u003Eu__\u0024awaiter11 = awaiter ; this.\u003C\u003Et__builder.AwaitUnsafeOnCompleted < TaskAwaiter < int > , Program.\u003CP\u003Ed__10 > ( ref awaite... | Why does a bool `` flag '' get generated for the async/await state machine ? |
C# | First , I apologize if this is not an appropriate venue to ask this question , but I was n't really sure where else to get input from.I have created an early version of a .NET object persistence library . Its features are : A very simple interface for persistence of POCOs.The main thing : support for just about every c... | var to1 = new TestObject { id = `` fignewton '' , number = 100 , FruitType = FruitType.Apple } ; ObjectStore db = new SQLiteObjectStore ( `` d : /objstore.sqlite '' ) ; db.Write ( to1 ) ; var readback = db.Read < TestObject > ( `` fignewton '' ) ; var readmultiple = db.ReadObjects < TestObject > ( collectionOfKeys ) ; ... | Is my idea for an object persistence library useful ? |
C# | I am trying to write a code generator using a c # console application . Now when I type this , I receive an error : It says `` input in wrong format '' I have checked that all the variables were strings , and they are . When I tried It worked perfectly fine . Is there a way to fix this ? | Console.WriteLine ( `` sphere { { 0 } { 1 } { 2 } texture { Gold_Metal } } '' , pre , i.ToString ( ) , sprad.ToString ( ) ) ; Console.WriteLine ( `` sphere { 0 } { 1 } { 2 } textureGold_Metal '' , pre , i.ToString ( ) , sprad.ToString ( ) ) ; | Writing scope ( { ) into string in console app |
C# | Today , I was doing some tests in .NET Core , and I have come across some interesting thing.Before ( ~ .NET Framework 4 ) , Random used Environment.TickCount , but now I believe this has changed.Consider the following code : In older .NET Framework versions , the new Random ( ) empty constructor would use Environment.T... | while ( true ) { Random random = new Random ( ) ; Console.WriteLine ( random.Next ( 0 , 10000 ) ) ; } 542421152445244524495019501 5332220392852429732840496556676576434317030467044 | Did Microsoft change Random default seed ? |
C# | I was playing around with the C # compiler on TryRoslyn recently , and I came across a strange problem where an inequality check was getting converted into a greater-than one . Here is the repro code : and here is the code that gets generated by the decompiler : Here 's the link to the repro . Why does Roslyn do this ;... | using System ; public class C { public void M ( ) { if ( Foo ( ) ! = 0 || Foo ( ) ! = 0 ) { Console.WriteLine ( `` Hi ! `` ) ; } } private int Foo ( ) = > 0 ; } using System ; using System.Diagnostics ; using System.Reflection ; using System.Runtime.CompilerServices ; using System.Security ; using System.Security.Permi... | Why is Roslyn generating a > comparison instead of a ! = one here ? |
C# | I just wrote an if statement in the lines ofand it annoys me that I always have to repeat the 'value == ' part . In my opinion this is serving no purpose other than making it difficult to read.I wrote the following ExtensionMethod that should make above scenario more readable : Now I can simply writeIs this a good usag... | if ( value == value1 || value == value2 || value == value3 || value == value4 ) //do something public static bool IsEqualToAny < T > ( this T value , params T [ ] objects ) { return objects.Contains ( value ) ; } if ( value.IsEqualToAny ( value1 , value2 , value3 , value4 ) ) //do something | Is this a good use of an ExtensionMethod ? |
C# | Let 's assume that I have a controller 's action which does the following : checks if there is a calendar slot at a particular timechecks if there are no appointments already booked that overlap with that slotif both conditions are satisfied it creates a new appointment at the given timeThe trivial implementation prese... | public class AController { // ... public async Task Fn ( ... , CancellationToken cancellationToken ) { var calendarSlotExists = dbContext.Slots.Where ( ... ) .AnyAsync ( cancellationToken ) ; var appointmentsAreOverlapping = dbContext.Appointments.Where ( ... ) .AnyAsync ( cancellationToken ) ; if ( calendarSlotExists ... | Enforcing business rules in entity framework core |
C# | I 've got some inheritance going , requiring a custom JsonConverter for deserialization . I 'm using a very straightforward approach for now where I determine the type based on the existence of certain properties.Important note : in my actual code I can not touch the DeserializeObject calls , i.e . I can not add custom... | abstract class Mammal { } class Cat : Mammal { public int Lives { get ; set ; } } class Dog : Mammal { public bool Drools { get ; set ; } } class Person { [ JsonConverter ( typeof ( PetConverter ) ) ] public Mammal FavoritePet { get ; set ; } [ JsonConverter ( typeof ( PetConverter ) ) ] public List < Mammal > OtherPet... | How to deserialize a list of abstract items without passing converters to DeserializeObject ? |
C# | I have a list of ranges . Each range has a from and to value , meaning the value can be between that range . For eample if range is ( 1,4 ) . , the values can be 1,2,3 and 4 . Now , I need to find the distinct values in a given list of range . Below is the sample code.I can loop through every range and find the distinc... | class Program { static void Main ( string [ ] args ) { List < Range > values = new List < Range > ( ) ; values.Add ( new Range ( 1 , 2 ) ) ; values.Add ( new Range ( 1 , 3 ) ) ; values.Add ( new Range ( 1 , 4 ) ) ; values.Add ( new Range ( 3 , 5 ) ) ; values.Add ( new Range ( 7 , 10 ) ) ; values.Add ( new Range ( 7 , 8... | Efficient Logic to get distinct values from a range of values in c # 2.0 |
C# | I 'd like to reinterpret a string in a array of int where every int take charge of 4 or 8 chars based on processor architecture.Is there a way to achieve this in a relatively inexpensive way ? I tried out this but does n't seem to reinterpret 4 chars in one intSOLUTION : ( change Int64 or Int32 based on your needs ) | string text = `` abcdabcdefghefgh '' ; unsafe { fixed ( char* charPointer = text ) { Int32* intPointer = ( Int32* ) charPointer ; for ( int index = 0 ; index < text.Length / 4 ; index++ ) { Console.WriteLine ( intPointer [ index ] ) ; } } } string text = `` abcdabcdefghefgh '' ; unsafe { fixed ( char* charPointer = tex... | reinterpret cast an array from string to int |
C# | I 'm trying to detect when mouse enters VS 2017 title bar , but I 've noticed that MouseEnter and MouseLeave events do n't work correctly . Event fires only when mouse enters child controls outlined by green rectangle on the screenshot below.The title bar is a DockPanel with some elements in it . I 've set its backgrou... | using Microsoft.VisualStudio.PlatformUI.Shell.Controls ; using Microsoft.VisualStudio.Shell ; using System ; using System.Windows ; using System.Windows.Automation.Peers ; using System.Windows.Controls ; using System.Windows.Input ; using System.Windows.Interop ; using System.Windows.Media ; namespace Microsoft.VisualS... | IsMouseOver returns false over some elements in a DockPanel |
C# | I have read that a 'BackgroundWorker ' is designed to be replaced by Ansyc/Await . Because I like the condensed look of Async/Await , I am starting to convert some of my BackgroundWorkers into Async/Await calls.This is an example of the code I have ( called from the UI ) : When I call RunFromTheUI it will return almost... | public async void RunFromTheUI ( ) { await OtherAction ( ) ; } public async void OtherAction ( ) { var results = await services.SomeRemoteAction ( ) ; foreach ( var result in results ) { result.SemiIntenseCalculation ( ) ; Several ( ) ; Other ( ) ; NonAsync ( ) ; Calls ( ) ; } SomeFileIO ( ) ; } | Does an await make the rest of the method asynchronous ? |
C# | I am trying to define code contracts for an interface using ContractClass and ContractClassFor . It works fine when everything is in the same assembly , but if I put the interface definition and its respective contract class in a different assembly then the concrete class implementation , it does n't work anymore.For e... | namespace DummyProject { [ ContractClass ( typeof ( AccountContracts ) ) ] public interface IAccount { void Deposit ( double amount ) ; } [ ContractClassFor ( typeof ( IAccount ) ) ] internal abstract class AccountContracts : IAccount { void IAccount.Deposit ( double amount ) { Contract.Requires ( amount > = 0 ) ; } } ... | Code Contracts for C # does not work when ContractFor is on a different assembly |
C# | IntroductionAs a developer , I 'm involved in writing a lot of mathematical code everyday and I 'd like to add very few syntactic sugar to the C # language to ease code writing and reviewing.I 've already read about this thread and this other one for possible solutions and would simply like to know which best direction... | [ double x , int i ] = foo ( z ) ; double x ; int i ; foo ( out x , out i , z ) ; namespace Foo { using binary operator `` \ '' as `` MyMath.LeftDivide '' ; using unary operator `` ' '' as `` MyMath.ConjugateTranspose '' ; public class Test { public void Example ( ) { var y = x ' ; var z = x \ y ; } } } namespace Foo {... | Extending C # language , how much effort/gain ? |
C# | As in : And how do I search for it in the documentation ? | public string [ , ] GetHelp ( ) { return new string [ , ] { ... things ... } } | What does [ , ] mean in c # ? |
C# | I 'm working on my solution to the Cult of the Bound Variable problem.Part of the problem has you implement an interpreter for the `` ancient '' Universal Machine . I 've implemented an intepreter for the machine they describe and now I 'm running a benchmark program that the university provided to test it.My C # imple... | # 12 . Load Program . The array identified by the B register is duplicated and the duplicate shall replace the ' 0 ' array , regardless of size . The execution finger is placed to indicate the platter of this array that is described by the offset given in C , where the value 0 denotes the first platter , 1 the second ,... | How can I speed up array cloning in C # ? |
C# | I 'm using Visual Studio 2015 on Windows 10 , I 'm still a new coder , I 've just started to learn C # , and while I was in the process , I discovered the Math class and was just having fun with it , till the console outputted : `` ∞ `` It 's a Console ApplicationHere 's the code : Why is this happening ? using normal ... | var k = Math.Sqrt ( ( Math.Pow ( Math.Exp ( 5 ) , Math.E ) ) ) ; var l = Math.Sqrt ( ( Math.Pow ( Math.PI , Math.E ) ) ) ; Console.WriteLine ( `` number 1 : `` + k ) ; Console.WriteLine ( `` number 2 : `` + l ) ; Console.ReadKey ( ) ; var subject = Math.Pow ( Math.Sqrt ( ( Math.Pow ( Math.PI , Math.E ) ) ) , Math.Sqrt ... | C # : The console is outputting infinite ( ∞ ) |
C# | I bet that 's an easy question for you , but searching SO or Google with { or } in the search string does n't work very well.So , let 's say i wan na output { Hello World } , how do i do this using string.format ( ... ) ? Edit : looks like this : would do the job , but that does n't look very elegant to me . Is there a... | string hello = `` Hello World '' ; string.format ( `` { 0 } '' , ' { ' + hello + ' } ' ) ; | Output ' { ' or ' } ' with string.format ( ... ) |
C# | I have an ID with me and I have name with me . So in essence , my method just has these parameters : and I have this piece of logic inside method : That 's it . Nothing fancy . I get this error : `` An object with the same key already exists in the ObjectStateManager . The ObjectStateManager can not track multiple obje... | public void Foo ( int id , string name ) { } User user = new User ( ) { Id = id , Name = name } ; Db.Entry ( user ) .State = System.Data.EntityState.Modified ; Db.SaveChanges ( ) ; | Why I do I fall into all of the hurdles for a simple update in EF ? |
C# | When we have two structs , and one is implicitly convertible to the other , then it seems like the System.Nullable < > versions of the two are also implicitly convertible . Like , if struct A has an implicit conversion to struct B , then A ? converts to B ? as well.Here is an example : Inside some method : In the C # L... | struct MyNumber { public readonly int Inner ; public MyNumber ( int i ) { Inner = i ; } public static implicit operator int ( MyNumber n ) { return n.Inner ; } } MyNumber ? nmn = new MyNumber ( 42 ) ; int ? covariantMagic = nmn ; // works ! | `` Covariance '' of the System.Nullable < > struct |
C# | I 'm trying to match strings that look like this : But not if it occurs in larger context like this : The regex I 've got that does the job in a couple different RegEx engines I 've tested ( PHP , ActionScript ) looks like this : You can see it working here : http : //regexr.com ? 36g0eThe problem is that that particul... | http : //www.google.com < a href= '' http : //www.google.com '' > http : //www.google.com < /a > ( ? < ! [ `` ' > ] \b* ) ( ( https ? : // ) ( [ A-Za-z0-9_= % & @ ? ./- ] + ) ) \b private static readonly Regex fixHttp = new Regex ( @ '' ( ? < ! [ `` '' ' > ] \b* ) ( ( https ? : // ) ( [ A-Za-z0-9_= % & @ ? ./- ] + ) ) ... | RegEx does n't work with .NET , but does with other RegEx implementations |
C# | As you can see in the following image , I have a model with a base class `` Person '' and both entities `` Kunde '' and `` Techniker '' inherit the base class.Now I 've got following problem . When I try to use the method Find to get an object of the derived class Kunde with given ID , it tells me that OfType < TResult... | public Kunde GetById ( int id ) { return dbModel.PersonMenge.OfType < Kunde > .Find ( id ) ; } | Finding inherited object by ID - Entity Framework |
C# | I 'm trying to learn how to use WPF binding and the MVVM architecture . I 'm running into some trouble with Dependency Properties . I 've tried to control the visibility of an item on the view by binding it to a DependencyProperty in the DataContext , but it does n't work . No matter what I set the GridVisible value to... | public class MyViewModel : DependencyObject { public MyViewModel ( ) { GridVisible = false ; } public static readonly DependencyProperty GridVisibleProperty = DependencyProperty.Register ( `` GridVisible '' , typeof ( bool ) , typeof ( MyViewModel ) , new PropertyMetadata ( false , new PropertyChangedCallback ( GridVis... | WPF Data Binding Architecture Question |
C# | I 'm trying to create an instance of a generic class , without knowing what type to cast it to it until runtime . I 've written the following codeHopefully that gives you an idea what I 'm trying to do , however it wont compile it just says `` the type or namespace pType could not be found '' . Is there any easy way of... | Type pType = propertyInfo.GetType ( ) ; ObjectComparer < pType > oc = new ObjectComparer < pType > ( ) ; | C # Generics |
C# | I have a very basic video recording project that was working perfectly in Swift , but the same code ported into a blank project in Xamarin is producing a video that is constantly skipping frames every few seconds . The code starts in ViewDidLoad and is stopped via a UIButton Here is the recording code below : And here ... | RPScreenRecorder rp = RPScreenRecorder.SharedRecorder ; AVAssetWriter assetWriter ; AVAssetWriterInput videoInput ; public override void ViewDidLoad ( ) { base.ViewDidLoad ( ) ; StartScreenRecording ( ) ; } public void StartScreenRecording ( ) { VideoSettings videoSettings = new VideoSettings ( ) ; NSError wError ; ass... | Video produced by ReplayKit is constantly skipping frames in Xamarin |
C# | I 'm trying to use reflection to retrieve a list of all methods of an interface + its base interfaces.So far I have this : I 'd like to be able to filter out methods that shadow methods declared in base interfaces , i.e. , `` new '' methods : With my current code , the result includes both methods - I 'd like to retrie... | var methods = type.GetMethods ( ) .Concat ( type.GetInterfaces ( ) .SelectMany ( @ interface = > @ interface.GetMethods ( ) ) ) ; public interface IBaseInterface { string Method ( ) ; } public interface IInterfaceWithNewMethod : IBaseInterface { new string Method ( ) ; } | How to check whether an interface 's MethodInfo is a `` new '' method |
C# | I have this BdlTabItem which receives a parameter of type DockableUserControl and would like to know if is it a bad practice to create a circular reference between the two by using uc.TabItem = this and new BdlDockableWindow ( this ) before the constructor finishes.I know this behavior can be considered really bad with... | public BdlTabItem ( BdlTabControl parent , DockableUserControl uc , string title ) { TabControlParent = parent ; UserControl = uc ; WindowParent = new BdlDockableWindow ( this ) ; this.Content = UserControl ; UserControl.TabItem = this ; } | Is it a bad practice to pass `` this '' as parameter inside its own constructor ? |
C# | I have some objects that read a file , save the data in arrays and make some operations . The sequence is Create object A , operate with object A . Create object B , operate with object B ... The data read by each object may be around 10 MB . So the best option would be to delete each object after operate with each one... | class MyClass { List < string [ ] > data ; public MyClass ( string datafile ) { using ( CsvReader csv = new CsvReader ( new StreamReader ( datafile ) , true ) ) { data = csv.ToList < string [ ] > ( ) ; } } public List < string > Operate ( ) { ... } } List < string > results = new List < results > ( ) ; using ( MyClass ... | Need to delete objects : implement Dispose or create objects in a function ? |
C# | I have the following block of linq queries to calculate some values for a report.I 've stepped through the code in a debugger and I 've noticed some oddities . After assigning into test its value is 0 . After assigning into test2 test2 == 0 and test == 11.31 after assigning into test3 test == 11.31 test2 == 11.28 and t... | var items = ( from trans in calclabordb.Sales_Transactions select trans ) .SelectMany ( st = > st.Sales_TransactionLineItems ) .Where ( stli = > stli.TypeID == typeID ) ; decimal test = items.Where ( stli = > stli.Inventory_Item is Base ) .Sum ( stli = > ( decimal ? ) stli.Inventory_Item.IntExtraServiceAmount ) ? ? 0 ;... | Why do n't the values from my linq queries appear immediately ? |
C# | EDITIf I use Stopwatch correctly and up the number of iterations by two orders of magnitude I getTernary took 22404msNormal took 21403msThese results are closer to what I was expecting and make me feel all is right with the world ( if not with my code . ) The Ternary/Conditional operator is in fact marginally slower.Fo... | using System ; using System.Diagnostics ; class Program { static void Main ( ) { var stopwatch = new Stopwatch ( ) ; var ternary = Looper ( 10 , Ternary ) ; var normal = Looper ( 10 , Normal ) ; if ( ternary ! = normal ) { throw new Exception ( ) ; } stopwatch.Start ( ) ; ternary = Looper ( 10000000 , Ternary ) ; stopW... | Why does the conditional ( ternary ) operator seem significantly faster ? |
C# | I have ICollectionView looks like I want to use drag & drop to change the item Series Name , and location on the list view any idea how to do that for example if Idraged and droped book3 in ScienceFiction the output should be I use xaml code like this : | public ICollectionView UsersCollectionView { get { var view = CollectionViewSource.GetDefaultView ( this ) ; view.GroupDescriptions.Add ( new PropertyGroupDescription ( `` SeriesName '' ) ) ; view.SortDescriptions.Add ( new SortDescription ( `` CreationDate '' , ListSortDirection.Ascending ) ) ; view.SortDescriptions.A... | change the group of item in ICollectionView |
C# | Is there a performance difference between the following two pieces of code ? andMy gut feeling is that the compiler should optimize for this and there should n't be a difference , but I frequently see it done both ways throughout our code . I 'd like to know if it comes down to a matter of preference and readability . | if ( myCondition ) { return `` returnVal1 '' ; } return `` returnVal2 '' if ( myCondition ) { return `` returnVal1 '' ; } else { return `` returnVal2 '' ; } | Is there a performance difference by excluding an 'Else ' clause ? |
C# | Situation : Assembly 1 is a application that other developers can use.We will give them only the .dll so we can publish updates from the application if we do n't change the api . The developers ca n't change the framework in assembly 1Methods are virtual so developers can override methods to implement there own logic i... | Assembly 1________________________ ________________________| Class A | | Class B || -- -- -- -- -- -- -- -- -- -- -- -| | -- -- -- -- -- -- -- -- -- -- -- -|| Method someMethod | -- -- -- -- -- > | Method otherMethod || | | ||_______________________| |_______________________| Assembly 1________________________ ________... | C # OO design problem with override from methods |
C# | I 'm trying to write a complement function , such that when provided with a function f , it returns a function which , when provided with the same input as f , returns it 's logical opposite.Having put similar code into VS2017 , I get no errors , however I 'm not yet able to run the code to see if it 'll work as expect... | public static Func < T , bool > Complement < T > ( Func < T , bool > f ) { return ( T x ) = > ! f ( x ) ; } public static bool GreaterThanTwo ( int x ) { return x > 2 ; } static public void Main ( string [ ] args ) { Func < int , bool > NotGreaterThanTwo = Complement ( GreaterThanTwo ) ; Console.WriteLine ( NotGreaterT... | Complement higher order function |
C# | I would like to write a method that gives me the 3 letters - representing the day , month , year - from a datetimeformat.So in en-US culture my desired return values would be ( plus the separator ) dMy/in de-DE the same method should returnT ( Tag = day ) M ( Monat = month ) J ( Jahr = year ) . ( Separator ) I had a lo... | var culture = Thread.CurrentThread.CurrentCulture ; Console.WriteLine ( culture.DateTimeFormat.DateSeparator ) ; =TEXT ( NOW ( ) ; '' dd.MM.yyyy '' ) =TEXT ( NOW ( ) ; '' TT.MM.JJJJ '' ) | DateTime get the letters representing day , month , year from the currentculture |
C# | I found interesting behavior of LinkedList < T > . I ca n't call Add method for an instance of LinkedList < > . However LinkedList < T > implements ICollection < T > ( link ) which actually has the Add method . Here are examples . When I do like this , it works perfect : But this code even will not compile : Compiler s... | ICollection < string > collection = new LinkedList < string > ( ) ; collection.Add ( `` yet another string '' ) ; LinkedList < string > linkedList = new LinkedList < string > ( ) ; linkedList.Add ( `` yet another string '' ) ; | LinkedList does not contain explicit Add method |
C# | I know I can create expression trees using : Factory methods.Compiler conversion of a lambda expression to an Expression.For complicated expression trees I would prefer 2 because it is more concise.Is it possible to refer to already constructed Expressions using this way ? | using System ; using System.Linq.Expressions ; public class Test { public static Expression < Func < int , int > > Add ( Expression expr ) { # if false // works ParameterExpression i = Expression.Parameter ( typeof ( int ) ) ; return Expression.Lambda < Func < int , int > > ( Expression.Add ( i , expr ) , i ) ; # else ... | Using an Expression in a compiler-generated expression tree |
C# | In one class , ClassA , I have a timer object . In this class I register the event handlers for the timer elapsed event . In another class , ClassB , I have a public event-handler for the timer elapsed event . So I register the event-handler from ClassB in ClassA as follows : What happens if I were to create a new inst... | myTimer.Elapsed += ClassBInstance.TimerElapsed ClassB classBInstance = new ClassB ( ) ; myTimer.Elapsed += classBInstance.TimerElapsedclassBInstance = new ClassB ( ) ; myTimer.Elapsed += classBInstance.TimerElapsed | What happens when an event fires and tries to execute an event-handler in an object that no longer exists ? |
C# | Sorry about the vocabulary question but I ca n't find this anywhere : how do you call this below ? Is it a statement , a directive , ... ? I want to indicate that you have to insert that line in order to give MyAssembly access to your assembly 's internal members , but I 'd like to use a more specific term than `` line... | [ assembly : System.Runtime.CompilerServices.InternalsVisibleTo ( `` MyAssembly '' ) ] | What is [ assembly : InternalsVisibleTo ( `` MyAssembly '' ) ] ? A statement , directive , ... ? |
C# | I wonder what the difference is between the following methods with regards to how the object parameter is referenced : andShould I use ref object parameter in cases where I want to change the reference to the object not override the object in the same reference ? | public void DoSomething ( object parameter ) { } public void DoSomething ( ref object parameter ) { } | What is the difference between 2 methods with ref object par and without ? |
C# | While analyzing the .NET memory allocation of my code with the Visual Studio 2013 performance wizard I noticed a certain function allocating a lot of bytes ( since it is called in a large loop ) . But looking at the function highlighted in the profiling report I did n't understand why it was allocating any memory at al... | Function Name | Inclusive | Exclusive | Inclusive | Exclusive | Allocations | Allocations | Bytes | Bytes -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -LinqAllocationTester.Test ( int32 ) | 100.000 | 100.000 | 1.200.000 | 1.200.000Program.... | non executing linq causing memory allocation C # |
C# | I 'm trying to refactor some code to use .NET Core dependency injection via mapping services in startup.cs . I would like to inject an IRequestDatabaseLogger here instead of newing it up . However it requires the context in the constructor . How can I achieve this ? Is it even possible without an DI framework or even t... | public class ActionFilter : ActionFilterAttribute { public override void OnActionExecuting ( ActionExecutingContext context ) { var requestDatabaseLogger = new RequestDatabaseLogger ( context ) ; long logId = requestDatabaseLogger.Log ( ) ; context.HttpContext.AddCurrentLogId ( logId ) ; base.OnActionExecuting ( contex... | Injecting a logger with constructor dependencies |
C# | I 'm trying to create a generic method that will return a predicate to find elements in an XML document . Basically something like this : Only thing is that this does n't compile . The problem is on the ( T ) x.Attribute ( criterion.PropertyName ) part where the compiler indicates : Can not cast expression of type 'Sys... | private static Func < XElement , bool > GetPredicate < T > ( Criterion criterion ) { switch ( criterion.CriteriaOperator ) { case CriteriaOperator.Equal : return x = > ( T ) x.Attribute ( criterion.PropertyName ) == ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.GreaterThan : return x = > ( T ) x.Attribute (... | Is there a way to do this kind of casting in a c # predicate |
C# | I 've been working , giving up and then reworking on this problem for a couple days . I 've looked at a lot of different ways to go about however I either ca n't implement it correctly or it does n't suit what I need it to do.Basically : I have two arrays , prefix and suffix I need to : Have a minimum of 3 used combine... | prefix = { 0 , 0 , 3 , 8 , 8 , 15 } suffix = { 0 , 3 , 2 , 7 , 7 , 9 , 12 , 15 } X = 423 + 8 + 8 + 2 + 9 + 12 = 420 + 8 + 8 + 7 + 7 + 12 = 42| Prefix | | Suffix |15 + 12 + 15 = 420 + 15 + 0 + 12 + 15 = 42 public int [ ] Prefix = { 0 , 6 , 6 , 8 , 8 , 8 , 8 , 8 , 8 , 11 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 16 ... | C # OR Javascript Permutations of two arrays multiple times |
C# | I have been struggling with these elements for about 2 months . The first problem arise when my MVC4 application was recycled . The current logged-in user suddenly can not access any controller actions which are marked [ Authorize ] . Also , any successful access to the controller action which requires database connect... | WebSecurity.Login ( userName , model.Password , persistCookie : true ) < machineKey validationKey= '' 685DD0E54A38F97FACF4CA27F54D3DA491AB40FE6941110A5A2BA2BC7DDE7411965D45A1E571B7B9283A0D0B382D35A0840B46EDBCE8E05DCE74DE5A37D7A5B3 '' decryptionKey= '' 15653D093ED55032EA6EDDBFD63E4AAA479E79038C0F800561DD2CC4597FBC9E '' ... | ASP.NET MVC : How do SimpleMembership , SQLSession store , Authentication , and Authorization work ? |
C# | I 'd like to arrange some TextBlocks horizontally without any margins . I can see that my TextBlock is as small as it should be , but for some reason a lot of space is added around it . I think it has something to do with the ListView or its styling , but I do n't know what.I have a following layout : | < ListView Width= '' Auto '' SelectionMode= '' None '' Background= '' # 654321 '' ItemsSource= '' { Binding } '' > < ListView.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' / > < /ItemsPanelTemplate > < /ListView.ItemsPanel > < ListView.ItemTemplate > < DataTemplate > < Border Background... | Too much spacing between StackPanel items in Windows Store app |
C# | it 's possible write something like : C # there a equivalent to .apply of javascript ? | function foo ( a , b , c ) { return a + b + c ; } var args = [ 2,4,6 ] ; var output = foo.apply ( this , args ) ; // 12 | dynamic arguments definition in C # |
C# | I 've been reading Jon Skeet 's C # In Depth : Second Edition and I noticed something slightly different in one of his examples from something I do myself.He has something similar to the following : Whereas I 've been doing the following : Is there any real difference between the two ? I know Jon Skeet is pretty much t... | var item = someObject.Where ( user = > user.Id == Id ) .Single ( ) ; var item = someObject.Single ( user = > user.Id == Id ) ; | Linq with dot notation - which is better form or what 's the difference between these two ? |
C# | I need a data structure with both named column and row . For example : I need to be able to access elements like magic_data_table [ `` row_foo '' , `` col_bar '' ] ( which will give me 3 ) I also need to be able to add new columns like : AFAIK , DataTable only has named column ... EDIT : I do n't need to change the nam... | magic_data_table : col_foo col_barrow_foo 1 3 row_bar 2 4 magic_data_table.Columns.Add ( `` col_new '' ) ; magic_data_table [ `` row_foo '' , `` col_new '' ] = 5 ; | Is there a `` DataTable '' with `` named row '' in C # ? |
C# | Robert C. Martin in one of his talks about clean architecture openly criticizes fairly standard way of doing things nowadays.Robert C. Martin - Clean Architecture and DesignWhat I understand as standard way is something like this : Martin here says , that the application should reveal its purpose immediately when you l... | solution - UI project - Models - Views - Controllers - Assets - Logic project - Data project | How can a top level directory structure reveal the purpose of the application ? |
C# | I 'm trying to replace CompilationUnitSyntax of a class using Roslyn.However , ReplaceNode that I 'm using has a different signature than ReplaceNode in Roslyn FAQ and any StackOverflow question that I 've looked at . Can anyone point out why is that , and how can I use ReplaceNode that takes old ClassDeclarationSyntax... | [ FAQ ( 26 ) ] public void AddMethodToClass ( ) CompilationUnitSyntax newCompilationUnit = compilationUnit.ReplaceNode ( classDeclaration , newClassDeclaration ) ; 'Roslyn.Compilers.CSharp.CompilationUnitSyntax ' does not contain a definition for 'ReplaceNode ' and the best extension method overload 'Roslyn.Compilers.C... | Ambiguity in Roslyn 's CompilationUnitSyntax.ReplaceNode |
C# | I have a list like so : and each element of the string array is another array with 3 elements.So countryList [ 0 ] might contain the array : How can I search countryList for a specific array e.g . how to search countryList for | List < string [ ] > countryList new string [ 3 ] { `` GB '' , `` United Kingdom '' , `` United Kingdom '' } ; new string [ 3 ] { `` GB '' , `` United Kingdom '' , `` United Kingdom '' } ? | How to search a list in C # |
C# | I would like to implement my generic IQueue < T > interface in an efficient way by doing one implementation if T is struct and another if T is a class.The , I 'd like to have a factory method which based on T 's kind returns an instance of one or the other : Of course , the compiler indicates that T should be non-nulla... | interface IQueue < T > { ... } class StructQueue < T > : IQueue < T > where T : struct { ... } class RefQueue < T > : IQueue < T > where T : class { ... } static IQueue < T > CreateQueue < T > ( ) { if ( typeof ( T ) .IsValueType ) { return new StructQueue < T > ( ) ; } return new RefQueue < T > ( ) ; } | Chose generic implementation if the type parameter is struct or class |
C# | I have a form that i dynamicly compiled and i have a style class . When i copy this style class to my form source and compile it all works fine . But how can i use this style class without copy it to my form source . My main program that compile this form has this class , how can i use it ? Maybe i can pass style class... | using System ; using System.CodeDom.Compiler ; using System.Collections.Generic ; using System.IO ; using System.Threading ; using System.Windows.Forms ; using Microsoft.CSharp ; namespace dynamic { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; new Thread ( newForm ) .Start ( ) ; } pu... | How to use custom class with dynamic compilation |
C# | I have a function which among other things does a conversion from Utc to Local and vice-versa.The problem is that when I run it on a PC with Win 7 it works OK , but when I run it on a PC with Vista the conversion goes wrong.ex : My current time zone is +2 UTCMyCurrentTime is set to 27.09.2012 , 19:00 and the DateTimeKi... | DateTime utcTime = DateTime.SpecifyKind ( MyCurrentTime , DateTimeKind.Utc ) ; DateTime localTime = new DateTime ( ) ; localTime = utcTime.Date.ToLocalTime ( ) ; | DateTime conversion from Utc to Local in .NET 4.0 |
C# | I have a vector class with two deconstruction methods as follows : Somewhere else I have : This gives me : How is this ambiguous ? Edit : Calling Deconstruct manually works fine : | public readonly struct Vector2 { public readonly double X , Y ; ... public void Deconstruct ( out double x , out double y ) { x = this.X ; y = this.Y ; } public void Deconstruct ( out Vector2 unitVector , out double length ) { length = this.Length ; unitVector = this / length ; } } Vector2 foo = ... ( Vector2 dir , dou... | Deconstruction is ambiguous |
C# | I have some user admin functionality in a WPF app that I 'm currently writing and would like to make it a bit more intuitive for the end userI 'd like to be able to provide some kind of means of easily editing the list of roles a given user belongs to . At the moment the grid is filled as a result of binding to a List ... | public class ApplicationUser { public Guid ? UserId { get ; set ; } public string GivenName { get ; set ; } public string Surname { get ; set ; } public string EmailAddress { get ; set ; } public string UserPhone { get ; set ; } public string NtLoginName { get ; set ; } public List < Role > ApplicationRoles { get ; set... | Enhancing the display of a particular column in a WPF grid view |
C# | I have two arrays , one with values an one with indicesnow I want a result array from the items selected by the indices of indices arrayQuestion : Is there a more generic approach for this ? | int [ ] items = { 1 , 2 , 3 , 7 , 8 , 9 , 13 , 16 , 19 , 23 , 25 , 26 , 29 , 31 , 35 , 36 , 39 , 45 } ; int [ ] indices = { 1 , 3 , 5 , 6 , 7 , 9 } ; // 2 , 7 , 9 , 13 , 19int [ ] result = new [ ] { items [ 1 ] , items [ 3 ] , items [ 5 ] , items [ 6 ] , items [ 7 ] , items [ 9 ] } ; | Get array items by index |
C# | Let 's say I have a service interface that looks like this : I would like to fulfill some cross-cutting concerns when calling methods on services like these ; for example , I want unified request logging , performance logging , and error handling . My approach is to have a common base `` Repository ' class with an Invo... | public interface IFooService { FooResponse Foo ( FooRequest request ) ; } public class RepositoryBase < TService > { private Func < TService > serviceFactory ; public RepositoryBase ( Func < TService > serviceFactory ) { this.serviceFactory = serviceFactory ; } public TResponse Invoke < TRequest , TResponse > ( Func < ... | Why is n't type inference working in this code ? |
C# | How can we access the complete visual studio solution from code analyzer in Roslyn ? I have been trying semantic analysis without much help.This is what I came up with using intellisense but this always gives a null value . | var sol = ( ( Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions ) context.Options ) .Workspace.CurrentSolution ; | Accessing VS complete solution in roslyn |
C# | I 'm generating a file on the fly on the event of a button . I have to following code : I would like the Save As Dialog to appear after the first flush , because the operation can take a while . How would I go about ? After some playing around I discovered that it will buffer 256 characters ( reproducible by sending ne... | Response.ClearHeaders ( ) ; Response.ClearContent ( ) ; Response.Buffer = false ; Response.ContentType = `` application/octet-stream '' ; Response.AppendHeader ( `` Content-Disposition '' , `` attachment ; filename=Duck.xml '' ) ; Response.Write ( `` First part '' ) ; Response.Flush ( ) ; //simulate long operation Syst... | How to make a save as dialog appear `` early '' ? Or : How to make Flush ( ) behave correctly ? |
C# | I have a checkbox substituting a switch-like control.It works great . The only problem is that this checkbox initial mode can be either true or false . For false - no problem , but if it 's true , then when the view is loaded , you immediately see the animation of the switch moving . I want to prevent that . Is there a... | < CheckBox Style= '' { StaticResource MySwitch } '' IsChecked= '' { Binding ExplicitIncludeMode } '' > < /CheckBox > < Style x : Key= '' MySwitch '' TargetType= '' { x : Type CheckBox } '' > < Setter Property= '' Foreground '' Value= '' { DynamicResource { x : Static SystemColors.WindowTextBrushKey } } '' / > < Setter ... | Pause/prevent animation for a checkbox control |
C# | Consider the following code that I 'm using when displaying a Customer 's mailing address inside a table in a view : I find myself using a fair amount of these ternary conditional statements and I am wondering if there is a way to refer back to the object being evaluated in the condition so that I can use it in the exp... | < % : Customer.MailingAddress == null ? `` '' : Customer.MailingAddress.City % > < % : Customer.MailingAddress == null ? `` '' : { 0 } .City % > | ASP.NET MVC/C # : Can I avoid repeating myself in a one-line C # conditional statement ? |
C# | If I compile the following code snippet with Visual C # 2010 I ALWAYS get false : Does anybody know why ? ? ? | object o = null ; Console.WriteLine ( `` Is null : `` + o == null ) ; // returns false | Testing for null reference always returns false ... even when null |
C# | In ASP.NET Core you can validate all non-GET requests by including this line in Startup.cs ( docs ) : However , if you add the filter by type ( using typeof or the generic Add < T > method ) , the validation does n't seem to work : See https : //github.com/davidgruar/GlobalFilterDemo for a minimal repro.What is going o... | services.AddMvc ( options = > options.Filters.Add ( new AutoValidateAntiforgeryTokenAttribute ( ) ) ) ; // Does n't workservices.AddMvc ( options = > options.Filters.Add ( typeof ( AutoValidateAntiforgeryTokenAttribute ) ) ; // Does n't work eitherservices.AddMvc ( options = > options.Filters.Add < AutoValidateAntiforg... | Why does adding AutoValidateAntiForgeryTokenAttribute by type not work ? |
C# | The following Rx.NET code will use up about 500 MB of memory after about 10 seconds on my machine.If I use the Observable.Generate overload without a Func < int , TimeSpan > parameter my memory usage plateaus at 35 MB.It seems to only be a problem when using SelectMany ( ) or Merge ( ) extension methods . | var stream = Observable.Range ( 0 , 10000 ) .SelectMany ( i = > Observable.Generate ( 0 , j = > true , j = > j + 1 , j = > new { N = j } , j = > TimeSpan.FromMilliseconds ( 1 ) ) ) ; stream.Subscribe ( ) ; var stream = Observable.Range ( 0 , 10000 ) .SelectMany ( i = > Observable.Generate ( 0 , j = > true , j = > j + 1... | Why does this Observable.Generate overload cause a memory leak ? [ Using Timespan < 15ms ] |
C# | I 'm trying to get the positions of controls ( buttons ) but it keeps returning { 0 ; 0 } . I 'm sure there 's an explanation for this , but I ca n't figure out why this happens.I want the position of the control , relative to the window or a certain container . My buttons are arranged in another grid . Taking the marg... | - var point = btnTest.TransformToAncestor ( mainGrid ) .Transform ( new Point ( ) ) ; - UIElement container = VisualTreeHelper.GetParent ( btnTest ) as UIElement ; Point relativeLocation = btnTest.TranslatePoint ( new Point ( 0 , 0 ) , mainGrid ) ; < Grid x : Name= '' mainGrid '' > < Grid Name= '' buttonGrid '' Margin=... | WPF - Getting position of a control keeps returning { 0 ; 0 } |
C# | ReSharper has features that look for inconsistencies in the use of keywords aliasing a type name . For example , it would see these two declarations and urge you to change one to be like the other ( depending on which is set as your preference ) : This is handy , because I always prefer using the keyword alias for the ... | string myString1 = `` String 1 '' ; String myString2 = `` String 2 '' ; string myString1 = `` String 1 '' ; string myString2 = String.Format ( `` { 0 } is String 1 . `` , myString1 ) ; | Can ReSharper use keyword for declarations but type name for member access ? |
C# | I know and I think I understand about the ( co/conta ) variance issue with IEnumerables . However I thought the following code would not be affected by it.This class is to mimic BackgroundWorker 's RunWorkerCompletedEventArgs so I can return errors from my WCF service without faulting the connection.Most of my code is ... | [ DataContract ] public class WcfResult < T > { public WcfResult ( T result ) { Result = result ; } public WcfResult ( Exception error ) { Error = error ; } public static implicit operator WcfResult < T > ( T rhs ) { return new WcfResult < T > ( rhs ) ; } [ DataMember ] public T Result { get ; set ; } [ DataMember ] pu... | Implicit cast fails for myClass < T > when T is IEnumerable < U > |
C# | Is there a way of calling a method/lines of code multiple times not using a for/foreach/while loop ? For example , if I were to use to for loop : The lines of code I 'm calling do n't use ' i ' and in my opinion the whole loop declaration hides what I 'm trying to do . This is the same for a foreach.I was wondering if ... | int numberOfIterations = 6 ; for ( int i = 0 ; i < numberOfIterations ; i++ ) { DoSomething ( ) ; SomeProperty = true ; } do ( 6 ) { DoSomething ( ) ; SomeProperty = true ; } Do.Multiple ( int iterations , Action action ) | Looping through a method without for/foreach/while |
C# | We have a lot of code that passes about “ Ids ” of data rows ; these are mostly ints or guids . I could make this code safer by creating a different struct for the id of each database table . Then the type checker will help to find cases when the wrong ID is passed.E.g the Person table has a column calls PersonId and w... | DeletePerson ( int personId ) DeleteCar ( int carId ) struct PersonId { private int id ; // GetHashCode etc ... . } DeletePerson ( PersionId persionId ) DeleteCar ( CarId carId ) | Is it a good idea to create a custom type for the primary key of each data table ? |
C# | I have a float4x4 struct which simply containts 16 floats : I want to copy an array of these structs into a big array of floats . This is as far as I know a 1:1 copy of a chunk of memoryWhat I do know is rather ugly , and not that fast : If I was using a lower level language , I would simply use memcpy , what can I use... | struct float4x4 { public float M11 ; public float M12 ; public float M13 ; public float M14 ; public float M21 ; public float M22 ; public float M23 ; public float M24 ; public float M31 ; public float M32 ; public float M33 ; public float M34 ; public float M41 ; public float M42 ; public float M43 ; public float M44 ... | Is there a faster/cleaner way to copy structs to an array in C # ? |
C# | Im trying to make a universal parser using generic type parameters , but i ca n't grasp the concept 100 % As you might guess , the code does n't compile , since i ca n't convert int|bool|string to T ( eg . value = valueInt ) . Thankful for feedback , it might not even be possible to way i 'm doing it . Using .NET 3.5 | private bool TryParse < T > ( XElement element , string attributeName , out T value ) where T : struct { if ( element.Attribute ( attributeName ) ! = null & & ! string.IsNullOrEmpty ( element.Attribute ( attributeName ) .Value ) ) { string valueString = element.Attribute ( attributeName ) .Value ; if ( typeof ( T ) == ... | Generic type parameters using out |
C# | I have a ( C # ) function that checks four sets of conditions and returns a bool . If any of them are true , it returns true . I 'm sure I could simplify the logic but I want it to be fairly readable.The CodeMaid extension in Visual Studios and tells me the cylomatic complexity of the function is 12 . I looked it up an... | public bool FitsCheckBoxCriteria ( TaskClass tasks ) { // note : bool == true/false comparisons mean you do n't have to cast 'bool ? ' as bool // if neither checkboxes are checked , show everything bool showEverything = NoShutDownRequiredCheckBox.IsChecked == false & & ActiveRequiredCheckBox.IsChecked == false ; // if ... | Why is the cylcomatic complexity of this function 12 ? |
C# | Why does the following compile ? It sure seems like the compiler has enough info to know that the attempted assignment is invalid , since the return type of the Func < > is not dynamic . | Func < dynamic , int > parseLength = whatever = > whatever.Length ; dynamic dynamicString = `` String with a length '' ; DateTime wrongType = parseLength ( dynamicString ) ; | Why does the compiler treat the return type of Func < dynamic , int > as strongly typed ? |
C# | I 'm trying to make a dynamic array in C # but I get an annoying error message . Here 's my code : And the error : This is just baffling my mind . I came from VB , so please me gentle , lol.Cheers . | private void Form1_Load ( object sender , EventArgs e ) { int [ ] dataArray ; Random random = new Random ( ) ; for ( int i = 0 ; i < random.Next ( 1 , 10 ) ; i++ ) { dataArray [ i ] = random.Next ( 1 , 1000 ) ; } } Use of unassigned local variable 'dataArray ' | Ca n't make an array in C # |
C# | want to know why String behaves like value type while using ==.StringBuilder and String behaves differently with == operator . Thanks . | String s1 = `` Hello '' ; String s2 = `` Hello '' ; Console.WriteLine ( s1 == s2 ) ; // True ( why ? s1 and s2 are different ) Console.WriteLine ( s1.Equals ( s2 ) ) ; //True StringBuilder a1 = new StringBuilder ( `` Hi '' ) ; StringBuilder a2 = new StringBuilder ( `` Hi '' ) ; Console.WriteLine ( a1 == a2 ) ; //false ... | Why String behaves like value type while using == |
C# | Currently working on a 2-way lookup association generic , sorted by TKey . At some point I hope to have access like the following : But obviously when TKey == TValue this will fail . Out of curiosity , is there a conditional compile syntax to do this : | public class Assoc < TKey , TValue > { public TKey this [ TValue value ] { get ; } public TValue this [ TKey value ] { get ; } } public class Assoc < TKey , TValue > { [ Condition ( ! ( TKey is TValue ) ) ] public TKey this [ TValue value ] { get ; } [ Condition ( ! ( TKey is TValue ) ) ] public TValue this [ TKey valu... | Conditional Compile of Generic Methods |
C# | Programmers on my team sometimes open a transaction and forget to include the scope.Complete ( ) statement ( see code block below ) . Any ideas on ways to either ( 1 ) search our solution for missing scope.Complete ( ) statements , or ( 2 ) have Visual Studio automatically highlight or raise a warning for missing scope... | using ( TransactionScope scope = new TransactionScope ( ) ) { /* Perform transactional work here */ scope.Complete ( ) ; < -- we forget this line /* Optionally , include a return statement */ } using ( TransactionScope scope = new TransactionScope ( ) ) { $ statements1 $ [ ^ ( scope.Complete ( ) ; ) ] $ statements2 $ } | C # - How do I check for missing scope.Complete ( ) statements ? |
C# | How would I know what `` it '' means here ? Whole example from MSDN docs | productQuery1.SelectValue < Int32 > ( `` it.ProductID '' ) ; using ( AdventureWorksEntities context = new AdventureWorksEntities ( ) ) { string queryString = @ '' SELECT VALUE product FROM AdventureWorksEntities.Products AS product '' ; ObjectQuery < Product > productQuery1 = new ObjectQuery < Product > ( queryString ,... | Where does `` it '' come from in this example of ObjectSet < T > .SelectValue ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.