lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | The following code : produces the following output in the textbox : From the first line of the output , it is clear that in the regional setting of my PC , date/time is formatted as date.month.year HHmm.ss.The second line of the output is confusing to me . Though I specified MM/dd/yyyy format for the variable s , the D... | DateTime dt = new DateTime ( 2013 , 9 , 13 , 14 , 34 , 0 ) ; string s = dt.ToString ( `` MM/dd/yyyy '' ) ; textBox1.AppendText ( DateTime.Now + `` \n '' ) ; textBox1.AppendText ( s + `` \n '' ) ; textBox1.AppendText ( dt.ToString ( ) + `` \n '' ) ; 13.09.2013 1441.2809.13.201313.09.2013 1434.00 | Formatting DateTime to string |
C# | I just programmed a simple reverse loop like this : but it does n't stop at 0 as expected but goes down far to the negative values , why ? See this ideone sample : http : //ideone.com/kkixx8 ( I tested it in c # and c++ ) | for ( unsigned int i = 50 ; i > = 0 ; i -- ) printf ( `` i = % d\n '' , i ) ; | strange behavior of reverse loop in c # and c++ |
C# | I have a customer that is trying to access their calendars from our web application . Everything works for all of our other customers , so I am not sure what is different here except this customer is in Australia and using a non gmail.com email address . The customer is able to authorize our application and we do get a... | public class GoogleCalendarAdapter : ICalendarAdapter { # region attributes private readonly ISiteAuthTokenQueryRepository _tokenRepo ; private readonly GoogleCalendarSettings _settings ; private const string APPNAME = `` SomeAppName '' ; private const string ACL_OWNER = `` owner '' ; private const string ACL_WRITER = ... | Google Calendar returning invalid grant |
C# | Is there a way to know what parameters are needed by an event in Visual Studio 2010 ? Let 's say I have a DropDownList control and I want to bind a method to the `` OnSelectedIndexChanged '' , I would do something like thisIn the ASPX File : In the codebehind : Is there a way to know what parameters the method needs ? ... | < asp : DropDownList ID= '' lstMyList '' runat= '' server '' OnSelectedIndexChanged= '' lstMyList_SelectedIndexChanged '' > < /asp : DropDownList > protected void lstMyList_SelectedIndexChanged ( object sender , EventArgs e ) { ... } | Find the right parameters for an event without using Design Mode in Visual Studio 2010 |
C# | BackgroundWhile writing a class for parsing certain text , I needed the ability to get the line number of a specific character position ( in other words , count all linebreaks that occur before that character ) .Trying to find the most efficient code possible to achieve this I set up a couple of benchmarks , which reve... | private string text ; /// < summary > /// Returns whether the specified character index is the end of a line./// < /summary > /// < param name= '' index '' > The index to check. < /param > /// < returns > < /returns > private bool IsEndOfLine ( int index ) { //Matches `` \r '' and `` \n '' ( but not `` \n '' if it 's p... | Method is not inlined by the JIT compiler even though all criteria seems to be met |
C# | In C # given a function with the below signatureIf the function was called using Inside the function Foo is it possible to test that the x and y arguments reference the same variable ? A simple equivalent test of x and y is n't sufficient as this is also true in the case two different variable have the same value . | public static void Foo ( ref int x , ref int y ) int A = 10 ; Foo ( ref A , ref A ) | How to Test if C # ref Arguments Reference the Same Item |
C# | In a collection of valuesI 'm trying to do with linqIs there someway to do it with linq ? | [ 0 , 2 , 25 , 30 ] [ 0 , 0 , 0 , 2 , 2 , 2 , 25 , 25 , 25 , 30 , 30 , 30 ] //Replicate 2 times ( values repeated 3 times ) | Insert duplicates values linq |
C# | Let 's say I haveSometimes , instead of just sayingI end up doingor maybe evento avoid boxing or copying structs.It works fine and everything , but are there any downsides I do n't know about ( other than a negligible increase in memory usage ) ? Is this an accepted practice , or is it discouraged for any reason I migh... | interface IMatrix { double this [ int r , int c ] { get ; } } struct Matrix2x2 : IMatrix { double a1 , a2 , b1 , b2 ; double this [ int r , int c ] { get { ... } } } struct Matrix3x3 : IMatrix { double a1 , a2 , a3 , b1 , b2 , b3 , c1 , c2 , c3 ; double this [ int r , int c ] { get { ... } } } class Matrix : IMatrix { ... | Using constrained generics instead of interfaces -- downsides ? |
C# | So Say I have 2 entities , Post and PostHistory . Whenever I create or edit a post , I want to create an exact copy of it as PostHistory to log all changes made to a post . Say the post entity has the following definition : The problem comes when I create my first Post . For example , if I try this : That will fail bec... | public class Post { public int Id { get ; set ; } public string Text { get ; set ; } public virtual ICollection < PostHistory > PostHistory { get ; set ; } } Post post = new Post { Text = `` Blah '' } ; context.Posts.Add ( post ) ; PostHistory history = new PostHistory { Text = `` Blah '' } ; context.PostHistory.Add ( ... | How do I create two associated entities at one time with EF4 Code-First |
C# | When writing preconditions for different functions with similar parameters , I want to group assertions or exceptions into a static method , rather than writing them out explicitly . For example , instead ofI would prefer to writeThis feels more natural and helps cut down the code I need to write ( and might even reduc... | GetFooForUser ( User user ) { assert ( null ! = user ) ; assert ( user.ID > 0 ) ; // db ids always start at 1 assert ( something else that defines a valid user ) ; ... // do some foo work } GetBarForUser ( User user ) { assert ( null ! = user ) ; assert ( user.ID > 0 ) ; // db ids always start at 1 assert ( something e... | Is grouping preconditions into a method acceptable to stay DRY ? |
C# | In StructureMap we can proxy TInterface and TConcreteImpl with TProxy this this : I wanted to use DispatchProxy ( and globally log before method invocation and after invocation ) and globally register it for all types being instantiated from StructureMap , I 'm wondering how to accomplish this ? More specifically , I w... | ConfigurationExpression config = ... config.For < TInterface > ( ) .DecorateAllWith < TProxy > ( ) ; config.For < TInterface > ( ) .Use < TConcreteImpl > ( ) ; TConcreteImpl instance = ... TInterface proxy = DispatchProxyGenerator.CreateProxyInstance ( typeof ( TInterface ) , typeof ( TProxy ) ) .SetParameters ( instan... | StructureMap proxy all instances or modify instances just before returning |
C# | I need to add the LinkButton btnAddRow in UpdatePanel upSectionB but the problem is I 'm having this error during load : A control with ID 'btnAddRow ' could not be found for the trigger in UpdatePanel 'upSectionB'.My simplified aspx | < asp : UpdatePanel ID= '' upSectionB '' runat= '' server '' UpdateMode= '' Conditional '' ChildrenAsTriggers= '' true '' > < ContentTemplate > Request Budget ( USD ) < asp : TextBox ID= '' txtTotal '' runat= '' server '' > < /asp : TextBox > < /ContentTemplate > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' ... | Update textbox from 1st UpdatePanel using LinkButton from 2nd UpdatePanel 's gridview . Control could not be found |
C# | I have an example that I can get to break every time I use an iterator , but it works fine with a for loop . All code uses variables local to the executing method . I am stumped . There is either a fact about iterators that I am not aware of , or there is an honest to goodness bug in .Net . I 'm betting on the former .... | //lstDMSID is a populated List < int > with 10 elements.for ( int i=0 ; i < lstDMSID.Count ; i++ ) { int dmsId = lstDMSID [ i ] ; ThreadStart ts = delegate { // Perform some isolated work with the integer DoThreadWork ( dmsId ) ; } ; Thread thr = new Thread ( ts ) ; thr.Name = dmsId.ToString ( ) ; thr.Start ( ) ; } //l... | Why would an iterator ( .Net ) be unreliable in this code |
C# | Can anyone explain why the default Asp.Net Web Application template , with Individual user identification , comes with an error in the Manage Controller ? In this code line ; View is Red , because there is no SendVerificationEmail view . Is this normal ? Can this be resolved ? I could specify a view to route to likebut... | [ HttpPost ] [ ValidateAntiForgeryToken ] public async Task < IActionResult > SendVerificationEmail ( IndexViewModel model ) { if ( ! ModelState.IsValid ) { return View ( model ) ; } var user = await _userManager.GetUserAsync ( User ) ; if ( user == null ) { throw new ApplicationException ( $ '' Unable to load user wit... | Default Asp.Net Core web template comes with error |
C# | Please I have a string such as this RemoteAuthorizationTestScope|Start : En Attente Validation|:001|:01195|21/01/2015I can extract the string from the | symbol using this codehowever , there are also text such `` Start : En Attente Validation '' in the string that needs to be separated , how do I achieve this so that I... | var userInfo= '' RemoteAuthorizationTestScope|Start : En Attente Validation|:001|:01195|21/01/2015 '' var entries=userInfo.Split ( '| ' ) ; RemoteAuthorizationTestScopeStartEn Attente Validation001 0119521/01/2015 | Need to extract string from a separator in c # |
C# | Is it possible to add the attribute StretchDirection to a VisualBrush ? My VisualBrush contains a media element , and the media element has this attribute , but not the VisualBrush . When I apply the StretchDirection attribute to this MediaElement , it is ignored . I am guessing because VisualBrush is overriding it 's ... | < VisualBrush x : Key= '' vb_zoneOneAdvertisement '' TileMode= '' None '' Stretch= '' Uniform '' AlignmentX= '' Center '' AlignmentY= '' Center '' > < VisualBrush.Visual > < MediaElement / > < /VisualBrush.Visual > < /VisualBrush > | Can I add StretchDirection to a VisualBrush ? |
C# | I 'm trying to write classes which handle different number types . I know that C # ( and .Net in general , I believe ) has no INumber interface , so I can not use something like the following : That 's okay , though , because I 'd like to avoid the boxing/unboxing of every one of my numbers . I could , however , use co... | public class Adder < T > where T : INumber { public T Add ( T a , T b ) { return a + b ; } } # if FLOAT public class AdderF { public float Add ( float a , float b ) # else public class Adder { public int Add ( int a , int b ) # endif { return a + b ; } } | How can I write a single class to compile multiple times with different number types ? |
C# | In my program , you can write a string where you can write variables.For example : The name of my dog is % x % and he has % y % years old.The word where I can replace is any between % % . So I need to get a function where tells which variables I have in that string . | GetVariablesNames ( string ) = > result { % x % , % y % } | How to count the number of occurrences of some symbols ? |
C# | I 'm sorry if this is a duplicate but I have n't found anything relevant to it.So , how can I print 0 for the numbers having a whole square root with the following code ? Current O/P : | for ( n = 1.0 ; n < = 10 ; n++ ) { Console.WriteLine ( `` Fractional Part : { 0 : # . # # # # } '' , ( Math.Sqrt ( n ) - ( int ) Math.Sqrt ( n ) ) ) ; } | Printing whole numbers with { # } in C # ? |
C# | It appears that default parameters do not work on a readonly struct in c # . Am I misunderstanding something ? Instantiating an instance of this struct using var test = new ReadonlyStruct ( ) ; does not appear to honor the default values . What am I doing wrong ? | public readonly struct ReadonlyStruct { public ReadonlyStruct ( int p1 = 1 , byte p2 = 2 , bool p3 = true ) { P1 = p1 ; P2 = p2 ; P3 = p3 ; } public int P1 { get ; } public byte P2 { get ; } public bool P3 { get ; } } | Can you have default parameters on a readonly struct in c # ? |
C# | In this variable , i would like to add some \ before every '.I would like to get that after Replace : Any ideas ? Thanks ! | string html = `` < a href=\ '' annee-prochaine.html\ '' > Calendrier de l'annee prochaine < /a > '' html = html.Replace ( `` ' '' , `` \ ' '' ) ; //No changehtml = html.Replace ( `` \ ' '' , `` \ ' '' ) ; //No changehtml = html.Replace ( `` \ ' '' , `` \\ ' '' ) ; //html = > < a href=\ '' annee-prochaine.html\ '' > Cal... | Replace ' with \ ' in C # |
C# | I have a class called Foo that has a function that looks like the followingBoth Foo and Bar are in a library that I want to reuse in other projects . Now I am working on a new project and I want to subclass Bar . Let 's call it NewBar.What is a simple and flexible way to get Foo.LoadData to return a list of NewBar ? I ... | List < Bar > LoadData ( ) ; | C # Class Factories |
C# | consider the following string as inputI need to remove all instances of substring like reference : url , xcon.xfocus.net/XCon2010_ChenXie_EN.pdf ; but this reference : tag is of variable length . Need to search `` Reference : '' keyword and remove all the text till I reach the character `` ; '' .I 've used Replace func... | ( msg : '' ACTIVEX Possible Microsoft WMI Administration Tools WEBSingleView.ocx ActiveX Buffer Overflow Attempt Function Call '' ; flow : to_client , established ; file_data ; content : '' ActiveXObject '' ; nocase ; distance:0 ; content : '' WBEM.SingleViewCtrl.1 '' ; nocase ; distance:0 ; pcre : '' /WBEM\x2ESingleVi... | Replace substring of variable length from a text file |
C# | I 've run into a really strange problem when using the default keyword in a DLL project . In my DLL project ( compiled with VS2013 ) I have the following class : Now , if I use this inside the DLL project , it works perfectly . I can create classes that derive from this base class without issue . But , as soon as I try... | public class BaseClass < T > { public T value ; public bool enabled ; public BaseClass ( T value = default ( T ) , bool enabled = true ) { this.value = value ; this.enabled = enabled ; } } public class ChildClass : BaseClass < int > { } public class OtherClass { public BaseClass < int > baseInt ; } public class BaseCla... | Using default keyword in a DLL |
C# | Using WPF and MVVM I 'm trying to display camera images into a Image.Each frame camera got , a callback is called : ViewmodelEach frame , I update the variable _bmpImage : ViewModelIn order to convert the Bitmap to BitmapImage I use a converter : ConverterFinnaly bind to my view : It 's work good the 15 first second , ... | public void OnNewFrame ( object sender , EventArgs e ) { Camera camera = sender as MyCamera ; camera.ToBitmap ( out _bmpImage ) ; RaisePropertyChanged ( `` BMPImage '' ) ; } private Bitmap _bmpImage ; public Bitmap BMPImage { get { return _bmpImage ; } private set { _bmpImage = value ; RaisePropertyChanged ( `` BMPImag... | WPF image stop repainting |
C# | Lets say i have an array myarr will be of length 13 ( 0-12 Index ) which will also be the length of int [ ] val.I want to check index of myarr where its value is 4 i.e . 1,3,8,11.Then i want One way of doing this is using for loopWe can use Array.indexof but it returns the first index of that value meaning that value h... | byte [ ] myarr = { 1,4,3,4,1,2,1,2,4,3,1,4,2 } ; int [ ] val = new int [ 13 ] ; val [ 1 ] ++ ; val [ 3 ] ++ ; val [ 8 ] ++ ; val [ 11 ] ++ ; for ( int i=0 ; i < myarr.length ; i++ ) { if ( myarr [ i ] == 4 ) val [ i ] ++ ; } | Does LINQ work on Index ? |
C# | Currently I have the following block of Rx/ReactiveUI code : As you can see , it flagrantly violates the DRY principle , but I dont know how I could parameterize away the passing of properties and delegates.What is the usual way of automating the creation of these method chains in Rx/ReactiveUI ? | this.WhenAnyValue ( x = > x.Listras ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( im = > GetArray.FromChannels ( im , 0 , 1 ) ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.Grayscale , out _grayscale ) ;... | How to encapsulate the creation of long reactive chains of observables |
C# | Being a computer programming rookie , I was given homework involving the use of the playing card suit symbols . In the course of my research I came across an easy way to retrieve the symbols : gives you ♠ gives you ♥and so on ... However , I still do n't understand what logic C # uses to retrieve those symbols . I mean... | Console.Write ( ( char ) 6 ) ; Console.Write ( ( char ) 3 ) ; | Where does ( char ) int get its symbols from ? |
C# | I have a block of code where I want to apply the using statement to each command in the commands enumerable . What is the C # syntax for this ? Edit : Rider / ReSharper seems to think these two are equivalent , or at least I get a prompt to convert the for into a foreach ( this is clearly wrong ) : andEdit 2 : After so... | await using var transaction = await conn.BeginTransactionAsync ( cancel ) ; IEnumerable < DbCommand > commands = BuildSnowflakeCommands ( conn , tenantId ) ; var commandTasks = new List < Task > ( ) ; foreach ( var command in commands ) { command.CommandTimeout = commandTimeout ; command.Transaction = transaction ; com... | Await using on enumerable |
C# | I have a method in a controller : It responds to /Apps/SendNotification/ { guid } ? { SendNotification properties } SendNotification is a model with multiple string properties . My issue is that SendNotification is NEVER null . No matter how I call the action .NET seems to always instantiate an object of SendNotificati... | public ActionResult SendNotification ( Guid ? id=null , SendNotification notification =null ) routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; | Optional Parameter always filled |
C# | The goalGet one of each result returned by a foreach.The scenarioTake a look in the follow Razor 's code fragment : The return to the client is : Xbox 360Xbox 360Xbox 360Xbox 360Playstation 3Playstation 3Playstation 3Now , let me explain : my application compares the price of products in different stores . In my case ,... | @ foreach ( var product in Model.Collection.Products ) { < p > @ product.name < /p > } @ foreach ( var product in Model.Collection.Products.FirstOrDefault ( ) ) { [ ... ] } | Get one of each |
C# | Could you please help me understand why variable a is not incremented in the first case but it is in the second case ? Case 1 : Case 2 : I 've gone through other similar questions but could n't find any specifics.UPDATE 1 : How I think the program flowsCase 1 : Case 2 : UPDATE 2 : Thanks to all the answers , i think i ... | int a = 10 ; a = a++ ; Console.WriteLine ( a ) ; //prints 10 int a = 10 ; int c = a++ ; Console.WriteLine ( a ) ; //prints 11 1 . ' a ' is assigned 102 . ' a ' is assigned 10 before increment happens3 . ' a ' is incremented by 1 ( Why does n't this step affect the final value of ' a ' ? ) 4 . ' a ' is printed -- > 10 1... | Unexpected post-increment behavior in assignment |
C# | Why VS complains about this finalizer ? VS 2017 -- 15.3.5Microsoft Code Analysis 2017 -- 2.3.0.62003 | using System ; namespace ConsoleApp { class DisposableClass : IDisposable { # if DEBUG ~DisposableClass ( ) // CA1821 Remove empty Finalizers { System.Diagnostics.Debug.Fail ( `` Forgot Dispose ? `` ) ; } # endif public void Dispose ( ) { # if DEBUG GC.SuppressFinalize ( this ) ; # endif } } class Program { static void... | CA1821 Remove empty Finalizers |
C# | What is the cause for the second case ? I know I cant cast a boxed enum to int ? directly , but I do a two stage casting , ie Cast < int > .Cast < int ? > which should be working.Edit : This is surprising considering the below works : | enum Gender { Male , Female } var k = new [ ] { Gender.Male } .Cast < int > ( ) .ToList ( ) .Cast < int ? > ( ) .ToList ( ) ; //alrightvar p = new [ ] { Gender.Male } .Cast < int > ( ) .Cast < int ? > ( ) .ToList ( ) ; //InvalidCastException object o = Gender.Male ; int i = ( int ) o ; // so here the cast is not to an ... | Cast < int > .Cast < int ? > applied on generic enum collection results in invalid cast exception |
C# | I have downloaded the source code files from here of a magnifier glass effect : http : //www.codeproject.com/Articles/18235/Simple-MagnifierAnd this is the main Form code : Now it will work on two cases : The mouse should be on the Form area on the magnifier glass icon.The mouse button left button should be pressed dow... | /// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /// Class : MagnifierMainForm/// Purpose : Provide simple magnifier . /// Written by : Ogun TIGLI/// History : 31 May 2006/Wed starting date./// 22 Dec 2006/Fri minor code fixes and hotsot support addit... | How can I make the effect to be shown only when moving the mouse ? |
C# | To check the validity of a Binary Search Tree , I use a method . But the method always returns false , when tested against a valid Binary Search Tree.Online Demo HereThe code | public class Program { public static void Main ( ) { BinarySearchTree < int > tree = new BinarySearchTree < int > ( ) ; tree.Insert ( 2 ) ; tree.Insert ( 1 ) ; tree.Insert ( 3 ) ; Console.WriteLine ( tree.IsValidBinarySearchTreeRecursive ( tree.root ) .ToString ( ) ) ; // this is supposed to return true when tested aga... | Is Valid Generic Binary Search Tree with Recursion |
C# | I am developing an application that using IDocumentClient to perform query to CosmosDB . My GenericRepository support for query by Id and Predicate.I am in trouble when change Database from SqlServer to CosmosDb , in CosmosDb , we have partition key . And I have no idea how to implement repository that support query by... | public interface IRepository < T > { //I can handle this one by adding value of partition key to id and split it by `` : '' Task < T > FindByIdAsync ( string id ) ; // I am stuck here ! ! ! Task < T > FindByPredicateAsync ( Expression < Func < T , bool > > predicate ) ; } public class Repository < T > : IRepository < T... | Repository that support query by partition key without change interface |
C# | In the constructor of an object , Listener , we take an argument and subscribe to one of its events . If an exception is thrown within the constructor after the event is subscribed the OnSomethingChanged ( ) method is still called when the event is raised - even through the object was not successfully constructed and ,... | class Program { static void Main ( string [ ] args ) { Input input = new Input ( ) ; try { new Listener ( input ) ; } catch ( InvalidOperationException ) { // swallow } input.ChangeSomething ( ) ; // prints `` Something changed ! '' } } public class Listener { public Listener ( Input input ) { input.SomethingChanged +=... | Local event listener called even though object failed to be constructed |
C# | I have groups of logic that consist of static classes such as : In this case , A and B are static classes that implement the same behavior via a group of functions ( e.g . mutate ) . I would like to use something like an interface for this pattern , however since static classes can not implement interfaces I am not sur... | static class A { static int mutate ( int i ) { /**implementation*/ } ; static double prop ( double a , double b ) { /**implementation*/ } ; } static class B { static int mutate ( int i ) { /**implementation*/ } ; static double prop ( double a , double b ) { /**implementation*/ } ; } Interface IMutator { int mutate ( in... | grouping static classes with the same behavior |
C# | I 've been working on a calculator using C # and came across an issue I have n't been able to work past.Currently when a user enters a number divided by zero then the answer defaults to 0.00 when instead it should be invalid.I have no idea why and after tinkering with it for awhile I have n't been able to figure it out... | private void button1_Click ( object sender , EventArgs e ) { double number1 , number2 , ans ; // Identify variables as double to account for decimals . number1 = Convert.ToDouble ( num1.Text ) ; // Convert the contents of the textBox into a double . number2 = Convert.ToDouble ( num2.Text ) ; // ans = 0.0 ; string symbo... | Why is my `` Divide by Zero '' prevention not working ? |
C# | I have application based on this tutorialMethod I use to get user list from service : Service main function : Other classes are inClasses.csMy question is : why I ca n't send anything that is not generic type ? I need to send List < User > or User [ ] but I ca n't even send int [ 2 ] ( sending int or string is possible... | public class PBMBService : IService { public ServiceResponse UserList ( ) { try { sql.Open ( ) ; List < User > result = new List < User > ( ) ; //filling list from database return new ServiceResponse ( SRFlag.OK , result ) ; } catch ( Exception ex ) { return new ServiceResponse ( SRFlag.EXCEPTION , ex ) ; } } //other m... | Ca n't send anything that is not generic type |
C# | Basically , I have the following scenario : But , the problem I see here is that I could have done ConcreteFooB : FooBase < ConcreteFooA > { ... } , which would completely mess up the class at runtime ( it would n't meet the logic I 'm trying to achieve ) , but still compile correctly.Is there some way I have n't thoug... | public abstract class FooBase < T > where T : FooBase < T > { public bool IsSpecial { get ; private set ; } public static T GetSpecialInstance ( ) { return new T ( ) { IsSpecial = true } ; } } public sealed class ConcreteFooA : FooBase < ConcreteFooA > { ... } public sealed class ConcreteFooB : FooBase < ConcreteFooB >... | Is it possible to programmatically enforce a derived class to pass itself into a base class as the generic type ? |
C# | I 'm making a Rebar wrapper for .NET . Here 's how I 've made my control.I tested my control by adding a REBARBANDINFO into the control and IT WORKED.I wo n't include the implementation of my p/invoke signatures because everything is fine there.The problem starts hereThe control does n't work the way I 've expected , t... | public class Rebar : Control { public Rebar ( ) : base ( ) { //Control wo n't even work if I let UserPaint enabled SetStyle ( ControlStyles.UserPaint , false ) ; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ClassName = `` ReBarWindow32 '' ; //REBARCLASSNAME cp.ExStyle ... | How can I let .NET wrapper for Rebar decide the mouse cursor ? |
C# | I am relatively new to using TDD and have been reading about mocking objects lately . I have the following test to test a method that given a date returns the next saturday . first off , does this represent good testing practices ? Second , what is the advantage of utilizing a mock framework to create this test ? Let m... | [ TestMethod ( ) ] public void NextSaturdayTest ( ) { DateTime date = new DateTime ( ) ; date = DateTime.Parse ( `` 2010-08-14 '' ) ; DateTime expected = new DateTime ( ) ; expected = DateTime.Parse ( `` 2010-08-21 '' ) ; DateTime actual ; actual = DateExtensions.NextSaturday ( date ) ; Assert.AreEqual ( expected , act... | Should I use mocking for the following example |
C# | I have a simple AngularJS $ http block like so ; My issue is that when my ASP.NET Controller returns a HTTP error code , the JS errorCallback receives an object like ; No matter what I do , I ca n't seem to populate the data property in my callback.If instead my controller returns a HTTP OK code , then the 'success ' c... | $ http ( req ) .then ( function successCallback ( response ) { alert ( response ) ; } , function errorCallback ( response ) { alert ( response ) ; } ) ; { data : `` '' , status : 304 , config : Object , statusText : `` Not Modified '' } [ System.Web.Http.HttpPost ] public async Task < HttpResponseMessage > Save ( [ Fro... | AngularJS $ http ( ... ) errorHandler receives empty string for data |
C# | If I Invoke a method onto the UI Thread is it searilized by the Windows message queue and subsequently does n't need to be re-entrant ? Clarification : It is only the UI thread that will be accessing _counter . | private void CalledFromWorkerThread ( ) { //changed from 'InvokeRequired ' Anti-Pattern this.Invoke ( ( Action ) ( ( ) = > _counter++ ; /* Is this ok ? */ ) ) ; } | Does a method marshalled on the UI Thread need to be thread-safe |
C# | Edit : Please read carefully , I have and issue Loading data for without cartesian production . Deleting data works fine if the references are loaded properly . I 'm trying to delete a large group of entities , However due to a many-to-many assoication OwnerRoles whenever I try to delete them I receive an error : SqlEx... | var rolesQuery = context.Organizations .Where ( x = > x.OrganizationId == organizationId ) .SelectMany ( x = > x.aspnet_Roles ) ; var roles = rolesQuery.ToArray ( ) ; rolesQuery.SelectMany ( x = > x.Permissions ) .Load ( ) ; rolesQuery.SelectMany ( x = > x.Organizations ) .Load ( ) ; roles.ForEach ( r = > r.Organizatio... | Entity Framework Reference constraint error on delete when using selectmany |
C# | EDITI took Jon 's comment and retried the whole thing . And indeed , it is blocking the UI thread . I must have messed up my initial test somehow . The string `` OnResume exits '' is written after SomeAsync has finished . If the method is changed to use await Task.WhenAll ( t ) it will ( as expected ) not block . Thank... | // This runs on the UI thread.async override OnResume ( ) { // What happens here ? Not necessarily a new thread I suppose . But what else ? Console.WriteLine ( `` OnResume is about to call an async method . `` ) ; await SomeAsync ( ) ; // Here we are back on the current sync context , which is the UI thread . Something... | How does the runtime know when to spawn a thread when using `` await '' ? |
C# | I tried the following to detach a graph of entity objects , and then attach it to a new context : I have two issues with this approach : After detaching all entity objects , newParent.Children becomes emptyAn InvalidOperationException is raised when re-attaching saying that `` An entity object can not be referenced by ... | // create a contextvar ctx = new TestEntities ( ) ; var parents = ctx.Parents ; // populate the graphvar newParent = new Parent { Nb = 1 , Title = `` Parent1 '' } ; parents.AddObject ( newParent ) ; newParent.Children.Add ( new Child { Nb = 1 , Title = `` Child1 '' } ) ; // put all entity objects in Unchanged state bef... | Can a graph be detached from an ObjectContext and be re-attached to another one ? |
C# | I have seen on various websites how developers version their css/javascripts files by specifying querystrings similar to : How is that done ? Is it a good practice ? I 've been searching around but apparently , I 'm not looking for the right terms . If it matters , I 'm using ASP.NET.Edit : : I just noticed ( via Fireb... | < head > < link rel= '' stylesheet '' href= '' css/style.css ? v=1 '' > < script src= '' js/helper.js ? v=1 '' > < /head > | How to version files in the < HEAD > section ? |
C# | I 'm building a small chat program that consists of a server and client . The server keeps a list of clients that it interacts with.I 've got two worker threads on the server . One handles incoming client connections . The other handles incoming client messages.Now , since both threads interact with a List called 'clie... | // The clients list looks something like this ... List < TcpClient > clients ; // This is running on one thread.ConnectionHandler ( ) { while ( true ) { // Wait for client to connect , etc . etc . // Now , add the client to my clients List . lock ( clients ) clients.Add ( myNewClient ) ; } } // This is running on anoth... | Is this a correct use of multithreading design ? ( C # ) |
C# | I have a List of Objects and within the Object there is a List of strings . What I want to do is find out how many of each string value there are.So to create a simple example with the languages spoken by people in a team.Create the test data ... To visualise the data : I can get the result I want by finding the distin... | public class PeopleLanguages { public string Name ; public List < string > Languages ; } List < PeopleLanguages > peopleLanguages = new List < PeopleLanguages > ( ) ; peopleLanguages.Add ( new PeopleLanguages { Name = `` Rod '' , Languages = new List < string > { `` English '' , `` French '' , `` German '' } } ) ; peop... | c # linq GroupBy on the values of a List within a List |
C# | I have the following script : And I need to return the following XML : The idea is that I will convert the XML into a DataSet with 2 DataTables ( one for Columns and the other for Rows ) . I will use this to populate a DataGridView.However , my problem is that the XML I 'm generating currently is malformed and is n't t... | DECLARE @ columns TABLE ( Caption varchar ( 50 ) , Width int ) ; INSERT INTO @ columns VALUES ( 'Id ' , 0 ) , ( 'Name ' , 100 ) ; DECLARE @ rows TABLE ( Id int , [ Name ] varchar ( 50 ) ) ; INSERT INTO @ rows VALUES ( 1 , 'John ' ) , ( 2 , 'Steve ' ) ; SELECT * , ( SELECT * FROM @ rows FOR XML PATH ( 'Row ' ) , ROOT ( ... | How to return multiple tables as one XML ? |
C# | Most of the applications consuming my add-in return `` C : \Users\ [ username ] \AppData\Local\Temp\ '' path . But one application is returning `` C : \Users\ [ username ] \AppData\Local\Temp\1affa5dd-2f26-4c96-9965-7a78f5c76321\ '' . The GUID in the end changes every time I launch the application.The application that ... | public static string GetLocalFilePath ( string sourceUri , string fileName , string extension ) { string [ ] sasTokenSeparated = sourceUri.Split ( ' ? ' ) ; string [ ] uriParts = sasTokenSeparated [ 0 ] .Split ( '/ ' ) ; string documentId = uriParts [ uriParts.Length - 2 ] ; documentId = documentId.Split ( ' . ' ) [ 0 ... | Path.GetTempPath ( ) method returns UserTempPath with GUID in the end when using Revit 2020 |
C# | I basically want two separate overloads for string/FormattableString ( the background is that I want to nudge people towards using string constants for log messages and pass parameters via structured logging instead of the log message to simplify analysis . So the FormattableString logging method would be obsoleted ) .... | public struct StringIfNotFormattableStringAdapter { public string StringValue { get ; } private StringIfNotFormattableStringAdapter ( string s ) { StringValue = s ; } public static implicit operator StringIfNotFormattableStringAdapter ( string s ) { return new StringIfNotFormattableStringAdapter ( s ) ; } public static... | Overload Resolution with implicit conversions |
C# | I 'm inserting a special ( summary ) row into a DataTable , and I want it to appear last in a sorted DataView . I know the DataView is being sorted ( ascending ) by a particular string column , and for display purposes it does n't matter what value appears in that column of the summary row.What string can I place in th... | footerRow [ colGrouping ] = `` \uFFFF '' ; | Who is the greatest among all strings ? |
C# | In my class I have these setters/getters : DateTime is a non-nullable type . So , when I retrieve my data from my legacy database that I pass to the class constructor , I get an error when the StartDate is null.How should I go about designing around this ? ThanksEric | public int Id { get ; set ; } public String ProjectName { get ; set ; } public String ProjectType { get ; set ; } public String Description { get ; set ; } public String Status { get ; set ; } public DateTime StartDate { get ; set ; } | How to design class around null values from database ? |
C# | I 'm currently dealing with 2 systems that expose interop via their own RESTful JSON APIs . One is in C # with JSON.NET and one is Java Spring Boot Starter ( Jackson JSON ) . I have full control over both systems.Both systems need to transfer JSON data with reference handling . Whilst both JSON serialization frameworks... | { `` Resources '' : [ { `` Id '' : 0 , `` Name '' : `` Resource 0 '' } , { `` Id '' : 1 , `` Name '' : `` Resource 1 '' } ] , `` Tasks '' : [ { `` Id '' : 0 , `` Name '' : `` Task 0 '' , `` Resource '' : 0 } , { `` Id '' : 1 , `` Name '' : `` Task 1 '' , `` Resource '' : 1 } , { `` Id '' : 2 , `` Name '' : `` Task 2 ''... | Dealing with JSON interop between Java and C # REST APIs |
C# | I refer to the Examples in How to : Combin Data with Linq by using joins . We have two Lists the first holds person objects ( First- and Lastname ) . The second List holds Pet objects ( Name ) that holds a person object ( pet owner ) . One Person can own > = 0 pets . What happend now is I performed the group join LinqP... | Dim result1 = From pers in people Group Join pet in pets on pers Equals pet.Owner Into PetList = Group Select pers.FirstName , pers.LastName , PetName = If ( pet is Nothing , String.Empty , pet.Name ) | Does Linq produces redundancies ? |
C# | I have tried two ways but they both didnt work..the first way : :the second way : :is there something wrong i dont see ... my xml file looks like this : :and i used a query string to load the values from a gridView located in another page using `` QueryString '' ... .thanks in advance . | string filepath = Server.MapPath [ this is not a link ] ( `` XMLFile2.xml '' ) ; XmlDocument xdoc = new XmlDocument ( ) ; xdoc.Load ( filepath ) ; XmlNode root = xdoc.DocumentElement ; XmlNode idNode = root.SelectSingleNode ( `` /students/student/id '' ) ; if ( idNode.Value == 9.ToString ( ) ) { var nodeOfStudent = xdo... | xml nodes editing based on an xmlElement |
C# | In my application I want to join multiple strings with a dictionary of replacement values . The readTemplateBlock gets fed with FileInfos and returns their contents as string.The getReplacersBlock gets fed ( once ) with a single replacers dictionary.The joinTemplateAndReplacersBlock should join each item of the readTem... | // Buildvar readTemplateBlock = new TransformBlock < FileInfo , string > ( file = > File.ReadAllText ( file.FullName ) ) ; var getReplacersBlock = new WriteOnceBlock < IDictionary < string , string > > ( null ) ; var joinTemplateAndReplacersBlock = new JoinBlock < string , IDictionary < string , string > > ( ) ; // Ass... | A datablock to join a single result with multiple other results |
C# | IntroI am working with a complex external library , where I am attempting to execute it 's functionality on a large list of items . The library does not expose a good async interface , so I 'm stuck with some quite old-fashioned code . My aim is to optimize the time it takes to complete a batch of processing , and to d... | public interface IAction { int Size { get ; } void Execute ( ) ; } public class LongAction : IAction { public int Size = > 10000 ; public void Execute ( ) { Thread.Sleep ( 10000 ) ; } } public class MediumAction : IAction { public int Size = > 1000 ; public void Execute ( ) { Thread.Sleep ( 1000 ) ; } } public class Sh... | Time optimization of parallel long-running tasks |
C# | If a dependency container , or data access factory , can return types that may implement IDisposable , should it be the client 's responsibility to check for that and handle it ? In my code below , one data class implements IDisposable and the other does n't . Either can be returned by the data access factory.The reaso... | private static void TestPolymorphismWithDisposable ( ) { // Here we do n't know if we 're getting a type that implements IDisposable , so // if we just do this , then we wo n't be disposing of our instance . DataAccessFactory.Resolve ( ) .Invoke ( ) ; // Do we just have to do something like this ? IFoo foo = DataAccess... | Polymorphism when concrete types *might* be disposable |
C# | I want to declare several constant objects that each have two subobjects , and I 'd like to store these in an enum for organizational purposes.Is it possible to do something like this in C # ? | enum Car { carA = { 'ford ' , 'red ' } carB = { 'bmw ' , 'black ' } carC = { 'toyota ' , 'white ' } } | Is it possible to create an enum containg arrays ? |
C# | I 'm trying to estimate the widths in pixel if a text would be rendered in Chrome by using C # for a specific font ( Arial 18px ) in a tool that I 'm creating.Comparing my results with this tool ( uses the browser to render the width ) : http : //searchwilderness.com/tools/pixel-length/ the string : Is calculated to be... | `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . '' var font = new Font ( `` Arial '' , 18 , FontStyle.Regular , GraphicsUnit.Pixel ) ; var text = `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . `` ; var size = TextRenderer.MeasureText ( text , font , new Size ( int.MaxValue , int.MaxValue ) ... | C # : Pixel width matching text rendered in a browser |
C# | Followup to this question : Why is Nullable < T > considered a struct and not a class ? I have two classes that essentially maintain a tuple of some user-supplied value with an internal object.When the type of the user-supplied value is a primitive , I have to wrap it in a Nullable < T > so that it can take on a null v... | public class BundledClass < T > where T : class { private Tuple < T , object > _bundle ; public T Value { get { return _bundle == null ? null : _bundle.Item1 ; } set { _bundle = new Tuple < T , object > ( value , internalObj ) ; } } // ... public class BundledPrimitive < T > where T : struct { private Tuple < T ? , obj... | Is there any way to combine these almost identical classes into one ? |
C# | This is more of a C # syntax question rather than an actual problem that needs solving . Say I have a method that takes a delegate as parameter . Let 's say I have the following methods defined : Now if I want to call TakeSomeDelegates with FirstAction and SecondFunc as arguments , As far as I can tell , I need to do s... | void TakeSomeDelegates ( Action < int > action , Func < float , Foo , Bar , string > func ) { // Do something exciting } void FirstAction ( int arg ) { /* something */ } string SecondFunc ( float one , Foo two , Bar three ) { /* etc */ } TakeSomeDelegates ( x = > FirstAction ( x ) , ( x , y , z ) = > SecondFunc ( x , y... | Is there any way to use C # methods directly as delegates ? |
C# | My main page sends an API request in async way and then sets the main page to some other other page like this : These are my WebView events : Now the problem is when the page containing WebView is set to main page when app starts it is opening the website fine . But when it is set from another main page then it goes in... | async private void GetContacts ( ) { try { activityIndicator.IsVisible = true ; activityIndicator.IsRunning = true ; var contacts = await Plugin.ContactService.CrossContactService.Current.GetContactListAsync ( ) ; var contactsWithPhone = contacts ! = null & & contacts.Count > 0 ? contacts.Where ( c = > c.Number ! = nul... | Trying to change MainPage but WebView on the new page fails to load site . But it is successful when I set it as the main page when application starts |
C# | I just bumped into a really strange C # behavior , and I ’ d be glad if someone could explain it to me.Say , I have the following class : As I get it , in the line of commentary I have the following objects in my field of view : len variable and call.Inside of lambda , I have local parameter len and Program.len variabl... | class Program { static int len = 1 ; static void Main ( string [ ] args ) { Func < double , double > call = len = > 1 ; len = 1 ; // error : 'len ' conflicts with the declaration 'csutils.Program.len ' Program.len = 1 ; // ok } } class Program { static int len = 0 ; static void Main ( string [ ] args ) { { int len = 1 ... | Lambda capture parameter provoking ambiguity |
C# | Suppose to have a polygon class like this one : To make triangles , squares , hexagons would you rather : Inherit from Polygon your Triangle , Square , etc . class that provides aspecific constructor and generate points programmatically ? Add a CreateSquare static method that returns a ready to use Polygon class ? This... | public class Polygon { Point [ ] _vertices ; public class Polygon ( Point [ ] vertices ) { _vertices = vertices ; } } public class Square : Polygon { public class Polygon ( double size ) { _vertices = new Point [ ] { new Point ( 0,0 ) , new Point ( size,0 ) , new Point ( size , size ) , new Point ( 0 , size ) } ; } } p... | OOP object creation guidelines |
C# | I am trying to render a simple view with the TinyWeb framework and Spark view engine.Enviroment is Visual Studio 2011 developer preview & .net 4.5Rendering a template with no model binding works fine.However when I bind a model then it no longer works.I get this error : The name 'Model ' does not exist in the current c... | public class IndexHandler { Route route = new Route ( `` / '' ) ; public IResult Get ( ) { var model = new { message = `` Hello World '' } ; return View.Spark ( model , `` Views/base.spark '' ) ; } } < html > < head > < title > This is a test < /title > < /head > < body > < p > $ { Model.message } < /p > < /body > < /h... | Can not render view in TinyWeb framework |
C# | Update : Heinzi is right . AutoCAD Polyline is reference type and not a struct . Good point . But I have simplified the scenario as what I am dealing with in the real application is an AutoCAD object which is struct . So please consider both as struct not reference type.I am looking for the right approach to take in th... | interface IEntity { void object GetPoly ( ) ; void void InsertPoly ( object poly ) ; } class AutocadEntity { void object GetPoly ( ) { //calling Autocad APIs return Autocad Polyline object } void InsertPoly ( object poly ) { ... } } | Using generic in the interface |
C# | I want to store Sub instances in a collection . However , to get it to actually work , I have to declare an interface and store instances of that interface.Is there a more elegant way of doing this ? | class B : A { } class Sub < T > where T : A { // ... } var c = new List < Sub < A > > ( ) ; c.Add ( new Sub < B > ( ) ) ; //does n't work interface IBase { void DoStuff ( A a ) ; } var c = new List < IBase > ( ) ; c.Add ( new Sub < B > ( ) ) ; //works | Generics and casting |
C# | I have this problem : I want to generate a new source code file from a object information.I make something like this : dictParamMapping is a Dictionary < string , Type > where the string is a variable name and Type is the type of that variable.I get the type to build new code using : When Type is int , string , datatab... | dictParamMapping [ pairProcess.Value ] .Type.Name ( or FullName ) System.Collections.Generic.Dictionary ` 2 [ [ System.Int32 , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] , [ System.Double , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] | How to reuse Type returned value to generate new source code |
C# | I 'm currently using Visual Studio ( specifically , 2012 Express ) . I have an interface already defined as follows : If I have an empty class : And I right-click on the IMyInterface , I can select `` Implement Interface '' . When I do this , the auto-generated code produces the following : My question is , is there a ... | interface IMyInterface { public String Data { get ; set ; } } class MyClass : IMyInterface { } class MyClass : IMyInterface { public string Data { get { throw new NotImplementedException ( ) ; } set { throw new NotImplementedException ( ) ; } } } public String Data public string Data | How can I prevent the generated implementation of an interface from using a type alias ? |
C# | I 've been working on a project for a client and had a lot of fun integrating SignalR into the system.Everything seems to work really well and the client is really excited about how the SignalR gives true real-time feedback for their application.For the most part everything has gone swimmingly , however I 've come into... | public class ClientHub : Hub { [ ... ] protected void UpdateRecords ( List < Int32 > ChangedValues ) { using ( var database = new DbContext ( ) ) { foreach ( Record R in database.Records.Where ( Rc = > ChangedValues.Contains ( Rc.Id ) ) { SignalRFormattedRecord Serialized = new SignalRFormattedRecord ( Record ) ; forea... | SignalR client calls fail for certain languages |
C# | I have a DoDragDrop where I set the data to a Point.when I drag within one instance – everything 's OK . But when I drag between two instances of the program Visual Studio gives me this error : The specified record can not be mapped to a managed value class.Why ? EDIT : here 's the code : And : | DataObject d = new DataObject ( ) ; d.SetData ( `` ThePoint '' , MyPoint ) ; DragDropEffects e = DoDragDrop ( d , DragDropEffects.Move ) ; Point e2 = ( Point ) e.Data.GetData ( `` ThePoint '' ) ; | Why ca n't I drag a Point between two instances of a program ? |
C# | First , excuse the rather funny name of my question . I 'm no native speaker and it took me 10 minutes to express my thoughts in these few characters.What I 'm trying to do is to create a dictionary in C # that allows the value to be either an int , a string or a bool . What first had come to my mind was using generics... | Dictionary < string , ( string , int , bool ) > foo = new Dictionary < string , ( string , int , bool ) > ( ) ; foo.Add ( `` key1 '' , `` Hello , World ! `` ) ; //Correct - Value is a stringfoo.Add ( `` key2 '' , 37 ) ; //Correct - Value is an intfoo.Add ( `` key3 '' , true ) ; //Correct - Value is a booleanfoo.Add ( `... | Dictionary with limited number of types |
C# | Say , we have 2 classes : Then whyThe same for explicit operator.P.S . : casting each element manually ( separetely ) works | public class A { public int a ; } public class B { public int b ; public static implicit operator B ( A x ) { return new B { b = x.a } ; } } A a = new A { a = 0 } ; B b = a ; //OKList < A > listA = new List < A > { new A { a = 0 } } ; List < B > listB = listA.Cast < B > ( ) .ToList ( ) ; //throws InvalidCastException L... | Why Enumerable.Cast does not utilize user-defined casts ? |
C# | ( let 's assume I have 10 cores ) When I write : Questions : What is the formula of assigning amount of numbers to each core ? ( is it 100/10 ? ) At execution point , does each core already know which numbers is is gon na handle ? Or does it consume each time a new number/s from the [ 0..100 ] repository ( let 's ignor... | Parallel.For ( 0 , 100 , ( i , state ) = > { Console.WriteLine ( i ) ; } ) ; | Parallel and work division in c # ? |
C# | Here I have a list from my class AssinantesAnd I needed to group by City , ClientCod and Num , which I 've already done here : Then , I needed to generate an html string with Linq , like the example below : Could somebody give me any sugestion ? | new Assinante { City= `` BAURU '' , Num= 112 , ClientCode= 3123 , Phone= `` 1412345675 '' } , new Assinante { City= `` BAURU '' , Num= 45 , ClientCode= 3123 , Phone= `` 214464347 '' } var listGroup= ( from a in lista group a by new { a.City , a.ClientCode , a.Num } ) ; < div > < h2 > Bauru < /h2 > < ul > < li > 3123 < ... | How do I generate an html string from group by |
C# | I have a problemI have a table with 44839 recordsBut when I try to load my table through EF with this code : I only get 16311 recordsBut when I use this I get all my recordsWhy is this happening ? ? | dbContext = new MyDbContext ( `` MyContext '' ) ; dbContext.SalesRegister.Load ( ) ; BindingList < SalesRegister > db =dbContext.SalesRegister.Local.ToBindingList ( ) ; gridControl.DataSource = db ; bsiRecordsCount.Caption = `` RECORDS : `` + db.Count ; dbContext = new MyDbContext ( `` MyContext '' ) ; List < SaleRegis... | Entity Framework Load ( ) method does n't load everything |
C# | FINAL EDITI 've more thoroughly tested the `` feature '' and written a complete article about it : Optional passed by reference parameters with C # for VBA COM APIsAny feedback is welcome.For whatever reason in C # a method ca n't have optional passed by reference ( marked with ref or out ) parameters.But in other infr... | void SomeDotNetCSMethod ( [ Optional ] ref someParameter ) | Possible nasty side effects of tricking .Net to have optional ref parameters for COM |
C# | I have custom class deriving from a library ( Satsuma ) like so : and a Neighbors method in the library that returns List < Node > . I want to be able to do this : But Any sees n as a Node , not DCBaseNode , so it does n't understand .selected.So I tried : ... which gives me this error : Error CS1928 : Type System.Coll... | public class DCBaseNode : Node { public bool selected = false ; } graph.Neighbors ( theNode ) .Any ( n = > n.selected == true ) ; graph.Neighbors ( theNode ) .Any < DCBaseNode > ( n = > n.selected == true ) ; | C # - Error CS1928 : Checking for list element with derived class |
C# | This code works : ... and so does this ( with the same result ) : Is there a reason to prefer one ( First , or Find ) over the other ? UPDATESo , using Reed 's suggestion , all I need is this : ... and it 's safe / it fails gracefully ( or not at all , of course , when provided a proper ID val ) . | public SiteMapping GetById ( int ID ) { var entity = siteMappings.First ( p = > p.Id == ID ) ; return entity == null ? null : entity ; } public SiteMapping GetById ( int ID ) { var entity = siteMappings.Find ( p = > p.Id == ID ) ; return entity == null ? null : entity ; } public SiteMapping GetById ( int ID ) { return ... | Is Find preferred over First , or vice versa , in LINQ ? |
C# | We have a web ASP.NET application with target framework 4.5.1 , which references some library built with target framework 2.0 . So , 4.5.1 can use 2.0 , that 's okay.But both app and library uses log4net 1.2.11 and app uses package for 4.0 framework , when library uses package for 2.0 framework.Here how it looks : When... | Application [ 4.5.1 ] -- > Library [ 2.0 ] | | V V log4net [ 4.0 ] log4net [ 2.0 ] | How target framework really works ( and why lib for 2.0 can use lib for 4.0 ) ? |
C# | I want to add a form-feed to my panel after each Item that I print so that I can have each Item print on its own page.Is that even possible to do ? For example I can add a line-break to my panel but not sure how to add a form-feed.Example : Any help would be appreciated.Thank you | Panel1.Controls.Add ( new LiteralControl ( `` < br / > '' ) ) ; | Is it possible to add a form-feed to an asp.net panel ? |
C# | How can i work with Array in Object ArrayPlease see picture for more info : I use from forech for get Object and then i want to work with Array in Object but it 's not possibleI want to get value from array and work with them for example i want to get `` TestCategory_1 '' or etc but i ca n't now how can i work with val... | foreach ( object element in result ) | work with array in object array |
C# | I am trying to understand need for static constructors . None of information I found answered following question I have . Why would you do thisas opposed to this ? This is not dupe of other question , this is about static constructors which do n't accept parameters . | class SimpleClass { // Static variable that must be initialized at run time . static readonly long baseline ; // Static constructor is called at most one time , before any // instance constructor is invoked or member is accessed . static SimpleClass ( ) { baseline = DateTime.Now.Ticks ; } } class SimpleClass { // Stati... | Trying to understand static constructors |
C# | I want DateTime in the following format.Output : I want to subtract 4 hours from this time . So I have used this line of code : Now , not only is the wrong time being shown , the above format is also disturbed.Expected Output : | DateTime a = Convert.ToDateTime ( DateTime.UtcNow.ToString ( `` s '' ) + `` Z '' ) ; 2018-05-29T09:16:59Z var result = a.AddHours ( -4 ) ; 29-05-2018 10:52:51 2018-05-29T05:16:59Z | DateTime.AddHours gives wrong output and datetime format changes |
C# | So , I know very little about decorators / adorners , but was given a great answer here which uses them.I have tried to implement them , but they ust dont seem to work as they do for the person who gave the answer . I have tried to keep everything as identical as I can.Here is my XAML : Here is the Adorner class : And ... | < models : TipFocusDecorator x : Name= '' LoginDecorator '' TipText= '' Enter your username and password and click 'Login ' '' IsOpen= '' { Binding ShowLoginTip } '' Grid.Column= '' 1 '' Grid.Row= '' 1 '' > < Image Grid.Column= '' 1 '' Grid.Row= '' 1 '' Source= '' { Binding EnemyImagePath , FallbackValue= { StaticResou... | Why wont my custom decorator / adorner function when bool changes to true ? |
C# | Consider the following code snippet , a traversal of a three dimensional array of singles , in terms of execution efficiency , assuming that process1 ( ) and process2 ( ) take identical lengths of time to execute : Now , it 's known that C # organizes arrays in the .NET framework as row-major structures . Without any o... | float arr [ mMax , nMax , oMax ] ; for ( m = 0 ; m < mMax ; m++ ) for ( n = 0 ; n < nMax ; n++ ) for ( o = 0 ; o < oMax ; o++ ) { process1 ( arr [ m , n , o ] ) ; } for ( o = 0 ; o < oMax ; o++ ) for ( n = 0 ; n < nMax ; n++ ) for ( m = 0 ; m < mMax ; m++ ) { process2 ( arr [ m , n , o ] ) ; } | .NET Compiler -- Are there nested loop optimizations built-in ? |
C# | I want to underline a word with a round brace . This should be part of a C # Text but if it is easier in CSS , no problem . My problem is that the length of the Word can vary , so the bow must by calculated for each word.My first idea was using CSS box-shadow : CSS : HTML : Unfortunately due to the dynamic Text sizes I... | # test { font-size : 50px ; background : transparent ; border-radius : 70px ; height : 65px ; width : 90px ; box-shadow : 0px 6px 0px -2px # 00F ; font-family : sans-serif ; } < div id= '' test '' > Hey < /div > | Dynamic text underlined by braces |
C# | Is there a way to change `` ABCDEFGHIJKLMNOP '' to `` ABCD-EFGH-IJKL-MNOP '' using string.format ( ) function or perhaps LINQ ? I am using this statement is there a better and clearer way to accomplish this ? | Out= String.Format ( `` { 0 } - { 1 } '' , String.Format ( `` { 0 } - { 1 } - { 2 } '' , In.Substring ( 0 , 4 ) , In.Substring ( 4 , 4 ) , In.Substring ( 8 , 4 ) ) , In.Substring ( 12 , 4 ) ) ; | What is the best way to separate string using string.format ( ) function or LINQ ? |
C# | Dabbling in reactive programming , I often encounter situations where two streams depend on each other . What is an idiomatic way to solve these cases ? A minimal example : There are buttons A and B , both display a value . Clicking on A must increment the value of A by B. Clicking on B must set the value of B to A.Fir... | let solution1 buttonA buttonB = let mutable lastA = 0 let mutable lastB = 1 let a = new Subject < _ > ( ) let b = new Subject < _ > ( ) ( OnClick buttonA ) .Subscribe ( fun _ - > lastA < - lastA + lastB ; a.OnNext lastA ) ( OnClick buttonB ) .Subscribe ( fun _ - > lastB < - lastA ; b.OnNext lastB ) a.Subscribe ( SetTex... | Cycling dependencies between streams in reactive programming |
C# | Today I tested the following code in Visual Studio 2010 ( .NET Framework version 4.0 ) And I was shocked to find these two on the list : System.Collections.Generic.IReadOnlyList ` 1 [ [ System.Int32 , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] , mscorlib , Version=4.0.0.0 , Cultu... | Type [ ] interfaces = typeof ( int [ ] ) .GetInterfaces ( ) ; System.Collections.Generic.IReadOnlyList < int > list = new int [ 3 ] ; int [ ] array = new int [ 3 ] ; Type iReadOnlyCollection = Type.GetType ( `` System.Collections.Generic.IReadOnlyCollection ` 1 [ [ System.Int32 , mscorlib , Version=4.0.0.0 , Culture=ne... | How can Type int [ ] implement interfaces that do not yet exist ( for me ) ? |
C# | I have an object model that has a property like this : I want the DoSomeWork function to execute automatically after the SomeString property changes . I tried this but it 's not working : What 's the correct syntax ? | public class SomeModel { public string SomeString { get ; set ; } public void DoSomeWork ( ) { ... . } } public string SomeString { get ; set { DoSomeWork ( ) ; } } | Setting only a setter property |
C# | There is DataTable with primary key to store information about files . There happen to be 2 files which differ in names with symbols ' 4 ' and ' 4 ' ( 0xff14 , a `` Fullwidth Digit Four '' symbol ) . The DataTable fails to include them both because of failed uniqueness . However , in Windows filesystem they seem to be ... | using System ; using System.Data ; namespace DataTableUniqueness { class Program { static void Main ( string [ ] args ) { var changes = new DataTable ( `` Rows '' ) ; var column = new DataColumn { DataType = Type.GetType ( `` System.String '' ) , ColumnName = `` File '' } ; changes.Columns.Add ( column ) ; var primKey ... | ' 4 ' and ' 4 ' clash in primary key but not in filesystem |
C# | For example . Lets say we have a stackpanel on a form . Its full of both Grids and Labels . I want to loop through all the Grids and do some operation on them but leave the Lables intact . At the moment I am doing it this way.So i 'm using the fact that `` as '' returns null if it can not cast into the required type . ... | foreach ( UIElement element in m_stacker.Children ) { Grid block = element as Grid ; if ( block ! = null ) { //apply changes here } } | Using `` as '' and expecting a null return |
C# | I have a small Dotnet core program ( 3.1.8 ) , with some FileWatchers.They watch folders on a network drive.With some load ( 200 - 250 files maximum here ) , the program crashes unexpectedly.These files come at the same time , moved by another process on another server thanks to a Biztalk app , I do n't think it 's rel... | private void InitializeInnerFilewatcher ( List < string > filters ) { _watcher = new FileSystemWatcher ( WatchPath ) ; _watcher.InternalBufferSize = 65536 ; if ( filters.Count > 1 ) { _watcher.Filter = FILTER_ALL ; // * . * _customFilters = filters ; } else _watcher.Filter = filters.First ( ) ; _watcher.NotifyFilter = ... | .NetCore - FileSystemWatcher on a network drive , unsafe code Win32 API crash |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.