text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : 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 led me to removing the new [ ] { personParam } from the Expression.Block call . It all makes complete sense that a Block scopes variables and you need to define them first ( like some languages force you to ) - my problem was that I did n't need any variables but was led astray by the magic DebugView property that the debugger shows you into thinking that they were parameters , and the Block was like a function definition : ... which of course it is n't . It 's a block of code as the name suggests duh ! <code> 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 Bloggs '' ) ) ) ; /* * block.DebugView in debugger shows : * * .Block ( MyProject.MyNamepace.Person $ person ) { * $ person.Name = `` Joe Bloggs '' * } * */ var method = Expression.Lambda < Action < Person > > ( block , personParam ) .Compile ( ) ; var person = new Person ( ) ; method ( person ) ; // **throws** System.NullReferenceException : ... at lambda_method ( Closure , Person ) Debug.WriteLine ( person.Name ) ; // I expect this to print `` Joe Bloggs '' } .Block ( MyProject.MyNamepace.Person $ person ) { $ person.Name = `` Joe Bloggs '' } | Dynamic Methods with Expression Trees : Simple property assignment fails |
C_sharp : 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 ) all over the site , and most of this has a `` no expire '' cache policy , so i manually evict it when required ( like the above ) .And the user part is basically giving user rep for doing something ( like Stack ) .So let 's recap : we have caching , user reputation handling , auditing , all in one . Does n't really belong in one spot does it . Hence the problem with the current code , and the problem with trying to figure out how to move it away.The reason i want to refactor this is for a few reasons : Difficult to unit test . Multithreading and unit testing does n't really play nice.Readability . It 's hard to read . Messy.SRP . Controller doing/knowing too much.I solved 1 ) by wrapping the thread spawning code into an interface , and just mocking/faking that out.But i would like to do some kind of pattern , where my code could look like this : Basically , putting the onus on `` something else '' to react , not the controller.I 've heard/read about Tasks , Commands , Events , etc but have yet to see one implemented in the ASP.NET MVC space.First thoughts would tell me to create some kind of `` event manager '' . But then i thought , where does this go ? In the domain ? Well then how does it handle interactions with the cache , which is an infrastructure concern . And then threading , which is also an infrastructure concern . And what if i want to do is synchronously , instead of async ? What makes that decision ? I do n't want to have to just pile all this logic somewhere else . It ideally should be re factored into manageable and meaningful components , not shifted responsbility , if that makes sense.Any advice ? <code> [ 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 , thread spawning , something about a user ? ? Why ... . Task.Factory.StartNew ( ( ) = > { _cache.RefreshSomeCache ( post ) ; _cache2.RefreshSomeOtherCache ( post2 ) ; _userRepository.GiveUserPoints ( post.User ) ; _someotherRepo.AuditThisHappened ( ) ; } ) ; // This should be the 3rd line in this method . return RedirectToAction ( `` Index '' ) ; } [ HttpPost ] public ActionResult Save ( PostViewModel viewModel ) { // Map . var post = Mapper.Map < PostViewModel , Post > ( viewModel ) ; // Save . _postRepository.Save ( post ) ; // Tell someone about this . _eventManager.RaiseEvent ( post ) ; // Redirect . return RedirectToAction ( `` Index '' ) ; } | Can this MVC code be refactored using a design pattern ? |
C_sharp : 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 : Obviously , this is not a great way to query these tables with computed values , non-indexed columns , lots of OR 's and an unrestricted join on table_a and table_b . But for a user , this may make total sense . So what 's the best way , if any , to allow internal users to supply a query to the database while ensuring that it wo n't lock a dozen tables and hang the webserver for 5 minutes ? I 'm guessing that 's a programmatic way in c # /sql-server to get the execution plan for a query before it runs . And if so , what factors contribute to cost ? Estimated I/O cost ? Estimated CPU cost ? What would be reasonable limits at which to tell the user that his query 's no good ? EDIT : We 're a market research company . We have thousands of surveys , each with their own data . We have dozens of researchers that want to slice that data in arbitrary ways . We have tools to let them construct `` valid '' filters using a GUI , but some `` power users '' want to supply their own queries . I realize this is n't standard or best practice , but how else can I let dozens of users query tables for the rows they want using arbitrarily complex conditions and ever-changing conditions ? <code> 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_sharp : 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 value , basically memset ( 0 ) . Also , for the default arguments of the method MyMethod the compiler has no complaints . So , why is it that a const struct field is not possible ? Is there a reason why or is it just the way C # was written ? Oh and by the way , what 's the idea of allowing enum types to have a default constructor ? ( Question originally found here , where it did n't get a real answer . ) <code> 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 s = default ( S ) , // NO ERROR I i = default ( I ) , D d = default ( D ) , C c = default ( C ) , int x = 10 , string y = `` s '' ) { } } | Why ca n't a constant field be of non-built-in struct type in C # ? |
C_sharp : 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 some StockQuote application that streams a bunch of quotes and displays them on screen . Typically , you 'd have this : StockQuote.cs : ( Model ) StockQuoteViewModel.cs : ( ViewModel ) StockQuoteView.xaml ( View ) And then you 'd have some kind of service that would feed the ObservableCollection with new StockQuotes . My question is this : In this type of scenario , the StockQuote is considered the Model , and we 're exposing that to the View through the ViewModel 's ObservableCollection . Which basically means , our View has knowledge of the Model . Does n't that violate the whole paradigm of M-V-VM ? Or am I missing something here ... . ? <code> 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 ; } } } < Window x : Class= '' WpfApplication1.Window1 '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : WpfApplication1 '' Title= '' Window1 '' Height= '' 300 '' Width= '' 300 '' > < Window.DataContext > < local : StockQuoteViewModel/ > < /Window.DataContext > < Window.Resources > < DataTemplate x : Key= '' listBoxDateTemplate '' > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' { Binding Symbol } '' / > < TextBlock Text= '' { Binding Price } '' / > < /StackPanel > < /DataTemplate > < /Window.Resources > < Grid > < ListBox ItemTemplate= '' { StaticResource listBoxDateTemplate } '' ItemsSource= '' { Binding Quotes } '' / > < /Grid > < /Window > | M-V-VM , is n't the Model leaking into the View ? |
C_sharp : 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 profile this app , even despite I have two cores.One core is 100 % free and the other core have done all the work , and I see that both threads have been running in that core.Why is this ? Is it because I use a wait handle that sets when I post a message and releases when the processing is done ? This is my sample code , now using 2 worker threads.It still behaves the same , main , worker1 and worker2 is running in the same core.Ideas ? [ EDIT ] It sort of works now , atleast , I get twice the performance compared to yesterday.the trick was to slow down the consumer just enough to avoid signaling using the AutoResetEvent . <code> 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 ) ; public SingleThreadDispatcher ( ) { var thread = new Thread ( Run ) { IsBackground = true , Name = `` worker '' + Guid.NewGuid ( ) , } ; thread.Start ( ) ; } private void Run ( ) { while ( _running ) { _signal.WaitOne ( ) ; do { _hasMoreTasks = false ; Action task ; while ( _queue.TryDequeue ( out task ) & & _running ) { Count ++ ; task ( ) ; } //wait a short while to let _hasMoreTasks to maybe be set to true //this avoids the roundtrip to the AutoResetEvent //that is , if there is intense pressure on the pool , we let some new //tasks have the chance to arrive and be processed w/o signaling if ( ! _hasMoreTasks ) Thread.Sleep ( 5 ) ; Interlocked.Exchange ( ref _status , 0 ) ; } while ( _hasMoreTasks ) ; } } public void Schedule ( Action task ) { _hasMoreTasks = true ; _queue.Enqueue ( task ) ; SetSignal ( ) ; } private void SetSignal ( ) { if ( Interlocked.Exchange ( ref _status , 1 ) == 0 ) { _signal.Set ( ) ; } } } | Two threads one core |
C_sharp : 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 ? <code> js += `` < script type=\ '' text/javascript\ '' > \n '' ; js += `` function ( ) ... \n '' ; | Library to write javascript code |
C_sharp : 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 the near futureSo , to work around this , I make BaseControl not abstract , and its implementation of IBaseControl methods virtual . However , since these methods make no sense for a BaseControl ( e.g. , not all components have been added yet ) , I make them throw : In the derived control , I have the corresponding override : Despite this , when I try to open the control in the designer , I get an error indicating that the BaseControl.LoadSettings has thrown an exception.Now , remember LoadSettings is called in the base class , so when the Designer loads the DerivedControl , it in turn calls the load method for the BaseControl , which throws.Have you encountered a similar problem ? How have you dealt with this ? I 'd like to have an elegant solution , if possible . <code> 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 ( object sender , EventArgs e ) { // intention : derived methods automagically load their settings this.LoadSettings ( ) ; } } public partial class DerivedControl : BaseControl { public override void LoadSettings ( ) { // load settings } } | VisualStudio 2010 Designer throws on implemented virtual method |
C_sharp : 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 latest implementation is here . As you see , it 's ugly as hell.So , what 's the C # way to do this ? <code> 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_sharp : 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 code and how my graph appears.The lines of myCurveAudio and myCurveAudio2 intersect like in the picture.How can I merge these two list preventing those intersections ? I have also tried to add ` double.NaN to end of the lists but it did not work . <code> 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 ) ; } float energy = ( float ) Math.Sqrt ( listOfSquaredSegment.Sum ( ) ) ; if ( energy < 4 ) { for ( int i = 0 ; i < read ; i += ( int ) window ) { list1.Add ( ( float ) ( count / ( ( float ) read / ( float ) window ) ) , fmainBuffer [ i ] ) ; count++ ; } } else { for ( int i = 0 ; i < read ; i += ( int ) window ) { list4.Add ( ( float ) ( count / ( ( float ) read / ( float ) window ) ) , fmainBuffer [ i ] ) ; count++ ; } } } zgc.MasterPane.PaneList [ 1 ] .XAxis.Scale.MaxAuto = true ; zgc.MasterPane.PaneList [ 1 ] .XAxis.Scale.MinAuto = true ; zgc.MasterPane.PaneList [ 1 ] .XAxis.Type = AxisType.Linear ; zgc.MasterPane.PaneList [ 1 ] .XAxis.Scale.Format = `` '' ; zgc.MasterPane.PaneList [ 1 ] .XAxis.Scale.Min = 0 ; myCurveAudio = zgc.MasterPane.PaneList [ 1 ] .AddCurve ( null , list1 , Color.Lime , SymbolType.None ) ; myCurveAudio2 = zgc.MasterPane.PaneList [ 1 ] .AddCurve ( null , list4 , Color.Red , SymbolType.None ) ; | Merging multiple pointpairlist |
C_sharp : 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 everyone around me ? My goal is to read stuff like the following and make a comment like : Yeh , you are having a race condition . <code> .maxstack 2.entrypoint.locals init ( valuetype [ MathLib ] HangamaHouse.MathClass mclass ) ldloca mclassldc.i4 5 | How to become an MSIL pro ? |
C_sharp : 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 clear I 'm looking for <code> 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_sharp : 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 <code> var maxVal = l.TakeWhile ( x= > x < val ) .Where ( x= > Matches ( x ) ) .Max ( ) ; | space complexity of a simple linq ( to objects ) query |
C_sharp : 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 as Loop . I thought that x++ / x+=y should not slow down when x gets larger ( since it takes 1 or 2 cpu instructions any way ) Is it due to Locality of reference ? However I thought that in Loop2 there are not many variables , they should all be close to each other ... Update : When , if ever , is loop unrolling still useful ? is useful <code> 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 ; } } return ret ; } | How to explain the difference of performance in these 2 simple loops ? |
C_sharp : 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 ? <code> cardnumber.Select ( ( c , i ) = > i < cardnumber.Length - 4 ? ' X ' : c ) .ToArray ( ) | Enable Password Char in TextBox except last N character / Limit Masked Char |
C_sharp : 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 Protected and Overridable ( in Visual Basic ) . Name this method OnEventName ; for example , OnDataReceived . The method should take one parameter that specifies an event data object . You provide this method to enable derived classes to override the logic for raising the event . A derived class should always call the OnEventName method of the base class to ensure that registered delegates receive the event.indicating the On ... method is to raise an event . However , in many coding samples , even some provided by Microsoft , we can see event the On method used as event handler , like on in here https : //msdn.microsoft.com/en-us/windows/uwp/gaming/tutorial -- adding-move-look-controls-to-your-directx-game ? f=255 & MSPPError=-2147217396 First , let 's populate the mouse and touch pointer event handlers . In the first event handler , OnPointerPressed ( ) , we get the x-y coordinates of the pointer from the CoreWindow that manages our display when the user clicks the mouse or touches the screen in the look controller region.My questions being : Is there indeed such ambiguity over the usage of `` On '' prefix or is it just my misunderstanding ? Do people really use `` On '' in both raising and handling event methods ? What is the standard style of implementing the method raising and handling event ? And what are the popular styles ? What is the style that you suggest ? <code> 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.Y ) ; auto device = args- > CurrentPoint- > PointerDevice ; auto deviceType = device- > PointerDeviceType ; if ( deviceType == PointerDeviceType : :Mouse ) { // Action , Jump , or Fire } // Check if this pointer is in the move control . // Change the values to percentages of the preferred screen resolution . // You can set the x value to < preferred resolution > * < percentage of width > // for example , ( position.x < ( screenResolution.x * 0.15 ) ) . if ( ( position.x < 300 & & position.y > 380 ) & & ( deviceType ! = PointerDeviceType : :Mouse ) ) { if ( ! m_moveInUse ) // if no pointer is in this control yet { // Process a DPad touch down event . m_moveFirstDown = position ; // Save the location of the initial contact . m_movePointerPosition = position ; m_movePointerID = pointerID ; // Store the id of the pointer using this control . m_moveInUse = TRUE ; } } else // This pointer must be in the look control . { if ( ! m_lookInUse ) // If no pointer is in this control yet ... { m_lookLastPoint = position ; // save the point for later move m_lookPointerID = args- > CurrentPoint- > PointerId ; // store the id of pointer using this control m_lookLastDelta.x = m_lookLastDelta.y = 0 ; // these are for smoothing m_lookInUse = TRUE ; } } } | What does prefix `` On '' implement in event cases in C # coding ? |
C_sharp : 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 misunderstanding how IsReusable works ? Is there something else that can defeat re-use ? My handler is being called from a Silverlight application if that makes any difference . <code> 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 = `` text/plain '' ; context.Response.Write ( `` Hello World '' ) ; } } Requests processed by this handler : 1Requests processed by this handler : 1Requests processed by this handler : 1Requests processed by this handler : 1 ... at least 100 times . I never see > 1 . | IHttpHandler IsReusable , but is not getting re-used |
C_sharp : 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 . The problem that I have found , however , is that Constructor.GetParameters appears to not be thread-safe when the ConstructorInfo is marked as being a thread-safe type . That is , if two threads reach Constructor.GetParameters at the same time , two results are produced , and subsequent calls to this method returns the second result that was created ( regardless of the thread that calls it ) .I have created some code to demonstrate this unexpected behavior ( I also have it hosted on GitHub if you would like to download and try the project locally ) .Here is the code : The two test classes ensure that two threads are created and run in parallel . Upon running these tests , you should get results that look like the following : ( NOTE : I 've added `` < -- -- Different ! '' to denote the unexpected value . You will not see this in the test results . ) As you can see , the result from the very first call to the GetParameters returns a different value than all subsequent calls.I have had my nose in .NET for quite a while now , but have never seen anything quite like this . Is this expected behavior ? Is there a preferred/known way of initializing the .NET type system so that this does not happen ? Finally , if anyone is interested , I ran into this problem while using xUnit with MEF 2 , where a ParameterInfo being used as a key in a dictionary is not returning as equal to the ParameterInfo being passed in from a previously saved value . This , of course , results in unexpected behavior and resulting in failed tests when run concurrently.EDIT : After some good feedback from the answers , I have ( hopefully ) clarified this question and scenario . The core of the issue is `` Thread-Safety '' of a `` Thead-Safe '' type , and acquiring better knowledge of what exactly this means.ANSWER : This issue ended up being being due to several factors , one of which is due to me never-ending ignorance to multi-threaded scenarios , which it seems I am forever learning with no end for the foreseeable future . I am again appreciative of xUnit for being designed in such a way to learn this territory in such an effective manner.The other issue does appear to be inconsistencies with how the .NET type system initializes . With the TypeInfo/Type , you get the same type/reference/hashcode no matter which thread accesses it however many times . For MemberInfo/MethodInfo/ParameterInfo , this is not the case . Thread access beware.Finally , it seems I am not the only person with this confusion and this has indeed been recognized as an invalid assumption on a submitted issue to .NET Core 's GitHub repository.So , problem solved , mostly . I would like to send my thanks and appreciation to all involved in dealing with my ignorance in this matter , and helping me learn ( what I am finding is ) this very complex problem space . <code> 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 ( typeof ( SampleObject ) .GetTypeInfo ( ) ) ; output.WriteLine ( `` After Initialized : '' ) ; Support.Output ( output ) ; } } public class AnotherClass { readonly ITestOutputHelper output ; public AnotherClass ( ITestOutputHelper output ) { this.output = output ; } [ Fact ] public void OutputHashCode ( ) { Support.Add ( typeof ( SampleObject ) .GetTypeInfo ( ) ) ; output.WriteLine ( `` Initialized : '' ) ; Support.Output ( output ) ; Support.Add ( typeof ( SampleObject ) .GetTypeInfo ( ) ) ; output.WriteLine ( `` After Initialized : '' ) ; Support.Output ( output ) ; } } public static class Support { readonly static ICollection < int > Numbers = new List < int > ( ) ; public static void Add ( TypeInfo info ) { var code = info.DeclaredConstructors.Single ( ) .GetParameters ( ) .Single ( ) .GetHashCode ( ) ; Numbers.Add ( code ) ; } public static void Output ( ITestOutputHelper output ) { foreach ( var number in Numbers.ToArray ( ) ) { output.WriteLine ( number.ToString ( ) ) ; } } } public class SampleObject { public SampleObject ( object parameter ) { } } Initialized:39053774 < -- -- Different ! 45653674After Initialized:39053774 < -- -- Different ! 456536744565367445653674 | Is ConstructorInfo.GetParameters Thread-Safe ? |
C_sharp : 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 still want to know whether this is absolutely safe and always works as expected , and I ca n't find the answer by Google.Could anyone give me some explanations ? Thanks in advance . <code> 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_sharp : 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 about the lambda side effect ( just an example ) , more if there is this functionality ... for instance in lisp , you have progn <code> int foo = { printf ( `` bar '' ) ; 1 } ; | C # scoping operator |
C_sharp : 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 ? <code> 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_sharp : 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 in the future . We wo n't have to change the method signature , but the Request object still have to change.Personally , I do n't think it is a good idea . Using parameters makes it explicit what the method requires to run . In addition , this force us to create another object for not much.What are the pros and cons of using Request objects ? Are you using it in your projects and why ? <code> public Stream GetMusic ( string songTitle , string albumName ) { ... } public Stream GetMusic ( SongRequest request ) { ... } | Request object , what are the pros and cons ? |
C_sharp : 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 I created because in my program , there are a lot of other classes that might want to refer to this special well-known instance.The downside of implementing this way is that I do n't know any way to make all the properties of Person.Waldo immutable , while all the properties of a `` normal '' Person instance should be mutable . Whenever I accidentally have a Person object referring to Waldo , and I carelessly do n't check to see if it 's referring to Waldo , then I accidentally clobber Waldo 's properties.Is there a better way , or even some additional alternative ways , to define special well-known instances of a class ? The only solution I know right now , is to implement the get & set accessors , and check `` if ( this == Waldo ) throw new ... '' on each and every set . While this works , I assume C # can do a better job than me of implementing it . If only I can find some C # way to make all the properties of Waldo readonly ( except during static constructor . ) <code> 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_sharp : 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 point but it 's not quite there yet : I would appreciate any suggestions . <code> 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 | | Hours |Date | Hours | Hours | | Hours | ... | Hours | Hours | | Hours | var _result = Employees.SelectMany ( x = > x.WorkDays ) .GroupBy ( x = > x.Date ) .Select ( y = > new { DATE = y.Key , NAME = y.Select ( z = > z.Employee.Name ) .ToArray ( ) } ) .ToList ( ) ; | Pivot data in two nested List < T > with Linq |
C_sharp : 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 ? <code> 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_sharp : 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 GetABunchOfDataZipped ( String sessionId ) be a void , when it finishes have another endpoint which on my duplex contract which I hit . I do n't like this as ifs a fundamental change in my architecture and if the string is a large block of text over a slow internet connection it will still suffer from the same issue ? <code> [ ServiceContract ( SessionMode = SessionMode.Required , CallbackContract = typeof ( IBuddyListContract ) ) ] public interface IBuddyListPubSubContract { [ OperationContract ] string GetABunchOfDataZipped ( String sessionId ) ; // this can take > 20 seconds ... . } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.PerCall , ConcurrencyMode = ConcurrencyMode.Multiple ) ] public class BuddyListPubSubContract : IBuddyListPubSubContract { string GetABunchOfDataZipped ( String sessionId ) { // do some calculations and data retrival return result ; } } | C # WCF NetTCPBinding Blocking Application |
C_sharp : 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 the rules : prefixes must be in random ordersuffixes must be in random order while making sure that each 10k numbers in the sequence have all numbers from 0000 to 9999. must be able to generate the numbers again in the same order , given a seed.Not really a requirement but it would be great if it was done using Linq.Thus far , I have written some code that meets all requirements but the first one : Using this I am able to reproduce the sequence by using the same seed , the first 10000 numbers have all numbers from 0000 to 9999 , as does the second 10k and so on , but the prefixes are not really random since each 10k group will have the same prefix.I also thought of creating a class with the number and it 's group ( 100 groups , each group having 10k numbers ) to make it easier to shuffle but I believe that are better , simpler ways to do it . <code> 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 ( var entry in result ) { Console.WriteLine ( entry ) ; } | How to generate a sequence of numbers while respecting some constraints ? |
C_sharp : 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 value from the header.I know that I can use a messageinspector to get the header data like this : But I need to get this information in the Evaluate method so I can make a proper login ( set principal ) . Is it possible ? And if so , how ? What is the alternative ? PS . This will be done by call so no specific login method could be used.Solved : I ended up with this : <code> 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.Message request , IClientChannel channel , InstanceContext instanceContext ) { IntegrationHeader integrationHeader ; LoginHandler loginHandler ; UserContextOnService userContext = null ; if ( request.Headers.Action == null || request.Headers.Action.ToString ( ) .Length < 1 ) return null ; foreach ( var header in request.Headers ) { if ( header.Namespace == `` ns '' & & header.Name == `` SecurityToken '' ) { return null ; } } throw new SecurityTokenException ( `` Unknown username or invalid password '' ) ; } integrationHeader = OperationContext.Current.IncomingMessageHeaders.GetHeader < IntegrationCertificateHeader > ( header.Name , header.Namespace ) ; | Login with IAuthorizationPolicy and UserNamePasswordValidator with header data ? |
C_sharp : 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 case bits 8,10,12 are most probable . Andin C # bits 6,8,11 are most probable.Also seems that C # most probable bits is mostly shifted by 2 positions then compared to C most probable bits . Why is this ? Because C # uses other RAND_MAX constant or what ? My test code for C : And test code for C # : Very thanks ! ! Btw , OS is Windows 7 , 64-bit architecture & Visual Studio 2010.EDITVery thanks to @ David Heffernan . I made several mistakes here : Seed in C and C # programs was different ( C was using zero and C # - current time ) .I did n't tried experiment with different values of Times variable to research reproducibility of results.Here 's what i 've got when analyzed how probability that first bit is set depends on number of times random ( ) was called : So as many noticed - results are not reproducible and should n't be taken seriously . ( Except as some form of confirmation that C/C # PRNG are good enough : - ) ) . <code> 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++ ) { accumulateResults ( rand ( ) , bitSet ) ; } for ( i=0 ; i < 15 ; i++ ) { printf ( `` % d : % d\n '' , i , bitSet [ i ] ) ; } system ( `` pause '' ) ; return 0 ; } static void accumulateResults ( int random , int [ ] bitSet ) { int i ; int isBitSet ; for ( i = 0 ; i < 15 ; i++ ) { isBitSet = ( ( random & ( 1 < < i ) ) ! = 0 ) ? 1 : 0 ; bitSet [ i ] += isBitSet ; } } static void Main ( string [ ] args ) { int i ; int [ ] bitSet = new int [ 15 ] ; int times = 10000000 ; Random r = new Random ( ) ; for ( i = 0 ; i < times ; i++ ) { accumulateResults ( r.Next ( ) , bitSet ) ; } for ( i = 0 ; i < 15 ; i++ ) { Console.WriteLine ( `` { 0 } : { 1 } '' , i , bitSet [ i ] ) ; } Console.ReadKey ( ) ; } | Most probable bits in random integer |
C_sharp : 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 approach , and not something simpler like the second or the third one . Is there any performance issue with Equals ( static or instance ) method ? Or is there any specific benefit with using String.Compare method that even outweighs the processing of an extra operation of the entailing .Equals ( 0 ) ? <code> 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_sharp : 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 ( .tif images ) Question : How do I optimize the performance of my application ? I 've read/researched that I might have to load the images directly from the computers memory and some other methods . How would i go about this or is there a better way of coding this ? That is the code I have so far , but my application lags a little when i go to the next page.Below is a link of a large TIFF image with multiple pages for testing . Linkhttp : //www.filedropper.com/tiftestingdoc <code> 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 not locked in users directory when in use by this application . try { if ( _myImg == null ) { try { _fileName = Path.Combine ( Path.GetTempPath ( ) , Guid.NewGuid ( ) .ToString ( `` N '' ) ) ; File.Copy ( @ '' C : \Picture_Doc\The_Image.tif '' , _fileName ) ; _stream = new FileStream ( _fileName , FileMode.Open , FileAccess.Read ) ; this._Source = Image.FromStream ( _stream ) ; } catch ( Exception ex ) { } } _TotalPages = _Source.GetFrameCount ( System.Drawing.Imaging.FrameDimension.Page ) ; intCurrPage = 1 ; Display_Page ( intCurrPage ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; } } private void Show_Processing_Image_Label ( ) { Application.DoEvents ( ) ; } private void Display_Page ( int PageNumber , RotateFlipType Change ) { if ( pictureBox1.Image ! = null & & pictureBox1.Image ! = _Source ) { //Release memory for old rotated image pictureBox1.Image.Dispose ( ) ; } // set the variable to null for easy Garbage Collection cleanup pictureBox1.Image = null ; _Source.SelectActiveFrame ( System.Drawing.Imaging.FrameDimension.Page , PageNumber - 1 ) ; pictureBox1.Image = new Bitmap ( _Source ) ; pictureBox1.Image.RotateFlip ( Change ) ; pictureBox1.Refresh ( ) ; //Refresh ( ) Calls Invalidate and then Update to refresh synchronously . } private void Display_Page ( int PageNumber ) { Show_Processing_Image_Label ( ) ; //You could adjust the PictureBox size here for each frame OR adjust the image to fit the picturebox nicely if ( pictureBox1.Image ! = _Source ) { if ( pictureBox1.Image ! = null ) { //Release memory for old copy and set the variable to null for easy GC cleanup pictureBox1.Image.Dispose ( ) ; pictureBox1.Image = null ; } pictureBox1.Image = _Source ; } pictureBox1.Image.SelectActiveFrame ( System.Drawing.Imaging.FrameDimension.Page , PageNumber - 1 ) ; pictureBox1.Refresh ( ) ; } private void Next_btn_Click ( object sender , EventArgs e ) { intCurrPage++ ; Display_Page ( intCurrPage ) ; } private void Open_btn_Click ( object sender , EventArgs e ) { if ( _stream ! = null ) { _myImg = null ; //dispose the copy image } if ( openFileDialog1.ShowDialog ( ) == DialogResult.OK ) { Clone_File ( ) ; } pictureBox1.Size = new Size ( 850 , 1100 ) ; } | Boost the performance when advancing to the next page using .tif images |
C_sharp : 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 remove.I 'm now using ConcurrentDicionary as a temporary solution . but it 's definitely not the proper way to do it.So my question is how can I solve this problem ? Is there any lock free implementation for things like this out there ? Because none of the Collections under Concurrent name space suit for this problem . <code> 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_sharp : 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 lots of validation logic . Below is the code that does not compile in VS 2015.Is there a workaround for this compilation issue ? Any help would be appreciated.The Error : <code> 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 > : Validator < T > { protected override void DoValidate ( T objectToValidate ) { } } public class Required : ValidatorBase < object > { } Severity Code Description Project File LineError CS0534 'Required ' does not implement inherited abstract member 'Validator < object > .DoValidate ( object ) ' Program.cs 38 | Visual Studio 2015 does not compile when generic type matches overloaded method that takes that type |
C_sharp : 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.Cast and found the following : For our intents and purposes , the only thing that matters are the first two lines , because they 're the only ones that get called . That means that the line : is effectively translated into : However , removing the cast to the non-generic IEnumerable causes a compiler error : I 've been scratching my head as to why this is , and I think it 's got to do with the fact that Array implements the non-generic IEnumerable and that there is all sorts of special casing for arrays in C # , but I 'm honestly not sure . Please can someone explain to me what 's going on here and why ? <code> 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 ( ) ) ; // output : Foo [ ] ? ? ? Console.WriteLine ( intValues.First ( ) .GetType ( ) ) ; // output : Int32 Console.WriteLine ( ReferenceEquals ( enumValues , intValues ) ) ; // true var intValuesArray = intValues.ToArray ( ) ; Console.WriteLine ( intValuesArray.GetType ( ) ) ; // output : Int32 [ ] Console.WriteLine ( intValuesArray.First ( ) .GetType ( ) ) ; // output : Int32 Console.WriteLine ( ReferenceEquals ( intValues , intValuesArray ) ) ; // false } public static IEnumerable < TResult > Cast < TResult > ( this IEnumerable source ) { IEnumerable < TResult > typedSource = source as IEnumerable < TResult > ; if ( typedSource ! = null ) return typedSource ; if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; return CastIterator < TResult > ( source ) ; } var intValues = enumValues.Cast < int > ( ) ; var intValues = ( ( IEnumerable ) enumValues ) as IEnumerable < int > ; var intValues = enumValues as IEnumerable < int > ; // error | Type system oddity : Enumerable.Cast < int > ( ) |
C_sharp : 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 , let 's call it GlobalFoo.Again , if I create a method called Application_Start ( ) it will get called inside my derived class , otherwise nothing that 's in Global will get called so I might as well be deriving from an empty class.Can anyone offer any advice ? Am I missing some fundamental part of ASP.NET ? <code> void Application_Start ( object sender , EventArgs e ) { } | Confused over global.asax ? |
C_sharp : 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 someone explain why the MainPage might appear four times ? Is it needed more than once , is it needed at all ? There are many files that are not in the list of Includes ? If only half are there then why is it ? I understand that some views depend on others but I have many more of these and yet it only shows the relationship for three . Why could this be ? Can I just remove all these entries from the project file as there seems to be not much similarity between the project file and the folders / files in the project ? <code> < 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 '' / > < PackageReference Include= '' Syncfusion.Xamarin.SfChart '' Version= '' 16.2.0.42 '' / > < /ItemGroup > < ItemGroup > < Folder Include= '' Views\ '' / > < Folder Include= '' Views\Settings\Pages\ '' / > < Folder Include= '' Views\Home\PopUp\ '' / > < Folder Include= '' Views\Help\Cards\ '' / > < /ItemGroup > < ItemGroup > < EmbeddedResource Remove= '' Views\Cards\Category\CategoriesPage.xaml '' / > < EmbeddedResource Remove= '' Views\Cards\Templates\LinkTextCell.xaml '' / > < EmbeddedResource Remove= '' Views\Cards\Templates\SwitchViewCell.xaml '' / > < EmbeddedResource Remove= '' Views\Home\Dictionary.xaml '' / > < /ItemGroup > < ItemGroup > < None Include= '' Views\Cards\Cards.xaml '' / > < None Include= '' Views\Cards\Category\CategoriesPage.xaml '' / > < None Include= '' Views\Cards\Category\CategoryViewCell.xaml '' / > < None Include= '' Views\Cards\Templates\LinkTextCell.xaml '' / > < None Include= '' Views\Cards\Templates\SwitchViewCell.xaml '' / > < None Include= '' Views\MainPage.xaml '' / > < None Include= '' Views\MainPage.xaml '' / > < None Include= '' Views\MainPage.xaml '' / > < None Include= '' Views\MainPage.xaml '' / > < /ItemGroup > < ItemGroup > < Compile Update= '' Views\MainPage.xaml.cs '' > < DependentUpon > MainPage.xaml < /DependentUpon > < /Compile > < Compile Update= '' Views\Home\HomePage.xaml.cs '' > < DependentUpon > HomePage.xaml < /DependentUpon > < /Compile > < Compile Update= '' Views\Cards\Category\CategoryViewCell.xaml.cs '' > < DependentUpon > CategoryViewCell.xaml < /DependentUpon > < /Compile > < /ItemGroup > < /Project > | C # project file - Why does n't it represent what 's in my project ? |
C_sharp : 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 something like the following appear in the console : ( a second passes.. ) And so on . So far , I have been able to get an output of the count of all events per second . But ca n't seem to be able to group them by event type . The code I am using is based on a gist by James Nugent : <code> 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 ( EventStoreSubscription subscription , Subject < ResolvedEvent > resolvedEvent , Subject < SubscriptionDropReason > droppedReasons ) { Subscription = subscription ; ResolvedEvents = resolvedEvent ; DroppedReasons = droppedReasons ; } } static class EventStoreConnectionExtensions { public static Task < EventStoreRxSubscription > SubscribeTo ( this IEventStoreConnection connection , string streamName , bool resolveLinkTos ) { return Task < EventStoreRxSubscription > .Factory.StartNew ( ( ) = > { var resolvedEvents = new Subject < ResolvedEvent > ( ) ; var droppedReasons = new Subject < SubscriptionDropReason > ( ) ; var subscriptionTask = connection.SubscribeToStreamAsync ( streamName , resolveLinkTos , ( subscription , @ event ) = > resolvedEvents.OnNext ( @ event ) , ( subscription , dropReason , arg3 ) = > droppedReasons.OnNext ( dropReason ) ) ; subscriptionTask.Wait ( ) ; return new EventStoreRxSubscription ( subscriptionTask.Result , resolvedEvents , droppedReasons ) ; } ) ; } } class Program { static void Main ( string [ ] args ) { var connection = EventStoreConnection.Create ( new IPEndPoint ( IPAddress.Loopback , 1113 ) ) ; connection.ConnectAsync ( ) ; var subscriptionTask = connection.SubscribeTo ( `` orders '' , true ) ; subscriptionTask.Wait ( ) ; var events = subscriptionTask.Result.ResolvedEvents ; var query = events.Timestamp ( ) .Buffer ( TimeSpan.FromSeconds ( 1 ) ) .Select ( e = > e.Count ) ; query.Subscribe ( Console.WriteLine ) ; Console.ReadLine ( ) ; } } | Rx : Count of Grouped Events in Moving Window |
C_sharp : 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 i click the dgv it display the error : formatting , display and some times formatting , preferredSize . When I remove the DataPropertyName property , this error goes but data are not displayed . Though , the payMonth values in the table are only in the list range or is null.This is payments table : Whats wrong ? <code> 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 ( ) { payMonth = 4 , monthName = `` apr '' } , new months ( ) { payMonth = 5 , monthName = `` may '' } , new months ( ) { payMonth = 6 , monthName = `` jun '' } , new months ( ) { payMonth = 7 , monthName = `` jul '' } , new months ( ) { payMonth = 8 , monthName = `` aug '' } , new months ( ) { payMonth = 9 , monthName = `` sep '' } , new months ( ) { payMonth = 10 , monthName = `` oct '' } , new months ( ) { payMonth = 11 , monthName = `` nov '' } , new months ( ) { payMonth = 12 , monthName = `` dec '' } } ; cmbMonth = new DataGridViewComboBoxColumn ( ) ; cmbMonth.DataSource = lstMonths ; cmbMonth.ValueMember = `` payMonth '' ; cmbMonth.DisplayMember = `` monthName '' ; cmbMonth.DataPropertyName = `` payMonth '' ; cmbMonth.Name = `` cmbPayMonth '' ; cmbMonth.HeaderText = `` Month '' ; cmbMonth.FlatStyle = FlatStyle.Flat ; cmbMonth.Width = 80 ; dgvPayments.Columns.Insert ( 5 , cmbMonth ) ; | C # binding datagridviewcomboboxcolumn to list display , formatting , preferred Size error |
C_sharp : 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 . <code> 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 ) { // ... _list.Add ( example ) ; // ... } } } | C # parallel read access to List without copying |
C_sharp : 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 cMyImplementationClass : I wrapped these 2 dlls with tlbimp.exe and attempt to call the function from C # .Calling foo.GetErrors ( ) causes a SafeArrayRankMismatchException . I think this indicates a marshaling problem as described in the Safe Arrays section here.The recommendation seems to be to use the /sysarray parameter of tlbimp.exe or to manually edit the IL produced , which I tried.The original IL looks like this : While the updated version is : I made identical function signature changes in both the interface and implementation . This process is described here . However , it does n't specify a return value in the function ( it uses an `` in '' reference ) and also does n't use an interface . When I run my code and call from C # , I get the error Method not found : 'System.Array MyDll.cImplementationClass.GetErrors ( ) '.It seems to be that something is wrong in the IL that I edited , though I do n't know where to go from here.How can I consume this function from C # without changing the VB6 code ? -- Edit -- Redefinition of `` msErrors '' , which initializes the private array that gets returned.If I understand correctly , the `` 1 '' in that means that the array is indexed from 1 instead of 0 , which is the cause of the exception I see get thrown . <code> [ 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 ) * ) ; } ; Private Function IMyInterface_GetErrors ( ) As String ( ) If mbCacheErrors Then IMyInterface_GetErrors = msErrors End IfEnd Function public void UseFoo ( ) { cMyImplementationClass foo ; ... var result = foo.GetErrors ( ) ; ... } .method public hidebysig newslot virtual instance string [ ] marshal ( safearray bstr ) GetErrors ( ) runtime managed internalcall { .override [ My.Interfaces ] My.Interface.IMyInterface : :GetErrors } // end of method cImplementationClass : :GetErrors .method public hidebysig newslot virtual instance class [ mscorlib ] System.Array marshal ( safearray ) GetErrors ( ) runtime managed internalcall { .override [ My.Interfaces ] My.Interface.IMyInterface : :GetErrors } // end of method cImplementationClass : :GetErrors ReDim Preserve msErrors ( 1 To mlErrorCount ) | Consuming VB6 string array in C # |
C_sharp : 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 just use them inside my XAML as follows : Well ... nothing to say . It works ... but it 's soooo damn ugly to see and I was wondering if there is any better solution for this . I do n't know ... maybe a Settings file , bindings , inline XAML calculations or whatever else ... something that would make it just look better . <code> 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.RealHeight + MarginInner ; public static readonly Double TableTop = MarginOuter + MyUC.RealHeight + MarginInner ; public static readonly Double TableWidth = ( StrokeThickness * 2D ) + ( MyUC.RealWidth * 6D ) + ( MarginInner * 7D ) ; public static readonly Double LayoutHeight = ( TableTop * 2D ) + TableHeight ; public static readonly Double LayoutWidth = TableLeft + TableWidth + MarginOuter ; < Window x : Class= '' MyNS.MainWindow '' ResizeMode= '' NoResize '' SizeToContent= '' WidthAndHeight '' > < Canvas x : Name= '' m_Layout '' Height= '' { x : Static ns : MainWindow.LayoutHeight } '' Width= '' { x : Static ns : MainWindow.LayoutWidth } '' > | Elegant Solution for Readonly Values |
C_sharp : 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 have an enum , PortfolioSheetMapping , which has ~40 or so elements.It sort of looks like this : I have a method which can invoke the List to be sorted depending on which enumeration the user selects . The method uses a mondo switch statement that has over 40 cases ( ugh ! ) . A short snippet below illustrates the code : My problem is with the switch statement . The switch is tightly bound to the PortfolioSheetMapping enum , which can change tomorrow or the next day . Each time it changes , I 'm going to have to revisit this switch statement , and add yet another case block to it . I 'm just afraid that eventually this switch statement will grow so big that it is utterly unmanageable.Can someone tell me if there 's a better way to sort my list ? <code> 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 = 0 , Symbol , Quantitiy , Price , // ... more elements ... } if ( frm.SelectedSortColumn.IsBaseColumn ) { switch ( frm.SelectedSortColumn.BaseColumn ) { case PortfolioSheetMapping.IssueId : if ( frm.SortAscending ) { // here I 'm sorting the Holding instance 's // Product.IssueId property values ... // this is the pattern I 'm using in the switch ... pf.Holdings = pf.Holdings.OrderBy ( c = > c.Product.IssueId ) .ToList ( ) ; } else { pf.Holdings = pf.Holdings.OrderByDescending ( c = > c.Product.IssueId ) .ToList ( ) ; } break ; case PortfolioSheetMapping.MarketId : if ( frm.SortAscending ) { pf.Holdings = pf.Holdings.OrderBy ( c = > c.Product.MarketId ) .ToList ( ) ; } else { pf.Holdings = pf.Holdings.OrderByDescending ( c = > c.Product.MarketId ) .ToList ( ) ; } break ; case PortfolioSheetMapping.Symbol : if ( frm.SortAscending ) { pf.Holdings = pf.Holdings.OrderBy ( c = > c.Symbol ) .ToList ( ) ; } else { pf.Holdings = pf.Holdings.OrderByDescending ( c = > c.Symbol ) .ToList ( ) ; } break ; // ... more code ... . | Looking for a better way to sort my List < T > |
C_sharp : 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 converting values I am surprised that the values are not more stable . I wanted to know how I can make accurate measurements which are meaningful and to not change from one day to the other . The differences are about 20 % from one day to the other . There are of course differences between the JITer of .NET 3.5 and 4.0 , debug and release mode , not running the executable under a debugger ( disables JIT optimizations until you disable it ) , code generation of the C # compiler between DEBUG and RELEASE ( mainly nop operations and more temporary variables in the IL code ) . I do get thenTimes : 1257 1388 1180Times : 1331 1428 1267Times : 1337 1435 1267Times : 1208 1414 1145From this it does look like the dumb safe variant is faster than any unsafe variant although bounds check elimination of the unsafe methods should make it at least as fast if not faster . Just for fun I did also compile the same IL code via LCG ( DynamicMethod ) which seem to be even slower than any of these methods although the additional cost of the delegate invocation does not seem to play such a big role here . The for loop does execute this code 10 million times which should produce stable results . Why am I seeing any differences here at all ? Using realtime as process priority did also not help ( psexec -realtime executable ) . How can I get reliable numbers ? My tests did includeDual Quad Core machinesWindows 7 32 / 64 bit editions.NET Framework 3.5/4.032/64 bit versions of the executable.If I use a profiler I am not sure if he will distort the measurements even more . Since he does interrupt my application from time to time to get the call stacks he will certainly destroy any cache locality which might aid performance . If there is any approach with better ( data ) cache locality I will not be able to find it out with a profiler.Edit1 : To take into account that I do not have a real time OS I do now sample my measurements . Since for one thread I have a 15ms time window granted the the Windows Scheduler I can keep out the Scheduler if I measure shorter than 15ms . If I do measure too shortly I will end up with very small tick counts which will not tell me much . To get stable values I need a time span long enough to let the OS do whatever it does on a regular basis . Empiric tests have shown that 30+ seconds is a good time span one measurment should take . This time span is then divided into sample time spans which are well below 15ms . Then I will get timing information for each sample . From the samples I can extract min/max and average . This way I can also see first time initialization effects . The code looks now like thisThe values from these tests do still vary ( < 10 % ) but I think that if I create a histogram chart of my values and drop the 10 % highest values which are likely caused by the OS , GC , ... I can get really stable numbers which I can trust . SampleSize : 100 , Min 25 , Max 86400 , Average 28,614631SampleSize : 100 , Min 24 , Max 86027 , Average 28,762608SampleSize : 100 , Min 25 , Max 49523 , Average 32,102037SampleSize : 100 , Min 24 , Max 48687 , Average 32,030088Edit2 : The histograms show that the measured values are not random . They look like a Landau distribution which should give me with the right approximation algorithms stable values . I wish in .NET would exist something like ROOT where I can interactivly fit the right distribution function to my data and get the results.The code to generate the histogram with the MSChart controls is below : <code> 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 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 } ; var s2 = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < RUNS ; i++ ) { float [ ] arr = Cast ( array ) ; } s2.Stop ( ) ; GC.Collect ( ) ; var s3 = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < RUNS ; i++ ) { float [ ] arr = Cast2 ( array ) ; } s3.Stop ( ) ; GC.Collect ( ) ; var s4 = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < RUNS ; i++ ) { var arr = CastSafe ( array ) ; } s4.Stop ( ) ; Console.WriteLine ( `` Times : { 0 } { 1 } { 2 } '' , s2.ElapsedMilliseconds , s3.ElapsedMilliseconds , s4.ElapsedMilliseconds ) ; } // Referece cast implementation to check performance public static unsafe float [ ] Cast ( int [ ] input ) { int N = input.Length ; float [ ] output = new float [ N ] ; fixed ( int* pIStart = & input [ 0 ] ) { int* pI = pIStart ; fixed ( float* pOStart = & output [ 0 ] ) { float* pO = pOStart ; for ( int i = 0 ; i < N ; i++ ) { *pO = ( float ) *pI ; pI++ ; pO++ ; } } } return output ; } // Referece cast implementation to check performance public static unsafe float [ ] Cast2 ( int [ ] input ) { int N = input.Length ; float [ ] output = new float [ N ] ; fixed ( int* pIStart = & input [ 0 ] ) { int* pI = pIStart ; fixed ( float* pOStart = & output [ 0 ] ) { float* pO = pOStart ; for ( int i = 0 ; i < N ; i++ ) { pO [ i ] = ( float ) pI [ i ] ; } } } return output ; } public static float [ ] CastSafe ( int [ ] input ) { int N = input.Length ; float [ ] output = new float [ N ] ; for ( int i = 0 ; i < input.Length ; i++ ) { output [ i ] = ( float ) input [ i ] ; } return output ; } } } class Program { const int RUNS = 100 * 1000 * 1000 ; // 100 million runs will take about 30s const int RunsPerSample = 100 ; // 100 runs for on sample is about 0,01ms < < 15ms 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 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 , 32 , 33 , 34 , 35 , 36 , 37 , 38 , 39 , 40 , 41 , 42 , 43 } ; long [ ] sampleTimes = new long [ RUNS/RunsPerSample ] ; int sample = 0 ; for ( int i = 0 ; i < RUNS ; i+=RunsPerSample ) { var sw = Stopwatch.StartNew ( ) ; for ( int j = i ; j < i+RunsPerSample ; j++ ) { float [ ] arr = Cast ( array ) ; } sw.Stop ( ) ; sampleTimes [ sample ] = sw.ElapsedTicks ; sample++ ; } Console.WriteLine ( `` SampleSize : { 0 } , Min { 1 } , Max { 2 } , Average { 3 } '' , RunsPerSample , sampleTimes.Min ( ) , sampleTimes.Max ( ) , sampleTimes.Average ( ) ) ; using System.Collections.Generic ; using System.Drawing ; using System.Linq ; using System.Windows.Forms ; using System.Windows.Forms.DataVisualization.Charting ; namespace ConsoleApplication4 { public partial class Histogram : Form { public Histogram ( long [ ] sampleTimes ) { InitializeComponent ( ) ; Series histogramSeries = cHistogram.Series.Add ( `` Histogram '' ) ; // Set new series chart type and other attributes histogramSeries.ChartType = SeriesChartType.Column ; histogramSeries.BorderColor = Color.Black ; histogramSeries.BorderWidth = 1 ; histogramSeries.BorderDashStyle = ChartDashStyle.Solid ; var filtered = RemoveHighValues ( sampleTimes , 40 ) ; KeyValuePair < long , int > [ ] histoData = GenerateHistogram ( filtered ) ; ChartArea chartArea = cHistogram.ChartAreas [ histogramSeries.ChartArea ] ; chartArea.AxisY.Title = `` Frequency '' ; chartArea.AxisX.Minimum = histoData.Min ( x= > x.Key ) ; chartArea.AxisX.Maximum = histoData.Max ( x= > x.Key ) ; foreach ( var v in histoData ) { histogramSeries.Points.Add ( new DataPoint ( v.Key , v.Value ) ) ; } chartArea.AxisY.Minimum = 0 ; chartArea.AxisY.Maximum = histoData [ 0 ] .Value + 100 ; } // Count the occurence of each value of input and return an array with the value as key and its count as value // as ordered list starting with the highest counts . KeyValuePair < long , int > [ ] GenerateHistogram ( long [ ] input ) { Dictionary < long , int > counts = new Dictionary < long , int > ( ) ; foreach ( var value in input ) { int old = 0 ; if ( ! counts.TryGetValue ( value , out old ) ) { counts [ value ] = 0 ; } counts [ value ] = ++old ; } var orderedCounts = ( from x in counts orderby x.Value descending select x ) .ToArray ( ) ; return orderedCounts ; } long [ ] RemoveHighValues ( long [ ] input , int maxDifference ) { var min = input.Min ( ) ; var max = input.Max ( ) ; long [ ] filtered = input ; while ( max - min > maxDifference ) // remove all values wich differ by more than maxDifference ticks { filtered = input.Where ( x = > x < max ) .ToArray ( ) ; max = filtered.Max ( ) ; } return filtered ; } } } | Why are performance measurements differing ? |
C_sharp : 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 OnMessage has a non-standard type . If this event is declared in another CLI language , you may need to access this event using the explicit add_OnMessage and remove_OnMessage methods for the event . If this event is declared in F # , make the type of the event an instantiation of either IDelegateEvent < _ > or IEvent < _ , _ > . The error message is self descriptive , though I aim to create stream from event and not to subscribe on it via add_OnMessage method . <code> 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 ? .Invoke ( message ) ; } let Start ( notifier : Namespace.Notifier ) = notifier.OnMessage | > Observable.subscribe ( fun ms - > ... 0 | Consume C # event from F # |
C_sharp : 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 interest of DRY , I 'd really want to move common functionality to a base class , but then I 'd need to inherit from 2 classes . I can use interfaces ( and infact I am using one right now ) but this solves only half the problem as the method implementations still need to be repeated across several custom classes.What 's the purist way of achieving what I am trying to do ? EDIT : Here 's a generic code sample <code> 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 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 } | Multiple Inheritance in C # : What is the purist way of achieving what I am trying to do ? |
C_sharp : 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 avoid is the torture of going through the possibilities likeDoes anyone know a cuter way to do this ? <code> 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 & & tile.isWallRight & & ! tile.isWallBottom & & ! tile.isWallLeft ) { return WALL_ON_TOP_AND_RIGHT ; } | Nice way to do this in modern OO C-like language ? |
C_sharp : 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 . But I was very surprised when tests showed that method calls of heavy built-in classes is almost two times faster than the calls of my light methods.For example : ~1.5-2 times slower thanin this simple testsWhy ? In all test optimization was enabled . In Debug mode average difference was as I said ~1.7 times . In Release mode ~1.3 times , less but still there.EDITThanks to the advice I found that outside of Visual Studio my code is several times faster or at least as fast as built-in code . So now the question is , why this is happening ? <code> 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 , Int32 offset , Int32 count ) { this.EnsureDataExist ( count ) ; Buffer.BlockCopy ( this.buffer , this.position , buffer , offset , count ) ; this.position += count ; } private void EnsureFreeSpace ( Int32 count ) { if ( this.buffer.Length - this.position < count ) { throw new InvalidOperationException ( ) ; } } private void EnsureDataExist ( Int32 count ) { if ( this.length - this.position < count ) { throw new InvalidOperationException ( ) ; } } memoryStream.Write ( ... ) memoryStream.Read ( ... ) Byte [ ] temp = new byte [ 64 ] ; stopWatch.Restart ( ) ; for ( int i = 0 ; i < 100000 ; i++ ) { ms.Write ( temp , 0 , temp.Length ) ; ms.Position = 0 ; ms.Read ( temp , 0 , temp.Length ) ; ms.Position = 0 ; } stopWatch.Stop ( ) ; Console.WriteLine ( stopWatch.ElapsedMilliseconds ) ; stopWatch.Restart ( ) ; for ( int i = 0 ; i < 100000 ; i++ ) { mb.WriteBytes ( temp , 0 , temp.Length ) ; mb.Position = 0 ; mb.ReadBytes ( temp , 0 , temp.Length ) ; mb.Position = 0 ; } stopWatch.Stop ( ) ; Console.WriteLine ( stopWatch.ElapsedMilliseconds ) ; | Why does c # built-in IO classes is faster than self-made ones ? |
C_sharp : 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 <code> IEnumerable < KeyValuePair < TKey , TValue > > | What do nested generics in C # mean ? |
C_sharp : 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 ? <code> 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_sharp : 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 which will displayed as the local notification.And I have some problems.If I close the application ( using task manager ) then the service will stop , so after change of coordinates nothing happens.What I need do that service work all the time ? Or it 's impossible ? After activation of the local notification it launches NotifyActivity which shows detailed information . There I click buttonDelete - it will close NotifyActivity and start MainActivity . But if after that I switch to the OS screen ( using Back button ) and back ( using task manager ) then instead of 'MainActivity ' will be again displayed 'NotifyActivity'.Why it occurs and how to avoid it ? MainActivityGeolocation servicelocal notificationsExample project here <code> [ 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 ) ; button.Click += delegate { StartService ( new Intent ( this , typeof ( TestService ) ) ) ; button.Text = `` Started '' ; } ; } } [ Service ] public class TestService : Service , ILocationListener { // Start service public override StartCommandResult OnStartCommand ( Intent intent , StartCommandFlags flags , int startId ) { locManager = ( LocationManager ) GetSystemService ( LocationService ) ; locationCriteria = new Criteria ( ) ; locationCriteria.Accuracy = Accuracy.Coarse ; locationCriteria.PowerRequirement = Power.Low ; string locationProvider = locManager.GetBestProvider ( locationCriteria , true ) ; // Preferences.MinTime , for example , 60 ( seconds ) // Preferences.MinDist , for example , 100 ( meters ) locManager.RequestLocationUpdates ( locationProvider , Preferences.MinTime * 1000 , Preferences.MinDist , this ) ; return StartCommandResult.Sticky ; } public void OnLocationChanged ( Location loc ) { // Send coordinates to the server , receive a response , and show local notification var msg = new ReceivedMessage ( counter++ , `` Test Title '' , loc.ToString ( ) ) ; ShowNotification ( msg ) ; } // show local notification void ShowNotification ( ReceivedMessage msg ) { var myContainer = new Bundle ( ) ; myContainer.PutLong ( `` msg_id '' , Convert.ToInt64 ( msg.Id ) ) ; myContainer.PutStringArray ( `` msg_data '' , new [ ] { msg.Title , msg.Text } ) ; var resultIntent = new Intent ( this , typeof ( NotifyActivity ) ) ; resultIntent.PutExtras ( myContainer ) ; TaskStackBuilder stackBuilder = TaskStackBuilder.Create ( this ) ; stackBuilder.AddParentStack ( Java.Lang.Class.FromType ( typeof ( NotifyActivity ) ) ) ; stackBuilder.AddNextIntent ( resultIntent ) ; PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent ( Convert.ToInt32 ( msg.Id ) , PendingIntentFlags.UpdateCurrent ) ; Notification.Builder builder = new Notification.Builder ( this ) .SetDefaults ( NotificationDefaults.Sound | NotificationDefaults.Vibrate ) .SetAutoCancel ( true ) .SetContentIntent ( resultPendingIntent ) .SetContentTitle ( msg.Title ) .SetContentText ( msg.Text ) .SetSmallIcon ( Resource.Drawable.Icon ) ; var nm = ( NotificationManager ) GetSystemService ( NotificationService ) ; nm.Notify ( Convert.ToInt32 ( msg.Id ) , builder.Build ( ) ) ; } } [ Activity ( Label = `` NotifyActivity '' ) ] public class NotifyActivity : Activity { protected override void OnCreate ( Bundle savedInstanceState ) { base.OnCreate ( savedInstanceState ) ; SetContentView ( Resource.Layout.NotifyActivity ) ; var msg_id = Intent.Extras.GetLong ( `` msg_id '' ) ; var msg_data = Intent.Extras.GetStringArray ( `` msg_data '' ) ; FindViewById < TextView > ( Resource.Id.textTitle ) .Text = msg_data [ 0 ] ; FindViewById < TextView > ( Resource.Id.textDescription ) .Text = msg_data [ 1 ] ; FindViewById < Button > ( Resource.Id.buttonDelete ) .Click += delegate { StartActivity ( typeof ( MainActivity ) ) ; Finish ( ) ; } ; } } | Geolocation , service and local notifications |
C_sharp : 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 will display the Html like this : So far I 've tried the following Linq code , but it did n't work <code> 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 > Foo1 < /li > < li > Foo2 < /li > < li > Foo3 < /li > < /ul > < /li > < li > 2 < ul > < li > Foo3 < /li > < li > Foo2 < /li > < li > Foo1 < /li > < /ul > < /li > BarList = FooList.Select ( x = > new Bar ( ) { Id = x.Id , NameList = x.Select ( y = > y . ) } ) .ToList ( ) ; | Convert List < T > into another List < T > that contains another List < T > |
C_sharp : 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 conversions from 'float ' and 'float ' and from 'float ' to 'float'This fixes it : So my question is this : What was that error trying to communicate and what actually went wrong ? Update 1 : Elbow is a GameObject and this error is in Visual Studio <code> 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_sharp : 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 kinda feel its ugly code to do this everytime I come across a similar situation . Maybe it -is- the way to go , but I want to make sure.Is there a better or commonly accepted way to do this ? I 'm using the XNA-Framework , which uses Vector2 's . <code> 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 , WorldPosition.Y % Level.Height ) ; } } } var levelPosition = Character.LevelPosition ; | 'new ' keyword in getter > performance hit ? |
C_sharp : 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 belowAnd I have implementedHow do I make sure by using distinct that I am keeping idn6 and removing idn1 and idn4 ? <code> 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 = new Identifier { Name = `` X '' } ; Identifier idn2 = new Identifier { Name = `` Y '' } ; Identifier idn3 = new Identifier { Name = `` Z '' } ; Identifier idn4 = new Identifier { Name = `` X '' } ; Identifier idn5 = new Identifier { Name = `` P '' } ; Identifier idn6 = new Identifier { Name = `` X '' } ; List < Identifier > list = new List < Identifier > ( ) ; list.Add ( idn1 ) ; list.Add ( idn2 ) ; list.Add ( idn3 ) ; list.Add ( idn4 ) ; list.Add ( idn5 ) ; list.Add ( idn6 ) ; var res = list.Distinct ( new DistinctIdentifierComparer ( ) ) ; | Removing Duplicates from bottom of Generic List |
C_sharp : 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 ? <code> public class Buffer { public String get ( ) & public async put ( String s ) { return s ; } } | Polyphonic C # methods separated by ampersand ? |
C_sharp : 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 passing down TId and TId2 . Is there a simpler way to do this , besides just removing the constraint ? <code> 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_sharp : 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 beizer curve control points generation and i just ca n't understand how to fix them.I want them to be drawn the same way no matter what 's the direction of the edge.How can i achieve this as in Pic1 ? How can i achieve this as in Pic2 ? Like here : https : //bl.ocks.org/mbostock/4063550Thank you ! Code : UPDATE 1 : I 've got the angle between previous vertex and source in radians using the following formula : Math.Atan2 ( prev.Y - source.Y , source.X - prev.X ) ; But still i get the edges like in Pic.4.UPDATE 2The prev vertex pos for branchAngle calculation is inaccurate so i decided to take an average angle between all edges in a branch as the branchAngle . This approach fails when edges from one brach are around the 180 deg mark and branch can have edge angles like 175 , 176.. -176 ! ! I use this code to make them all positive : But now the angles can be 350 , 359.. 2 ! ! ! Quite difficult to calc an average : ) Can you please advice me how i can work this around ? Pic1Pic2Pic3Pic4 <code> //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.EvenOdd } ; using ( var ctx = geometry.Open ( ) ) { ctx.BeginFigure ( START_POINT , false /* is filled */ , false /* is closed */ ) ; ctx.BezierTo ( pts [ 0 ] , pts [ 1 ] , END_POINT , true , false ) ; } geometry.Freeze ( ) ; //draw itdc.DrawGeometry ( DrawingBrush , DrawingPen , geometry ) ; var angle = Math.Atan2 ( point1.Y - point2.Y , point1.X - point2.X ) ; while ( angle < 0d ) angle += Math.PI*2 ; | Radial tree graph layout : fix beizer curves |
C_sharp : 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 schema , to which I do n't have access , and now their XML is adding in a final < node > tag to the end which does not contain the decedent elements I am looking for , and so , my parsing breaks on this last tag and I throw an exception . Here is an example : I need to know if there is a way to ignore this final tag ( its always at the end of the document ) even though it has the same name as all the other `` node '' tags I am looking for . I do have a try catch around this block of code but it doesnt return the list of good reviews out if it sees this error.Thanks guys . <code> 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 > 12345657890123 < /ISBN > < Review > This is a nice and silly book < /Review > < /node > < node > < created > 01-01-2011 < /created > < ISBN > 1236245234554 < /ISBN > < Review > This is a stupid book < /Review > < /node > < node > < created > 12-06-1942 < /created > < ISBN > 1234543234577 < /ISBN > < Review > This is a old , naughty book < /Review > < /node > < /reviews > < reviews > < node > < created > 01-01-1900 < /created > < ISBN > 12345657890123 < /ISBN > < Review > This is a nice and silly book < /Review > < /node > < node > < created > 01-01-2011 < /created > < ISBN > 1236245234554 < /ISBN > < Review > This is a stupid book < /Review > < /node > < node > < created > 12-06-1942 < /created > < ISBN > 1234543234577 < /ISBN > < Review > This is a old , naughty book < /Review > < /node > < node > < count > 4656 < /count > < /node > < /reviews > | How to ignore a specific with a LINQ where clause ? |
C_sharp : 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 one compiles and the other does not ? <code> 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_sharp : 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 , the code our programmer used is : I do n't see any advantage here for using a generic instead of just using a parameter of the IDrawing type . I presume there must be some case where its very appropriate . I was curious to see if I was missing something . <code> 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_sharp : 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 = new Application ( ) ; // Application is an interfaceWhat am I missing here ? <code> interface IFood { string Color { get ; set ; } } class Apple : IFood { public string Color { get ; set ; } } | How is it possible to initialize an interface ? |
C_sharp : 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 further into a system which only accepts a single instance of Class D and dynamically binds these methods to other functions.To be clear , this is not inheritance I 'm looking for . I 'm literally stating that methods with different names need to be stuffed into one class . The system I pass it into understands these naming conventions and dynamically binds them ( it 's a black box to me ) . I am going down the path of extracting the methods from A , B , and C , dynamically combining them with the source of Class D in memory and compiling them into a new Class D and then creating an instance of D and passing it forward.Is there a way to extract the MethodInfos from class A , B and C and somehow directly attach them to Class D ? If so how ? <code> 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_C_DoAnything ( ) { } } | Dynamically Compose a Class in C # |
C_sharp : 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 <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 , top ) ; } } } | C # Store values in static dictionary |
C_sharp : 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 $ and : [ closed : { $ eq : true } , { updatedon : { $ gt : new ISODate ( `` 2017-10-20T20:15:31Z '' ) } } ] But how can you reference the parent element $ .updatedon for the comparison ? In plain mongodb shell query language it would aleady be of help.But I am actually accessing it using c # driver , so my query filter is like this : How can I replace DateTime.Now.AddDays ( -15 ) with a reference to the document root element updatedon ? <code> { `` _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 '' : `` PIR '' , `` cai '' : `` 2259700 '' } ] , `` updatedon '' : ISODate ( `` 2017-05-17T13:51:24.252Z '' ) } , { `` cartid '' : 422907 , `` status '' : `` New '' , `` cart_created '' : ISODate ( `` 2017-10-23T08:57:06.846Z '' ) , `` closed '' : false , `` items '' : [ { `` brandid '' : `` PIR '' , `` cai '' : `` IrHlNdGtLfBoTlKsJaRySnM195U '' } ] , `` updatedon '' : ISODate ( `` 2017-10-23T09:46:08.579Z '' ) } ] , `` createdon '' : ISODate ( `` 2016-11-08T10:29:55.120Z '' ) , `` updatedon '' : ISODate ( `` 2017-10-23T09:46:29.486Z '' ) } FilterDefinition < _visitorData > filter ; filter = Builders < _visitorData > .Filter .Gte ( f = > f.updatedon , DateTime.Now.AddDays ( -15 ) ) ; filter = filter & ( Builders < _visitorData > .Filter .Exists ( f = > f.carts , false ) | ! Builders < _visitorData > .Filter.ElemMatch ( f = > f.carts , c = > c.closed & & c.updatedon > DateTime.Now.AddDays ( -15 ) ) ) ; | Find if an element in array has value equal to parent element value |
C_sharp : 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 other than this ? <code> 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_sharp : Using Linq on collections , which one is best for finding that collection is not empty ? and <code> HasChild = Childs.GetEnumerator ( ) .MoveNext ( ) ? true : false ; HasChild = Childs.Any ( ) ? true : false ; | Linq Any ( ) vs MoveNext ( ) |
C_sharp : 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 Without Public Constructors blog post and converting it to be declarative . It is very similar to my original query but I ca n't get it to work . Please note that the code given is not actually production code and that this is a learning exercise . Now if it helps , I 've got the imperative code up on GitHub and the code in question is reproduced below : This is the code similar to the one given in this post.Hence , my question is what should I know/read in order to convert this snippet of imperative code to be declarative . <code> [ 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_sharp : 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 completed '' . This is a proper warning , because it often indicates a flaw in your code . In case you actually want this behavior , then you can solve it by using the following code : Assigning the value to _ is a relative new feature to indicate that the value is ignored intentionally.This code does n't raise CS4014 : Of course , I could rewrite all my methods to use the async/await method , but this results in more code that runs less efficient ( due to the state machine generated by the async keyword ) . Maybe I will never forget about it , but my coworkers might and then I wo n't get a trigger ( or I call a third-party library that does n't use async ) .There is also a difference in the warning about the returned Task usage . Does anyone know why this warning is not generated for methods that return a Task that do n't use the async keyword ? <code> 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 ( ) ; // CS4014 is not shown ! | Why is CS4014 not shown for all functions that return a task ? |
C_sharp : 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 learn something here . <code> // -- 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 capture in match.Captures ) { string name = capture.Value.Replace ( prefix , `` '' , StringComparison.CurrentCultureIgnoreCase ) .Replace ( suffix , `` '' , StringComparison.CurrentCultureIgnoreCase ) ; // -- point of difference string value = nvp [ name ] ; render = render.Replace ( capture.Value , value ) ; } } return render ; } private string RenderSessionType ( string render , HttpContext httpContext , string prefix , string regexWild , string suffix ) { string regex = prefix + regexWild + suffix ; MatchCollection matches = Regex.Matches ( render , regex ) ; foreach ( Match match in matches ) { foreach ( Capture capture in match.Captures ) { string name = capture.Value.Replace ( prefix , `` '' , StringComparison.CurrentCultureIgnoreCase ) .Replace ( suffix , `` '' , StringComparison.CurrentCultureIgnoreCase ) ; // -- point of difference object session = httpContext.Session [ name ] ; string value = ( session ! = null ? session.ToString ( ) : `` '' ) ; render = render.Replace ( capture.Value , value ) ; } } return render ; } private string RenderCookieType ( string render , HttpContext httpContext , string prefix , string regexWild , string suffix ) { string regex = prefix + regexWild + suffix ; MatchCollection matches = Regex.Matches ( render , regex ) ; foreach ( Match match in matches ) { foreach ( Capture capture in match.Captures ) { string name = capture.Value.Replace ( prefix , `` '' , StringComparison.CurrentCultureIgnoreCase ) .Replace ( suffix , `` '' , StringComparison.CurrentCultureIgnoreCase ) ; // -- point of difference HttpCookie cookie = httpContext.Request.Cookies [ name ] ; string value = ( cookie ! = null ? cookie.Value : `` '' ) ; render = render.Replace ( capture.Value , value ) ; } } return render ; } | How to refactor these functions which have one line difference |
C_sharp : 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 <code> //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_sharp : 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 ( ExpireTimeSpan ) is set to TimeSpan.FromMinutes ( 30 ) . I found a similar question on SO whose answer indicated that TimeSpan.FromMinutes ( 30 ) should be sufficient to prevent ASP.Net Identity from reaching out to the DB on every request.What am I missing here ? Startup.Auth.csQueries being executed on each request ( standard ASP.Net Identity queries ) EDITI did make one change that I forgot to mention . We moved our Identity-related tables to a SQL DB . Changes below : <code> 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 ) ; app.CreatePerOwinContext < ApplicationSignInManager > ( ApplicationSignInManager.Create ) ; // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication ( new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie , LoginPath = new PathString ( `` /Account/Login '' ) , Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in . // This is a security feature which is used when you change a password or add an external login to your account . OnValidateIdentity = SecurityStampValidator .OnValidateIdentity < ApplicationUserManager , ApplicationUser > ( validateInterval : TimeSpan.FromMinutes ( 30 ) , regenerateIdentity : ( manager , user ) = > user.GenerateUserIdentityAsync ( manager ) ) , } SlidingExpiration = true , ExpireTimeSpan = TimeSpan.FromMinutes ( 30 ) } ) ; app.UseExternalSignInCookie ( DefaultAuthenticationTypes.ExternalCookie ) ; // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process . app.UseTwoFactorSignInCookie ( DefaultAuthenticationTypes.TwoFactorCookie , TimeSpan.FromMinutes ( 5 ) ) ; // Enables the application to remember the second login verification factor such as phone or email . // Once you check this option , your second step of verification during the login process will be remembered on the device where you logged in from . // This is similar to the RememberMe option when you log in . app.UseTwoFactorRememberBrowserCookie ( DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie ) ; } } exec sp_executesql N'SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Email ] AS [ Email ] , [ Extent1 ] . [ EmailConfirmed ] AS [ EmailConfirmed ] , [ Extent1 ] . [ PasswordHash ] AS [ PasswordHash ] , [ Extent1 ] . [ SecurityStamp ] AS [ SecurityStamp ] , [ Extent1 ] . [ PhoneNumber ] AS [ PhoneNumber ] , [ Extent1 ] . [ PhoneNumberConfirmed ] AS [ PhoneNumberConfirmed ] , [ Extent1 ] . [ TwoFactorEnabled ] AS [ TwoFactorEnabled ] , [ Extent1 ] . [ LockoutEndDateUtc ] AS [ LockoutEndDateUtc ] , [ Extent1 ] . [ LockoutEnabled ] AS [ LockoutEnabled ] , [ Extent1 ] . [ AccessFailedCount ] AS [ AccessFailedCount ] , [ Extent1 ] . [ UserName ] AS [ UserName ] FROM [ dbo ] . [ AspNetUsers ] AS [ Extent1 ] WHERE [ Extent1 ] . [ Id ] = @ p0 ' , N ' @ p0 nvarchar ( 4000 ) ' , @ p0=N ' [ ID ] 'exec sp_executesql N'SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ UserId ] AS [ UserId ] , [ Extent1 ] . [ ClaimType ] AS [ ClaimType ] , [ Extent1 ] . [ ClaimValue ] AS [ ClaimValue ] FROM [ dbo ] . [ AspNetUserClaims ] AS [ Extent1 ] WHERE [ Extent1 ] . [ UserId ] = @ p__linq__0 ' , N ' @ p__linq__0 nvarchar ( 4000 ) ' , @ p__linq__0=N ' [ ID ] 'exec sp_executesql N'SELECT [ Extent1 ] . [ LoginProvider ] AS [ LoginProvider ] , [ Extent1 ] . [ ProviderKey ] AS [ ProviderKey ] , [ Extent1 ] . [ UserId ] AS [ UserId ] FROM [ dbo ] . [ AspNetUserLogins ] AS [ Extent1 ] WHERE [ Extent1 ] . [ UserId ] = @ p__linq__0 ' , N ' @ p__linq__0 nvarchar ( 4000 ) ' , @ p__linq__0=N ' [ ID ] 'exec sp_executesql N'SELECT [ Extent1 ] . [ UserId ] AS [ UserId ] , [ Extent1 ] . [ RoleId ] AS [ RoleId ] FROM [ dbo ] . [ AspNetUserRoles ] AS [ Extent1 ] WHERE [ Extent1 ] . [ UserId ] = @ p__linq__0 ' , N ' @ p__linq__0 nvarchar ( 4000 ) ' , @ p__linq__0=N ' [ ID ] ' public class ApplicationDbContext : IdentityDbContext < ApplicationUser > { // Changed connection string name public ApplicationDbContext ( ) : base ( `` MaestroConnection '' , throwIfV1Schema : false ) { } public static ApplicationDbContext Create ( ) { return new ApplicationDbContext ( ) ; } } | ASP.Net Identity running multiple queries on every request |
C_sharp : 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 gap in F # compilation / CLR ? <code> 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 continue . . . | F # / .NET null instance oddity |
C_sharp : 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 ? <code> 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_sharp : 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 type of the objects . Something like this : As you see , the code performs many checks for type of the object and casts . For collections with many elements performance of the code is not that great.What would you recommend to speed up run time type checks in my case ? <code> 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_sharp : 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 ( sudo raspi-config ) to `` en-GB.UTF-8 '' all functions work as expected . Anyone knows how to solve this as a German user I would like to use German system settings . <code> 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_sharp : 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 dataGridView . I have tried some SQL commands I found online , but it looks like commands in C # might differ from normal SQL queries . Suppose table1 has these fields : ISBN , color , size and table2 has the fields ISBN , weight . I need a way to display ISBN , color , size , weight in my datagrid view . I think I will have to somehow do this with an adapter . I am able to connect and do queries on the tables individually , and show that data in my datagridview , but I ca n't figure out how to mix data from two separate tables.If you have a good resource I can read about this I 'd love to have it , my google-fu is failing me . Here 's an example of something I can do now with my database : So , essentially , I 'd like to do what I 've done above , but I want to include the data from a different table too . The other table also has a key field ISBN , and it contains values of ISBN that match the first table . <code> 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= '' + @ '' C : \Users\Geoff\Documents\cs 351\Database1.accdb '' + `` ; Persist Security Info=False ; '' ; OleDbConnection conn = new OleDbConnection ( connectionString ) ; string query = `` select * from Book where ISBN = 12345 '' ; OleDbCommand com = conn.CreateCommand ( ) ; com.CommandText = query ; OleDbDataAdapter adapter = new OleDbDataAdapter ( com ) ; DataSet data = new DataSet ( ) ; conn.Open ( ) ; adapter.Fill ( data ) ; conn.Close ( ) ; dataGridView1.DataSource = data.Tables [ 0 ] ; } | Need some help working with databases in C # |
C_sharp : 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 # I 've never known calling a method on a null reference in any context to be `` ok '' . Is this a special case in the context of a using clause ? I can understand this being OK ( did n't know it was , but apparently it is ? ) : but calling a method on a null reference seems like it should throw an exception regardless of whether it 's in a using clause . Can someone please explain how such a construct is translated behind the scenes , so I can understand why it is OK to do this ? <code> 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_sharp : 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 > . But do you see any other problems with using < in D > in my class/interface-hierarchy ? I 'm a bit doubtful because of ISelector which implements ITransform < IValue > and ITransform < ISelection > . Might contravariance cause any problems here because IValue inherits ISelection ? EDITJust to let you know : I 'm currently using Silverlight 4 but I think this is the general C # behaviour . <code> 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 { ... } class Editor : IEditor { ... } // implements ITransform < IValue > class Selector : Editor , ISelector { ... } // implements ITransform < ISelection > Value v = new Value ( ) ; Selector s1 = new Selector ( ) ; ISelector s2 = s1 ; s1.Transform ( v ) ; // resolves to ITransform < ISelection > -- > WHY ? s2.Transform ( v ) ; // resolves to ITransform < IValue > -- > OK | Method overload resolution and generic/contravariant interfaces in C # |
C_sharp : 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 an example solution for this which can be found here.The same is a list of radiobuttons : It 's not included in MVC ( at the moment ) . There is another good solution which can be found here and with this solution I would be able to write So there are solutions available but not structured in a library ( respectively I did n't found one ) and I do n't want to copy and paste this solutions together piece by piece ( because I can not update it easily with NuGet e.g . ) , a whole library would be better but I could not find any.Please help : ) <code> @ 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_sharp : 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 : PostScalar Properties : PostID , PostDateNavigation Property : PostTagsPostTagScalar Properties : PostTagID , PostID , TagIDNavigation Properties : Post , TagTagScalar Properties : TagIDNavigation Property : PostTagsThis is the query I 'm currently using which works well : This is the ( probably incorrect ) start of the extension method I 'm struggling to create : And the ideal simplification of the original query : Any help in writing this extension method , or any other more efficient way to perform this query , will be greatly appreciated . <code> 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 IEnumerable < TSource > collection , Func < IEnumerable < TSource > , IEnumerable < TResult > > selector ) { return selector ( collection ) ; } public IEnumerable < Post > GetPostsByTags ( IEnumerable < Tag > tags ) { return from p in context.Posts where p.PostTags.SelectRange ( x = > ? ) & & p.PostDate ! = null orderby p.PostDate descending select p ; } | Writing an extension method to help with querying many-to-many relationships |
C_sharp : 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 ? <code> drawBoxdrawSpherepaintImage | How do F # types transfer over to C # ? |
C_sharp : 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 explanation for this rule ? ( I had guessed that the compiler would choose recursion in both cases . ) Here is the program in its entirety : <code> 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 ) { Bar ( baz ) ; } void Foo < T > ( T baz ) { Console.WriteLine ( `` Foo < T > called '' ) ; } public override void Foo ( Baz baz ) { Foo ( baz ) ; } } class Program { static void Main ( string [ ] args ) { var child = new Child ( ) ; child.Foo ( null ) ; child.Bar ( null ) ; Console.ReadLine ( ) ; } } } | Why is a generic method chosen when a non-generic exists ? |
C_sharp : 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 . <code> using ( SqlConnection sqlConnection = new SqlConnection ( connectionString ) ) { code ... } | C # : Initializing a variable with `` using '' |
C_sharp : 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 notifications ( signalr ) .For faster response time , my client keeps a sort of database in memory ( since the amount of data is not that big , less than 500 records ) . I keep an array of students and for each one of them also keep array of courses : And in that object I keep track of all the students and their courses in the client side.In my application I have the option to remove multiple courses from the entire system . However when doing such thing , when the action is successfully finished on server-side , the processing in the client side becomes heavy when there are many students . That is because I need to iterate through all the removed courses and for each one of them iterate through the entire students array to locate and remove those courses from the students array . ( Or iterate the removed courses first and within iterate through the students ) - both are heavy and take a while.Is there a different better design for this ? Should I approach this in a different way maybe ? <code> 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_sharp : 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 ? <code> 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_sharp : 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 conforms to two interfaces.For example I want to have those two interfaces : IValidateISaveableI do not want to have an extra interface combining the methods those two provide separately.For example there could be a manager class that wants to save objects but only if they 're valid : So if I got a simple class like SimpleData : IValidate , ISaveable objects of this class could be passed into the method but another object whose class only implements ISaveable can not be passed in.In C # I would simply define the save method as a generic method : How to do this in abap-oo , if possible ? <code> 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_sharp : 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 `` umbrella '' types - I want to exchange the `` Frobbler '' with something descriptive . `` Collection '' , `` List '' and `` Set '' are n't good enough , in the sense that it 's not a collection/list/set where elements can be enumerated , added or removed . `` Manager '' is out , because there 's no management being done - the factory and configurations handle that . `` Aggregator '' makes it sound like picked straight from the GoF book ( although I do n't think they would break `` the law of demeter '' - that 's out of topic here ) .Please , enlighten me , what 's a good naming scheme for my `` umbrella '' types ? Edit : As xtofl pointed out in a comment , there 's actually more semantics to this than I first exposed above . If I instead do the following , I think my need is clearer : In fact , I 've identified my problem in the real-life addition above as a design flaw , not a naming problem , the smell of which several people has pointed out below . <code> 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 ; } Boolean CanTaper { get ; } void Taper ( ) ; } //// Used for rendering a simple marked-up text in// a restricted area.//public interface ITaperableFonts { ITaperableFont Biggest { get ; } ITaperableFont Big { get ; } ITaperableFont Normal { get ; } ITaperableFont Small { get ; } ITaperableFont Smallest { get ; } } | How should I name an `` umbrella '' type sanely ? |
C_sharp : 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 problem is that the property starts with a capitol , which makes it look a bit weird imho when using it in this manner . I did n't mind that properties start with a capitol before because they would always be behind a `` dot '' . Now I have found myself prefixing all the properties I use internally with this. , to sooth my feeling . My dilemma is that before I was always a bit against prefixing all usage of internal members with this. , unless `` necessary '' ( like in a setter or constructor ) . So I am kind of looking for a second opinion on this . Is there a standard good way to do this ? Should I just stop complaining ( I have the tendency to be a `` ant humper '' ( Dutch expression ) ) ? Before : After : UpdateIt seems that opinions vary , although more people are in favor of prefixing with this.. Before the auto properties I was always pretty much against prefixing with this . instead of in constructors and in setters ( as I mentioned before ) . But now I just do n't know anymore.Additional note : The fact that it is also common to name the property the same as the class ( public Bar Bar { get ; private set ; } ) also makes me tend towards prefixing . Every time I type Bar.DoMethod ( ) , I feel like it looks like a static method . Even though VS would color Bar if it was a static method and you can not have a static and instance method with the same signature . When it is colored it is clear that it is a static method , but when it is not colored it is not 100 % clear that it is not a static method . You could for example just be missing a using statement , but also just because I am not used to having to link the not being colored to whether it 's a static call or not . Before I 'd instantly see it by the capitalization of the first letter in case of a member or by the `` dot '' in case of a property ( E.g . the `` dot '' after foo in ( Foo ) foo.Bar.DoMethod ( ) ) . ( Difficult to choose an `` Accepted answer '' at the moment ) <code> 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 ( ) { if ( this.Bar ! = null ) { this.Bar.DoMethod ( ) ; } // or if ( Bar ! = null ) { Bar.DoMethod ( ) ; } } } | Is always prefixing ( auto ) properties with the this-keyword considered a good practice ? |
C_sharp : 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 } | { filedescription } | { filehttppath } | { previewimagepath } | { length } | { source } when I use short test text to put it into a text box it displays fine in the text box.IE : a string like test|test|test|test|test|testbut if I put in a real string that I would actually be using for the program to DL files the only way I get the string to display is to iterate through it with a for or foreach loop . If I try to access the data with the index I get an index missing error . ( IE array [ 0 ] ) So this is the code that gets the array to display : And then this is the code that gives an index missing error : Any help is this is apreciated I do n't see why I can access they data through a for loop but not directly it just does n't make any sense to me.Also , here is the code that generates the array : <code> 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.NewLine + @ '' \\newline '' + Environment.NewLine ; } } } public Form2 ( string [ ] [ ] textList , string path ) { InitializeComponent ( ) ; textBox1.Text = textBox1.Text + path + Environment.NewLine ; WebClient downloader = new WebClient ( ) ; foreach ( string [ ] i in textList ) { textBox1.Text = textBox1.Text + i [ 0 ] + Environment.NewLine ; textBox1.Text = textBox1.Text + i [ 1 ] + Environment.NewLine ; textBox1.Text = textBox1.Text + i [ 2 ] + Environment.NewLine ; textBox1.Text = textBox1.Text + i [ 3 ] + Environment.NewLine ; textBox1.Text = textBox1.Text + i [ 4 ] + Environment.NewLine ; textBox1.Text = textBox1.Text + i [ 5 ] + Environment.NewLine ; } } public String [ ] [ ] finalList ( string [ ] FileList ) { String [ ] [ ] FinalArray = new String [ FileList.Length ] [ ] ; for ( int i = 0 ; i < FinalArray.Length ; i++ ) { string [ ] fileStuff = FileList [ i ] .Split ( new char [ ] { '| ' } ) ; FinalArray [ i ] = fileStuff ; } return FinalArray ; } | Can only display array by iterating through a for loop |
C_sharp : 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 currentActivity does not even exist in the superclass , but if I understand Firebase Cloud Messaging correctly , then it should still exist in the super class . I have also tried replacing currentActivity with things such as UnityPlayerActivity , MessagingUnityPlayerActivity , mypackage , and com.mypackage - but same error . Referencing com.unity3d.player.UnityPlayer in my AndroidJavaClass while using Firebase Cloud Messaging has problems of its own : https : //gamedev.stackexchange.com/questions/183734/how-can-i-use-an-inherited-activity-in-cIn case it is relevant , here is my AndroidManifest.xml : How can I get my current activity while using Firebase Cloud Messaging ? Why does the code not work as shown ? <code> 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 < AndroidJavaObject > ( `` currentActivity '' ) ; 08-01 15:51:31.838 20323 20375 E Unity : AndroidJavaException : java.lang.NoSuchFieldError : no `` Ljava/lang/Object ; '' field `` currentActivity '' in class `` Lcom/google/firebase/MessagingUnityPlayerActivity ; '' or its superclasses08-01 15:51:31.838 20323 20375 E Unity : java.lang.NoSuchFieldError : no `` Ljava/lang/Object ; '' field `` currentActivity '' in class `` Lcom/google/firebase/MessagingUnityPlayerActivity ; '' or its superclasses08-01 15:51:31.838 20323 20375 E Unity : at com.unity3d.player.UnityPlayer.nativeRender ( Native Method ) 08-01 15:51:31.838 20323 20375 E Unity : at com.unity3d.player.UnityPlayer.access $ 300 ( Unknown Source:0 ) 08-01 15:51:31.838 20323 20375 E Unity : at com.unity3d.player.UnityPlayer $ e $ 1.handleMessage ( Unknown Source:83 ) 08-01 15:51:31.838 20323 20375 E Unity : at android.os.Handler.dispatchMessage ( Handler.java:103 ) 08-01 15:51:31.838 20323 20375 E Unity : at android.os.Looper.loop ( Looper.java:214 ) 08-01 15:51:31.838 20323 20375 E Unity : at com.unity3d.player.UnityPlayer $ e.run ( Unknown Source:20 ) 08-01 15:51:31.838 20323 20375 E Unity : at UnityEngine.AndroidJNISafe.CheckException ( ) [ 0x00000 ] in < 00000000000000000000000000000000 > :008-01 15:51:31.838 20323 20375 E Unity : at UnityEngine.AndroidJNISafe.GetStaticFieldID ( System.IntPtr clazz , System.String name , System.String sig ) [ 0x00000 ] in < 00000000000000000000000000000000 > :008-01 15:51:31.838 20323 20375 E Unity : at UnityEngine._AndroidJNIHelper.GetFieldID ( System.IntPtr jc < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : tools= '' http : //schemas.android.com/tools '' package= '' com.mypackage '' android : versionCode= '' 1 '' android : versionName= '' 1.0 '' > < application android : label= '' @ string/app_name '' android : icon= '' @ drawable/app_icon '' > < ! -- The MessagingUnityPlayerActivity is a class that extends UnityPlayerActivity to work around a known issue when receiving notification data payloads in the background . -- > < meta-data android : name= '' com.google.firebase.messaging.default_notification_icon '' android : resource= '' @ drawable/notification_icon '' / > < activity android : name= '' com.google.firebase.MessagingUnityPlayerActivity '' android : configChanges= '' fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < meta-data android : name= '' unityplayer.UnityActivity '' android : value= '' true '' / > < /activity > < service android : name= '' com.google.firebase.messaging.MessageForwardingService '' android : exported= '' false '' / > < /application > < /manifest > | How can I get the current activity while using Firebase Cloud Messaging in Unity ? |
C_sharp : 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 that IActionFlow < IUserRepository > instance so I ca n't dispose it.What are the disadvantages of having the instance dipose itself on the Execute ( ) method ? Something like : The code seems to compile just fine but I 'm looking for strange behaviors or bugs that may rise because of this . Is it bad practice at all ? <code> 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_sharp : 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 : ) <code> 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_sharp : 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 <code> 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_sharp : 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 of the lines together to get the third DGV that looks like this : Now , as you may expect there could be possible lines that do not match properly and will not combine the two sets of lines from the two files . If this is the case it will only input the information from the first file and not the second.So some sample data might look like this : SOThe third row ( not including the titles of the columns ) has blank cells in it . When the user changes the cell data in those blank spots , I would like to add it to a text document that already contains similar data . So , if the user added 456 someITEM 4 1 1 UNI2 9MM 10MS to the DataGridView lines that were blank , I want to add that to the end of the a file that already contains data . I want to only add the line if all of the column cells are filled in for each row . The output can just be space delimited.Can anyone help me with this ? <code> 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 1255 1255 ITEM 2 1 1 UNI2 5MM 1MSJ18 9845 11 4 270 456C127 1111 05 1 270 5555 5555 ITEM2 3 1 1 UNI 8MM 0.1MS | Saving DataGridView |
C_sharp : 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 ? Then , if I let the code continue , it hits the first breakpoint , and now I 'm wondering why is it trying to convert a string ( the value is null despite the fact that I 've explicitly cast null into a MyValue ) into a MyValue ? Strings should n't be involved when using a statement like if ( first == ( MyValue ) null ) , so what is actually happening here ? <code> 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 ] ) ; } public static implicit operator string ( MyValue fromInput ) { // second breakpoint here . return fromInput.ToString ( ) ; } public override string ToString ( ) { return FirstPart + `` @ '' + SecondPart ; } public MyValue ( string firstPart , string secondPart ) : this ( ) { this.FirstPart = firstPart ; this.SecondPart = secondPart ; } } var first = new MyValue ( `` first '' , `` second '' ) ; if ( first == ( MyValue ) null ) throw new InvalidOperationException ( ) ; | Strange conversion operator behavior |
C_sharp : 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 time ) ? <code> var defaultMyTypeVal = default ( MyType ) ; public object GetDefaultValueForType ( Type type ) { ... . } | C # : How to find the default value for a run-time Type ? |
C_sharp : 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 ? <code> 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 ] [ MaxLength ( 32 , ErrorMessage = `` Password can only contain { 0 } characters '' ) ] [ MinLength ( 8 , ErrorMessage = `` Password must be at least { 0 } characters '' ) ] public string UsrPassword { get ; set ; } } public class UsrDetails { [ ForeignKey ( `` UsrID '' ) ] [ Required ] public virtual Usr Usr { get ; set ; } [ Required ] [ MaxLength ( 40 , ErrorMessage = `` Name can only contain { 0 } characters '' ) ] public string UsrName { get ; set ; } [ Required ] [ MaxLength ( 40 , ErrorMessage = `` Surname can only contain { 0 } characters '' ) ] public string UsrSurname { get ; set ; } [ Required ] [ MaxLength ( 20 , ErrorMessage = `` Country can only contain { 0 } characters '' ) ] public string UsrCountry { get ; set ; } [ Required ] [ MaxLength ( 20 , ErrorMessage = `` City can only contain { 0 } characters '' ) ] public string UsrCity { get ; set ; } [ Required ] [ MaxLength ( 40 , ErrorMessage = `` Street can only contain { 0 } characters '' ) ] public string UsrStreet { get ; set ; } [ Required ] public int UsrNum { get ; set ; } [ Required ] public int UsrPostalCode { get ; set ; } } | Error with primary key in one-to-one relationship using Entity Framework |
C_sharp : 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 ? <code> var query = customers.Where ( c = > c.Name == `` Test '' ) ; | Analyzing a Linq expression |
C_sharp : 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 I create a Hierarchical feature histogram ) , and easier to re-factor ( if I happen to decide that the name Histogram is unfortunate ) . But the compiler wo n't do it . Why ? Any way to circumvent this ? Creating new classes seems a little bit overkill ... <code> 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_sharp : 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 ReadOnly . The error is not triggered if the column is simply aliased with no function applied.The error is not triggered if the select is moved to a table-function , then the proc selects from that function.The error ( obviously ) does n't occur when setting the column property to ReadOnly in C # .The Question : Is there any way to alter a procedure so that an aliased column with a function applied is not ReadOnly ? I am looking for an alternate to changing the C # or creating a function to do what the proc already does.The C # : The SQL : <code> 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 ( `` + '' , `` % 20 '' ) ; //Testing Function Applied - Fail //dr [ `` DocumentPath '' ] = `` file : /// '' + Server.UrlEncode ( dr [ `` DocumentPath '' ] .ToString ( ) ) .Replace ( `` + '' , `` % 20 '' ) ; } GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [ dbo ] . [ usp_ActiveDocs_RetrieveMerged ] @ KeyID INTAS BEGIN -- Testing Select From Function -- SELECT * FROM dbo.ufn_ActiveDocs_RetrieveMerged ( @ KeyID ) -- PassSELECT AD.ADMergeLogID , AD.TemplateName , CONVERT ( NVARCHAR ( 10 ) , AD.InitiatedOn , 101 ) [ CreatedOn ] , ( SELECT fn.UserName FROM dbo.ufn_User_GetFullName ( AD.InitiatedBy ) fn ) [ CreatedBy ] , AD.DocumentName , AD.DocumentPath [ DocumentPathAlias ] -- Pass -- , REPLACE ( AD.DocumentPath , '\\ ' , '\ ' ) [ DocumentPath ] -- Fail -- , dbo.udf_VerifyPath ( AD.DocumentPath ) [ DocumentPath ] -- FailFROM dbo.ActiveDocsMergeLog ADWHERE AD.DocumentPath ! = 'DocumentPath not found . 'AND AD.KeyID = @ KeyIDEND | TSQL Functions used in stored procedure force column to readonly |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.