lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
We need to write some logs in our code . The logs are being written via a network request which logs some info ( the logger is an Http-API module ) , But we do n't want to break the whole flow if there 's an exception in the API.I do n't to use Task.Run for this kind of operation , because it 's bad.But then I thought ...
private static readonly HttpClient client = new HttpClient ( ) ; void Main ( ) { Console.WriteLine ( 1 ) ; async Task LogMe ( ) { var response = await client.PostAsync ( `` http : //www.NOTEXISTS.com/recepticle.aspx '' , null ) ; var responseString = await response.Content.ReadAsStringAsync ( ) ; //response.EnsureSucce...
Non awaitable as `` fire & forget '' - is it safe to use ?
C#
In some obscure way a derived class which does n't add new functionality ( yet ) behaves different from it 's base class . The derived class : MyCheckButton inherits from a ( GTK # , part of the Mono project ) CheckButton . However in the following code snippet they behave differently : The underscore in the label make...
public class MyCheckButton : CheckButton { public MyCheckButton ( string label ) : base ( label ) { } } var button1 = new CheckButton ( `` _foo '' ) ; var button2 = new MyCheckButton ( `` _foo '' ) ; // code omitted
Why does this derived class behave different from it 's base class
C#
My situation : This gives me an error : Can not cast expression of type 'T ' to type 'T2 ' ( or Can not convert type 'T ' to 'T2 ' ) I understand that it is because neither T or T2 are constrained with class , but if I know - due to IsAssignableFrom - that I can use T where I need T2 , how can I convince compiler to al...
interface ISomeInterface { void DoSmth < T > ( T other ) ; } class Base : ISomeInterface { public virtual void DoSmth < T > ( T other ) { // for example do nothing } } class Derived < T2 > : Base { Action < T2 > MyAction { get ; set ; } public override void DoSmth < T > ( T other ) { if ( typeof ( T2 ) .IsAssignableFro...
Unconstrained type parameters casting
C#
I initialize a property within the Controller 's Constructor.I have an Action Method which reset the property again on a button click event.Following javascript code is in my view which is called when the button is clicked.My problem is when I click the button , value of property changes in the Controller . But it does...
public BookController ( ) { SessionProvider.SessionLoadSceanrio = false ; } public ActionResult LoadScenario ( int bookId ) { SessionProvider.SessionLoadSceanrio = true ; // remaining code return Json ( ScenarioId , JsonRequestBehavior.AllowGet ) ; } var BookHandler = { $ ( `` # btnLoadScen '' ) .click ( function ( e )...
C # property value does n't get modified within Javascript/ jquery
C#
Can I have two same function name with same parameters but different meaning.For example : Thank you .
public void test ( string name ) public void test ( string age )
function overload
C#
When implementing the INotifyPropertyChanged interface in its most basic form , most people seem to implement it like this : :My question is : Why the extra assignment of var propertyChanged = PropertyChanged ; ? Is it just a matter of preference , or is there a good reason for it ? Surely the following is just as vali...
public virtual void OnPropertyChanged ( string propertyName ) { var propertyChanged = PropertyChanged ; if ( propertyChanged ! = null ) { propertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public virtual void OnPropertyChanged ( string propertyName ) { if ( PropertyChanged ! = null ) { Prope...
INotifyProperyChanged - why the extra assignment ?
C#
Caution , before You read the restThis question is not about POST method , redisplaying view with submited form or binding input values to controller method parameters . It 's purely about rendering the View using html helper ( HiddenFor or Hidden - both returns the same ) .I created a simple hidden field using HiddenF...
@ Html.HiddenFor ( m = > m.ProductCode ) < input id= '' productCode '' name= '' productCode '' type= '' hidden '' value/ > < input id= '' productCode '' name= '' productCode '' type= '' hidden '' value= '' 8888888 '' / > @ Html.HiddenFor ( m = > m.ProductCode ) @ Html.HiddenFor ( m = > m.ProductCode ) public class Prod...
MVC @ Html.HiddenFor renders html form with no value
C#
I have written a user control , MenuItem , which inherits from a Form Label.I have a backgroundworker thread whose IsBusy property is exposed through a property in the MainForm as IsBackgroundBusy.How do I read this property from the MenuItem usercontrol ? I am currently using Application.UseWaitCursor and I set that i...
public partial class MainForm : Form { public bool IsBackgroundBusy { get { return bwRefreshGalleries.IsBusy ; } } public partial class MenuItem : Label { private bool _disableIfBusy = false ; [ Description ( `` Change color if Application.UseWaitCursor is True '' ) ] public bool DisableIfBusy { get { return _disableIf...
How do I read a property from my main form in a user control
C#
Here is the code example : Now , if there was an exception inside of loggingProvider.ReadLogs ( ) method , it will be caught and traced . But if , for example , there is no ParticipantObjects [ 0 ] , this exception wo n't be caught and traced here . It seems that it has something to do with lambda expressions and closu...
public IList < LogEntry > ReadLogs ( Guid id , string name ) { var logs = this.RetrieveLogs ( id , name ) ; if ( logs ! = null ) { foreach ( LogEvent logEvent in logs ) { // bla , bla , bla } } return logEntries ; } private IEnumerable < LogEvent > RetrieveLogs ( Guid id , string name ) { try { FilterCriteria filterCri...
Why was exception not caught within the closure ?
C#
I have a to rewrite a part of an existing C # /.NET program using Java . I 'm not that fluent in Java and am missing something handling regular expressions and just wanted to know if I 'm missing something or if Java just does n't provide such feature.I have data likeThe Regex pattern I 'm using looks like : In .NET I ...
2011:06:05 15:50\t0.478\t0.209\t0.211\t0.211\t0.205\t-0.462\t0.203\t0.202\t0.212 ? ( \d { 4 } : \d { 2 } : \d { 2 } \d { 2 } : \d { 2 } [ : \d { 2 } ] ? ) \t ( ( - ? \d* ( \.\d* ) ? ) \t ? ) { 1,16 }
Regex Captures in Java like in C #
C#
I have a RavenDB 3.5 collection `` Municipalities '' with documents structured like this : Note that the districts property can also be null.Now I 'm working on a typehead feature where you can search for both municipality names and district names . So I want to ( wildcard all ) query over both fields and also get back...
{ `` Name '' : ... , ... , `` Districts '' : [ { `` Name '' : ... , ... } ] }
How to do a RavenDB query over multiple ( complex structure ) fields and return the matched values ?
C#
Suppose I have a struct with just one field : This works great , until I want to do stuff like this : So , I implemented IEquatable < in T > and IComparable < in T > , but that still did n't enable any operators ( not even == , < , > = , etc . ) .So , I started providing operator overloads.For example : This worked , h...
public struct Angle { public static readonly double RadiansPerDegree = Math.PI / 180 ; private readonly double _degrees ; public Angle ( double degrees ) { _degrees = degrees ; } public double Degrees { get { return _degrees ; } } public double Radians { get { return _degrees * RadiansPerDegree ; } } public static Angl...
Do I have to define every single operator ?
C#
I 'm trying to implement a strategy pattern to allow me to allow me to apply some `` benefit '' to an `` account '' . In the code below , I ca n't add my implementation of an interface to a dictionary expecting the interface . I think it 's some kind of contravariance problem , but it feels like I should be able to do ...
void Main ( ) { var provider = new BenefitStrategyProvider ( ) ; var freeBenefit = new FreeBenefit ( ) ; var strategy = provider.GetStrategy ( freeBenefit ) ; strategy.ApplyBenefit ( freeBenefit , new Account ( ) ) ; } public class BenefitStrategyProvider { private Dictionary < Type , IBenefitStrategy < BenefitBase > >...
Invariant inheritance problem
C#
Can someone tell me if or what the difference of the following statements is : whenever I press += the first choice pops up when I click tab so I 've always left it . but I 'm wondering if I can just write the second . I 'm guessing that they both get compiled the same , but I 'm curious if that 's true . I 'm pretty s...
MyObject.MyEvent += new EventHandler ( MyEventHandlerMethod ) ; vs.MyObject.MyEvent += MyEventHandlerMethod ;
adding an event handler
C#
I have a methodwhich , very descriptively , executes some work on a remote machine by : Queueing a message on a message bus signalling that work should be doneA remote agent picks up the message and executes the workThe work finishes and the agent queues a message on a message bus to say that the work is doneThe applic...
public Task < Task > DoSomeWorkOnARemoteMachine ( ) await await DoSomeWorkOnARemoteMachine ( ) ; await DoSomeWorkOnARemoteMachine ( ) ;
Is there a way to know if a Task is being awaited ?
C#
I am making my first attempt at using threads in an application , but on the line where I try to instantiate my thread I get the error 'method name expected ' . Here is my code :
private static List < Field.Info > FromDatabase ( this Int32 _campId ) { List < Field.Info > lstFields = new List < Field.Info > ( ) ; Field.List.Response response = new Field.List.Ticket { campId = _campId } .Commit ( ) ; if ( response.status == Field.List.Status.success ) { lstFields = response.fields ; lock ( campId...
threading question
C#
I am testing the Extreme Optimization C # library , precisely the nonlinear system solvers.As an example I find that I have to pass the solver the nonlinear system in the following shape : The problem is that the system I try to solve can not be specified at design time . It is a nonlinear system composed by the load f...
Func < Vector , double > [ ] f = { x = > Math.Exp ( x [ 0 ] ) *Math.Cos ( x [ 1 ] ) - x [ 0 ] *x [ 0 ] + x [ 1 ] *x [ 1 ] , x = > Math.Exp ( x [ 0 ] ) *Math.Sin ( x [ 1 ] ) - 2*x [ 0 ] *x [ 1 ] } ; For ( int i=0 ; i < n ; i++ ) { double A=0.0 ; double B=0.0 ; For ( int j=0 ; j < n ; j++ ) { A+= G [ i , j ] *Math.Cos ( ...
Define a function dynamically
C#
I 'm working on some customized authentication code based on Microsoft 's membership stuff . While looking into the Profile functionality , I looked into the ProfileBase class found in System.Web.dll v4.0.30319 . There are a few class level variables that are declared as a type but then and then initialized to a null v...
private static Exception s_InitializeException = ( Exception ) null ; private static ProfileBase s_SingletonInstance = ( ProfileBase ) null ; private static Hashtable s_PropertiesForCompilation = ( Hashtable ) null ;
Microsoft is casting null to a type , should I ?
C#
I am creating an MVC application where I am sending an email to JIRA . I initially had it working when I had the ModelType in the view just IssueTable , but when I changed it too ModelType ViewModelClass.ViewModel it stopped working correctly.In the controller : In the view : This initially worked but I needed to have ...
Public Function SubmitIssue ( issuetable As IssueTable , test As IssueTracker.ClientUserProjectIssue ) As ActionResultDim mail As New MailMessage ( ) mail.Subject = issuetable.IssueSummaryDim body As String = test.iTable.IssueDescriptionmail.Body = bodysmtp.Send ( mail ) @ ModelType IssueTable @ Html.EditorFor ( Functi...
Null value error when trying to make viewmodel item equal variable
C#
I 'd like to animate a Button 's Background if the Mouse is over the Button.The Button 's Background is bound to a custom dependency property I 've created in the Code Behind of my UserControlNow if I try to animate the Button 's background by usingI get an exception that says : can not animate an immutable property ( ...
... Background= '' { Binding BGColor , Elementname= '' QButton '' } '' < Trigger Property= '' IsMouseOver '' Value= '' True '' > < Trigger.EnterActions > < BeginStoryboard > < Storyboard > < ColorAnimation To= '' LightBlue '' Duration= '' 0:0:2 '' Storyboard.TargetProperty= '' Background.Color '' / > < /Storyboard > < ...
UserControl Animate Button 's Background
C#
I 'm working on programming a basic media player , and I 'm having some trouble writing polymorphic code , which is something I 've studied , but never actually implemented before.There are four relevant classes : MediaInfo , MovieInfo , Media , and Movie . MediaInfo is an abstract base class that holds information rel...
protected MediaInfo info ; protected MovieInfo info ; this.info = new MovieInfo ( path ) ; /// < summary > /// Gets the frame height of the movie file./// < /summary > public string FrameHeight { get { return this.info.FrameHeight ; } }
Polymorphism : Deriving from a protected member in a base class ?
C#
UPDATE May this post be helpful for coders using RichTextBoxes . The Match is correct for a normal string , I did not see this AND I did not see that `` ä '' transforms to `` \e4r '' in the richTextBox.Rtf ! So the Match.Value is correct - human error.A RegEx finds the correct text but Match.Value is wrong because it r...
String example_text = `` < em > Primär-ABC < /em > '' ; Regex em = new Regex ( @ '' < em > [ ^ < ] * < /em > '' ) ; Match emMatch = em.Match ( example_text ) ; //Works ! Match emMatch = em.Match ( richtextBox.RTF ) ; //Fails ! while ( emMatch.Success ) { string matchValue = emMatch.Value ; Foo ( matchValue ) ... }
Match.Value and international characters
C#
I am using ASP.NET MVC and EF to create a vehicle reservation app in which a user will be able to reserve multiple vehicles for one datetime , if they want . I created a stored procedure to prevent double booking of vehicles , but am having trouble figuring out how to add the results to a list . Example : I want to res...
public ActionResult Create ( [ Bind ( Include = `` ID , StartDate , EndDate , RequestorID , Destination , PurposeOfTrip , TransportStudentsFG , LastChangedBy , LastChangedDate , VehicleList , ThemeColor '' ) ] Reservations reservation ) { if ( ModelState.IsValid ) { var selectedVehicles = reservation.VehicleList.Where ...
How do I create a list from stored procedure results Entity Framework
C#
I have a feature that I only want to happen on Debug , but do not want to ship the dll 's that this feature requires . Is that possible to do ? I have : Of course MyAssembly is being referenced by the project . I would like MyAssembly.dll to not be shipped on a release mode . Can that be achieved ? Will using Condition...
# if DEBUGusing MyAssembly ; # endif
C # using statement inside # if DEBUG but not ship assembly
C#
I am using a fairly simple DI pattern to inject my data repository into my controller classes , and I 'm getting the CA2000 code analysis warning ( Dispose objects before losing scope ) on every one of them . I know why the warning is happening , and can usually figure out how to fix it , but in this case I can not fig...
public class AccountController : Controller { public AccountController ( ) : this ( new SqlDataRepository ( ) ) { } public AccountController ( IDataRepository db ) { this.db = db ? ? new SqlDataRepository ( ) ; // Lots of other initialization code here that I 'd really like // to avoid duplicating in the other construc...
CA2000 and Dependency Injection
C#
In C # and its cousin languages , we always useBut you can also use ( I found this out only recently and while fooling around with the compiler ) I do not have any formal training in programming and everything is self-tought . I have been using { get ; set ; } without any thought just like we use 1 + 1 = 2 Is the order...
public string SomeString { get ; set ; } public string SomeString { set ; get ; }
Using { set ; get ; } instead of { get ; set ; }
C#
I have an interface with methods annotated with the Pure attribute from System.Diagnostics.Contracts : I wish to iterate over the members of the interface and check if the member is pure or not.Currently I 'm not able to get any attributes from the member info : What am I missing ? Note that I do not have a class or an...
public interface IFoo < T > { [ Pure ] T First { get ; } [ Pure ] T Last { get ; } [ Pure ] T Choose ( ) ; void Add ( T item ) ; T Remove ( ) ; } var type = typeof ( IFoo < > ) ; var memberInfos = type.GetMembers ( ) ; var memberInfo = memberInfos.First ( ) ; // < -- Just select one of themvar attributes = memberInfo.G...
Check if Generic Interface Member is `` Pure '' ( has Pure Attribute )
C#
I need to process a list of records returned from a service.However the processing algorithm for a record changes completely based on a certain field on the record.To implement this , I have defined an IProcessor interface which has just one method : And I have two concrete implementations of IProcessor for the differe...
public interface IProcessor { ICollection < OutputEntity > Process ( ICollection < InputEntity > > entities ) ; } public class Engine { public void ProcessRecords ( IService service ) { var records = service.GetRecords ( ) ; var type1Records = records.Where ( x = > x.SomeField== `` Type1 '' ) .ToList ( ) ; var type2Rec...
How to implement usage of multiple strategies at runtime
C#
I have the following code : If I try this it throws an error : Can not convert bool ? to boolHaving searched for this this I 'm not sure why the error is thrown , where as it will allow me to doWhy am I unable to use .Any ( ) in this case - why is it classed as a nullable bool yet the count is n't a nullable int ?
if ( Model.Products ? .Cards ? .Any ( ) ) { } if ( Model.Products ? .Cards ? .Count > 0 ) { }
Why is ? .Any ( ) classed as a nullable bool ?
C#
Is it possible to use one AdControl in a Windows 8.1 app with multiple AdUnitIds ? I followed the approach from different sources on the net to get the AdControl somewhat working , but now I 've found out ( after adding an event handler to the AdControls ErrorOccurred event ) that the error code is NoAdAvailable , mean...
AdControl adControl = new AdControl { ApplicationId = `` a1b2c3d4-1a2a-1234-1a2a-1a2b3c4d5e6f '' , AdUnitId = `` 123456 '' , HorizontalAlignment = HorizontalAlignment.Left , Height = 250 , VerticalAlignment = VerticalAlignment.Top , Width = 250 } ; adControl.ErrorOccurred += adControl_ErrorOccurred ;
How can I use an AdControl with multiple AdUnitIds ?
C#
This is confusing to me please expalin me the behaviour of this ? A declaration of a new member hides an inherited member only within the scope of the new member.CopyIn the example above , the declaration of F in Derived hides the F that was inherited from Base , but since the new F in Derived has private access , its ...
**class Base { public static void F ( ) { } } class Derived : Base { new private static void F ( ) { } // Hides Base.F in Derived only } class MoreDerived : Derived { static void G ( ) { F ( ) ; } // Invokes Base.F } **
c # hiding confusion
C#
I have the following piece of codes.When executed , the assertion passed . However , the assertion failed when the constructor for Reg class is disabled . On a closer look , I 've found that the implicit constructor of Reg class is called before Main ( ) . If the constructor of Reg class is explicitly defined , it will...
class Program { static void Main ( string [ ] args ) { Enterprise.Initialize ( `` Awesome Company '' ) ; // Assertion failed when constructor of 'Reg ' class is disabled . Debug.Assert ( Reg.Root == @ '' Software\Awesome Company '' ) ; } } public static class Enterprise { // Static Properties . public static string Com...
Implicit static constructor called before Main ( )
C#
I have a List of custom a datatype , simplified example ( myMovies ) : Now I am trying to remove all duplicates from myMovies but ignoring TVIndex.I have tried looking at But can not figure out how to ignore TvIndex . Is this possible ?
public class Movie { public Int32 TVIndex ; public string MovieName ; public string MovieRating ; public string MovieRuntime ; public List < Actor > MovieActors ; public List < MovieArt > MovieImages ; } public class Actor { public string ActorName ; public string ActorRole ; } public class MovieArt { public string Ima...
Select distinct from List < t > ignoring one element
C#
If I use the Resharper code cleanup function , I 'm finding my code ... is changed to ... But then Resharper makes a suggestion `` To extension method invocation '' for the Enumerable.ToList so the code goes back to ... I 've checked in the Resharper code editing options , but I ca n't see where/how I can stop this tog...
var personInfos = persons.Select ( Mapper.Map < PersonInfo > ) .ToList ( ) ; var personInfos = Enumerable.ToList ( persons.Select ( Mapper.Map < PersonInfo > ) ) ; var personInfos = persons.Select ( Mapper.Map < PersonInfo > ) .ToList ( ) ;
How to stop Resharper toggling between Enumerable.ToList and Select suggestion
C#
Is there a way to get MVC4 to call different actions based on a GET variable in the URL ? For example , let 's say I have the following two actions.Is there a way I can use the following URLs to have MVC4 'choose ' which action to call ? UPDATE : I am very much aware that I can use actions / urls the way they are , and...
[ HttpPost ] public ActionResult SubmitCrash ( CrashReport rawData ) { return View ( ) ; } [ HttpPost ] public ActionResult SubmitBug ( BugReport data ) { return View ( ) ; } http : //MySite/Submit ? Crash ( calls 'SubmitCrash ' ) http : //MySite/Submit ? Bug ( calls 'SubmitBug ' )
Different MVC4 action based on GET variable
C#
Sample program below : This sample program represents the interfaces my actual program uses , and demonstrates the problem I 'm having ( commented out in FakeRepository ) . I would like for this method call to be generically handled by the base class ( which in my real example is able to handle 95 % of the cases given ...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace GenericsTest { class Program { static void Main ( string [ ] args ) { IRetrievable < int , User > repo = new FakeRepository ( ) ; Console.WriteLine ( repo.Retrieve ( 35 ) ) ; } } class User { public int Id { get ; set ; ...
Can you explain this generics behavior and if I have a workaround ?
C#
I 'm stuck at this problem I would really appreciate if someone can help me solve this problem.I want to add spaces for sub-folder like this format down below . ( it must be done with recursion ) I want to add spaces for sub-folder like this format down below . ( itmust be done with recursion )
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.IO ; namespace G14_211115 { class Program { static void Main ( string [ ] args ) { string path = @ '' C : \Program Files\FinchVPN '' ; WriteDirectories ( path ) ; Console.ReadKey ( ) ; }...
Start new line with spaces
C#
What happens behind the curtains when I include a function into my compiled query , like I do with DataConvert.ToThema ( ) here to convert a table object into my custom business object : and call it like thisApparently the function is not translated in to SQL or something ( how could it ) , but it also does not hold wh...
public static class Queries { public static Func < MyDataContext , string , Thema > GetThemaByTitle { get { var func = CompiledQuery.Compile ( ( MyDataContext db , string title ) = > ( from th in elan.tbl_Thema where th.Titel == title select DataConvert.ToThema ( th ) ) .Single ( ) ) ; return func ; } } } public static...
including `` offline '' code in compiled querys
C#
I 've just started using C # 4.0 ( RC ) and come up with this problem : Note , I 've never tried this actual code , but I 've just looked at the results of doing GetConstructor using debugging in VS2010This is perfect for the two first classes ( 1 and 2 ) , the first one prints an actual ConstructorInfo-object 's name ...
class Class1 { public Class1 ( ) { } } class Class2 { public Class2 ( string param1 ) { } } class Class3 { public Class3 ( string param1 = `` default '' ) { } } Type [ ] types = new Type [ ] { typeof ( Class1 ) , typeof ( Class2 ) , typeof ( Class3 ) } ; // Problem starts here , main-methodfor ( int i = 0 ; i < types.L...
Reflecting constructors with default values in C # 4.0
C#
I have an application that loads a list of client/matter numbers from an input file and displays them in a UI . These numbers are simple zero-padded numerical strings , like `` 02240/00106 '' . Here is the ClientMatter class : I 'm using MVVM , and it uses dependency injection with the composition root contained in the...
public class ClientMatter { public string ClientNumber { get ; set ; } public string MatterNumber { get ; set ; } } public interface IMatterListLoader { IReadOnlyCollection < string > MatterListFileExtensions { get ; } IReadOnlyCollection < ClientMatter > Load ( FileInfo fromFile ) ; } public sealed class ExcelMatterLi...
Using abstraction and dependency injection , what if implementation-specific details need to be configurable in the UI ?
C#
Sometimes back I was trying the following statement in C # Does space has impact in expressions ? In what way the above statements are different ? Ramachandran
i+++++i // does not compile < bt > i++ + ++i // executed
Does C # has impact when evaluating /parsing expressions ?
C#
Hi , I have a problem with getting data from youtube xml : address of youtube xml : http : //gdata.youtube.com/feeds/api/videos ? q=keyword & orderby=viewCountI try this , but the program does n't go into the linq inquiry.Anyone has idea , how to solve this ? Thanks !
key = @ '' http : //gdata.youtube.com/feeds/api/videos ? q= '' +keyword+ @ '' & orderby=viewCount '' ; youtube = XDocument.Load ( key ) ; urls = ( from item in youtube.Elements ( `` feed '' ) select new VideInfo { soundName = item.Element ( `` entry '' ) .Element ( `` title '' ) .ToString ( ) , url = item.Element ( `` ...
How to get data from xml , by linq , c #
C#
I 've a filename : How can i split the above filename to 4 string groups . I tried : but i 'm not getting the above required four strings
NewReport-20140423_17255375-BSIQ-2wd28830-841c-4d30-95fd-a57a7aege412.zip NewReport20140423_17255375BSIQ2wd28830-841c-4d30-95fd-a57a7aege412.zip string [ ] strFileTokens = filename.Split ( new char [ ] { '- ' } , StringSplitOptions.None ) ;
Splitting a filename
C#
I am using Linux containers on the latest Windows build Windows 10 2004 and enabled WSL 2 and Docker Desktop 2.3.0.3 ( 45519 ) .I right click the docker-compose file , and select Set as Startup Project.I then hit F5 to debug.I can see the image running with docker ps however breakpoints are not being hit.I can not view...
It was not possible to find any compatible framework versionThe framework 'Microsoft.AspNetCore.App ' , version ' 3.1.0 ' was not found . - No frameworks were found.You can resolve the problem by installing the specified framework and/or SDK.The specified framework can be found at : - https : //aka.ms/dotnet-core-appla...
Unable to debug dotnet core GenericHost docker container
C#
I am trying to understand how inheritance works in C # . I wrote the following code : The CIL ( Common Intermediate Language ) code for the Main ( ) looks like the following : The lines in CIL that are troubling me are : After the castclass of animal to Dog type the code executes dog.OverRideMe ( ) ; . This is translat...
class Program { static void Main ( string [ ] args ) { Animal animal = new Dog ( ) ; animal.OverRideMe ( ) ; //animal.NewMethod ( ) ; Dog dog = ( Dog ) animal ; dog.OverRideMe ( ) ; dog.NewMethod ( ) ; Console.Read ( ) ; } } public abstract class Animal { public Animal ( ) { Console.WriteLine ( `` Base Constructor '' )...
Regarding Inheritance C #
C#
I try to use trial version of third party software written C # .While I try to use its API , I face up with a strange problem.I am using visual studio 2015 and I found an interesting extended method signature in their API-SDKThe second parameter type is not exist.Never seen before in C # . I try to give a generic Objec...
public static class CallExtendedInfoEx { public static void AddToSIPMessage ( this CallExtendedInfo info , msg ) ; } IL_0073 : call void [ CallExtendedInfoEx : :AddToSIPMessage ( class [ VoIP.CallExtendedInfo , class [ VoIPSDK ] '' . '' )
Method Parameter Without A Parameter Type In C #
C#
You can only have one View per class name in the DisplayTemplates folder as the class name is used as the name of the view.cshtml file.However , you can have two classes in a solution with the same name if they appear in different namespaces : Both try to use the DisplayTemplate defined by view : However in the view fi...
MyNamespace.Class1MyOtherNamespace.Class1 Class1.cshtml @ model MyNamespace.Class1
How to handle MVC DisplayTemplates for two classes with the same name ( different namespaces )
C#
I have many strings with numbers.I need to reformat the string to add commas after all number sequences.Numbers may sometimes contain other characters including 12-3 or 12/4e.g . `` hello 1234 bye '' should be `` hello 1234 , bye '' '' 987 middle text 654 '' should be `` 987 , middle text 654 , '' '' 1/2 is a number co...
private static string CommaAfterNumbers ( string input ) { string output = null ; string [ ] splitBySpace = Regex.Split ( input , `` `` ) ; foreach ( string value in splitBySpace ) { if ( ! string.IsNullOrEmpty ( value ) ) { if ( int.TryParse ( value , out int parsed ) ) { output += $ '' { parsed } , '' ; } else { outp...
C # Add comma after every number sequence in string
C#
I 'm calling the following two lines . The second line crashes . : However , if I modify the values to not have ' , ' characters and remove the NumberStyles enum it works . e.g.Am I doing something wrong ? Is this a known issue ? Is there an acceptable work-around that does n't involve hacky string manipulation ? edit ...
var a = long.Parse ( `` 2,147,483,648 '' , NumberStyles.AllowThousands ) ; var b = long.Parse ( `` -2,147,483,648 '' , NumberStyles.AllowThousands ) ; var a = long.Parse ( `` 2147483648 '' ) ; var b = long.Parse ( `` -2147483648 '' ) ;
Why does NumberStyles.AllowThousands cause an exception when passing a negative number ?
C#
i have following caseI have added a quickwatch in debug to some fields in my case : And now the strange behaviour also from quickwatch and of course the resultSo the addition of 8.39 + -0.49 does n't give me 7.9 but 8.39This code was running for 600k cases on at least two i had this behaviour the others behaved well . ...
beleg.PreisDB = ( double ? ) orders.Where ( x = > x.orderId == beleg.auftrnr ) .Sum ( x = > x.itemPrice + x.shippingPrice + x.giftWrapPrice ) ? ? 0 ; beleg.PreisCouponDB = ( double ? ) orders.Where ( x = > x.orderId == beleg.auftrnr ) .Sum ( x = > x.itemPromotionDiscount + x.shipPromotionDiscount ) ? ? 0 ; var gesamtPr...
Addition in C # .net does n't work in some cases
C#
I have business models named Product and Category like below in which I add the validations : For the view model I have created something like this : A friend of mine suggested keeping all the validations in the view model and mapping all the properties of the business model in the view model like this : I asked him th...
public class Product { public int ProductId { get ; set ; } [ Required ] [ StringLength ( 25 ) ] public string Name { get ; set ; } public string Description { get ; set ; } public int CategoryId { get ; set ; } } public class Category { public int CategoryId { get ; set ; } public string Name { get ; set ; } } public ...
What should be in my View Models ?
C#
I 'm having trouble with the Random class in .NET , I 'm implementing a threaded collection which is working fine , except for one smaller detail . The collection is a Skip list and those of you familiar with it know that for every node inserted I need to generate a new height that is < = CurrentMaxHeight+1 , here 's t...
int randomLevel ( ) { int height = 1 ; while ( rnd.NextDouble ( ) > = 0.5 & & height < MaxHeight ) ++height ; return height ; }
Problem with Random and Threads in .NET
C#
I have defined an interface in F # I would like other apps in the same appdomain to implement it so that I can call Update on any that implement the interface ( I gather the implementations in an TinyIoC container ) . The return type Async < bool > can indicate if the update succeeded or not without having to wait for ...
type IConnect = abstract Update : seq < DataType > - > Async < bool >
How to define an async f # interface that can be implemented in c # ?
C#
Is it possible to call a throwing C # function from a C++ call in a C # app such that the C++ stack is unwound properly ? Is there any documentation of this ? For example , please consider this C # code : Along with this C++ code : I tried this out , and the C # exception was caught successfully , but releasesResourceO...
using System ; public class Test { public static void CalledFromCpp ( ) { throw new Exception ( `` Is this safe ? Is C++ stack unwound properly ? `` ) ; } public static void Main ( ) { try { CppFunc ( CalledFromCpp ) ; } catch ( Exception e ) { Console.Writeline ( `` Exception e : { 0 } '' , e ) ; } } [ UnmanagedFuncti...
How to call a throwing C # function from C++ in a C # app such that the C++ stack is unwound properly ?
C#
I got some old LED board to which you 'd send some text and hang it up somewhere ... it was manufactured in 1994/95 and it communicates over a serial port , with a 16-bit MS-DOS application in which you can type in some text.So , because you probably could n't run it anywhere except by using DOSBox or similar tricks , ...
02 86 04 0F 05 03 01 03 01 03 01 03 00 01 03 00 ... ... ... ... ... 00 31 00 32 00 33 00 20 00 20 00 20 00 20 00 20 .1.2.3. . . . . 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 . . . . . . . . 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 . . . . . . . . 00 20 00 20 00 20 00 20 00 20 00 FE 03 01 03 01 . . . . . .þ...
How would I reverse this simple-looking algorithm ?
C#
Is it possible to compare two objects without knowing their boxed types at compile time ? For instance , if I have a object { long } and object { int } , is there a way to know if the boxed values are equal ? My method retrieves two generic objects , and there 's no way to know what their inner types are at compile tim...
_keyProperties [ x ] .GetValue ( entity , null ) .Equals ( keyValues [ x ] )
Compare boxed objects in C #
C#
Problem : return all records where Jon Doe = < bus_contact > OR < bus_sponsor > .Current code returns record 1 , so what modifications are required to return records 1 and 2 using just one query ? .XMLC # Edit : This is not exactly the same problem as pointed out in the possible duplicate link . Yes , it partially refe...
< root > < row > < project_id > 1 < /project_id > < project_name > Name1 < /project_name > < bus_contact > Jon Doe < /bus_contact > < bus_sponsor > Bruce Wayne < /bus_sponsor > < /row > < row > < project_id > 2 < /project_id > < project_name > Name2 < /project_name > < bus_contact > Peter Parker < /bus_contact > < bus_...
How to add OR condition in LINQ while querying XML ?
C#
I have about 20 functions with almost the same pattern , i run on array of Sites , create SiteOperation with Site object and perform some operation ( in this case with one param but sometimes there are none or more ) Is it possible to wrap this code , so i will just send action to lets say _sitesManagement which will r...
int wantedBandwidthInLBps = 2048 / 8 ; foreach ( Sites site in _sitesManagement.GetAll ( ) ) { SiteOperation siteOperation = new SiteOperation ( site ) ; siteOperation.LimitBandwidth ( wantedBandwidthInLBps ) ; } foreach ( Sites site in _sitesManagement.GetAll ( ) ) { SiteOperation siteOperation = new SiteOperation ( s...
similar function refactoring pattern
C#
Failed : I wish to know what is happening behind the scenes in ToString ( ) etc to cause this behavior.EDIT After seeing Jon 's Answer : Result : Same result with capital and small ' o ' . I 'm reading up the docs , but still unclear .
[ Test ] public void Sadness ( ) { var dateTime = DateTime.UtcNow ; Assert.That ( dateTime , Is.EqualTo ( DateTime.Parse ( dateTime.ToString ( ) ) ) ) ; } Expected : 2011-10-31 06:12:44.000 But was : 2011-10-31 06:12:44.350 [ Test ] public void NewSadness ( ) { var dateTime = DateTime.UtcNow ; Assert.That ( dateTime , ...
What is causing this behavior , in our C # DateTime type ?
C#
I am instantiating a List < T > of single dimensional Int32 arrays by reflection . When I instantiate the list using : I see this strange behavior on the list itself : If I interface with it through reflection it seems to behave normally , however if I try to cast it to its actual type : I get this exception : Unable t...
Type typeInt = typeof ( System.Int32 ) ; Type typeIntArray = typeInt.MakeArrayType ( 1 ) ; Type typeListGeneric = typeof ( System.Collections.Generic.List < > ) ; Type typeList = typeListGeneric.MakeGenericType ( new Type [ ] { typeIntArray , } ) ; object instance = typeList.GetConstructor ( Type.EmptyTypes ) .Invoke (...
Unable to cast List < int [ * ] > to List < int [ ] > instantiated with reflection
C#
I 've just seen a video-class by Jon Skeet , where he talks about unit testing asynchronous methods . It was on a paid website , but I 've found something similar to what he says , in his book ( just Ctrl+F `` 15.6.3 . Unit testing asynchronous code '' ) .The complete code can be found on his github , but I have simpli...
public static class LoginTest { private static TaskCompletionSource < Guid ? > loginPromise = new TaskCompletionSource < Guid ? > ( ) ; public static void Main ( ) { Console.WriteLine ( `` == START == '' ) ; // Set up var context = new ManuallyPumpedSynchronizationContext ( ) ; // Comment this SynchronizationContext.Se...
Was ManuallyPumpedSynchronizationContext required in Jon Skeet 's `` TimeMachine '' async unit test framework ?
C#
I have the following piece of code : But the stringBuilder appends text MyNamespace.MyClass+CD instead of A or X . Why does this happen ?
delegate string CD ( ) ; void MyFunction ( ) { stringBuilder.Append ( ( CD ) delegate ( ) { switch ( whatever ) { case 1 : return `` A '' ; ... default : return `` X '' ; } } ) ; }
Anonymous function not returning the correct string
C#
I need to make a connection to an API using a complicated authentication process that I do n't understand.I know it involves multiple steps and I have tried to mimic it , but I find the documentation to be very confusing ... The idea is that I make a request to an endpoint which will return a token to me that I need to...
import time , base64 , hashlib , hmac , urllib.request , jsonapi_nonce = bytes ( str ( int ( time.time ( ) *1000 ) ) , `` utf-8 '' ) api_request = urllib.request.Request ( `` https : //www.website.com/getToken '' , b '' nonce= % s '' % api_nonce ) api_request.add_header ( `` API-Key '' , `` API_PUBLIC_KEY '' ) api_requ...
Authentication with hashing
C#
I 'm setting up a really small Entity-Component-System example and have some problems with the component pools.Currently my entities are just IDs ( GUIDs ) which is fine.Each system has to implement the ISystem interface and is stored in a KeyedByTypeCollection . This collection makes sure , that each system is unique....
internal interface ISystem { void Run ( ) ; } internal interface IComponent { } internal static class EntityManager { public static List < Guid > activeEntities = new List < Guid > ( ) ; private static KeyedByTypeCollection < Dictionary < Guid , IComponent > > componentPools = new KeyedByTypeCollection < Dictionary < G...
create performant component pooling for system loops
C#
Came across the following MS Unit Test : I have never seen the use of generics when doing Assertions . This is how i would write the Assertion : What is the difference ? When i hover over the AreNotEqual ( ) overload i am using , the method is using the overload which compares two doubles ( not sure why there is n't an...
[ TestMethod ] public void PersonRepository_AddressCountForSinglePerson_IsNotEqualToZero ( ) { // Arrange . Person person ; // Act . person = personRepository.FindSingle ( 1 ) ; // Assert . Assert.AreNotEqual < int > ( person.Addresses.Count , 0 ) ; } // Assert.Assert.AreNotEqual ( person.Addresses.Count , 0 ) ;
What is the difference between these two Unit Test Assertions ?
C#
Hi I am trying to achive something like this ; if I can succeed on that , then I can visit this expression and get the GetData Method and use it for creating a dynamic sql query . I could do this by giving method name as a string however I do n't want to break the strongly type world of my developer friends.I know I ha...
Method < TObjectType > ( m= > m.GetData ) ; //m is the instance of TObjectType void Method < TObjectType > ( Expression < Func < TObjectType , Delegate > > ex ) { /**/ }
Lambda expression that returns a delegate
C#
In my program i have some very long task , which should be interruptable from GUI ( WPF ) . Any advices about threading architecture ? This task looks like N thread with such code :
public void DoLongOperation ( ) { for ( int i=beginPoint ; i < endPoint ; i++ ) { doSomethingStupid ( dataArray [ i ] ) ; } }
Threading in C # . Interruptable task
C#
I 'm writing an asp.net MVC application and decide to try Knockout.js for dynamic UI stuff . It 's a great framework it helped me so much so far . But I faced 2 problems that I ca n't solve and find any useful information on that.I 'll start with code to show you what I have and then I shall try to explain what I want ...
var Project = function ( project ) { var self = this ; self.Id = ko.observable ( project ? project.Id : 0 ) ; self.CustumerCompany = ko.observable ( project ? project.CustumerCompany : `` '' ) ; self.CustomerRepresentative = ko.observable ( project ? project.CustomerRepresentative : `` '' ) ; self.ProjectTitle = ko.obs...
Posting Collection with Knockout.js
C#
I have two different jwt auth tokens from two different providers my api accepts , setup as so : These auth providers have access to different APIs so when a access token attempts to access a API it 's not allowed to I will throw a 403 . I accomplish this with the following policy setup I am running into the following ...
services.AddAuthentication ( ) .AddJwtBearer ( `` auth provider1 '' , options = > { options.Audience = authSettings.Audience1 ; options.Authority = authSettings.Authority1 ; options.ClaimsIssuer = authSettings.Issuer1 ; } ) .AddJwtBearer ( `` auth provider2 '' , options = > { options.TokenValidationParameters = new Tok...
Using multiple authentication schemes on policy causes signature validation failures
C#
People usually ask why they get always the same numbers when they use Random . In their case , they unintenionally create a new instance of Random each time ( instead of using only one instance ) , which of course leads to the same numbers the whole time . But in my case , I do need several instances of Random which re...
int seed1 = ( int ) DateTime.Now.Ticks - 13489565 ; int seed2 = ( int ) DateTime.Now.Ticks - 5564 ; Random helper = new Random ( ) ; int seed1 = helper.Next ( 1 , int.MaxValue ) ; int seed2 = helper.Next ( 1 , int.MaxValue ) ;
Create different seeds for different instances of `` Random ''
C#
I 've been trying to learn more about the CLR and while doing so noticed that the following interface in C # will be compiled to IL that contains some kind of `` abstract interface '' .Given that declaring an interface as abstract in C # is not valid , what does it mean to allow an abstract interface at the IL level ? ...
public interface IExample { void SomeMethod ( int number ) ; } .class interface public auto ansi abstract IExample { // Methods .method public hidebysig newslot abstract virtual instance void SomeMethod ( int32 number ) cil managed { } // end of method IExample : :SomeMethod }
Why does an interface get emitted at the IL level as an `` abstract interface '' ?
C#
I have a DataSet with 1-3 tables , each table have a column named m_date ( string ) I want to get max value from all of them using LINQ.I know how to get each table Maximum value : but I do n't know how to get Max value from all the tables information Edit : I now have something like this which works : but I have a fee...
var maxDate=ds.Tables [ index ] .AsEnumerable ( ) .Max ( x= > DateTime.Parse ( x [ `` m_date '' ] .ToString ( ) ) ) .ToString ( ) ; DateTime maxDate=DateTime.MinValue ; foreach ( DataTable tbl in ds.Tables ) { DateTime maxDateCur=ds.Tables [ index ] .AsEnumerable ( ) .Max ( x= > DateTime.Parse ( x [ `` m_date '' ] .ToS...
Get a Maximum Date value from X tables in DataSet
C#
Is there a way to make the parameters of this extension method 'intellisensible ' from my view ? At the moment , I can get a tooltip nudge of what the parameters ( in the controller action method ) are but would love to confidently IntelliSense type the parameter names for 'safety ' . Anyway , without further ado , the...
public static string Script < T > ( this HtmlHelper html , Expression < Action < T > > action ) where T : Controller { var call = action.Body as MethodCallExpression ; if ( call ! = null ) { // paramDic - to be used later for routevalues var paramDic = new Dictionary < string , object > ( ) ; string actionName = call.M...
LINQ extension method help sought II
C#
to avoid confusion I summarised some code : When I debug the code I get an InvalidCastException in Main ( ) .I know that ISpecificEntity implements IIdentifier.But obviously a direct cast from an IManager < ISpecificEntity > into an IManager < IIdentifier > does not work.I thought working with covariance could do the t...
namespace ConsoleApplication1 { class Program { static void Main ( ) { IManager < ISpecificEntity > specificManager = new SpecificEntityManager ( ) ; IManager < IIdentifier > manager = ( IManager < IIdentifier > ) specificManager ; manager.DoStuffWith ( new SpecificEntity ( ) ) ; } } internal interface IIdentifier { } ...
How to implement generic polymorphism in c # ?
C#
I was toying with Await/Async and CancellationTokens . My code works , but what happens to the Task when it 's Cancelled ? Is it still taking up resources or is it garbage collected or what ? Here is my code :
private CancellationTokenSource _token = new CancellationTokenSource ( ) ; public Form1 ( ) { InitializeComponent ( ) ; } async Task < String > methodOne ( ) { txtLog.AppendText ( `` Pausing for 10 Seconds \n '' ) ; var task = Task.Delay ( 10000 , _token.Token ) ; await task ; return `` HTML Returned . \n '' ; } privat...
What Happens To a Task When It 's Cancelled ?
C#
I am trying to convert Ruby 's time to C # , but I am stuck now.Here 's my try : I am new to C # , and maybe this one should be easy , and I know I want to use Extensionmethods . But since functions are not 'first class ' in C # , I am stuck for now.So , what parametertype should I use for of WhatGoesHere ?
public static class Extensions { public static void Times ( this Int32 times , WhatGoesHere ? ) { for ( int i = 0 ; i < times ; i++ ) ? ? ? } }
Convert Ruby 's times to C #
C#
I 've been testing this code at https : //dotnetfiddle.net/ : If I compile with .NET 4.7.2 I get8590917637But if I do Roslyn or .NET Core , I get8590917630Why does this happen ?
using System ; public class Program { const float scale = 64 * 1024 ; public static void Main ( ) { Console.WriteLine ( unchecked ( ( uint ) ( ulong ) ( 1.2 * scale * scale + 1.5 * scale ) ) ) ; Console.WriteLine ( unchecked ( ( uint ) ( ulong ) ( scale* scale + 7 ) ) ) ; } }
C # overflow behavior for unchecked uint
C#
I see some code of some guy that goes like this : What is while ( ... ) { ... } while ( ... ) statement ? is the following equivalent code ?
while ( ! ( baseType == typeof ( Object ) ) ) { ... . baseType = baseType.BaseType ; if ( baseType ! = null ) continue ; break ; } while ( baseType ! = typeof ( Object ) ) ; while ( baseType ! = null & & baseType ! = typeof ( Object ) ) { ... . baseType = baseType.BaseType ; }
unknown while while statement
C#
I 'd like to modify a source string which is looking like and transfer it into a string with slashes to use it as a folder string which has the following structure : Do you know more elegant ways to realize this , than my solution below ? I 'm not very satisfied with my for-loops .
`` one.two.three '' `` one\one.two\one.two.three '' var folder = `` one.two.three '' ; var folderParts = folder.Split ( ' . ' ) ; var newFolder = new StringBuilder ( ) ; for ( int i = 0 ; i < folderParts.Length ; i++ ) { for ( int j = 0 ; j < i ; j++ ) { if ( j == 0 ) { newFolder.Append ( `` \\ '' ) ; } newFolder.Appen...
Building a new path-like string from an existing one
C#
Is it possible for me to render unbundled and unminified scripts and styles for users in `` Admin '' role ? I 've searched and found how to disable bundling and minificationin Global.asax.cs Application_Start , but I want this logic to be per-user , not per app instance , so it should not only be running on application...
BundleTable.EnableOptimizations = ... foreach ( Bundle bundle in bundles ) { bundle.Transforms.Clear ( ) ; }
render unbundled assets for admin user role
C#
Background : I will be working on tools that will be dependent on a rapidly changing API and rapidly changing data model over which I will have zero control . Data model and API changes are common , the issue here is that my code must continue to work with current and all past versions ( ie 100 % backwords compatibilit...
< Edit > < Edit2 > < /Edit >
Suggestions for change tolerance
C#
Using Reflector or DotPeek , the System.Linq.Data.Binary implementation of the equality operator overload looks like this : I must be missing something obvious , or there is a mechanism taking place of which I 'm unaware ( such as implicitly calling object == within the body ? ) . I admit , I rarely if ever need to ove...
[ Serializable , DataContract ] public sealed class Binary : IEquatable < Binary > { ... public static bool operator == ( Binary binary1 , Binary binary2 ) { return ( ( binary1 == binary2 ) || ( ( ( binary1 == null ) & & ( binary2 == null ) ) || ( ( ( binary1 ! = null ) & & ( binary2 ! = null ) ) & & binary1.EqualsTo (...
Referencing equality operator within equality operator implementation
C#
This might be a trivial question , but I did n't find any information about this : is it `` harmful '' or considered bad practice to make a type T implement IComparable < S > ( T and S being two different types ) ? Example : Should this kind of code be avoided , and if yes , why ?
class Foo : IComparable < int > { public int CompareTo ( int other ) { if ( other < i ) return -1 ; if ( other > i ) return 1 ; return 0 ; } private int i ; }
Implementing IComparable < NotSelf >
C#
I 've recently come across this code in a WinForm application and I ca n't figure if there is any reason to run async code inside a Task.Run that is awaited.Would n't this code do the exact same thing without the Task.Run ?
public async Task SaveStuff ( ) { await Task.Run ( ( ) = > SaveStuffAsync ( ) .ConfigureAwait ( false ) ) ; await Task.Run ( ( ) = > SendToExternalApiAsync ( ) .ConfigureAwait ( false ) ) ; } private async Task SaveStuffAsync ( ) { await DbContext.SaveChangesAsync ( ) .ConfigureAwait ( false ) ; } private async Task Se...
Is there any reason to run async code inside a Task.Run ?
C#
In his PluralSight course Asynchronous C # 5 , Jon Skeet provides this implementation for a convenience extension method called InCOmpletionOrder : In this question , Martin Neal provides a , seemingly more elegant , implementation using yield returnBeing still somewhat new to the rigours of asynchronous programming , ...
public static IEnumerable < Task < T > > InCompletionOrder < T > ( this IEnumerable < Task < T > > source ) { var inputs = source.ToList ( ) ; var boxes = inputs.Select ( x = > new TaskCompletionSource < T > ( ) ) .ToList ( ) ; int currentIndex = -1 ; foreach ( var task in inputs ) { task.ContinueWith ( completed = > {...
Is there a reason to prefer one of these implementations over the other
C#
I 'm learning C # ( background in C++ ) , and I have a question about LINQ expressions . The following two functions both do the same thing ( near as I can tell ) . The type of Wombats is System.Data.Linq.Table < Wombat > .I 'm interested to know Which is more efficient ? Does it even matter ? Is there something to be ...
public static DBConnector.Connections.Wombat getWombat ( String wombatID ) { var db = getDBInstance ( ) ; return db.Wombats.FirstOrDefault ( x = > x.ID.ToString ( ) == wombatID ) ; } public static DBConnector.Connections.Wombat getWombat ( String wombatID ) { var db = getDBInstance ( ) ; var guid = new System.Guid ( wo...
Compare efficiency of two different LINQ statements
C#
A discussion has come up at work : We 've got a class that has an IList . Fact is an abstract base class , and there are several concrete subclasses ( PopulationFact , GdpFact , etc ) .Originally we 'd query for a given fact in this fashion , i.e . by type : Now , however , the question 's been raised whether we should...
.Facts.FirstOrDefault ( x = > x.Year == 2011 & & x is GdpFact ) .Facts.FirstOrDefault ( x = > x.Year == 2011 & & x.FactType == FactType.Gdp )
Performance of Linq query by type
C#
I have this situation ( drastically simplified ) : Here is typical implementation : So on a HexGrid , the client can make a call to get a point on a dual grid , with exactly the right type : So far so good ; the client does not need to know anything about the type how the two points relate , all she needs to know is th...
interface IPoint < TPoint > where TPoint : IPoint < TPoint > { //example method TPoint Translate ( TPoint offset ) ; } interface IGrid < TPoint , TDualPoint > where TPoint : IPoint < T where TDualPoint : Ipoint { TDualPoint GetDualPoint ( TPoint point , /* Parameter specifying direction */ ) ; } class HexPoint : IPoint...
Expressing type relationships and avoiding long type parameter lists in C #
C#
At my work I have to maintain some C # projects . The original developer is not around anymore . Lately I noticed some strange code mostly found in situations like this : What is the 0.ToString ( ) for ? Most of the code was written under stress , so I can think of two possibilities : It 's a placeholder ( like //TODO ...
try { //some Code } catch { 0.ToString ( ) ; }
Strange Exception Handling dummy instruction
C#
I thought the whole reason for Interfaces , Polymorphism , and a pattern like Inversion of Control via Dependency Injection was to avoid tight coupling , separation , modularity , and so on.Why then do I have to explicitly `` wire up '' an Interface to a concrete class like in ASP.NET ? Wo n't me having the registry be...
services.AddTransient < ILogger , DatabaseLogger > ( ) ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApp1 { public interface ILogger { void logThis ( string message ) ; } public class DatabaseLogger : ILogger { public void log...
Why do I have to `` wire up '' Dependency Injection in ASP.NET MVC ?
C#
In Java I can specify generic with wildcard `` ? '' . It is possible to create a map like this one : Map < String , ? > .I 'm working with C # and I need a Dictionary < String , SomeInterface < ? > > ( where ? can be int , double , any type ) . Is this possible in C # ? EDIT : Example : I was trying to map this objects...
interface ISomeInterface < out T > { T Method ( ) ; void methodII ( ) ; } class ObjectI : ISomeInterface < int > { ... } class ObjectII : ISomeInterface < double > { ... } class ObjectIII : ISomeInterface < string > { ... . } Dictionary < String , ISomeInterface < ? > > _objs = new Dictionary < String , ISomeInterface ...
Question about generics in C # comparing to Java
C#
I 'm writing a system that underlies programmer applications and that needs to detect their access to certain data . I can mostly do so with properties , like this : Then I go in and tweak the get and set accessors so that they handle the accesses appropriately . However this requires that the users ( application progr...
public class NiceClass { public int x { get ; set ; } } public class NotSoNiceClass { public int y ; } NotSoNiceClass notSoNice ; ... Write ( notSoNice.y , 0 ) ; // ( as opposed to notSoNice.y = 0 ; ) public class SemiNiceClass { public NotSoNiceClass notSoNice { get ; set ; } public int z { get ; set ; } } SemiNiceCla...
An `` elegant '' way of identifying a field ?
C#
I 'm building a book library app , I have a abstract book Class , two types of derived books and two Enums that will save the genre of the book.Each Book can be related to one genre or more.Now i want to save the discounts based on the book genres ( no double discounts , only the highest discount is calculated ) , so i...
abstract public class Book { public int Price { get ; set ; } ... } public enum ReadingBooksGenre { Fiction , NonFiction } public enum TextBooksGenre { Math , Science } abstract public class ReadingBook : Book { public List < ReadingBooksGenre > Genres { get ; set ; } } abstract public class TextBook : Book { public Li...
selecting correct list of Enums from 2 derived classes
C#
I 'm working on an engine which is meant to be configurable by the user ( not end user , the library user ) to use different components.For example , let 's say the class Drawer must have an ITool , Pencil or Brush , and an IPattern , Plain or Mosaic . Also , let 's say a Brush must have an IMaterial of either Copper o...
public class Drawer < Tool , Pattern > where Tool : ITool where Pattern : IPattern { ... } public class Brush < Material > where Material : IMaterial { ... } Drawer < Pencil , Mosaic > FirstDrawer = new Drawer < Pencil , Mosaic > ( ) ; Drawer < Brush < Copper > , Mosaic > SecondDrawer = new Drawer < Brush < Copper > , ...
Using Generics in a non-collection-like Class
C#
I have the following action methods : When I hit submit received model in POST method is incomplete . It contains FirstName , LastName etc . But UserID is null . So I ca n't update object . What am I doing wrong here ?
public ActionResult ProfileSettings ( ) { Context con = new Context ( ) ; ProfileSettingsViewModel model = new ProfileSettingsViewModel ( ) ; model.Cities = con.Cities.ToList ( ) ; model.Countries = con.Countries.ToList ( ) ; model.UserProfile = con.Users.Find ( Membership.GetUser ( ) .ProviderUserKey ) ; return View (...
Model object incomplete when try to update
C#
Please take a look at the code . It should n't take long to have a glimpse.Since GetCourse ( ) returns a reference of _items , calling t.GetCourses ( ) .Clear ( ) ; is clearing the underlying Course-list in the Teacher instance . I want to prevent this behaviour . That is , the GetCourse ( ) would return a list but it ...
class Teacher { private int _id ; public int ID { get { return _id ; } set { _id = value ; } } private string _message ; public string Message { get { return _message ; } set { _message = value ; } } public Teacher ( int id , string msg ) { _id = id ; _message = msg ; } private List < Course > _items ; public List < Co...
List < T > is cleared problem
C#
I have a following design in Java ( 7 ) application : There is a method where i pass collection of objects of some type and object that I call `` predicate '' that is used to filter given collection.Predicate is an interface with one method called test - it takes an object and return a boolean value.In such situation :...
public class Person { private final String firstName ; private final String secondName ; public Person ( String firstName , String secondName ) { this.firstName = firstName ; this.secondName = secondName ; } public String getFirstName ( ) { return firstName ; } public String getSecondName ( ) { return secondName ; } } ...
How to achieve similar design ( from Java ) that use interface and implementing classes , using delegates in C #
C#
I 'm trying to append some numbers to a string , that string already contains Persian character and StringBuilder always appends Persian number to the string.Even when I 'm explicitly using English numbers like ones in the above code , I still end up with Persian numbers . How can I append English numbers to this strin...
StringBuilder sb = new StringBuilder ( ) ; sb.Append ( other things ) ; sb.Append ( `` ' , ' '' ) ; sb.Append ( `` 1234234 '' ) ; sb.Append ( `` ' , `` ) ; StringBuilder temp = new StringBuilder ( ) ; temp.Append ( `` INSERT INTO [ db ] ( ... . ) VALUES ( '21211221 ' , 111555 , '2015/12/12 ' , 'نام خانوادگی ' , 'اتاق چ...
StringBuilder appends Persian Numbers
C#
Each item has an interface , IItem . As well as this , there is a interface known as IDrawableItem which inherits from Item.The code below , is trying to draw a drawable item , but can not as the collection this class stores accepts only IItem . You can add anything that inherits from IItem to this class , but using ot...
foreach ( var item in Items ) { item.Draw ( ) ; // The casting would go here . }
Casting and interface inheritance
C#
What ( if any ) is the upside or downside ( performance , good coding practice , garbage collection etc . ) of invoking a non-static method of a class in the manner below : as against the more `` traditional '' way ofAny thoughts would be greatly appreciated .
new ClassA ( ) .MethodA ( param1 , param2 ) ; ClassA classA = new ClassA ( ) ; classA.MethodA ( param1 , param2 ) ;
Invoking nonstatic methods of a class