lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | Could someone please help enlighten me ? I went to check-in some changes to TFS and my check-in was rejected . It prompted me to take a look at a switch statement I had edited . What I 've found is that Visual Studio 2017 claims there is no compile time issue and allows me to build and deploy the application successful... | public enum PaymentStatus { Issued , Cleared , Voided , Paid , Requested , Stopped , Unknown } public class PaymentViewModel { public PaymentStatus Status { get ; set ; } ... public String StatusString { get { switch ( this.Status ) { case PaymentStatus.Cleared : return `` Cleared '' ; case PaymentStatus.Issued : retur... | Invalid Switch syntax builds successfully ? |
C# | What I 'm doing is looking up a value for a particular field in the hashtable . The object can be a handful of primitive types who 's value is destined to be put inside XML but it comes out of the hashtable as an object . So I have the problem of needing to decide what the type is , cast it up and then use that types T... | public string GetColumnValue ( string columnName ) { object value = item [ columnName ] ; if ( value == null ) return string.Empty ; if ( value.GetType ( ) == typeof ( string ) ) { return ( string ) value ; } else if ( value.GetType ( ) == typeof ( double ) ) { return ( ( double ) value ) .ToString ( ) ; } ... } | A clean way to cast to an objects actual type |
C# | In the following code : ... what is the meaning of ( i & 1 ) == 1 ? | Expression < Func < int , bool > > isOdd = i = > ( i & 1 ) == 1 ; | What is the meaning of the & operator ? |
C# | I have been reading a book called Clean Code A Handbook of Agile Software Craftsmanship . The author in the book motivates that a switch statement should be avoided and if it can not be avoided it should be relegated to factory methods . I have a connection object which is receiving various PDUs ( protocol data units )... | public BasePdu ReceiveNext ( ) ; | How can a switch statement be avoided if the return type is unknown by the calling method ? |
C# | I have viewed similar SO questions but can not figure out why mine wo n't work.I need to convert my Func < string , bool > value to an Expression to be used in the Moq framework but I can not get passed an error when trying to convert the Func to an Expression.This is the error : Static method requires null instance , ... | using System ; using System.Linq.Expressions ; namespace ConsoleApp1 { class Program { public class MyObject { public void Add < T > ( Func < T , bool > value ) { // Line below causes error : Static method requires null instance , // non-static method requires non-null instance . Expression < Func < T , bool > > expres... | Expression.Call causes `` Static method requires null instance , non-static method requires non-null instance '' |
C# | I was trying to find information about transforming an index that has been converted from a 2 dimensional index , to a single one . Then turn the single index back to a 2 dimensional one . I do n't even know what this method is called.formula to single indexSo my question is how do I turn it back into two dimensions ? ... | int index = x + y * width ; MyArray [ index ] ; int x = index ? ? ? width ; int y = index ? ? ? width ; | Two dimension array to single dimension and back again |
C# | Let cls be of type XmlNodeFollowing statement allows me to access child nodes : Now when I try to use var : then the type of child is not XmlNode , only object . I can not use child.NodeType , compiler says : object ' does not contain a definition for 'NodeTypeWhy is this ? | foreach ( XmlNode child in cls.ChildNodes ) foreach ( var child in cls.ChildNodes ) | Why var used in foreach for XmlNode does not deduce real type , only object ? |
C# | If I save this string to a text file ; Hello this \n is a test messageThe \n character is saved as HEX [ 5C 6E ] I would like to have it saved as [ 0A ] .I believe this is an encoding issue ? I am using ; All this is inside a FileStream scope and uses fs.Write to write the encodedBytes into the file.I have tried to use... | // 1252 is a variable in the applicationEncoding codePage = Encoding.GetEncoding ( `` 1252 '' ) ; Byte [ ] bytes = new UTF8Encoding ( true ) .GetBytes ( `` Hello this \\n is a test message '' ) ; Byte [ ] encodedBytes = Encoding.Convert ( Encoding.UTF8 , codePage , bytes ) ; | C # '\n ' saved in different bytes than expected |
C# | Suppose I want to implement a functional composition , like this : Now in practice , I can use this Compose ( ) fn like this : And the result is FREDFRED . Is there a way to use a simpler syntax to invoke Compose ? I tried like this : ... but I get a compile error : error CS0411 : The type arguments for method 'Functio... | public Func < T , T > Compose < T > ( Func < T , T > f , Func < T , T > g ) { return new Func < T , T > ( x = > f ( g ( x ) ) ) ; } public String ToUpper ( String s ) { return s.ToUpper ( ) ; } public String Replicate ( String s ) { return s+s ; } public void Run ( ) { var h = Compose < String > ( ToUpper , Replicate )... | Inferring generic types with functional composition |
C# | How can I take advantage of the content negotiation pipeline when assigning to NancyContext.Response ? Currently my IStatusCodeHandler.Handle method returns JSON regardless of any content negotiation . I want this method to use JSON or XML according on any content negotiation ( preferably using the content negotiation ... | public void Handle ( HttpStatusCode statusCode , NancyContext context ) { var error = new { StatusCode = statusCode , Message = `` Not Found '' } ; context.Response = new JsonResponse ( error , new JsonNetSerializer ( ) ) .WithStatusCode ( statusCode ) ; } | Automatic Content Negotation When Assigning To Response |
C# | I am encountering what seems to be a very weird bug in ImmutableArray < > ( with BCL Immutable collections v1.0.12.0 , runtime .NET 4.5 ) : I have the following two identical structs exactly in the same source file under the same namespace : The following will throw an exception : If I project elements1 into ToArray ( ... | public struct WeightedComponent { public readonly IComponent Component ; public readonly decimal Weight ; public WeightedComponent ( IComponent component , decimal weight ) { this.Component = component ; this.Weight = weight ; } } public struct WeightedComponent2 { public readonly IComponent Component ; public readonly... | ImmutableArray < > behaves differently than Array < > for nested Select with index |
C# | Given a type , a name and a signature , how can I do a member lookup of the member with name name and signature signature using the C # rules of 7.4 ( the 7.4 is the chapter number from the C # Language Specification ) ( or at least part of them ... Let 's say I can live with an exact match , without conversions/casts ... | class C1 { public int Current { get ; set ; } public object MoveNext ( ) { return null ; } } class C2 : C1 { public new long Current { get ; set ; } public new bool MoveNext ( ) { return true ; } } class C3 : C2 { } var m = typeof ( C3 ) .GetMethods ( ) ; // I get both versions of MoveNext ( ) var p = typeof ( C3 ) .Ge... | Resolving a member name at runtime |
C# | Looking to the implementation of the method in the List < > class ( .NET Framework 4.5.2 ) , I can see an iteration over a collection like thisI am wondering what could be the reason to prefer that syntax over this oneI have created an assembly with two methods each one using a different approach . Then , looking into ... | void InsertRange ( int index , IEnumerable < T > collection ) using ( IEnumerator < T > en = collection.GetEnumerator ( ) ) { while ( en.MoveNext ( ) ) { Insert ( index++ , en.Current ) ; } } foreach ( var item in collection ) { Insert ( index++ , item ) } | Iterating an IEnumerable < T > . Best way ? |
C# | in all ( Agile ) articles i read about this : keep your code and functions small and easy to test.How should i do this with the 'controller ' or 'coordinator ' class ? In my situation , i have to import data . In the end i have one object who coordinates this , and i was wondering if there is a way of keeping the coord... | //Write to the log that the import has startedLog.StartImport ( ) //Get the data in Excel sheet formatresult = new Downloader ( ) .GetExcelFile ( ) //Log this stepLog.LogStep ( result ) //convert the data to intern objectsresult = new Converter ( ) .Convertdata ( result ) ; //Log this stepLog.LogStep ( result ) //write... | How to keep my functions ( objects/methods ) 'lean and mean ' |
C# | My motivation for chaining my class constructors here is so that I have a default constructor for mainstream use by my application and a second that allows me to inject a mock and a stub . It just seems a bit ugly 'new'-ing things in the `` : this ( ... ) '' call and counter-intuitive calling a parametrized constructor... | using SystemWrapper ; public class MyDirectoryWorker { // SystemWrapper interface allows for stub of sealed .Net class . private IDirectoryInfoWrap dirInf ; private FileSystemWatcher watcher ; public MyDirectoryWorker ( ) : this ( new DirectoryInfoWrap ( new DirectoryInfo ( MyDirPath ) ) , new FileSystemWatcher ( ) ) {... | Is this a good or bad way to use constructor chaining ? ( ... to allow for testing ) |
C# | I am trying to put a mocked Range ( which contains cells with values ) inside the rows of a new Range . But when I try to access a specific element from the Range , a exception is thrown.I 've tried everything , does anyone have a idea what I am doing wrong here ? Exception Message : Test method xxx.MockUtilsTest.MockR... | [ TestMethod ] public void MockRowsTest ( ) { var row1 = MockUtils.MockCells ( `` test_row_1 '' , `` test_row_1 '' ) ; var row2 = MockUtils.MockCells ( `` test_row_2 '' , `` test_row_2 '' ) ; var range = MockUtils.MockRows ( row1 , row2 ) ; Assert.IsNotNull ( range ) ; Assert.AreEqual ( 2 , range.Count ) ; Assert.IsNot... | How to mock rows in a Excel VSTO plugin ? |
C# | Is there a way to Define a default constructor for all classes in a given assembly . For example I have classes like this in an assembly -These classes all require a default constructor but I do n't want to have to riddle all of these classes with a default constructor so how do I do this using reflection or something ... | public class SomeClass { public SomeClass ( int x , int y ) { } } | Define Default Constructor for existing classes in assembly |
C# | Does anybody see any drawbacks ? It should be noted that you ca n't remove anonymous methods from an event delegate list , I 'm aware of that ( actually that was the conceptual motivation for this ) .The goal here is an alternative to : And the code : } | if ( onFoo ! = null ) onFoo.Invoke ( this , null ) ; public delegate void FooDelegate ( object sender , EventArgs e ) ; public class EventTest { public EventTest ( ) { onFoo += ( p , q ) = > { } ; } public FireFoo ( ) { onFoo.Invoke ( this , null ) ; } public event FooDelegate onFoo ; | C # Events and Lambdas , alternative to null check ? |
C# | I have two libraries written in C # that I 'd like to use in an F # application . Both libraries use the same type , however , I am unable to convince F # 's type checker of this fact.Here 's a simple example using the Office interop types . F # seems particularly sensitive to these type issues . Casting on the F # sid... | namespace Project1 { public class Class1 { public static Microsoft.Office.Interop.Excel.Application GetApp ( ) { return new Microsoft.Office.Interop.Excel.Application ( ) ; } } } namespace Project2 { public class Class2 { Microsoft.Office.Interop.Excel.Application _app ; public Class2 ( Microsoft.Office.Interop.Excel.A... | The type 'T ' is not compatible with the type 'T ' |
C# | I 'm using NuGetVersion from the NuGet.Versioning package in LinqPad . I 'm trying to Dump ( ) it to inspect it 's properties , but instead of the usual dump I just get the string representation.For example , this : Shows the following in the output window : Does anyone know why LinqPad runs ToString ( ) when some type... | var v = new NuGetVersion ( `` 1.0.0 '' ) ; v.Dump ( ) ; 1.0.0 | Why does LinqPad run ToString ( ) on some types when they are dumped ? |
C# | This question is particularly pointed at other C # devs coming over to TypeScript in VS Code.I fell in love with the code completion in VS C # . To illustrate , say I 'm trying to write : Using C # , I would have : type `` con '' a list of suggestions would appear , probably starting with `` console '' since that 's hi... | console.log ( 'hello ' ) | Can VS Code code completion be configured to accept a suggestion on punctuation ? |
C# | I am querying built-in TimeoutData entity in RavenDB using Raven.Client.Lightweight 2.5 library to get specific timeout document . It is possible that TimeoutData does not exist in the database because no document is stored there yet . In that case NotSupportedException is thrown when you try to query it.Currently I ha... | try { timeoutData = _session.Query < TimeoutData > ( ) .FirstOrDefault ( t = > t.Headers.ContainsValue ( someValue ) ) ; } catch ( NotSupportedException ) { return null ; } if ( ! _session.Query < TimeoutData > ( ) .Any ( ) ) { } | How to check if table ( entity ) exists in RavenDB |
C# | Can I unit test my multi-threaded code using CHESS & MSTest in VS 2010 . I tried this but I get the following error | [ TestMethod ] [ HostType ( `` Chess '' ) ] [ TestProperty ( `` ChessExpectedResult '' , `` deadlock '' ) ] public void TestMyMethod ( ) { ... } The host type 'Chess ' can not be loaded for the following reason : The key 'Chess ' can not be found | MSTest + CHESS in VS 2010 |
C# | As I understand it , each language can have it 's own dynamic handler , so that the appropriate rules are applied . I 'm unsure if the following is correct/incorrect ; thoughts ? Scenario : two interfaces ( one implements the other ) with some methods : and a basic implementation : Now , with normal C # ( no dynamic ) ... | public interface IA { void Bar ( object o ) ; } public interface IB : IA { void Foo ( object o ) ; } public class B : IB { public void Foo ( object o ) { Console.WriteLine ( `` Foo '' ) ; } public void Bar ( object o ) { Console.WriteLine ( `` Bar '' ) ; } } IB b = new B ( ) ; var o = new { y = `` z '' } ; b.Foo ( o.y ... | Should an interface-based method invoke that uses `` dynamic '' still obey C # method resolution rules ? |
C# | If I create a simple class like the following : and examine it within NDepend , it shows that the TestMethod taking a bool and being async Task has a struct generated for it with an enumerator , the enumerator state machine and some additional stuff.Why does the compiler generate a struct called TestClass+ < TestMethod... | public class TestClass { public Task TestMethod ( int someParameter ) { return Task.FromResult ( someParameter ) ; } public async Task TestMethod ( bool someParameter ) { await Task.FromResult ( someParameter ) ; } } | Why does the async keyword generate an enumerator & additional struct when compiled ? |
C# | Using the silverlight Windows Phone 8.1 ProjectI 'm trying to load data from a website . I have to authenticate at that site first however.So I do a post to the Website , using a lightly modified version of the CookieAwareWebClient from here.Now I make a WebClient send a POST with Username and Password and continue get... | class CookieAwareWebClient : WebClient { public CookieContainer Cookies = new CookieContainer ( ) ; protected override WebRequest GetWebRequest ( Uri address ) { var request = base.GetWebRequest ( address ) ; if ( request is HttpWebRequest ) ( request as HttpWebRequest ) .CookieContainer = Cookies ; return request ; } ... | How can I retrieve multiple websites asynchronously ? |
C# | I 'm using events as part of a game model , and for extensibility and code `` locality 's '' sake I need to be able to veto most actions.More clearly , nearly every method that has a side effect takes this form : What I 'd like is for TryingToDoSomething ( ... ) to be able to indicate that a registered event handler ob... | public event TryingToDoSomethingHandler TryingToDoSomething ; public event SomethingHappenedHandler SomethingHappened ; /* * Returning true indicates Something happened successfully . */public bool DoSomething ( ... ) { //Need a way to indicate `` veto '' here TryingToDoSomething ( ... ) ; //Actual do it SomethingHappe... | Is there a standard way to implement `` Vetoable '' events ? |
C# | A little background : I 'm a WPF to WinForms convertee and for some time I 've been migrating my application.I was reported by a friend that my code does n't work on Windows XP ( it generates a stack overflow at startup ) even though it works fine on Windows 7 ( which I develop in ) .After a little research , what caus... | private void listView1_SelectedIndexChanged ( object sender , EventArgs e ) { listView1.SelectedIndices.Clear ( ) ; listView1.Items [ 0 ] .Selected = true ; } | Why does this code work on Windows 7 , but does n't on Windows XP ? |
C# | Imagine someone coding the following : We all know that in the example above , the call to the “ ToUpper ( ) ” method is meaningless because the returned string is not handled at all . But yet , many people make that mistake and spend time trying to troubleshoot what the problem is by asking themselves “ Why aren ’ t t... | string s = `` SomeString '' ; s.ToUpper ( ) ; [ MustHandleReturnValueAttribute ] public string ToUpper ( ) { … } string s = `` SomeString '' ; string uppers = s.ToUpper ( ) ; | C # Compiler Enhancement Suggestion |
C# | When I write a value into a field , what guarantees do I get regarding when the new value will be saved in the main memory ? For example , how do I know that the processor do n't keep the new value in it 's private cache , but updated the main memory ? Another example : Is there a possibility that after Write ( ) was f... | int m_foo ; void Read ( ) // executed by thread X ( on processor # 0 ) { Console.Write ( m_foo ) ; } void Write ( ) // executed by thread Y ( on processor # 1 ) { m_foo = 1 ; } | When do writes/reads affect main memory ? |
C# | I have to rotate JPG images lossless in .net ( 90°|180°|270° ) . The following articles show how to do it : https : //docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.encoder.transformation ? view=netframework-4.7.2https : //www.codeproject.com/tips/64116/Using-GDIplus-code-in-a-WPF-application-for-lossle.asp... | Image image ; using ( var ms = new MemoryStream ( originalImageData ) ) { image = System.Drawing.Image.FromStream ( ms ) ; } // If I do n't copy the image into a new bitmap , every try to save the image fails with a general GDI+ exception . This seems to be another bug of GDI+.var bmp = new Bitmap ( image ) ; // Creati... | Lossless rotation of a JPG image with Image.Save and EncoderParameters fails |
C# | I have a program on .NET 4 for Windows . I 'm trying to port it for Mac computers with mono and Xamarin studio.I have third-part library EmguCV ( it 's a wrapper for OpenCV library ) . I 'm using official manual to install it . It installs both OpenCV and EmguCV to Library/Python/2.7/site-packages/emgucv/libWhen I star... | macpack -m:1 -o : . -r : /Library/Frameworks/Mono.framework/Versions/Current/lib/ -r : /Library/Python/2.7/site-packages/emgucv/lib -r : /Library/Python/2.7/site-packages/emgucv/bin -r : Assimp32.dll -r : Assimp64.dll -r : cvextern.dll -r : Emgu.CV.dll -r : Emgu.Util.dll -r : libegl.dll -r : libglesv2.dll -r : OpenTK.d... | How to attach third-part libraries in release version |
C# | I ca n't get this to work for font names that are 16 characters or longer , but the console itself obviously does n't have this limitation . Does anyone know a programmatic way to set the font that will work with the built-in `` Lucida Sans Typewriter '' or the open source `` Fira Code Retina '' ? This following code w... | using System ; using System.Runtime.InteropServices ; public static class ConsoleHelper { private const int FixedWidthTrueType = 54 ; private const int StandardOutputHandle = -11 ; [ DllImport ( `` kernel32.dll '' , SetLastError = true ) ] internal static extern IntPtr GetStdHandle ( int nStdHandle ) ; [ return : Marsh... | SetCurrentConsoleFontEx is n't working for long font names |
C# | I have a case where I have the name of an object , and a bunch of file names . I need to match the correct file name with the object . The file name can contain numbers and words , separated by either hyphen ( - ) or underscore ( _ ) . I have no control of either file name or object name . For example : The object name... | 10-11-12_001_002_003_13001_13002_this_is_an_example.svg 10001 1000110002100031100111002110031200112002120031300113002 13003 public bool IsMatch ( string filename , string objectname ) { var namesegments = GetNameSegments ( filename ) ; var match = namesegments.Contains ( objectname ) ; return match ; } public static Li... | How to combine items in List < string > to make new items efficiently |
C# | With a setup like this , I can show a singular list containing books , authors , and bookmarks . I can drill down into a book , and see that specific books authors and bookmarks.Problem # 1 : I 'd like to drill down into an author , and see all of the authors books . On top of that , I 'd like to see all the bookmarks ... | public class Base : ICustomItem { } public class Book : Base { public List < Author > Authors ; public List < Bookmark > Bookmarks ; } public class Author : Base { } public class Bookmark : Base { } public ObservableCollection ( ICustomItem ) MyItems ; public ListCollectionView MyItemsView { get ; } = new ListCollectio... | Architecting a collection of related items of different types |
C# | I have an Item that contains a list of Product 's which are mapped to their respective ViewModel objects using AutoMapper.In my MVC project I have an Action method that displays an Item with a selected Product . For this i have a ViewModel called ItemDetailsViewModel that contains the flattened Item object , a list of ... | Mapper.CreateMap < Item , ItemViewModel > ( ) .ReverseMap ( ) ; Mapper.CreateMap < ProductViewModel , ItemDetailsViewModel > ( ) .ForMember ( d = > d.ProductId , o = > o.MapFrom ( s = > s.Id ) ) .ForMember ( d = > d.ProductCode , o = > o.MapFrom ( s = > s.Code ) ) ; public class Item { public int Id { get ; set ; } pub... | How to flatten a conditional object in a list in automapper |
C# | There are multiple related questions , but I 'm looking for a solution specific to my case . There is an array of ( usually ) 14 integers , each in the range of 1 to 34 . How can I quickly tell if each int in a specific , static list appears at least once in this array ? For reference , I 'm currently using this code ,... | if ( array.Count < 13 ) { return ; } var required = new int [ ] { 0*9 + 1 , 0*9 + 9 , 1*9 + 1 , 1*9 + 9 , 2*9 + 1 , 2*9 + 9 , 3*9 + 1 , 3*9 + 2 , 3*9 + 3 , 3*9 + 4 , 3*9 + 5 , 3*9 + 6 , 3*9 + 7 , } ; IsThirteenOrphans = ! required.Except ( array ) .Any ( ) ; | How can I quickly tell if a list contains a list ? |
C# | First of all , I want to say that I 'm new to C # , so this question may seem completely off track.I have a set of enumerables called ShapeType : And a method to return a random value from the enumerables : Every enumerable has a corresponding concrete class . And the question I 'm wondering about is if you can instant... | Cube , Sphere , Rectangle , Ellipse private static ShapeType GetRandomShape ( ) { Array values = Enum.GetValues ( typeof ( ShapeType ) ) ; Random random = new Random ( ) ; ShapeType randomShape = ( ShapeType ) values.GetValue ( random.Next ( values.Length ) ) ; return randomShape ; } private static Shape GetRandomShape... | Use variable as type and instantiate it |
C# | I have an application which takes a string value of the form % programfiles % \directory\tool.exe from its application config file.I want to make this into a useable filename so that I can call and have it execute the application . I 'm curently getting a System.ComponentModel.Win32Exception - The system can not find t... | System.Diagnostics.Process.Start ( filename ) | How do I convert a string of the form % programfiles % \directory\tool.exe to a useable Filename in C # /.net ? |
C# | I 'm trying to create a class that takes a lambda and stores it internally . The syntax would be something like : Usage : But I 'm having some trouble figuring out the details . I know that a lambda is an anon type until it 's assigned to either an expression or a delegate and that I would ( I believe ) have to use an ... | class Lambda < TIn , TOut > { private Expression < Func < TIn , TOut > > expr ; private Func < TIn , TOut > > func ; public Lambda ( Expression < Func < TIn , TOut > > e ) { expr = e ; } public Lambda ( Func < TIn , TOut > f ) { func = f ; } public static implicit operator Lambda < TIn , TOut > ( [ lambdatype ] o ) { r... | Implicit Operators and lambdas |
C# | I 'm trying to write a VBA parser ; in order to create a ConstantNode , I need to be able to match all possible variations of a Const declaration.These work beautifully : Const foo = 123Const foo $ = `` 123 '' Const foo As String = `` 123 '' Private Const foo = 123Public Const foo As Integer = 123Global Const foo % = 1... | Const foo = 123 'this comment is included as part of the value Const foo = 123 , bar = 456 /// < summary > /// Gets a regular expression pattern for matching a constant declaration . /// < /summary > /// < remarks > /// Constants declared in class modules may only be < c > Private < /c > . /// Constants declared at pro... | Parsing VBA Const declarations ... with regex |
C# | I am working on an application in which have different repositories for different entities and now i have to put search logic , hence i am confused where should i put my search logic , should i create a new repository for search or should i put the logic in the existing repository , and if i should put in some existing... | public class VendorRepository { } public class ProductRepository { } Public Class ProductBatchRepository { } | Best Practices | Where to put search logic if we have different repository for each entity |
C# | I was working with some C # code today in the morning and I had something like : So , as I dont have a full understanding of the language framework I would like to know if GetDataTable ( ) gets called each time an iteration is done or if it just gets called once and the resulting data ( which would be Rows ) is saved i... | foreach ( DataRow row in MyMethod.GetDataTable ( ) .Rows ) { //do something } DataRowCollection rowCollection = MyMethod.GetDataTable ( ) .Rows ; foreach ( DataRow row in rowCollection ) { //do something } | Does a method that returns a collection get called in every iteration in a foreach statement in C # ? |
C# | I have some code that is meant to get files in a directory , which is simple enoughThe files are named as follows : My issue is that it is not picking up the last file.I have fixed the code by putting this instead : Saying get any files that contains both Totals and .csv , with anything after the .csv.What I do n't get... | foreach ( var Totalfile in new DirectoryInfo ( rootfolder ) .GetFiles ( `` *Totals*.csv '' , SearchOption.TopDirectoryOnly ) ) Totals.CSV142344Totals.CSV142409Totals.CSV142433Totals.CSV142501Totals.CSV142528 foreach ( var Totalfile in new DirectoryInfo ( rootfolder ) .GetFiles ( `` *Totals*.csv* '' , SearchOption.TopDi... | Directory.GetFiles does n't pick up all files |
C# | allI have searched this question , and I found so many answers to it was not difficult to find a solution for my question.BUT , I have strange experience and I do n't know the reason that 's why I ask people to give me some advice.Here are my codes : Yes , they are ordinary thread codes.I expect all the thread array sh... | void SetThread ( ) { for ( int i = 0 ; i < _intArrayLength ; i++ ) { Console.Write ( string.Format ( `` SetThread- > i : { 0 } \r\n '' , i ) ) ; _th [ i ] = new Thread ( new ThreadStart ( ( ) = > RunThread ( i ) ) ) ; _th [ i ] .Start ( ) ; } } void RunThread ( int num ) { Console.Write ( string.Format ( `` RunThread- ... | How to pass arguments to thread in C # |
C# | I have a data object with three fields , A , B and C. The problem is that the user can set any of them because : A * B = CSo if a user starts off by setting A & B , C will be calculated . but then if a user set C , A gets recalculated , so there is an implicit anchoring that is happening based off the last field that t... | public class Object { private double _A ; private double _B ; private double _C ; private bool _enteredA ; private bool _enteredB ; private bool _enteredC ; public double A { get { if ( _enteredC ) { return _C / _B ; } else { return _A ; } } } | 3 way calculation |
C# | I 'm thinking of something along the lines of the `` Inline Task '' in MsBuild . For reference : http : //msdn.microsoft.com/en-us/library/dd722601.aspxI 'd like to find or create a framework which allows me to override a method via configuration . For example if I have a well known base class which has a method Execut... | public static Collection < PSObject > ExecuteScript ( string code , string variableName , object variableValue ) { PowerShell ps = PowerShell.Create ( ) ; ps.AddScript ( code ) ; if ( ! string.IsNullOrWhiteSpace ( variableName ) ) { ps.Runspace.SessionStateProxy.SetVariable ( variableName , variableValue ) ; } var resu... | How best to create and execute a method in a .NET ( C # ) class dynamically through configuration |
C# | Can somebody explain why the .Net framework team decided that a delegate without subscribers should be null instead of an object with an empty InvocationList ? I 'd like to know the rationale that led to this decision.Thanks | void DoSomething ( ) { EventHandler handler = SomeEvent ; if ( handler ! = null ) //why is this null-check necessary ? { handler ( this , EventArgs.Empty ) ; } } | Why are delegates null rather than an empty list when there is no subscriber ? |
C# | Consider this function , which you can think of as a truth table : The compiler insists on that last else clause . But from a truth table 's perspective , that is an impossible state.Yes , it works , and yes , I can live with it . But I 'm wondering if there is some mechanism in c # to avoid this sort of code , or if I... | public Foo doSomething ( bool a , bool b ) { if ( a & & b ) return doAB ( ) ; else if ( a & & ! b ) return doA ( ) ; else if ( ! a & & b ) return doB ( ) ; else if ( ! a & & ! b ) return doNotANotB ( ) ; else throw new Exception ( `` Well done , you defeated boolean logic ! `` ) ; } | How can I avoid an impossible boolean state in c # ? |
C# | I 'm trying to determine how AsParallel ( ) splits it 's 'source ' , and indeed what is meant by 'source ' ... For example ... Then put 500k varying CSVItem 's into CSVItemList.Then use : Will it only split the 'source ' ( meaning for example 250k records onto each of two threads ) onto multiple asynch threads and perf... | public class CSVItem { public DateTime Date { get ; set ; } public string AccountNumber { get ; set ; } } List < CSVItem > CSVItemList = new List < CSVItem > ( ) ; CSVItemList = CSVItemList.AsParallel ( ) .OrderBy ( x = > x.AccountNumber ) .ThenBy ( q = > q.Date ) .ToList ( ) ; | How does AsParallel ( ) split it 's 'source ' ? |
C# | Modern unit tests frameworks support awaiting the results of an asychronous unit test , like this : Is there any advantage of using this async approach over simply blocking ? Does the async only provide a benefit when running tests in parallel ? | public async Task SomeTest ( ) { var result = await SomeMethodAsync ( ) ; // ... Verify the result ... } public void SomeTest ( ) { var result = SomeMethodAsync ( ) .Result ; // ... Verify the result ... } | Advantage of async/await over blocking in unit tests |
C# | The following two C # functions differ only in swapping the left/right order of arguments to the equals operator , == . ( The type of IsInitialized is bool ) . Using C # 7.1 and .NET 4.7.But the IL code for the second one seems much more complex . For example , B is:36 bytes longer ( IL code ) ; calls additional functi... | static void A ( ISupportInitialize x ) { if ( ( x as ISupportInitializeNotification ) ? .IsInitialized == true ) throw null ; } static void B ( ISupportInitialize x ) { if ( true == ( x as ISupportInitializeNotification ) ? .IsInitialized ) throw null ; } [ 0 ] bool flag nop ldarg.0 isinst [ System ] ISupportInitialize... | Argument order for '== ' with Nullable < T > |
C# | I must be doing something dumb : So why when i = 7 is ans coming out at 2.0 ? i is an int | float ans = ( i/3 ) ; | Simple division |
C# | Consider the following ( VS 16.8.0 Preview 2.1 C # 9.0 preview ) code : I am having a hard time understanding/addressing the errors in F3 , Seems like the compiler thinks johnAge there is long not long ? ( as I verified by hovering over it in VS ) despite the return of Archive < T > .GetAt being T ? Is there a way to h... | # nullable enableusing System.Collections.Generic ; class Archive < T > where T : notnull { readonly Dictionary < string , T > Dict = new ( ) ; public T ? GetAt ( string key ) { return Dict.TryGetValue ( key , out var value ) ? value : default ; } } class Manager { public int Age { get ; set ; } } class Main34 { long F... | C # 9 Nullable types issues |
C# | I was under the impression that in .NET casting ( not converting ) is very cheap and fast . However , this does not seem to be the case for array . I 'm trying to do a very simple cast here , take a T1 [ ] and cast as T2 [ ] . where T1 : T2.There are 3 ways to do this and I 'm calling them the following : :And I create... | DropCasting : T2 [ ] array2 = array ; CastClass : ( T2 [ ] ) array ; IsInst : array as T2 [ ] ; DropCast : 223msIsInst : 3648msCastClass : 3732ms DropCast : 386msIsInst : 611msCastClass : 519ms class Program { static readonly String [ ] strings = Enumerable.Range ( 0 , 10 ) .Select ( x = > x.ToString ( ) ) .ToArray ( )... | Why is casting arrays ( vectors ) so slow ? |
C# | I have a Silverlight 5 application trying establish a socket connection to a server as follows : I have the following clientaccesspolicy.xml file at https : //subdomain.maindomain.com/clientaccesspolicy.xml : I am able to run a local instance of the Silverlight application from visual studio and can establish the socke... | var targetEndpoint = new DnsEndPoint ( `` subdomain.maindomain.com '' , 443 ) ; var clientSocket = new Socket ( AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp ) ; var socketAsyncEventArgs = new SocketAsyncEventArgs { RemoteEndPoint = targetEndpoint } ; socketAsyncEventArgs.Completed += AsyncConnectCa... | Silverlight 5 Opening Socket AccessDenied |
C# | We have implemented a localized version of an ASP.NET MVC website which has a URL structure as following : url : // { language } - { culture } / { controller } / { action } / { id } In this way we can generate URLs by language which are properly crawled by Google bot : http : //localhost/en-US/Homehttp : //localhost/fr... | routes.MapRoute ( name : `` Default '' , url : `` { language } - { culture } / { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional , language = `` en '' , culture = `` US '' } ) ; public class LocalizationAttribute : ActionFilterAttribut... | Pre-Append Route if not available |
C# | I have been looking for a way of splitting a foreach loop into multiple parts and came across the following code : Would items.Skip ( currentPage * itemsPerPage ) .Take ( itemsPerPage ) be processed in every iteration , or would it be processed once , and have a temporary result used with the foreach loop automatically... | foreach ( var item in items.Skip ( currentPage * itemsPerPage ) .Take ( itemsPerPage ) ) { //Do stuff } | Linq optimisation within a foreach |
C# | I noticed something strange when trying to pass a StringBuilder 's Append method to a function that took an Action < string > .For testing purposes , I just want to write the data into a StringBuilder , so I tried to call it like this : However , this gives a compile error , because the Append method does not match the... | public void DoStuff ( Action < string > handler ) { // Do stuff , call handler ( `` data '' ) ; } var output = new StringBuilder ( ) ; DoStuff ( output.Append ) ; var output = new StringBuilder ( ) ; DoStuff ( s = > output.Append ( s ) ) ; | Why can ` s = > x.Append ( s ) ` can be passed as an Action < string > but ` x.Append ` ca n't ? |
C# | To keep my code cleaner I often try to break down parts of my data access code in LINQ to SQL into private sub-methods , just like with plain-old business logic code . Let me give a very simplistic example : I 'm sure no one 's imagination would be stretched by imagining more complex examples with deeper nesting or usi... | public IEnumerable < Item > GetItemsFromRepository ( ) { var setA = from a in this.dataContext.TableA where /* criteria */ select a.Prop ; return DoSubquery ( setA ) ; } private IEnumerable < Item > DoSubQuery ( IEnumerable < DateTimeOffset > set ) { return from item in set where /* criteria */ select item ; } | Rules for LINQ to SQL across method boundaries |
C# | Today I faced a problem and I 'm not able to get weather I understand something wrong about ASP.NET MVC ( and possibly MVC in general ) or I miss something about it 's implementation.So , I have a simple model hierarchy : Here is my HomeController 's Edit actions : Hese is my Edit.aspx view : The point is that in Edit ... | public class Child { public Child ( int notId , bool isSelected , string text ) { NotId = notId ; IsSelected = isSelected ; Text = text ; } public Child ( ) { } // naming : just to make sure I do not mess with some // conventional infrastructure public int NotId { get ; set ; } public bool IsSelected { get ; set ; } pu... | ASP.NET MVC rendering model not the way I expect |
C# | I am trying to get better with IoC , DI and OOD for better testability and looser coupling.So when we design classes with heavy use of IoC and DI we can endup with classes with multiple dependencies for exampleIm thinking what should be the usual approach here . We can leave constructor with 3 parameters , but if we ar... | class Processor { private IService1 m_Service1 ; private IService2 m_Service2 ; private IService3 m_Service3 ; //approach 1 public Processor ( IService1 service1 , IService2 service2 , IService3 service3 ) { m_Service1 = service1 ; m_Service2 = service2 ; m_Service3 = service3 ; } //approach 2 public Processor ( IConta... | OOD using IoC containers - how to construct dependant objects ? |
C# | I need to connect my NET Framework 4 Client App , to a Webservice , deployed on a Apache CXF , with WS Security . That service is out of my control.The service is added to the project as a `` Service Reference '' .This is the proxy : Well . The server accepts my Request , and send the the response , in this way : I get... | ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback ( AddressOf AcceptAllCertifications ) Dim oBinding As New CustomBinding ( ) Dim oSecurity As SecurityBindingElementoSecurity = AsymmetricSecurityBindingElement.CreateCertificateOverTransportBindingEleme... | Apache CXF WS Security WebService from NET Client - Can not resolve KeyInfo for unwrapping key |
C# | I have a main application that loads up some plugins . These plugins are loaded and run in separate app domains using a class that inherits from `` MarshalByRefObject '' ; This all works fine.What I need now is a way to handle when the plugin wants the main app to do something and a way to dynamically handle this in th... | CallbackClass myCallbackClass = new CallbackClass ( ) ; pluginInterface.HeresMyCallbackClass ( ( ICallbackClass ) myCallbackClass ) ; myCallbackClass.MyMainAppEvent += new MainEventHandler ( MyMainAppFunction ) ; //code within pluginICallbackClass callToMainApp ; public HeresMyCallbackClass ( ICallbackClass cbClass ) {... | What ways can I send data from a plugin across an app domain that triggers an event in the main application in C # ? |
C# | I found this other stack overflow question about files and directories , and the answer included this statement : His question was about .net , and I was coding in C # .net in Visual Studio . Is the ability to have both an assignment operator and an equals operator in the same statement work for all .net languages or i... | bool isDir = ( File.GetAttributes ( path ) & FileAttributes.Directory ) == FileAttributes.Directory ; | How can a statement have both = and == ? |
C# | Quick question . I have a listbox being populated from a directory listing . Each file contains its name and ~ # # # # # . I 'm trying to read it all into a string and replace the ~ # # # # with nothing . The # # # # could be digits from length 1-6 and could be anything from 0-9 . Here 's the code I 'm using : Example ... | string listItem = ( listBox1.SelectedItem.ToString ( ) .Replace ( `` ~* '' , '' '' ) ) ; Here223~123 -- - > HereHere224~2321 -- -- > Here | C # string replacement question |
C# | I am using this iOS SegmentedControlRenderer on a page . But when I go to the page this way : Navigation.PushAsync ( new CFSPage ( ) ) and then click on the back arrow to go to the previous page , the OnElementChanged event in my customer iOS renderer is fired . The result with my renderer is that the following line gi... | segmentedControl.TintColor = e.NewElement ? .TintColor.ToUIColor ( ) ; SetNativeControl ( segmentedControl ) ; SetSelectedSegment ( ) ; protected override void Dispose ( bool disposing ) public class SegmentedControlRenderer : ViewRenderer < SegmentedControl , UISegmentedControl > { protected override void OnElementCha... | Does a controls OnElementChanged ( ) get called when I leave a page ? |
C# | I 'm trying to open a thumbscache.db file , I 've tried to open it like any other database but no use . I 've also looked for any API or support in C # . Kindly suggest if there is another way.BTW below is my approach so far.1 . Open it like any other db.But this exception comes up.2 . Open it using ShellFileAnd instea... | path = Environment.GetFolderPath ( Environment.SpecialFolder.LocalApplicationData ) ; path += @ '' \Microsoft\Windows\Explorer\thumbcache_1280.db '' ; datasource = `` Data source = `` + path ; SQLiteCommand cmd = new SQLiteCommand ( ) ; SQLiteConnection conn = new SQLiteConnection ( datasource ) ; cmd.Connection = conn... | How to open Thumbscache.db |
C# | Every time we need a high decimal-precision , we use decimals to do the calculations . Is there any way to check if the precision did suffice for the calculation ? I would like to make the following code throw an exception : It does n't really matter in real code , but it would be nice to be safe . | decimal almostMax = Decimal.MaxValue - 1 ; decimal x = almostMax + 0.1m ; // This should create an exception , since x equals almostMax.Assert.AreEqual ( x , almostMax ) ; // This does NOT fail . | How to get an exception on inaccurate calculation ? |
C# | I 've created a simple .NET Framework 4.7.2 WPF app with two controls - a text box and a button . Here is my code behind : After pressing StartTest button I see the following results in the Output text box : My question is why [ 7 ] Task delay has been cancelled . is executed in the same thread where token cancellation... | private async void StartTest_Click ( object sender , RoutedEventArgs e ) { Output.Clear ( ) ; var cancellationTokenSource = new CancellationTokenSource ( ) ; // Fire and forget Task.Run ( async ( ) = > { try { await Task.Delay ( TimeSpan.FromMinutes ( 1 ) , cancellationTokenSource.Token ) ; } catch ( OperationCanceledE... | Unexpected task cancellation behaviour |
C# | I have these two statements : What I would like to do is to check if changes ( ) = 0 in the first statement before running the second statement . Can anyone tell me how I can group together these two statements in to one so I can check the value of changes ( ) ? | db2.Execute ( `` UPDATE CLICKHISTORY SET `` + `` DAYOFYEAR = `` + dayOfYear + `` , `` + `` YEAR = `` + year + `` , `` + `` MONTH = `` + month + `` , `` + `` DAY = `` + day + `` , `` + `` BTNACOUNT = BTNACOUNT + 1 WHERE YYMMDD = `` + yymmdd ) ; db2.Execute ( `` INSERT INTO CLICKHISTORY `` + `` ( YYMMDD , DAYOFYEAR , YEA... | How to combine two SQLite statements running in C # ? |
C# | We 've been using EF 4.0 with a database-first approach using an .edmx model.We 're now upgrading to EF 6.1.3 , and we 're investigating whether to go with or without that .edmx model . We definitely still want to be in control of our database schema - so we 'll be creating new tables etc . with SQL script and then gen... | CREATE TABLE dbo.Contact ( ContactID INT NOT NULL CONSTRAINT PK_Contact PRIMARY KEY CLUSTERED , Name VARCHAR ( 200 ) , Address VARCHAR ( 200 ) , ZipCode VARCHAR ( 20 ) , City VARCHAR ( 100 ) , Phone VARCHAR ( 100 ) ) CREATE TABLE dbo.Customer ( CustomerID INT NOT NULL CONSTRAINT PK_Customer PRIMARY KEY CLUSTERED , Name... | Influencing how entity classes are created in EF 6 code-first from database |
C# | I 'm working on upgrading my .NET Core 2.2 MVC application to 3.0 . In this application I 'm authenticating to a controller using a JWT token . The token contains several claims , but when I try to access them through User.Claims the resulting list is always empty.In my Startup.cs I have the authentication setup like s... | public class Startup { public void ConfigureServices ( IServiceCollection services ) { // Code removed for clarity // services.AddAuthentication ( JwtBearerDefaults.AuthenticationScheme ) .AddJwtBearer ( options = > { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true , ValidateAu... | User.Claims Is Empty In MVC Application |
C# | I can calculate cluster membership with KMeans pretty easily : Can I calculate partial membership with the standard KMeans algorithm ? A coworker suggested using the mean and variances of the cluster members to determine proportional membership and today I 've been looking into fuzzy sets and their implementations for ... | open Systemopen System.IOopen Utilsopen Accordopen Accord.Math open Accord.MachineLearninglet vals = [ | [ |1.0 ; 2.0 ; 3.0 ; 2.0| ] [ |1.1 ; 1.9 ; 3.1 ; 4.0| ] [ |2.0 ; 3.0 ; 4.0 ; 4.0| ] [ |3.0 ; 3.1 ; 2.0 ; 3.0| ] [ |2.0 ; 4.0 ; 3.0 ; 6.0| ] [ |1.0 ; 5.0 ; 5.0 ; 7.0| ] [ |4.0 ; 3.0 ; 6.0 ; 8.0| ] [ |5.0 ; 4.0 ; 3.0 ... | Find partial membership with KMeans clustering algorithm |
C# | Let 's say I have a class that will be called from multiple threads , and am going to store some data in an ImmutableDictionary in a private field in this classCould this be called in such a way by multiple threads that you will get an error about the key already existing in the dictionary ? Thread1 checks dictionary s... | public class Something { private ImmutableDictionary < string , string > _dict ; public Something ( ) { _dict = ImmutableDictionary < string , string > .Empty ; } public void Add ( string key , string value ) { if ( ! _dict.ContainsKey ( key ) ) { _dict = _dict.Add ( key , value ) ; } } } | Using Bcl ImmutableDictionary in private field |
C# | I believe ( correct me if i am wrong ) , according to the C # rule for value types , there is no default constructor . The CLR will define the one for zeroing out the field values.For reference type : Will the default constructor be supplied by C # or the CLR ? | class Test { private string Name ; } | Does the C # Compiler supply a default constructor for reference types ( if one not specified ) or does the CLR ? |
C# | My class with an event : Derived event class : Some other class that register it to the event : What have I gained from following the .Net convention ? It would make more sense to have a contract like thisDoing it this way , I do n't need to create a new class and is easier to understand.I am not coding a .Net library ... | public class WindowModel { public delegate void WindowChangedHandler ( object source , WindowTypeEventArgs e ) ; public event WindowChangedHandler WindowChanged ; public void GotoWindow ( WindowType windowType ) { this.currentWindow = windowType ; this.WindowChanged.Invoke ( this , new WindowTypeEventArgs ( windowType ... | Events convention - I do n't get it |
C# | I am pretty sure this was asked before but unfortunately the only thing I 've found was this that was not solution for me . In my current project I do something like : This code does not work of course because I 've not cast obj because its type changes dynamically.How can I cast it dynamically ? | private object obj ; private void Initialize ( ) { obj.Initialize ( ) ; } private void CreateInstanceA ( ) { obj = Activator.CreateInstance ( typeof ( MyClassA ) ) ; } private void CreateInstanceB ( ) { obj = Activator.CreateInstance ( typeof ( MyClassB ) ) ; } | How can I cast object dynamically ? |
C# | Using xUnit 's Assert.Throws , I stumbled upon this ( to me ) hard to explain overload resolution issue . In xUnit , this method is marked obsolete : The question is , why does an inline statement lambda ( or expression ) that simply throws an exception resolve to this overload ( and therefore does n't compile ) ? | [ Obsolete ( `` You must call Assert.ThrowsAsync < T > ( and await the result ) `` + `` when testing async code . `` , true ) ] public static T Throws < T > ( Func < Task > testCode ) where T : Exception { throw new NotImplementedException ( ) ; } using System ; using Xunit ; class Program { static void Main ( string [... | Why does this Assert.Throws call resolve this way ? |
C# | We have this code which serves a download : It works fine , except that the log download code runs as soon as the download starts seemingly , not when the download has fully completed as we expect.Can someone explain why this is , and how to change it so it only logs when it 's completed ? We do n't want to count parti... | public class downloadRelease : IHttpHandler { public void ProcessRequest ( HttpContext context ) { -- snip -- context.Response.Clear ( ) ; context.Response.ContentType = `` application/octet-stream '' ; context.Response.AddHeader ( `` Content-Disposition '' , `` attachment ; filename= '' + OriginalFileName ) ; context.... | Only count a download once it 's served |
C# | What is the best way in C # to get a collection of objects representing the changes between two XML texts , e.g . : First : Second : Changes : The point is to then pass the changes as a collection of objects onto a GUI which can appropriately display them.What is the best way to go about this , i.e . structure the clas... | < Customer > < Id > 1 < /Id > < FirstName > Angie < /FirstName > < LastName > Jones < /LastName > < ZipCode > 23434 < /ZipCode > < Contracts > < Contract > < Id > 234 < /Id > < Title > Test Contract 1 < /Title > < /Contract > < /Contracts > < /Customer > < Customer > < Id > 1 < /Id > < FirstName > Angie < /FirstName > ... | How to get a collection of objects representing the diff between two XML texts ? |
C# | What would be the way to call some method by name , like `` Method1 '' , if I 've got an Object and it 's Type ? I want to do something like this : Is this somehow possible ? I do realize that this would be slow , it 's inconvenient , but unfortunately I 've got no other ways to implement this in my case . | Object o ; Type t ; // At this point I know , that ' o ' actually has// 't ' as it 's type.// And I know that 't ' definitely has a public method 'Method1'.// So , I want to do something like : Reflection.CallMethodByName ( o , `` Method1 '' ) ; | How do you call a method by its `` name '' ? |
C# | I want to write a rule that will fail if an object allocation is made within any method called by a method marked with a particular attribute.I 've got this working so far , by iterating up all methods calling my method to check using CallGraph.CallersFor ( ) , to see if any of those parent methods have the attribute.T... | -- -- -In Assembly Apublic class ClassA { public MethodA ( ) { MethodB ( ) ; } public MethodB ( ) { object o = new object ( ) ; // Allocation i want to break the rule // Currently my rule walks up the call tree , // checking for a calling method with the NoAllocationsAllowed attribute . // Problem is , because of the d... | Determining if a method calls a method in another assembly containing a new statement and vice-versa |
C# | I 'm trying to build a code sample to show the optimization of code by the compiler when multiplying with a power of 2 number . Yet when I turn Optimize code on the IL remains mainly the same . Any ideas what I 'm doing wrong here ? The code : Non Optimized IL : Optimized IL : I thought the compiler would optimize the ... | int nr ; int result ; var stopwatch = new Stopwatch ( ) ; nr = 5 ; stopwatch.Start ( ) ; result = nr * 4 ; stopwatch.Stop ( ) ; Console.WriteLine ( result ) ; Console.WriteLine ( stopwatch.Elapsed.ToString ( ) + `` ms ellapsed '' ) ; stopwatch.Reset ( ) ; stopwatch.Start ( ) ; result = nr < < 2 ; stopwatch.Stop ( ) ; C... | When does the compiler optimize my code |
C# | Areo Glass Effect and windowStyle set to none and AllowTransparency causes widow resize to not function properlyAfter adding the Areo Glass theme to my window and setting WindowState to None the window does not resize properly . I can go as large as I want but when resizing down smaller the glass effect stays the same ... | < Window x : Class= '' WpfApplication2.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' AllowsTransparency= '' True '' WindowStyle= '' None '' ResizeMode= '' C... | Areo Glass Effect and windowStyle set to none causes window resize to not function properly |
C# | C # 6.0 in a Nutshell by Joseph Albahari and Ben Albahari ( O ’ Reilly ) . Copyright 2016 Joseph Albahari and Ben Albahari , 978-1-491-92706-9.states the following at page 96 , after introducing Implicit Calling of Parameterless Base-Class Constructor : If the base class has no accessible parameterless constructor , su... | public class X { public int Num { get ; set ; } public void Method_1 ( ) { Console.WriteLine ( `` X '' ) ; } public virtual void Method_2 ( ) { Console.WriteLine ( Num ) ; } } public class Y : X { public Y ( ) { Num = 1000 ; } } private static void Main ( string [ ] args ) { new Y ( ) .Method_2 ( ) ; } | When are derived classes constructors forced to use base keyword ? |
C# | I 'm writing a program that is container for other , smaller programs . It loads it 's modules via Assembly.Load , finds types implementing IModule and makes instances of them.In WPF MainWindow I have a RoutedViewHost , which will display everything.In my AppBoostrapper , I have the following : Then , in my sample modu... | private ReactiveList < IModule > LoadModules ( IMutableDependencyResolver resolver ) { var modules = ModuleLoader.Load ( ModulesDirectory ) ; // var modules = new IModule [ ] { new SampleModuleClass ( ) , } ; // this works perftectly ! foreach ( var module in modules ) { try { module.RegisterDependencies ( this , resol... | `` Could n't find an IPlatformOperations . This should never happen , your dependency resolver is broken '' on WPF |
C# | For example I have the following flag enum : According to MS Guidelines : DO name flag enums with plural nouns or noun phrases and simple enums with singular nouns or noun phrases.So I 've used plural form here . Now , there is another guideline to name your collections in plural form : DO name collection properties wi... | [ Flags ] public enum Colors { Red = 1 , Green = 2 , Blue = 4 } public class Foo { public IEnumerable < Colors > Colors { get ; set ; } } [ Flags ] public enum Operations { TextFormatting = 1 , SpellChecking = 2 , Translation = 4 } public class TextProcessingParameters { public IEnumerable < Operations > Operations { g... | How to name a collection of flags ? |
C# | I 'm looking at domain events , specifically at 2 possibilities : A . Using `` generic '' events like that : then the consumer would figure out the new state and do something . Since I 'm using Rx this would be not that hard ( and way better than a switch/case ) : B . Using specific events : this would lead to way more... | public class OrderStateChangedEvent : IEvent { public Guid OrderId { get ; } public OrderState NewState { get ; } } var subscription = DomainEvents .AsObservable < OrderStateChangedEvent > ( ) .Where ( e = > e.NewState == OrderState.OrderCompleted ) .Subscribe ( OnOrderCompleted ) ; public class OrderCompletedEvent : I... | DDD generic vs. specific domain events |
C# | I was trying to create an example for deadlock . I tried the following code . But instead of creating deadlock , it worked like charm . Help me in understanding why it did n't create a deadlock . What change in this code would create a deadlock ? | using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading ; namespace ReferenceTypes { class DeadLockExample { static int a ; static int b ; public static void Main ( string [ ] args ) { DeadLockExample.a = 20 ; DeadLockExample.b = 30 ; DeadLockExample d = new Dead... | Dead lock in Multithreading |
C# | I 'm working on obtaining RSS feeds like so : XmlReader.Create ( ) in this case can throw up to 4 exceptions related to things like the parameter being null , 404 error , etc.Should I try to validate the Uri ( make sure it 's not null , 404 , correct doctype , etc ) before I call that line or should I just handle the e... | SyndicationFeed rss = SyndicationFeed.Load ( XmlReader.Create ( textBox1.Text ) ) ; | Catch exception , validate input or both ? |
C# | Edit : It seems that by trying to provide some solutions to my own problem I blurred the whole problem . So I 'm modifying the question little bit.Suppose I have this class : It is actually not important what 's going on in these methods . The important is that I have multiple unit tests to cover GetProtocolHeader meth... | public class ProtocolMessage : IMessage { public IHeader GetProtocolHeader ( string name ) { // Do some logic here including returning null // and throw exception in some cases return header ; } public string GetProtocolHeaderValue ( string name ) { IHeader header = GetProtocolHeader ( name ) ; // Do some logic here in... | How to keep my unit tests DRY when mocking does n't work ? |
C# | Not sure if there 's a algorithm to describe this problem but are there any elegant methods to combine the list in a custom sequence . For example : I would like the contents of combined to contain a sequence as follows : The number of records in each list may not be equal . EDITWhen the number of records in each list ... | List < string > list1 = new List < string > ( ) ; List < string > list2 = new List < string > ( ) ; List < string > list3 = new List < string > ( ) ; list1.Add ( `` a '' ) ; list1.Add ( `` b '' ) ; list1.Add ( `` c '' ) ; list2.Add ( `` d '' ) ; list2.Add ( `` e '' ) ; list2.Add ( `` f '' ) ; list3.Add ( `` g '' ) ; li... | How to combine multiple lists with custom sequence |
C# | I have some code for strongly typing Includes ( ) 's in linq , like so ... My question is , is there anyway I can write a more generic function account for any level of successive includes ? Rather than having to rewrite it for say 3 , 4 , etc include types ? | public static ObjectQuery < T > Include < T > ( this ObjectQuery < T > mainQuery , Expression < Func < T , object > > subSelector ) { return mainQuery.Include ( ( ( subSelector.Body as MemberExpression ) .Member as System.Reflection.PropertyInfo ) .Name ) ; } /// < summary > /// Old way : ( from dbUser in DataSource.Da... | Query Extension for LINQ |
C# | I 'm using Visual Studio 2012 Update 1 and .NET 4.5 here is the code.It appears the last function call is incorrectly resolving to Func instead of Action and it has something to do with unconditionally throwing an exception.Is this a BUG ? Thanks . | void Test ( Action a ) { } void Test ( Func < int > a ) { } void TestError ( ) { bool throwException = true ; //Resolves to Test ( Action a ) Test ( ( ) = > { } ) ; //Resolves to Test ( Action a ) Test ( ( ) = > { if ( throwException ) throw new Exception ( ) ; } ) ; //Resolves to Test ( Func < int > a ) // ( This seem... | Resolving incorrect function at compile time BUG ? |
C# | I am currently working on an extension method that facilitates what the question 's title suggests.I could , of course . use the GetMetohd ( `` Invoke '' ) method call on the type and be done with it , But something tells me this is not the `` safest '' way to go.Classes and types may change , including those in the BC... | public static class ActionExtensions { public static MethodInfo GetInvoke < T > ( this Action < T > obj ) { var actionType = obj.GetType ( ) ; var tType= typeof ( T ) ; return ( from methodInfo in actionType.GetMethods ( ) let par = methodInfo.GetParameters ( ) where par.Length == 1 & & par [ 0 ] .ParameterType == tTyp... | Safest way to get the Invoke MethodInfo from Action < T > 's Instance |
C# | I have a system in which the main form is the menu , and it pops up a login form on loading . Originally it loaded the login form below the menu , so I used this.topmost = true to make it come to the front . ( as bring to front and send to back did not work ) However , if the user then clicks on something else , say ch... | private void login_Deactivate ( object sender , EventArgs e ) { // do not want it to remain top most when the application is not in focus . this.TopMost = false ; } private void Menu_Load ( object sender , EventArgs e ) { openLogin ( ) } private void openLogin ( ) { Cursor.Current = Cursors.WaitCursor ; login theForm =... | Login form not losing focus correctly |
C# | I 'm trying to read information from an SSL certificate ( in this case I 've saved a copy of StackOverflow 's via Chrome ) but for some reason the moment I build it and run it from within a Linux Docker container , it fails to output anything.On Windows the output is what I expect : But the output from the same applica... | S*.stackexchange.comstackexchange.comstackoverflow.com*.stackoverflow.comstackauth.comsstatic.net*.sstatic.netserverfault.com*.serverfault.comsuperuser.com*.superuser.comstackapps.comopenid.stackauth.com*.meta.stackexchange.commeta.stackexchange.commathoverflow.net*.mathoverflow.netaskubuntu.com*.askubuntu.comstacksnip... | Ca n't read certificate when running in Linux Docker container - works on Windows |
C# | Here 's the setup : Having the following data : Now I 'm trying to get the following result in ONE linq statement : I 've tried grouping , using selectmany , joins and I ca n't seem to find the proper way.Any Linq wiz around ? P.S : Also , I want to traverse the master list only once ... ; ) | public class Parent { public List < Child > ChildrenA = new List < Child > ( ) ; public List < Child > ChildrenB = new List < Child > ( ) ; } public class Child { public Child ( string name ) { Name=name ; } public string Name { get ; set ; } } var parents = new List < Parent > ( ) ; parents.Add ( new Parent ( ) ) ; pa... | Using Linq and C # , trying to get two lists from a list of master items grouped by two inner lists |
C# | I 'm try to parse this xml , but c # keeps throwing an exception saying it has invalid characters . I ca n't copy the text from the messagebox directly , so I 've screened it . http : //img29.imageshack.us/img29/694/xmler.jpgEdit : copied textHere 's the code to get the string | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < user > < id > 9572 < /id > < screen_name > fgfdgfdgfdgffg44 < /screen_name > < /user > string strRetPage = System.Text.Encoding.GetEncoding ( 1251 ) .GetString ( RecvBytes , 0 , bytes ) ; while ( bytes > 0 ) { bytes = socket.Receive ( RecvBytes , RecvBytes.Length ,... | XmlTextReader issue |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.