lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Following code to do a simple property assignment person.Name = `` Joe Bloggs '' by dynamically creating a method using an Expression Tree fails with a NullReferenceException - it 's like the person parameter I create is n't being passed in.Any ideas ? UpdateThanks for the great answers , I saw @ decPL 's first that le...
class Person { public string Name { get ; set ; } } static void ExpressionTest ( ) { var personParam = Expression.Parameter ( typeof ( Person ) , `` person '' ) ; var block = Expression.Block ( new [ ] { personParam } , Expression.Assign ( Expression.Property ( personParam , `` Name '' ) , Expression.Constant ( `` Joe ...
Dynamic Methods with Expression Trees : Simple property assignment fails
C#
I 've got controller code like this all over my ASP.NET MVC 3 site : Basically , i 'm referring to the code in the threading block . All things need to happen , but the user does n't need to wait for them ( good case for a background thread , right ? ) .Just to be clear , i use caching ( regular ASP.NET data cache ) al...
[ HttpPost ] public ActionResult Save ( PostViewModel viewModel ) { // VM - > Domain Mapping . Definetely belongs here . Happy with this . var post = Mapper.Map < PostViewModel , Post > ( viewModel ) ; // Saving . Again , fine . Controllers job to update model . _postRepository.Save ( post ) ; // No . Noooo..caching , ...
Can this MVC code be refactored using a design pattern ?
C#
In our organization we have the need to let employees filter data in our web application by supplying WHERE clauses . It 's worked great for a long time , but we occasionally run into users providing queries that require full table scans on large tables or inefficient joins , etc.Some clown might write something like :...
select * from big_table whereName in ( select name from some_table where name like ' % search everything % ' ) or name in ( ' a ' , ' b ' , ' c ' ) or price < 20or price > 40or exists ( select 1 from some_other_table where col1 + col2 + col3 = 4 ) or exists ( select 1 from table_a , table+b )
Ensure `` Reasonable '' queries only
C#
All of the above are possible except for the constant field of struct type.I can see why the non-string reference types would default to the only literal expression they can represent - null - but if I 'm not mistaken the default value of a struct is an instance of the struct with all its fields set to their default va...
class T { enum E { } struct S { } interface I { } delegate void D ( ) ; class C { } const E e = new E ( ) ; //const S s = default ( S ) ; // ERROR const I i = default ( I ) ; const D d = default ( D ) ; const C c = default ( C ) ; const int x = 10 ; const string y = `` s '' ; private void MyMethod ( E e = new E ( ) , S...
Why ca n't a constant field be of non-built-in struct type in C # ?
C#
The point of M-V-VM as we all know is about speraration of concerns . In patterns like MVVM , MVC or MVP , the main purpose is to decouple the View from the Data thereby building more flexible components . I 'll demonstrate first a very common scenario found in many WPF apps , and then I 'll make my point : Say we have...
public class StockQuote { public string Symbol { get ; set ; } public double Price { get ; set ; } } public class StockQuoteViewModel { private ObservableCollection < StockQuote > _quotes = new ObservableCollection < StockQuote > ( ) ; public ObservableCollection < StockQuote > Quotes { get { return _quotes ; } } } < W...
M-V-VM , is n't the Model leaking into the View ?
C#
I 'm playing around with a simple console app that creates one thread and I do some inter thread communication between the main and the worker thread.I 'm posting objects from the main thread to a concurrent queue and the worker thread is dequeueing that and does some processing.What strikes me as odd , is that when I ...
public class SingleThreadDispatcher { public long Count ; private readonly ConcurrentQueue < Action > _queue = new ConcurrentQueue < Action > ( ) ; private volatile bool _hasMoreTasks ; private volatile bool _running = true ; private int _status ; private readonly AutoResetEvent _signal = new AutoResetEvent ( false ) ;...
Two threads one core
C#
Is there a c # library that can help to write and indent Javascript code.It 's because I 'm writing some c # code that generated some Javascript code . Something like this : And I find that generated a lot of ugly code.So , I thought that maybe a existing library can help me doing that ?
js += `` < script type=\ '' text/javascript\ '' > \n '' ; js += `` function ( ) ... \n '' ;
Library to write javascript code
C#
I want to have an abstract UserControl , BaseControl , that implements an interface IBaseControl.However , setting the class to abstract breaks VisualStudio designer ( This is a known issue with Visual Studio ( e.g. , see this StackOverflow posting for more info ) , and as far as I know , there 's no change expected in...
public class BaseControl : UserControl , IBaseControl { /// < summary > /// This IBaseControl method is not abstract because /// that breaks the Designer /// < /summary > public virtual void LoadSettings ( ) { throw new NotImplementedException ( `` Implement in derived class . `` ) ; } private void BaseControl_Load ( o...
VisualStudio 2010 Designer throws on implemented virtual method
C#
I 'd like to convert string containing recursive array of strings to an array of depth one.Example : Seems quite simple . But , I come from functional background and I 'm not that familiar with .NET Framework standard libraries , so every time ( I started from scratch like 3 times ) I end up just plain ugly code . My l...
StringToArray ( `` [ a , b , [ c , [ d , e ] ] , f , [ g , h ] , i ] '' ) == [ `` a '' , `` b '' , `` [ c , [ d , e ] ] '' , `` f '' , `` [ g , h ] '' , `` i '' ]
parsing of a string containing an array
C#
I have a .wav file and I am plotting waveform using ZedGraph . I am calculating the energies of .wav file of each second and if energy is less then 4 I want to draw the sample in different color . I have created two PointPairLlist and LineItem to do this but there is a problem while merging these two list . Here is my ...
LineItem myCurveAudio ; LineItem myCurveAudio2 ; PointPairList list1 = new PointPairList ( ) ; PointPairList list2 = new PointPairList ( ) ; while ( true ) { for ( int i = 0 ; i < fmainBuffer.Length ; i++ ) { float segmentSquare = fmainBuffer [ i ] * fmainBuffer [ i ] ; listOfSquaredSegment.Add ( segmentSquare ) ; } fl...
Merging multiple pointpairlist
C#
I have spent hours on a debugging problem only to have a more experienced guy look at the IL ( something like 00400089 mov dword ptr [ ebp-8 ] , edx ) and point out the problem . Honestly , this looks like Hebrew to me - I have no idea what the heck it 's saying.Where can I learn more about this stuff and impress every...
.maxstack 2.entrypoint.locals init ( valuetype [ MathLib ] HangamaHouse.MathClass mclass ) ldloca mclassldc.i4 5
How to become an MSIL pro ?
C#
I have a string [ ] which contains code . Each line contains some leading spaces . I need to 'unindent ' the code as much as possible without changing the existing formatting.For instance the contents of my string [ ] might beI 'd like to find a reasonably elegant and efficient method ( LINQ ? ) to transform it toTo be...
public class MyClass { private bool MyMethod ( string s ) { return s == `` '' ; } } public class MyClass { private bool MyMethod ( string s ) { return s == `` '' ; } } IEnumerable < string > UnindentAsMuchAsPossible ( string [ ] content ) { return ? ? ? ; }
Efficient way to unindent lines of code stored in a string
C#
I have ; How much space does this need ? Does linq build up a list of the above Where ( ) condition , or is Max ( ) just iterating through the IEnumerable keeping track of what is the current Max ( ) ? And where can I find more info about this , besides asking on SO f
var maxVal = l.TakeWhile ( x= > x < val ) .Where ( x= > Matches ( x ) ) .Max ( ) ;
space complexity of a simple linq ( to objects ) query
C#
For those who are interested in how I do the benchmark , look here , I simple replace / add a couple of methods near the build in `` Loop 1K '' method.Sorry , I forgot to say my testing environment . .Net 4.5 x64 ( do n't pick 32bit preferred ) . in x86 both methods take 5x as much as time.Loop2 takes 3x as much time a...
public long Loop ( long testSize ) { long ret = 0 ; for ( long i = 0 ; i < testSize ; i++ ) { long p = 0 ; for ( int j = 0 ; j < 1000 ; j++ ) { p+=10 ; } ret+=p ; } return ret ; } public long Loop2 ( long testSize ) { long ret = 0 ; for ( long i = 0 ; i < testSize ; i++ ) { for ( int j = 0 ; j < 1000 ; j++ ) { ret+=10 ...
How to explain the difference of performance in these 2 simple loops ?
C#
How to enable Password Char in TextBox except last N character ? I already tried this method But it is so hard to manipulate , I will pass original card value in every event like Keypress , TextChange and etc..Is there I way that is more simple and easy to managed ?
cardnumber.Select ( ( c , i ) = > i < cardnumber.Length - 4 ? ' X ' : c ) .ToArray ( )
Enable Password Char in TextBox except last N character / Limit Masked Char
C#
I think there is quite a confusion over the usage of `` On '' as prefix of a C # method.In MSDN article `` Handling and Raising Event '' https : //msdn.microsoft.com/en-us/library/edzehd2t ( v=vs.110 ) .aspx it says , Typically , to raise an event , you add a method that is marked as protected and virtual ( in C # ) or...
void MoveLookController : :OnPointerPressed ( _In_ CoreWindow^ sender , _In_ PointerEventArgs^ args ) { // Get the current pointer position . uint32 pointerID = args- > CurrentPoint- > PointerId ; DirectX : :XMFLOAT2 position = DirectX : :XMFLOAT2 ( args- > CurrentPoint- > Position.X , args- > CurrentPoint- > Position....
What does prefix `` On '' implement in event cases in C # coding ?
C#
I have an IHttpHandler which I believe can benefit from re-use , because it is expensive to set up , and is thread-safe . But a new handler is being created for each request . My handler is not being re-used.Following is my simple test case , without the expensive setup . This simple case demonstrates my problem : Am I...
public class MyRequestHandler : IHttpHandler { int nRequestsProcessed = 0 ; public bool IsReusable { get { return true ; } } public void ProcessRequest ( HttpContext context ) { nRequestsProcessed += 1 ; Debug.WriteLine ( `` Requests processed by this handler : `` + nRequestsProcessed ) ; context.Response.ContentType =...
IHttpHandler IsReusable , but is not getting re-used
C#
This is a very strange problem that I have spent the day trying to track down . I am not sure if this is a bug , but it would be great to get some perspective and thoughts on why this is happening.I am using xUnit ( 2.0 ) to run my unit tests . The beauty of xUnit is that it automatically runs tests in parallel for you...
public class OneClass { readonly ITestOutputHelper output ; public OneClass ( ITestOutputHelper output ) { this.output = output ; } [ Fact ] public void OutputHashCode ( ) { Support.Add ( typeof ( SampleObject ) .GetTypeInfo ( ) ) ; output.WriteLine ( `` Initialized : '' ) ; Support.Output ( output ) ; Support.Add ( ty...
Is ConstructorInfo.GetParameters Thread-Safe ?
C#
I found a method to shuffle an array on the internet.However , I am a little concerned about the correctness of this method . If OrderBy executes x = > rand.Next ( ) many times for the same item , the results may conflict and result in weird things ( possibly exceptions ) .I tried it and everything is fine , but I stil...
Random rand = new Random ( ) ; shuffledArray = myArray.OrderBy ( x = > rand.Next ( ) ) .ToArray ( ) ;
In LINQ , does orderby ( ) execute the comparing function only once or execute it whenever needed ?
C#
back in school , we wrote a compiler where curly braces had the default behavior of executing all expressions , and returning the last value ... so you could write something like : Is there something equivalent in C # ? For instance , if I want to write a lambda function that has a side effect.The point less being abou...
int foo = { printf ( `` bar '' ) ; 1 } ;
C # scoping operator
C#
I have this method : It 's not working correctly as it seems like I need the value of { 0 } needs to be a 0 or a 1 . Is there a simple way that I can take value and change it to be a 0 or a 1 ?
public void UpdatePhrase ( PHRASE phraseColumn , bool value , string phraseId ) { sql = string.Format ( `` UPDATE Phrase SET `` + phraseColumn.Text ( ) + `` = { 0 } WHERE PhraseId = ' { 1 } ' '' , value , phraseId ) ; App.DB.RunExecute ( sql ) ; }
How can I change a bool to a 0 or a 1 , can I cast it ?
C#
Let 's say I have the following method : A colleague of mine is convinced that this a bad method signature . He would like me to use a Request object , which would transform the method signature into this : I really do n't see the point of doing that . The only benefit I see is that it will be easier to add parameters ...
public Stream GetMusic ( string songTitle , string albumName ) { ... } public Stream GetMusic ( SongRequest request ) { ... }
Request object , what are the pros and cons ?
C#
For some classes , ideally , I 'd like to create special named instances , similar to `` null . '' As far as I know , that 's not possible , so instead , I create static instances of the class , with a static constructor , similar to this : As you can see , Person.Waldo is a special instance of the Person class , which...
public class Person { public static Person Waldo ; // a special well-known instance of Person public string name ; static Person ( ) // static constructor { Waldo = new Person ( `` Waldo '' ) ; } public Person ( string name ) { this.name = name ; } }
C # How to create special instances of a class ?
C#
I have the following class structure : Is it possible to pivot the List < Employee > with Linq so i have result like this in my DataGridView : It 's tricky because it 's two nested lists and i only found examples with single list which are pretty straightforward.Is it possible to Pivot data using LINQ ? I got to this p...
class Employee ( ) { public String Name { get ; set ; } public List < WorkDay > WorkDays { get ; set ; } } class WorkDay ( ) { public DateTime Date { get ; set ; } public Int Hours { get ; set ; } } | Name | Name | ... | Name |Date | Hours | Hours | | Hours |Date | Hours | Hours | | Hours | Date | Hours | Hours | | Hou...
Pivot data in two nested List < T > with Linq
C#
F # has a convenient feature `` with '' , example : F # created keyword `` with '' as the record types are by default immutable.Now , is it possible to define a similar extension in C # ? seems it 's a bit tricky , as in C # i 'm not sure how to convert a string to a delegate or expression ?
type Product = { Name : string ; Price : int } ; ; let p = { Name= '' Test '' ; Price=42 ; } ; ; let p2 = { p with Name= '' Test2 '' } ; ; Name= '' Test2 ''
C # : how to define an extension method as `` with '' in F # ?
C#
I have a basic buddylist type application which is a pub/sub deal in WCF . My problem is one or two of the calls are long running and this blocks up the entire server application ( gui updates etc ) .Here 's my code : So far I have an idea on how to go about it but is there a simpler way ? Idea 1 : Have GetABunchOfData...
[ ServiceContract ( SessionMode = SessionMode.Required , CallbackContract = typeof ( IBuddyListContract ) ) ] public interface IBuddyListPubSubContract { [ OperationContract ] string GetABunchOfDataZipped ( String sessionId ) ; // this can take > 20 seconds ... . } [ ServiceBehavior ( InstanceContextMode = InstanceCont...
C # WCF NetTCPBinding Blocking Application
C#
I need to generate all possible numbers ( integers ) from 0 to 999999 ( without repetition ) while respecting a series of constraints.To better understand the requirements , imagine each number being formed by a 2 digit prefix and a suffix of 4 digits . Like 000000 being read as 00-0000 and 999999 as 99-9999 . Now to t...
var seed = 102111 ; var rnd = new Random ( seed ) ; var prefix = Enumerable.Range ( 0 , 100 ) .OrderBy ( p = > rnd.Next ( ) ) ; var suffix = Enumerable.Range ( 0 , 10000 ) .OrderBy ( s = > rnd.Next ( ) ) ; var result = from p in prefix from s in suffix select p.ToString ( `` d2 '' ) + s.ToString ( `` d4 '' ) ; foreach ...
How to generate a sequence of numbers while respecting some constraints ?
C#
I have a WCF service where I use a custom UserNamePasswordValidator to validate user . When this is done the IAuthorizationPolicy.Evaluate is triggered and this is where I set the principal to a custom user context like this : The problem is that I need 2 things to get the proper usercontext and this is username and a ...
public override void Validate ( string userName , string password ) { LoginHelper loginHelper = new LoginHelper ( ) ; loginHelper.ValidateUserRegularLogin ( userName , password ) ; } evaluationContext.Properties [ `` Principal '' ] = userContext ; public object AfterReceiveRequest ( ref System.ServiceModel.Channels.Mes...
Login with IAuthorizationPolicy and UserNamePasswordValidator with header data ?
C#
I 've made such experiment - made 10 million random numbers from C and C # . And then counted how much times each bit from 15 bits in random integer is set . ( I chose 15 bits because C supports random integer only up to 0x7fff ) .What i 've got is this : I have two questions : Why there are 3 most probable bits ? In C...
void accumulateResults ( int random , int bitSet [ 15 ] ) { int i ; int isBitSet ; for ( i=0 ; i < 15 ; i++ ) { isBitSet = ( ( random & ( 1 < < i ) ) ! = 0 ) ; bitSet [ i ] += isBitSet ; } } int main ( ) { int i ; int bitSet [ 15 ] = { 0 } ; int times = 10000000 ; srand ( 0 ) ; for ( i=0 ; i < times ; i++ ) { accumulat...
Most probable bits in random integer
C#
What could possibly be the reasons to use - instead of , or , even simpler - for comparing two strings in .NET with C # ? I 've been assigned on a project with a large code-base that has abandon use of the first one for simple equality comparison . I could n't ( not yet ) find any reason why those senior guys used that...
bool result = String.Compare ( fieldStr , `` PIN '' , true ) .Equals ( 0 ) ; bool result = String.Equals ( fieldStr , `` PIN '' , StringComparison.CurrentCultureIgnoreCase ) ; bool result = fieldStr.Equals ( `` PIN '' , StringComparison.CurrentCultureIgnoreCase ) ;
Efficient ( ? ) string comparison
C#
I 'm using WinForms . In my forms I have an open and a next button . My application opens .tif images into a picturebox . All the .tif images I work with have multiple pages . The next button is for going to the next page in the tif image . These .tif images I work with are very large.Example : Dimensions : 2600 x 3300...
FileStream _stream ; Image _myImg ; // setting the selected tiff string _fileName ; private Image _Source = null ; private int _TotalPages = 0 ; private int intCurrPage = 0 ; private void Clone_File ( ) { // Reads file , then copys the file and loads it in the picture box as a temporary image doc . That way files are n...
Boost the performance when advancing to the next page using .tif images
C#
I have now a scenario that needs to add and remove items in multi-threading conditionI 'm doing andBut I have now a very big problem with race condition . The lock time is increasing and incrasing.I wished I could use ConcurrentBag but it does n't has Contains Method , so I ca n't remove the specific item I want to rem...
lock ( list ) { if ( ! list.Contains ( item ) ) { list.Add ( Item ) ; } } lock ( list ) { if ( list.Contains ( item ) ) { list.Remove ( Item ) ; } }
What 's the best way of adding/removing a specific item from List < T > in multi-threading scenario
C#
My project compiles in VS 2013 but does not compile in VS 2015 . Below code reproduces the compile problem . The Validator classes are actually in a 3rd party assembly so I can not change the implementation . The require class is a local class but I do n't want to change the implementation because I will have to change...
public abstract class Validator < T > : Validator { public override void DoValidate ( object objectToValidate ) { } protected abstract void DoValidate ( T objectToValidate ) ; } public abstract class Validator { public abstract void DoValidate ( object objectToValidate ) ; } public abstract class ValidatorBase < T > : ...
Visual Studio 2015 does not compile when generic type matches overloaded method that takes that type
C#
Consider : Note the third Console.WriteLine - I 'm expecting it to print the type to which the array is being cast ( Int32 [ ] ) , but instead it prints the original type ( Foo [ ] ) ! And ReferenceEquals confirms that indeed , the first Cast < int > call is effectively a no-op.So I peeked into the source of Enumerable...
enum Foo { Bar , Quux , } void Main ( ) { var enumValues = new [ ] { Foo.Bar , Foo.Quux , } ; Console.WriteLine ( enumValues.GetType ( ) ) ; // output : Foo [ ] Console.WriteLine ( enumValues.First ( ) .GetType ( ) ) ; // output : Foo var intValues = enumValues.Cast < int > ( ) ; Console.WriteLine ( intValues.GetType (...
Type system oddity : Enumerable.Cast < int > ( )
C#
I have a class called Global that derives from HttpApplication.Oddly , I see a lot of methods inside Global that look like : The code is definitely executing inside this method , so the method is being called from somewhere , but where ? The methods are n't marked overload ? Secondly , I derived a class from Global , l...
void Application_Start ( object sender , EventArgs e ) { }
Confused over global.asax ?
C#
I am trying to understand the contents of a .csproj file after I converted from PCL to a .NET shared . Here is an example and some questions : Can someone explain to me why only certain folders appear above even though my project has many more foldersCan someone explain what all these Remove lines do / mean ? Can someo...
< Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netstandard2.0 < /TargetFramework > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' Xamarin.Forms '' Version= '' 3.1.0.583944 '' / > < PackageReference Include= '' sqlite-net-pcl '' Version= '' 1.4.118 '' / > < PackageReferen...
C # project file - Why does n't it represent what 's in my project ?
C#
I have started looking at using Reactive Extensions with EventStore . As a proof of concept , I 'd like to see if I can get Rx to consume an event stream and output the count of events grouped by type for a window of one second . So , say that I am consuming a stream with the name `` orders '' , I 'd like to see someth...
OrderCreated 201OrderUpdated 111 OrderCreated 123OrderUpdated 132 internal class EventStoreRxSubscription { public Subject < ResolvedEvent > ResolvedEvents { get ; } public Subject < SubscriptionDropReason > DroppedReasons { get ; } public EventStoreSubscription Subscription { get ; } public EventStoreRxSubscription ( ...
Rx : Count of Grouped Events in Moving Window
C#
I have a table payments that has a null-able integer column named payMonth . I have the following class and list : The problem comes here . When data is displayed in the dgv , the DataGridViewComboBoxColumn cmbMonth shows the number values ( 1,2,3 , ... ) not the month name ( 'Jan ' , 'Feb ' , 'Mar ' , ... ) . And when...
public class months { public int payMonth { get ; set ; } public string monthName { get ; set ; } } lstMonths = new List < months > { , new months ( ) { payMonth = 1 , monthName = `` jan '' } , new months ( ) { payMonth = 2 , monthName = `` feb '' } , new months ( ) { payMonth = 3 , monthName = `` mar '' } , new months...
C # binding datagridviewcomboboxcolumn to list display , formatting , preferred Size error
C#
Consider the following example : How could parallel read access to the Contents List be achieved without copying the whole List ? In C # there are concurrent Collections , but there is no thread safe List . In Java there is something like the CopyOnWriteArrayList .
class Example { private readonly List < string > _list = new List < string > ( ) ; private readonly object _lock = new object ( ) ; public IReadOnlyList < string > Contents { get { lock ( _lock ) { return new List < string > ( _list ) ; } } } public void ModifyOperation ( string example ) { lock ( _lock ) { // ... _lis...
C # parallel read access to List without copying
C#
I have ( legacy ) VB6 code that I want to consume from C # code . This is somewhat similar to this question , but it refers to passing an array from VB6 consuming a C # dll . My problem is the opposite.In VB , there is an interface in one dll , and an implementation in another.Interface : Implementation ( fragment ) in...
[ odl , uuid ( 339D3BCB-A11F-4fba-B492-FEBDBC540D6F ) , version ( 1.0 ) , dual , nonextensible , oleautomation , helpstring ( `` Extended Post Interface . '' ) ] interface IMyInterface : IDispatch { [ id ( ... ) , helpstring ( `` String array of errors . '' ) ] HRESULT GetErrors ( [ out , retval ] SAFEARRAY ( BSTR ) * ...
Consuming VB6 string array in C #
C#
I 'm developing a WPF application whose Window size and component locations must be dynamically calculated upon initialization because they are based on the main UserControl size I use and some other minor size settings . So , for the moment , I 've placed those constant values in my Window code as follows : Then , I j...
public const Double MarginInner = 6D ; public const Double MarginOuter = 10D ; public const Double StrokeThickness = 3D ; public static readonly Double TableHeight = ( StrokeThickness * 2D ) + ( MarginInner * 3D ) + ( MyUC.RealHeight * 2.5D ) ; public static readonly Double TableLeft = ( MarginOuter * 3D ) + MyUC.RealH...
Elegant Solution for Readonly Values
C#
I 'm reviewing a piece of code I wrote not too long ago , and I just hate the way I handled the sorting - I 'm wondering if anyone might be able to show me a better way.I have a class , Holding , which contains some information . I have another class , HoldingsList , which contains a List < Holding > member . I also ha...
public class Holding { public ProductInfo Product { get ; set ; } // ... various properties & methods ... } public class ProductInfo { // .. various properties , methods ... } public class HoldingsList { public List < Holding > Holdings { get ; set ; } // ... more code ... } public enum PortfolioSheetMapping { Unmapped...
Looking for a better way to sort my List < T >
C#
I have a simple method which converts an array from one type to another . I wanted to find out which method is the fastest . But so far I get differing results from which I can not conclude which method is really faster by which margin . Since the conversion is only about allocating memory , reading the array and conve...
using System ; using System.Collections.Generic ; using System.Diagnostics ; namespace PerfTest { class Program { const int RUNS = 10 * 1000 * 1000 ; static void Main ( string [ ] args ) { int [ ] array = new int [ ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , ...
Why are performance measurements differing ?
C#
Followed Functional Reactive Programming tutorial , where stream of events ( Observable ) is directly created from System.Timers.Timer.Elapsed event.Have class defined in C # Referenced corresponding .dll into F # project and trying to create Observable from Notifier.OnMessage event Getting error message The event OnMe...
let timer = new System.Timers.Timer ( float 1 ) let observable = timer.Elapsed observable | > Observable.subscribe ... public delegate void OnMessageDelegate ( Message message ) ; public class Notifier : INotifier { public event OnMessageDelegate OnMessage ; public void Notify ( Message message ) = > OnMessage ? .Invok...
Consume C # event from F #
C#
I do understand that there 's no multiple inheritence in C # . However , I 've run into a situation in which I really wish it existed . I am creating a custom class that requires me to inherit from CLR types and override a few methods . Unfortunately , I am creating several of these which are very similar . In the inte...
public class CustomTypeOne : CLRType { public override void Execute ( HttpContext context ) { //Some code that 's similar across CustomTypeOne , CustomTypeTwo etc } public void DoStuff ( ) { //Same for all CustomTypes and can be part of a base class } //More methods } public class CustomTypeTwo : CLRType { public overr...
Multiple Inheritance in C # : What is the purist way of achieving what I am trying to do ?
C#
I have Tiles which represent the tiles in a game 's 2-dimensional world . The tiles can have walls on any number of their 4 sides . I have something like this at the moment : Somewhere else I also have 16 images , one for each possible tile wall configuration . Something like this : I want to write a What I 'd like to ...
interface Tile { boolean isWallAtTop ( ) ; boolean isWallAtRight ( ) ; boolean isWallAtLeft ( ) ; boolean isWallAtBottom ( ) ; } static final Image WALLS_ALL_AROUND = ... static final Image WALL_ON_TOP_AND_RIGHT = ... /* etc etc all 16 possibilities */ static Image getWallImage ( Tile tile ) if ( tile.isWallTop & & til...
Nice way to do this in modern OO C-like language ?
C#
When I decided to make my own implementation of Java ByteBuffer in C # I thought it would be faster than MemoryStream + BinaryWriter/BinaryReader . I looked at their source through ILSpy and there was a lot of checks and helper methods calls , while in my implementation I work directly with an underlying array of bytes...
public void WriteBytes ( Byte [ ] buffer , Int32 offset , Int32 count ) { this.EnsureFreeSpace ( count ) ; Buffer.BlockCopy ( buffer , offset , this.buffer , this.position , count ) ; this.position += count ; if ( this.length < this.position ) { this.length = this.position ; } } public void ReadBytes ( Byte [ ] buffer ...
Why does c # built-in IO classes is faster than self-made ones ?
C#
A bit of a basic question , but one that seems to stump me , nonetheless.Given a `` nested generic '' : Is this stating that IEnumerable can have generic types that are themselves KeyValuePair 's ? Thanks , Scott
IEnumerable < KeyValuePair < TKey , TValue > >
What do nested generics in C # mean ?
C#
I have written an F # module that has a list inside : Now from a C # class I 'm trying to access the previously defined list , but I do n't know how converting it : I 'd need something like : How can I achieve that ?
module MyModuletype X = { valuex : float32 } let l = [ for i in 1 .. 10 - > { valuex = 3.3f } ] ... list = MyModule.l ; //here 's my problem IList < X > list = MyModule.l ;
Accessing an F # list from inside C # code
C#
I 'm trying to make my first system application for Android related to geolocation and local notifications.I imagine it like this ... There is basic activity MainActivity . After start it launches a service TestService which in case of change of coordinates sends them on the server , and in reply receives some message ...
[ Activity ( Label = `` LocationTest '' , MainLauncher = true , Icon = `` @ drawable/icon '' ) ] public class MainActivity : Activity { protected override void OnCreate ( Bundle bundle ) { base.OnCreate ( bundle ) ; SetContentView ( Resource.Layout.Main ) ; var button = FindViewById < Button > ( Resource.Id.myButton ) ...
Geolocation , service and local notifications
C#
I have a list of Foo : And I want to convert it to a list Bar : The data in Foo looks like this : And I want it to look like this : I 'm doing this so it will be easier to display in a Razor rendered Html unordered list . Also , if there is an easy way to do this without conversion , please let me know.Ultimately , I w...
class Foo { public int Id { get ; set ; } public String Name { get ; set ; } } class Bar { public int Id { get ; set } public List < String > NameList { get ; set ; } } Id Name -- -- -- -- -- -1 Foo11 Foo21 Foo32 Foo32 Foo22 Foo1 Id NameList -- -- -- -- -- -- -- -- 1 Foo1 Foo2 Foo32 Foo3 Foo2 Foo1 < li > 1 < ul > < li ...
Convert List < T > into another List < T > that contains another List < T >
C#
In probably the best error message I 've gotten in awhile , I 'm curious as to what went wrong.The original code I 'm using Unity3d and C # ; LeftArm is a bool type and according to documentation Elbow.transform.localRotation.eulerAngles.y returns a float value.This code gives me the error : There exists both implicit ...
float currElbowAngle = LeftArm ? Elbow.transform.localRotation.eulerAngles.y : 360f - Elbow.transform.localRotation.eulerAngles.y float currElbowAngle = LeftArm ? ( float ) Elbow.transform.localRotation.eulerAngles.y : 360f - Elbow.transform.localRotation.eulerAngles.y
There exists both implicit conversions from 'float ' and 'float ' and from 'float ' to 'float '
C#
I have the following code : Now somewhere else in my code , I make about 2500 calls in a loop to Character.LevelPosition.This means that per update-cycle , 5000 'new ' Vector2s are being made , and on my laptop , it really drops the framerate.I have temporarily fixed it by creatingbefore I initiate the loop , but I kin...
public class Character { public Vector2 WorldPixelPosition { get { return Movement.Position ; } } public Vector2 WorldPosition { get { return new Vector2 ( Movement.Position.X / Tile.Width , Movement.Position.Y / Tile.Height ) ; } } public Vector2 LevelPosition { get { return new Vector2 ( WorldPosition.X % Level.Width...
'new ' keyword in getter > performance hit ?
C#
I am trying to remove duplicates item from bottom of generic list . I have class defined as belowAnd I have defined another class which implements IEqualityComparer to remove the duplicates from ListHowever , I am trying to remove the old items and keep the latest . For example if I have list of identifier defined as b...
public class Identifier { public string Name { get ; set ; } } public class DistinctIdentifierComparer : IEqualityComparer < Identifier > { public bool Equals ( Identifier x , Identifier y ) { return x.Name == y.Name ; } public int GetHashCode ( Identifier obj ) { return obj.Name.GetHashCode ( ) ; } } Identifier idn1 =...
Removing Duplicates from bottom of Generic List
C#
I 'm reading this introduction to Polyphonic C # and the first page contains this example : Example : A Simple BufferHere is the simplest interesting example of a Polyphonic C # class : I do n't get it at all.What does the & between methods get ( ) and put ( ) signify ?
public class Buffer { public String get ( ) & public async put ( String s ) { return s ; } }
Polyphonic C # methods separated by ampersand ?
C#
I have a two generic abstract types : Entity and Association.Let 's say Entity looks like this : and Association looks like this : How do I constrain Association so they can be of any Entity ? I can accomplish it by the following : This gets very tedious as more types derive from Association , because I have to keep pa...
public class Entity < TId > { // ... } public class Association < TEntity , TEntity2 > { // ... } public class Association < TEntity , TId , TEntity2 , TId2 > where TEntity : Entity < TId > where TEntity2 : Entity < TId2 > { // ... }
How to declare a generic constraint that is a generic type
C#
i want to render nice radial tree layout and a bit stumbled with curved edges . The problem is that with different angles between source and target points the edges are drawn differently . Provided pics are from the single graph so you can see how they 're differ for different edge directions . I think the point is in ...
//draw using DrawingContext of the DrawingVisual//gen 2 control pointsdouble dx = target.X - source.X , dy = target.Y - source.Y ; var pts = new [ ] { new Point ( source.X + 2*dx/3 , source.Y ) , new Point ( target.X - dx/8 , target.Y - dy/8 ) } ; //get geometryvar geometry = new StreamGeometry { FillRule = FillRule.Ev...
Radial tree graph layout : fix beizer curves
C#
I have a client that sends an xml feed which I parse using the following code . This code works.After getting all my `` reviews '' I cast the IEnumerable as a List and return it out . Originally , I was having a good and easy time parsing their XML which used to look like this : They have , however , changed their sche...
reviews = from item in xmlDoc.Descendants ( `` node '' ) select new ForewordReview ( ) { PubDate = ( string ) item.Element ( `` created '' ) , Isbn = ( string ) item.Element ( `` isbn '' ) , Summary = ( string ) item.Element ( `` review '' ) } ; < reviews > < node > < created > 01-01-1900 < /created > < ISBN > 12345657...
How to ignore a specific with a LINQ where clause ?
C#
Consider the following snippets : compared toCode including Foo ( ) successfully compiles in .Net 4.6.1 , while code including Bar ( ) results in Use of unassigned local variable 'comboBox ' . Without getting into a debate over the reasons behind using == false instead of the negation operator , can someone explain why...
void Foo ( object sender , EventArgs e ) { if ( ! ( sender is ComboBox comboBox ) ) return ; comboBox.DropDownWidth = 100 ; } void Bar ( object sender , EventArgs e ) { if ( ( sender is ComboBox comboBox ) == false ) return ; comboBox.DropDownWidth = 100 ; }
Inline variable declaration does n't compile when using '== false ' instead of negation operator
C#
I 've seen some examples where they transformed a call likeintoBeside tricking the intellisense into displaying the name of your class instead of the interface name when calling the function , because of inferred type usage in C # 4 , are there any other advantage to using the second approach ? To answer Jon Skeet , th...
void Add ( IDrawing item ) ; void Add < TDrawing > ( TDrawing item ) where TDrawing : IDrawing ; public ObservableCollection < IDrawing > Items { get ; private set ; } public void Add < TDrawing > ( TDrawing item ) where TDrawing : IDrawing { this.Items.Add ( item ) ; }
What are the advantage of using a generics-where-clause call over a non-generic call ?
C#
What I have learned so far is that we can not create an instance of an interface . IFood food = new IFood ( ) ; //this gives compile errorIFood food = new Apple ( ) ; //this will workUpto here everything were okay . But when I work with Microsoft.Office.Interop.Excel I have seen something like belowApplication excel = ...
interface IFood { string Color { get ; set ; } } class Apple : IFood { public string Color { get ; set ; } }
How is it possible to initialize an interface ?
C#
Is it possible to dynamically compose a class from the methods contained in other Classes ? For instance . Class A , B and C have public methods named such that they can be identified easily . They need to be extracted and added to Class D. Class D , which then contains all of the implementation logic can be passed fur...
public class A { public void EXPORT_A_DoSomething ( ) { } } public class B { public void EXPORT_B_DoSomethingElse ( ) { } } public class C { public void EXPORT_C_DoAnything ( ) { } } //should becomepublic class D { public void EXPORT_A_DoSomething ( ) { } public void EXPORT_B_DoSomethingElse ( ) { } public void EXPORT_...
Dynamically Compose a Class in C #
C#
I have this code , and i want to store values of parameters left , top in static dictionary . and after storing this values i want to access them in Jquery.Thanks For your Help.my code
using Microsoft.AspNet.SignalR ; using Microsoft.AspNet.SignalR.Hubs ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; namespace WebApplication1.MoveShape { public class MoveShapeHub : Hub { public void calculate ( string left , string top ) { Clients.Others.updateshape ( left ,...
C # Store values in static dictionary
C#
Let 's say we have a collection of documents like this one : How do you extract only the documents where no item in the array $ .carts have $ .carts.closed set to true and $ .carts.updatedon greater than $ .updatedon minus 3 days ? I know how to do find all the documents where no item in the array satisfy the condition...
{ `` _id '' : ObjectId ( `` 591c54faf1c1f419a830b9cf '' ) , `` fingerprint '' : `` 3121733676 '' , `` screewidth '' : `` 1920 '' , `` carts '' : [ { `` cartid '' : 391796 , `` status '' : `` New '' , `` cart_created '' : ISODate ( `` 2017-05-17T13:50:37.388Z '' ) , `` closed '' : false , `` items '' : [ { `` brandid ''...
Find if an element in array has value equal to parent element value
C#
I was just implementing the Dispose pattern , and when I just typed the GC.SuppressFinalize ( this ) line , I was wondering if there is ever a use case for using something other than this as the parameter to the method.This is the typical pattern : Does it ever make sense to call GC.SuppressFinalize ( ) with something ...
public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; // right here } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( foo ) ; // should this ever happen ? }
Is there a use case for not using `` this '' when calling GC.SuppressFinalize ( this ) ?
C#
Using Linq on collections , which one is best for finding that collection is not empty ? and
HasChild = Childs.GetEnumerator ( ) .MoveNext ( ) ? true : false ; HasChild = Childs.Any ( ) ? true : false ;
Linq Any ( ) vs MoveNext ( )
C#
I have previously asked a similar question on SO to which I got an answer . At the time , for the sake of expediency , I mechanically applied the answer but now I 'm trying to get a handle on how the mechanism for declaratively setting up a fixture is.So , I am currently looking at Mark Seemann 's Dealing With Types Wi...
[ Fact ] public static void CanOverrideCtorArgs ( ) { var fixture = new Fixture ( ) ; var knownText = `` This text is not anonymous '' ; fixture.Register < int , IMyInterface > ( i = > new FakeMyInterface ( i , knownText ) ) ; var sut = fixture.Create < MyClass > ( ) ; }
What are the principles behind AutoFixture 's declarative way of setting up a fixture ?
C#
Suppose the following code : Functionally , these functions are exactly the same but the compiler treats calling these methods different . The following code compiles , but issues a CS4014 warning : It generates the warning `` because this call is not awaited , the current method continues to run before the call is com...
private async Task Test1Async ( ) = > await Task.Delay ( 1000 ) .ConfigureAwait ( false ) ; private Task Test2Async ( ) = > Test1Async ( ) ; private void Test ( ) = > Test1Async ( ) ; // CS4014 is shown private void Test ( ) = > _ = Test1Async ( ) ; // CS4014 is not shown anymore private void Test ( ) = > Test2Async ( ...
Why is CS4014 not shown for all functions that return a task ?
C#
I have 3 functions where the only difference in is the values I point out with commentThe majority of the function is the same across all three . The `` DRY '' factor is haunting my sleep : ) . I was wondering ; can these could be merged easily and readably ? I have had situations like this before and I am hoping to le...
// -- point of difference private string RenderRequestType ( string render , NameValueCollection nvp , string prefix , string regexWild , string suffix ) { string regex = prefix + regexWild + suffix ; MatchCollection matches = Regex.Matches ( render , regex ) ; foreach ( Match match in matches ) { foreach ( Capture cap...
How to refactor these functions which have one line difference
C#
When i run following code in .Net Core 3.1 i get 6Resultbut when i run this code in .Net 5 i get different result . why ? Result
//Net Core 3.1string s = `` Hello\r\nworld ! `` ; int idx = s.IndexOf ( `` \n '' ) ; Console.WriteLine ( idx ) ; 6 //NET 5string s = `` Hello\r\nworld ! `` ; int idx = s.IndexOf ( `` \n '' ) ; Console.WriteLine ( idx ) ; -1
string.IndexOf get different result in .Net 5
C#
ASP.Net Identity is executing the queries below on every request . I have not changed any of the Identity code that was gen 'd when my MVC project was created . My Startup.Auth.cs code is below.Note that validateInterval is set to TimeSpan.FromMinutes ( 30 ) . Also note that cookie expiration is being explicitly set ( ...
public partial class Startup { public void ConfigureAuth ( IAppBuilder app ) { // Configure the db context , user manager and signin manager to use a single instance per request app.CreatePerOwinContext ( ApplicationDbContext.Create ) ; app.CreatePerOwinContext < ApplicationUserManager > ( ApplicationUserManager.Create...
ASP.Net Identity running multiple queries on every request
C#
I have this C # DLL : And this F # app which references the DLL : No-one initiates the Instance static variable . Guess what the output of the F # app is ? After a few tests I found out that unless I use this ( e.g . to access instance field ) , I wo n't get NullReferenceExpcetion . Is that an intended behaviour or a g...
namespace TestCSProject { public class TestClass { public static TestClass Instance = null ; public int Add ( int a , int b ) { if ( this == null ) Console.WriteLine ( `` this is null '' ) ; return a + b ; } } } open TestCSProjectprintfn `` % d '' ( TestClass.Instance.Add ( 10,20 ) ) this is null30Press any key to cont...
F # / .NET null instance oddity
C#
I know that there are some atmoic types defined in C # , from where I ca n't find array.Opration 1 is something like a pointer reassignment . Does itguarantee to be atmoic ? How about operation 2 ?
var a = new bool [ ] { true , false } ; var b = new bool [ 4 ] ; a=b ; //operation 1a [ 1 ] =true ; //operation 2
Is array write atomic in C # ?
C#
I have hierarchy of classes like follows ( in fact I have more than 3 derived types ) : Instances of these classes are stored in List < A > collections . Sometimes collections are quite big ( thousands or even tens of thousands of objects ) .In my code I frequently need to perform some actions depending on the exact ty...
class A { } ; class B : A { } ; class C : B { } ; class D : A { } ; List < A > collection = ... foreach ( A obj in collection ) { if ( obj is C ) something ( obj as C ) ; else if ( obj is B ) somethingElse ( obj as B ) ; ... . }
Efficient run-time type checking
C#
I have a raspberry pi with system language set to `` de_DE.UTF-8 '' and mono version 3.28 installed . My programs need to convert Strings into Doubles , but I ran into a few problems : Works just fine.Throws FormatException , what is weird.Throws FormatException too ; The funny thing is if I change my system language (...
Double.Parse ( `` 500 '' , NumberStyles.Float , CultureInfo.InvariantCulture ) ; Double.Parse ( `` 500.123 '' , NumberStyles.Float , CultureInfo.InvariantCulture ) ; Double.Parse ( `` 500,123 '' , NumberStyles.Float , CultureInfo.GetCultureInfo ( `` de-DE '' ) ) ;
Double.Parse fails in german locale
C#
I have a database with two tables . Both of these tables are related and have the same key field . For example , both of them have rows of data corresponding to ISBN = 12345 , but the two tables have differing data about that ISBN . So , I 'm trying to figure out how to display data from both tables into one dataGridVi...
private void Form1_Load ( object sender , EventArgs e ) { // TODO : This line of code loads data into the 'database1DataSet.Book ' table . You can move , or remove it , as needed . this.bookTableAdapter.Fill ( this.database1DataSet.Book ) ; string connectionString = `` Provider=Microsoft.ACE.OLEDB.12.0 ; Data Source= '...
Need some help working with databases in C #
C#
I was looking at the mvc-mini-profiler designed by the Stack Overflow team on Google Code and one thing on the getting started page struck me as particularly strange : How can it be `` ok '' if profiler is null ? It seems to me that calling Step would throw a NullReferenceException . In all my years of programming C # ...
var profiler = MiniProfiler.Current ; // it 's ok if this is nullusing ( profiler.Step ( `` Set page title '' ) ) { ViewBag.Title = `` Home Page '' ; } using ( null ) { ... }
Calling methods on a null reference in the context of a using clause is OK ?
C#
I think my problem is best explained with a code snippet of my class/interface-hierarchy : Question 1 : Why does s1.Transform ( v ) resolve to ITransform < ISelection > and not to ITransform < IValue > as in the second case ? Question 2 : For Question 1 it seems to make no difference if ITransform is < D > or < in D > ...
public interface ITransform < D > // or < in D > -- > seems to make no difference here { void Transform ( D data ) ; } interface ISelection { } interface IValue : ISelection { } public interface IEditor : ITransform < IValue > { } public interface ISelector : IEditor , ITransform < ISelection > { } class Value : IValue...
Method overload resolution and generic/contravariant interfaces in C #
C#
I 'm building an application using ASP.net MVC 3 and I 'm wondering if anyone knows a great library to fill the gaps of the build-in html form field helpers ? E.g . creating a Textbox is easy : But for creating a Dropdown list I have to write : And it should be written like where DropdownTest is a SelectList.There is a...
@ Html.EditorFor ( model = > model.TextboxTest ) @ Html.DropDownListFor ( model = > model.DropdownTest , Model.DropdownTestData ) @ Html.EditorFor ( model = > model.DropdownTest ) @ Html.RadioButtonListFor ( model= > model.Item , Model.ItemList )
Has anyone a great library for the missing MVC 3 html form field helpers ?
C#
I am trying to write an extension method in order to refactor a linq many-to-many query I 'm writing . I am trying to retrieve a collection of Post ( s ) which have been tagged with any of the Tag ( s ) in a collection passed as a parameter to my method.Here are the relevant entities along with some of their properties...
public IEnumerable < Post > GetPostsByTags ( IEnumerable < Tag > tags ) { return from pt in context.PostTags from t in tags where pt.TagID == t.TagID & & pt.Post.PostDate ! = null orderby pt.Post.PostDate descending select pt.Post ; } public static IEnumerable < TResult > SelectRange < TSource , TResult > ( this IEnume...
Writing an extension method to help with querying many-to-many relationships
C#
If in F # I have methods like : Would they be transferred to C # , exactly the same ? If that 's the case , then would n't it compromise the naming conventions in C # , where methods are supposed to be PascalCase ? Or should I make them PascalCase in F # as well to remedy this ?
drawBoxdrawSpherepaintImage
How do F # types transfer over to C # ?
C#
The program below produces this output : So , Foo ( baz ) calls the generic Foo < T > , but Bar ( baz ) recurses and does not call Bar < T > .I 'm on C # 5.0 and Microsoft .NET . The compiler seems to choose the generic method , instead of recursion , when the non-generic method is an override.Where can I find an expla...
Foo < T > calledProcess is terminated due to StackOverflowException . using System ; namespace ConsoleApplication1 { class Baz { } abstract class Parent { public abstract void Foo ( Baz baz ) ; } class Child : Parent { void Bar < T > ( T baz ) { Console.WriteLine ( `` Bar < T > called '' ) ; } public void Bar ( Baz baz...
Why is a generic method chosen when a non-generic exists ?
C#
In regards to the following code : Is the SqlConnection initialized with `` using '' so it is dereferenced/destructed after the brackets ? Please correct my questioning where necessary .
using ( SqlConnection sqlConnection = new SqlConnection ( connectionString ) ) { code ... }
C # : Initializing a variable with `` using ''
C#
I have a server side developed in c # with entity framework as a provider for SQL server . My server is managing a many to many relation between students and classes.My client side is developed in angular js with Typscript.To be synchronized with the server , each change in server is pushed to the clients with push not...
public class Student { public List < Course > Courses . . } public class Course { public List < Student > Students . . } Students : { [ studentId : number ] : Courses } = { }
Performance issue using in memory database with Typescript/javascript
C#
I have faced a strange problem . Here I reproduced the problem.Until now , I thought that Linq functions get executed when they are called . But , in this method it seems after I call ToList the Linq function OrderBy executes again . Why is that so ?
Random r = new Random ( ) ; List < int > x = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var e = x.OrderBy ( i = > r.Next ( ) ) ; var list1 = e.ToList ( ) ; var list2 = e.ToList ( ) ; bool b = list1.SequenceEqual ( list2 ) ; Console.WriteLine ( b ) ; // prints false
IEnumerable repeats function
C#
I 'm trying to understand some workings of Abap-OO . In C # it is possible to restrict a type to be any type but conform at least to certain ( multiple ) interfaces through constraints in generics by doing : Is it possible to archive the same in abap-oo ? I want to pass in any object as a parameter to a method that con...
where T : IAmInterfaceA , IAmInterfaceB Manager.Save ( /* < object that conforms to both interfaces IValidate and ISaveable > */ ) ; static bool Save < T > ( T dataObject ) where T : IValidate , ISaveable { /* ... */ }
Constraints on parameter to implement two interfaces
C#
This has `` always '' bothered me ... Let 's say I have an interface IFiddle and another interface that does nothing more than aggregate several distinct IFiddles : ( The concrete IFiddleFrobblers and IFiddles depend on configurations and are created by a factory . ) I repeatedly stumble on the naming of such `` umbrel...
public interface IFiddleFrobbler { IFiddle Superior { get ; } IFiddle Better { get ; } IFiddle Ordinary { get ; } IFiddle Worse { get ; } IFiddle Crackpot { get ; } } //// Used for places where the font width might need// to be tapered for a rendered text to fit.//public interface ITaperableFont { Font Font { get ; } B...
How should I name an `` umbrella '' type sanely ?
C#
Ever since I found out about auto properties , I try to use them everywhere . Before there would always be a private member for every property I had that I would use inside the class . Now this is replaced by the auto property . I use the property inside my class in ways I normally would use a normal member field . The...
class Foo { private Bar bar ; public Bar Bar { get { return bar ; } } public Foo ( Bar bar ) { this.bar = bar ; } public void DoStuff ( ) { if ( bar ! = null ) { bar.DoMethod ( ) ; } } } class Foo { public Bar Bar { get ; private set ; } public Foo ( Bar bar ) { this.Bar = bar ; // or Bar = bar ; } public void DoStuff ...
Is always prefixing ( auto ) properties with the this-keyword considered a good practice ?
C#
Hello I am trying to make a C # program that downloads files but I am having trouble with the array.I have it split up the text for downloading and put it into a 2 level jagged array ( string [ ] [ ] ) .Now I split up the rows up text by the | char so each line will be formatted like so : { filename } | { filedescripti...
public Form2 ( string [ ] [ ] textList , string path ) { InitializeComponent ( ) ; textBox1.Text = textBox1.Text + path + Environment.NewLine ; WebClient downloader = new WebClient ( ) ; foreach ( string [ ] i in textList ) { for ( int j=0 ; j < i.Length ; j++ ) { textBox1.Text = textBox1.Text + i [ j ] + Environment.N...
Can only display array by iterating through a for loop
C#
To get the current activity in Unity without Firebase Cloud Messaging , the following code works : However , Firebase Cloud Messaging extends the default Unity Activity . So I changed my AndroidJavaClass as such : However , I now get the following error in my logcat : I do not understand why . It says that currentActiv...
var unityPlayer = new AndroidJavaClass ( `` com.unity3d.player.UnityPlayer '' ) ; var activity = unityPlayer.GetStatic < AndroidJavaObject > ( `` currentActivity '' ) ; var unityPlayer = new AndroidJavaClass ( `` com.google.firebase.MessagingUnityPlayerActivity '' ) ; var activity = unityPlayer.GetStatic < AndroidJavaO...
How can I get the current activity while using Firebase Cloud Messaging in Unity ?
C#
I 'm designing a fluent API and the usage is somewhat like this : So , let 's say that work is of type IUnitOfWork , but the method WithRepository ( c = > c.Users ) returns an interface called IActionFlow < IUserRepository > which is IDisposable.When I call Execute ( ) and get the final result , I lose the reference to...
IUser user = work .Timeout ( TimeSpan.FromSeconds ( 5 ) ) .WithRepository ( c = > c.Users ) .Do ( r = > r.LoadByUsername ( `` matt '' ) ) .Execute ( ) ; public TResult Execute ( ) { // ... Dispose ( ) ; return result ; }
Disposing object from same object
C#
What i 'm trying to do is get Type of enum which is nested in Class having only name of that enumerator as string.example : i need get Is there any way to get this Type in runtime ? Thanks in advance : )
public static class MyClassWithEnumNested { public enum NestedEnum { SomeEnum1 , SomeEnum2 , SomeEnum3 } } Type type = //what shall I write here ? Type type = Type.GetType ( `` MyClassWithEnumNested.NestedEnum '' ) ; //that does n't work
Getting type of nested enum having only string ?
C#
I was looking at a code sample in C # . There is ; without any statement before it . I thought it is typo . I tried to compile with ; . It compiled fine . What is the use of ; without any code statement ? I 'm using VS 2010 , C # and .Net 4.0
private void CheckSmcOverride ( PatLiverSmc smc ) { ; if ( smc.SmcOverride & & smc.Smc ! = null & & smc.Smc.Value < LiverSmcConst.SMC_OVERRIDE_POINT ) { smc.Smc = 10 ; _logger.DebugFormat ( `` CheckSmcOverride : Override SMC { 0 } '' , smc.Smc ) ; } }
a ; without statement in C #
C#
I open two files into 2 seperate DGVs.. Once opened and the button `` Format '' is clicked , it matches all of the lines in the two seperate DGVs and copies it into a new DGV.The first DGV looks like this ( column labels ) : and the second DGV looks like this : The two files will match the PkgStyle and concat the rest ...
Name P/N X Y Rotation PkgStyle PkgStyle P/D Feeder Vision Speed Machine Width Time Name P/N X Y Rotation PkgStyle PkgStyle P/D Feeder Vision Speed Machine Width Time Name P/N X Y Rotation PkgStyle PkgStyle P/D Feeder Vision Speed Machine Width TimeJ11 1234 12 7 180 9876 9876 THETHING 1 1 1 UNI 12MM 1MSR90 2222 19 9 0 1...
Saving DataGridView
C#
I have this struct : And I 've set breakpoints as indicated by the comments above.Then I do this : I 'm observing some strange behavior when it enters if ( first == ( MyValue ) null ) : the second breakpoint is hit for some reason . Why is it trying to convert the MyValue into a string for a simple equality comparison ...
public struct MyValue { public string FirstPart { get ; private set ; } public string SecondPart { get ; private set ; } public static implicit operator MyValue ( string fromInput ) { // first breakpoint here . var parts = fromInput.Split ( new [ ] { ' @ ' } ) ; return new MyValue ( parts [ 0 ] , parts [ 1 ] ) ; } publ...
Strange conversion operator behavior
C#
So given a static type in your code you can doHow would you do the same thing given a variable of Type so you can use it during runtime ? In other words how do I implement the following method without a bunch of if statements or using Generics ( because I will not know the type I 'm passing into the method at compile t...
var defaultMyTypeVal = default ( MyType ) ; public object GetDefaultValueForType ( Type type ) { ... . }
C # : How to find the default value for a run-time Type ?
C#
I 've created a database according to which the user profile is formed by the following two classes : I want to connect them by having both as primary key the UsrID and I get an error that UsrDetails do n't have a primary key because I 'm using the foreign key attribute . Any ideas ?
public class Usr { [ Key ( ) ] public int UsrID { get ; set ; } public virtual UsrType UsrType { get ; set ; } public virtual UsrStatus UsrStatus { get ; set ; } [ Required ] [ MaxLength ( 100 , ErrorMessage = `` Email can only contain { 0 } characters '' ) ] public string UsrEmail { get ; set ; } [ Required ] [ MaxLen...
Error with primary key in one-to-one relationship using Entity Framework
C#
I would like to know if an IQueryable object 's Expression contains a certain `` Where clause '' . For example , given as IQueryable instance , which could be something like : How can I determine if the query is filtering the customers by Name ?
var query = customers.Where ( c = > c.Name == `` Test '' ) ;
Analyzing a Linq expression
C#
I want to ( am trying to ) make my code more readable . I have been using the following class aliasing.But I think something like ( note : I 'm attempting to describe FeatureHistogram in terms of Histogram here , rather than EmpiricScore < int > > ) : Seems more readable ( the dependencies can go much deeper , what if ...
using Histogram = EmpiricScore < int > ; using FeatureHistogram = Dictionary < string , EmpiricScore < int > > ; using Histogram = EmpiricScore < int > ; using FeatureHistogram = Dictionary < string , Histogram > ;
Aliasing multiple classes in C #
C#
The Set Up : Loading a DataReader into a DataTable . Attempting to alter a column in the DataTable after load.The Problem : ReadOnlyException triggered when attempting to alter a column.The Conditions : When a function ( udf or system ) is applied to an aliased column inthe stored procedure , the column becomes ReadOnl...
var dt = new DataTable ( ) ; using ( var sqlDR = objDocsFBO.GetActiveDocsMerged ( KeyID ) ) { dt.Load ( sqlDR ) ; } foreach ( DataRow dr in dt.Rows ) { //Testing Alias Alone - Pass dr [ `` DocumentPathAlias '' ] = `` file : /// '' + Server.UrlEncode ( dr [ `` DocumentPathAlias '' ] .ToString ( ) ) .Replace ( `` + '' , ...
TSQL Functions used in stored procedure force column to readonly