text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : Basically I 'm doing is converting from Exception to GenericFaultException class ( The below code snippet uses C # as a language.See the below details I have created a faultExceptionObject using the below line of codeI have a Error handling layer which do not have any idea about ValidationFault class , only it knows IValidationFault . For some reason the line : results in genericFaultException always equal to null , but from the QuickWatch I see Exception is of type FaultException < ValidationFault > . How should I convert from Exception to FaultException < IValidationFault > ? Please let me know if you need any more information.Thanks in advance <code> FaultException < T > : FaultException ( FaultException derived from exception ) FaultException : Exception public class ValidationFault : IValidationFault { } FaultException < ValidationFault > faultExceptionObject=new FaultException < ValidationFault > ( new ValidationFault ( ) ) public Exception HandleException ( Exception exception , Guid handlingInstanceId ) { FaultException < IValidationFault > genericFaultException = exception as FaultException < IValidationFault > ; //********genericFaultException is always NULL********************** IValidationFault fault = genericFaultException.Detail as IValidationFault ; } FaultException < IValidationFault > genericFaultException = exception as FaultException < IValidationFault > ; | Generic conversion |
C_sharp : I am using windows forms.My C # application contains 100 user controls . I show/hide one of those 100 user controls at a time when I need to and hide the rest . Each one of those user controls has 30 buttons and I subscribe to button event as following in the constructor : So when I run the Application all the 100 User controls subscribe to the 30 buttons event and some of the user controls subscribe to the event but they are never used during the use of the application.I read something about unsubscribing events here and Here but some answers say you should unsubscribe because it cause memory leak and some say you do n't have to , therefore the answer is still not clear . My question is do I have to unsubscribe from button events after using it for example : when I show/hide a user control . If yes , how can I subscribe from button event when a user control is shown and unsubscribe when it is not shown . <code> public UserControl1 ( ) { InitializeComponent ( ) ; button1.Click += new EventHandler ( MyButtonClick ) ; button2.Click += new EventHandler ( MyButtonClick ) ; . . button30.Click += new EventHandler ( MyButtonClick ) ; } void MyButtonClick ( object sender , EventArgs e ) { // do something } | Do I have to unsubscribe from button events after using it in c # ? |
C_sharp : I have just posted an answer to this question but I 'm not entirely convinced of my answer.There are two things I 'm wondering , consider this code : According to C # Specification 5.0 , there are two different kinds of conversion of as operator . If the compile-time type of E is not dynamic , the operation E as T produces the same result as If the compile-time type of E is dynamic , unlike the cast operator the as operator is not dynamically bound ( §7.2.2 ) . Therefore the expansion in this case is : Since , this is invalid because of ( Foo < T > ) strI thought it should be translated as : But the spec says this only happens when the type of E is dynamic.So my questions are : Is the compiler translating this expression to a code that is normally invalid ? When the type of E is dynamic why first it casts E to object then T while the ( T ) E is completely valid ? <code> class Foo < T > { void SomeMethod ( ) { string str = `` foo '' ; Foo < T > f = str as Foo < T > ; } } E is T ? ( T ) ( E ) : ( T ) null E is T ? ( T ) ( object ) ( E ) : ( T ) null str is Foo < T > ? ( Foo < T > ) str : ( Foo < T > ) null ; str is Foo < T > ? ( Foo < T > ) ( object ) str : ( Foo < T > ) null ; | How is `` as '' operator translated when the right-side operand is generic ? |
C_sharp : In a recent question of mine I learned that if there are more than one extension methods with constraints that match the given type , the most specific one will be chosen . This got me thinking - how does the compiler determine which one is `` more specific '' ? And what will the outcome be ? Let 's say I have the following classes : If I now use the extension method as which method will be used ? Or will the compiler throw an error ? Note : I 'm not saying this is good design , or even that I have a case where I need to do this . But the term `` more specific '' was loose enough to make me ponder this , and now I have to know ! : PUpdate : I guess I was n't really as interested in what will happen in the above example , as in why . It came to my mind since I 'd been doing stuff likewhere the compiler knows to choose the first method for new List < Something > ( ) .DoSomething ( ) , since it is `` closer '' to the type passed . What I was interested in then , was `` what does closer in this context mean ? How will the compiler react if the constraints are from two different inheritance chains ? Why ? '' <code> public MyClass : IComparable , IDisposable { // Implementation of members } public static class MyExtensions { public static void DoSomething < T > ( this T item ) where T : IComparable { /* whatever */ } public static void DoSomething < T > ( this T item ) where T : IDisposable { /* whatever else */ } } var instance = new MyClass ( ) ; instance.DoSomething ( ) ; public static class CollectionExtensions { public static void DoSomething < T > ( this T items ) where T : IList { ... } public static void DoSomething < T > ( this T items ) where T : IEnumerable { ... } } | Generic extension methods in C # : what will happen in this edge case ? |
C_sharp : I am trying to filter the results from an explicit load in EntityFramework.The explicit loading works when I do not apply any filter but it does not load results once the filter is applied.ClassesFluent API MappingUsageThis works and populates the student.Grades property.The SQL that is generated looks like this : When I run this query I get the full results.However , when I apply filtering and use the following line , it does not populate student.Grades.This line generates this query : When I run this manually against the DB I get the correctly filtered results within SQL Server . The problem is that this does n't populate student.Grades in the C # object . <code> public partial class Student { public int StudentId { get ; set ; } public int CourseId { get ; set ; } public string Name { get ; set ; } public string Status { get ; set ; } public virtual ICollection < Grade > Grades { get ; set ; } } public partial class Grade { public int GradeId { get ; set ; } public string Value { get ; set ; } public string Status { get ; set ; } public virtual ICollection < Student > Students { get ; set ; } } modelBuilder.Entity < Grade > ( ) .HasMany ( e = > e.Students ) .WithMany ( x = > x.Grades ) .Map ( m = > m.ToTable ( `` StudentGrades '' ) .MapLeftKey ( `` GradeId '' ) .MapRightKey ( `` StudentId '' ) ) ; using ( var context = new Model1 ( ) ) { context.Configuration.LazyLoadingEnabled = false ; var student = context.Students.Single ( x = > x.StudentId == 1 ) ; context.Entry ( student ) .Collection ( x = > x.Grades ) .Load ( ) ; } SELECT [ Extent2 ] . [ GradeId ] AS [ GradeId ] , [ Extent2 ] . [ Value ] AS [ Value ] , [ Extent2 ] . [ Status ] AS [ Status ] FROM [ dbo ] . [ StudentGrades ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ Grades ] AS [ Extent2 ] ON [ Extent1 ] . [ GradeId ] = [ Extent2 ] . [ GradeId ] WHERE [ Extent1 ] . [ StudentId ] = 1 // this is parameterized in the actual hit . context.Entry ( student ) .Collection ( x = > x.Grades ) .Query ( ) .Where ( x = > x.Status == `` A '' ) .Load ( ) ; SELECT [ Extent2 ] . [ GradeId ] AS [ GradeId ] , [ Extent2 ] . [ Value ] AS [ Value ] , [ Extent2 ] . [ Status ] AS [ Status ] FROM [ dbo ] . [ StudentGrades ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ Grades ] AS [ Extent2 ] ON [ Extent1 ] . [ GradeId ] = [ Extent2 ] . [ GradeId ] WHERE ( [ Extent1 ] . [ StudentId ] = 1 ) AND ( ' A ' = [ Extent2 ] . [ Status ] ) //the `` 1 '' is parameterized in the actual hit . | Explicit Loading N : M with Filtering |
C_sharp : In olden days , you often had a data module that was `` low level '' , did not depend on any other modules , but could be referenced by them , for example to get enums that were used throughout the system.Now we have object oriented interfaces between modules , with calls and events . My question is , should n't we still have one place where enums that are used throughout the system are defined , and these enums should be referenced by every interface that needs them ? I have seen software where essentially the same enum is re-defined on each interface , with translation functions for when it is passed on to another module.So for example , the interface IModule1 might haveand the interface IModule2 might havewhere module 1 for example collects data , module 2 performs some logic , and then passes data further to a 3rd module , e.g . a GUI.In many cases , the enums would be genuinely different , because for example , the 2nd module can abstract away some information that is n't needed by the 3rd module , and pass on a simplified version.But in some cases , they are n't different , and here it seems wrong to me that the enums are still re-defined on each interface.An example is an action that is carried out as part of several different use cases . The action is the same , but depending on the use case , several small details are different . An enum carrying details of the use case is passed over an interface to a high level logic module , and then on over another interface to a lower level module . It is redefined on each interface , and therefore must be translated in the high level logic module.There are some other modules which just translate older , existing interfaces to newer ones , and again , both interfaces have re-defined the same enum.Can anyone tell me which is best practice ? <code> enum module1_state { Unknown , NotRunning , Running } enum module2_state { Unknown , NotRunning , Running } | Re-defining the same enum on every object oriented interface in C # |
C_sharp : I am new to c # . I have text file with data in it but I want to read particular block line data.Here address can occur multiple times in text file . but i want to capture within thisI want to capture this ip from the block : I tried this code : Expected Output : my expected output is to capture the ip address from that block ie.10.4.1.10that ip is inside `` interface system '' block.. that makes that address as unique.. as there can be many ips with keyword address . So i want to take address which is inside interface system block.Please let me know how i can capture particular string from the block . <code> Something here ... ... ... ... interface `` system '' address 10.4.1.10/32 no shutdown exitsomething here ... ... ... ... address 101.4.1.11/32 interface `` system '' address 10.4.1.10/32 no shutdown exit 10.4.1.10 int counter = 0 ; string line ; // Read the file and display it line by line.System.IO.StreamReader file = new System.IO.StreamReader ( `` c : \\test.txt '' ) ; while ( ( line = file.ReadLine ( ) ) ! = null ) { Console.WriteLine ( line ) ; counter++ ; } file.Close ( ) ; // Suspend the screen.Console.ReadLine ( ) ; | Fetch particular string from particular block |
C_sharp : SAMPLE CODE : VS : Why is it that I always see people creating assigning PropertyChanged to a `` handler '' instead of just using it ? <code> public event PropertyChangedEventHandler PropertyChanged ; private void OnPropertyChanged ( String propertyName ) { PropertyChangedEventHandler handler = PropertyChanged ; if ( handler ! = null ) { handler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public event PropertyChangedEventHandler PropertyChanged ; private void OnPropertyChanged ( String propertyName ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } | Events - Handler vs direct access ? Why ? |
C_sharp : So I have this code here : What is the best method for me to call the Calculate ( n , time ) function for multiple n values ( given one after the other ) , but the same time . I already thought of using an array to store multiple n values , but is there a better option.Also I would like to pass multiple n 's as as arguments from the command line.Any ideas ? Thanks in advance ! <code> int n ; public static void Main ( string [ ] args ) { Console.Write ( `` Please insert a number : `` ) ; n = int.Parse ( Console.ReadLine ( ) ) ; Console.Write ( `` Please insert wait time ( 0,1 or 2 ) : `` ) ; int time = int.Parse ( Console.ReadLine ( ) ) *1000 ; Calculate ( n , time ) ; } | C # Calling a function with multiple values |
C_sharp : I have a string array . What is the simplest way to check if all the elements of the array are numbers <code> string [ ] str = new string [ ] { `` 23 '' , `` 25 '' , `` Ho '' } ; | Easiest way to check numbers |
C_sharp : I 'm running into a generics issue while working on a generic Dependency Injection handler ( a base Service Locator ) .Edit 1 ( for clarity ) Okay so I 'm actually using SimpleInjector as a DI resolver and it has the class constraint on it 's GetInstance method , so here is some more complete code : Edit 2 - final code since it looks strange in comments : <code> public T GetInstance < T > ( ) where T : class { try { // works return _container.GetInstance < T > ( ) ; } catch ( ActivationException aEx ) { return default ( T ) ; } } public T GetInstance < T > ( ) { try { if ( typeof ( T ) .IsClass ) { // does not work , T is not a reference type return _container.GetInstance < T > ( ) ; } } catch ( ActivationException aEx ) { return default ( T ) ; } } public T GetInstance < T > ( ) { try { if ( typeof ( T ) .IsClass ) { return ( T ) _container.GetInstance ( typeof ( T ) ) ; } } catch ( ActivationException aEx ) { return default ( T ) ; } } | How can you cast T to a class to match a `` where T : class '' constraint ? |
C_sharp : I have the following code for a compiled Linq2sql query to count rows in a table . The query throws an exception despite the same uncompiled query running smoothly : ServiceCustomContext inherits from DataContext and has only ( besides a constructor ) Tables including a table named Current used in the example above.And I get the following exception : 'Query was compiled for a different mapping source than the one associated with the specified DataContext . 'This is only when using , as above , a compiled query . As long as I have a simple : in the Count ( ) method , everything is fine.I do n't understand what 's wrong . I thought it might be that I need to keep a reference to the DataContext ( ServiceCustomContext ) although that seemed counter intuitive , but even the Microsoft examples do n't do that . The only explanation I 've found , is here which is basically that compiled queries as mentioned in the Microsoft examples in the link above are really wrong . I doubt that 's true though . <code> public static Func < ServiceCustomContext , int > CompiledCount = CompiledQuery.Compile ( ( ServiceCustomContext db ) = > db.Current.Count ( ) ) ; public static int Count ( ) { using ( ServiceCustomContext db = new ServiceCustomContext ( Constants.NewSqlConnection ) ) return CompiledCount ( db ) ; } return db.Current.Count ( ) ; | Compiled query fails - Query was compiled for a different mapping source than the one associated with the specified DataContext |
C_sharp : The root of my question is that the C # compiler is too smart . It detects a path via which an object could be undefined , so demands that I fill it . In the code , I look at the tables in a DataSet to see if there is one that I want . If not , I create a new one . I know that dtOut will always be assigned a value , but the the compiler is not happy unless it 's assigned a value when declared . This is inelegant.How do I rewrite this in a more elegant way ? <code> System.Data.DataTable dtOut = new System.Data.DataTable ( ) ; . . // find table with tablename = grp // if none , create new table bool bTableFound = false ; foreach ( System.Data.DataTable d1 in dsOut.Tables ) { string d1_name = d1.TableName ; if ( d1_name.Equals ( grp ) ) { dtOut = d1 ; bTableFound = true ; break ; } } if ( ! bTableFound ) dtOut = RptTable ( grp ) ; | How to avoid creating unneeded object in an elegant way ? |
C_sharp : I need to perform a check based on a string value whether its a date or decimal but date parse always return true for decimal.It returns a valid date 3/5/2019.How to validate string to know its a valid date when date format is not known ? <code> string val = `` 3.5 '' ; DateTime oDate = DateTime.Parse ( val ) ; | Decimal values recognized as DateTime instead of returning false from DateTime.Parse |
C_sharp : I have a grid which , when hovered over with the mouse , makes one of its child elements come to life ( opacity from 0 to 1 ) but that grid also can be disposed of ( that grid is part of a listbox that can be remove via a close button on the grid ) .When the user clicks the remove button it also launches the MouseLeave event below which of course can not find my DockStackPanel control anymore since it was disposed . How can I fix this issue ? <code> < Grid.Triggers > < EventTrigger RoutedEvent= '' UIElement.MouseEnter '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Duration= '' 0:0:0.5 '' Storyboard.TargetName= '' DockStackPanel '' Storyboard.TargetProperty= '' Opacity '' To= '' 1 '' / > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < EventTrigger RoutedEvent= '' UIElement.MouseLeave '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Duration= '' 0:0:0.5 '' Storyboard.TargetName= '' DockStackPanel '' Storyboard.TargetProperty= '' Opacity '' To= '' 0 '' / > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < /Grid.Triggers > | Block MouseLeave trigger if object is disposed of |
C_sharp : I can not understand why the code below compiles.At the compile time it is obvious that ( s+1 ) is not a Int16 anymore as we know the value of s.And CLR allows casting to : To its own typeOr any of the base-types ( because it is safe ) As Int32 is not Int16 and Int16 is not base type of Int32.Question : So why the compiler does not fail for the casting above ? Can you please explaint it from the CLR and compiler point of view ? Thanks <code> public void Overflow ( ) { Int16 s = 32767 ; s = ( Int16 ) ( s + 1 ) ; } | Why does C # compiler does not complain with Overflow for this obvious 'bad ' casting ? |
C_sharp : Reading the Jon Skeet book , I have found ( some time now ) the use of the `` Named arguments '' in the function call . Here is a fast and easy example : After using it and later see the compiled code I see that the use of this name actually create variables before the call of the function . And this is the created code : and the full compiled code , you see how bigger is I call it using the `` Named Arguments '' So this is one point that c # have forget to optimize , or is there any other use of them ? Follow upI like to clear that the code above is what the compile produce . Here is what I get with the answer from Servy . <code> void Dump ( int x , int y , int z , string cSomeText ) { // no use , just to see how we call this later string cOnMe = string.Format ( `` [ { 0 } ] [ { 1 } ] [ { 2 } ] [ { 3 } ] '' , x , y , z , cSomeText ) ; } void CallDumpWithoutNameArguments ( ) { // call with out Name Arguments Dump ( 1 , 2 , 3 , `` Test string '' ) ; } void CallDumpWithNameArguments ( ) { // more easy to read , call the same function with Name Arguments Dump ( x : 1 , y : 2 , z : 3 , cSomeText : `` Test string '' ) ; } private void CallDumpWithoutNameArguments ( ) { this.Dump ( 1 , 2 , 3 , `` Test string '' ) ; } private void CallDumpWithNameArguments ( ) { int CS $ 0 $ 0000 = 1 ; int CS $ 0 $ 0001 = 2 ; int CS $ 0 $ 0002 = 3 ; string CS $ 0 $ 0003 = `` Test string '' ; this.Dump ( CS $ 0 $ 0000 , CS $ 0 $ 0001 , CS $ 0 $ 0002 , CS $ 0 $ 0003 ) ; } .method private hidebysig instance void CallDumpWithoutNameArguments ( ) { .maxstack 8 nop ldarg.0 ldc.i4.1 ldc.i4.2 ldc.i4.3 ldstr `` Test string '' call instance void SubSonic.BabisExtrasNoUseIt.ExtraTestCode : :Dump ( int32 x , int32 y , int32 z , string cSomeText ) nop ret } .method private hidebysig instance void CallDumpWithNameArguments ( ) { .maxstack 5 .locals init ( int32 V0 , int32 V1 , int32 V2 , string V3 ) nop ldarg.0 ldc.i4.1 stloc.0 ldc.i4.2 stloc.1 ldc.i4.3 stloc.2 ldstr `` Test string '' stloc.3 ldloc.0 ldloc.1 ldloc.2 ldloc.3 call instance void SubSonic.BabisExtrasNoUseIt.ExtraTestCode : :Dump ( int32 x , int32 y , int32 z , string cSomeText ) nop ret } private void CallDumpWithoutNameArguments ( ) { // what generated from // int i = 0 ; // Dump ( i++ , i++ , i++ , cSomeText : `` Test string '' ) ; int i = 0 ; string CS $ 0 $ 0000 = `` Test string '' ; this.Dump ( i++ , i++ , i++ , CS $ 0 $ 0000 ) ; } private void CallDumpWithNameArguments ( ) { // what is generate from // int i = 0 ; // Dump ( x : i++ , z : i++ , y : i++ , cSomeText : `` Test string '' ) ; int i = 0 ; int CS $ 0 $ 0000 = i++ ; int CS $ 0 $ 0001 = i++ ; int CS $ 0 $ 0002 = i++ ; string CS $ 0 $ 0003 = `` Test string '' ; this.Dump ( CS $ 0 $ 0000 , CS $ 0 $ 0002 , CS $ 0 $ 0001 , CS $ 0 $ 0003 ) ; } | Why the use of name arguments in a function actually generate more code ? |
C_sharp : I 'm running CultureInfo 1031 ( german ) . IndexOf matches 'straße ' or 'strasse ' with defined 'strasse ' and returns 18 as position . Neither Remove nor Replace got any overload for setting a culture.If I remove 6 chars using Remove 1 character will be left if input-string is 'strasse ' and 'straße ' will work . If input-string is 'straße ' and I remove 7 chars I get ArgumentOutOfRangeException.Is there a way to safely remove the found string ? Any method which provides the last index of IndexOf ? I stepped closer into IndexOf and it 's native code under the hood as expected - so no way to do something own ... <code> string s = `` Gewerbegebiet Waldstraße '' ; //other possible input `` Waldstrasse '' int iFoundStart = s.IndexOf ( `` strasse '' , StringComparison.CurrentCulture ) ; if ( iFoundStart > -1 ) s = s.Remove ( iFoundStart , 7 ) ; | ArgumentOutOfRangeException using IndexOf with CultureInfo 1031 |
C_sharp : Am stuck with small problem.I want to add multiple setConditions for the same Name that is for PublicationTarget . This is using interops dll.For this PublicationTarget , I want to filter with staging & live target and I tried all the ways but no use.Please suggest,1 . Passing xis possible , what is the best way to achieve ? I tried this ways but no luck ; -List < string > <code> ListRowFilter rowFilter = mTDSE.CreateListRowFilter ( ) ; rowFilter.SetCondition ( `` StartDate '' , sDate ) ; rowFilter.SetCondition ( `` EndDate '' , eDate ) ; rowFilter.SetCondition ( `` PublicationTarget '' , pubStgTarget ) ; rowFilter.SetCondition ( `` PublicationTarget '' , pubStgTarget ) ; rowFilter.SetCondition ( `` PublicationTarget '' , `` tcm:0-1-65537 '' ) ; // Gives only stagingrowFilter.SetCondition ( `` PublicationTarget '' , `` tcm:0-2-65537 '' ) ; // Gives only LiverowFilter.SetCondition ( `` PublicationTarget '' , `` tcm:0-1-65537|tcm:0-1-65537 '' ) ; // No resultrowFilter.SetCondition ( `` PublicationTarget '' , oPubList ) ; // No result - ` oPubList ` is a | Tridion 2009 - Using Interops - Is there a possibility to add multiple setConditions for the same Name |
C_sharp : FSharp code is structured as following ( I 'm not in control of the source ) .C # calling code is as follows <code> namespace FS [ < AbstractClass ; Sealed > ] type TestType ( ) = static member IrrelevantFunction ( ) = 0 [ < AutoOpen > ] module Extensions = type TestType with //How do we call this from C # static member NeedToCallThis ( ) = 0module Caller = let CallIt ( ) = //F # can call it TestType.NeedToCallThis ( ) public void Caller ( ) { TestType.IrrelevantFunction ( ) ; //We want to call this //TestType.NeedToCallThis ( ) ; //Metadata : //namespace FS // { // [ Microsoft.FSharp.Core.AutoOpenAttribute ] // [ Microsoft.FSharp.Core.CompilationMappingAttribute ] // public static class Extensions // { // public static int TestType.NeedToCallThis.Static ( ) ; // } // } //None of these compile //TestType.NeedToCallThis ( ) ; //Extensions.TestType.NeedToCallThis.Static ( ) ; //Extensions.TestType.NeedToCallThis ( ) ; } | How to call F # type extensions ( static member functions ) from C # |
C_sharp : I 'm converting some application code to use NodaTime classes instead of System.DateTime . Part of my application uses the PropertyGrid control to allow a user to edit a class containing both a LocalDate and an Instant . Without changing anything , the PropertyGrid displays the properties okay , but they are no longer editable . What 's the best way of allowing the user to edit these fields.For the sake of exposition , we can use this class as a representative of the type of thing I 'd like to display and edit : <code> public class User { public string Name { get ; set ; } public LocalDate BirthDate { get ; set ; } public Instant NextAppointment { get ; set ; } } | How do you use NodaTime Classes in a PropertyGrid ? |
C_sharp : I 'm looking at the MSDN docs about List.GetEnumerator.They say the C # method signature is : I was expecting this much simpler signature : What does their signature mean , with all the punctuation and the `` Of '' keyword ? Edit : Well , I guess if no one has seen that syntax , then the MSDN docs are just a bit buggy , and that 's all . <code> public List < ( Of < ( < 'T > ) > ) > .. : :..Enumerator GetEnumerator ( ) public List < T > .Enumerator GetEnumerator ( ) | public List < ( Of < ( < 'T > ) > ) > .. : :..Enumerator ? |
C_sharp : I am either going crazy or missing something entirely here . I have a time entry I am trying to submit with a `` TimeWorked '' attribute whose data type in the SQL server is decimal ( 4,2 ) .When I try to add a time entry with 10.00 as the value for TimeWorked , I get the following error.ErrorCode To InsertDatabase ModelDatabase data types : What I have tried : I have tried a few things . I tried adding a Range ( 0,10 ) data annotation to the model for the database . I increased the precision of the decimal to ( 18,4 ) just to see if it would accept it.I was able to manually insert a value of 10 into the database directly in SSMS so I am not quite sure how that is working but my code to insert does not ? EditI also tried adding 10 directly to the timeworked attribute from my code and it still threw the error . I am inspecting the data before inserting and it shows up as 10 as well . <code> using ( var context = new ProjectTrackingDb ( ) ) { TimeEntry entry = new TimeEntry { ProjectName = SelectedProject.ProjectName , Phase = SelectedProject.Phase , Code = SelectedClassification.Code , TimeWorked = TimeEntry.TimeWorked , Description = TimeEntry.Description , UserName = CurrentUserName , Date = TimeEntry.Date } ; context.TimeEntries.Add ( entry ) ; context.SaveChanges ( ) ; } [ Table ( `` TimeEntry '' ) ] public partial class TimeEntry { [ Key ] public int EntryID { get ; set ; } public decimal TimeWorked { get ; set ; } [ Column ( TypeName = `` text '' ) ] [ Required ] public string Description { get ; set ; } [ Column ( TypeName = `` date '' ) ] public DateTime Date { get ; set ; } [ StringLength ( 20 ) ] public string UserName { get ; set ; } [ StringLength ( 30 ) ] public string ProjectName { get ; set ; } [ StringLength ( 30 ) ] public string Phase { get ; set ; } [ StringLength ( 2 ) ] public string Code { get ; set ; } } | Argument out of range exception for decimal SQL Server EF C # |
C_sharp : I 'm trying to work with the optgroup dropdown helper from Serge Zab that can be found here.This is my category table : As you can see I have a category and a category can also be categoryparent from a category . I want to have the parentcategorys as optgroup and the children as options of the optgroup . ( Only the children can be selected ) In my ViewModel : In my Controller : In my View : When I try to run this I always get the error : I get this error on this rule : .OrderBy ( t = > t.ParentCategory.Name ) .ThenBy ( t = > t.Name ) Can anybody help me find a solution for this problem ? <code> public short ? CategoryId { get ; set ; } public IEnumerable < ReUzze.Helpers.GroupedSelectListItem > GroupedTypeOptions { get ; set ; } [ Authorize ] // USER NEEDS TO BE AUTHORIZEDpublic ActionResult Create ( ) { ViewBag.DropDownList = ReUzze.Helpers.EnumHelper.SelectListFor < Condition > ( ) ; var model = new ReUzze.Models.EntityViewModel ( ) ; PutTypeDropDownInto ( model ) ; return View ( model ) ; } [ NonAction ] private void PutTypeDropDownInto ( ReUzze.Models.EntityViewModel model ) { model.GroupedTypeOptions = this.UnitOfWork.CategoryRepository.Get ( ) .OrderBy ( t = > t.ParentCategory.Name ) .ThenBy ( t = > t.Name ) .Select ( t = > new GroupedSelectListItem { GroupKey = t.ParentId.ToString ( ) , GroupName = t.ParentCategory.Name , Text = t.Name , Value = t.Id.ToString ( ) } ) ; } @ Html.DropDownGroupListFor ( m = > m.CategoryId , Model.GroupedTypeOptions , `` [ Select a type ] '' ) Object reference not set to an instance of an object . | Error using Serge Zab 's helper for optgroup dropdowns |
C_sharp : I have a hypothetical question about the efficiency consequences of using exception handling in situations where no exceptions are thrown . First take a look at this C # : I am confident that Dave 's code will be the fastest/most efficient ; while Simon will incur a large penalty for throwing an exception.But what about Carol ? As she throws no exceptions does she incur a penalty ? If so , then what kind and how large ? ( Performance penalty or extra memory usage or anything else ? ) <code> int simpleSimon , cautiousCarol , dangerousDave ; try { simpleSimon = int.Parse ( `` fail '' ) ; } catch { simpleSimon = 1 ; } try { cautiousCarol = int.Parse ( `` 1 '' ) ; } catch { cautiousCarol = 1 ; } dangerousDave = int.Parse ( `` 1 '' ) ; | Exception efficiency when nothing is thrown |
C_sharp : In case the title is not completely self-explanatory , here 's the code that puzzles me : I 'm suprised this compiles with no error . It feels like I 'm exposing a private type . Should n't this be illegal ? Maybe your answers will simply be `` There 's no rule against that , so why would n't it be OK ? '' Perhaps it 's equally surprising that MyClass.NestedInMyClass is even in `` scope '' . If I remove the MyClass . qualification , it will not compile . ( If I change IFoo < > into a generic class , which should then become base class of MyClass , this is illegal , for a base type must be at least as accessible as the type itself . ) I tried this with the C # 4 compiler of Visual Studio 2010 . <code> public interface IFoo < T > { } public class MyClass : IFoo < MyClass.NestedInMyClass > { private class NestedInMyClass { } } | Why is it not `` inconsistent accessibility '' to use a private nested type inside a generic type in the interface list ? |
C_sharp : I am working on a project where the game world is irregularly shaped ( Think of the shape of a lake ) . this shape has a grid with coordinates placed over it . The game world is only on the inside of the shape . ( Once again , think Lake ) How can I efficiently represent the game world ? I know that many worlds are basically square , and work well in a 2 or 3 dimension array . I feel like if I use an array that is square , then I am basically wasting space , and increasing the amount of time that I need to iterate through the array . However , I am not sure how a jagged array would work here either.Example shape of gameworldEdit : The game world will most likely need each valid location stepped through . So I would a method that makes it easy to do so . <code> XXX XX X XX XXX XXX XXXXXXXXXXXXXXX XXXXX XX XX X X | Representing a Gameworld that is Irregularly shaped |
C_sharp : I am facing a problem with UpdateSourceTrigger property . I have a UserControl named LabelWithTextBox , where UpdateSourceTrigger ( On Text Property ) is not defined ( therefore has default value ) . This should stay like this because of performance ( Text should update when Focus is out of the TextBox ) .But now I have a case where the UserControl should be used and the update should happen as the user types , therefore I want to set UpdateSourceTrigger to PropertyChanged.Ideally the best solution would be if the UpdateSourceTrigger property could be inherited . The user uses in his View the UserControl and defines UpdateSourceTrigger = PropertyChanged , this information is handed over to my UserControl and everything works as expected . Does anyone know how I can archive this ? What other options do I have ? How can I change the UpdateSourceTrigger Property at runtime ? Here is the relevant UserControl ( Code Behind ) Code : And here is the UserControl ( Xaml ) Code : If add UpdateSourceTrigger = PropertyChanged to Text everything will work as expected . But I do not want that.Here is for example how someone could use the UserControl in his View . What I am looking for is a way to hand over the value of the UpdateSourceTrigger to my UserControl , but how ? <code> public static readonly DependencyProperty TextProperty = DependencyProperty.Register ( `` Text '' , typeof ( string ) , typeof ( LabelWithTextBox ) , new FrameworkPropertyMetadata ( string.Empty , FrameworkPropertyMetadataOptions.BindsTwoWayByDefault ) ) ; public string Text { get { return ( string ) this.GetValue ( TextProperty ) ; } set { this.SetValue ( TextProperty , value ) ; } } < Grid Grid.Column= '' 1 '' > < telerik : RadWatermarkTextBox TextChanged= '' TextBoxBase_OnTextChanged '' Name= '' TextBox '' Text= '' { Binding Text , Mode=TwoWay , ElementName=userControl } '' WatermarkContent= '' { Binding Placeholder , Mode=TwoWay , ElementName=userControl } '' TextWrapping= '' { Binding TextWrap , Mode=TwoWay , ElementName=userControl } '' AcceptsReturn= '' { Binding AcceptsReturn , Mode=TwoWay , ElementName=userControl } '' VerticalScrollBarVisibility= '' { Binding VerticalScrollBarVisibility , Mode=TwoWay , ElementName=userControl } '' MinLines= '' { Binding MinLines , Mode=TwoWay , ElementName=userControl } '' MaxLines= '' { Binding MaxLines , Mode=TwoWay , ElementName=userControl } '' IsReadOnly= '' { Binding IsReadOnly , ElementName=userControl } '' / > ... . < controls : LabelWithTextBox Grid.Row= '' 1 '' Margin= '' 0,5,0,0 '' Label= '' Excel Blattname : '' SharedSizeGroup= '' LabelsX '' Text= '' { Binding SheetName , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' / > | How to hand over the value of UpdateSourceTrigger to UserControl or update it at runtime ? |
C_sharp : Looking for a some help with Ef Core and Linq.Lets say I 'm making big request to receive all support tickets with info about product , company , and so on . It 's quite simple , just joining things : However I have issues with last 4 joins . In project I 'm using Ef Core . That is how I made it ( partially ) : To receive data I 'm using repository pattern . And then all data mapped to ViewModel using AutoMapper . This is how my ViewModel looks like : Now I try to get info about Company ( AbpTenants ) with info about Edition ( one to many relationship ) and List of TicketLinkedUsers ( many to many relationship ) with TicketLinkType info . Schema : I can receive all required data using additional joins , however I do n't know how to correctly bind and map data to GetTicketForView . List of LinkedUsers and Tenant with nested mapping of Edition is an issue here . Right now I 'm doing separate request for each ticket to make many-to-many work : Which is a time-consuming , cause I can get all data in one request using o8 and 09 , but I make additional request for each ticket . Do n't have enough experience to make it right.So the question is , how can I implement the first request using linq and map it to ViewModel . Should I use additional request ? Or it will be better to use Ef Core Api to make a complex request ? Or it 's not possible to map complex things inside linq ? Thanks in advance <code> select * from Tickets Tleft join Products P on T.ProductId = P.Id left join ProductVersions PV on T.ProductVersionId = PV.Id left join TicketTypes TT on T.TicketTypeId = TT.Id left join TicketPriorities TP on T.TicketPriorityId = TP.Id left join TicketStates TS on T.TicketStateId = TS.Id left join AbpTenants A on T.TenantId = A.Id left join AbpEditions E on A.EditionId = E.Id left join TicketLinkedUsers TLU on TLU.TicketId = T.Id left join TicketLinkTypes TLT on TLT.Id = TLU.TicketLinkTypeId var query = ( from o in filteredTickets join o1 in _productRepository.GetAll ( ) on o.ProductId equals o1.Id into j1 from s1 in j1.DefaultIfEmpty ( ) join o2 in _productVersionRepository.GetAll ( ) on o.ProductVersionId equals o2.Id into j2 from s2 in j2.DefaultIfEmpty ( ) join o3 in _ticketTypeRepository.GetAll ( ) on o.TicketTypeId equals o3.Id into j3 from s3 in j3.DefaultIfEmpty ( ) join o4 in _ticketPriorityRepository.GetAll ( ) on o.TicketPriorityId equals o4.Id into j4 from s4 in j4.DefaultIfEmpty ( ) join o5 in _ticketStateRepository.GetAll ( ) on o.TicketStateId equals o5.Id into j5 from s5 in j5.DefaultIfEmpty ( ) join o6 in _tenantManager.Tenants on o.TenantId equals o6.Id into j6 from s6 in j6.DefaultIfEmpty ( ) // join o7 in _editionaRepository.GetAll ( ) on s6.EditionId equals o7.Id into j7 // from s7 in j7.DefaultIfEmpty ( ) // join o8 in _ticketLinkedUsersRepository.GetAll ( ) on o.Id equals o8.TicketId into j8 // from s8 in j8.DefaultIfEmpty ( ) // join o9 in _ticketLinkTypesRepository.GetAll ( ) on s9.TicketLinkTypeId equals o9.Id into j9 // from s9 in j9.DefaultIfEmpty ( ) select new GetTicketForView ( ) { Ticket = ObjectMapper.Map < TicketDto > ( o ) , ProductName = s1 == null ? `` '' : s1.Name.ToString ( ) , ProductVersionName = s2 == null ? `` '' : s2.Name.ToString ( ) , TicketTypeName = s3 == null ? `` '' : s3.Name.ToString ( ) , TicketPriorityName = s4 == null ? `` '' : s4.Name.ToString ( ) , TicketState = ObjectMapper.Map < TicketStateTableDto > ( s5 ) , Tenant = ObjectMapper.Map < TenantShortInfoDto > ( s6 ) } ) public class GetTicketForView { public TicketDto Ticket { get ; set ; } public TenantShortInfoDto Tenant { get ; set ; } public string ProductName { get ; set ; } public string ProductVersionName { get ; set ; } public TicketStateTableDto TicketState { get ; set ; } public string TicketTypeName { get ; set ; } public string TicketPriorityName { get ; set ; } public List < TicketLinkedUserDto > LinkedUsers { get ; set ; } } // execute to get ticketstickets = await query .OrderBy ( input.Sorting ? ? `` ticket.id asc '' ) .PageBy ( input ) .ToListAsync ( ) ; // then for each ticket get related users : foreach ( var ticket in tickets ) { var linkedUsers = _ticketLinkedUsersRepository .GetAllIncluding ( lu = > lu.TicketLinkType , lu = > lu.User ) .OrderBy ( a = > a.TicketLinkType.Ordinal ) .Where ( p = > p.TicketId == ticket.Ticket.Id ) .ToList ( ) ; ticket.LinkedUsers = ObjectMapper.Map < List < TicketLinkedUserDto > > ( linkedUsers ) ; } | How to map complex linq to object |
C_sharp : Why the Linq expression IL results in omission of the Select projection whereas the corresponding method expression keeps the Select projection ? I suppose these two pieces of code does the same.Then why the difference in IL ? EDITED : then why result in SELECT projection even inside IL . it can also be omitted right ? <code> var a = from c in companies where c.Length > 10 select c ; //var b = companies.Where ( c = > c.Length > 10 ) .Select ( c = > c ) ; //IL - LINQIEnumerable < string > a = this.companies.Where < string > ( CS $ < > 9__CachedAnonymousMethodDelegate1 ) ; //IL IEnumerable < string > b = this.companies.Where < string > ( CS $ < > 9__CachedAnonymousMethodDelegate4 ) .Select < string , string > ( CS $ < > 9__CachedAnonymousMethodDelegate5 ) ; var a = from c in companies select c ; | Differences in LINQ vs Method expression |
C_sharp : I want to understand how chain query is processed . For example , let us consider the following querywhere e.g . numbers= { -1 , 4 , 9 } .Is this what happends behind the scene:1 . Getting all enumerators ( forward pass ) numbers calls GetEnumerator ( ) which returns ( let us denote it with ) IEnum0 instanceIEnum0 calls GetEnumerator ( ) which returns IEnum1 instanceIEnum1 calls GetEnumerator ( ) which returns IEnum2 instanceIEnum2 calls GetEnumerator ( ) which returns IEnum3 instance2 . Calling MoveNext ( backward pass ) .Sum ( ) calls MoveNext ( ) on IEnum3IEnum3 calls MoveNext ( ) on IEnum2IEnum2 calls MoveNext ( ) on IEnum1IEnum1 calls MoveNext ( ) on IEnum03 . Returning from MoveNext ( forward-backward pass ) IEnum0 moves to element -1 and return true.IEnum1 check if -1 satisfy condition ( which is not true ) so IEnum1 calls MoveNext ( ) on IEnum0.IEnum0 moves to element 4 and return true.IEnum1 check if 4 satisfy condition ( which is true ) and returns trueIEnum2 does nothing , just return output of IEnum1 which is trueIEnum2 does nothing , just return output of IEnum2 which is true4 . Calling Current ( backward pass ) .Sum ( ) calls Current on IEnum3.IEnum3 calls Current on IEnum2IEnum2 calls Current on IEnum1IEnum1 calls Current on IEnum05 . Returning Current ( forward pass ) IEnum0 returns 4IEnum1 returns 4IEnum2 returns sqrt ( 4 ) =2IEnum3 returns exp ( 2 ) 6 . Repeat steps 2.-5. until step 3. returns falsePlease correct me if a chain query is processed in a different way . <code> var sumOfRoots = numbers //IEnum0 .Where ( x = > x > 0 ) //IEnum1 .Select ( x = > Math.Sqrt ( x ) ) //IEnum2 .Select ( x = > Math.Exp ( x ) ) //IEnum3 .Sum ( ) ; | Linq : Order of execution chain query |
C_sharp : This is not really a question , but an answer which would hopefully help other people.Those who 've written a windows service before , know what a mission it could be to find a bug in it , particularly if it only happens on the live environment . In my case , I had a service that ran smoothly for a couple of hours , and then fell over from a stack overflow error . No stack trace . Good luck finding the needle in the haystack.The service did produce a log file , and the code was littered with log entries , but as detailed as is was , it produced log files of 500 MB ! You could barely open the file , never mind analyse it . But how do you get around this problem ? You could try to produce log files with less information , or one that automatically delete older logs entries as newer ones are being written , but then you loose important context of the error.The solution is a log file that will keep track of loops in your code , and automatically delete the log entries for each successful iteration of that loop . This way , you can maintain a highly detained log file which remains relatively small at the same time . When your service breaks , your log file will tell you exactly where it happened , plus all the necessary context to explain how and why it happened . You can download this logfile generator from http : //sourceforge.net/projects/smartl/files/ ? source=navbar . It 's a stand alone class and all its methods is static . An example class is provided to show you how to use the logging methods correctly : Make sure your application has read and write access on its root folder . If you execute the code , and you break it inside the loop , the logfile will look something like this : Once the loop has been completed , its content is removed , and your log file will look like this : I hope this can help someone solve that problem which otherwise could 've taken weeks . It sure did the trick for me . <code> public void ExampleMethod ( ) { SmartLog.EnterMethod ( `` ExampleMethod ( ) '' ) ; try { SmartLog.Write ( `` Some code happening before the loop '' ) ; Guid exampleLoopID = SmartLog.RegisterLoop ( `` exampleLoopID '' ) ; for ( int i = 0 ; i < 10 ; i++ ) { SmartLog.IncrementLoop ( exampleLoopID ) ; SmartLog.Write ( `` Some code happening inside the loop . `` ) ; } SmartLog.CompleteLoop ( exampleLoopID ) ; SmartLog.Write ( `` Some code happening after the loop . `` ) ; SmartLog.LeaveMethod ( `` ExampleMethod ( ) '' ) ; } catch ( Exception ex ) { SmartLog.WriteException ( ex ) ; SmartLog.LeaveMethod ( `` ExampleMethod ( ) '' ) ; throw ; } } . ENTER METHOD : FirstMethod ( ) some code happening here.Calling a different method : . . ENTER METHOD : ExampleMethod ( ) some code happening before the loop.LOOP : doWorkLoopID [ 4135a8ed-05b7-45de-b887-b2ab3c638faa ] - CURRENT ITERATION : 20some code happening inside the loop . . ENTER METHOD : FirstMethod ( ) some code happening here.Calling a different method : . . ENTER METHOD : ExampleMethod ( ) some code happening before the loop.LOOP : doWorkLoopID [ 4135a8ed-05b7-45de-b887-b2ab3c638faa ] - TOTAL ITERATIONS : 22some code happening after the loop.. . LEAVING METHOD : ExampleMethod ( ) some code happening here.some code happening here.. LEAVING METHOD : FirstMethod ( ) | Debugging Stack overflow errors on background services |
C_sharp : Is there any downside to a class like : If I always want to set this value is there any downside to Example1 ? UPDATE : Session [ `` user '' ] is set in the Global.asax Session_Start . So if this fails . Nothing should work anyways . <code> class Example1 { protected string UserId = ( string ) Session [ `` user '' ] ; } //versusclass Example2 { protected string UserId ; public Example2 ( ) { UserId = ( string ) Session [ `` user '' ] ; } } | C # - Downside to Setting Initial Value in Declaration |
C_sharp : http : //msdn.microsoft.com/en-us/library/1x308yk8.aspxThis allows me to do this : Rather than : Seems unusual , so I looked at the reflection : Three things struck me : Why does it bother to do the limit check only on the upper bound ? Throwing an ArgumentOutOfRangeException , while index below 0 would give string 's standard IndexOutOfRangeExceptionThe precense of SecuritySafeCriticalAttribute which I 've read the general blerb about , but still unclear what it is doing here and if it is linked to the upper bound check.TargetedPatchingOptOutAttribute is not present on other Is ... ( char ) methods . Example IsLetter , IsNumber etc . <code> var str = `` string `` ; Char.IsWhiteSpace ( str , 6 ) ; Char.IsWhiteSpace ( str [ 6 ] ) ; [ TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] public static bool IsWhiteSpace ( char c ) { if ( char.IsLatin1 ( c ) ) { return char.IsWhiteSpaceLatin1 ( c ) ; } return CharUnicodeInfo.IsWhiteSpace ( c ) ; } [ SecuritySafeCritical ] public static bool IsWhiteSpace ( string s , int index ) { if ( s == null ) { throw new ArgumentNullException ( `` s '' ) ; } if ( index > = s.Length ) { throw new ArgumentOutOfRangeException ( `` index '' ) ; } if ( char.IsLatin1 ( s [ index ] ) ) { return char.IsWhiteSpaceLatin1 ( s [ index ] ) ; } return CharUnicodeInfo.IsWhiteSpace ( s , index ) ; } | Why does every Char static `` Is ... '' have a string overload , e.g . IsWhiteSpace ( string , Int32 ) ? |
C_sharp : I have created the following to expose some data as a regex match string as well as a StringDictionary . It feels like I could do this using LINQ with fewer lines . <code> private const string STREETTYPES = @ '' ALY|Alley|AVE|Avenue|BLVD|Boulevard|CIR|Circle|CT|Court|CTR|Center|DR|Drive|EXPY|Expressway|FWY|Freeway|HALL|Hall|HWY|Highway|JCT|Junction|LN|Lane|LP|Loop|PIKE|Pike|PKWY|Parkway|PL|Place|RD|Road|ST|Street|TER|Terrace|TPKE|Turnpike|TRL|Trail|WAY|Way '' ; private static StringDictionary streetTypes = null ; public static StringDictionary StreetTypes { get { if ( streetTypes ! = null ) return streetTypes ; streetTypes = new StringDictionary ( ) ; var streetArray = STREETTYPES.Split ( PIPE ) ; for ( int i = 0 ; i < streetArray.Length-1 ; i = i+2 ) { streetTypes.Add ( streetArray [ i ] , streetArray [ i + 1 ] ) ; } return streetTypes ; } } | Looking for a slicker way to convert delimited string to StringDictionary |
C_sharp : I have a command as below . I find if I use a file pattern of *.csv it also picks up items with a .csvx extension . Maybe it 's a throwback to the 8.3 filename days - anyone know a way that would return them properly , preferably without rolling our own ? <code> files = ( from file in Directory.EnumerateFiles ( sourceFolder , filePattern , SearchOption.TopDirectoryOnly ) select file ) .ToList ( ) ; | .Net file pattern picks up unwanted files ( C # ) |
C_sharp : Possible Duplicate : Can I customize automatic event handler generation in Visual Studio ? Can I configure VS2010 Intellisense so that it does this : instead of this : when adding an EventHandler via += and pressing the Shift key ? I understand that this does n't make any difference as far as the generated IL is concerned but I personally much prefer the first version . It is easier to read and I do n't have to go and fix the += / -= calls when I go and change the EventHandler type to something different . <code> SomeEvent += Some_Method ; SomeEvent += new EventHandler ( Some_Method ) ; | Configure VS 2010 so that it does n't add new EventHandler ( ... ) ; when adding an EventHandler via += |
C_sharp : I asked this question . This code does n't compile ( `` Can not convert Generic < T > to T '' ) because of the reason explained here ( even if I 'd expect an InvalidCastException at run-time instead of a compile-time error ) .Accepted solution gave this workaround : My question is : why ? as operator should be exactly equivalent to cast operator : The as operator is like a cast operation . However , if the conversion is n't possible , as returns null instead of raising an exception.If this as T should be equivalent to this is T ? ( T ) this : ( T ) null then why as T works and ( T ) this does n't even compile ? AFAIK cast could be used in a more wide range of situations than as : Note that the as operator performs only reference conversions , nullable conversions , and boxing conversions . The as operator ca n't perform other conversions , such as user-defined conversions , which should instead be performed by using cast expressions.Then why this ? Is it a documented feature of as operator ? Is it a compiler/language limitation with generic types ? Note that this code compiles fine : Is this because compiler ca n't be sure if T is dynamic ( even if there is a where constraint ) then it 'll always generate such code ? <code> class NonGeneric { } class Generic < T > : NonGeneric where T : NonGeneric { T DoSomething ( ) { return ( T ) this ; // ** Can not convert ... } } T DoSomething ( ) { return this as T ; } return ( T ) ( ( object ) this ) ; | Unexpected behavior of `` as '' operator , it differs from plain cast |
C_sharp : I 've recently started a project that involves using data from a London Ungerground dataset , in order to find routes that are n amount of minutes from a given station . So far I have been able to parse in the data from the dataset , and create possible routes between each station . I have now a list of route objects which have the following properties : The data I currently have , using VICTORIA as a starting station is : i 've formatted my output to make it easier to read , but each line is a representation of a route object . So you have the starting station , the time , the next station , and the line.What would be the best method to gather all the possible routes , from VICTORIA ? For example : <code> Parent - the first stationChild - the next linked stationLine - whichever line the station is onTime - the time between the two stations VICTORIA = > 1 < = PIMLICO : VictoriaVICTORIA = > 2 < = GREEN PARK : VictoriaVICTORIA = > 2 < = ST JAMES PARK : CircleVICTORIA = > 2 < = SLOANE SQUARE : CirclePIMLICO = > 2 < = VAUXHALL : VictoriaGREEN PARK = > 2 < = OXFORD CIRCUS : VictoriaGREEN PARK = > 1 < = WESTMINSTER : JubileeGREEN PARK = > 2 < = BOND STREET : JubileeGREEN PARK = > 1 < = PICCADILLY CIRCUS : PiccadillyGREEN PARK = > 1 < = HYDE PARK CORNER : PiccadillyST JAMES PARK = > 1 < = WESTMINSTER : CircleSLOANE SQUARE = > 1 < = SOUTH KENSINGTON : CircleVAUXHALL = > 2 < = STOCKWELL : VictoriaVAUXHALL = > 2 < = PIMLICO : VictoriaOXFORD CIRCUS = > 1 < = PICCADILLY CIRCUS : BakerlooOXFORD CIRCUS = > 2 < = REGENTS PARK : BakerlooOXFORD CIRCUS = > 2 < = TOTTENHAM COURT ROAD : CentralOXFORD CIRCUS = > 1 < = BOND STREET : CentralOXFORD CIRCUS = > 2 < = GREEN PARK : VictoriaOXFORD CIRCUS = > 1 < = WARREN STREET : Victoria VICTORIA > GREEN PARK > WESTMINSTERVICTORIA > GREEN PARK > BOND STREETVICTORIA > PIMLICO > VAUXHALL | How do I do list traversal ? |
C_sharp : I am not able to figure out the Valid points which can justify that I broke encapsulation or may be otherwise . As per my understanding I am breaking encapsulation as a private method is getting called from another class , Is this enough for justifying that I broke on the laws of OOP . Need to gather some more inner concepts and descrption for the code above . <code> class Program { static void Main ( string [ ] args ) { B b = new B ( ) ; b.Run ( ) ; Console.Read ( ) ; } } class A { public event Action onChanged ; public void Raise ( ) { if ( onChanged ! = null ) onChanged ( ) ; } } class B { public void Run ( ) { A a = new A ( ) ; a.onChanged += a_onChanged ; a.Raise ( ) ; } private void a_onChanged ( ) { Console.WriteLine ( `` Wow ! Invoked '' ) ; } } | Did I break Encapsulation ? |
C_sharp : I have an array of PropertyInfo representing the properties in a class . Some of these properties are of type ICollection < T > , but T varies across the properties - I have some ICollection < string > , some ICollection < int > , etc.I can easily identify which of the properties are of type ICollection < > by using the GetGenericTypeDefinition ( ) method on type , but I am finding it impossible to get the type of T - the int or string in my example above.Is there a way to do this ? <code> IDocument itemPropertyInfo [ ] documentProperties = item.GetType ( ) .GetProperties ( ) ; PropertyInfo property = documentProperties.First ( ) ; Type typeOfProperty = property.PropertyType ; if ( typeOfProperty.IsGenericType ) { Type typeOfProperty = property.PropertyType.GetGenericTypeDefinition ( ) ; if ( typeOfProperty == typeof ( ICollection < > ) { // find out the type of T of the ICollection < T > // and act accordingly } } | How can I find the type of T in a c # Generic collection of T when all I know is the type of the collection ? |
C_sharp : I have a datatable with the following information : I only need to remove the next matched items , like this : I tried : Result : Any ideas ? <code> 365.00370.00369.59365.00365.00 - > match with previous item365.00 - > match with previous item 365.00370.00369.59365.00 ( from articlespricehistory in dt.AsEnumerable ( ) select new { articlepricehistory_cost = articlespricehistory.Field < Double > ( `` articlepricehistory_cost '' ) } ) .DistinctBy ( i = > i.articlepricehistory_cost ) .ToList ( ) ; 365.00370.00369.59 | Linq Distinct only in next rows match |
C_sharp : Consider the following code : What does this accomplish that having the public members alone would not ? <code> private string _text = null ; private string [ ] _values = null ; public string Text { get { return _text ; } } public string [ ] Values { get { return _values ; } } | What is the purpose of this approach to access modifiers ? |
C_sharp : I Created a Listview with some items.When I click at one , I 'm navigating to new page.When I press back , l 'm going back to the old page ( Main menu page - > item page - > backing to main menu by Frame.GoBack ( ) ) andI see all last clicked items are having gray background.I tried to set background to transparent , it does n't work.On Desktop this problem does n't exist , Background is black.I 'm testing it at Windows 10 RS2 & Windows 10 Mobile last insider build at L640XL.Listview : How i 'm backing : How to avoid this effect ? EditI tried with and it doesnt workedit2In main menu page , when I clicked at button and went back , this effect stays . All pages are having NavigationCachePage=Requirededit3any of these did not fix that . <code> < ListView Grid.Row= '' Name= '' LineSecondTrackListView '' ItemsSource= '' { x : Bind _LineSecondTrackBusStops } '' ContainerContentChanging= '' SetBusStopViewAttribute '' ItemTemplate= '' { StaticResource BusStopListViewStyle } '' SelectionMode= '' Single '' SelectionChanged= '' LineTrackListView_SelectionChangedAsync '' > < ListView.ItemsPanel > < ItemsPanelTemplate > < ItemsWrapGrid HorizontalAlignment= '' Center '' Orientation= '' Horizontal '' MaximumRowsOrColumns= '' 1 '' / > < /ItemsPanelTemplate > < /ListView.ItemsPanel > < /ListView > public static void BackButtonPressed ( object sender , BackRequestedEventArgs e ) { Frame mainAppFrame = MainFrameHelper.GetMainFrame ( ) ; Type currentPageType = mainAppFrame.CurrentSourcePageType ; bool goBack = IsGoBackFromPageAllowed ( currentPageType ) ; if ( goBack ) { mainAppFrame.GoBack ( ) ; e.Handled = true ; return ; } App.Current.Exit ( ) ; } private static bool IsGoBackFromPageAllowed ( Type currentPageType ) { if ( currentPageType == typeof ( Pages.Lines.LinesViewPage ) ) return true ; if ( currentPageType == typeof ( Pages.Lines.LinePage ) ) return true ; if ( currentPageType == typeof ( Pages.Lines.LineBusStopPage ) ) return true ; return false ; } foreach ( ListViewItem item in LineSecondTrackListView.Items ) VisualStateManager.GoToState ( item , `` Normal '' , false ) ; //in the OnNavigatedTo ButtonListGridView.InvalidateMeasure ( ) ; ButtonListGridView.UpdateLayout ( ) ; ButtonListGridView.InvalidateArrange ( ) ; | How to remove broken background of ListViewItem In UWP ? |
C_sharp : I have been reading some C # interview questions and found a permutation of a popular one about delegates the code of which puzzles me.The question was : Predict the output of the code below.The normal version of this question I 've seen declares the i variable before the for loop , thus making it method-wide and from there it 's easy to see why the output is `` 15 '' 15 times.However when I debugged the code the i variable is out of scope in the foreach loop and does not exist , anymore . Yet , when I step into the iterator ( ) method it exists for the Console.WriteLine ( i ) line.This I can not understand . <code> delegate void Iterator ( ) ; static void Main ( string [ ] args ) { List < Iterator > iterators = new List < Iterator > ( ) ; for ( int i = 0 ; i < 15 ; i++ ) { iterators.Add ( delegate { Console.WriteLine ( i ) ; } ) ; } foreach ( var iterator in iterators ) { iterator ( ) ; } Console.Read ( ) ; } | Why is this for iteration variable still around after the for loop ? |
C_sharp : Some iterators are faster . I found this out because I heard from Bob Tabor on Channel 9 to never copy and paste.I was in the habit of doing something like this to set array values : This is a simplified example , but in order to not copy and paste , or not type things out again , I suppose I should use a loop . But I had this nagging feeling that a loop would be slower than simply listing the commands , and it looks like I 'm right : listing things is a lot faster . The speed , fastest to slowest , in most of my trials , was the list , the do loop , the for loop , and then the while loop.Why is listing things faster than using an iterator , and why are iterators different speeds ? Please help me out if I have n't used these iterators in the most efficient way possible.Here are my results ( for a 2 int array ) and my code is below ( for a 4 int array ) . I tried this a few time on my Windows 7 64 bit.Either I 'm not good at iterating , or using iterators is n't as great as its made out to be . Please let me know which it is . Thanks so much.When I tried a 4 element array the results seemed to get a little more pronounced.I thought it would be only fair if I made the value for the listThem group assigned via a variable like the other trials . It did make the listThem group a little slower , but it was still the fastest . Here are the results after a few tries : And here 's how I implemented the list : I know these results are probably implementation specific , but you would think Microsoft would warn us of the advantages and disadvantages of each loop when it comes to speed . What do you think ? Thanks.Update : As per the comments I published the code and the list is still faster then the loops , but the loops seem closer in performance . The loops are from fastest to slowest : for , while , then do . This is a little different , so my guess is do and while are essentially the same speed , and the for loop is about half a percent faster than the do and while loops , at least on my machine . Here are the results of a few trials : <code> testArray [ 0 ] = 0 ; testArray [ 1 ] = 1 ; int trials = 0 ; TimeSpan listTimer = new TimeSpan ( 0 , 0 , 0 , 0 ) ; TimeSpan forTimer = new TimeSpan ( 0 , 0 , 0 , 0 ) ; TimeSpan doTimer = new TimeSpan ( 0 , 0 , 0 , 0 ) ; TimeSpan whileTimer = new TimeSpan ( 0 , 0 , 0 , 0 ) ; Stopwatch stopWatch = new Stopwatch ( ) ; long numberOfIterations = 100000000 ; int numElements = 4 ; int [ ] testArray = new int [ numElements ] ; testArray [ 0 ] = 0 ; testArray [ 1 ] = 1 ; testArray [ 2 ] = 2 ; testArray [ 3 ] = 3 ; // List themstopWatch.Start ( ) ; for ( int x = 0 ; x < numberOfIterations ; x++ ) { testArray [ 0 ] = 0 ; testArray [ 1 ] = 1 ; testArray [ 2 ] = 2 ; testArray [ 3 ] = 3 ; } stopWatch.Stop ( ) ; listTimer += stopWatch.Elapsed ; Console.WriteLine ( stopWatch.Elapsed ) ; stopWatch.Reset ( ) ; // for themstopWatch.Start ( ) ; int q ; for ( int x = 0 ; x < numberOfIterations ; x++ ) { for ( q = 0 ; q < numElements ; q++ ) testArray [ q ] = q ; } stopWatch.Stop ( ) ; forTimer += stopWatch.Elapsed ; Console.WriteLine ( stopWatch.Elapsed ) ; stopWatch.Reset ( ) ; // do themstopWatch.Start ( ) ; int r ; for ( int x = 0 ; x < numberOfIterations ; x++ ) { r = 0 ; do { testArray [ r ] = r ; r++ ; } while ( r < numElements ) ; } stopWatch.Stop ( ) ; doTimer += stopWatch.Elapsed ; Console.WriteLine ( stopWatch.Elapsed ) ; stopWatch.Reset ( ) ; // whilestopWatch.Start ( ) ; int s ; for ( int x = 0 ; x < numberOfIterations ; x++ ) { s = 0 ; while ( s < numElements ) { testArray [ s ] = s ; s++ ; } } stopWatch.Stop ( ) ; whileTimer += stopWatch.Elapsed ; Console.WriteLine ( stopWatch.Elapsed ) ; stopWatch.Reset ( ) ; Console.WriteLine ( `` listTimer '' ) ; Console.WriteLine ( listTimer ) ; Console.WriteLine ( `` forTimer '' ) ; Console.WriteLine ( forTimer ) ; Console.WriteLine ( `` doTimer '' ) ; Console.WriteLine ( doTimer ) ; Console.WriteLine ( `` whileTimer '' ) ; Console.WriteLine ( whileTimer ) ; Console.WriteLine ( `` Enter any key to try again the program '' ) ; Console.ReadLine ( ) ; trials++ ; int w = 0 ; for ( int x = 0 ; x < numberOfIterations ; x++ ) { testArray [ w ] = w ; w++ ; testArray [ w ] = w ; w++ ; testArray [ w ] = w ; w++ ; testArray [ w ] = w ; w = 0 ; } | Why are some iterators faster than others in C # ? |
C_sharp : The following snippet evaluates to zero : Whereas , if you do this : The result is ( would you even guess this ? ) int.MinValue . That fact alone is weird enough [ see below ] , but I was under the impression that unchecked was meant to force the compiler into emitting code that pretends not to know that a conversion will definitely fail and/or some overflow happens . In other words , it should give the same result as when the compiler has no knowledge of the values involved ( assuming it is compiled with `` Check for arithmetic overflow '' disabled ) So , what 's going on here ? Is my understanding of unchecked wrong ? Is one of the results `` wrong '' , as per the C # /.NET standard ? edit : the int.MinValue is explained easily enough : cvttsd2si gives 0x80000000 when there would have been overflow but the exception is masked . That 's the instruction used by the JIT compiler , as can be seen in the disassembly window . That does n't solve any part of the issue though.According to ECMA 334 ( C # 2 spec ) , the unchecked keyword should always truncate and therefore the result should be zero in both of these cases : But it is n't , the second one gives int.MinValue . This still smells like compiler bug to me . <code> int result = unchecked ( ( int ) double.MaxValue ) ; double x = double.MaxValueint result = ( int ) x ; int result1 = unchecked ( ( int ) double.MaxValue ) ; double x = double.MaxValue ; int result2 = unchecked ( ( int ) x ) ; | Weird result from unchecked ( ) , possible compiler bug ? |
C_sharp : I am currently trying to implement history tracking on all of my tables in my app in a generic way by overriding the SaveChanges method and making use of reflection . As a simple case , let 's say I have 2 classes/dbsets for my domain objects and a history table for each like the following : The CatHistory class looks like the following ( DogHistory follows the same scheme ) : My Goal is when an object is saved , I would like to insert a record in the appropriate history table . I am having trouble overcoming type difference when using reflection . My current attempt is below and I seem to be stuck on the //TODO : line : <code> DbSet < Cat > Cats { get ; set ; } DbSet < CatHistory > CatHistories { get ; set ; } DbSet < Dog > Dogs { get ; set ; } DbSet < DogHistory > DogHistories { get ; set ; } public class CatHistory : HistoricalEntity { public int CatId { get ; set ; } public virtual Cat Cat { get ; set ; } } var properties = entry.CurrentValues.PropertyNames.Where ( x = > entry.Property ( x ) .IsModified ) .ToList ( ) ; //get the history entry type from our calculated typeName var historyType = Assembly.GetExecutingAssembly ( ) .GetTypes ( ) .FirstOrDefault ( x = > x.Name == historyTypeName ) ; if ( historyType ! = null ) { //modified entries if ( dbSet ! = null & & historyDbSet ! = null & & entry.State == EntityState.Modified ) { var existingEntry = dbSet.Find ( entry.Property ( `` Id '' ) .CurrentValue ) ; //create history record and add entry to table var newHistories = GetHistoricalEntities ( existingEntry , type , entry ) ; var listType = typeof ( List < > ) .MakeGenericType ( new [ ] { historyType } ) ; var typedHistories = ( IList ) Activator.CreateInstance ( listType ) ; //TODO : turn newHistories ( type = List < HistoricalEntity > ) into specific list type ( List < MyObjectHistory > ) so I can addrange on appropriate DbSet ( MDbSet < MyObjectHistory > ) historyDbSet.AddRange ( newHistories ) ; } } | Implementing history tracking in SaveChanges override |
C_sharp : There are a few other questions concerning this on SO , but I felt none of them really provided a solid answer.I 'm messing around with reflection a lot lately , and I wanted to check for types contained within a few assemblies that implement a certain interface.So I have a class called BESCollector that implements ICollectorHere I load the assembly , loop through all types and see if that type contains an interface of type ICollector ... ... which yields no results : ( . While debugging I can clearly see that it DOES contain this type . I break on the if-loopThese results are straight from the debugger . Here you can see that interfaces contains a single Type , namely ICollector : And the Type I 'm calling .GetInterfaces ( ) on is clearly BESCollector : But the equality statement interfaces.Contains ( typeof ( ICollector ) ) never evaluates to true.Just so you think I 'm not mixing up types here , when I mouse over ( typeof ( ICollector ) ) while debugging , it clearly displays SquidReports.DataCollector.Interface.ICollector.This , of course , does work : But that does't tell me a whole lot , besides the fact that the types of the same name.Moreover , why does this check fail ? Why does my first equality check fail ? More specifically , how does type equality work in C # 5.0 ? Was there nothing specific implemented for .Equals ( ) for the 'Type ' type ? EDIT : At the request of I Quality Catalyst below quickly did a test if the equality would evaluate to true if the interface and class were defined in the same assembly . This DOES work : EDIT2 : Here 's the implementation of ICollectorHowever , I do believe I may have missed out on an important detail . I 'm working with three Assemblies here : The 'Main ' ( SquidReports.DataCollector ) assembly where I 'm doing the equality checkThe 'Interface ' ( SquidReports.DataCollector.Interface ) assembly that contains ICollectorThe 'Plugin ' ( SquidReports.DataCollector.Plugin.BES ) assembly that contains the definition of BESCollectorIt is probably very important to note that the 'Interface ' ( SquidReports.DataCollector.Interface ) is being loaded from the ReflectionOnlyAssemblyResolve event , like shown below , because ReflectionOnlyLoadFrom ( ) does not automatically resolves dependencies : EDIT3 : At the suggestion of Joe below , I debugged the application again using this : I copied the complete properties of interface1 and interface2 , then threw those in a file diff.The result , I think , may have solved my problem : interface1 is described as follows : Whereas interface2 is described like this : So am I correct in assuming that the problem is caused because { System.RuntimeType } ! = { System.ReflectionOnlyType } , and that Assembly.ReflectionOnlyLoadFrom ( ) is to blame for this ? <code> public class BESCollector : ICollector { // ... } Assembly pluginAssembly = Assembly.ReflectionOnlyLoadFrom ( pluginConfig.AssemblyLocation ) ; IEnumerable < Type > types = pluginAssembly.GetTypes ( ) .Where ( t = > t.GetInterfaces ( ) .Contains ( typeof ( ICollector ) ) ) ; Assembly pluginAssembly = Assembly.ReflectionOnlyLoadFrom ( pluginConfig.AssemblyLocation ) ; IEnumerable < Type > types = pluginAssembly.GetTypes ( ) .Where ( t = > t.GetInterfaces ( ) .Contains ( typeof ( ICollector ) ) ) ; foreach ( Type type in pluginAssembly.GetTypes ( ) ) { Type [ ] interfaces = type.GetInterfaces ( ) ; if ( interfaces.Contains ( typeof ( ICollector ) ) ) { Console.WriteLine ( @ '' \o/ '' ) ; } } - interfaces { System.Type [ 1 ] } System.Type [ ] + [ 0 ] { Name = `` ICollector '' FullName = `` SquidReports.DataCollector.Interface.ICollector '' } System.Type { System.ReflectionOnlyType } + type { Name = `` BESCollector '' FullName = `` SquidReports.DataCollector.Plugin.BES.BESCollector '' } System.Type { System.ReflectionOnlyType } Type [ ] interfaces = type.GetInterfaces ( ) ; if ( interfaces.Any ( t = > t.Name == typeof ( ICollector ) .Name ) ) { Console.WriteLine ( @ '' \o/ '' ) ; } if ( typeof ( ICollector ) .Equals ( typeof ( ICollector ) ) ) { Console.WriteLine ( `` EQUALIZED '' ) ; } class Program { public interface ITest { } public class Test : ITest { public int ID { get ; set ; } } static void Main ( string [ ] args ) { Type [ ] interfaces = ( typeof ( Test ) ) .GetInterfaces ( ) ; if ( interfaces.Any ( t = > t == typeof ( ITest ) ) ) { Console.WriteLine ( @ '' \o/ '' ) ; } } } public interface ICollector { IDbRelay DbRelay { get ; set ; } ILogManager LogManager { get ; set ; } void Init ( ILogManager logManager , IDbRelay dbRelay ) ; void Execute ( ) ; } public Assembly ReflectionOnlyAssemblyResolve ( object sender , ResolveEventArgs args ) { // This event is used to resolve dependency problems . We need to return the requested assembly in this method . // We should probably look in two locations : // 1 . The SquidReports.DataCollector folder // 2 . The Corresponding folder in SquidReports.DataCollector\Plugins // Let 's first turn the 'full ' assembly name into something more compact AssemblyName assemblyName = new AssemblyName ( args.Name ) ; this.Logger.LogMessage ( LogLevel.Debug , String.Format ( `` Attempting to resolve Assembly { 0 } to load { 0 } '' , assemblyName.Name , args.RequestingAssembly.GetName ( ) .Name ) ) ; // Let 's also get the location where the requesting assembly is located DirectoryInfo pluginDirectory = Directory.GetParent ( args.RequestingAssembly.Location ) ; string assemblyFileName = String.Format ( `` { 0 } .dll '' , assemblyName.Name ) ; if ( File.Exists ( assemblyFileName ) ) { // It 's in the main bin folder , let 's try to load from here return Assembly.ReflectionOnlyLoadFrom ( assemblyFileName ) ; } else if ( File.Exists ( Path.Combine ( pluginDirectory.FullName , assemblyFileName ) ) ) { // It 's in the plugin folder , let 's load from there return Assembly.ReflectionOnlyLoadFrom ( Path.Combine ( pluginDirectory.FullName , assemblyFileName ) ) ; } return null ; } if ( type.Name == `` BESCollector '' ) { Type [ ] interfaces = type.GetInterfaces ( ) ; Type interface1 = interfaces [ 0 ] ; Type interface2 = typeof ( ICollector ) ; Console.WriteLine ( `` '' ) ; } interface1 { Name = `` ICollector '' FullName = `` SquidReports.DataCollector.Interface.ICollector '' } System.Type { System.ReflectionOnlyType } interface2 { Name = `` ICollector '' FullName = `` SquidReports.DataCollector.Interface.ICollector '' } System.Type { System.RuntimeType } | Why are my types not marked as equal ? |
C_sharp : It seems like .NET goes out of its way to make strings that are equal by value equal by reference.In LINQPad , I tried the following , hoping it 'd bypass interning string constants : but that returns true . However , I want to create a string that 's reliably distinguishable from any other string object . ( The use case is creating a sentinel value to use for an optional parameter . I 'm wrapping WebForms ' Page.Validate ( ) , and I want to choose the appropriate overload depending on whether the caller gave me the optional validation group argument . So I want to be able to detect whether the caller omitted that argument , or whether he passed a value that happens to be equal to my default value . Obviously there 's other less arcane ways of approaching this specific use case , the aim of this question is more academical . ) , <code> var s1 = new string ( `` '' .ToCharArray ( ) ) ; var s2 = new string ( `` '' .ToCharArray ( ) ) ; object.ReferenceEquals ( s1 , s2 ) .Dump ( ) ; | Is it possible to create a string that 's not reference-equal to any other string ? |
C_sharp : I have a text file and I am reading it line by line.I want to split a single line with ' , '.But I want the commas which are inside quotes `` '' to be skipped.I have tried following regex and it is not working correctly.How to do it.The contents of file areThe regex is as followsThis regex is outputting the following for line 5The result should be as follows <code> `` Mobile '' , '' Custom1 '' , '' Custom2 '' , '' Custom3 '' , '' First Name '' '' 61402818083 '' , '' service '' , '' in Portsmith '' , '' is '' , '' First Name '' '' 61402818083 '' , '' service '' , '' in Parramatta Park '' , '' is '' , '' First Name '' '' 61402818083 '' , '' services '' , '' in postcodes 3000 , 4000 '' , '' are '' , '' First Name '' '' 61402818083 '' , '' services '' , '' in postcodes 3000 , 4000 , 5000 '' , '' are '' , '' First Name '' '' 61402818083 '' , '' services '' , , '' are '' , '' First Name '' , ( ? = ( [ ^\ '' ] *\ '' [ ^\ '' ] *\ '' ) * [ ^\ '' ] * $ ) `` 61402818083 '' , '' First Name '' '' services '' , '' First Name '' '' in postcodes 3000 , 4000 , 5000 '' , '' First Name '' '' are '' '' First Name '' '' First Name '' `` 61402818083 '' '' services '' '' in postcodes 3000 , 4000 , 5000 '' '' are '' '' First Name '' | Regex split while reading from file |
C_sharp : A bit of domain knowledgeI 'm writing a POS ( Point Of Sales ) software which allows to pay goods or to refund them.When paying or refunding , one need to specify which money transfer mean to use : cash , EFT ( ~=credit card ) , loyalty card , voucher , etc.These money transfer means are a finite and known set of values ( a kind of enum ) .The tricky part is that I need to be able to store a custom subset of these means for both payments and refunds ( the two sets may be different ) on the POS terminal.For example : Available payment means : Cash , EFT , Loyalty card , VoucherAvailable refund means : Cash , VoucherCurrent state of implementationI choose to implement the concept of money transfer mean as follow : The reason it is not a `` plain enum '' is that there exists some behavior that is inside these classes . I also had to declare inner classes public ( instead of private ) in order to reference them in FluentNHibernate mapping ( see below ) .How it is usedBoth the payment and refund means are always stored or retrieved in/from the DB as a set . They are really two distinct sets even though some values inside both sets may be the same.Use case 1 : define a new set of payment/refund meansDelete all the existing payment/refund meansInsert the new onesUse case 2 : retrieve all the payment/refund meansGet a collection of all the stored payment/refund meansProblemI 'm stuck with my current design on the persistence aspect . I 'm using NHibernate ( with FluentNHibernate to declare class maps ) and I ca n't find a way to map it to some valid DB schema.I found that it is possible to map a class multiple times using entity-name however I 'm not sure that it is possible with subclasses.What I 'm not ready to do is to alter the MoneyTransferMean public API to be able to persist it ( for example adding a bool isRefund to differentiate between the two ) . However adding some private discriminator field or so is ok.My current mapping : This mapping compiles however it only produces 1 table and I 'm not able to differentiate between payment/refund when querying this table.I tried to declare two mappings referencing both MoneyTransferMean with different table and entity-name however this leads me to an exception Duplicate class/entity mapping MoneyTransferMean+CashMoneyTransferMean.I also tried to duplicate subclass mappings but I 'm unable to specify a `` parent mapping '' which leads me to the same exception as above.QuestionDoes a solution exist to persist my current domain entities ? If not , what would be the smallest refactor I need to perform on my entities to make them persistable with NHibnernate ? <code> public abstract class MoneyTransferMean : AggregateRoot { public static readonly MoneyTransferMean Cash = new CashMoneyTransferMean ( ) ; public static readonly MoneyTransferMean EFT = new EFTMoneyTransferMean ( ) ; // and so on ... //abstract method public class CashMoneyTransferMean : MoneyTransferMean { //impl of abstract method } public class EFTMoneyTransferMean : MoneyTransferMean { //impl of abstract method } //and so on ... } public sealed class MoneyTransferMeanMap : ClassMap < MoneyTransferMean > { public MoneyTransferMeanMap ( ) { Id ( Entity.Expressions < MoneyTransferMean > .Id ) ; DiscriminateSubClassesOnColumn ( `` Type '' ) .Not.Nullable ( ) ; } } public sealed class CashMoneyTransferMeanMap : SubclassMap < MoneyTransferMean.CashMoneyTransferMean > { public CashMoneyTransferMeanMap ( ) { DiscriminatorValue ( `` Cash '' ) ; } } public sealed class EFTMoneyTransferMeanMap : SubclassMap < MoneyTransferMean.EFTMoneyTransferMean > { public EFTMoneyTransferMeanMap ( ) { DiscriminatorValue ( `` EFT '' ) ; } } //and so on ... | Mapping the same entity to different tables |
C_sharp : In C++ , ' > > ' and ' < < ' are used for cascading during performing the Input/Output Operations.Is there any way in which such things can be done in C # ? Till now , I know that I can take one input at a time and assign it to a variable , for eg , in the following code snippet : whereas in C++ , the same thing can be done as : <code> int a , b ; Console.Write ( `` Enter the value of first number : `` ) ; a=Convert.ToInt32 ( Console.ReadLine ( ) ) ; Console.Write ( `` Enter the value of second number : `` ) ; b=Convert.ToInt32 ( Console.ReadLine ( ) ) ; int a , b ; cout < < `` Enter the values of the two numbers : `` ; cin > > a > > b ; | I/O Cascading in c # |
C_sharp : When I decompile String.IndexOf ( String ) method , I see this ; In the second parameter definition : if string.LegacyMode is true , StringComparison.Ordinal is evaluated.if string.LegacyMode is false , StringComparison.CurrentCulture is evaluated.But what does String.LegacyMode exactly mean ? When I decompile this property I see this : I searched about String.LegacyMode and CompatibilitySwitches.IsAppEarlierThanSilverlight4 on Google first but I could n't find any useful information.Can you enlighten me ? <code> [ __DynamicallyInvokable ] public int IndexOf ( string value ) { return this.IndexOf ( value , string.LegacyMode ? StringComparison.Ordinal : StringComparison.CurrentCulture ) ; } internal static bool LegacyMode { get { return CompatibilitySwitches.IsAppEarlierThanSilverlight4 ; } } | What is String.LegacyMode property for exactly ? |
C_sharp : This is something I have n't ever noticed before , but recently ran into . When I encountered this situation , I was surprised at what the compiler considered was correct , and what it forced me to do . I think it is easiest described through example.Let 's say we have a generic base class with a single method.Nothing crazy here . Now , let 's extend it , providing a concrete implementation for int : Seems simple enough , right ? Or , so I thought ... In fact , you can not do this . The compiler throws you the message 'IntImplementation ' does not implement inherited abstract member 'GenericBase.SomeMethod ( T ) 'But ... T is now an int ! Why ca n't I just substitute this in my override ? It turns out the only acceptable override iswhich means my method now has to beWow , that is n't generic at all . In fact , I might as well ditch generics from the base class and go with good ol ' object ! Mind . Blown . I 've been puzzling over what might be the reasoning behind this , but I 'm at a loss . Does anybody have any ideas ? <code> abstract class GenericBase < T > { public abstract T SomeMethod < T > ( T value ) ; } class IntImplementation : GenericBase < int > // T is now , and forever shall be , int { public override int SomeMethod ( int value ) { return ++value ; } } public override T SomeMethod < T > ( T value ) public override T SomeMethod < T > ( T value ) { return ++ ( ( int ) value ) ; } | Why is my subclass still generic when I supply a type argument to the base class ? |
C_sharp : I just wrote this code : It seems very repetitive . Is there a way to generalize this ? So I do n't have to have 4 lines that are the same except a different sign ? ( Note : if there is a better way that does not use the OperationEnum that is great ) <code> private double PerformOperation ( OperationEnum operation , double aggregateValue , double sourceValue ) { if ( operation == OperationEnum.Sum ) return aggregateValue + sourceValue ; if ( operation == OperationEnum.Subtract ) return aggregateValue - sourceValue ; if ( operation == OperationEnum.Multiply ) return aggregateValue * sourceValue ; if ( operation == OperationEnum.Divide ) return aggregateValue / sourceValue ; throw new InvalidOperationException ( `` Unsupported Aggregation Operation '' ) ; } | Can operations be generalized ? |
C_sharp : I have a user control that hosts other controls . The way I implemented this is via data templates that define the control that should be associated with a specific view-model . These view-models have similar properties and interaction triggers . Please see XAML snippet below.The problem with this approach is that I would have to copy-paste the data bindings if I want to support a new view-model . Is there any way of consolidating all similar data bindings and/or triggers into one template ? I do n't want to type/copy-paste the same data binding definitions into each control . ( Yes , I know , I 'm that lazy . ) <code> < UserControl.Resources > < DataTemplate DataType= '' { x : Type vm : SomeViewModel1 } '' > < TextBlock Canvas.Left= '' { Binding Left } '' Canvas.Top= '' { Binding Top } '' RenderTransform= '' { Binding Transform } '' Height= '' { Binding Height } '' Width= '' { Binding Width } '' > < i : Interaction.Triggers > < i : EventTrigger EventName= '' MouseEnter '' > < cmd : EventToCommand Command= '' { Binding MouseEnterCommand } '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' MouseLeave '' > < cmd : EventToCommand Command= '' { Binding MouseLeaveCommand } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /TextBlock > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : SomeViewModel2 } '' > < Rectangle Canvas.Left= '' { Binding Left } '' Canvas.Top= '' { Binding Top } '' RenderTransform= '' { Binding Transform } '' Height= '' { Binding Height } '' Width= '' { Binding Width } '' > < i : Interaction.Triggers > < i : EventTrigger EventName= '' MouseEnter '' > < cmd : EventToCommand Command= '' { Binding MouseEnterCommand } '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' MouseLeave '' > < cmd : EventToCommand Command= '' { Binding MouseLeaveCommand } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /Rectangle > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : SomeViewModel3 } '' > < Button Canvas.Left= '' { Binding Left } '' Canvas.Top= '' { Binding Top } '' RenderTransform= '' { Binding Transform } '' Height= '' { Binding Height } '' Width= '' { Binding Width } '' > < i : Interaction.Triggers > < i : EventTrigger EventName= '' MouseEnter '' > < cmd : EventToCommand Command= '' { Binding MouseEnterCommand } '' / > < /i : EventTrigger > < i : EventTrigger EventName= '' MouseLeave '' > < cmd : EventToCommand Command= '' { Binding MouseLeaveCommand } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /Button > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : SomeViewModel4 } '' > < ! -- Do not want copy-paste code here ... -- > < /DataTemplate > < /UserControl.Resources > | Is there anyway of consolidating similar data bindings and/or triggers in XAML ? |
C_sharp : First I give a simple example where I know the answer . Consider : and then somewhere the code : We see that am and gm are not considered equal , which is entirely fair ( the latter is an override of the former ) . However , with the last line we can determine that these two methods are related ; one is a `` base method '' of the other . ( You can even check for reference equality , ( object ) am == ( object ) gm.GetBaseDefinition ( ) , and you still get True . ) And now for the situation I have a question for . Consider instead : with : In this case pn and tn are still considered different ( and their ReflectedType differ ) .How can I test whether they are in fact ( through inheritance ) the same method ? Is there any built-in method in the framework ? If I will have to work out this by hand , what is the strategy ? Must I check that both have same DeclaringType , have identical lists of ( types of ) paramaters , and have the same number of type parameters ? <code> class Animal { public virtual void M ( ) { Console.WriteLine ( `` a '' ) ; } } class Giraffe : Animal { public override void M ( ) { Console.WriteLine ( `` g '' ) ; } } var am = typeof ( Animal ) .GetMethod ( `` M '' ) ; var gm = typeof ( Giraffe ) .GetMethod ( `` M '' ) ; Console.WriteLine ( am == gm ) ; // False Console.WriteLine ( am == gm.GetBaseDefinition ( ) ) ; // True class Plant { public void N ( ) /* non-virtual */ { } } class Tree : Plant { } var pn = typeof ( Plant ) .GetMethod ( `` N '' ) ; var tn = typeof ( Tree ) .GetMethod ( `` N '' ) ; Console.WriteLine ( pn == tn ) ; // False // How can I determine that 'pn ' and 'tn ' are in a sense the same method ? | Determine if two MethodInfo instances represent the same ( non-virtual ) method through inheritance |
C_sharp : If I convert single s into decimal d I 've noticed it 's bit representation differs from that of the decimal created directly.For example : Returns ( middle elements removed for brevity ) : Both of these are decimal numbers , which both ( appear ) to be accurately representing 0.01 : Looking at the spec sheds no light except perhaps : §4.1.7 Contrary to the float and double data types , decimal fractional numbers such as 0.1 can be represented exactly in the decimal representation.Suggesting that this is somehow affected by single not being able accurately represent 0.01 before the conversion , therefore : Why is this not accurate by the time the conversion is done ? Why do we seem to have two ways to represent 0.01 in the same datatype ? <code> Single s = 0.01f ; Decimal d = 0.01m ; int [ ] bitsSingle = Decimal.GetBits ( ( decimal ) s ) int [ ] bitsDecimal = Decimal.GetBits ( d ) bitsSingle : [ 0 ] = 10 [ 3 ] = 196608bitsDecimal : [ 0 ] = 1 [ 3 ] = 131072 | Explicit conversion from Single to Decimal results in different bit representation |
C_sharp : Now filed on Microsoft Connect ; please upvote if you feel it needs fixing . I 've also simplified the test case a lot : Looking at the IL , as far as I can tell , the C # compiler did everything right , and the bug lies in the JITter.Original question : What is going on here ? This test requires a 64-bit OS targeting the x64 platform.Output : So is this a bug or did I mess something up ? <code> byte* data = ( byte* ) 0x76543210 ; uint offset = 0x80000000 ; byte* wrong = data + offset ; byte* correct = data + ( uint ) 0x80000000 ; // `` wrong '' is now 0xFFFFFFFFF6543210 ( ! ) // `` correct '' is 0xF6543210 byte* data = ( byte* ) Marshal.AllocHGlobal ( 0x100 ) ; uint uioffset = 0xFFFF0000 ; byte* uiptr1 = data + uioffset ; byte* uiptr2 = data + ( uint ) 0xFFFF0000 ; ulong uloffset = 0xFFFF0000 ; byte* ulptr1 = data + uloffset ; byte* ulptr2 = data + ( ulong ) 0xFFFF0000 ; Action < string , ulong > dumpValue = ( name , value ) = > Console.WriteLine ( `` { 0,8 } : { 1 : x16 } '' , name , value ) ; dumpValue ( `` data '' , ( ulong ) data ) ; dumpValue ( `` uiptr1 '' , ( ulong ) uiptr1 ) ; dumpValue ( `` uiptr2 '' , ( ulong ) uiptr2 ) ; dumpValue ( `` ulptr1 '' , ( ulong ) ulptr1 ) ; dumpValue ( `` ulptr2 '' , ( ulong ) ulptr2 ) ; data : 000000001c00a720 ( original pointer ) uiptr1 : 000000001bffa720 ( pointer with a failed carry into the higher dword ) uiptr2 : 000000011bffa720 ( pointer with a correct carry into the higher dword ) ulptr1 : 000000011bffa720 ( pointer with a correct carry into the higher dword ) ulptr2 : 000000011bffa720 ( pointer with a correct carry into the higher dword ) ^ look here | Why does this addition of byte* and uint fail to carry into the higher dword ? |
C_sharp : I want to perform data-binding to Room.ToNorth.ImageName while ToNorth may be null.I 'm trying to write my own text adventure and have images next to each of the directions a player can go ( ie . open/closed door , pathway ) . When there is n't a room in a given direction I have the controls bound to show a 'no exit ' image , this works great so long the player starting location has an exit in all 4 directions , however when one is null I get the following exception System.ArgumentNullException : 'Value can not be null . Parameter name : component'This is is n't an issue on a new game but I 'm making randomly generated dungeons so it ca n't be guaranteed on a load game . I realise I could probably fudge it by creating a safe space while the bindings are set then moving the player to where they need to be but is there a proper way to handle this ? The closest answer I 've found is this question , but I 'm not sure I can apply it here due to how it 's bound.The ToNorth property just gets the object from an an array of exits , but telling it to return an empty exit if it 's null ( like suggested in the above link ) would be problematic in that the exit would n't have any rooms to connect to and thus fail to initialise likely throwing an exception itself along the way . To explain better , I have my rooms set up as followsAnd my exits are set up like soDoor is just an unnamed object with a few bools for IsOpen , IsLocked etc . and should n't be needed if you want to test this but exits are created anonymously and add themselves to the Exit array in both connecting rooms , hence creating empty ones would fail.Any suggestions would be greatly appreciated . <code> private GameSession _CurrentGame ; private BindingSource _BindToPlayer = new BindingSource ( ) ; private void BtnNewGame_Click ( object sender , EventArgs e ) { _CurrentGame = new GameSession ( ) ; _BindToPlayer.DataSource = _CurrentGame.CurrentPlayer ; PicBoxNorth.DataBindings.Add ( `` ImageLocation '' , _BindToPlayer , `` CurrentRoom.ToNorth.ImageName '' , true , DataSourceUpdateMode.OnPropertyChanged , `` Images\\Wall.png '' ) ; } public Class Room { public int ID { get ; set ; } public String Name { get ; set ; } public String Description { get ; set ; } public String FarDescription { get ; set ; } public CoOrds Co_Ords { get ; set ; } public Boolean UniqueRoom { get ; set ; } public Exit [ ] ExitArr { get ; set ; } public Exit ToNorth = > ExitArr [ 0 ] ; public Exit ToSouth = > ExitArr [ 1 ] ; public Exit ToWest = > ExitArr [ 2 ] ; public Exit ToEast = > ExitArr [ 3 ] ; public Exit ToUp = > ExitArr [ 4 ] ; public Exit ToDown = > ExitArr [ 5 ] ; public Exit ToIn = > ExitArr [ 6 ] ; public Exit ToOut = > ExitArr [ 7 ] ; public Room ( int id , String name , String desc , String fardesc , bool unique = false ) { ID = id ; Name = name ; Description = desc ; FarDescription = fardesc ; Co_Ords = new CoOrds ( ) ; ExitArr = new Exit [ 8 ] ; UniqueRoom = unique ; } public class Exit { public String Description { get ; } public Room RoomA { get ; set ; } public Room RoomB { get ; set ; } public Boolean CanExitA { get ; set ; } = true ; public Boolean CanExitB { get ; set ; } = true ; public Room NextRoom { get { if ( RoomA.PlayerHere & & CanExitA ) { return RoomB ; } else if ( RoomB.PlayerHere & & CanExitB ) { return RoomA ; } else return null ; } } public String ImageName { get { string imagePath = `` Images\\ '' ; if ( DoorHere ! = null ) { return imagePath + DoorHere.ImageName ; } else return imagePath + `` Pathway.png '' ; } } public Door DoorHere { get ; set ; } public Exit ( Room roomA , int Adir , Room roomB , int Bdir , Door door = null ) { RoomA = roomA ; RoomA.ExitArr [ Adir ] = this ; RoomB = roomB ; RoomB.ExitArr [ Bdir ] = this ; DoorHere = door ; } | Data binding to a nested property with possibly null parent |
C_sharp : Occasionally I find I need to process a list by inserting a new item after each item , except the last one . Similar to how you might put a comma between each item of a list of strings.I got fed up of coding the special case for the last ( or first ) item every time , so I captured the pattern in a Linq-style extension : For example , this allows me to easily programatically fill a flow document with hyperlinks , but with a line-break between each one : Assuming this does n't already exist in System.Linq.Enumerable ( which is what I typically discover immediately after writing something like this ) , the question is , what is this Separate operation on lists usually called in other functional frameworks or languages ? <code> public static IEnumerable < T > Separate < T > ( this IEnumerable < T > source , Func < T > separator ) { bool first = true ; foreach ( T item in source ) { if ( first ) first = false ; else yield return separator ( ) ; yield return item ; } } para.Inlines.AddRange ( _recentFiles.Select ( f = > f.ToHyperlink ( ) ) .Separate ( ( ) = > new LineBreak ( ) ) ) ; | In functional list manipulation , what do we call `` inserting something between each item '' ? |
C_sharp : Why does taking the address of a variable eliminate the `` Use of unassigned local variable '' error ? ( Why can we take the address without initialization in the first place ? ) <code> static unsafe void Main ( ) { int x ; int* p = & x ; //No error ? ! x += 2 ; //No error ? ! } | No `` Unassigned Local Variable '' error ? |
C_sharp : I get a list of projects using following : Refer following link for more details.But it gives me each and every item in the solution like Directories , projects , etc.I require only projects.How can I get only projects from the solution ? <code> var solution = ( IVsSolution ) Microsoft.VisualStudio.Shell.Package.GetGlobalService ( typeof ( IVsSolution ) ) ; | How can I get only projects from the solution ? |
C_sharp : I 'm writing a small game in C # using Test Driven Development approach . I 'm facing a problem : I have a class CheckersBoard : And a class BoardGenerator : BoardGenerator allows me to initialize CheckersBoard in a very readable way . So , I really would like to use BoardGenerator in my unit tests to avoid ugly array initialization . But it 's against the rule that says that I must keep all my unit tests independent of each other . If the test of GenerateFromPattern fails , that will produce a `` cascade '' effect and all the tests which use GenerateFromPattern will fail too.This is the first time I have ever used unit tests so I 'm a little bit confused . How can I avoid this problem ? Is there something wrong with my design ? <code> public class CheckersBoard { private const string InitialBoardPattern = `` B-B-B-B- '' + `` -B-B-B-B '' + `` B-B-B-B- '' + `` -- -- -- -- '' + `` -- -- -- -- '' + `` -W-W-W-W '' + `` W-W-W-W- '' + `` -W-W-W-W '' ; public SquareStatus [ , ] Squares { get ; private set ; } public CheckersBoard ( IBoardGenerator boardGenerator ) { Squares = boardGenerator.GenerateFromPattern ( InitialBoardPattern , 8 , 8 ) ; } // ... . } public class BoardGenerator : IBoardGenerator { public SquareStatus [ , ] GenerateFromPattern ( string pattern , int width , int height ) { // ... . } } | How can I keep my unit tests independent of each other in this simple case ? |
C_sharp : Possible Duplicate : Nested using statements in C # I 'm a big fan of the using statement in C # . I find this : ... very much more readable than this : Not only is it more readable , it also prevents accidental use of the foo variable after the using statement ( i.e . after it has been disposed ) , whereas in the second example foo could be used after it had been disposed.One problem with using , though , is that it tends to lead to very nested code if lots of disposable objects are being created . For example : If both the objects are of the same type , then you can combine them into a single using statement , like so : However , if the objects are not of the same type , then this will not work.My question is whether it is OK to to achieve a similar end like this : In this case , there are no curly-braces after the first using ( and hence no need to indent the code ) . This compiles , and I assume that this works just like an if statement with no braces - i.e . it 'll use the next statment ( the second using in this case ) as its `` body '' .Can anyone confirm whether that 's correct ? ( The description of the using statement is no help ) . <code> using ( var foo = new ObjectWhichMustBeDisposed ( ) ) { other code } var foo = new ObjectiWhichMustBeDisposed ( ) ; try { other code } finally { foo.Dispose ( ) ; } using ( var foo = new ObjectWhichMustBeDisposed ( ) ) { using ( var bar = new ObjectWhichMustBeDisposed ( ) ) { other code } } using ( var foo = new ObjectWhichMustBeDisposed ( ) , bar = new ObjectWhichMustBeDisposed ( ) ) { other code } using ( var foo = new ObjectWhichMustBeDisposed ( ) ) using ( var bar = new OtherObjectWhichMustBeDisposed ( ) ) { other code } | Is it OK to use ` using ` like this ? |
C_sharp : In a WCF client application , there are a number of parameterless methods for which we 'd like to cache the results - GetAllFoo ( ) , GetAllBar ( ) . These are used to populate dropdowns and the like , and the results do n't change during the running life of the client.These results are currently being cached by a unique string stored in a Resource file - for example , GetAllCountries ( ) is cached against the CountryKey Resource . The service is only called when the cache does n't contain the requested key.This is fine except we need to maintain the keys in the Resource file , and need to make sure that every method uses the correct cache key otherwise things break . The old Control+C , Control+V causes a few headaches here and I do n't want to have to go check every place that calls this method.So the question : The serviceCall delegate has a Method property on it which describes the method to execute . This is a MethodInfo instance , which in turn contains a MethodHandle property . Am I right in assuming that the MethodHandle property uniquely and consistently identifies the method that is referenced ? I 'd change the wrapper to which properly encapsulates the caching and key concerns , & removes any dependency on the caller 'doing the right thing'.Do n't care if the MethodHandle changes between instances - the caching is only per instanceDo n't care if the MethodHandle is not consistent across clients - caching is per clientDO care if the MethodHandle is not consistent within an instance on a client - I actually want the cache to be used , rather than every request resulting in a new service call and the cache being full of unused dataDO care if the MethodHandle is not unique within an instance on a client - I have to be sure that the correct data ( and type ) is returned when the wrapper is used . <code> public T Get < T , V > ( string key , Func < V , T > serviceCall , V proxy ) { if ( ! cache.Contains ( key ) ) { cache.Add ( key , serviceCall ( proxy ) ) ; } return cache.GetData ( key ) as T ; } public T Get < T , V > ( Func < V , T > serviceCall , V proxy ) { var key = serviceCall.Method.MethodHandle ; // etc | Is it safe to cache the results of a parameterless method using the method 's MethodHandle as a key ? |
C_sharp : I need to generate this simple looking XML , looking for a clean way to generate it . <code> < order > < user > 2343 > < /user > < creditcardtype > 2333 > < /creditcarttype > < country > USA < /country > < orderDetails > < amount > 23434 < /amount > < shipping > 32 < /shipping > < /orderDetails > < /order > | How would you build this xml in c # |
C_sharp : I am using a basic State Management system found here : ( code below ) https : //github.com/xDelivered-Patrick/Xamarin.Forms.Essentials/blob/master/Essentials/Controls/State/StateContainer.csWhen implementing , my XAML View looks like the below.The problem is the StackLayout CenterAndExpand is not working . All the views when rendered are simply scrunched at the top.If I pull the particular section out of the StateContainer and eliminate its usage , it renders correctly . Is this an issue with the way the View is being rendered inside the Content of the StateContainer ? EDIT : Here is a minimal example : https : //github.com/aherrick/StateManagementDemoXAML : C # <code> < ContentPage.Content > < StackLayout x : Name= '' layoutWrap '' VerticalOptions= '' FillAndExpand '' HorizontalOptions= '' FillAndExpand '' > < controls : StateContainer State= '' { Binding State } '' > < controls : StateCondition Is= '' Loading '' > < StackLayout Orientation= '' Vertical '' HorizontalOptions= '' CenterAndExpand '' VerticalOptions= '' CenterAndExpand '' > < ActivityIndicator x : Name= '' loadingIndicator '' IsVisible= '' { Binding IsBusy } '' IsRunning= '' { Binding IsBusy } '' VerticalOptions= '' FillAndExpand '' HorizontalOptions= '' FillAndExpand '' / > < /StackLayout > < /controls : StateCondition > < controls : StateCondition Is= '' Loaded '' > < ! -- actual content here -- > < /controls : StateCondition > < controls : StateCondition Is= '' Error '' > < StackLayout Orientation= '' Vertical '' HorizontalOptions= '' CenterAndExpand '' VerticalOptions= '' CenterAndExpand '' > < Label FontAttributes= '' Bold '' Text= '' Oops ! There was a problem . '' VerticalOptions= '' CenterAndExpand '' HorizontalOptions= '' CenterAndExpand '' / > < Button Text= '' Tap to Retry '' Command= '' { Binding LoadVenuesCommand } '' CommandParameter= '' true '' HorizontalOptions= '' CenterAndExpand '' TextColor= '' White '' Padding= '' 15 '' BackgroundColor= '' # 26265E '' / > < /StackLayout > < /controls : StateCondition > < /controls : StateContainer > < /StackLayout > < /ContentPage.Content > [ ContentProperty ( `` Content '' ) ] [ Preserve ( AllMembers = true ) ] public class StateCondition : View { public object Is { get ; set ; } public object IsNot { get ; set ; } public View Content { get ; set ; } } [ ContentProperty ( `` Conditions '' ) ] [ Preserve ( AllMembers = true ) ] public class StateContainer : ContentView { public List < StateCondition > Conditions { get ; set ; } = new List < StateCondition > ( ) ; // https : //forums.xamarin.com/discussion/102024/change-bindableproperty-create-to-bindableproperty-create //public static readonly BindableProperty StateProperty = BindableProperty.Create ( nameof ( State ) , typeof ( object ) , typeof ( StateContainer ) , propertyChanged : StateChanged ) ; public static readonly BindableProperty StateProperty = BindableProperty.Create < StateContainer , object > ( x = > x.State , null , propertyChanged : StateChanged ) ; public static void Init ( ) { } private static void StateChanged ( BindableObject bindable , object oldValue , object newValue ) { var parent = bindable as StateContainer ; parent ? .ChooseStateProperty ( newValue ) ; } public object State { get { return GetValue ( StateProperty ) ; } set { SetValue ( StateProperty , value ) ; } } private void ChooseStateProperty ( object newValue ) { foreach ( StateCondition stateCondition in Conditions ) { if ( stateCondition.Is ! = null ) { if ( stateCondition.Is.ToString ( ) .Equals ( newValue.ToString ( ) ) ) { Content = stateCondition.Content ; } } else if ( stateCondition.IsNot ! = null ) { if ( ! stateCondition.IsNot.ToString ( ) .Equals ( newValue.ToString ( ) ) ) { Content = stateCondition.Content ; } } } } } | Xamarin Forms State Container View not Respecting Layout Options |
C_sharp : I have two classes A & B , where B is derived from A . Both the classes have a method with same signature . They are called in the following manner in Java & c # -- > In case of JAVA : This program generates the following output : -In case of C # : This program generates the following output : -Why does the output differ ? <code> class A { public void print ( ) { System.out.println ( `` Inside Parent '' ) ; } } class B extends A { public void print ( ) { System.out.println ( `` Inside Child '' ) ; } } class test4 { public static void main ( String args [ ] ) { B b1=new B ( ) ; b1.print ( ) ; A a1=new B ( ) ; a1.print ( ) ; } } Inside ChildInside Child class A { public void print ( ) { System.Console.WriteLine ( `` Inside Parent '' ) ; } } class B : A { public void print ( ) { System.Console.WriteLine ( `` Inside Child '' ) ; } } class Program { public static void Main ( string [ ] args ) { B b1=new B ( ) ; b1.print ( ) ; A a1=new B ( ) ; a1.print ( ) ; System.Console.Read ( ) ; } } Inside ChildInside Parent | Why this difference of handling method ambiguity in Java & c # ? |
C_sharp : I want to check if any of the items in a list has a field set to trueat the moment I do this : How can I do this using Linq might be trivial to some but ca n't figure if now . <code> bool isPaid = visit.Referrals.Exists ( delegate ( AReferral r ) { return r.IsPaidVisit ; } ) ; | Do List.Exist using Linq |
C_sharp : I have a Silverlight app with several graphs and a date control on the top which allows the user to set the date range ( e.g . July 1 - Sep 30 ) . Basically , when a user modifies the date range , a command is executed which sets the ViewModel 's DateRange property to the new value . The DateRange 's setter calls a RunQueries method which queries for new data and sets the Data1 and Data2 properties with the results of those queries . The graphs that are bound to Data1 or Data2 get updated accordingly . See below for the basic ViewModel code ; take note of the RunQueries method call in the DateRange setter.Now in reality , there are already more than two data collections and more keep on being added as the app is expanded . In addition , not all graphs are visible at once ; at times only one graph is visible . But when the user changes the date range , all the queries to obtain all the data that is needed for any of the graphs are rerun with the new start and end dates . This seems very inefficient to me - perhaps only one query needs to be run ! So my question is - how do I implement delayed data querying in my ViewModel class ? Here are two ideas I 've been considering : Keep track of which data collections are up-to-date and then check in the data getter method if a query needs to be run . Break out the ViewModel into several subclasses , one for each graph , and have each ViewModel manage its own data with the base class keeping track of the DateRange.Both ideas seem complex to implement and I 've been wondering - is there a standard approach to this ? Am I missing something in the MVVM design pattern that addresses this issue ? Here 's the very simplified version of my ViewModel class : <code> public class MyViewModel : INotifyPropertyChanged { private ObservableCollection < MyData > _Data1 ; private ObservableCollection < MyData > _Data2 ; private MyDateRange _DateRange ; public ObservableCollection < MyData > Data1 { get { return _Data1 ; } set { if ( _Data1 ! = value ) { _Data1 = value ; NotifyPropertyChanged ( `` Data1 '' ) ; } } } // getter and setter for Data2 go here public MyDateRange DateRange { get { return _DateRange ; } set { if ( _DateRange ! = value ) { _DateRange = value ; NotifyPropertyChanged ( `` DateRange '' ) ; // if date range changed , need to query for stats again RunQueries ( ) ; } } } private void RunQueries ( ) { GetData1 ( ) ; GetData2 ( ) ; } private void GetData1 ( ) { // call wcf service to get the data } private void GetData1Completed ( object s , EventArgs e ) { // update Data1 property with results of service call } // etc } | How to defer data querying in Silverlight ViewModel class ? |
C_sharp : This might be really simple but i have a service that returns a string that has a number preceded with zeros . The count of zeros is not predictable but i need to extract the number out of the value . The length of the value is also not constant . For ex . 00001234 , 002345667 , 0000000 , 011 , 00000987 - in all these values , i need to extract the 1234 , 2345667 , < no value > , 11 , 987. i have tried doing the below code but it returns the zeros as well : Can anyone help ? Got my Answer : :I got it using stringObj.TrimStart ( ' 0 ' ) . But i agree using Int.Parse or Int.TryParse is a better way of handling . Hope this is useful to someone like me ! <code> string.Join ( null , System.Text.RegularExpressions.Regex.Split ( expr , `` [ ^\\d ] '' ) ) ; | extracting integer from string |
C_sharp : After considerable measurement , I have identified a hotspot in one of our windows services that I 'd like to optimize . We are processing strings that may have multiple consecutive spaces in it , and we 'd like to reduce to only single spaces . We use a static compiled regex for this task : and then use it as follows : This line is being invoked several million times , and is proving to be fairly intensive . I 've tried to write something better , but I 'm stumped . Given the fairly modest processing requirements of the regex , surely there 's something faster . Could unsafe processing with pointers speed things further ? Edit : Thanks for the amazing set of responses to this question ... most unexpected ! <code> private static readonly Regex regex_select_all_multiple_whitespace_chars = new Regex ( @ '' \s+ '' , RegexOptions.Compiled ) ; var cleanString= regex_select_all_multiple_whitespace_chars.Replace ( dirtyString.Trim ( ) , `` `` ) ; | How to outperform this regex replacement ? |
C_sharp : We have a lot CanExecute tests for a various commands in our project.All tests passed properly when we use Visual Studio testing or AxoCover.We tried to add some previous object initialization , before executing 'CanExecute ' and sometimes it worked ( or we thought that ) .I have a test : Sometimes ( NOT ALWAYS ) when Jenkins does the build and run unit tests some of can execute tests failed with message : The problem is that is happening only on Jenkins and it 's very nondeterministic.EDIT : Ok , one more thing to think about . Property InEditMode is placed in base parent class of SomeModelView.And I merged code for you in the sample.And we think that can be related , that object is thinking that is initialized before initialization of base class is done . But that is very hard to check this with a Jenkins.SOLUTIONI 've created an attribute class : And then I can use for each 'CanExecute ' test this attribute : <code> testedViewModel.Object.InEditMode = inEditMode ; [ TestCase ( true , true , TestName = `` Command_InEditMode_CanExecute '' ) ] [ TestCase ( false , false , TestName = `` Command_NotInEditMode_CannotExecute '' ) ] public void CommandCanExecute ( bool inEditMode , bool expectedResult ) { var testedViewModel = new Mock < SomeViewModel > ( inEditMode ) { CallBase = true } ; testedViewModel.Setup ( x = > x.InEditMode ) .Returns ( inEditMode ) ; Assert.AreEqual ( expectedResult , testedViewModel.Object.Command.CanExecute ( null ) ) ; } MESSAGE : Expected : True But was : False+++++++++++++++++++ STACK TRACE : at Project.CommandCanExecute ( Boolean inEditMode , Boolean expectedResult ) public BaseViewModel { public virtual bool InEditMode { get ; set ; } } public SomeViewModel : BaseViewModel { public SomeViewModel ( ) : base ( ) { } public ICommand Command { get ; set ; } public virtual void RegisterCommands ( ) { Command = new RelayCommand ( /*Do something*/ , ( ) = > InEditMode ) ; } } [ AttributeUsage ( AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Assembly , AllowMultiple = true ) ] public class GarbageCollectorDisabler : Attribute , ITestAction { public void BeforeTest ( ITest test ) { GC.TryStartNoGCRegion ( 2048 * 4096 ) ; } public void AfterTest ( ITest test ) { GC.EndNoGCRegion ( ) ; } public ActionTargets Targets = > ActionTargets.Test ; } [ GarbageCollectorDisabler ] [ TestCase ( TestName = `` SomeTest_InEditMode_CanExecute '' ) ] public void SomeTestCanExecute ( ) { } | Jenkins failed unit CanExecute test 's methods nondeterministic |
C_sharp : Lets say a FIFO ( one which is thread safe ) has items being added to it ( we dont care how ) Now lets say the items ( one by one ) should be inserted to another concurrent collection .The rate of data insertion is dynamic.I want to do it in the fastest way . ( transfer all the elements from the Fifo to the collection ) .But I 'm having a conflict : I could use one thread to pull out items from the Fifo and insert them into the collection . but then I wont be using cores / other threads which can help me.I could use several consumer threads to take items from Fifo , but then maybe the internal locking on the Fifo ( when reading ) , and the internal locking on the collection ( when writing ) will eventually reduce performance.I mean , there will be a situation where if I have enormousness consumer threads , there will be also enormousness internal locking with the fifo / collection , plus many many context switchingHow can I approach this kind of problem the right way ? What is the guideline ? <code> |__| || | ||__| || | ||__| V| d||__|| c||__|| b||__|| a| | To MultiThread or not to MultiThread ? |
C_sharp : What I need to do : I need to capture all shortcut key presses such as Ctrl+S from a specific application . Any key combo , even if it 's not a shortcut for that application.Then my midway application that capture these keys need to validate those key combination and check if another of our apps that are running can respond to that key , and if it can send the command to it.What I have so far : Since we wrote the other apps we can easily send the keys to be processed that 's not a problem . I can get the window handle of the application . I need to capture the shortcut keys . This app I know it 's build in C++ . I am looking to find a way to capture an equivalent of the following event in Winforms : Right now everything is working as expected on the forward key part . I am only missing the capture of keys on that handle . I really do n't want to have to adventure myself in hooking the whole keyboard and detect whether the key stroke is done in my apps or not and do I need to cancel the key or continue the process . I would prefer also getting key combination events only . I would prefer not receiving all letter the guy press when he type in a textbox or anything . I 'm really looking for anything starting with CTRL , ALT , SHIFT or any combination of themExample of what I want to do : uncontrolled application : Notepad.exemy midway app : ShortcutHandler.exemy target applications : A.exe , B.exeShortcutHandler.exe will listen to Notepad.Exe shortcuts then forward them to A.exe and B.exeSituation : <code> protected override bool ProcessCmdKey ( ref Message msg , Keys keyData ) 1 - in Notepad.exe press CTRL+H for replace2 - ShortcutHandler.exe detect CTRL+H pressed on Notepad.exe3 - ShortcutHandler.exe Analyse CTRL+H and knows it need to do some task4 - ShortcutHandler.exe call Save on A.exe in reaction to CTRL+H in Notepad.exe5 - ShortcutHandler.exe call Print report in B.exe in reaction to CTRL+H in Notepad.exe | Capture keyboard shortcuts and forward |
C_sharp : We 're writing a diagnostic tool that needs to run for many hours at a time , but we 're running into a mysterious Out of Memory Exception when we try to remove items from a CheckedListBox after the application has run for a couple of hours.We initially tried using checkedListBox.Items.Clear ( ) ; , and after some Googling around , we tried something like the following instead : Unfortunately , the above did not solve the issue . I found that idea on the MSDN forums , but I ca n't for the life of me find the link again this morning . However , that forum did say that someone had profiled their application and found a memory leak in CheckedListBox.Items.Clear ( ) .Does anyone know of a functional work around ? EDIT : FingerTheCat 's answer has temporarily solved our problem , so I will mark it as the answer for now . However , we 've begun combing through the code to try and find the real problem . Unfortunately , the current implementation is largely spaghetti code , so it may be a few days before we find anything . <code> for ( int i = checkedListBox.Items.Count - 1 ; i > = 0 ; i -- ) { checkedListBox.Items.RemoveAt ( i ) ; } | CheckedListBox memory leak |
C_sharp : I have a custom AuthorizeAttribute in a legacy MVC5 project : We noticed while looking through the logs , that in addition to being to applied to controllers with [ AuthorizeWithLogging ] , it was being called explicitly elsewhere in the code , generating spurious logs : Is there a way to tell ( via StackTrace or something ) whether the OnAuthorization method is being explicitly called , or called from the attribute ? The best I currently have is Environment.StackTrace.Contains ( `` at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters '' ) . <code> public class AuthorizeWithLoggingAttribute : AuthorizeAttribute { public override void OnAuthorization ( AuthorizationContext filterContext ) { if ( ! base.AuthorizeCore ( httpContext ) ) { Log ( FilterContext ) ; } } } var filters = new FilterInfo ( FilterProviders.Providers.GetFilters ( controllerContext , actionDescriptor ) ) ; foreach ( var authFilter in filters.AuthorizationFilters ) { authFilter.OnAuthorization ( authContext ) ; if ( authContext.Result ! = null ) { return false ; } } | Detecting if AuthorizationAttribute manually called |
C_sharp : I have an issue where I 'm using the same template to render some content on a page and the same template is used to render additional content on the page using an AJAX request.The following code renders the partial razor view : The following code makes the AJAX request : So what you get is the same partial razor view output on the page twice , once during the page request and once during the AJAX request.The problem is that TextBoxFor , CheckBoxFor , etc . all make use of TagBuilder.GenerateId to generate the id attribute value but it does n't account for generating id 's across multiple requests where AJAX might be involved . This results in the same id value being output on the page , causing JavaScript to break.The following is the HTML that is output twice ( once during the request and then added in a separate part of the page during an AJAX request ) : So the SearchPhrase and WhatToSearch id 's are duplicated.Is there any way to work around this , or is there a better way to render the form elements to avoid this issue ? <code> @ model SearchBoxViewModel < div class= '' smart-search '' > @ using ( Html.BeginForm ( `` Index '' , `` Search '' , FormMethod.Get , new { @ class = `` form-horizontal '' , role = `` form '' } ) ) { < div class= '' form-group '' > < div class= '' hidden-xs col-sm-1 col-md-1 col-lg-1 text-right '' > @ Html.LabelFor ( m = > m.SearchPhrase , new { @ class = `` control-label heading '' } ) < /div > < div class= '' col-xs-8 col-md-9 col-lg-10 '' > @ Html.TextBoxFor ( m = > m.SearchPhrase , new { @ class = `` form-control '' , placeholder = `` for products , companies , or therapy areas '' } ) < /div > < div class= '' col-xs-4 col-sm-3 col-md-2 col-lg-1 '' > < input type= '' submit '' value= '' Search '' class= '' btn btn-default '' / > < /div > < div class= '' what-to-search hidden-11 col-sm-11 col-sm-offset-1 '' > < div class= '' checkbox '' > < label > @ Html.CheckBoxFor ( m = > m.WhatToSearch , null , false ) @ Html.DisplayNameFor ( m = > m.WhatToSearch ) < /label > < /div > < /div > < /div > } < /div > < ! -- /.smart-search -- > $ .ajax ( anchor.attr ( `` data-overlay-url-action '' ) ) .done ( function ( data ) { $ ( `` div.overlay '' ) .addClass ( `` old-overlay '' ) ; $ ( `` div.navbar '' ) .after ( data ) ; $ ( `` div.overlay : not ( .old-overlay ) '' ) .attr ( `` data-overlay-url-action '' , anchor.attr ( `` data-overlay-url-action '' ) ) .hide ( ) .fadeIn ( ) ; $ ( `` div.old-overlay '' ) .fadeOut ( ) .removeClass ( `` old-overlay '' ) ; anchor.addClass ( `` overlay-exists '' ) ; } ) ; < div class= '' smart-search '' > < form role= '' form '' method= '' get '' class= '' form-horizontal '' action= '' /PharmaDotnet/ux/WebReport/Search '' > < div class= '' form-group '' > < div class= '' hidden-xs col-sm-1 col-md-1 col-lg-1 text-right '' > < label for= '' SearchPhrase '' class= '' control-label heading '' > Search < /label > < /div > < div class= '' col-xs-8 col-md-9 col-lg-10 '' > < input type= '' text '' value= '' '' placeholder= '' for products , companies , or therapy areas '' name= '' SearchPhrase '' id= '' SearchPhrase '' class= '' form-control '' > < /div > < div class= '' col-xs-4 col-sm-3 col-md-2 col-lg-1 '' > < input type= '' submit '' class= '' btn btn-default '' value= '' Search '' > < /div > < div class= '' what-to-search hidden-11 col-sm-11 col-sm-offset-1 '' > < div class= '' checkbox '' > < label > < input type= '' checkbox '' value= '' true '' name= '' WhatToSearch '' id= '' WhatToSearch '' > NewsManager Search Only < /label > < /div > < /div > < /div > < /form > < /div > | TagBuilder not generating unqiue id attribute values across ajax requests |
C_sharp : I have the following code : .This code compiles just fine ( why ? ) . However when I try to use it : I get : i.e . MethodToImplement is not visible from outside . But if I do the following changes : Then Main.cs also compiles fine . Why there is a difference between those two ? <code> // IMyInterface.csnamespace InterfaceNamespace { interface IMyInterface { void MethodToImplement ( ) ; } } // InterfaceImplementer.csclass InterfaceImplementer : IMyInterface { void IMyInterface.MethodToImplement ( ) { Console.WriteLine ( `` MethodToImplement ( ) called . `` ) ; } } // Main.cs static void Main ( ) { InterfaceImplementer iImp = new InterfaceImplementer ( ) ; iImp.MethodToImplement ( ) ; } InterfaceImplementer does not contain a definition for 'MethodToImplement ' // InterfaceImplementer.csclass InterfaceImplementer : IMyInterface { public void MethodToImplement ( ) { Console.WriteLine ( `` MethodToImplement ( ) called . `` ) ; } } | c # interface question |
C_sharp : I 've had a search round the internet and can not find anything that directly matches what I 'm after ... .I have a stored procedure that returns a fixed set of columns ( let 's say ColumnA , ColumnB and ColumnC ) and then additionally returns an indeterminate number / signature of additional columns ( maybe ColumnD , ColumnE and ColumnF , or ColumnF , ColumnP , ColumnT and ColumnW ) .The dynamic part of the query is determined by an Id param to the proc.Unfortunately I am not in control of the schema and it has been poorly designed to have a very large number of unrelated columns added to the end ( and they keep adding them ) , rather than having an additional table ( s ) to store this effectively.As a result , I am unable to return a determinate set of columns at compile time , so LINQ to SQL can not determine the return type of the stored procedure.Do I have any other options , or ways I can get around this ? Here 's an example of what I am doing below . Can I re-write this to work with LINQ to SQL ? I am writing the application with C # and SQL Server 2008 if that helps.Thanks . <code> CREATE PROCEDURE [ Foo ] . [ GetBar ] ( @ Id INT , @ FooVar VARCHAR ( 50 ) , @ BarVar DATE ) AS BEGINCREATE TABLE # TempTbl ( [ ColumnName ] VARCHAR ( 50 ) ) INSERT # TempTbl EXEC [ Foo ] .GetColumnNames @ IdDECLARE @ ColumnNameList NVARCHAR ( max ) SET @ ColumnNameList = `` SELECT @ ColumnNameList = COALESCE ( @ ColumnNameList + ' ] , [ ' , `` ) + ColumnName FROM # TempTblDROP TABLE # TempTblSELECT @ ColumnNameList = @ ColumnNameList + ' ] 'SELECT @ ColumnNameList = SUBSTRING ( @ ColumnNameList , 3 , LEN ( @ ColumnNameList ) ) DECLARE @ FixedColumns VARCHAR ( 200 ) DECLARE @ SelectQuery NVARCHAR ( max ) DECLARE @ WhereQuery VARCHAR ( 100 ) DECLARE @ FullQuery NVARCHAR ( max ) DECLARE @ ParamaterDef nvarchar ( 100 ) DECLARE @ Foo VARCHAR ( 50 ) DECLARE @ Bar DATESET @ FixedColumns = N ' [ ColumnA ] , [ ColumnB ] , [ ColumnC ] , 'SET @ SelectQuery = N'SELECT ' + @ FixedColumns + @ ColumnNameList + N ' FROM [ Foo ] . [ FooBar ] 'SET @ WhereQuery = N'WHERE [ Foo ] = @ Foo AND [ Bar ] = @ Bar'SET @ FullQuery = @ SelectQuery + @ WhereQuery SET @ ParamaterDef = N ' @ Foo VARCHAR ( 50 ) , @ Bar DATE'EXECUTE sp_executesql @ FullQuery , @ ParamaterDef , @ Foo = @ FooVar , @ Bar = @ BarVar END | How can I return variable column lengths via LINQ to SQL |
C_sharp : I had some verbose code : ... that Resharper offered to elegantize with a LINQ expression like so : ... but the subsequent Resharper inspection says about the code it generated ( above ) : `` Type cast is redundant '' ( referring to the `` c as ComboBox '' part ) , so that it ends up as : Should n't Resharper generate Resharper-approved code ? Or does it simply sometimes need two passes for it to fully `` gird up its loins '' ? <code> private bool AnyUnselectedCombox ( ) { bool anyUnselected = false ; foreach ( Control c in this.Controls ) { if ( c is ComboBox ) { if ( ( c as ComboBox ) .SelectedIndex == -1 ) { anyUnselected = true ; break ; } } } return anyUnselected ; } return this.Controls.OfType < ComboBox > ( ) .Any ( c = > ( c as ComboBox ) .SelectedIndex == -1 ) ; return this.Controls.OfType < ComboBox > ( ) .Any ( c = > c.SelectedIndex == -1 ) ; | Resharper yanks its own tail ; Is it right the first time or the last ? |
C_sharp : Similar question : Passing int list as a parameter to a web user controlIs there any similar example for enum type ? I am creating a asp.net custom control in which I want to pass comma separated list of enums as property.I am writing a TypeConverter for converting comma separated string values to List of Enum.In the ConvertTo method , How to create InstanceDescriptor object for list of enum ? My current code is as follows : This fails with the message I wonder why <code> //enumpublic enum MyEnum { Hello , World } //main methodList < MyEnum > list = new List < MyEnum > ( ) ; list.Add ( MyEnum.Hello ) ; list.Add ( MyEnum.World ) ; ConstructorInfo constructor = typeof ( List < MyEnum > ) .GetConstructor ( Type.EmptyTypes ) ; InstanceDescriptor idesc = new InstanceDescriptor ( constructor , list ) ; Length mismatch | How to create InstanceDescriptor for List of enum ? |
C_sharp : I have a Dictionary data type . My question is , is Dictionary.Keys.ToList ( ) [ i ] always correspond to Dictionary.Values.ToList ( ) [ i ] ? That is , will the following test always passes <code> public void DictionaryTest ( int i , Dictionary < U , T > dict ) { var key = dict.Keys.ToList ( ) [ i ] ; Assert.AreEqual ( dict [ key ] , dict.Values.ToList ( ) [ i ] ) ; } | Does Dictionary.Keys.List ( ) [ i ] correspond to Dictionary.Values.ToList ( ) [ i ] ? |
C_sharp : I 've encountered something quite surprising when using generic constraints with inheritance . I have an overloaded methods Foo that differ with parameter - either base or derived class instance . In both cases it 's generally just passing the instance to the second pair of overloaded methods - Bar.When I call Foo with base class instance , Bar overload for the base class is called . When I call Foo with derived class instance , Bar overload for the derived class is called . This is clear and expected.But when I tried to merge Foo methods into single one GenericFoo that use generics and constraints , methods are resolved differently - T is resolved correctly , but only base-class overload of Bar is called.Testing code - two first cases for non-generic old methods , two last for new generic method.And the result - note the difference in type resolved in Bar : It looks like the compiler binds all calls from GenericFoo to the least specific overload , even if all more specific-typed calls are known at compile time . Why is that , what is the reason for such behaviour ? Which part of specs defines this ? <code> public class Animal { } public class Cat : Animal { } public class AnimalProcessor { public static void Foo ( Animal obj ) { Console.WriteLine ( `` Foo ( Animal ) '' ) ; Bar ( obj ) ; } public static void Foo ( Cat obj ) { Console.WriteLine ( `` Foo ( Cat ) '' ) ; Bar ( obj ) ; } // new generic method to replace the two above public static void GenericFoo < T > ( T obj ) where T : Animal { Console.WriteLine ( `` Foo ( generic ) '' ) ; Bar ( obj ) ; } public static void Bar ( Animal obj ) { Console.WriteLine ( `` Bar ( Animal ) '' ) ; } public static void Bar ( Cat obj ) { Console.WriteLine ( `` Bar ( Cat ) '' ) ; } } Console.WriteLine ( `` Animal ( ) '' ) ; AnimalProcessor.Foo ( new Animal ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Cat ( ) '' ) ; AnimalProcessor.Foo ( new Cat ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Animal ( ) '' ) ; AnimalProcessor.GenericFoo ( new Animal ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Cat ( ) '' ) ; AnimalProcessor.GenericFoo ( new Cat ( ) ) ; Console.ReadLine ( ) ; Animal ( ) Foo ( Animal ) Bar ( Animal ) Cat ( ) Foo ( Cat ) Bar ( Cat ) Animal ( ) Foo ( generic ) Bar ( Animal ) Cat ( ) Foo ( generic ) Bar ( Animal ) | Two-step method resolution with inheritance and generic constraints |
C_sharp : I wrote the following method to remove the namespace in brackets from strings.I would like to make this as fast as possible.Is there a way to speed up the following code ? <code> using System ; namespace TestRemoveFast { class Program { static void Main ( string [ ] args ) { string [ ] tests = { `` { http : //company.com/Services/Types } ModifiedAt '' , `` { http : //company.com/Services/Types } CreatedAt '' } ; foreach ( var test in tests ) { Console.WriteLine ( Clean ( test ) ) ; } Console.ReadLine ( ) ; } static string Clean ( string line ) { int pos = line.IndexOf ( ' } ' ) ; if ( pos > 0 ) return line.Substring ( pos + 1 , line.Length - pos - 1 ) ; else return line ; } } } | How can I speed up this method which removes text from a string ? |
C_sharp : So , in visual studio , if you type something like this : Then a little tooltip thing pops up saying that you can press TAB to turn it into this : Then if you press TAB again , it generates : Of course , this is very useful . But I find myself more often needing a construction like so : So , is there anyway to add a new shortcut , or at least change the functionality of pressing TAB ? <code> retryExecutor.Retrying += retryExecutor.Retrying+= new EventHandler ( retryExecutor_Retrying ) ; void retryExecutor_Retrying ( object sender , EventArgs e ) { throw new NotImplementedException ( ) ; } retryExecutor.Retrying += ( o , e ) = > { } ; | C # event subscription in Visual Studio 2010 |
C_sharp : We have an internal app ( Thick Client ) that relies on our central SQL server . The app is a Desktop app that allows the users to work in `` Offline '' mode ( e.g . Outlook ) . What I need to accomplish is a way to accurately tell if SQL is available or not.What I have so far : I currently use the following method -- > I am not crazy about this approach for the following reasons . Prone to false NegativesNeeds to be `` manually '' calledSeems `` smelly '' ( the try/catch ) I had thought to use a timer and just call this every X ( 3 ? ? ) minutes and also , if a negative result , try a second time to reduce the false negatives.There is a similar question here -- > Detecting if SQL server is runningbut it differs from mine in these ways : I am only checking 1 serverI am looking for a reactive way versus proactiveSo in the end , is there a more elegant way to do this ? It would all be `` in-network '' detection.P.S . To offer some background as requested in an answer below : My app is a Basic CRUD app that can connect to our Central SQL Server or a local SQLExpress Server . I have a Merge Replication Module that keeps them in Sync and the DAL is bound to a User.Setting value . I can , already , manually flip them from Central to Local and back . I just want to implement a way to have it automatically do this . I have a NetworkChangeDetection class that works quite well but , obviously , does not detect the Remote SQL 's . <code> internal static void CheckSQLAvailability ( ) { using ( TcpClient tcpc = new TcpClient ( ) ) { try { tcpc.Connect ( Settings.Default.LiveSQLServer , Settings.Default.LiveSQLServerPort ) ; IsSQLAvailable = true ; } catch { IsSQLAvailable = false ; } } } | How to Implement Exchange like availability monitoring of internal SQL Server |
C_sharp : On some machines but not on others I get System.ObjectDisposedException using this class . After modifying GenerateDiff ( ) to : I ca n't reproduce the exception.Interesting thing is that this is not working : I 'm using an instance of this class diff here for example . No using or Dispose anywhere . No tasks or threads.Could someone please explain the root cause ? Thank you . ( Our guess is that this is because of IEnumerable < > implements lazy loading and the garbage collector closes the reader before I want to access InFirstNotInSecond or InSecondNotInFirst . But using GC.Collect ( ) there are still no exception on some machines . ) <code> class LogComparer { private string firstFile ; private string secondFile ; private IEnumerable < string > inFirstNotInSecond ; private IEnumerable < string > inSecondNotInFirst ; public LogComparer ( string firstFile , string secondFile ) { if ( ! File.Exists ( firstFile ) || ! File.Exists ( secondFile ) ) { throw new ArgumentException ( `` Input file location is not valid . `` ) ; } this.firstFile = firstFile ; this.secondFile = secondFile ; GenerateDiff ( ) ; } public string FirstFile { get { return firstFile ; } } public bool IsEqual { get { return inFirstNotInSecond.SequenceEqual ( inSecondNotInFirst ) ; } } public string SecondFile { get { return secondFile ; } } public IEnumerable < string > InFirstNotInSecond { get { return inFirstNotInSecond ; } } public IEnumerable < string > InSecondNotInFirst { get { return inSecondNotInFirst ; } } private void GenerateDiff ( ) { var file1Lines = File.ReadLines ( firstFile ) ; var file2Lines = File.ReadLines ( secondFile ) ; inFirstNotInSecond = file1Lines.Except ( file2Lines ) ; inSecondNotInFirst = file2Lines.Except ( file1Lines ) ; } } System.ObjectDisposedException : Can not read from a closed TextReader.ObjectName : at System.IO.__Error.ReaderClosed ( ) at System.IO.StreamReader.ReadLine ( ) at System.IO.File. < InternalReadLines > d__0.MoveNext ( ) at System.Linq.Enumerable. < ExceptIterator > d__99 ` 1.MoveNext ( ) at System.Linq.Enumerable.Any [ TSource ] ( IEnumerable ` 1 source , Func ` 2 predicate ) private void GenerateDiff ( ) { var file1Lines = File.ReadLines ( firstFile ) .ToList ( ) ; var file2Lines = File.ReadLines ( secondFile ) .ToList ( ) ; inFirstNotInSecond = file1Lines.Except ( file2Lines ) ; inSecondNotInFirst = file2Lines.Except ( file1Lines ) ; } private void GenerateDiff ( ) { var file1Lines = File.ReadLines ( firstFile ) ; var file2Lines = File.ReadLines ( secondFile ) ; inFirstNotInSecond = file1Lines.Except ( file2Lines ) .ToList ( ) ; inSecondNotInFirst = file2Lines.Except ( file1Lines ) .ToList ( ) ; } if ( diff.InSecondNotInFirst.Any ( s = > ! s.Contains ( `` bxsr '' ) ) ) | IEnumerable < string > System.ObjectDisposedException |
C_sharp : I 'm curious to know if there is such an operator that will allow for the followingInitial line : Desired Line : ( Variable repetition assumption ? ) Im looking to educate myself a little on how these operators work at a lower level , explanation as to why not would be much appreciated.Thanks , <code> if ( foo > 1 & & foo < 10 ) if ( foo > 1 & & < 10 ) | In c # is there such an operator to mean 'AndAlso ' with reference to the first variable ? |
C_sharp : I have to strip a file path and get the parent folder.Say my path is I need to getFile Name = File.jogFolder it resides in = FolderBAnd parent folder = FolderAI always have to go 2 levels up from where the file resides.Is there an easier way or is a regular expression the way to go ? <code> \\ServerA\FolderA\FolderB\File.jpg | Do I use a regular expression on this file path ? |
C_sharp : I 'm looking for a serializer which could take an instance , and serialize it to a string which would contain c # code , representing the contents of the graph.The class would function similar to SerializeObject in JSON.NET.I know only a very narrow set of structures will work , but the ones I 'm interested in are quite simple and they would . Bonus points if anyone knows of a Visual Studio Visualizer with similar functionality.Edit : The output will be used in a different application at compile time . I do n't need to deserialize the output ( c # code ) at runtime , it gets saved to a file for analysis.Output : <code> var foo = new Foo ( ) { Number = 1 , Bar = new Bar ( ) { Str = `` Bar '' } } ; string sourceCode = Magic.SerializeObject ( foo ) ; Foo obj = new Foo ( ) ; obj.Number = 1 ; obj.RefType = null ; // infer thisobj.Bar = new Bar ( ) ; obj.Bar.Str = `` Bar '' ; | Is there a serializer for .net which will output c # code ? |
C_sharp : I have a project where I have to take in input of names , weights , and heights and put them into arrays and display them into a TextBox like thisI have been able to populate my arrays but I do not understand how to it output it like the example above . Currently my output is all names , THEN all weights then all heights . Could someone explain how I would be able to make it display like the example ? The code I have so far isThe array can store up to 10 values and I am required to use arrays and not lists . <code> name = `` ... '' weight = `` ... '' height= `` ... '' private void ShowButton_Click ( object sender , EventArgs e ) { txtShow.Text += string.Join ( System.Environment.NewLine , nameArray ) ; txtShow.Text += string.Join ( System.Environment.NewLine , weightArray ) ; txtShow.Text += string.Join ( System.Environment.NewLine , heightArray ) ; } private void AddButton_Click ( object sender , EventArgs e ) { if ( this.index < 10 ) { nameArray [ this.index ] = nameBox.Text ; weightArray [ this.index ] = double.Parse ( weightBox.Text ) ; heightArray [ this.index ] = double.Parse ( heightBox.Text ) ; this.index++ ; } } | Displaying Multiple Arrays |
C_sharp : I am looking for ways of making the following more concise.In particular specifying the type again when creating the mock seems redundant . For example I can write it this way and use reflection to get the type and create the stub automatically : This would work but the compiler can no longer detect that presenter is assigned and starts issuing warnings . This also makes ReSharper very unhappy.Can anyone suggest a better approach ? <code> public class MyTests { IPresenter presenter ; [ SetUp ] public void SetUp ( ) { presenter = MockRepository.GenerateStub < IPresenter > ( ) ; } ... } public class MyTests { IPresenter presenter ; [ SetUp ] public void SetUp ( ) { Stub ( x = > x.presenter ) ; } void Stub ( Expression < Func < MyTests , object > > expression ) { ... } } | Getting DRY with Rhino Mocks |
C_sharp : How can I find the set of items that occur in 2 or more sequences in a sequence of sequences ? In other words , I want the distinct values that occur in at least 2 of the passed in sequences.Note : This is not the intersect of all sequences but rather , the union of the intersect of all pairs of sequences.Note 2 : The does not include the pair , or 2 combination , of a sequence with itself . That would be silly.I have made an attempt myself , but I 'm concerned that this might be sub-optimal , I think it includes intersects of pair A , B and pair B , A which seems inefficient . I also think there might be a more efficient way to compound the sets as they are iterated.I include some example input and output below : returnsandreturnsI 'm looking for the best combination of readability and potential performance.EDITI 've performed some initial testing of the current answers , my code is here . Output below.At the moment , it looks as if Tim Schmelter 's answer performs better by at least an order of magnitude . <code> public static IEnumerable < T > UnionOfIntersects < T > ( this IEnumerable < IEnumerable < T > > source ) { var pairs = from s1 in source from s2 in source select new { s1 , s2 } ; var intersects = pairs .Where ( p = > p.s1 ! = p.s2 ) .Select ( p = > p.s1.Intersect ( p.s2 ) ) ; return intersects.SelectMany ( i = > i ) .Distinct ( ) ; } { { 1 , 1 , 2 , 3 , 4 , 5 , 7 } , { 5 , 6 , 7 } , { 2 , 6 , 7 , 9 } , { 4 } } { 2 , 4 , 5 , 6 , 7 } { { 1 , 2 , 3 } } or { { } } or { } { } Original valid : TrueDoomerOneLine valid : TrueDoomerSqlLike valid : TrueSvinja valid : TrueAdricadar valid : TrueSchmelter valid : TrueOriginal 100000 iterations in 82msDoomerOneLine 100000 iterations in 58msDoomerSqlLike 100000 iterations in 82msSvinja 100000 iterations in 1039msAdricadar 100000 iterations in 879msSchmelter 100000 iterations in 9ms | The union of the intersects of the 2 set combinations of a sequence of sequences |
C_sharp : Between these two : With Property : With Field : Apparently I 'm supposed to pick the first one . Why ? I 've heard the argument that the point here is to allow interface changes , butif I have the second one , and change it to the first one , no other code shouldever have to change . When recompiled everything 's just going to point to theproperty instead.Am I missing something important here ? <code> class WithProperty { public string MyString { get ; set ; } } class WithField { public string MyString ; } | Why should I use an automatically implemented property instead of a field ? |
C_sharp : I have started to learn c # . I am trying to declare a class and some variables and trying to do a simple concatenation of strings . But i am getting some error - the code is belowThe error i am getting is - a field initializer can not reference the non-static field , method , property 'ConsoleApplication1.Class1.s1Can someone explain what is happening here.Thanks . <code> namespace ConsoleApplication1 { class Class1 { string s1 = `` hi '' ; string s2 = `` hi '' ; string s3 = s1 + s2 ; } } | Need some explaination with beginner C # code |
C_sharp : I have a Linq DataContext as a database for the application . I have set up the MVVM pattern and am able to insert new records into the database . However when I load these records and try update them a new instance of the record is being created in the background and being updated with the property changes . So when they UI is invoking the save command the originally loaded instance of the record has no changes and is not saved.from what I can tell this is the sequence of eventsLoad Instance 1Start updating propertyNotifyPropertyChanging is calledNew instance2 is loadedNew Instance2 is updatedInvoke save changes from UI for Instance 1No changes are made because Instance 1 has not been updatedBelow is the code I have : /* This is the Entity *//* This is the data context *//* This is the View Model */ <code> [ Table ] public class User : IDisposable , INotifyPropertyChanged , INotifyPropertyChanging { private MyDataContext context ; public event PropertyChangedEventHandler PropertyChanged ; private void NotifyPropertyChanged ( String propertyName ) { PropertyChangedEventHandler handler = PropertyChanged ; if ( null ! = handler ) { handler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public event PropertyChangingEventHandler PropertyChanging ; private void NotifyPropertyChanging ( String propertyName ) { PropertyChangingEventHandler handler = PropertyChanging ; if ( null ! = handler ) { handler ( this , new PropertyChangingEventArgs ( propertyName ) ) ; } } public void Dispose ( ) { context.Dispose ( ) ; } private Guid _id ; [ Column ( IsPrimaryKey = true , IsDbGenerated = false , DbType = `` UNIQUEIDENTIFIER NOT NULL '' , CanBeNull = false , AutoSync = AutoSync.OnInsert ) ] public Guid Id { get { return _id ; } set { if ( _id ! = value ) { NotifyPropertyChanging ( `` Id '' ) ; _id = value ; NotifyPropertyChanged ( `` Id '' ) ; } } } private string _name ; [ Column ( CanBeNull = false ) ] public string Name { get { return _name ; } set { if ( _name ! = value ) { NotifyPropertyChanging ( `` Name '' ) ; // This line creates the new entity _name = value ; NotifyPropertyChanged ( `` Name '' ) ; } } } public User ( ) { this.context = MyDataContext.GetContext ( ) ; } public override void SaveChanges ( ) { if ( _id == Guid.Empty ) { this.Id = Guid.NewGuid ( ) ; context.Users.InsertOnSubmit ( this ) ; context.SubmitChanges ( ) ; } else { context.SubmitChanges ( ) ; } } public static User NewInstance ( ) { return new User { Name = String.Empty } ; } } public class MyDataContext : DataContext { // Specify the connection string as a static , used in main page and app.xaml . public static string ConnectionString = `` Data Source=isostore : /MyApp.sdf ; Password=pwd '' ; public MyDataContext ( string connectionString ) : base ( connectionString ) { } public static MyDataContext GetContext ( ) { var context = new MyDataContext ( ConnectionString ) ; return context ; } public Table < User > Users ; } public sealed class UserViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged ; protected void NotifyPropertyChanged ( String propertyName ) { PropertyChangedEventHandler handler = PropertyChanged ; if ( handler ! = null ) { handler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } private User _user ; public UserViewModel ( Guid id ) { using ( MyDataContext context = new MyDataContext ( MyDataContext.ConnectionString ) ) { _User = context.User.First ( u = > u.Id == id ) ; } } public UserViewModel ( User user ) { _user = user ; } public UserViewModel ( ) { _user = User.NewInstance ( ) ; } public string Name { get { return _user.Name ; } set { _user.Name = value ; NotifyPropertyChanged ( `` Name '' ) ; } } private ICommand _saveCommand ; public ICommand SaveCommand { get { return _saveCommand ? ? ( _saveCommand = new GenericCommand ( ( ) = > { _user.SaveChanges ( ) ; } , true ) ) ; } } } | Windows phone 8 MVVM Linq table Creates new instance on NotifyPropertyChanging |
C_sharp : In a website , if I have a class : In a page I have : How many times the query will be compiled ? Every time the page loads ... ? Once in the application ... ? <code> public class Provider { static readonly Func < Entities , IEnumerable < Tag > > AllTags = CompiledQuery.Compile < Entities , IEnumerable < Tag > > ( e = > e.Tags ) ; public IEnumerable < Tag > GetAll ( ) { using ( var db = new Entities ( ) ) { return AllTags ( db ) .ToList ( ) ; } } } protected void Page_Load ( object sender , EventArgs ev ) { ( new Provider ( ) ) .GetAll ( ) ; } | How many times does a compiled query have to recompile during the lifecycle of an application ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.