lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I need to develop a fairly simple algorithm , but am kindof confused as how to best write a test for it.General description : User needs to be able to delete a Plan . Plan has Tasks associated with it , these need to be deleted as well ( as long as they 're not already done ) .Pseudo-code as how the algorithm should be...
PlanController.DeletePlan ( plan ) = > PlanDbRepository.DeletePlan ( ) ForEach Task t in plan.Tasks If t.Status = Status.Open Then TaskDbRepository.DeleteTask ( t ) End If End ForEach
How would I go about unit testing this ?
C#
In a heavily multi-threaded scenario , I have problems with a particular EF query . It 's generally cheap and fast : This compiles into a very reasonable SQL query : The query , in general , has optimal query plan , uses the right indices and returns in tens of milliseconds which is completely acceptable.However , when...
Context.MyEntity .Any ( se = > se.SameEntity.Field == someValue & & se.AnotherEntity.Field == anotherValue & & se.SimpleField == simpleValue // few more simple predicates with fields on the main entity ) ; SELECT CASE WHEN ( EXISTS ( SELECT 1 AS [ C1 ] FROM ( SELECT [ Extent1 ] . [ Field1 ] AS [ Field1 ] FROM [ dbo ] ....
Curious slowness of EF vs SQL
C#
I have the following method in my custom WebTest : On my GetRequestEnumerator I am calling the method like this : Note : The original code is more complicated than this , but it is irrelevant.This is working fine when running the load test on my local machine : You can see that each request is being identified by the v...
private WebTestRequest CreateRequest ( CommandInput command ) { WebTestRequest request = new WebTestRequest ( URL ) ; request.ReportingName = command.CommandName ; request.Method = command.HttpMethod ; // ... return request ; } public override IEnumerable < WebTestRequest > GetRequestEnumerator ( ) { return new Command...
WebTestRequest.ReportingName is ignored when using VS Team Services
C#
They use StructureMap for IoC where I am currently working.I have an application class that will implement multiple properties of the same interface ... and I need to bind DIFFERENT IMPLEMENTATIONS ... and no , I can not do this : IProvider < T > FOR INSTANCE : In Unity , there are many ways to do this , for instance ;...
public class MyApplication { [ SetterProperty ] public IProvider OneProvider { get ; set ; } [ SetterProperty ] public IProvider TwoProvider { get ; set ; } } public class FooProvider : IProvider { // I would like to force this one to bind-on OneProvider ... } public class BarProvider : IProvider { // I would like to f...
How Do I Bind Different Concretes to a Property Using StructureMap
C#
I am deserializing an Object using this codeMy UserData class is as followsWhen it deserializes I get an object returned as if I had just called new UserData ( ) but if I remove the : BindableBase from the class definition it deserializes correctly . I guess this is because the base class contains some properties that ...
PlayerData = JsonConvert.DeserializeObject < UserData > ( response.Content ) ; public class UserData : BindableBase { public string UID { get ; set ; } public string UDID { get ; set ; } public object liveID { get ; set ; } public int timeLastSeen { get ; set ; } public string country { get ; set ; } public string user...
Deserializing JSON produces default class
C#
I was wondering ... When I have a code like this : Can MyAgent contain code that recognizes it is running under a lock block ? What about : Can MyAgent contain code that recognizes it is running under a loop block ? The same question can be asked for using blocks , unsafe code , etc ... - well you get the idea ... Is t...
lock ( obj ) { MyCode.MyAgent ( ) ; } for ( int i=0 ; i < 5 ; i++ ) { MyCode.MyAgent ( ) ; }
Under what context am I running in C # ?
C#
I have a category/file tree structure . Both categories and files can have parents , so I derived them from a common base class that has a Parent property . Since all parents will obviously always be categories ( files ca n't be a parent ) , it seems to make sense to make the Parent property of the node be the Category...
class Node { public CategoryNode Parent { get ; set ; } } class File : Node { ... } class CategoryNode : Node { ... }
Is it bad form to refer to a derived type in a base type ?
C#
My understanding is that LINQ IEnumerable extensions are supposed to call Dispose on the IEnumerators produced by the IEnumerable . See this answer on SO . However , I 'm not seeing that in practice . Is the other SO answer incorrect , or have I found a bug in LINQ ? Here 's a minimal reproduction of the issue using Mo...
using System ; using System.Threading ; using System.Linq ; using System.Collections.Generic ; using System.Collections ; namespace union { class MyEnumerable : IEnumerable < long > { public IEnumerator < long > GetEnumerator ( ) { return new MyEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEn...
LINQ is n't calling Dispose on my IEnumerator when using Union and Select , expected behavior or bug ?
C#
I would like to know if it is possible to remove an IDictionary item by its key and in the same time get its actual value that has been removed ? Examplesomething like : Output
Dictionary < string , string > myDic = new Dictionary < string , string > ( ) ; myDic [ `` key1 '' ] = `` value1 '' ; string removed ; if ( nameValues.Remove ( `` key1 '' , out removed ) ) //No overload for this ... { Console.WriteLine ( $ '' We have just remove { removed } '' ) ; } //We have just remove value1
IDictionary How to get the removed item value while removing
C#
In javascript , it is common to use closures and create then immediately invoke an anonymous function , as below : Due to strong typing , this very verbose in C # : Is there a more elegant way to go about this type of thing in C # ?
var counter = ( function ( ) { var n = 0 ; return function ( ) { return n++ ; } } ( ) ) ; Func < int > counter = ( ( Func < Func < int > > ) ( ( ) = > { int n = 0 ; return ( ) = > n++ ; } ) ) ( ) ;
Invoking Lambdas at Creation
C#
I do n't understand the difference between Anonymous Class and object Classif i have an anonymous type object : i can see how i can iterate through it and get values of the properties doing this x.name ... but if i change this to an object then if i loop through it i will not be able to access the properties ? ? i have...
var x = new [ ] { new { name = `` x '' , phone = 125 } , new { name = `` f '' , phone = 859 } , new { name= '' s '' , phone=584 } } ; var x = new Object [ ] { new { name = `` x '' , phone = 125 } , new { name = `` f '' , phone = 859 } , new { name= '' s '' , phone=584 } } ;
what is the difference between Anonymous Class Array and Object Array ?
C#
This has probably been already asked but it 's hard to search for.What is the difference between [ Something ] and [ SomethingAttribute ] ? Both of the following compile : Are there any differences between these apart from their appearance ? What 's the general guideline on their use ?
[ DefaultValue ( false ) ] public bool Something { get ; set ; } [ DefaultValueAttribute ( false ) ] public bool SomethingElse { get ; set ; }
What 's the difference between [ Something ] and [ SomethingAttribute ]
C#
I 'm trying to design a class that exposes the ability to add asynchronous processing concerns . In synchronous programming , this might look likein an asynchronous world , where each concern may need to return a task , this is n't so simple . I 've seen this done lots of ways , but I 'm curious if there are any best p...
public class ProcessingArgs : EventArgs { public int Result { get ; set ; } } public class Processor { public event EventHandler < ProcessingArgs > Processing { get ; } public int Process ( ) { var args = new ProcessingArgs ( ) ; Processing ? .Invoke ( args ) ; return args.Result ; } } var processor = new Processor ( )...
Pattern for delegating async behavior in C #
C#
Comparing `` î '' With `` i '' Current culture was en-GB . I would expect all of these to return 1 . Why does having a longer string change the sort order ?
string.Compare ( `` î '' , `` I `` , StringComparison.CurrentCulture ) -- returns -1string.Compare ( `` î '' , `` I `` , StringComparison.CurrentCultureIgnoreCase ) -- returns -1string.Compare ( `` î '' , `` I '' , StringComparison.CurrentCulture ) -- returns 1 ( unexpected ) string.Compare ( `` î '' , `` I '' , String...
Weird string sorting when 2nd string is longer
C#
I had to reinstall everything on my computer including Visual Studio , my question is , before I reinstalled Visual Studio was showing the code on my C # programs in a method using Unicode operators for example : instead of However upon reinstalling Visual Studio they 've reverted back to the text format , does anyone ...
if ( 1 ≠ 2 ) { } if ( 1 ! = 2 ) { }
Visual Studio a way to show operators as opposed to text Example : ≠ instead of ! =
C#
Foreword : I am trying to describe the scenario very precisely here . The TL ; DR version is 'how do I tell if a lambda will be compiled into an instance method or a closure ' ... I am using MvvmLight in my WPF projects , and that library recently changed to using WeakReference instances in order to hold the actions th...
ctor ( Guid token ) { Command = new RelayCommand ( x = > Messenger.Default.Send ( x , token ) ) ; } [ CompilerGenerated ] private sealed class < > c__DisplayClass4 { public object token ; public void < .ctor > b__0 ( ReportType x ) { Messenger.Default.Send < ReportTypeSelected > ( new ReportTypeSelected ( X ) , this.to...
Determining when a lambda will be compiled to an instance method
C#
My problem isi have this JSON file : and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException , as if my list is empty . this is my code : and these are my two class for the saves : and can you help me solve it ?
JavaScriptSerializer ser = new JavaScriptSerializer ( ) ; Causali o = new Causali ( ) ; List < CausaliList > lista = new List < CausaliList > ( ) ; WebRequest causali = ( HttpWebRequest ) WebRequest.Create ( `` http : //trackrest.cgestmobile.it/causali '' ) ; WebResponse risposta = ( HttpWebResponse ) CreateCausaliRequ...
Deserializing a JSON file with c #
C#
I seem to be having trouble executing a lambda expression that I 've previously assigned to a variable . Here 's a small C # example program I 've put together : I want it to produce this output:3 2 5 8 1 4 7 9 61 2 3 4 5 6 7 8 99 8 7 6 5 4 3 2 1But , confusingly , it produces this output:3 2 5 8 1 4 7 9 63 2 5 8 1 4 7...
public class Program { public static void Main ( string [ ] args ) { int [ ] notOrdered = { 3 , 2 , 5 , 8 , 1 , 4 , 7 , 9 , 6 } ; Print ( notOrdered ) ; IEnumerable < int > ascOrdered = Order ( notOrdered , true ) ; Print ( ascOrdered ) ; IEnumerable < int > descOrdered = Order ( notOrdered , false ) ; Print ( descOrde...
Assigning a lambda expression causes it to not be executed later ?
C#
I 'm working on a prototype EF application , using POCOs . Mainly as an introduction to the framework I 'm wondering about a good way to set up the application in a nice structure . Later on I 'm planning to incorporate WCF into it.What I 've done is the following:1 ) I created an edmx file , but with the Code Generati...
public class Person { public Person ( ) { } public Person ( string firstName , string lastName ) { FirstName = firstName ; LastName = lastName ; } public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } public class PocoContext : ObjectContext , IPocoContext { priv...
Setting up an EF application 's structure
C#
I need to perform multi string replacement . I have a string where several parts need to be changed according to substitution map.All replacement must be done in one action - it means if `` a '' should be replaced with `` b '' and also `` b '' must be replaced with `` c '' and input string is `` abc '' , the result wil...
public static string Replace ( string s , Dictionary < string , string > substitutions ) { string pattern = `` '' ; int i = 0 ; foreach ( string ch in substitutions.Keys ) { if ( i == 0 ) pattern += `` ( `` + Regex.Escape ( ch ) + `` ) '' ; else pattern += `` | ( `` + Regex.Escape ( ch ) + `` ) '' ; i++ ; } var r = new...
Fast multi-string replacement
C#
I have two IEnumerables of different types , both of which derive from a common base class . Now I try to union the enumerables to get an enumerable of the base class . I have to explicitly cast one of the enumerables to the base class for this to work.I would have guessed that the Compiler would have automatically cho...
namespace ConsoleApp1 { public class BaseClass { } public class DerivedClass1 : BaseClass { } public class DerivedClass2 : BaseClass { } class Program { static void Main ( string [ ] args ) { List < DerivedClass1 > list1 = new List < DerivedClass1 > ( ) ; List < DerivedClass2 > list2 = new List < DerivedClass2 > ( ) ; ...
Why cant the compiler resolve the resulting type ?
C#
Is there a way to control access to methods to certain roles in .net . Like I 'm using windows authentication only for retrieving user names and nothing more.User roles are maintained in a different application . I think it 's possible through attributes but I 'm not really sure how
class A { //should only be called by Admins** public void Method1 ( ) { } //should only be called by Admins and PM's** public void Method2 ( ) { } }
Controlling access to methods
C#
I 've been looking into Functional Programming lately and wanting to bring some concepts to my C # world . I 'm trying to compose functions to create services ( or whatever you 'd call them ) instead of creating classes with injectable dependencies.I 've come up with a way to partially apply a function ( to have the sa...
// this makes a func with a single arg from a func with twostatic Func < T2 , TResult > PartiallyApply < T1 , T2 , TResult > ( Func < T1 , T2 , TResult > f , T1 t1 ) { // use given t1 argument to create a new function Func < T2 , TResult > map = t2 = > f ( t1 , t2 ) ; return map ; } static string MakeName ( string a , ...
Static method signature type arguments and partial application
C#
I am a bit clueless about the next task . I wish to select a text between `` that its inside a tag but not outside of the tag , i.e . a selection inside another selection.I have the next tag : < | and | > and i want to select a text only if its between the `` and between the tags. < | blah blah blah `` should be select...
( \ < \| ) ( \ '' ) .* ? ( \ '' ) ( \|\ > )
Regular expression , selects a portion of text inside other
C#
Given the struct S1 : and an equality test : areEqual evaluates to true , as expected.Now lets slightly change our struct to S2 ( replacing the pointer with a string ) : with an analog test : this evaluates to true as well.Now the interesting part . If we combine both structs to S3 : and test for equality : The equalit...
unsafe readonly struct S1 { public readonly int A1 , A2 ; public readonly int* B ; public S1 ( int a1 , int a2 , int* b ) { A1 = a1 ; A2 = a2 ; B = b ; } } int x = 10 ; var a = new S1 ( 1 , 2 , & x ) ; var b = new S1 ( 1 , 2 , & x ) ; var areEqual = Equals ( a , b ) ; // true unsafe readonly struct S2 { public readonly...
Unexpected equality tests , Equals ( a , a ) evaluates to false
C#
Suppose I 've a generic method as : Are this.Fun < Feature > and this.Fun < Category > different instantiations of the generic method ? In general , how does the generic method get instantiated ? Different generic argument produces different method , or same method along with different metadata which is used at runtime...
void Fun < T > ( FunArg arg ) { } client.SomeEvent += this.Fun < Feature > ; //line1client.SomeEvent += this.Fun < Category > ; //line2client.SomeEvent += this.Fun < Result > ; //line3 client.SomeEvent -= this.Fun < Feature > ; //lineX
How generic methods gets instantiated in C # ?
C#
I have the following KeyBindings : When I press Ctrl+Shift+S to execute the SaveAs command , it works -- but directly afterwards , the Save command is also executed . Is this caused by my Gesture definitions ?
< KeyBinding Gesture= '' Ctrl+S '' Command= '' Save '' / > < KeyBinding Gesture= '' Ctrl+Shift+S '' Command= '' SaveAs '' / >
How can I ensure that only one KeyBinding command is executed when a keyboard shortcut is used ?
C#
I just wonder how to write a number that has to be expressed as string.For instance : or or or
if ( SelectedItem.Value == 0.ToString ( ) ) ... if ( SelectedItem.Value == `` 0 '' ) ... public const string ZeroNumber = `` 0 '' ; if ( SelectedItem.Value == _zeroNumber ) ... if ( Int.Parse ( SelectedItem.Value ) == 0 )
BestPractice for conditions with strings and numbers
C#
Excuse the poor wording , but I could n't find a better way to explain it.From my understanding , C # is a WORA language- you can write it on one machine and deploy it on another , because the MSIL is n't compiled until the application is actually run.So then why is it that BitConverter.IsLittleEndian is defined like s...
# if BIGENDIAN public static readonly bool IsLittleEndian /* = false*/ ; # else public static readonly bool IsLittleEndian = true ; # endif
Why is BIGENDIAN a directive if it 's not resolved at compile-time ?
C#
I have a custom control that when I drag onto the form , creates the following designer.cs code : I 'd like it ( Visual Studio ) to completely ignore the .Color attribute and leave it be . How can I tell it to do that ? Thank you !
// // colorPickerBackground// this.colorPickerBackground.Color = Color.Empty ; this.colorPickerBackground.Location = new System.Drawing.Point ( 256 , 175 ) ; this.colorPickerBackground.Name = `` colorPickerBackground '' ; this.colorPickerBackground.Size = new System.Drawing.Size ( 156 , 21 ) ; this.colorPickerBackgroun...
How can I tell Visual Studio to not populate a field in the designer code ?
C#
I 'm hunting down a bug in a large business application , where business processes are failing but partially persisted to the database . To make things harder to figure out , the process fails only once every few weeks , with hundreds of thousands successfully processed between every failure . The error frequency seems...
using ( var transactionScope = new TransactionScope ( TransactionScopeOption.RequiresNew ) ) { using ( var sqlConnection = new SqlConnection ( `` Server=localhost ; Database=Database1 ; Trusted_Connection=True '' ) ) { sqlConnection.Open ( ) ; // Doing some unwanted nested manual transaction and rolling it back var tra...
How to detect that rollback has occurred ?
C#
By abusing the type system in c # , I can create code , where the compiler will enforce a rule , to ensure an impossible operation is not performed . In the below code , its specific to matrix multiplication . Obviously the below is totally impractical/wrong , but are there reasons we cant have something like this in c...
public abstract class MatrixDimension { } public class One : MatrixDimension { } public class Two : MatrixDimension { } public class Three : MatrixDimension { } public class Matrix < TRow , TCol > where TRow : MatrixDimension where TCol : MatrixDimension { // matrix mult . rule . N×M * M×P = N×P public Matrix < TRow , ...
Using generics to enforce valid structure at compile time
C#
Im using this code to Send a Mail with excel attachment from gridview , it works fine for the mail part but the excel attachment is always blank i have already debugged the code and sure that the datasource of the Gridview passes the data it needed to the gridview , it seems that im not rendering the gridview to excel ...
protected void MailButton_Click ( object sender , EventArgs e ) { List < FOAM > foamList = new List < FOAM > ( servs.GetAreaList ( ) ) ; foreach ( FOAM foam in foamList ) { Session [ `` Area '' ] = foam.ItemAreaCode ; Session [ `` Principal '' ] = foam.PrincipalAmount ; Session [ `` Accountability '' ] = foam.Accountab...
Retrieving Blank Excel upon attaching excel in Mail
C#
Feel free to load your guns and take aim , but I want to understand why you should n't do this.I have created a custom class designed to replace any instances of List ( which I use to update XML objects behind them ) : The idea is whenever I add or remove an item from this list my bound events will fire and I can deal ...
public class ListwAddRemove < T > : List < T > { public event EventHandler < ListModifyEventArgs > OnAdd ; public event EventHandler < ListModifyEventArgs > OnRemove ; new public void Add ( T o ) { base.Add ( o ) ; if ( OnAdd ! = null ) { OnAdd ( this , new ListModifyEventArgs ( o ) ) ; } } new public void Remove ( T o...
Custom ( derived ) List < T >
C#
Here is an example of a property I have , coded as simply as possibleThis is verbose ; I would like to make it more concise if possible . The following would be acceptable ... ... but it does n't compile . Keyword 'this ' is not valid in a static property , static method , or static field initializerSo I came up with t...
private IEnumerable < int > _blocks ; private bool _blocksEvaluated ; public IEnumerable < int > Blocks { get { if ( ! _blocksEvaluated ) { _blocksEvaluated = true ; _blocks = this.CalculateBlocks ( 0 ) .FirstOrDefault ( ) ; } return _blocks ; } } private Lazy < IEnumerable < int > > _blocks = new Lazy < IEnumerable < ...
Lazy property requiring `` this ''
C#
Edit : Solved ! thanks to @ kfinity.AskTom suggests using select /*+ opt_param ( '_optimizer_use_feedback ' 'false ' ) */ at the start of your query to disable the feedback usage . This has fixed the problem for me.tldr : Adding a randomized comment to a query makes it run consistent , removing this comment breaks it.W...
select *from v $ session_longopswhere time_remaining > 0 select -- Hierarchic info , some aliases exceeded 30 chars and had to be shorted to current state hierarchic_workorders.ccn as HierarchicCcn , hierarchic_workorders.mas_loc as HierarchicMasLoc , hierarchic_workorders.wo_num as HierarchicWoNum , hierarchic_workord...
Oracle query only runs consistently when adding a random comment
C#
This is my very first question after many years of lurking here , so I hope I do n't break any rules.In some of my ASP.NET Core API 's POST methods , I 'd like to make it possible for clients to provide only the properties they want to update in the body of their POST request.Here 's a simplified version of my code : M...
[ Route ( `` api/v { version : apiVersion } / [ controller ] '' ) ] [ ApiController ] public sealed class FooController : ControllerBase { public async Task < IActionResult > UpdateFooAsync ( Guid fooGuid , [ FromBody ] UpdateFooModel model ) { ... Apply updates for specified properties , checking for authorization whe...
Differentiating between explicit 'null ' and 'not specified ' in ASP.NET Core ApiController
C#
Suppose , we have a very simple class : and we want to make an instance of this class : So , in case of List2 it is ok , using `` = '' we set property . But in List1 case it looks like we set property , but actually , we suppose to set it somewhere before , and here we only set values . And it very similar to array ini...
class ObjectList { public List < string > List1 { get ; } = new List < string > ( ) ; public List < string > List2 { get ; set ; } } ObjectList objectList = new ObjectList { List1 = { `` asdf '' , `` qwer '' } , List2 = new List < string > { `` zxcv '' , `` 1234 '' } } ; string [ ] arr = { `` val1 '' , `` val2 '' } cla...
Weird syntax of collection initializers
C#
I am doing a Func - > Expression - > Func conversion . It works fine if I create the Func < > ( ) from a method ( first example below ) however if I create the function using an expression tree ( 2nd example ) it fails with a NullReferenceException when accessing func2.Method.DeclaringType.FullName . And this is becaus...
// Build a Func < > Func < int , int > add = Add ; // Convert it to an Expression using NJection LibraryExpression < Func < int , int > > expr = ToExpr < Func < int , int > > ( add ) ; // Convert it back to a Func < > Func < int , int > func = expr.Compile ( ) ; // Run the Func < > int result = func ( 100 ) ; // Build ...
Is there a way to set 'DeclaringType ' in an expression tree ?
C#
The code below will compile but fails at runtime . It 's provided just to give an idea of what I 'm trying to do . What I would like to do is create a method that accepts a collection of objects ( effectively an `` untyped '' collection ) and if this collect is comprised of numbers of a single type return the mean usin...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace nnConsole { class Program { static void Main ( string [ ] args ) { var ints = new object [ 4 ] { 1 , 2 , 3 , 4 } ; var dbls = new object [ 4 ] { 1.0 , 2.0 , 3.0 , 4.0 } ; Console.WriteLine ...
Is there a clever way to call a type dependent extension method dynamically ?
C#
The above code is copy from Page 153 c # in a Nutshell , I do n't understand why the { } are missing after the using statement , is that a typo in the book ( unlikely ) or just not needed ? As the syntax is that using need to follow by a block of code inside { } .I would expect this code to be :
using System.Net ; // ( See Chapter 16 ) ... string s = null ; using ( WebClient wc = new WebClient ( ) ) // why there is no brackets after this using statement try { s = wc.DownloadString ( `` http : //www.albahari.com/nutshell/ '' ) ; } catch ( WebException ex ) { if ( ex.Status == WebExceptionStatus.Timeout ) Consol...
c # `` using '' statement follow by try statement can the bracket be ombitted in that case ?
C#
I safely search a list for an object like this : If there are no objects that match my criteria then someResult is going to be null.But if I only have the index of the object I want , things are not so nice . I seem to have to so something like this : I admit that is not terrible to have to write . But it seems to me t...
var someResult = myList.FirstOrDefault ( x= > x.SomeValue == `` SomethingHere '' ) ; try { var someResult = myList [ 4 ] ; } catch ( ArgumentOutOfRangeException ) { someResult = null ; }
Is there a concise built-in way to get a list item by index that is not going to throw an exception ?
C#
I have a custom class that I use to build table strings . I would like to rewrite the code so that I can chain the operators . Something like : So it seems like I would have each of these methods ( functions ) return the object itself so that I can then call another method ( function ) on the resulting object , but I c...
myObject .addTableCellwithCheckbox ( `` chkIsStudent '' , isUnchecked , isWithoutLabel ) .addTableCellwithTextbox ( `` tbStudentName '' , isEditable ) etc .
How do I declare a class in C # so that I can chain methods ?
C#
So I have a dotNet CoreCLR application for hololens and it 's my understanding that standard sockets are n't supported in CoreCLR and the recommended avenue is to use StreamSocket.It 's also my understanding that CodedInputStream and StreamSocket are n't compatible.So I 've been manually trying to decode the size pre-s...
int bytenum = 0 ; int num = 0 ; while ( ( bytes [ bytenum ] & 0x80 ) == 0x80 ) { bytenum++ ; } while ( bytenum > = 0 ) { int tem = bytes [ bytenum ] & 0x7F ; num = num < < 7 ; num = num | tem ; bytenum -- ; } var dr = new DataReader ( socket.InputStream ) ; await dr.LoadAsync ( 1 ) ; int result = -1 ; int tmp = dr.Read...
Manually decoding the Size presend on a CodedInputStream
C#
I have a MyProject project where I have IMyService interface and MyService class that implements IMyService . In Startup.cs class I dependency injection them : Because MyService has many dependencies ( makes many REST calls to 3rd party etc . ) I would like to create a stub version of it for development environment . I...
// MyProject project | Startup.cspublic void ConfigureServices ( IServiceCollection services ) { services.AddScoped < IMyService , MyService > ( ) ; } // MyStubsProject projectpublic class MyStubService : IMyService { ... } // MyProject project | Startup.cspublic void ConfigureServices ( IServiceCollection services ) {...
How to implement dependency injection in Startup.cs when dependencies are circular ?
C#
ContextI have two classes : LiteralModel is a wrapper around a string Value property . Expression has a string Name and a LiteralModel called Literal.All are public properties with public getters and setters , and so I would expect both of them to serialize and deserialize easily , even with the null guards , and , for...
public class ExpressionModel { private string name ; public string Name { get = > name ? ? `` `` ; set = > name = value ; } private LiteralModel literal ; public LiteralModel Literal { get = > literal ? ? new LiteralModel ( ) ; set = > literal = value ; } } public class LiteralModel { private string value ; public stri...
Why does the Newtonsoft deserializer not deserialize a smart getter ?
C#
I have two unit tests that use TypeMock Isolator to isolate and fake a method from asp.net 's SqlMembershipProvider.In test 1 I have : In test 2 I have : When I run each test by itself they both pass successfully . When I run both tests , test number 1 runs first and passes , then test number 2 runs and fails with the ...
Isolate.WhenCalled ( ( ) = > Membership.CreateUser ( ... ) ) ) .WithExactArguments ( ) .WillThrow ( new Exception ( ) ) ; Isolate.WhenCalled ( ( ) = > Membership.CreateUser ( ... ) ) ) .WithExactArguments ( ) .WillReturn ( new MembershipUser ( ... ) ) ;
TypeMock Isolator : WillThrow ( ) bleeds across unit test boundaries ?
C#
I discovered a strange behavior when using property indexer ( C # ) .Consider the following program : Why do I get all results back when using the default indexer ( the x2 variable ) ? It seems that the int parameter ( 0 ) is automatically converted to the enum type ( Type1 ) . This is not what I was expecting ... .Tha...
public class Program { public static void Main ( string [ ] args ) { CustomMessageList cml = new CustomMessageList { new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) , // Type1 new CustomMessage ( ) // Type1 } ; // ...
Property indexer with default 0 ( zero ) value
C#
I have an employees list in my application . Every employee has name and surname , so I have a list of elements like : I want my customers to have a feature to search employees by names with a fuzzy-searching algorithm . For example , if user enters `` Yuma Turmon '' , the closest element - `` Uma Turman '' will return...
[ `` Jim Carry '' , `` Uma Turman '' , `` Bill Gates '' , `` John Skeet '' ] static class LevenshteinDistance { /// < summary > /// Compute the distance between two strings . /// < /summary > public static int Compute ( string s , string t ) { int n = s.Length ; int m = t.Length ; int [ , ] d = new int [ n + 1 , m + 1 ...
Implementing Levenstein distance for reversed string combination ?
C#
is there any functional difference between : and if so , is there a more compelling reason to use one over the other ?
if ( photos.Any ( it = > it.Archived ) ) if ( photos.Where ( it = > it.Archived ) .Any ( ) )
are these two linq expressions functionally equivalent ?
C#
I 'm working on optimization techniques performed by the .NET Native compiler.I 've created a sample loop : And I 've compiled it with Native . Then I disassembled the result .dll file with machine code inside in IDA . As the result , I have : ( I 've removed a few unnecessary lines , so do n't worry that address lines...
for ( int i = 0 ; i < 100 ; i++ ) { Function ( ) ; } LOOP : add esi , 0FFFFFFFFhjnz LOOP LOOP : inc esicmp esi , 064hjl LOOP
Why does .NET Native compile loop in reverse order ?
C#
Basically , I want to write a wrapper for all ICollection < > types . Lets call it DelayedAddCollection . It should take any ICollection as its .Furthermore , I need access to that ICollection type 's generic type as the Add method needs to restrict its parameter to that type.The syntax I would imagine would look somet...
public DelayedAddConnection < T > : where T : ICollection < U > { ... . public void Add ( U element ) { ... } }
How do I create a generic class that takes as its generic type a generic class ?
C#
I 'm working on Project Euler number 5 . I 've not Googled , as that will typically lead to a SO with the answer . So , this is what I 've got : In my mind , this makes sense . Yet VS2012 is giving me a StackOverFlowException suggesting I make sure I 'm not in an infinite loop or using recursion . My question is , why ...
private int Euler5 ( int dividend , int divisor ) { if ( divisor < 21 ) { // if it equals zero , move to the next divisor if ( dividend % divisor == 0 ) { divisor++ ; return Euler5 ( dividend , divisor ) ; } else { dividend++ ; return Euler5 ( dividend , 1 ) ; // move to the dividend } } // oh hey , the divisor is abov...
How to break out of this loop
C#
I 'm trying to use a .NET Regex to validate the input format of a string . The string can be of the formatSo 0AAA , 107ZF , 503GH , 0AAAA are all valid . The string with which I construct my Regex is as follows : Yet this does not validate strings in which the second term is one of 03 , 07 or AA . Whilst debugging , I ...
single digit 0-9 followed bysingle letter A-Z OR 07 OR 03 or AA followed bytwo letters A-Z `` ( [ 0-9 ] { 1 } ) '' + `` ( ( 03 $ ) | ( 07 $ ) | ( AA $ ) | [ A-Z ] { 1 } ) '' + `` ( [ A-Z ] { 2 } ) ''
Simple Regular Expression ( Regex ) issue ( .net )
C#
I have a method A ( ) that processes some queries . This method , from opening bracket to just before its return statement , times at +/-70ms . A good 50 % of which comes from opening the connection , about 20 % comes from the actual queries , 5-10 % is used by some memory access , the rest is ( probably ) used for dis...
B ( ) { var timer = Stopwatch.Startnew ( ) A ( ) ; timer.Stop ( ) ; // elapsed : +/- 250ms Debugger.Break ( ) ; } A ( ) { var totalTimer = Stopwatch.StartNew ( ) ; var stuff = new Stuffholder ( ) ; using ( connection ) { using ( command ) { using ( reader ) { // fill 'stuff ' } } } totalTimer.Stop ( ) ; // elapsed : +/...
Overhead in returning from a method
C#
I have two lists like these:2 list also have same size . I want some operations in listQ relation to listVal : if listVal 's any indexes have same values , I want to take average listQ 's values in same indexes . For example : So , I want listQ 's same indexes be same.Now , each these indexes must have 23.45 : Likewise...
public static List < List < List < double > > > listQ = new List < List < List < double > > > ( ) ; public static List < List < List < double > > > listVal = new List < List < List < double > > > ( ) ; listVal [ 0 ] [ 0 ] [ 1 ] = listVal [ 0 ] [ 0 ] [ 2 ] = 3 . ( listQ [ 0 ] [ 0 ] [ 1 ] + listQ [ 0 ] [ 0 ] [ 2 ] ) / 2 ...
List operations related to another list 's conditions
C#
I am trying to set up a navigation between views using a MVVM pattern . My application contains a MainWindow and two views with a button each . When I click on the button in the View1 I want to set up the View2 on the MainWindow.I have found several tutorials witch explain how to navigate from a view to another with a ...
public partial class View1_View : UserControl { private View1_ViewModel _viewModel = new View1_ViewModel ( ) ; public View1_View ( ) { InitializeComponent ( ) ; } private void Btn_SwitchToView2_Click ( object sender , RoutedEventArgs e ) { MainWindow.SwitchToView2 ( ) ; } } public partial class MainWindow : Window { pu...
WPF view who leads to another using MVVM
C#
this is a small code which shows virtual methods.This code is printing the below output : I can not understand why a.F ( ) will print B.F ? I thought it will print D.F because Class B overrides the F ( ) of Class A , then this method is being hidden in Class C using the `` new '' keyword , then it 's again being overri...
class A { public virtual void F ( ) { Console.WriteLine ( `` A.F '' ) ; } } class B : A { public override void F ( ) { Console.WriteLine ( `` B.F '' ) ; } } class C : B { new public virtual void F ( ) { Console.WriteLine ( `` C.F '' ) ; } } class D : C { public override void F ( ) { Console.WriteLine ( `` D.F '' ) ; } ...
Need to understand the below code for C # virtual methods
C#
In C # I could do this : But can I do something like that in C++ ? I tried : But it does n't compile .
char [ ] a = new char [ ] { ' a ' , ' a ' , ' a ' } ; char *a = new char [ ] { ' a ' , ' a ' , ' a ' } ;
Array initialization when using new
C#
I have a class called playingcards it inherits from a cards class . I instantiated it as an object called chuckcards . One of the data members is CARD ID . I 'm trying to assign a int to the value . it is declared public int the class.Here 's how its instantiated.playingcards [ ] chuckcards = new playingcards [ 10 ] ; ...
for ( int ctr = 1 ; ctr < 10 ; ctr++ ) { chuckcards [ ctr ] .cardID = ctr ; temp++ ; }
giving a class object a value c #
C#
How can I quickly create a string list with numbered strings ? Right now I 'm using : This works , however I wonder if there 's a quicker way to initialize such a string list , maybe in one or two lines ?
var str = new List < string > ( ) ; for ( int i = 1 ; i < = 10 ; i++ ) { str.Add ( `` This is string number `` + i ) ; }
Quick way to initialize list of numbered strings ?
C#
I 've noticed this type of behavior before , and it occurred to me to ask a question this time : I have a simple `` proof of concept '' program that spawns a few threads , waits for them to do some work , then exits . But Main is n't returning unless I call server.Close ( ) ( which closes the socket and ends the server...
private void Run ( ) { var server = StartServer ( ) ; //Starts a thread in charge of listening on a socket _serverResetEvent.WaitOne ( ) ; ThriftProtocolAccessManager protocolManager = CreateProtocolManager ( ) ; //Does n't create any threads const int numTestThreads = 10 ; Barrier testCompletedBarrier ; Thread [ ] tes...
Why is n't Main returning ?
C#
If I want to periodically check if there is a cancellation request , I would use the following code below constantly inside my DoWork event handler : Is there a clean way for checking a cancellation request in BackgroundWorker in C # without re-typing the same code over and over again ? Please refer to the following co...
if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } void worker_DoWork ( object sender , DoWorkEventArgs e ) { ... BackgroundWorker w = sender as BackgroundWorker ; if ( w.CancellationPending == true ) { e.Cancel = true ; return ; } some_time_consuming_task ... if ( w.CancellationPending == true ) { e.C...
Is there a clean way for checking a cancellation request in BackgroundWorker without re-typing the same code over and over again ?
C#
I expect the following code to deadlock when Clear tries to lock on the same object that Build has already locked : Output : ClearBuildEdit 1Thank you all for your answers.If I add a call to Build inside the lock of Clear ( keeping the rest of the code the same ) : A deadlock does occur ( or at least that 's what I thi...
void Main ( ) { ( new SiteMap ( ) ) .Build ( ) ; } class SiteMap { private readonly object _lock = new object ( ) ; public void Build ( ) { lock ( _lock ) { Clear ( ) ; Console.WriteLine ( `` Build '' ) ; } } public void Clear ( ) { lock ( _lock ) { Console.WriteLine ( `` Clear '' ) ; } } } public void Clear ( ) { lock...
Why does n't this code deadlock ?
C#
I wrote a program that compiles my .cs files using csc.exe : The compile instruction runs but produces no results , just a quick flash of a black console screen . Basically what seems to be happening , is when all the strings are parsed in the commandline as arguments for the process , the .cs project source directory ...
namespace myCompiler { public partial class Form1 : Form { string compilerFolder ; string outputFolder ; string projectFile ; string output = @ '' /out : '' ; public Form1 ( ) { InitializeComponent ( ) ; } private void startCompile_Click ( object sender , EventArgs e ) { Compile ( ) ; } public void findCompile_Click ( ...
Expected behaviour with white space in the command line
C#
I have two snippets , one in Java and one in c # .the Java snippet returns 7101.674and in c # produces a result of 7103.674.why am I off by 2 and what is correct ?
float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; long e = 1234L ; int f = 0xa ; int g = 014 ; char h = ' Z ' ; char ia = ' ' ; byte j = 123 ; short k = 4321 ; System.out.println ( a+b+ca+d+e+f+g+h+ia+j+k ) ; float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; l...
why does java and c # differ in simple Addition
C#
Because I am using a `` using '' here , If there is an exception any where in the TRY will the FtpWebRequest , FtpWebRespons and responseStream automatically be closed ?
Try Dim request As FtpWebRequest = CType ( WebRequest.Create ( `` '' ) , FtpWebRequest ) request.Method = WebRequestMethods.Ftp.ListDirectoryDetails request.Credentials = New NetworkCredential ( `` '' , `` '' ) Using response As FtpWebResponse = CType ( request.GetResponse ( ) , FtpWebResponse ) Using responseStream As...
if there is an exception in the `` using '' will it be automatically closed
C#
Why input length on regex does not affect performance and how is that possible ? The generated string is like this : 128 random characters . then two numbers inside parenthesis . and this is repeated many times.The regex gets all the numbers inside parenthesis . here is the pattern.So the matches would be likeHere is t...
128 radnom characters ... . ( -2435346|45436 ) 128 radnom characters ... . ( -32525562|-325346 ) \ ( ( [ -+ ] ? \d+\| [ -+ ] ? \d+ ) \ ) -2435346|45436-32525562|-325346etc ... Random rand = new Random ( ) ; Func < string > getRandString = // generates 128 random characters . ( ) = > Enumerable.Range ( 0 , 128 ) .Select...
Why regex does not care about string length
C#
I 've got a Linq To Sql query ( or with brackets ) here that works on my local SQL2008 , in about 00:00:00s - 00:00:01s , but on the remote server , it takes around 00:02:10s . There 's about 56k items in dbo.Movies , dbo.Boxarts , and 300k in dbo.OmdbEntriesThe inner query first takes all the related items in the tabl...
{ SELECT//pull distinct t_meter out of the created objectDistinct2.t_Meter AS t_Meter//match all movie data on the same movie_idFROM ( SELECT DISTINCT Extent2.t_Meter AS t_Meter FROM dbo.Movies AS Extent1 INNER JOIN dbo.OmdbEntries AS Extent2 ON Extent1.movie_ID = Extent2.movie_ID INNER JOIN dbo.BoxArts AS Extent3 ON E...
DbContext times out on remote server only
C#
If I do the following : This works and testdecimal ends up being 12222.Should n't this reasonably/logically fail parsing ? I was surprised to see that it worked and was curious as to what is the logic behind it that allows this .
string teststring = `` 12,2,2,2 '' ; decimal testdecimal ; decimal.TryParse ( teststring , out testdecimal )
Why does decimal.TryParse successfully parse something like 12,2,2,2
C#
When I place an open brace in Visual Studio 2017 ( C # ) the cursor automatically goes to the next line to the left of the end brace . Like this ( period as cursor ) : I 'd like the cursor to automatically be on its own line like this ( period as cursor ) : Does anybody know how to make the cursor automatically go wher...
if ( ) { . } if ( ) { . }
How to automatically place cursor between braces on its own line using Visual Studio 2017
C#
Today I was thinking it would be neat to make anonymous object which is type of some interface , and I have seen on SO that I am not only one.Before I started checking out what happens I wrote some code like the one below.To my amusement it compiled , I am using .net framework 4 and I know there is no way to do anonymo...
namespace test { class Program { static void Main ( string [ ] args ) { Holder holder = new Holder { someInterface = { Property = 1 } } ; Console.WriteLine ( holder.someInterface.Property ) ; } } class Holder { public ISomeInterface someInterface { get ; set ; } } interface ISomeInterface { int Property { get ; set ; }...
Assign to interface array initializator compiles but why ?
C#
I have a person table filled with Person information . I would like to get a list of the personer inside the table and check if they have renewed thier password in last 24 hours , and then return a person name and a boolean property whether they have updated the password or not . This is my Person table : Person table ...
varchar ( 30 ) Name , DateTime LastRenewedPassword . public class Person { public string Name { get ; set ; } public boolean HasRenewedPassword { get ; set ; } } public List < Person > GetPersons ( ) { using ( var context = Entities ( ) ) { var persons = from p in contex.Persons select new Person { Name = p.Name , HasR...
Boolean inside of Select ( )
C#
I 'm wondering if I should change the software architecture of one of my projects.I 'm developing software for a project where two sides ( in fact a host and a device ) use shared code . That helps because shared data , e.g . enums can be stored in one central place.I 'm working with what we call a `` channel '' to tra...
public abstract class ChannelAbstract { protected void ChannelAbstractMethodUsedByDeviceSide ( ) { } protected void ChannelAbstractMethodUsedByHostSide ( ) { } } public abstract class MeasurementChannelAbstract : ChannelAbstract { protected void MeasurementChannelAbstractMethodUsedByDeviceSide ( ) { } protected void Me...
Is it good practice to blank out inherited functionality that will not be used ?
C#
I want to parse plain text comments and look for certain tags within them . The types of tags I 'm looking for look like : Where `` name '' is a [ a-z ] string ( from a fixed list ) and `` 1234 '' represents a [ 0-9 ] + number . These tags can occur within a string zero or more times and be surrounded by arbitrary othe...
< name # 1234 > `` Hello < foo # 56 > world ! '' '' < bar # 1 > ! `` `` 1 & lt ; 2 '' '' + < baz # 99 > + < squid # 0 > and also < baz # 99 > .\n\nBy the way , maybe < foo # 9876 > '' `` 1 < 2 '' '' < foo > '' '' < bar # > '' '' Hello < notinfixedlist # 1234 > '' < [ a-z ] + # \d+ > < ( foo|bar|baz|squid ) # \d+ > gram...
Extracing specific tags from arbitrary plain text
C#
I would like to know , in .NET , if the ( managed ) Microsoft UI Automation framework provides some way to instantiate an AutomationElement type given the AutomationId value of a window , suppressing this way the need to search the window by a window handle or other kind of identifiers.A pseudo example written in VB.NE...
Dim automationId As Integer = 1504Dim element As AutomationElement = AutomationElement.FromAutomationId ( automationId )
Can be instantiated the type AutomationElement given an AutomationId value ?
C#
I have a class which is basically a message handler , it accepts requests , finds a processor for that message type , creates an appropriate response and returns it . To this end , I have created a delegate as follows public delegate Rs ProcessRequest < Rq , Rs > ( Rq request ) ; and then inside my class , created a nu...
public delegate Rs ProcessRequest < in Rq , out Rs > ( Rq request ) where Rq : API.Request where Rs : API.Response ; public class WebSocketServer { private WebSocketMessageHandler messageHander ; // Incoming message handlers public ProcessRequest < InitUDPConnectionRq , InitUDPConnectionRs > ProcessInitUDPConnection ; ...
Dynamically executing delegates
C#
I am learning about implementing interfaces and generics , I made this code , but VStudio says that I did not implement System.Collections.Enumerable.GetEnumerator ( ) .Did I not do this below , generically ? It wants two implementations ?
namespace Generic_cars { class VehicleLot : IEnumerable < Vehicle > { public List < Vehicle > Lot = new List < Vehicle > ( ) ; IEnumerator < Vehicle > IEnumerable < Vehicle > .GetEnumerator ( ) { foreach ( Vehicle v in Lot ) { yield return v ; } ; } } }
IEnumerable , requires two implementations ?
C#
I have this code to open multiple urls from a richtextbox , it works fine , but the problem is that it opens all sites in separate browsers . Any ideas how I can open the pages like tabs in the same browser ?
private void button1_Click ( object sender , EventArgs e ) { for ( int i = 0 ; i < richTextBox1.Lines.Length ; i++ ) { Process.Start ( `` http : // '' + richTextBox1.Lines [ i ] ) ; } }
how to open multiple urls from richtextbox
C#
While reading this answer from another question I was 100 % sure that the following code would lock up the UI and not cause any movement.I and several others in the comments said it would not work but the OP insisted that it did and we should try . I ended up making a new Winforms project , adding a button , then putti...
private void button1_Click ( object sender , EventArgs e ) { for ( int i = 0 ; i < 5 ; i++ ) { this.Left += 10 ; System.Threading.Thread.Sleep ( 75 ) ; this.Left -= 10 ; System.Threading.Thread.Sleep ( 75 ) ; } }
Why does my form NOT lock up ?
C#
I do n't know if I 'm missing something ... anyway : You can see , for example , that the object with the property 'HomeTeam ' = ' Forest Green Rovers ' has the state = 'Unchanged ' . Anyway all entities are 'unchanged ' in my case . So , if I 'm correct , the saveChanges should n't try to insert those in my table but ...
{ using System ; using System.Collections.Generic ; public partial class MatchInfo { [ System.Diagnostics.CodeAnalysis.SuppressMessage ( `` Microsoft.Usage '' , `` CA2214 : DoNotCallOverridableMethodsInConstructors '' ) ] public MatchInfo ( ) { this.Sport = `` Soccer '' ; this.OddsInfoes1X2 = new HashSet < OddsInfo1X2 ...
SaveChanges ( ) is saving Unchanged records
C#
This was a interview question - How will you efficiently trim the duplicate characters in string with single character . Example : suppose this is the input string `` reeeturrrnneedd '' The output should be : `` returned '' I explained it by using splitting the string and loop through the char array , but interviewer d...
private void test ( ) { string s = `` reeeturrrnneeddryyf '' ; StringBuilder sb = new StringBuilder ( ) ; char pRvChar = default ( char ) ; foreach ( var item in s.ToCharArray ( ) ) { if ( pRvChar == item ) { continue ; } pRvChar = item ; sb.Append ( pRvChar ) ; } MessageBox.Show ( sb.ToString ( ) ) ; }
Trimming duplicate characters with single character in string
C#
I 've been thinking recently about the Liskov Substitution Principle and how it relates to my current task . I have a main form which contains a menu ; into this main form I will dock a specific form as a MDI child . This specific form may or may not contain a menu . If it does , I want to merge it with the main menu ....
public class MainForm { public void Dock ( SpecificBaseForm childForm ) { this.Dock ( childForm ) ; if ( childForm is IHaveMenu ) { this.Menu.Merge ( childForm as IHaveMenu ) .Menu ; } } } public interface IHaveMenu { Menu Menu { get ; } } public abstract class SpecificBaseForm { } public class SpecificFormFoo : Specif...
Does one child implementing an interface , but another not , violate the Liskov Substitution Principle ?
C#
I am working on EF . I am trying to insert into a table , the insert function is in a thread . And this is my save data function The above code runs for some time , but after that I encountered an error at u.SaveChanges ( ) ; System.Data.Entity.Core.EntityException : 'An error occurred while closing the provider connec...
private void DataReceivedHandler ( object sender , SerialDataReceivedEventArgs e ) { int bytes = port.BytesToRead ; //string indata = sp.ReadExisting ( ) ; Thread.Sleep ( 50 ) ; try { receivedBytes = port.BaseStream.Read ( buffer , 0 , ( int ) buffer.Length ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message....
EF inserting values in table failed after some time
C#
I have an interesting thought-problem right now , so maybe someone of you could help.Basically what I have is an array of bytes and need to know the order of each individual item in that array - by value . Oh man , i will just show you a small example , i think that will help better : I want to get this as a resultWhat...
byte [ ] array = new byte [ 4 ] { 42 , 5 , 17 , 39 } 4 1 2 3 new byte [ 4 ] { 22 , 33 , 33 , 11 } 2 3 4 1
Get the order of bytes by value
C#
I ’ m having an issue ( probably due to my lack of familiarity of C # generics ) in getting the unclosed type of a generic . I have several methods that look rather similar to the following except for the explicit validator interface in use . The method GetRecursiveBaseTypesAndInterfaces does as it says and gathers all...
public IEnumerable < IDeleteValidator < T > > GetDeleteValidators < T > ( ) { var validatorList = new List < IDeleteValidator < T > > ( ) ; foreach ( var type in GetRecursiveBaseTypesAndInterfaces ( typeof ( T ) ) ) { var validatorType = typeof ( IDeleteValidator < > ) .MakeGenericType ( type ) ; var validators = Objec...
Retrieving the unclosed type of a generic type closing a generic type
C#
Possible Duplicate : Foreach can throw an InvalidCastException ? Consider the following block of codeNotice the cast from Base to DerivedLeft in foreach statement . This compiles fine ( Visual Studio 2010 ) , without any error or even warning.Obviously , on the second loop-iteration we will get an InvalidCastException ...
public class Base { } public class DerivedLeft : Base { } public class DerivedRight : Base { } class Program { static void Main ( string [ ] args ) { List < Base > list = new List < Base > { new DerivedLeft ( ) , new DerivedRight ( ) } ; foreach ( DerivedLeft dl in list ) { Console.WriteLine ( dl.ToString ( ) ) ; } } }
Why does compiler let this slip ?
C#
everyone , I want one application that could control window open and close multi-time . For example , press 1 , open a window ; press 2 , close the window.And there is my code I found , which only could do this once.Could somebody be nice to help me correct it ? Thanks a lot .
public static void Main ( string [ ] args ) { var appthread = new Thread ( new ThreadStart ( ( ) = > { app = new testWpf.App ( ) ; app.ShutdownMode = ShutdownMode.OnExplicitShutdown ; app.Run ( ) ; } ) ) ; appthread.SetApartmentState ( ApartmentState.STA ) ; appthread.Start ( ) ; while ( true ) { var key = Console.Read...
How I re-open WPF window in the same pragrom/application ?
C#
I want to transfer BusinessObjects from one PC to another . If I think about a number of around 40 different object types to transfer the use of many contracts for the different objects would seem to be quite some overload for always the same task : `` Send Object A to Computer B and save object to DB '' ( objects all ...
BinaryFormatter aFormatter = new BinaryFormatter ( ) ; aFormatter.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple ; Object.ParseTypeFromString ( aObjektType ) aObject = aFormatter.Deserialize ( stream ) as Object.ParseTypeFromString ( aObjektType ) ;
How to use a variable as type
C#
I am reading through documents , and splitting words to get each word in the dictionary , but how could I exclude some words ( like `` the/a/an '' ) . This is my function : Also , in this scenario , where is the right place to add .ToLower ( ) call to make all the words from file in lowercase ? I was thinking about som...
private void Splitter ( string [ ] file ) { try { tempDict = file .SelectMany ( i = > File.ReadAllLines ( i ) .SelectMany ( line = > line.Split ( new [ ] { ' ' , ' , ' , ' . ' , ' ? ' , ' ! ' , } , StringSplitOptions.RemoveEmptyEntries ) ) .AsParallel ( ) .Distinct ( ) ) .GroupBy ( word = > word ) .ToDictionary ( g = >...
Excluding words from dictionary
C#
I 'm trying to convert this simple class to IL code : In fact I used ILDasm to know the IL instructions before trying to use Emit to create the class dynamically . The result it shows is : From that , I tried using Emit like this : Now try using it : That means the IL code would be wrong at some point . But comparing i...
public class IL { Dictionary < string , int > props = new Dictionary < string , int > ( ) { { `` 1 '' ,1 } } ; } .class public auto ansi beforefieldinit IL extends [ mscorlib ] System.Object { .field private class [ mscorlib ] System.Collections.Generic.Dictionary ` 2 < string , int32 > props .method public hidebysig s...
Converting simple class to IL failed due to some invalid IL code ?
C#
I would appreciate any help from the PLYNQ experts out there ! I will take time reviewing answers , I have a more established profile on math.SE.I have an object of type ParallelQuery < List < string > > , which has 44 lists which I would like to process in parallel ( five at a time , say ) . My process has a signature...
private ProcessResult Process ( List < string > input ) private struct ProcessResult { public ProcessResult ( bool initialised , bool successful ) { ProcessInitialised = initialised ; ProcessSuccessful = successful ; } public bool ProcessInitialised { get ; } public bool ProcessSuccessful { get ; } } processMe.AsParall...
Possible reasons why ParallelQuery.Aggregate does not run in parallel
C#
I have added a web ref to my .net project which contains the methods for a 3rd party service.When I try to call one of the methods its expecting an OrderIdentifier object to be passed but its giving me the error : InvalidOperationException : < > f__AnonymousType0 ` 3 [ System.DateTime , ETS_OpenAccessNew.ETS.DateRange ...
OrderIdentifier oi = new OrderIdentifier { area = testArea , portfolio = testPortfolio } ; DateRange dr = new DateRange { from = DateTime.Today.AddDays ( -7 ) , to = DateTime.Today } ; var Ai = new AuctionIdentification { Item = DateTime.Today.AddDays ( -1 ) , ItemElementName = ItemChoiceType1.AuctionDate , name = `` t...
Web Service method - can not be serialized because it does not have a parameterless constructor
C#
I am working on the first lab of headfirst C # . I ran into a problem in my program that the dogs go at the same speed . I cant figure out why they do so , because in my eyes every object instance get a random 1 to 5 pixels added to its X location . The randomness of this should make enough of a difference.So because I...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.Drawing ; namespace test { public class Greyhound { public int DogID ; public PictureBox myPictureBox ; public Point StartingPosition ; public Point CurrentPosition ; public Random Randomi...
Dogs go at same speed
C#
Why does this snippet of code produces 60ddd , and this one produces ddd302010 ? Seems like it 's very simple , but I ca n't get my head around it.Please , show me direction in which I can go in order to find a detailed answer.Thanks !
string str = 30 + 20 + 10 + `` ddd '' ; Console.WriteLine ( str ) ; string str = `` ddd '' + 30 + 20 + 10 ; Console.WriteLine ( str ) ;
How does c # string evaluates its own value ?
C#
Is there a way to use value ending with space as XmlPoke value ? When I execute task , value is replaced but without space at the end.Reproduction : test.targets : test.xml : When I run : I get output.xml without space : Is there a way to force XmlPoke to set correct value ( with space at the end ) ?
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Project ToolsVersion= '' 14.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < Target Name= '' Build '' > < Copy SourceFiles= '' test.xml '' DestinationFiles= '' output.xml '' / > < XmlPoke Query= '' /root/elemen...
XmlPoke task trims value
C#
I am wanting to trim any white space off a collection of strings . I used the following code but it does n't seem to work . Could anyone explain why ?
result.ForEach ( f = > f = f.Trim ( ) ) ;
Do n't understand why the ForEach command is n't working
C#
This question is somewhat an illustration to a related post , I believe the example below describes the essence of the problem.Is n't it bad that the second call to GetData raises exception only because GetData received a parameter cast to dynamic ? The method itself is fine with such argument : it treats it as a strin...
class Program { public static IList < string > GetData ( string arg ) { return new string [ ] { `` a '' , `` b '' , `` c '' } ; } static void Main ( string [ ] args ) { var arg1 = `` abc '' ; var res1 = GetData ( arg1 ) ; Console.WriteLine ( res1.Count ( ) ) ; dynamic arg2 = `` abc '' ; var res2 = GetData ( arg2 ) ; tr...
Bad interoperability between static and dynamic C #
C#
I am writing an IComparer < T > implementation by deriving from the Comparer < T > class , as recommended by MSDN . For example : However , under this approach , the MyComparer class inherits the Default and Create static members from the Comparer < T > class . This is undesirable , since the implementation of the said...
public class MyComparer : Comparer < MyClass > { private readonly Helper _helper ; public MyComparer ( Helper helper ) { if ( helper == null ) throw new ArgumentNullException ( nameof ( helper ) ) ; _helper = helper ; } public override int Compare ( MyClass x , MyClass y ) { // perform comparison using _helper } } // c...
Should derived classes hide the Default and Create static members inherited from Comparer < T > ?
C#
Is there a difference between these two implementations ? 1 :2 : The first one seems to be more correct than the second in regards to memory leaks . But is it really correct ?
public class SMSManager : ManagerBase { private EventHandler < SheetButtonClickEventArgs > _buttonClickevent ; public SMSManager ( DataBlock smsDataBlock , DataBlock telephonesDataBlock ) : base ( smsDataBlock ) { _buttonClickevent = new EventHandler < SheetButtonClickEventArgs > ( OnButtonClick ) ; SheetEvents.ButtonC...
Difference between two dispose implementations ?