lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 IV...
FaultException < T > : FaultException ( FaultException derived from exception ) FaultException : Exception public class ValidationFault : IValidationFault { } FaultException < ValidationFault > faultExceptionObject=new FaultException < ValidationFault > ( new ValidationFault ( ) ) public Exception HandleException ( Exc...
Generic conversion
C#
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...
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#
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 prod...
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#
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 foll...
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 =...
Generic extension methods in C # : what will happen in this edge case ?
C#
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...
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 Valu...
Explicit Loading N : M with Filtering
C#
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 sti...
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#
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 tha...
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 ...
Fetch particular string from particular block
C#
SAMPLE CODE : VS : Why is it that I always see people creating assigning PropertyChanged to a `` handler '' instead of just using it ?
public event PropertyChangedEventHandler PropertyChanged ; private void OnPropertyChanged ( String propertyName ) { PropertyChangedEventHandler handler = PropertyChanged ; if ( handler ! = null ) { handler ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public event PropertyChangedEventHandler PropertyCh...
Events - Handler vs direct access ? Why ?
C#
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 argu...
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#
I have a string array . What is the simplest way to check if all the elements of the array are numbers
string [ ] str = new string [ ] { `` 23 '' , `` 25 '' , `` Ho '' } ;
Easiest way to check numbers
C#
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...
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 ...
How can you cast T to a class to match a `` where T : class '' constraint ?
C#
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...
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.C...
Compiled query fails - Query was compiled for a different mapping source than the one associated with the specified DataContext
C#
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 , bu...
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 ; }...
How to avoid creating unneeded object in an elegant way ?
C#
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 ?
string val = `` 3.5 '' ; DateTime oDate = DateTime.Parse ( val ) ;
Decimal values recognized as DateTime instead of returning false from DateTime.Parse
C#
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...
< 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 > < EventTrigg...
Block MouseLeave trigger if object is disposed of
C#
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 comp...
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#
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 cod...
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 '' ...
Why the use of name arguments in a function actually generate more code ?
C#
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 i...
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#
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 ach...
ListRowFilter rowFilter = mTDSE.CreateListRowFilter ( ) ; rowFilter.SetCondition ( `` StartDate '' , sDate ) ; rowFilter.SetCondition ( `` EndDate '' , eDate ) ; rowFilter.SetCondition ( `` PublicationTarget '' , pubStgTarget ) ; rowFilter.SetCondition ( `` PublicationTarget '' , pubStgTarget ) ; rowFilter.SetCondition...
Tridion 2009 - Using Interops - Is there a possibility to add multiple setConditions for the same Name
C#
FSharp code is structured as following ( I 'm not in control of the source ) .C # calling code is as follows
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 C...
How to call F # type extensions ( static member functions ) from C #
C#
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 ...
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#
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 ...
public List < ( Of < ( < 'T > ) > ) > .. : :..Enumerator GetEnumerator ( ) public List < T > .Enumerator GetEnumerator ( )
public List < ( Of < ( < 'T > ) > ) > .. : :..Enumerator ?
C#
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 Mod...
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.D...
Argument out of range exception for decimal SQL Server EF C #
C#
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 chi...
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....
Error using Serge Zab 's helper for optgroup dropdowns
C#
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 abou...
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#
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 '...
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#
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 bas...
XXX XX X XX XXX XXX XXXXXXXXXXXXXXX XXXXX XX XX X X
Representing a Gameworld that is Irregularly shaped
C#
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 hav...
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 ( Te...
How to hand over the value of UpdateSourceTrigger to UserControl or update it at runtime ?
C#
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 rece...
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.Ten...
How to map complex linq to object
C#
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 ?
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 $...
Differences in LINQ vs Method expression
C#
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 call...
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#
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 , an...
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 ( `` S...
Debugging Stack overflow errors on background services
C#
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 .
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#
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 ...
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 CharUnicod...
Why does every Char static `` Is ... '' have a string overload , e.g . IsWhiteSpace ( string , Int32 ) ?
C#
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 .
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 StringDicti...
Looking for a slicker way to convert delimited string to StringDictionary
C#
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 ?
files = ( from file in Directory.EnumerateFiles ( sourceFolder , filePattern , SearchOption.TopDirectoryOnly ) select file ) .ToList ( ) ;
.Net file pattern picks up unwanted files ( C # )
C#
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 concer...
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#
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 ...
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#
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 w...
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 < = VAUXHA...
How do I do list traversal ?
C#
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 co...
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 ( ) ; } priva...
Did I break Encapsulation ?
C#
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 th...
IDocument itemPropertyInfo [ ] documentProperties = item.GetType ( ) .GetProperties ( ) ; PropertyInfo property = documentProperties.First ( ) ; Type typeOfProperty = property.PropertyType ; if ( typeOfProperty.IsGenericType ) { Type typeOfProperty = property.PropertyType.GetGenericTypeDefinition ( ) ; if ( typeOfPrope...
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#
I have a datatable with the following information : I only need to remove the next matched items , like this : I tried : Result : Any ideas ?
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.articlepri...
Linq Distinct only in next rows match
C#
Consider the following code : What does this accomplish that having the public members alone would not ?
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#
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 , i...
< ListView Grid.Row= '' Name= '' LineSecondTrackListView '' ItemsSource= '' { x : Bind _LineSecondTrackBusStops } '' ContainerContentChanging= '' SetBusStopViewAttribute '' ItemTemplate= '' { StaticResource BusStopListViewStyle } '' SelectionMode= '' Single '' SelectionChanged= '' LineTrackListView_SelectionChangedAsyn...
How to remove broken background of ListViewItem In UWP ?
C#
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 ...
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#
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 ...
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 ( ) ; lon...
Why are some iterators faster than others in C # ?
C#
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 w...
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#
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 ...
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.CurrentV...
Implementing history tracking in SaveChanges override
C#
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 ICo...
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.Reflectio...
Why are my types not marked as equal ?
C#
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 ca...
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#
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 f...
`` 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...
Regex split while reading from file
C#
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 value...
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 ab...
Mapping the same entity to different tables
C#
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...
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#
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 pro...
[ __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#
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 ...
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 <...
Why is my subclass still generic when I supply a type argument to the base class ?
C#
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 )
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 aggreg...
Can operations be generalized ?
C#
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 wo...
< 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 : ...
Is there anyway of consolidating similar data bindings and/or triggers in XAML ?
C#
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 metho...
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 Cons...
Determine if two MethodInfo instances represent the same ( non-virtual ) method through inheritance
C#
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 ...
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#
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 ...
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...
Why does this addition of byte* and uint fail to carry into the higher dword ?
C#
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 ' ...
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...
Data binding to a nested property with possibly null parent
C#
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...
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 ( ) ) .Sep...
In functional list manipulation , what do we call `` inserting something between each item '' ?
C#
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 ? )
static unsafe void Main ( ) { int x ; int* p = & x ; //No error ? ! x += 2 ; //No error ? ! }
No `` Unassigned Local Variable '' error ?
C#
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 ?
var solution = ( IVsSolution ) Microsoft.VisualStudio.Shell.Package.GetGlobalService ( typeof ( IVsSolution ) ) ;
How can I get only projects from the solution ?
C#
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 ...
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 boardGene...
How can I keep my unit tests independent of each other in this simple case ?
C#
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 seco...
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 Object...
Is it OK to use ` using ` like this ?
C#
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 uniq...
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#
I need to generate this simple looking XML , looking for a clean way to generate it .
< 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#
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 vie...
< ContentPage.Content > < StackLayout x : Name= '' layoutWrap '' VerticalOptions= '' FillAndExpand '' HorizontalOptions= '' FillAndExpand '' > < controls : StateContainer State= '' { Binding State } '' > < controls : StateCondition Is= '' Loading '' > < StackLayout Orientation= '' Vertical '' HorizontalOptions= '' Cent...
Xamarin Forms State Container View not Respecting Layout Options
C#
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 diff...
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 ChildInsid...
Why this difference of handling method ambiguity in Java & c # ?
C#
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 .
bool isPaid = visit.Referrals.Exists ( delegate ( AReferral r ) { return r.IsPaidVisit ; } ) ;
Do List.Exist using Linq
C#
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 Run...
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 ; NotifyPropertyCha...
How to defer data querying in Silverlight ViewModel class ?
C#
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 ...
string.Join ( null , System.Text.RegularExpressions.Regex.Split ( expr , `` [ ^\\d ] '' ) ) ;
extracting integer from string
C#
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 ...
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#
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 ...
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 < ...
Jenkins failed unit CanExecute test 's methods nondeterministic
C#
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 ...
|__| || | ||__| || | ||__| V| d||__|| c||__|| b||__|| a|
To MultiThread or not to MultiThread ?
C#
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 re...
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 Note...
Capture keyboard shortcuts and forward
C#
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 Goog...
for ( int i = checkedListBox.Items.Count - 1 ; i > = 0 ; i -- ) { checkedListBox.Items.RemoveAt ( i ) ; }
CheckedListBox memory leak
C#
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 somet...
public class AuthorizeWithLoggingAttribute : AuthorizeAttribute { public override void OnAuthorization ( AuthorizationContext filterContext ) { if ( ! base.AuthorizeCore ( httpContext ) ) { Log ( FilterContext ) ; } } } var filters = new FilterInfo ( FilterProviders.Providers.GetFilters ( controllerContext , actionDesc...
Detecting if AuthorizationAttribute manually called
C#
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 ...
@ 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...
TagBuilder not generating unqiue id attribute values across ajax requests
C#
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 ?
// IMyInterface.csnamespace InterfaceNamespace { interface IMyInterface { void MethodToImplement ( ) ; } } // InterfaceImplementer.csclass InterfaceImplementer : IMyInterface { void IMyInterface.MethodToImplement ( ) { Console.WriteLine ( `` MethodToImplement ( ) called . `` ) ; } } // Main.cs static void Main ( ) { In...
c # interface question
C#
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 , ...
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 ( @ Colum...
How can I return variable column lengths via LINQ to SQL
C#
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 ...
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 ) .S...
Resharper yanks its own tail ; Is it right the first time or the last ?
C#
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 C...
//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 ...
How to create InstanceDescriptor for List of enum ?
C#
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
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#
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...
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 tw...
Two-step method resolution with inheritance and generic constraints
C#
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 ?
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.Re...
How can I speed up this method which removes text from a string ?
C#
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 ne...
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#
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 -- ...
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#
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 thread...
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 ...
IEnumerable < string > System.ObjectDisposedException
C#
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 ,
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#
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 ?
\\ServerA\FolderA\FolderB\File.jpg
Do I use a regular expression on this file path ?
C#
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 quit...
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#
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 heigh...
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.NewLi...
Displaying Multiple Arrays
C#
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 a...
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 > > express...
Getting DRY with Rhino Mocks
C#
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 ...
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 ) ...
The union of the intersects of the 2 set combinations of a sequence of sequences
C#
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...
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#
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...
namespace ConsoleApplication1 { class Class1 { string s1 = `` hi '' ; string s2 = `` hi '' ; string s3 = s1 + s2 ; } }
Need some explaination with beginner C # code
C#
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 t...
[ Table ] public class User : IDisposable , INotifyPropertyChanged , INotifyPropertyChanging { private MyDataContext context ; public event PropertyChangedEventHandler PropertyChanged ; private void NotifyPropertyChanged ( String propertyName ) { PropertyChangedEventHandler handler = PropertyChanged ; if ( null ! = han...
Windows phone 8 MVVM Linq table Creates new instance on NotifyPropertyChanging
C#
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 ... ?
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 ...
How many times does a compiled query have to recompile during the lifecycle of an application ?