lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I have the below which calculates the running total for a customer account status , however he first value is always added to itself and I 'm not sure why - though I suspect I 've missed something obvious : Which outputs : Where the 309.60 of the first row should be simply 154.80 What have I done wrong ? EDIT : As per ... | decimal ? runningTotal = 0 ; IEnumerable < StatementModel > statement = sage.Repository < FDSSLTransactionHistory > ( ) .Queryable ( ) .Where ( x = > x.CustomerAccountNumber == sageAccount ) .OrderBy ( x= > x.UniqueReferenceNumber ) .AsEnumerable ( ) .Select ( x = > new StatementModel ( ) { SLAccountId = x.CustomerAcco... | Linq running total 1st value added to itself |
C# | Why does n't the C # compiler tell me that this piece of code is invalid ? The call to MyMethod fails at runtime because I am trying to call a non-static method from a static method . That is very reasonable , but why does n't the compiler consider this an error at compile time ? The following will not compile so despi... | class Program { static void Main ( string [ ] args ) { dynamic d = 1 ; MyMethod ( d ) ; } public void MyMethod ( int i ) { Console.WriteLine ( `` int '' ) ; } } class Program { static void Main ( string [ ] args ) { dynamic d = 1 ; MyMethod ( d ) ; } } | Why does n't the c # compiler check `` staticness '' of the method at call sites with a dynamic argument ? |
C# | I 'm trying to figure out a way to structure my data so that it is model bindable . My Issue is that I have to create a query filter which can represent multiple expressions in data.For example : x = > ( x.someProperty == true & & x.someOtherProperty == false ) || x.UserId == 2x = > ( x.someProperty & & x.anotherProper... | public enum FilterCondition { Equals , } public enum ExpressionCombine { And = 0 , Or } public interface IFilterResolver < T > { Expression < Func < T , bool > > ResolveExpression ( ) ; } public class QueryTreeNode < T > : IFilterResolver < T > { public string PropertyName { get ; set ; } public FilterCondition FilterC... | Polymorphic Model Bindable Expression Trees Resolver |
C# | Is there an easy way to find lines that consist of date time.So far I can read the textfile and my next step is to parse it , but before that I think I need some guidance before I proceed . Here is my current read script : Here is the sample text template that I need to parse generated from the tool.And here is my Aim ... | List < string > Temp = new List < string > ( ) ; string [ ] filePaths = Directory.GetFiles ( @ '' C : \\Temp\\ '' , `` *.txt '' ) ; foreach ( string files in filePaths ) { var fileStream = new FileStream ( files , FileMode.Open , FileAccess.Read ) ; using ( var streamReader = new StreamReader ( fileStream , Encoding.UT... | Reading text file and get line with date values |
C# | If I have code like this : Is this any slower than ? If so , why ? In the second example , is the compiler generally making a variable from the GetString ( ) ; method which returns a string ? Also , what is the benefit of declaring variables as late as possible ? Does this benefit the GC ? If so , how ( I 'm assuming i... | string s = MyClass.GetString ( ) ; // Returns string containing `` hello world '' ; ProcessString ( s ) ; ProcessString ( MyClass.GetString ( ) ) ; | Declaring variables as late as possible and passing returning method as a parameter |
C# | Alright , so I 've done some research into this topic and most of the solutions I 've found claim to fix the problem but I am finding that they are n't quite working right . I 'm in the early stages of implementing just a simple little particle engine , nothing crazy I 'm just doing it out of boredom . I have not done ... | public MainWindow ( ) { this.DoubleBuffered = true ; InitializeComponent ( ) ; Application.Idle += HandleApplicationIdle ; } void HandleApplicationIdle ( object sender , EventArgs e ) { Graphics g = CreateGraphics ( ) ; while ( IsApplicationIdle ( ) ) { UpdateParticles ( ) ; RenderParticles ( g ) ; g.Dispose ( ) ; } } ... | Flicker in C # WinForms program on screen clear |
C# | I 'm trying to diff two strings by phrase , similar to the way that StackOverflow diffs the two strings on the version edits page . What would be an algorithm to do this ? Are there gems , or other standard libraries that accomplish this ? EDIT : I 've seen other diffing algorithms ( Differ with Ruby ) and they seem to... | > > o = 'now is the time when all good men . ' > > p = 'now some time the men time when all good men . ' > > Differ.diff_by_word ( o , p ) .format_as ( : html ) = > `` now < del class=\ '' differ\ '' > some < /del > < ins class=\ '' differ\ '' > is < /ins > < del class=\ '' differ\ '' > time < /del > the < del class=\ ... | What is an Algorithm to Diff the Two Strings in the Same Way that SO Does on the Version Page ? |
C# | Following the MVVM pattern I 'm trying to wire up the display of a child window by the View in response to a request from the View Model.Using the MVVM-Light Messenger the View will Register for the request to display the child window in the constructor of the View as so : Does subscribing to the ChildWindow Closed eve... | InitializeComponent ( ) ; Messenger.Default.Register < EditorInfo > ( this , ( editorData ) = > { ChildWindow editWindow = new EditWindow ( ) ; editWindow.Closed += ( s , args ) = > { if ( editWindow.DialogResult == true ) // Send data back to VM else // Send 'Cancel ' back to VM } ; editWindow.Show ( ) ; } ) ; | Will this coding style result in a memory leak |
C# | If numeric expression contains operands ( constants and variables ) of different numeric types , are operands promoted to larger types according to the following rules : if operands are of types byte , sbyte , char , short , ushort , they get converted to int typeIf one of the operands is int , then all operands are co... | int i2= ( b1+b2 ) +i1 | Are operands inside an expression promoted to larger types according to the following rules ? |
C# | I have a query that should return a sum of total hours reported for the current week.This code below returns the Correct total of hours but not for a specific user in the database.The first method returns the number 24 , wich is correct but as i said , not for a specific user.I am trying to do this , but it gives me 0 ... | public int reportedWeekTime ( int currentWeek , string username ) { var totalTime = ( from u in context.Users from r in context.Reports from w in context.Weeks from d in context.Days where u.Id == r.UserId & & r.weekNr.Equals ( currentWeek ) & & r.Id == w.ReportId & & w.DayId == d.Id select d.Hour ) .DefaultIfEmpty ( 0... | Linq Query , messed up where clause in method |
C# | I 'm currently reading a book on C # programming and it has brief intro to Overflow and Underflow and the writer gives a general idea of what happens when you go over the allowed range of a certain type.Example So the short type only has a range of from -32768 to 32767 and in the book the explanation given by the write... | short a = 30000 ; short b = 30000 ; short sum = ( short ) ( a + b ) ; // Explicitly cast back into shortConsole.WriteLine ( sum ) ; // This would output the value -5536 | Can someone explain overflow in C # using binary ? |
C# | I tried to use FileInfo.CreationTime , but it does n't represent the copy finish time.I am trying to get a list of files in a directory . The problem is that the call also returns files which are not yet finished copying.If I try to use the file , it returns an error stating that the file is in use.How can you query fo... | if ( String.IsNullOrEmpty ( strDirectoryPath ) ) { txtResultPrint.AppendText ( `` ERROR : Wrong Directory Name ! `` ) ; } else { string [ ] newFiles = Directory.GetFiles ( strDirectoryPath , '' *.epk '' ) ; _epkList.PushNewFileList ( newFiles ) ; if ( _epkList.IsNewFileAdded ( ) ) { foreach ( var fileName in _epkList.G... | querying a directory for files that are complete ( not copy-in-progress ) |
C# | MonoDevelop suggests turning this : into this : It also does it when I set anotherBoolVar to false instead : becomes : Can someone explain how these statements are equal ? | if ( someBoolVar ) anotherBoolVar = true ; anotherBoolVar |= someBoolVar ; if ( someBoolVar ) anotherBoolVar = false ; anotherBoolVar & = ! someBoolVar ; | MonoDevelop suggests turning if statements into bitwise operations |
C# | I am having a ValueConverter used for binding 'To ' Value in a StoryBoard animation , similar to the answer - WPF animation : binding to the “ To ” attribute of storyboard animation.The problem is I am repeating the below piece of code for MultiBinding ValueConverter in couple of places.I want to remove this duplicate ... | < MultiBinding Converter= '' { StaticResource multiplyConverter } '' > < Binding Path= '' ActualHeight '' ElementName= '' ExpanderContent '' / > < Binding Path= '' Tag '' RelativeSource= '' { RelativeSource Self } '' / > < /MultiBinding > < system : Double x : Key= '' CalculatedWidth '' > < MultiBinding Converter= '' {... | Storing ValueConverter to variable |
C# | I 'm trying to parse an incoming stream of bytes that represents messages.I need to split the stream and create a message structure for each part.A message always starts with a 0x81 ( BOM ) and ends with a 0x82 ( EOM ) .The data part is escaped using an escape byte 0x1B ( ESC ) : Anytime a byte in the data part contain... | start : 0x81header : 3 bytesdata : arbitrary lengthstop : 0x82 [ 81 01 02 03 82 ] single message [ 81 82 81 82 82 ] single message , header = [ 82 81 82 ] [ 81 01 02 1B 82 ] single message , header = [ 01 02 1B ] . [ 81 01 02 03 1B 82 82 ] single message , header = [ 01 02 03 ] , ( unescaped ) data = [ 82 ] [ 81 01 02 ... | Rx.Net Message Parser |
C# | Here is how my last interview went : Question : Where are strings stored ? Answer : Heap since it is a reference typeQuestion : Explain me this following code : Answer : Drew two diagrams like below : ( represents the statement , string two = one ; ( represents the statement , one = one + `` string '' ; . A new string ... | static void Main ( string [ ] args ) { string one = `` test '' ; string two = one ; one = one + `` string '' ; Console.WriteLine ( `` One is { 0 } '' , one ) ; Console.WriteLine ( `` Two is { 0 } '' , two ) ; } class Program { static void Main ( string [ ] args ) { Test one = new Test { someString = `` test '' } ; Test... | Strings vs classes when both are reference types |
C# | I 've created a custom structure for handling RGBA values that will be marshaled to the GPU.In my type , I am holding individual R , G , B and A components as byte values and am overlapping a 32-bit unsigned integer ( Uint32 ) to easily pass and assign the packed value . I know the concept is obvious but here 's a samp... | [ StructLayout ( LayoutKind.Explicit , Size = 4 ) ] public struct RGBA { [ FieldOffset ( 0 ) ] public uint32 PackedValue ; [ FieldOffset ( 0 ) ] public byte R ; [ FieldOffset ( 1 ) ] public byte G ; [ FieldOffset ( 2 ) ] public byte B ; [ FieldOffset ( 3 ) ] public byte A ; } public RGBA ( uint packed value ) { R = G =... | Seeking optimal way to handle constructors of struct with overlapping fields |
C# | Suppose I have the following two classes.How can I know if a specific property is a Father property ( Inherited ) or a Child property ? I tried but seems like Except is not detecting the equality of Father properties and Child inherited properties . | public class Father { public int Id { get ; set ; } public int Price { get ; set ; } } public class Child : Father { public string Name { get ; set ; } } var childProperties = typeof ( Child ) .GetProperties ( ) .Except ( typeof ( Father ) .GetProperties ( ) ) ; | How to exclude properties of father class |
C# | I 'm trying to do below where condition is true , I want to execute WHERE else no.Above code giving me error , Type of conditional expression can not be determined because there is no implicit conversion between 'lambda expression ' and 'bool ' | var condition = true ; var mast = new List < Master > { new Master { Id = 2 , Prop1 = `` Default '' , Prop2 = `` Data '' , Prop3 = 11 } , new Master { Id = 3 , Prop1 = `` Some '' , Prop2 = `` TestData '' , Prop3 = 11 } , new Master { Id = 4 , Prop1 = `` Some '' , Prop2 = `` MoreData '' , Prop3 = 11 } , } ; var g = mast... | how to put conditional WHERE clause within LINQ query |
C# | Good afternoon , I have been working on a dll that can use CORBA to communicate to an application that is network aware . The code works fine if I run it as a C++ console application . However , I have gotten stuck on exporting the methods as a dll . The methods seems to export fine , and if I call a method with no par... | bool __declspec ( dllexport ) SpiceStart ( char* installPath ) [ DllImportAttribute ( `` SchemSipc.dll '' , CharSet=CharSet.Ansi ) ] private static extern bool SpiceStart ( string installPath ) ; bool success = SpiceStart ( @ '' c : \sedatools '' ) ; | PInvoke Unbalances the stack |
C# | I 'd like to replace the character `` by a space in a string in C # .But I have an issue when writing the function : The first argument seems to be an issue.Any idea | myString.Replace ( `` '' '' , '' `` ) | Replace character `` in C # |
C# | I am getting an error when I attempt to display a datetime value in a textbox : My code is : The error message is : ex.Message = `` Unable to cast object of type 'System.DateTime ' to type 'System.String ' . `` Any ideas how I can resolve this ? | txtStartDate.Text = rdrGetUserInfo.IsDBNull ( 14 ) ? String.Empty : Convert.ToString ( rdrGetUserInfo.GetString ( 14 ) ) ; | Error converting datetime to string |
C# | When using ReactiveExtension Observer exceptions are not being caught by the onError action . Using the example code below instead of the exception being caught `` An unhandled exception of type 'System.ApplicationException ' occurred in System.Reactive.Core.dll '' and the application terminates . The exception seems t... | var source = Observable.Interval ( TimeSpan.FromSeconds ( seconds ) ) ; var observer = Observer.Create < long > ( l = > { //do something throw new ApplicationException ( `` test exception '' ) ; } , ex = > Console.WriteLine ( ex ) ) ; var subscription = source.Subscribe ( observer ) ; var source = Observable.Interval (... | .NET ReactiveExtension observer is n't catching errors in OnError |
C# | Given a list of MethodDeclarationSyntax I would like to collect all the methods in a solution that are calling this method transitively.I have been using the following code : The problem is that MethodDeclarationSyntax does n't seem to be a singleton , so this loop is running forever , visiting the same methods again a... | var methods = new Stack < MethodDeclarationSyntax > ( ) ; ... // fill methods with original method to start from var visited = new HashSet < MethodDeclarationSyntax > ( ) ; while ( methods.Count > 0 ) { var method = methods.Pop ( ) ; if ( ! visited.Add ( method ) ) { continue ; } var methodSymbol = ( await solution.Get... | How to collect all MethodDeclarationSyntax transitively with Roslyn ? |
C# | I 've tried to set up a small demo , in which an article has multiple comments . The article details view , should render the comments in a partial view . The partialView itself contains another partial view for adding a new comment . When I try to add another comment I receive a InsufficientExecutionStackException , b... | [ ChildActionOnly ] public PartialViewResult _GetCommentsForArticle ( int articleId ) { ViewBag.ArticleId = articleId ; var comments = db.Comments.Where ( x = > x.Article.ArticleId == articleId ) .ToList ( ) ; return PartialView ( `` _GetCommentsForArticle '' , comments ) ; } public PartialViewResult _CreateCommentForA... | Why does the PartialView keep calling itself ? |
C# | I need to validate that the user entered text in the format : Can I do this using Regex.Match ? | # # # # - # # # # # - # # # # - # # # | C # regex help - validating input |
C# | Here it is returning same result . Now when I 'm using StringBuilder it is not returning same value . What is the underneath reason ? Edit1 : My above question answered below . But during this discussion what we find out StringBuilder does n't have any override Equals method in its implementation . So when we call Stri... | string s1 = `` t '' ; string s2 = 't'.ToString ( ) ; Console.WriteLine ( s1.Equals ( s2 ) ) ; // returning true Console.WriteLine ( object.Equals ( s1 , s2 ) ) ; // returning true StringBuilder s1 = new StringBuilder ( ) ; StringBuilder s2 = new StringBuilder ( ) ; Console.WriteLine ( s1.Equals ( s2 ) ) ; // returning ... | Why object.Equals and instanceobject.Equals are not same |
C# | I come from a VB.Net environment , where using Imports System and then IO.Directory.GetFiles ( ... ) works.On the other hand , it seems that using System ; is not sufficient to write use IO.Directory without prefixing it with System.. The only workaround seems to be using IO = System.IO ; Why ? Example code : Edit : My... | using System ; using System.IO ; namespace Test { class Program { static void Main ( string [ ] args ) { System.Console.WriteLine ( IO.Directory.GetFiles ( System.Environment.CurrentDirectory ) [ 0 ] ) ; } } } | Why ca n't I write IO.Directory.GetFiles ? |
C# | Take this example : Why is the implicit implementation of IFoo Bar ( ) necessary even though Foo converts to IFoo without a cast ? | public interface IFoo { IFoo Bar ( ) ; } public class Foo : IFoo { public Foo Bar ( ) { // ... } IFoo IFoo.Bar ( ) { return Bar ( ) ; } //Why is this necessary ? } | In C # , why do interface implementations have to implement a another version of a method explicitly ? |
C# | I want to format a typed in time to a specific standard : When the user types it like : `` 09 00 '' , `` 0900 '' , `` 09:00 '' , `` 9 00 '' , `` 9:00 '' But when the user types it like : `` 900 '' or `` 9 '' the system fails to format it , why ? They are default formats I tought . | private String CheckTime ( String value ) { String [ ] formats = { `` HH mm '' , `` HHmm '' , `` HH : mm '' , `` H mm '' , `` Hmm '' , `` H : mm '' , `` H '' } ; DateTime expexteddate ; if ( DateTime.TryParseExact ( value , formats , System.Globalization.CultureInfo.InvariantCulture , System.Globalization.DateTimeStyle... | FormatException with TryParseExact |
C# | I 'm trying to write an extension method that will convert IDictionary < K , S < V > > holding any type of collection/sequence ( S < V > ) to ILookup < K , V > which is more proper data structure in those cases . This means I 'd like my extension to work on different S types and interfaces : IDictionary < K , IEnumerab... | public static ILookup < TKey , TValue > ToLookup < TKey , TCollection , TValue > ( this IDictionary < TKey , TCollection > dictionary ) where TCollection : IEnumerable < TValue > var dictOfIEnumerables = new Dictionary < int , IEnumerable < int > > ( ) ; var lookupFromIEnumerables = dictOfIEnumerables.ToLookup ( ) ; va... | Single extension method on IDictionary < K , IEnumerable/IList/ICollection < V > > |
C# | Say I have a method like this : and say I need to detect if the type of arguments is actually an enumeration . I would write something like this : Now , let 's say I need to detect if it 's an enumeration of KeyValuePair ( regardless of the type of the key and the type of the value ) . My instinct would be to write som... | public void Foo ( object arguments ) if ( arguments is IEnumerable ) if ( arguments is IEnumerable < KeyValuePair < , > > ) if ( arguments is IEnumerable < KeyValuePair < object , object > > ) | How to iterate through an enumeration of KeyValuePair without knowing the type of the key and the type of the value |
C# | I have problem to convert this VB code into C # BidEventInfo is a name of classC # code : | Public Event SendNewBid As EventHandler ( Of BidEventInfo ) Public event SendNewBid ... . ? ? ? ? ? ? | Convert code from VB into C # |
C# | I 'm trying out Ninject and I 'm modifying to code I wrote with Structure Map to see how easy it is . In this base code I have a graph of objects which have different configurations via the Structure Map registries and the one to use is chosen at runtime via a value in the database ( in this case to pull back a wcf ser... | public GenericRegistry ( ) { // Set up some generic bindings here For < ILogger > ( ) .Use < Loggers.GenericLogger > ( ) ; For < IBusinessRule > ( ) .Use < Rules.StandardRule > ( ) ; For < IBusinessContext > ( ) .Use < Contexts.GenericBusinessContext > ( ) ; For < ILoggerContext > ( ) .Use < Loggers.GenericLoggerContex... | Using names to discriminate instances using IoC |
C# | I have an abstract base class from which many classes are derived . I want derived classes to be able to override a virtual method defined in the base class , but there is complex logic in the base class that determines whether the overridden method is `` enabled '' at any particular moment.Consider this code -- one po... | public abstract class AbstractBaseClass { public bool IsMethodEnabled { get ; set ; } public virtual void DerivedMethod ( ) { } public void Method ( ) { if ( IsMethodEnabled ) DerivedMethod ( ) ; } } public class DerivedClass : AbstractBaseClass { public override void DerivedMethod ( ) { Console.WriteLine ( `` DerivedM... | Is there a better way to call a derived class 's overridden method from its abstract base class ? |
C# | I was working with the first method below , but then I found the second and want to know the difference and which is best.What is the difference between : and | from a in this.dataContext.reglementsjoin b in this.dataContext.Clients on a.Id_client equals b.Id select ... from a in this.dataContext.reglementsfrom b in this.dataContext.Clientswhere a.Id_client == b.Id select ... | The best way to join in Linq |
C# | Before I started using Code Contracts I sometimes ran into fiddlyness relating to parameter validation when using constructor chaining.This is easiest to explain with a ( contrived ) example : I want the Test ( string ) constructor to chain the Test ( int ) constructor , and to do so I use int.Parse ( ) .Of course , in... | class Test { public Test ( int i ) { if ( i == 0 ) throw new ArgumentOutOfRangeException ( `` i '' , i , `` i ca n't be 0 '' ) ; } public Test ( string s ) : this ( int.Parse ( s ) ) { if ( s == null ) throw new ArgumentNullException ( `` s '' ) ; } } if ( s == null ) throw new ArgumentNullException ( `` s '' ) ; class... | Are code contracts guaranteed to be evaluated before chained constructors are called ? |
C# | This link says that : The @ symbol tells the string constructor to ignore escape characters and line breaks.I try to append contain in StringBuilder like this.But it gives an error in test_all.I got a solution for this using single quotes . ' ' : But I do n't understand as per document why `` `` does not work . Or am I... | StringBuilder sb = new StringBuilder ( ) ; sb.Append ( @ '' < test name= '' test_all '' > '' ) ; sb.Append ( `` < test name='layout_all ' > '' ) ; | Using @ symbol in string |
C# | My WPF project will be organised like this : To show the Screen1 from the Screen2 I 'll use something like this : ScreenManager.Show ( `` Group1.Screen1 '' ) This looks ( using reflection ) in the Screens.Group1.Screen1 namespace for a View and a ViewModel and instantiates them.How can I eliminate the magic string with... | Screens Group1 Screen1 View.xaml ViewModel.cs Group2 Screen2 View.xaml ViewModel.cs public class ScreenNames { public Group1Screens Group1 ; public class Group1Screens { public ScreenName Screen1 ; } } public sealed class ScreenName { private ScreenName ( ) { } } public class ScreenManager : IScreenManager { public voi... | Decouple the screens without magic strings |
C# | I 'm currently in the design phase of multiple rather complex systems which share common functionality ( e.g . both have customer-relationship management ( CRM ) and sales functionality ) . Therefore I 'm trying to extract the common part of the domain and reuse it in both applications . Let 's say I have application A... | interface ICustomer { string CustomerNumber { get ; set ; } } class Customer : ICustomer interface IACustomer : ICustomer { bool ReceivesNewsletter { get ; set ; } } class ACustomer : Customer , IACustomer { ... } interface IBCustomer : ICustomer { string NickName { get ; set ; } } class BCustomer : Customer , IBCustom... | Can I safely query using the base type of an entity 's proxy interface in NHibernate ? |
C# | I have an enum with custom value for only part of the listWhen I tried strina name = ( MyEnum ) 2 ; name was ThirdValue.But when I changed the enum toIn strina name = ( MyEnum ) 2 ; name was FifthValue.Does the compiler ( I 'm using Visual Studio 2012 ) initialize custom values only if the first has custom values ? And... | public enum MyEnum { FirstValue , SecondValue , ThirdValue , ForthValue = 1 , FifthValue = 2 } public enum MyEnum { FirstValue = 3 , SecondValue , ThirdValue , ForthValue = 1 , FifthValue = 2 } | Enum with specified values for only some of the members |
C# | Consider this program : Here , an exception of type A is thrown for which there is no handler . In the finally block , an exception of type B is thrown for which there is a handler . Normally , exceptions thrown in finally blocks win , but it 's different for unhandled exceptions.When debugging , the debugger stops exe... | using System ; static class Program { static void Main ( string [ ] args ) { try { try { throw new A ( ) ; } finally { throw new B ( ) ; } } catch ( B ) { } Console.WriteLine ( `` All done ! `` ) ; } } class A : Exception { } class B : Exception { } | Changing an unhandled exception to a handled one in a finally block |
C# | One of the nuget dependencies in my project ( Swashbuckle ) requires a version of the System.Web.Http library ( 4.0.0.0 ) that is older than the version required by the rest of the project ( 5.2.3.0 ) .Swashbuckle requires that I write a class implementing a certain interface : The important part above is the apiDescri... | public class OperationFilter : Swashbuckle.Swagger.IOperationFilter { public void Apply ( Swashbuckle.Swagger.Operation operation , Swashbuckle.Swagger.SchemaRegistry schemaRegistry , System.Web.Http.Description.ApiDescription apiDescription ) { } } var asm = System.Reflection.Assembly.GetExecutingAssembly ( ) ; var ty... | C # library which references older version of nuget dependency causes assembly reflection to fail |
C# | I want to be able to match an entire string ( hence the word boundaries ) against a pattern `` ABC '' ( `` ABC '' is just used for convenience , I do n't want to check for equality with a fixed string ) , so newlines are significant to me . However it appears that a single `` \n '' when put at the end of a string is ig... | Regex r = new Regex ( @ '' ^ABC $ '' ) ; string [ ] strings = { `` ABC '' , //True `` ABC\n '' , //True : But , I want it to say false . `` ABC\n\n '' , //False `` \nABC '' , //False `` ABC\r '' , //False `` ABC\r\n '' , //False `` ABC\n\r '' //False } ; foreach ( string s in strings ) { Console.WriteLine ( r.IsMatch (... | How to match a string , ignoring ending newline ? |
C# | I used the following in my MVC3 ( aspx ) .NETFramework 4.0 works great . view page extension method : Partial model : In the view : When I updated the application to MVC5 .NETFramework 4.5.1 . First I could not resolve GetDropDownListItems , so I copied it from the extension model to the view using @ functions , I get ... | public static List < SelectListItem > GetDropDownListItems < T > ( this ViewPage < T > viewPage , string listName , int ? currentValue , bool addBlank ) where T : class { List < SelectListItem > list = new List < SelectListItem > ( ) ; IEnumerable < KeyValuePair < int , string > > pairs = viewPage.ViewData [ listName ]... | SelectListItem / updating application form MVC3 4.0 to MVC5 4.5.1 / view extension method |
C# | I am using c # framework 3.5 ..my class hereI have a listList konumlar ; well , I want to get items that equal their enlem and boylam variables each other..As you see on the photo belowI want to compate enlem and boylam and if its the equal I want to get them to different list..I can do that with a loop but want to use... | public class KonumBilgisi { public string Enlem { get ; set ; } public string Boylam { get ; set ; } public string KonumAdi { get ; set ; } public DateTime Tarih { get ; set ; } public byte SucTuruId { get ; set ; } } var distinctList = konumlar.GroupBy ( x = > x.Enlem ) .Select ( g = > g.First ( ) ) .ToList ( ) .Group... | How to get distinct List from a custom list ? |
C# | We are using recursion to find factors and are receiving a StackOverflow exception . We 've read that the C # compiler on x64 computers performs tail call optimizations : JIT definitely does tailcals when running optimized code and not debugging.Running dotnet -- configuration release gets this far in our program : Why... | ... 7214 is a factor of 12345678907606 is a factor of 123456789010821 is a factor of 123456789011409 is a factor of 1234567890 Process is terminated due to StackOverflowException . class Program { static void Main ( string [ ] args ) { const long firstCandidate = 1 ; WriteAllFactors ( 1234567890 , firstCandidate ) ; } ... | Why is tail call optimization not occurring here ? |
C# | Hi there i am new to the repository pattern . I would like to have feedback on the approach i am following.Requirement : Build the menu for the user that is currently logged in . My Solution : I created a Service , that will be called by the controller to get the menu items.The implementation for the serviceThen the Co... | public interface IApplicationHelperService { List < Menu > GetMenuForRoles ( ) ; } public class ApplicationHelperService : IApplicationHelperService { private readonly IMenuRepository _menuRepository ; //this fecthes the entire menu from the datastore private readonly ICommonService _commonService ; //this is a Service... | Repository pattern for common items |
C# | I have a `` settings '' class , which has some properties for usability and to restrict set accessor . It seems easy while i had within ten items , but then their count was increased . I need some way to create these properties automatically , something like that : It may have deal with reflection , but i ca n't get to... | foreach ( var property in SettingsList ) { _settings.AddAutoProperty ( property ) ; } public bool cbNextExcCount { get { return ( bool ) this.GetValueById ( `` cbNextExcCount '' ) ; } } public bool cbSaveOnChangeExc { get { return ( bool ) this.GetValueById ( `` cbSaveOnChangeExc '' ) ; } } public bool cbAutoIncrement ... | How to create properties automatically ? |
C# | I have identified that when the following expression is executed : on mysql the query executed is : Can anyone explain please why this last extra condition is added ? AND ( 52 IS NOT NULL ) ) | int aNum = 52 ; var myArtifacts = mydbcontext.artifacts.Where ( a = > a.ParentID == aNum ) .ToList ( ) ; SELECT ` Extent1 ` . ` ID ` , ` Extent1 ` . ` ParentID ` FROM ` artifacts ` AS ` Extent1 ` WHERE ( ( ` Extent1 ` . ` ParentID ` = 52 ) AND ( 52 IS NOT NULL ) ) ; | Entity framework adds an extra condition on where clause |
C# | I have two classes like thisTrying to mock this in a unit test using Moq with this line new Mock < FooWithGoo < Bar > > ( ) gives me this exception.System.ArgumentException : Type to mock must be an interface or an abstract or non-sealed class . -- - > System.TypeLoadException : Method 'Do ' in type 'Castle.Proxies.Foo... | public abstract class Foo < T > where T : Bar { public Bar Do ( Bar obj ) { //I cast to T here and the call the protected one . } ... protected abstract Bar Do ( T obj ) ; } public abstract class FooWithGoo < T > : Foo < T > where T : Bar { ... } using Microsoft.VisualStudio.TestTools.UnitTesting ; using Moq ; namespac... | Mocking an abstract class derived from an abstract class |
C# | Where the _Internal is a Service with a guaranteed 99.99 % up-time and not formalized fault contract interfaces defined . Exceptions which are handled in my application level ( business layer level ) as a BusinessException - root class Where BusinessException is defined as followsAnd the current test Method is To do : ... | [ HttpPost ] [ Route ( `` TnC '' ) ] public IHttpActionResult TnC ( CustomViewModel myViewModel ) { try { return Json ( _Internal.TnC ( myViewModel , LoggedInUser ) ) ; } catch ( BusinessException exception ) { return Json ( BuildErrorModelBase ( exception ) ) ; } } public class BusinessException : Exception { Business... | How to add an exception test for the below Http call that returns a json |
C# | Short VersionFor those who do n't have the time to read my reasoning for this question below : Is there any way to enforce a policy of `` new objects only '' or `` existing objects only '' for a method 's parameters ? Long VersionThere are plenty of methods which take objects as parameters , and it does n't matter whet... | var people = new List < Person > ( ) ; Person bob = new Person ( `` Bob '' ) ; people.Add ( bob ) ; people.Add ( new Person ( `` Larry '' ) ) ; Array.Sort < int > ( new int [ ] { 5 , 6 , 3 , 7 , 2 , 1 } ) ; DataTable firstTable = myDataSet.Tables [ `` FirstTable '' ] ; DataTable secondTable = myDataSet.Tables [ `` Seco... | Can I detect whether I 've been given a new object as a parameter ? |
C# | I 've been looking quite a bit at Mr. Skeet 's blog on how to re-implement LINQ.In particular , he states that the code : is translated to methods that are extension methods that are provided by the LINQ library : BY THE COMPILER.My question is , how does one impress the bigwigs enough with a library to cause them to a... | var list = ( from person in people where person.FirstName.StartsWith ( `` J '' ) orderby person.Age select person.LastName ) .ToList ( ) ; people.Where ( person = > person.FirstName.StartsWith ( `` J '' ) ) .OrderBy ( person = > person.Age ) .Select ( person = > person.LastName ) | Is it possible to create C # language modifications as did LINQ ? |
C# | I 'm using Simple.Data ORM . I 'm trying to make a query from two joined tables . This query works fine : But when this line is added : I 'm getting this exception : The multi-part identifier \ '' dbo.CandidateProfiles.CandidateId\ '' could not be bound.I was trying explicitly pass 0 , 1 and few other numbers to Skip b... | dynamic alias ; var candidatesRec = db.dbo.Candidates .FindAll ( db.dbo.Candidates.CommonOfferId == commonOfferId & & db.dbo.CandidateProfiles.CandidateId == null ) .LeftJoin ( db.dbo.CandidateProfiles , out alias ) .On ( db.dbo.Candidates.Id == alias.CandidateId ) .Select ( db.dbo.Candidates.Id , db.dbo.Candidates.Ema... | Simple.Data ORM . The multi-part identifier could not be bound |
C# | If I implement a generic type that risks being instantiated with lots of type params , should I avoid ( for JIT performance/code size etc . reasons ) having many nested non-generic types ? Example : The alternative which works equally well is to have the non-generic types outside , but then they pollute the namespace .... | public class MyGenericType < TKey , TValue > { private struct IndexThing { int row ; int col ; } private struct SomeOtherHelper { .. } private struct Enumerator : IEnumerator < KeyValuePair < TKey , TValue > > { } } public class MyGenericType < TKey , TValue > { private struct Enumerator : IEnumerator < KeyValuePair < ... | Should I avoid nested types in generic types ? |
C# | I have a column in a table that is full of regular expressions . I have a string in my code , and I want to find out which regular expressions in that column would match that string and return those rows . Aside from pulling each row and matching the regular expression ( which is costly , checking against potentially t... | 1 ^ [ W11 ] [ \w ] + $ 2 ^ [ W12 ] [ \w ] + $ 3 ^ [ W13 ] [ \w ] + $ 4 ^ [ W1 ] [ \w ] + [ A ] [ \w ] + $ 5 ^ [ W1 ] [ \w ] + [ B ] [ \w ] + $ 6 ^ [ W1 ] [ \w ] + [ C ] [ \w ] + $ | Matching a string against a column full of regular expressions |
C# | I have a variable that indicates the length of time the UI can be idle . I have elected to call this variable UITimer . I want to pass the variable into my classes constructor and then store it off in a local field.What is the proper way to do the casing of this ? We use the common convention of a parameter not being c... | uITimer uiTimer private int _uITimer private int _uiTimer ? | Capitalization of an acronym that starts a parameter |
C# | I 've seen and used this pattern several times , and it 's very useful for providing common functionality across a series of type-specific subclasses . For instance , this could be a model for Controllers/Presenters specific to a type of domain object that is central to the page ( s ) the class is used to control ; bas... | //this class ( or interface if you like ) is set up as generic ... public abstract class GenericBase < T > { public T PerformBasicTask ( T in ) { ... } } // ... but is intended to be inherited by objects that close the generic ... public class ConcreteForDates : GenericBase < DateTime > { public DateTime PerformSpecifi... | Is there a name for this pattern of using generics ? |
C# | Does code in the constructor add to code in subclass constructors ? Or does the subclass 's constructor override the superclass ? Given this example superclass constructor : ... and this subclass constructor : When an instance of FordCar is created , will this trace `` Car '' and `` Ford '' ? ? Edit : Will arguments al... | class Car { function Car ( speed : int ) { trace ( `` CAR speed `` +speed ) } } class FordCar extends Car { function FordCar ( model : string ) { trace ( `` FORD model `` +model ) } } | Does code in the constructor add to code in subclass constructors ? |
C# | I am trying to aggregate several queries together to provide a latest updates display for my users using a common data structure for union support . In my first function I have the following select clause : When called this correctly generates a query that returns 9 fields . The second method 's select is : When this q... | .Select ( x = > new PlayerUpdateInfo { FirstName = x.PodOptimizedSearch.FirstName , LastName = x.PodOptimizedSearch.LastName , RecruitId = x.RecruitId , Date = x.Date , UpdateMessage = x.IsAddedAction ? `` Player was added to this recruiting board by `` + x.Person.FirstName + `` `` + x.Person.LastName : `` Player was r... | Why is Linq-to-sql incorrectly removing fields in my union ? |
C# | I was wondering why it is possible to do this in C # 7.0 : ..but not this : Can someone explain that ? | int ? test = 0 ; int test2 = test ? ? throw new Exception ( `` Error '' ) ; int ? test = 0 ; int test2 = test ? ? return ; | Null coalescing operator ( ? ? ) with return |
C# | I have Net Core 3.1.1000 installed.Now we are trying to run ef migrations with EF Core 2.2.6 database previous Solution , when running the following , receive error below.The application to execute does not exist : .dotnet\tools.store\dotnet-ef\2.2.6-servicing-10079\dotnet-ef\2.2.6-servicing-10079\tools\netcoreapp2.2\a... | dotnet ef migrations add InitialCreate | Entity Framework : Run EF Migrations for Previous Version in Net Core |
C# | I need to take an 8 bit number on a 64 bit cpu and shift it to the right 8 times . Each time I shift the number I need to shift the same 8 bit number in behind it so that I end up with the same 8 bit number repeating 8 times . This would end up being shift , add 8 , shift add 8 ... etc . which ends up being 40+ cycles ... | long _value = 0 ; byte _number = 7 ; for ( int i = 0 ; i < 8 ; i++ ) { _value = ( _value < < 8 ) + _number ; } | Is there a shift and copy cpu instruction that can be accessed from c # ? |
C# | How can I get this in to one query ? What I want is the Person from the Company that matches the name of the person I 'm searching for.Currently I get the Company and then run basically the same search . | var existingCompany = bidInfo.Companies .FirstOrDefault ( c= > c.CompanyDomain ! = null & & c.CompanyDomain.People.FirstOrDefault ( p = > p.Name == bidInfo.ArchitectPerson.Name ) ! = null ) ; Person existingPerson=null ; if ( existingCompany ! =null ) { existingPerson = existingCompany.CompanyDomain.People.FirstOrDefau... | How do I combine these two linq queries into a single query ? |
C# | When I 'm running this code , I 'm getting error Index was outside the bounds of the array.Can anyone help me out , please ? | for ( var i = 9 ; i + 2 < lines.Length ; i += 3 ) { Items.Add ( new ItemProperties { Item = lines [ i ] , Description = lines [ i + 1 ] , Quantity = lines [ i + 2 ] , UnitPrice = lines [ i + 3 ] } ) ; } | Error : Index was outside the bounds of the array |
C# | I have the following classAnd NUnit unit testMy Unit tests fails with When I debug the method return 8.49 so where does the unit test get the long number from with a 2 at the end ? | public static class MyClass { public static double Converter ( int mpg ) { return Math.Round ( ( double ) mpg / ( ( double ) 36 / 12.74 ) , 2 ) ; } } [ TestFixture ] public class ConverterTests { [ Test ] public void Basic_Tests ( ) Assert.AreEqual ( 8.50 , MyClass.Converter ( 24 ) ) ; } } Expected : 8.5dBut was : 8.49... | C # NUnit unit test not using correct method return to compare |
C# | I have implemented Multi Language Support into my ASP.NET C # followed by this tutorial and set english to my Default language as can be seen here : When switching to german nothing happens : In my App_GlobalResource Folder I have to files : de.language.resx and en.language.resxMy mls.cs file ( In the tutorial named Ba... | public class mls : System.Web.UI.Page { public void setLang ( ) { InitializeCulture ( ) ; } protected override void InitializeCulture ( ) { if ( ! string.IsNullOrEmpty ( Request [ `` lang '' ] ) ) { Session [ `` lang '' ] = Request [ `` lang '' ] ; } string lang = Convert.ToString ( Session [ `` lang '' ] ) ; string cu... | Switching Language in C # .NET has no impact to site |
C# | Reading through answers to this question prompted me to think about what happens exception-wise when the awaited task throws . Do all `` clients '' get to observe the exception ? I admit I may be confusing a couple of things here ; that 's the reason I 'm asking for clarification.I 'll present a concrete scenario ... L... | var timeout = Task.Delay ( numberOfSecondsUntilClientsPatienceRunsOut ) ; try { var result = await Task.WhenAny ( timeout , task ) ; if ( result == timeout ) { // SNIP : No result is available yet . Just report the progress so far . } // SNIP : Report the result . } catch ( Exception e ) { // SNIP : Report the error . ... | What happens when multiple parallel threads await the same Task instance which then throws ? |
C# | I have this list in C # : I can easily print the content of the list with : Now I want to do the same in F # ( I understand from over here that a List < T > is similar to a ResizeArray ) : Now the problem is , that in the for-loop word becomes null . What am I doing wrong here ? EDIT : Here is the full code . I have ch... | List < string > words = new List < string > { `` how '' , `` are '' , `` you '' } ; foreach ( string word in words ) Debug.WriteLine ( word ) ; let words = ResizeArray < string > ( ) words.Add ( `` how '' ) words.Add ( `` are '' ) words.Add ( `` you '' ) for word in words do Debug.WriteLine ( sprintf `` % s '' word ) l... | Why ca n't I print this array in F # ? |
C# | I have come across this several times in the last week , and am curious to know the reason - I had a google , but could n't find anything directly relevant.I have a class with a dynamic method , and I can add a static method with the same interface : This is fine , but if I try to call the static method from the dynami... | public class MyClass { public int MyMethod ( ) { //do something # 1 ; } public static int MyMethod ( ) { //do something } } | Method overload static + Dynamic fails |
C# | I was wondering if this code could be improved . The IProvider implements IProvider and overwrites Request ( ... ) . I 'd like to combine these into a single interface . But I still need a typed and untyped interface to work with.Is there a way to combine these where I get both or is this how the interfaces should look... | public interface IProvider { DataSourceDescriptor DataSource { get ; set ; } IConfiguration Configuration { get ; set ; } IResult Request ( IQuery request ) ; } public interface IProvider < T > : IProvider { new IResult < T > Request ( IQuery request ) ; } | Is it possible to define a non-generic interface which can have generic methods ? |
C# | If it helps , the following question is in the context of a game I am building.In a few different places I have the following scenario . There exists a parent class , for this example called Skill , and I have a number of sub-classes implementing the methods from the parent class . There also exists another parent clas... | //Skill.IdEnum { FireSkill , WaterSkill , etc } //SkillFactorypublic static Skill Create ( Skill.Id id ) { switch ( id ) { case Skill.Id.FireSkill : return new FireSkill ( ) ; //etc } } | What is a correct way of replacing the switch block and Enum in this situation ( C # ) ? |
C# | I have a class that manages collections of objects e.g . List < Car > and List < Bike > which are atribute . I 'd like to find a way to get a reference to each of those collections in a lookup so I can implement methods such as Add < Car > ( myCar ) or Add ( myCar ) ( with reflection ) and it will add it to the right c... | public class ListManager { private Dictionary < Type , Func < IEnumerable < object > > > _lookup = new Dictionary < Type , Func < IEnumerable < object > > > ( ) ; public ListManager ( ) { this._lookup.Add ( typeof ( Car ) , ( ) = > { return this.Cars.Cast < object > ( ) .ToList ( ) ; } ) ; this._lookup.Add ( typeof ( B... | Implementing a lookup table that takes T and returns attributes on method of type List < T > |
C# | I would like to know the most efficient way of creating new arrays from the content of other arrays.I have several arrays of strings of the type : It would be possible to create now a new array of string in a similar way to this ? That would contain all the strings included in the other arrays . | public readonly string [ ] Taiwan = { `` TW '' , `` TWO '' } ; public readonly string [ ] Vietnam = { `` HM '' , `` HN '' , `` HNO '' } ; public readonly string [ ] Korea = { `` KQ '' , `` KS '' } ; public readonly string [ ] China = { `` SS '' , `` SZ '' } ; public readonly string [ ] Japan = { `` T '' , `` OS '' , ``... | Create new array using content of other arrays in C # |
C# | I want to associate custom data to a Type , and retrieve that data in run-time , blazingly fast.This is just my imagination , of my perfect world : var myInfo = typeof ( MyClass ) .GetMyInformation ( ) ; this would be very fast ... of course this does not exist ! If it did I would not be asking . hehe ; ) This is the w... | Dic.buckets | Dic.Count | Dic.Key | Ops ( x17 ) /s | Avg.Time | Min.Time | Max.Time -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 17519 | 12467 | Type | 1051538 | 0.95μs | 0.86μs | 0.42ms 919 | 912 | Type | 814862 | 1.23μs | 1.14μs | 0.46ms 1162687 |... | What is the most efficient performance-wise way of associating information with a 'Type ' object in .Net ? |
C# | I have these classes : Then I have two generic methods with this signature : Now when I create an instance of Data class and call Add methodThe first generic method is used and generic type Data is correctly inferred.But when I call the same method with a more implemented type object instanceI would expect the second g... | /* Data classes */public class Data { public int Id { get ; set ; } } public class InfoData < TInfo > : Data where TInfo : InfoBase { public TInfo Info { get ; set ; } } /* Info classes */public abstract class InfoBase { public int Id { get ; set ; } } public interface IRelated { IList < InfoBase > Related { get ; set ... | How does type inference work with overloaded generic methods |
C# | We have a complex XML Structure and really a big one ( > 500 MB ) . the XSD of the structure is : This XSDAs we know this is a complex one . and because of size or non-tab deliminator structure , I could n't convert it to a readable better presentation . I want to read this file via C # and search the drug name . what ... | try { XmlReader xmlFile ; xmlFile = XmlReader.Create ( `` C : \\Users\\Dr\\Desktop\\full database.xml '' , new XmlReaderSettings ( ) ) ; DataSet ds = new DataSet ( ) ; ds.ReadXml ( xmlFile ) ; dataGridView1.DataSource = ds.Tables [ 0 ] ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString ( ) ) ; } | Unstructured XML via non-tab deliminator ? |
C# | I have an ad-hoc reporting system ; I have no compile-time knowledge of the source type of queries or of the required fields . I could write expression trees at runtime using the System.Linq.Expressions.Expression factory methods , and invoke LINQ methods using reflection , but Dynamic LINQ is a simpler solution.The re... | enum Color { Red , Green , Blue } // using System ; // using static System.Linq.Enumerable ; // using System.Linq ; var range = Range ( 0 , 3 ) .Select ( x = > ( Color ) x ) .AsQueryable ( ) ; var qry = range.Select ( x = > ( Color ? ) x ) ; // using static System.Linq.Dynamic.Corevar qry1 = range.Select ( `` int ? ( i... | Convert my value type to nullable equivalent |
C# | I am trying to build the source for the .net connector c # in Visual Studio 2017 . I 've tried downloading several versions of the MySQL connector from GitHub ( https : //github.com/mysql/mysql-connector-net/releases ) , but every version has an issue , I 'm not sure what I 'm missing . I tried downloading the latest v... | Source file 'Desktop\mysql-connector-net-6.10.0\Source\MySQL.Data\X\XDevAPI\Common\ColumnTypes.cs ' could not be found . | Opening MySQL.Data source from Github source |
C# | I am collecting data from a USB device and this data has to go to an audio output component . At the moment I am not delivering the data fast enough to avoid clicks in the output signal . So every millisecond counts.At the moment I am collecting the data which is delivered in a byte array of 65536 bytes.The first two b... | byte [ ] buffer = new byte [ 65536 ] ; double [ ] bufferA = new double [ 16384 ] ; double [ ] bufferB = new double [ 16384 ] for ( int i= 0 ; i < 65536 ; i +=4 ) { bufferA [ i/4 ] = BitConverter.ToInt16 ( buffer , i ) ; bufferB [ i/4 ] = BitConverter.ToInt16 ( buffer , i+2 ) ; } | Improve performance of Bitconverter.ToInt16 |
C# | Below is my array : Now in above array , selected property represent check/uncheck status of checkbox and i am posting above array to web service ( WCF ) as string using json.stringify.Above array contains 2000 - 4000 records and now user can check/uncheck checkboxes.Now consider there are 4000 records in above array i... | var.child.Cars1 = { name : null , operation:0 , selected : false } Error : ( 413 ) Request Entity Too Large | Suggestions on posting huge string to web service |
C# | I 'm trying to get the data for each cells to align correctly with each other , but for one column the contents are not lining up with the others . I 'm not sure why this is , as I have looked over all the default styles and other layout/appearance options and nothing is out of the ordinary . I do n't know if this will... | // // dataGridView// dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft ; dataGridViewCellStyle1.Font = new System.Drawing.Font ( `` Verdana '' , 9.75F , System.Drawing.FontStyle.Regular , System.Drawing.GraphicsUnit.Point , ( ( byte ) ( 0 ) ) ) ; dataGridViewCellStyle1.Wrap... | Column cell value in datagridview not aligning with others |
C# | Just wondering , does it matter in which sequence the LINQ methods are added ? Eg.and this are completely the same ? Of course I can have all methods tested one by one , but I 'd like to have some general idea about the logic.So : Other than methods like FirstOrDefault ( ) , ToList ( ) and other methods that really tri... | using ( MyDataContext context = new MyDataContext ( ) ) { var user = context.Users .Where ( u = > u.UserName.StartsWith ( `` t '' ) ) .OrderByDescending ( u = > u.CreatedDate ) .FirstOrDefault ( ) ; } using ( MyDataContext context = new MyDataContext ( ) ) { var user = context.Users .OrderByDescending ( u = > u.Created... | Sequence of LINQ method of any importance ? |
C# | Here is what I 'm trying to do overall . Just to be clear , this is n't homework or for a contest or anything . Hopefully , I 've made the wording clear enough : ProblemGiven a set of strings in the same format , but where some end in a lowercase letter and some do not , return a set of one of each string that does not... | where grouped.SomeButNotAll ( x = > x == string.Empty ) select grouped.Key where grouped.ContainsSomeButNotAll ( string.Empty ) select grouped.Key where grouped.Contains ( string.Empty ) & & grouped.Any ( x = > x ! = string.Empty ) select grouped.Key | Is there an elegant LINQ solution for SomeButNotAll ( ) ? |
C# | I have this code , I am concerned that it is `` not safe '' I used Dispose ( ) before the using statement end , for me it is slightly illogical , but it works just fine . So , is it safe ? | using ( FileStream stream = new FileStream ( SfilePath , FileMode.Open ) ) { try { XmlSerializer deserializer = new XmlSerializer ( typeof ( HighscoresViewModel ) ) ; HVM = deserializer.Deserialize ( stream ) as HighscoresViewModel ; } catch ( InvalidOperationException ) { stream.Dispose ( ) ; ( new FileInfo ( SfilePat... | What happens if I called Dispose ( ) before using statement end ? |
C# | In our external boundaries that expose WCF services , we convert all internal exceptions to FaultException . This is a manual process which often has minor flaws unique to each implementation . It has been copy/pasted and mindlessly modified ( or forgotten ) for each exposed method . To reduce the errors , I wanted to ... | [ Serializable ] public sealed class FaultExceptionConverter : OnExceptionAspect { public Func < Exception , FaultException > FaultConverter { get ; set } } | Passing Func < > or similar to PostSharp aspect |
C# | I have an inline lambda expression that I would like to use throughout my application . I just ca n't seem to find a reference on how to do this with more parameters than the element being tested . Here is a quick example of what I currently have.I know the IEnumerable.Where accepts a method with the element type as a ... | Private Sub Test ( ) Dim List As New List ( Of String ) From { `` Joe '' , `` Ken '' , `` Bob '' , `` John '' } Dim Search As String = `` *Jo* '' Dim Result = List.Where ( Function ( Name ) Name Like Search ) End Sub Private Sub Test ( ) Dim List As New List ( Of String ) From { `` Joe '' , `` Ken '' , `` Bob '' , `` J... | Can I use a Method instead of Lambda expression with extra parameters |
C# | I 've stumbled accross this code in production and I think It may be causing us problems.Calling the Instance field twice returns two objects with the same hash code . Is it possible that these objects are different ? My knowledge of the CLI says that they are the same because the hash codes are the same.Can anyone cla... | internal static readonly MyObject Instance = new MyObject ( ) ; | Is the following code a rock solid way of creating objects from a singleton ? |
C# | We can raise event in two ways : and I prefer the last one . It is shorter.My colleagues insist on the first variant.Is there any superiority of the first over the second one ? | public event EventHandler MyEvent ; private void DoSomething ( ) { ... var handler = MyEvent ; if ( handler ! = null ) handler ( this , EventArgs.Empty ) ; } public event EventHandler MyEvent = ( o , e ) = > { } ; private void DoSomething ( ) { ... MyEvent ( this , EventArgs.Empty ) ; } | .NET event raising and NullObject pattern |
C# | I have some Action Attributes that allow parameters . This is how it looks like : Now I want to get rid of the magic string `` GetTerms '' in my Attribute . So I would prefer something like : ( Pseudocode , not working ) Having an additional Property inside my attribute-class and doing `` Method2String '' -Conversions ... | [ DeleteActionCache ( Action= '' GetTerms '' ) ] public ActionResult AddTerm ( string term ) { } public ActionResult GetTerms ( ) { } [ DeleteActionCache ( Action=this.GetTerms ( ) .GetType ( ) .Name ) ] | Get action name as string for Attribute-parameter |
C# | I am currently working with json.net ! I know how to deserialize json data and how to map with our class . Now I am eager about some queries ! Suppose my jsonstrings isand my attribute class ( in which i want to deserialize above string ) isNow I am using following code for deserialization . ! And Obviously this code i... | `` attributes '' : { `` color '' : '' Brown '' , `` condition '' : '' Used '' , `` currency '' : '' USD '' , `` price '' : '' 10500 '' , `` price_display '' : '' $ 10,500 '' , } Public class Attribute { public string name { get ; set ; } public string value { get ; set ; } } JavaScriptSerializer ser = new JavaScriptSer... | Is this possible in JSON ? |
C# | I have a design problem I 'd like to solve.I have an interface , lets call it IProtocol , which is implemented by two separate classes . We 're looking at over 600 lines of code here . The vast majority of the stuff they do is the same , except for some specific areas , like DiffStuff ( ) ; Current structure is somethi... | public class Protocol1 : IProtocol { MyInterfaceMethod1 ( ) { Same1 ( ) ; DiffStuff ( ) ; Same2 ( ) ; } } public class Protocol2 : IProtocol { MyInterfaceMethod1 ( ) { Same1 ( ) ; Same2 ( ) ; } } public class Protocol1 : Protocol2 { void Same1 ( ) { base.Same1 ( ) ; } void Same2 ( ) { base.Same2 ( ) ; } MyInterfaceMeth... | Design Problem - Is Inheritance the right way to simplify this code ? |
C# | I have a method which I 'd like to take all list-like objects in my solution . Before .NET 4.5 , this was simple : However , .NET 4.5 introduced IReadOnlyList < T > , which this method should also apply to.I ca n't just change the signature to take an IReadOnlyList < T > , as there are places where I apply the method t... | public static T Method < T > ( IList < T > list ) { // elided } public static T Method < T > ( IReadOnlyList < T > list ) { // elided } | C # overload resolution with IList < T > and IReadOnlyList < T > |
C# | I have one asynchronous method : Let 's say I also have this class : I now want to create a convenience method producing a BitmapSource output , using the asynchronous method above to do the work . I can come up with at least three approaches to do this , but it is not immediately obvious to me which one I should choos... | public async Task < BitmapSource > GetBitmapAsync ( double [ ] pixels ) ; public class PixelData { public double [ ] Pixels { get ; } } public BitmapSource GetBitmap ( PixelData pixelData ) { return GetBitmapAsync ( pixelData.Pixels ) .Result ; } public Task < BitmapSource > GetBitmap ( PixelData pixelData ) { return G... | Recommended method signature when returning output from asynchronous method ? |
C# | I 'm trying to test a really simple function . It returns numbers which contain some specified digit . If the first argument is null , it 'll throw ArgumentNullException.Unfortunately , Assert.Throws says , that the expected exception is n't thrown and the test fails . When I 'm trying to debug the test , it does n't s... | /// < summary > /// Filter given numbers and return only numbers containing the specified digit . /// < /summary > /// < param name= '' numbers '' > The numbers to be filtered. < /param > /// < param name= '' digit '' > The digit which should be found. < /param > /// < returns > Numbers that contains the digit. < /retu... | Assert.Throws method does n't catch the expected exception |
C# | I 'm currently studying for my MS 70-515 exam . In one of the practices the author implements an interface both implicit as well as explicit . The explicit implementation just calls the implicit implementation . The explicit implementation is just listed without an explanation.Does it make sense to have both an implici... | public class PassTextBox : TextBox , IScriptControl { public virtual IEnumerable < ScriptDescriptor > GetScriptDescriptors ( ) { var descriptor = new ScriptControlDescriptor ( `` AjaxEnabled.PassTextBox '' , ClientID ) ; // ... return new ScriptDescriptor [ ] { descriptor } ; } IEnumerable < ScriptDescriptor > IScriptC... | Does implementing Interface both implicit and explicit make sense ? |
C# | I am creating an application for a shop , where clients are divided into two groups : receivers and payers.1 ) Many receivers can be related to one same payer.2 ) Payer can be receiver itself , thus he is related to one receiver onlyMy code so far look like this : However I need to let the user create a new payer that ... | public class Receiver { [ Key ] public int ReceiverId { get ; set ; } public string Name { get ; set ; } [ Required ] public int PayerId { get ; set ; } public virtual Payer Payer { get ; set ; } } public class Payer { [ Key ] public int PayerId { get ; set ; } public string Name { get ; set ; } public virtual ICollect... | How to model this entity |
C# | I have a class that saves logging information to the database ( in an NServiceBus message Handle method ) . Most of the time that logging can be done on a separate thread ( and transaction ) from the main process . But it all needs to be done on the same background thread ( meaning that they have to be done in order , ... | public class MyExample { public void LogSomeStuff ( Stuff stuff ) { using ( MoveOutsideTransaction ( ) ) { // Do Method Stuff here dataAccess.SaveChanges ( ) ; } } public void LogSomeOtherStuff ( Stuff stuff ) { using ( MoveOutsideTransaction ( ) ) { // Do Other Method Stuff here dataAccess.SaveChanges ( ) ; } } privat... | Conditionally run the methods of a class on a separate thread |
C# | I have a small program which creates Excel files from a database table , with Excel 2013 it works all fine , but i Need it now for Excel 2010 and now I get the following exception when i will add the `` Format '' to the NumberFormatLocal ( range.NumberFormatLocal = format ; ) The same exception will come when I use the... | if ( chkWithValues.Checked & & results.Item3.Any ( ) ) { var rows = results.Item3.Count ; var cols = results.Item3.Max ( x = > x.Count ) ; object [ , ] values = new object [ rows , cols ] ; object [ , ] format = new object [ rows , cols ] ; //All returned items are inserted into the Excel file //Item2 contains the data... | excel 2010 Type Conflict NumberFormat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.