text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : 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 about non-awaitable-inline-function , something like this : output : Question : Is it a viable solution for logging in a `` fire-and-forget '' mode ? What if I create objects inside this inline method , when are they going to be GC'ed ? <code> 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.EnsureSuccessStatusCode ( ) ; // I do n't need this here Console.WriteLine ( `` error '' ) ; } //some code LogMe ( ) ; //some code Console.WriteLine ( 3 ) ; } 12 | Non awaitable as `` fire & forget '' - is it safe to use ? |
C_sharp : 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 makes sure that the label gets a mnemonic . For button1 this works in my testcode : I get `` foo '' where the f is underlined . However for button2 this fails . I just get `` _foo '' as a label in my dialog.Can anyone explain how the derived class in this example could behave differently or is there some magic going on behind the screen that maybe checks the type of the actual class ? <code> 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_sharp : 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 allow it ? <code> 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 ) .IsAssignableFrom ( typeof ( T ) ) ) MyAction ( ( T2 ) other ) ; } } | Unconstrained type parameters casting |
C_sharp : 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 n't change in my javascript code.Please see the screen capture of the developer tool.does Anyone has a clue on this ? <code> 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 ) { $ .ajax ( { url : `` @ Url.Action ( `` LoadScenario '' , `` Book '' ) '' , dataType : 'json ' , type : 'POST ' , data : { 'bookId ' : BookHandler.getBookId ( ) } , success : function ( response ) { var scenarioId = response ; var isLoadScenario = `` @ Portal.Presentation.Web.Planning.MVC.App_Start.SessionProvider.SessionLoadSceanrio '' ; //otherproperties window.open ( `` @ Url.Action ( `` Index '' , `` BookScenario '' , new { loadScenario = `` _loadScenario '' } ) .replace ( '_loadScenario ' , isLoadScenario ) , tabId ) ; } , error : function ( ) { } } ) ; } ) ; } | C # property value does n't get modified within Javascript/ jquery |
C_sharp : Can I have two same function name with same parameters but different meaning.For example : Thank you . <code> public void test ( string name ) public void test ( string age ) | function overload |
C_sharp : 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 valid ? <code> 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 ) { PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } | INotifyProperyChanged - why the extra assignment ? |
C_sharp : 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 HiddenFor helperand my problem is that value for this hidden field is rendered as null : Even if I set it when instantiating a model and of course it 's confirmed with debugging ( it always has a value ) .So instead it should look like this : Because I know there are some questions like this one ( actually all of them refer to changing form values during form POST ) I included list of things I tried already . My code is right below this section which I belive to be essential.So far I tried : ModelState.Clear ( ) everywhere possible - cause as we know the value from ModelState is first place where it looks for the value . NO EFFECT which I expected , cause my ModelState is empty ( my case is not about changing value during POST in controller as in many questions like that ) , so it should take value from my view model.Not using HiddenFor helper , but pure html instead . WORKS , but its just workaround , not an answer to the problem.Duplicating line with helper in view as follows : PARTIALLY WORKS Produces first input as value/ > and second as value= '' 8888888 '' / > which indicates that there is probably something that hides initial property value . Anyway , I found nothing in ViewData at any point , nor in query string . Obviously I ca n't accept it this way , no explonation needed I guess.Changing name of the property . Originally it was ProductCode . I changed it to productCode , ProdCode , ProductCodeasd , etc . and all of these WORKS . Again , it looks like there is something that hides/updates the value , but again - 100 % sure there is no JS or anything else doing it . So still no answer found - just workaround again.Explicitly setting the value for HiddenFor : @ Html.HiddenFor ( x = > x.ProductCode , new { Value = @ Model.ProductCode } ) . NO EFFECT , renders the same way.Using @ Html.Hidden instead of @ Html.HiddenFor . NO EFFECT , with name set as ProductCode it renders the same way.One more thing I found interesting . Reading html with Display page source in Chrome [ ctrl+U ] shows that value is valid value= '' 8888888 '' / > , but in DevTools it 's still value/ > and of course submitting the form passes null to Controller method.ModelViewControllerThe view is returned from controller with RedirectToAction as follows : ValidateAndProceed - > ResolveNextStep ( here redirection occurs ) - > ShowProductFinally , what can cause such a weird behavior ? I 've already ran out of options . Maybe anyone had problem like mine before , would appreciate any clue on this case . <code> @ 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 Product { public string Description { get ; set ; } public int Quantity { get ; set ; } public string ProductCode { get ; set ; } public string ImageUrl { get ; set ; } public Product ( string desc , string productCode , string imgUrl ) { Description = desc ; ProductCode = productCode ; ImageUrl = imgUrl ; } } @ model Product @ using ( Html.BeginForm ( `` UpdateCart '' , `` Cart '' ) ) { < div class= '' row pad10 '' > < div class= '' col-sm-6 text-center '' > < img src= '' @ Model.ImageUrl '' width= '' 300 '' height= '' 300 '' / > < /div > < div class= '' col-sm-6 text-justify '' > < p > @ Model.Description < /p > < div class= '' row padding-top-2 '' > < div class= '' col-sm-6 '' > < label > @ CommonResources.Quantity : < /label > < /div > < div class= '' col-sm-4 '' > @ Html.TextBoxFor ( m = > m.Quantity , new { @ class = `` form-control '' , @ data_val_required = CommonResources.FieldRequired , @ data_val_number = CommonResources.ValidationNumber } ) @ Html.ValidationMessageFor ( model = > model.Quantity , `` '' , new { @ class = `` text-danger '' } ) @ Html.HiddenFor ( m = > m.ProductCode ) < /div > < /div > < /div > < /div > < div class= '' text-center col-xs-12 padTop20 padBottom20 '' > < input type= '' submit '' value= '' Submit '' class= '' whtBtn pad '' / > < /div > } public ActionResult ValidateAndProceed ( ) { var order = Session.Current.Order ; var lang = LangService.GetSelectedLanguage ( ) ; var invoice = Session.Current.CurrentInvoice ; var localCurrency = Session.Current.LocalCurrencyInfo ; List < CheckoutValidationFieldError > errors = new List < CheckoutValidationFieldError > ( ) ; errors = ValidationService.ValidateAddress ( order ) ; if ( errors.Count > 0 ) { return RedirectToAction ( `` InvalidAddress '' , `` Address '' , new { serializedErrors = JsonConvert.SerializeObject ( errors ) } ) ; } return ResolveNextStep ( order , invoice ) ; } public ActionResult ResolveNextStep ( IOrder order , IInvoice invoice ) { if ( OrderService.ShowProductView ( order , invoice ) ) { return RedirectToAction ( `` ShowProduct '' ) ; } return RedirectToAction ( `` Summary '' ) ; } public ActionResult ShowProduct ( ) { Product model = ProductService.GetProduct ( Session.Current.CurrentInvoice ) ; return View ( `` ~/Views/Product.cshtml '' , model ) ; } | MVC @ Html.HiddenFor renders html form with no value |
C_sharp : 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 in the backgroundworker and it works perfectly , however I do not want the cursor to change . That 's why I figured a property that I could set would be much better.Here is the code in my MainForm : Here is the code for my usercontrol : <code> 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 _disableIfBusy ; } set { _disableIfBusy = value ; } } public MenuItem ( ) { InitializeComponent ( ) ; } protected override void OnMouseEnter ( EventArgs e ) { if ( Application.UseWaitCursor & & _disableIfBusy ) { this.BackColor = SystemColors.ControlDark ; } else { this.BackColor = SystemColors.Control ; } base.OnMouseEnter ( e ) ; } | How do I read a property from my main form in a user control |
C_sharp : 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 closures.What is the explanation ? <code> 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 filterCriteria = CreateFilterCriteria ( ) ; return ( from log in this.loggingProvider.ReadLogs ( filterCriteria , 1 ) where log.ParticipantObjects [ 0 ] .ParticipantObjectId == id.ToString ( ) & & log.LogEventParameters [ 0 ] .Value == name orderby log.Timestamp.ToLocalTime ( ) descending select log ) .AsEnumerable ( ) ; } catch ( Exception ex ) { this.tracer.Write ( Category.Error , ex , `` Error '' ) ; return null ; } } | Why was exception not caught within the closure ? |
C_sharp : 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 can access the values after matching using match.Group [ 3 ] .Captures [ i ] .In Java I have n't found anything like that . matcher.group ( 3 ) just returns an empty string.How can I achieve a behaviour like the one I 'm used to from C # ? <code> 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_sharp : 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 the value that was matched . So I do n't want the whole document because if the match was on a district name , I ca n't easily return that value.I 've tried several options with .Search ( ) and .Suggest ( ) but could n't quite get there . <code> { `` Name '' : ... , ... , `` Districts '' : [ { `` Name '' : ... , ... } ] } | How to do a RavenDB query over multiple ( complex structure ) fields and return the matched values ? |
C_sharp : 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 , however , when I looked at all the operators I could conceivably overload ( + , - , ! , ~ , ++ , -- , true , false , + , - , * , / , % , & , | , ^ , < < , > > , == , ! = , < , > , < = , > = ) , I started to feel like there must be a better way . After all , the struct only contains one field , and that field is a value type.Is there some way to enable all the operators of double in one shot ? Or do I really have to type out every operator I could possibly want to support by hand ? ( Even if I had two or three fields , I 'd still like to be able to add the operators in one batch ... ) <code> 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 Angle FromDegrees ( double value ) { return new Angle ( value ) ; } public static Angle FromRadians ( double value ) { return new Angle ( value / RadiansPerDegree ) ; } } var alpha = Angle.FromDegrees ( 90 ) ; var beta = Angle.FromDegrees ( 100 ) ; var inequality = alpha > beta ; var sum = alpha + beta ; var negation = -alpha ; //etc . public static Angle operator + ( Angle a , Angle b ) { return new Angle ( a._degrees + b._degrees ) ; } public static Angle operator - ( Angle a ) { return new Angle ( -a._degrees ) ; } public static bool operator > ( Angle a , Angle b ) { return a._degrees > b._degrees ; } | Do I have to define every single operator ? |
C_sharp : 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 this : EDIT : Since the answer seems to be that it 's just not possible , any suggestions on how to achieve what I 'm going for here ? <code> 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 > > _strategies = new Dictionary < Type , IBenefitStrategy < BenefitBase > > ( ) ; public BenefitStrategyProvider ( ) { /* Why ca n't I add this ? */ _strategies.Add ( typeof ( FreeBenefit ) , new FreeBenefitStrategy ( ) ) ; } public IBenefitStrategy < BenefitBase > GetStrategy ( BenefitBase benefit ) { return _strategies [ benefit.GetType ( ) ] ; } } public class Account { } public abstract class BenefitBase { public string BenefitName { get ; set ; } } public class FreeBenefit : BenefitBase { } public interface IBenefitStrategy < T > where T : BenefitBase { void ApplyBenefit ( T benefit , Account account ) ; } public class FreeBenefitStrategy : IBenefitStrategy < FreeBenefit > { public void ApplyBenefit ( FreeBenefit benefit , Account account ) { Console.WriteLine ( `` Free Benefit applied '' ) ; } } | Invariant inheritance problem |
C_sharp : 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 sure I could just look at the IL , but I 'm too lazy for that : ) , I 'd rather just ask . <code> MyObject.MyEvent += new EventHandler ( MyEventHandlerMethod ) ; vs.MyObject.MyEvent += MyEventHandlerMethod ; | adding an event handler |
C_sharp : 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 application which invoked the work picks up the message that the work is doneThe reason I used Task < Task > is because the first Task < > is for the queueing of the message ; while the inner Task is completed when the work has been completed on the remote machine ( i.e . when the message from the agent has been received ) . Any exceptions which the remote agent caught during execution of the work are passed along with the completion message and are re-thrown when the inner Task completes . To call this method I use : which would wait for the message to be queued to execute the job , as well as to complete the job and receive any exceptions . However , if I was not interested in whether the job completed on the remote agent or not , I might call it as follows : which would not await the inner Task . However , the inner Task ( which receives the message from the remote agent , and re-throws the exceptions ) would still execute at some point . I feel that this is a bit of a waste and I would like to avoid executing it when I do n't await for the results . My question is thus : is it possible for a Task to `` know '' whether it is being awaited and not execute if it is not , or execute some other code path ( such as an empty Task body ) . I do realize that there are alternatives that I could implement , such as passing a `` fire and forget '' flag , or adding an overload for `` fire and forget '' . It would be great though if I could implement this without the client API changingAnswers involving other projects which implement this sort of remote work execution would also be great ! <code> public Task < Task > DoSomeWorkOnARemoteMachine ( ) await await DoSomeWorkOnARemoteMachine ( ) ; await DoSomeWorkOnARemoteMachine ( ) ; | Is there a way to know if a Task is being awaited ? |
C_sharp : 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 : <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 ( campIdLock ) { loadedCampIds.Add ( _campId ) ; } } if ( response.status == Field.List.Status.retry ) { Thread th1 = new Thread ( new ThreadStart ( FromDatabase ( _campId ) ) ) ; th1.Start ( ) ; } return lstFields ; } | threading question |
C_sharp : 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 flow equations to solve an electrical circuit of altern current ( AC ) . The equations are composed by a number of variables that depend of the number of nodes in the grid , which is especified by the user , the equations are these : So basically I have 2 equations per node , this is 2*n equations , which can not be composed in a single line bacause they depend of i , j indices , therefore I have to have 2 nested for loops to create the P and Q equations.Is there a way to create Func < Vector , double > [ ] f = { equation system of variable lenght } ; ? I have seen the post Creating a function dynamically at run-time , but it does n't answer my quetion ( I believe ) //************************EDIT**************************************The creation of the equations is something like this : Ofcourse A and B contain the variables , and this loop formulation as it is makes little sense.Thanks in advance . <code> 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 ( Theta [ i , j ] ) + B [ i , j ] *Math.Sin ( Theta [ i , j ] ) B+= G [ i , j ] *Math.Sin ( Theta [ i , j ] ) + B [ i , j ] *Math.Cos ( Theta [ i , j ] ) } P [ i ] =V [ i ] *A ; Q [ i ] =V [ i ] *B ; } | Define a function dynamically |
C_sharp : 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 value that is cast to that type.For example , I do n't normally initialize variables that have a class level scope . I 'm wondering if this is something I should be doing or what purpose it serves.Thanks for any enlightenment . <code> 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_sharp : 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 multiple tables to send data so I created a viewModel like this : In the view I displayed information like this : Now the problem lies in my in the controller because the way I am trying to populate the description and summary like this I get a null error : As you can see apart from the obvious ViewModel Class added to the code it is the exact same.This is clearly must not be correct way to get a value into a variable / email by using a viewModel , does anyone know how I can do this correctly ? <code> 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 ( Function ( model ) model.IssueSummary ) @ Html.EditorFor ( Function ( model ) model.IssueDescription ) Public Class ViewModel Public proTableList As List ( Of ProjectType ) Public cTableList As List ( Of ClientTable ) Public proTable As ProjectType Public iTable As IssueTableViewModelEnd ClassPublic Class IssueTableViewModel Public IssueSummary As String Public IssueDescription As StringEnd Class @ ModelType IssueTracker.ViewModel @ Html.EditorFor ( Function ( model ) model.iTable.IssueSummary ) @ Html.EditorFor ( Function ( model ) model.iTable.IssueDescription ) Public Function SubmitIssue ( issuetable As IssueTable , test As IssueTracker.ClientUserProjectIssue ) As ActionResultDim mail As New MailMessage ( ) mail.Subject = test.iTable.IssueSummaryDim body As String = test.iTable.IssueDescriptionmail.Body = bodysmtp.Send ( mail ) | Null value error when trying to make viewmodel item equal variable |
C_sharp : 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 ( or similar ) .How do I solve this issue ? <code> ... 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 > < /BeginStoryboard > < /Trigger.EnterActions > < /Trigger > | UserControl Animate Button 's Background |
C_sharp : 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 relevant to all media files.MovieInfo inherits from MediaInfo and adds some information that is specific to video files.Media is an abstract base class that represents all media files.Movie inherits from Media.Now , Media contains the following line of code : Inside Media , I have Accessors that extract information from MediaInfo.However , inside Movie , I 'd like to have Accessors that also extract information from MovieInfo.So what I did inside Movie was : And inside the constructor : However , now I have an Accessor : The problem is , FrameHeight is an accessor only available inside MovieInfo . this.info is treated as a MediaInfo , despite the fact that I declared it as a MovieInfo , and so the code generates an error.So to sum up my problem into a more generic question : In a derived class , how do I derive from a protected base variable in the base class ? Sorry if this was a bit confusing , I 'd be happy to clarify any unclear details . <code> 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_sharp : 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 replaces the german `` ä '' with `` \'e4 '' ! Let example_text = `` Primär-ABC '' and lets use the following codethen the emMatch.Value returns `` Prim\'e4r-ABC '' instead of `` Primär-ABC '' .The German ä transforms to \'e4 ! Because I want to work with the exact string , i would needemMatch.Value to be Primär-ABC - how do I achieve that ? <code> 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_sharp : 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 reserve Vehicle # 1 and Vehicle # 2 for 12/18/2018 from 12:00 to 13:00 ... .stored procedure goes to db to find out that Vehicle # 1 is already reserved from 12:00 to 13:00 , but Vehicle # 2 is not reserved . Due to the foreach that runs , alreadyReservedVehicle comes back with the result of .Count ( ) = 0 because it sees the last result , which is that Vehicle # 2 is not reserved . It should be showing an error message to say double booking is not allowed , since Vehicle # 1 is already reserved , but it is n't counting that reservation.Is there a way to collect both results and tell the application that because one of those 2 vehicles are reserved , that neither vehicle can be reserved ? Above is what I have so far and I know I am close , because what I have will work assuming a user is only trying to reserve one vehicle that is already booked . It 's when they are trying to create a reservation for multiple vehicles where the code only counts the last vehicle in the list and uses that as the result that determines whether or not the reservation will be saved.I thought about moving the conditional statement into the foreach , but I do n't want the reservation to be saved for each vehicle that was selected ... that would n't make any sense because there is only 1 reservation to be saved , it just has multiple vehicles that can be associated to it . Here is the stored procedure that finds the reserved vehicles : So how can I get the alreadyReservedVehicle List to add each result to the list so I can determine if the List actually has a Count of 0 ? UPDATE : Here is the model for the stored procedure <code> 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 ( x = > x.IsChecked == true ) .ToList ( ) ; List < usp_PreventDoubleBooking_Result > alreadyReservedVehicle = null ; // get each vehicle that was selected to be reserved then check db to make sure it is available foreach ( var selectedVehicle in selectedVehicles ) { using ( VehicleReservationEntities db = new VehicleReservationEntities ( ) ) { alreadyReservedVehicle = db.usp_PreventDoubleBooking ( selectedVehicle.ID , reservation.StartDate , reservation.EndDate ) .ToList ( ) ; } } if ( alreadyReservedVehicle.Count ( ) == 0 ) // create a new reservation if the vehicle is available at the selected date and time { db.Reservations.Add ( reservation ) ; reservation.LastChangedDate = DateTime.Now ; db.SaveChanges ( ) ; } else { //return error message on page if vehicle is already reserved TempData [ `` Error '' ] = `` Double booking of vehicles is not allowed . Please choose another vehicle/time . Check the availability timeline before reserving to ensure there are no errors . Thank you . `` ; return RedirectToAction ( `` Create '' ) ; } } } SELECT v.ID , r.StartDate , r.EndDate FROM dbo.Reservations rJOIN dbo.ReservationToVehicle rtv ON r.id = rtv.ReservationIDJOIN dbo.Vehicles v ON v.ID = rtv.VehicleIDWHERE ( v.ID = @ VehicleID ) AND ( r.StartDate < = @ NewEndDate ) AND ( r.EndDate > = @ NewStartDate ) public partial class usp_PreventDoubleBooking_Result { public int ID { get ; set ; } public DateTime StartDate { get ; set ; } public DateTime EndDate { get ; set ; } } | How do I create a list from stored procedure results Entity Framework |
C_sharp : 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 Conditional ( `` DEBUG '' ) help in this regard ? <code> # if DEBUGusing MyAssembly ; # endif | C # using statement inside # if DEBUG but not ship assembly |
C_sharp : 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 figure outHow there is any possibility of an exception being thrown in between object creation and the method returning , orWhere I can put try/finally blocks to get rid of the error.Before I just give up and suppress the warning messages all over the place , is there a better way to achieve this same effect that does n't result in a potential undisposed object ? <code> 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 constructor . } protected override void Dispose ( bool disposing ) { if ( disposing & & ( this.db ! = null ) ) { IDisposable temp = this.db as IDisposable ; if ( temp ! = null ) { temp.Dispose ( ) ; } } } } | CA2000 and Dependency Injection |
C_sharp : 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 of { get ; set ; } just a convention or is it necessary to maintain this order or is it some remnant of a bygone era of C history like the way we define conventional electric current flowing from positive to the negative terminal when it is actually the other way around ? <code> public string SomeString { get ; set ; } public string SomeString { set ; get ; } | Using { set ; get ; } instead of { get ; set ; } |
C_sharp : 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 instance hereof . Only the interface . <code> 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.GetCustomAttributesData ( ) ; // < -- Empty | Check if Generic Interface Member is `` Pure '' ( has Pure Attribute ) |
C_sharp : 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 different types of processing.The issue is that I need to use all implementations of IProcessor at the same time .. so how do I inject the IProcessor into my Engine class which drives the whole thing : This is what I 'm doing at present .. and it does n't look nice and clean.Any ideas as to how I could improve this design .. using IoC perhaps ? <code> 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 type2Records = records.Where ( x = > x.SomeField== `` Type2 '' ) .ToList ( ) ; IProcessor processor1 = new Type1Processor ( ) ; processor.Process ( type1Records ) ; IProcessor processor2 = new Type2Processor ( ) ; processor.Process ( type2Records ) ; } } | How to implement usage of multiple strategies at runtime |
C_sharp : 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 ? <code> if ( Model.Products ? .Cards ? .Any ( ) ) { } if ( Model.Products ? .Cards ? .Count > 0 ) { } | Why is ? .Any ( ) classed as a nullable bool ? |
C_sharp : 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 , meaning that for the selected category no ads are being served ( I 'm in Germany ) . The code for my AdControl looks like this : According to the information shown in Microsoft 's pubCenter , the ApplicationId stays the same ( as expected ) when I add multiple categories for ads , but the AdUnitId changes . How would I go about using ads from multiple categories , is there a simple solution ? Or would I have to try instantiating an AdControl while changing the category ( and therefore the AdUnitId until I wo n't get an exception anymore and then use that one ? What would be the best approach ? UpdateYou are not allowed to change the AdUnitId once it 's been set , so this wo n't work.Update 2I am still not sure if everything is set up correctly - when I start my app ( installed from the Windows App Store ) , I always get a `` NoAdsAvailable '' error . The category from which ads should be shown is `` Games '' , so the error message suggests that ( for my region ) there are no ads from that category . When I use different apps with advertising , they show ads which must be from the games category , so somehow I fear I might not have everything set up correctly.Does anyone have an idea ? <code> 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_sharp : 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 scope does not extend to MoreDerived . Thus , the call F ( ) in MoreDerived.G is valid and will invoke Base.F.I am not understanding that how static void G ( ) { F ( ) ; } can access the base class f method when it can access all methods of it 's immediate super class and super class hides the f method of base class <code> **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_sharp : 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 be called after Main ( ) .Why such discrepancy between implicit and explicit constructor ? <code> 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 Company { get ; private set ; } // Static Methods . public static void Initialize ( string company ) { Company = company ; } } public class Reg { public static string Root = $ @ '' Software\ { Enterprise.Company } '' ; // ctor . static Reg ( ) { // Assertion failed when this constructor is disabled . } } | Implicit static constructor called before Main ( ) |
C_sharp : 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 ? <code> 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 ImagePath ; } List < Movie > myMovies = new List < Movie > ( ) ; List < Movie > myDistinctMovies = myMovies.Distinct ( ) .ToList ( ) ; | Select distinct from List < t > ignoring one element |
C_sharp : 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 toggling behaviour <code> 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_sharp : 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 do stuff with routing to make it happen ( which is what I am doing now ) , but I am really interested in the GET vars part of the question . <code> [ 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_sharp : 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 to it ) , allowing for overrides in the child classes by specifying the type of TKey explicitly . It does n't seem to matter what parameter constraints I use for the IRetrievable , I can never get the method call to fall through to the base class.Also , if anyone can see an alternate way to implement this kind of behavior and get the result I 'm ultimately looking for , I would be very interested to see it.Thoughts ? <code> 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 ; } public string Name { get ; set ; } } class FakeRepository : BaseRepository < User > , ICreatable < User > , IDeletable < User > , IRetrievable < int , User > { // why do I have to implement this here , instead of letting the // TKey generics implementation in the baseclass handle it ? //public User Retrieve ( int input ) // { // throw new NotImplementedException ( ) ; // } } class BaseRepository < TPoco > where TPoco : class , new ( ) { public virtual TPoco Create ( ) { return new TPoco ( ) ; } public virtual bool Delete ( TPoco item ) { return true ; } public virtual TPoco Retrieve < TKey > ( TKey input ) { return null ; } } interface ICreatable < TPoco > { TPoco Create ( ) ; } interface IDeletable < TPoco > { bool Delete ( TPoco item ) ; } interface IRetrievable < TKey , TPoco > { TPoco Retrieve ( TKey input ) ; } } | Can you explain this generics behavior and if I have a workaround ? |
C_sharp : 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 ) <code> 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 ( ) ; } /* Tasks . * 1 . I want to add spaces for subfolder like this format down below . ( it must be done with recursion ) * Like this * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- * Folder 1 * Folder 1.1 * Folder 1.2 * Folder 2 * Folder 2.1 * Folder 2.1.1 * Folder 2.2 * Folder 3 * Folder 4 * * 2 . Task 2 I want to retype this code without using recurrence and C # inbuilt functions . */ static void WriteDirectories ( string path ) { string [ ] dirs = Directory.GetDirectories ( path ) ; for ( int i = 0 ; i < dirs.Length ; i++ ) { Console.WriteLine ( dirs [ i ] ) ; WriteDirectories ( dirs [ i ] ) ; } } } } | Start new line with spaces |
C_sharp : 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 when I set a breakpoint there in VS2010.It works without problems , but I do n't understand how or why . What exactly happens there ? <code> 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 class DataConvert { public static Thema ToThema ( tbl_Thema tblThema ) { Thema thema = new Thema ( ) ; thema.ID = tblThema.ThemaID ; thema.Titel = tblThema.Titel ; // and some other stuff return thema ; } } Thema th = Queries.GetThemaByTitle.Invoke ( db , `` someTitle '' ) ; | including `` offline '' code in compiled querys |
C_sharp : 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 of the parameterless constructor of Class1 , the second prints null . However , the problem arises with the third one , because what I actually want is n't to know whether it takes 0 parameters or not , but it 's whether Ican create an instance of the class without any parameters . How do I do that ? <code> 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.Length ; i++ ) { ConstructorInfo ctr = provider.GetConstructor ( Type.EmptyTypes ) ; Console.WriteLine ( ctr == null ? `` null '' : ctr.Name ) ; } | Reflecting constructors with default values in C # 4.0 |
C_sharp : 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 UI . There is an IMatterListLoader service interface where implementations represent mechanisms for loading the lists from different file types . For simplicity , let 's say that only one implementation is used with the application , i.e . the application does n't support more than one file type at present.Let 's say in my initial version , I 've chosen an MS Excel implementation to load the list of matters , like this : I 'd like to allow the user to configure at runtime the row and column numbers where the list starts , so the view might look like this : And here 's the MS Excel implementation of IMatterListLoader : The row and column numbers are an implementation detail specific to MS Excel implementations , and the view model does n't know about it . Nevertheless , MVVM dictates that I control view properties in the view model , so if I were to do that , it would be like this : Just for comparison , here 's an ASCII text file based implementation that I might consider for the next version of the application : Now I do n't have the row and column numbers that the MS Excel implementation needed , but I have a Boolean flag indicating whether the client/matter numbers start on the first row ( i.e . no header row ) or start on the second row ( i.e . with a header row ) . I believe the view model should be unaware of the change between implementations of IMatterListLoader . How do I let the view model do its job controlling presentation concerns , but still keep certain implementation details unknown to it ? Here 's the dependency diagram : <code> 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 ExcelMatterListLoader : IMatterListLoader { public uint StartRowNum { get ; set ; } public uint StartColNum { get ; set ; } public IReadOnlyCollection < string > MatterListFileExtensions { get ; set ; } public IReadOnlyCollection < ClientMatter > Load ( FileInfo fromFile ) { // load using StartRowNum and StartColNum } } public sealed class MainViewModel { public string InputFilePath { get ; set ; } // These two properties really do n't belong // here because they 're implementation details // specific to an MS Excel implementation of IMatterListLoader . public uint StartRowNum { get ; set ; } public uint StartColNum { get ; set ; } public ICommandExecutor LoadClientMatterListCommand { get ; } public MainViewModel ( IMatterListLoader matterListLoader ) { // blah blah } } public sealed class TextFileMatterListLoader : IMatterListLoader { public bool HasHeaderLine { get ; set ; } public IReadOnlyCollection < string > MatterListFileExtensions { get ; set ; } public IReadOnlyCollection < ClientMatter > Load ( FileInfo fromFile ) { // load tab-delimited client/matters from each line // optionally skipping the header line . } } | Using abstraction and dependency injection , what if implementation-specific details need to be configurable in the UI ? |
C_sharp : 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 <code> i+++++i // does not compile < bt > i++ + ++i // executed | Does C # has impact when evaluating /parsing expressions ? |
C_sharp : 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 ! <code> 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 ( `` entry '' ) .Element ( `` id '' ) .ToString ( ) , } ) .ToList < VideInfo > ( ) ; | How to get data from xml , by linq , c # |
C_sharp : 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 <code> 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_sharp : 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 Logs ( on the Visual Studio Containers window ) as it says : I have installed the SDKs from the link given above.Build output is below : My Dockerfile is below : I am unable to hit any breakpoints or even confirm if the app is running . I have a Generic Host app , and I do n't even hit the breakpoint of the first line within public static void Main ( string [ ] args ) .Pointers much appreciated.UPDATE AND FIXSo this was the smoking gun , in particular as this was a console application , and not a AspNetCore app.I found one of my referenced libraries had a reference to Grpc.AspNetCore.Once i moved this code out , it was able to run ( I can confirm before the container instance was not running ) , with full debugging.It compiled OK , the container ran , the application within the container never seemed to launch.QUESTIONI would like to get to the bottom of why , as i do n't fully understand how this fixed everything and what can be done to avoid in future ( seems any console app that references a library that accidentally or otherwise references an AspNetCore dependency could have the same issue ) . <code> 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-applaunch ? framework=Microsoft.AspNetCore.App & framework_version=3.1.0 & arch=x64 & rid=debian.10-x64 1 > -- -- -- Build started : Project : Libertas.Host.Tickers.ScheduledTasks , Configuration : Debug Any CPU -- -- -- 1 > Libertas.Host.Tickers.ScheduledTasks - > C : \Users\User\Source\Repos\myrepo\Libertas\src\Libertas.Host.Tickers.ScheduledTasks\bin\Debug\netcoreapp3.1\Libertas.Host.Tickers.ScheduledTasks.dll1 > docker build -f `` C : \Users\User\Source\Repos\myrepo\Libertas\src\Libertas.Host.Tickers.ScheduledTasks\Dockerfile '' -- force-rm -t libertashosttickersscheduledtasks : dev -- target base -- label `` com.microsoft.created-by=visual-studio '' -- label `` com.microsoft.visual-studio.project-name=Libertas.Host.Tickers.ScheduledTasks '' `` C : \Users\User\Source\Repos\myrepo\Libertas\src '' 1 > Sending build context to Docker daemon 1.362MB1 > 1 > Step 1/4 : FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS base1 > -- - > 86a2e7d459481 > Step 2/4 : WORKDIR /app1 > -- - > Running in d1ed1740d43e1 > Removing intermediate container d1ed1740d43e1 > -- - > 90bd1703e28d1 > Step 3/4 : LABEL com.microsoft.created-by=visual-studio1 > -- - > Running in 2626d5865d891 > Removing intermediate container 2626d5865d891 > -- - > da74703374d21 > Step 4/4 : LABEL com.microsoft.visual-studio.project-name=Libertas.Host.Tickers.ScheduledTasks1 > -- - > Running in 7a381e7ea47a1 > Removing intermediate container 7a381e7ea47a1 > -- - > fd2dd439cce61 > Successfully built fd2dd439cce61 > Successfully tagged libertashosttickersscheduledtasks : dev1 > SECURITY WARNING : You are building a Docker image from Windows against a non-Windows Docker host . All files and directories added to build context will have '-rwxr-xr-x ' permissions . It is recommended to double check and reset permissions for sensitive files and directories.1 > docker rm -f 9ff95181e06801ed3d4b4d5743397604b743d77c840f2047fb2caee046e5d8eb1 > Error : No such container : 9ff95181e06801ed3d4b4d5743397604b743d77c840f2047fb2caee046e5d8eb1 > docker run -dt -v `` C : \Users\User\vsdbg\vs2017u5 : /remote_debugger : rw '' -v `` C : \Users\User\Source\Repos\myrepo\Libertas\src\Libertas.Host.Tickers.ScheduledTasks : /app '' -v `` C : \Users\User\Source\Repos\myrepo\Libertas\src : /src/ '' -v `` C : \Users\User\AppData\Roaming\Microsoft\UserSecrets : /root/.microsoft/usersecrets : ro '' -v `` C : \Users\User\.nuget\packages\ : /root/.nuget/fallbackpackages '' -e `` DOTNET_USE_POLLING_FILE_WATCHER=1 '' -e `` NUGET_PACKAGES=/root/.nuget/fallbackpackages '' -e `` NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages '' -- name Libertas.Host.Tickers.ScheduledTasks_1 -- entrypoint tail libertashosttickersscheduledtasks : dev -f /dev/null1 > ba95df9d32d6a0af07b1eab32af606131e075b2afff664c4003dbe3eae349543========== Build : 1 succeeded , 0 failed , 6 up-to-date , 0 skipped ========== # See https : //aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.FROM mcr.microsoft.com/dotnet/core/runtime:3.1-buster-slim AS baseWORKDIR /appFROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS buildWORKDIR /srcCOPY [ `` Libertas.Host.Tickers.ScheduledTasks/Libertas.Host.Tickers.ScheduledTasks.csproj '' , `` Libertas.Host.Tickers.ScheduledTasks/ '' ] COPY [ `` Libertas.Application.Tickers.ScheduledTasks/Libertas.Application.Tickers.ScheduledTasks.csproj '' , `` Libertas.Application.Tickers.ScheduledTasks/ '' ] COPY [ `` PolygonIo.WebSocket/PolygonIo.WebSocket.csproj '' , `` PolygonIo.WebSocket/ '' ] RUN dotnet restore `` Libertas.Host.Tickers.ScheduledTasks/Libertas.Host.Tickers.ScheduledTasks.csproj '' COPY . .WORKDIR `` /src/Libertas.Host.Tickers.ScheduledTasks '' RUN dotnet build `` Libertas.Host.Tickers.ScheduledTasks.csproj '' -c Release -o /app/buildFROM build AS publishRUN dotnet publish `` Libertas.Host.Tickers.ScheduledTasks.csproj '' -c Release -o /app/publishFROM base AS finalWORKDIR /appCOPY -- from=publish /app/publish .ENTRYPOINT [ `` dotnet '' , `` Libertas.Host.Tickers.ScheduledTasks.dll '' ] 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-applaunch ? framework=Microsoft.AspNetCore.App & framework_version=3.1.0 & arch=x64 & rid=debian.10-x64 | Unable to debug dotnet core GenericHost docker container |
C_sharp : 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 translated to CIL as IL_0016 : callvirt instance void ConsoleApplication1.Animal : :OverRideMe ( ) I had cast the animal object to Dog type . Why should dog.OverRideMe ( ) ; be translated to the above statement in CIL ? The output of the above code is : This output has nothing to do with Base class Animal but CIL still places a call to it . <code> 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 '' ) ; } public virtual void OverRideMe ( ) { Console.WriteLine ( `` In Base Class 's OverRideMe '' ) ; Console.Read ( ) ; } } public class Dog : Animal { public Dog ( ) { Console.WriteLine ( `` Derived Constructor '' ) ; } public override void OverRideMe ( ) { Console.WriteLine ( `` In Derived Class 's OverRideMe '' ) ; Console.Read ( ) ; } public void NewMethod ( ) { Console.WriteLine ( `` In Derived Class 's NewMethod '' ) ; Console.Read ( ) ; } } .method private hidebysig static void Main ( string [ ] args ) cil managed { // Method begins at RVA 0x2050 // Code size 42 ( 0x2a ) .maxstack 1 .entrypoint .locals init ( [ 0 ] class ConsoleApplication1.Animal animal , [ 1 ] class ConsoleApplication1.Dog dog ) IL_0000 : nop IL_0001 : newobj instance void ConsoleApplication1.Dog : :.ctor ( ) IL_0006 : stloc.0 IL_0007 : ldloc.0 IL_0008 : callvirt instance void ConsoleApplication1.Animal : :OverRideMe ( ) IL_000d : nop IL_000e : ldloc.0 IL_000f : castclass ConsoleApplication1.Dog IL_0014 : stloc.1 IL_0015 : ldloc.1 IL_0016 : callvirt instance void ConsoleApplication1.Animal : :OverRideMe ( ) IL_001b : nop IL_001c : ldloc.1 IL_001d : callvirt instance void ConsoleApplication1.Dog : :NewMethod ( ) IL_0022 : nop IL_0023 : call int32 [ mscorlib ] System.Console : :Read ( ) IL_0028 : pop IL_0029 : ret } // end of method Program : :Main IL_000f : castclass ConsoleApplication1.DogIL_0014 : stloc.1IL_0015 : ldloc.1IL_0016 : callvirt instance void ConsoleApplication1.Animal : :OverRideMe ( ) IL_001b : nopIL_001c : ldloc.1IL_001d : callvirt instance void ConsoleApplication1.Dog : :NewMethod ( ) | Regarding Inheritance C # |
C_sharp : 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 Object parameter as second parameter , and C # Compiler gives a strange error Severity Code Description Project File Line Error CS1503 Argument 2 : can not convert from 'object ' to ' . 'It works with `` null '' ... No compiler error or run time error [ ignored i think ] How those guys can able to write such a code in C # ? Is It Posssible ? Any idea ? Note : I suspect from a code obscurification problem ... But still i do not understand what is going here <code> 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_sharp : 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 file you must declare the model - for example : This means that if you have a DisplayFor which takes a MyOtherNamespace.Class1 you get a runtime error due to a type mismatch.If you knew in advance the places where this was going to happen you could use the UIHint to force the DisplayFor to use an alternative template ( or you could use a named template directly in the view ) . But if you do n't know in advance ( you have all these objects in an enumeration of some kind and therefore ca n't write specific code to handle edge cases like this without a lot of unwieldy reflection - is there any way to have DisplayTemplates for these classes ? <code> MyNamespace.Class1MyOtherNamespace.Class1 Class1.cshtml @ model MyNamespace.Class1 | How to handle MVC DisplayTemplates for two classes with the same name ( different namespaces ) |
C_sharp : 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 containing other characters '' should be `` 1/2 , is anumber containing other characters '' '' this also 12-3 has numbers '' should be `` this also 12-3 , hasnumbers '' Thank you allEDIT : My example does not account for any special characters . I did n't include it originally as I thought I 'd get a fresh perspective if someone can do this more efficiently - my bad ! <code> 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 { output += $ '' { value } `` ; } } } return output ; } | C # Add comma after every number sequence in string |
C_sharp : 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 I should have mentioned the exception is a System.FormatException , `` Input string was not in a correct format . '' <code> 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_sharp : 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 . I 'm to blind to see my error at the moment . The question is why is .net behaving like this ? I 'm Using Visual Studio 2015 with .net 4.5.2 . <code> 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 gesamtPreis = Math.Round ( beleg.PreisDB ? ? 0 + beleg.PreisCouponDB ? ? 0 , 2 ) ; beleg.PreisDB == 8.39beleg.PreisDB ? ? 0 == 8.39beleg.PreisCouponDB == -0.49beleg.PreisCouponDB ? ? 0 == -0.49 beleg.PreisDB ? ? 0 + beleg.PreisCouponDB ? ? 0 == 8.39Math.Round ( beleg.PreisDB ? ? 0 + beleg.PreisCouponDB ? ? 0 , 2 ) == 8.39gesamtPreis == 8.39 | Addition in C # .net does n't work in some cases |
C_sharp : 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 the advantages of this approach to the above one , he was n't very sure . But he insisted that you should n't use the business models directly in your views and that only view models should be validated.My questions : Should I keep my validation logic in view models or business models ? Is it bad to have view models depend on business models ? <code> 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 class ProductViewModel { public Product Product { get ; set ; } public IList < Category > Categories { get ; set ; } } public class ProductViewModel { public int ProductId { get ; set ; } [ Required ] [ StringLength ( 25 ) ] public string Name { get ; set ; } public string Description { get ; set ; } public int CategoryId { get ; set ; } public IList < SelectListItem > CategoryDropdownValues { get ; set ; } } | What should be in my View Models ? |
C_sharp : 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 the code that I 'm using to do that ( I know it 's very inefficient , but it works and thats my main priority now ) My problem here is that sometimes I keep getting only 1 back from this for several thousand elements in a row which kills the performance of the skip list . The chance for 10.000 elements to generate only 1 from this method in a row , seems very slim ( happens pretty consistently ) .So I 'm assuming ( guessing ) that there is a problem with the Random object in some way , but I do n't really know where to start digging around . So I turn to stackoverflow to see if anyone has an idea ? EditThe rnd-variable is declared in the class SkipList < T > , and it is accessed from several threads ( each thread calls .Add on the collection and Add calls .randomLevel ) <code> int randomLevel ( ) { int height = 1 ; while ( rnd.NextDouble ( ) > = 0.5 & & height < MaxHeight ) ++height ; return height ; } | Problem with Random and Threads in .NET |
C_sharp : 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 it . And I can update the apps in parallel.The other apps are written in c # and when I started to write a reference ( mock ) implementation I realised that this would require any implementer to use a FSharpAsync type which is not very pretty.So , how do I define the interface so that it is easy to implement in c # and keep the async aspects ? <code> type IConnect = abstract Update : seq < DataType > - > Async < bool > | How to define an async f # interface that can be implemented in c # ? |
C_sharp : 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 releasesResourceOnDestruction did n't have it 's destructor called . This seems to indicate that the C++ stack is not being unwound properly -- is it possible to get it to unwind properly here ? Is there any documentation on this behavior ? For context : I want to sometimes trigger a C # exception from C++ code if possible , so that I do n't need every call from C # into C++ have to check something afterwards to see if a C # exception needs to be thrown . <code> 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 ) ; } } [ UnmanagedFunctionPointer ( CallingConvention.Cdecl ) ] delegate void CsFuncToBeCalledFromCpp ( ) ; [ DllImport ( `` CppApp '' , CallingConvention = CallingConvention.Cdecl ) ] private static extern void CppFunc ( CsFuncToBeCalledFromCpp callback ) ; } void CppFunc ( void ( *handler ) ) { SomeResourceWrappingClass releasesResourceOnDestruction ( ) ; handler ( ) ; } | How to call a throwing C # function from C++ in a C # app such that the C++ stack is unwound properly ? |
C_sharp : 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 , I decided to rewrite it in C # .After port-monitoring the original dos-exe I 've found that it 's really not interested in you rebuilding it - requests must be answered suitable , varying bytes , pre-sent `` ping '' messages , etc ... Maybe you know a similar checksum routine/pattern as my dos-exe uses or you could give any tips in trying to reverse-engineer this ... Additionally , because I am only familiar with programming and did n't spend much time on reversing methods and/or analyzing protocols , please do n't judge me if this topic is a bit of a stupid idea - I 'll be glad about any help I get ... The message really containing the text that should be displayed is 143 bytes long ( just that long because it puts filler bytes if you do n't use up all the space with your text ) , and in that msg I noticed the following patterns : The fourth byte ( which still belongs to the msg header ) varies from a list of 6 or 7 repeating values ( in my examples , that byte will always be 0F ) .The two last bytes function as a checksumSome examples : displayed text : `` 123 '' ( hex : `` 31 32 33 '' ) , checksum hex : `` 45 52 '' text : `` 132 '' ( `` 31 33 32 '' ) , checksum hex : `` 55 FF '' text : `` 122 '' ( `` 31 32 32 '' ) , checksum hex : `` 95 F4 '' text : `` 133 '' ( `` 31 33 33 '' ) , checksum hex : `` 85 59 '' text : `` 112 '' ( `` 31 31 32 '' ) , checksum hex : `` C5 C8 '' text : `` 124 '' ( `` 31 32 34 '' ) , checksum hex : `` 56 62 '' text : `` 134 '' ( `` 31 33 34 '' ) , checksum hex : `` 96 69 '' text : `` 211 '' ( `` 32 31 31 '' ) , checksum hex : `` 5D 63 '' text : `` 212 '' ( `` 32 31 32 '' ) , checksum hex : `` 3C A8 '' text : { empty } , checksum hex : `` DB BA '' text : `` 1 '' ( `` 31 '' ) , checksum hex : `` AE 5F '' So far I am completely sure that the checksum really does depend on this fourth byte in the header , because if it changes , the checksums will be completely different for the same text to be displayed.Here 's an an example of a full 143 bytes-string displaying `` 123 '' , just for giving you a better orientation : ( the text information starts with 2nd byte in 2nd line `` 31 00 32 00 33 00 ( ... ) '' Unfortunately on the whole web , there are no user manuals , documentations , not even a real evidence that this info board-device ever existed . <code> 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 . . . . . .þ ... .04 01 03 00 01 03 00 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 20 00 20 00 20 00 20 00 20 00 20 45 52 | How would I reverse this simple-looking algorithm ? |
C_sharp : 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 time . Right now , the comparison is made by the following code : where , say , _keyProperties [ x ] .GetValue ( entity , null ) is a object { long } and keyValues [ x ] is a object { int } ( but they can be inverted as well ) .I need this because I am building a mock repository for my unit tests , and I have started by including a generic repository implementation as described here . This implementation compares two generic fake-DB keys in its Find method . <code> _keyProperties [ x ] .GetValue ( entity , null ) .Equals ( keyValues [ x ] ) | Compare boxed objects in C # |
C_sharp : 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 refers to that but as a beginner getting an answer with appropriate context , which the accepted answer provides , is quite helpful . <code> < 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_sponsor > Jon Doe < /bus_sponsor > < /row > < /root > class Program { static void Main ( string [ ] args ) { XElement main = XElement.Load ( `` master_list.xml '' ) ; var results = main.Descendants ( `` row '' ) .Descendants ( `` bus_contact '' ) .Where ( e = > e.Value == `` Jon Doe '' ) .Select ( e = > e.Parent ) .Select ( e = > new { project_id = e.Descendants ( `` project_id '' ) .FirstOrDefault ( ) .Value , project_name = e.Descendants ( `` project_name '' ) .FirstOrDefault ( ) .Value } ) ; foreach ( var result in results ) Console.WriteLine ( `` { 0 } , { 1 } '' , result.project_id , result.project_name ) ; Console.ReadLine ( ) ; } } | How to add OR condition in LINQ while querying XML ? |
C_sharp : 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 run this action on all Sites ? <code> 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 ( site ) ; siteOperation.KillJames ( ) ; } foreach ( Sites site in _sitesManagement.GetAll ( ) ) { SiteOperation siteOperation = new SiteOperation ( site ) ; siteOperation.FlyToMoon ( 2012 , new TaskIdentifier ( 10,20 ) ) ; } | similar function refactoring pattern |
C_sharp : 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 . <code> [ 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 , Is.EqualTo ( DateTime.Parse ( dateTime.ToString ( `` o '' ) ) ) ) ; } Expected : 2011-10-31 12:03:04.161But was : 2011-10-31 06:33:04.161 | What is causing this behavior , in our C # DateTime type ? |
C_sharp : 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 to cast object of type 'System.Collections.Generic.List ` 1 [ System.Int32 [ * ] ] ' to type 'System.Collections.Generic.List ` 1 [ System.Int32 [ ] ] '.Any ideas what may be causing this or how to resolve it ? I am working in visual studio 2010 express on .net 4.0 . <code> 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 ( null ) ; List < int [ ] > list = ( List < int [ ] > ) instance ; | Unable to cast List < int [ * ] > to List < int [ ] > instantiated with reflection |
C_sharp : 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 simplified it for the sake of my question ( my code is basically StockBrokerTest.CalculateNetWorthAsync_AuthenticationFailure_ThrowsDelayed ( ) but with TimeMachine and Advancer operations inlined ) .Let 's suppose we have a class to test a failed login ( no unit test framework to simplify the question ) : Where the implementation of ManuallyPumpedSynchronizationContext is : The output is : My question is : Why do we need the ManuallyPumpedSynchronizationContext ? Why is n't the default SynchronizationContext enough ? The Post ( ) method is n't even called ( based on the output ) . I 've tried commenting the lines marked with // Comment this , and the output is the same and the asserts pass.If I understood correctly what Jon Skeet says in the video , the SynchronizationContext.Post ( ) method should be called when we meet an await with a not-yet-completed task . But this is not the case . What am I missing ? Aditional infoThrough my researches , I stumbled across this answer . To try it , I changed the implementation of the Login ( ) method to : With that modification , the Post ( ) method was indeed called . Output : So with Jon Skeet 's use of TaskCompletionSource , was his creation of ManuallyPumpedSynchronizationContext not required ? Note : I think the video I saw was made just around C # 5 release date . <code> 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.SetSynchronizationContext ( context ) ; // Comment this // Run method under test var result = MethodToBeTested ( ) ; Debug.Assert ( ! result.IsCompleted , `` Result should not have been completed yet . `` ) ; // Advancing time Console.WriteLine ( `` Before advance '' ) ; loginPromise.SetResult ( null ) ; context.PumpAll ( ) ; // Comment this Console.WriteLine ( `` After advance '' ) ; // Check result Debug.Assert ( result.IsFaulted , `` Result should have been faulted . `` ) ; Debug.Assert ( result.Exception.InnerException.GetType ( ) == typeof ( ArgumentException ) , $ '' The exception should have been of type { nameof ( ArgumentException ) } . `` ) ; Console.WriteLine ( `` == END == '' ) ; Console.ReadLine ( ) ; } private static async Task < int > MethodToBeTested ( ) { Console.WriteLine ( `` Before login '' ) ; var userId = await Login ( ) ; Console.WriteLine ( `` After login '' ) ; if ( userId == null ) { throw new ArgumentException ( `` Bad username or password '' ) ; } return userId.GetHashCode ( ) ; } private static Task < Guid ? > Login ( ) { return loginPromise.Task ; } } public sealed class ManuallyPumpedSynchronizationContext : SynchronizationContext { private readonly BlockingCollection < Tuple < SendOrPostCallback , object > > callbacks ; public ManuallyPumpedSynchronizationContext ( ) { callbacks = new BlockingCollection < Tuple < SendOrPostCallback , object > > ( ) ; } public override void Post ( SendOrPostCallback callback , object state ) { Console.WriteLine ( `` Post ( ) '' ) ; callbacks.Add ( Tuple.Create ( callback , state ) ) ; } public override void Send ( SendOrPostCallback d , object state ) { throw new NotSupportedException ( `` Synchronous operations not supported on ManuallyPumpedSynchronizationContext '' ) ; } public void PumpAll ( ) { Tuple < SendOrPostCallback , object > callback ; while ( callbacks.TryTake ( out callback ) ) { Console.WriteLine ( `` PumpAll ( ) '' ) ; callback.Item1 ( callback.Item2 ) ; } } } == START ==Before loginBefore advanceAfter loginAfter advance== END == private static Task < Guid ? > Login ( ) { // return loginPromise.Task ; return Task < Guid ? > .Factory.StartNew ( ( ) = > { Console.WriteLine ( `` Login ( ) '' ) ; return null ; } , CancellationToken.None , TaskCreationOptions.None , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; } == START ==Before loginPost ( ) Before advancePumpAll ( ) Login ( ) After loginAfter advance== END == | Was ManuallyPumpedSynchronizationContext required in Jon Skeet 's `` TimeMachine '' async unit test framework ? |
C_sharp : I have the following piece of code : But the stringBuilder appends text MyNamespace.MyClass+CD instead of A or X . Why does this happen ? <code> 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_sharp : 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 use to make a websocket connection.I did get a code sample which is in Python that I do n't know the syntax of , but I can use it as a guide to convert it to C # -syntax.This is the Python code sample : So I have tried to convert this into C # and this is the code I got so far : So the next part is where I 'm really struggling . There needs to be some HMAC-calculation that needs to be done but I 'm completely lost there . <code> 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_request.add_header ( `` API-Sign '' , base64.b64encode ( hmac.new ( base64.b64decode ( `` API_PRIVATE_KEY '' ) , b '' /getToken '' + hashlib.sha256 ( api_nonce + b '' nonce= % s '' % api_nonce ) .digest ( ) , hashlib.sha512 ) .digest ( ) ) ) print ( json.loads ( urllib.request.urlopen ( api_request ) .read ( ) ) [ 'result ' ] [ 'token ' ] ) static string apiPublicKey = `` API_PUBLIC_KEY '' ; static string apiPrivateKey = `` API_PRIVATE_KEY '' ; static string endPoint = `` https : //www.website.com/getToken '' ; private void authenticate ( ) { using ( var client = new HttpClient ( ) ) { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls ; // CREATE THE URI string uri = `` /getToken '' ; // CREATE THE NONCE /// NONCE = unique identifier which must increase in value with each API call /// in this case we will be using the epoch time DateTime baseTime = new DateTime ( 1970 , 1 , 1 , 0 , 0 , 0 ) ; TimeSpan epoch = CurrentTime - baseTime ; Int64 nonce = Convert.ToInt64 ( epoch.TotalMilliseconds ) ; // CREATE THE DATA string data = string.Format ( `` nonce= { 0 } '' , nonce ) ; // CALCULATE THE SHA256 OF THE NONCE string sha256 = SHA256_Hash ( data ) ; // DECODE THE PRIVATE KEY byte [ ] apiSecret = Convert.FromBase64String ( apiPrivateKey ) ; // HERE IS THE HMAC CALCULATION } } public static String SHA256_Hash ( string value ) { StringBuilder Sb = new StringBuilder ( ) ; using ( var hash = SHA256.Create ( ) ) { Encoding enc = Encoding.UTF8 ; Byte [ ] result = hash.ComputeHash ( enc.GetBytes ( value ) ) ; foreach ( Byte b in result ) Sb.Append ( b.ToString ( `` x2 '' ) ) ; } return Sb.ToString ( ) ; } | Authentication with hashing |
C_sharp : 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.Each component has to implement the IComponent interface . By doing so I can store all the different component types to their matching component pool . Each pool is a Dictionary < Guid , IComponent > . The key represents the ID of the Entity and the value is the component of that entity . Each pool is stored in a KeyedByTypeCollection to make sure the component pool is unique.Currently my EntityManager class contains the core logic . I do n't know if it 's required to have it static but currently my systems need to get some information from it.The important core methods to deal with the component pools are : I created a small movement system for testing purposes : Which should be fine because of the dictionary lookups . I am not sure if I can optimize it but I think I have to loop through all the entities first.And here is the problem : I am not able to use KeyedByTypeCollection < Dictionary < Guid , IComponent > > because I need to have something likeKeyedByTypeCollection < Dictionary < Guid , Type where Type : IComponent > > My GetComponentPool and AddComponentPool methods throw errors.GetComponentPool : Can not implicitly convert IComponent to TComponentWhen calling GetComponentPool I would have to cast the dictionary values from IComponent to TComponent.AddComponentPool : Can not convert from TComponent to IComponentWhen calling AddComponentPool I would have to cast TComponent to IComponent.I do n't think casting is an option because this seems to lower the performance.Would someone mind helping me fix the type problem ? Update : When debugging I use this Code to test the whole ECSI already showed the Movement System , here are the missing components <code> 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 < Guid , IComponent > > ( ) ; public static KeyedByTypeCollection < ISystem > systems = new KeyedByTypeCollection < ISystem > ( ) ; // Hold unique Systems public static Guid CreateEntity ( ) // Add a new GUID and return it { Guid entityId = Guid.NewGuid ( ) ; activeEntities.Add ( entityId ) ; return entityId ; } public static void DestroyEntity ( Guid entityId ) // Remove the entity from every component pool { activeEntities.Remove ( entityId ) ; for ( int i = 0 ; i < componentPools.Count ; i++ ) { componentPools [ i ] .Remove ( entityId ) ; } } public static Dictionary < Guid , TComponent > GetComponentPool < TComponent > ( ) where TComponent : IComponent // get a component pool by its component type { return componentPools [ typeof ( TComponent ) ] ; } public static void AddComponentPool < TComponent > ( ) where TComponent : IComponent // add a new pool by its component type { componentPools.Add ( new Dictionary < Guid , TComponent > ( ) ) ; } public static void RemoveComponentPool < TComponent > ( ) where TComponent : IComponent // remove a pool by its component type { componentPools.Remove ( typeof ( TComponent ) ) ; } public static void AddComponentToEntity ( Guid entityId , IComponent component ) // add a component to an entity by the component type { componentPools [ component.GetType ( ) ] .Add ( entityId , component ) ; } public static void RemoveComponentFromEntity < TComponent > ( Guid entityId ) where TComponent : IComponent // remove a component from an entity by the component type { componentPools [ typeof ( TComponent ) ] .Remove ( entityId ) ; } } internal class Movement : ISystem { public void Run ( ) { for ( int i = 0 ; i < EntityManager.activeEntities.Count ; i++ ) { Guid entityId = EntityManager.activeEntities [ i ] ; if ( EntityManager.GetComponentPool < Position > ( ) .TryGetValue ( entityId , out Position positionComponent ) ) // Get the position component { positionComponent.X++ ; // Move one to the right and one up ... positionComponent.Y++ ; } } } } internal class Program { private static void Main ( string [ ] args ) { EntityManager.AddComponentPool < Position > ( ) ; EntityManager.AddComponentPool < MovementSpeed > ( ) ; EntityManager.Systems.Add ( new Movement ( ) ) ; Guid playerId = EntityManager.CreateEntity ( ) ; EntityManager.AddComponentToEntity ( playerId , new Position ( ) ) ; EntityManager.AddComponentToEntity ( playerId , new MovementSpeed ( 1 ) ) ; foreach ( ISystem system in EntityManager.Systems ) { system.Run ( ) ; } } } internal class Position : IComponent { public Position ( float x = 0 , float y = 0 ) { X = x ; Y = y ; } public float X { get ; set ; } public float Y { get ; set ; } } internal class MovementSpeed : IComponent { public MovementSpeed ( float value = 0 ) { Value = value ; } public float Value { get ; set ; } } | create performant component pooling for system loops |
C_sharp : 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 int , int overload ) .And if i do put the generic type-parameter of < int > in , ReSharper says it 's redundant.So my question is : if the way i do it is still type-safe , why use generic assertions ? <code> [ 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_sharp : 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 have to give the exact definition of the delegate but this still does n't helped me ; Do you have an idea ? <code> 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_sharp : 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 : <code> public void DoLongOperation ( ) { for ( int i=beginPoint ; i < endPoint ; i++ ) { doSomethingStupid ( dataArray [ i ] ) ; } } | Threading in C # . Interruptable task |
C_sharp : 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 to achieve.C # ViewModelMy HTML/Razor and knockout ModuleMy Result looks likeProblem Nr 1When I enter all information and adding few project services item 's my controller receive model but Service 's properties are empty and I ca n't figure out why ? What I 'm doing wrong ? Problem Nr 2Next to Project Service panel ( see design screenshot ) I will build another almost the same panel but in that window the same Add To List functionality should depend on which Item I select in Project Service Panel . For example : If I selected first item in Project Service panel on the right should appear panel with ADD button so I can put item to another list . After I put information to one item I can selected another and put there and panel should update based on Project Service selection . I ca n't find anywhere example , article or tutorial how to achieve this kind of result.Any kind of help with be helpful ! <code> 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.observable ( project ? project.ProjectTitle : `` '' ) ; self.WWSNumber = ko.observable ( project ? project.WWSNumber : `` '' ) ; self.AqStatus = ko.observable ( project ? project.AqStatus : `` '' ) ; self.Completed = ko.observable ( project ? project.Completed : `` '' ) ; self.StartDate = ko.observable ( project ? project.StartDate : `` '' ) ; self.EndDate = ko.observable ( project ? project.EndDate : `` '' ) ; self.ProjectLeader = ko.observable ( project ? project.ProjectLeader : `` '' ) ; self.Deputy = ko.observable ( project ? project.Deputy : `` '' ) ; self.SalesConsultant = ko.observable ( project ? project.SalesConsultant : `` '' ) ; self.Service = ko.observableArray ( project ? project.Service : [ ] ) ; } ; var ProjectService = function ( projectService ) { var self = this ; self.Id = ko.observable ( projectService ? projectService.Id : 0 ) ; self.Number = ko.observable ( projectService ? projectService.Number : `` '' ) ; self.Name = ko.observable ( projectService ? projectService.Name : `` '' ) ; self.Positions = ko.observableArray ( projectService ? projectService.Positions : [ ] ) ; } ; var ServicePosition = function ( servicePosition ) { var self = this ; self.Id = ko.observable ( servicePosition ? servicePosition.Id : 0 ) ; self.Number = ko.observable ( servicePosition ? servicePosition.Number : `` '' ) ; self.Name = ko.observable ( servicePosition ? servicePosition.Name : `` '' ) ; self.PerformanceGroup = ko.observable ( servicePosition ? servicePosition.PerformanceGroup : `` '' ) ; self.PerformanceGroupPrice = ko.observable ( servicePosition ? servicePosition.PerformanceGroupPrice : `` '' ) ; self.Remarks = ko.observable ( servicePosition ? servicePosition.Remarks : `` '' ) ; } ; var ProjectCollection = function ( ) { var self = this ; self.project = ko.observable ( new Project ( ) ) ; self.projectServices = ko.observableArray ( [ new ServicePosition ( ) ] ) ; self.servicePositions = ko.observableArray ( [ new ServicePosition ( ) ] ) ; self.addService = function ( ) { self.projectServices.push ( new ProjectService ( ) ) ; console.log ( self.projectServices ) ; } ; self.removeService = function ( projectService ) { self.projectServices.remove ( projectService ) ; } ; self.saveProject = function ( ) { self.project ( ) .Service = self.projectServices ; console.log ( self.projectServices ) ; console.log ( self.project ( ) ) ; var token = $ ( ' [ name=__RequestVerificationToken ] ' ) .val ( ) ; $ .ajax ( { type : `` POST '' , url : `` /LeistungManager/CreateProject '' , data : { __RequestVerificationToken : token , model : ko.toJS ( self.project ( ) ) } , dataType : `` json '' , cache : false , async : true , success : function ( response ) { } , complete : function ( response ) { console.log ( response ) ; } } ) ; } ; } ; ko.applyBindings ( new ProjectCollection ( ) ) ; < link href= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css '' rel= '' stylesheet '' / > < script src= '' https : //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js '' > < /script > < script src= '' https : //maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js '' > < /script > < script src= '' https : //cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js '' > < /script > < div class= '' row '' > < div class= '' col-md-6 '' > < div class= '' widget '' > < div class= '' widget-heading '' > < h3 class= '' widget-title '' > Project Services < /h3 > < div > < form class= '' form-inline '' > < p > < div class= '' form-group '' > < label > WWS-Number < /label > < input class= '' form-control '' placeholder= '' Number '' data-bind= '' value : $ root.Number '' / > < label > WWS-Number < /label > < input class= '' form-control '' placeholder= '' Name '' data-bind= '' value : $ root.Name '' / > < button class= '' btn btn-primary '' data-bind= '' click : addService '' > Add < /button > < /div > < /p > < /form > < /div > < /div > < div class= '' widget-body '' > < table data-bind= '' visible : projectServices ( ) .length > 0 `` class= '' table '' > < thead > < tr > < th > Number < /th > < th > Service Name < /th > < th > < /th > < /tr > < /thead > < tbody data-bind= '' foreach : projectServices '' > < tr > < td data-bind= '' text : $ parent.Number '' > < /td > < td data-bind= '' text : $ parent.Name '' > < /td > < td > < button class= '' btn btn-success '' > Edit < /button > < button class= '' btn btn-danger '' data-bind= '' click : $ root.removeService '' > Delete < /button > < /td > < /tr > < /tbody > < /table > < /div > < /div > < /div > < /div > | Posting Collection with Knockout.js |
C_sharp : 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 exception when I use either of these policies because I believe the pipeline tries to validate the auth token passed in on both authentication schemes . IDX10501 : Signature validation failed . Unable to match 'kid ' : The exception does n't bubble up and terminate requests it just adds lots of noise to my logging , has anyone encountered this exception when using multiple authentication schemes on one policy ? <code> 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 TokenValidationParameters { ClockSkew = TimeSpan.FromMinutes ( 5 ) , IssuerSigningKey = new SymmetricSecurityKey ( Encoding.UTF8.GetBytes ( authSettings.SymmetricKey ) ) , RequireSignedTokens = true , RequireExpirationTime = true , ValidateLifetime = true , ValidateAudience = true , ValidAudience = authSettings.Audience2 , ValidateIssuer = true , ValidIssuer = authSettings.Issuer2 } ; } ) ; services.AddAuthorization ( options = > { // Blocks auth provider 2 tokens by returning 403 because it does not have claim only present in tokens from auth provider 1 options.DefaultPolicy = new AuthorizationPolicyBuilder ( ) .RequireAuthenticatedUser ( ) .RequireClaim ( Constants.CLAIM_ONLY_IN_AUTH_1 ) .AddAuthenticationSchemes ( `` auth provider1 '' , `` auth provider2 '' ) .Build ( ) ; // Accepts both auth provider tokens options.AddPolicy ( `` accept both auth1 and auth2 policy '' , new AuthorizationPolicyBuilder ( ) .RequireAuthenticatedUser ( ) .AddAuthenticationSchemes ( `` auth provider1 '' , `` auth provider2 '' ) .Build ( ) ) ; } ) ; | Using multiple authentication schemes on policy causes signature validation failures |
C_sharp : 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 return different number streams.Using hard-coded seeds is a bad idea in my opinion since you get the same values again and again after restarting the program . What about this : I know this looks silly and naive , but it would avoid the same values after every restart and both of the seeds should differ . Or maybeAs you can see , I am a bit uncreative here and need your help . Thanks . <code> 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_sharp : 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 ? Initially I wondered if this was how the runtime internally represents an interface , by declaring an abstract class thus preventing it being new-ed up.It does appear to be following this idea , as shown by the .class . However , following that is interface . So the idea of needing to actually create an abstract class appears to be moot when the runtime already seems to support the concept of an interface.This leads me to a couple of questions : What is the purpose of the abstract interface , and why is an abstract interface valid at the IL level ? Why is .class and interface necessary , and why is this valid at the IL level ? If the runtime supports the concept of an interface , why is the .class or abstract required at all ? C # : IL : <code> 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_sharp : 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 feeling it could be done better . <code> 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 '' ] .ToString ( ) ) ) ; maxDate=new DateTime [ ] { maxDateCur , maxDate } .Max ( ) ; } | Get a Maximum Date value from X tables in DataSet |
C_sharp : 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 method , followed by the usage : Usage ( where FundShareholderController is my controller and x.JsFile ( ) is an action method thereon . ) : I hope this makes sense . Let me know if there are any missing details that you need to assist.BTW - any optimization tips are gladly taken on-board too . <code> 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.Method.Name ; var methodParams = call.Method.GetParameters ( ) ; if ( methodParams.Any ( ) ) { for ( int index = 0 ; index < methodParams.Length ; index++ ) { ParameterInfo parameterInfo = methodParams [ index ] ; Expression expression = call.Arguments [ index ] ; object objValue ; var expressionConst = expression as ConstantExpression ; if ( expressionConst ! =null ) { objValue = expressionConst.Value ; } else { Expression < Func < object > > expressionConstOther = Expression.Lambda < Func < object > > ( Expression.Convert ( expression , typeof ( object ) ) , new ParameterExpression [ 0 ] ) ; objValue = expressionConstOther.Compile ( ) ( ) ; } paramDic.Add ( parameterInfo.Name , objValue ) ; } } string controllerName = typeof ( T ) .Name ; if ( controllerName.EndsWith ( `` Controller '' , StringComparison.OrdinalIgnoreCase ) ) { controllerName = controllerName.Remove ( controllerName.Length - 10 , 10 ) ; } var routeValues = new RouteValueDictionary ( paramDic ) ; var urlHelper = new UrlHelper ( html.ViewContext.RequestContext ) ; var url = urlHelper.Action ( actionName , controllerName , routeValues ) ; const string linkFormat = `` < script type=\ '' text/javascript\ '' src=\ '' { 0 } \ '' > < /script > '' ; string link = string.Format ( linkFormat , url ) ; return link ; } return null ; } < % =Html.Script < FundShareholderController > ( x = > x.JsFile ( `` CreateInvestorBookingJsFile '' , 0 ) ) % > | LINQ extension method help sought II |
C_sharp : 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 trick but changing IManager < TIdentifier > into IManager < in TIdentifier > does not help either.So , is there a way do cast specificManager into an IManager < IIdentifier > ? Thanks and all the best . <code> 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 { } internal interface ISpecificEntity : IIdentifier { } internal class SpecificEntity : ISpecificEntity { } internal interface IManager < TIdentifier > where TIdentifier : IIdentifier { void DoStuffWith ( TIdentifier entity ) ; } internal class SpecificEntityManager : IManager < ISpecificEntity > { public void DoStuffWith ( ISpecificEntity specificEntity ) { } } } | How to implement generic polymorphism in c # ? |
C_sharp : 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 : <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 '' ; } private async void button1_Click ( object sender , EventArgs e ) { try { var task1 = methodOne ( ) ; await task1 ; txtLog.AppendText ( task1.Result + `` \n '' ) ; txtLog.AppendText ( `` All Done \n '' ) ; } catch ( OperationCanceledException oce ) { txtLog.AppendText ( `` Operation was cancelled '' ) ; } } private void button2_Click ( object sender , EventArgs e ) { _token.Cancel ( ) ; } | What Happens To a Task When It 's Cancelled ? |
C_sharp : 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 ? <code> 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_sharp : 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 ? <code> 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_sharp : I see some code of some guy that goes like this : What is while ( ... ) { ... } while ( ... ) statement ? is the following equivalent code ? <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_sharp : 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 . <code> `` 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.Append ( $ '' { folderParts [ j ] } . `` ) ; } newFolder.Append ( folderParts [ i ] ) ; } | Building a new path-like string from an existing one |
C_sharp : 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 start . <code> BundleTable.EnableOptimizations = ... foreach ( Bundle bundle in bundles ) { bundle.Transforms.Clear ( ) ; } | render unbundled assets for admin user role |
C_sharp : 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 compatibility ) because all will continue to be used internally . It must also gracefully degrade when it runs into missing/unknown features etc.The tools will be written in C # with WinForms and are for testing custom hardware.My goal would be something close to only having to create classes to add features and when data model changes come , create a new set of data model classes that will get created by a factory based on API version.The challenge for me is that future features then may depend on the specific data models , which may be mixed and matched ( until a final combo is reached ) . How would you handle this gracefully ? Of course , once a product is shipped , I would like to reuse the tool and just add code for newer products . Before I started here , every product cycle meant rewriting ( from scratch ) all the tooling , something I aim to prevent in the future : ) Question : What design techniques and patterns would you suggest or have had success with to maintain compatibility with multiple versions of an API/Data Model ? What pitfalls should I watch out for ? <code> < Edit > < Edit2 > < /Edit > | Suggestions for change tolerance |
C_sharp : 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 overload standard operators . Why does this implementation not result in an infinite recursion ( which a simple test shows it does n't recurse infinitely ) ? The first conditional expression is binary1 == binary2 , within the implementation of the operator overload that would get called if you used binary1 == binary2 outside the implementation , and I would have thought , inside as well . <code> [ 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 ( binary2 ) ) ) ) ; } | Referencing equality operator within equality operator implementation |
C_sharp : 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 ? <code> 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_sharp : 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 ? <code> 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 SendToExternalApiAsync ( ) { // some async code that is awaited with ConfigureAwait ( false ) ; } public async Task SaveStuff ( ) { await SaveStuffAsync ( ) .ConfigureAwait ( false ) ; await SendToExternalApiAsync ( ) .ConfigureAwait ( false ) ; } | Is there any reason to run async code inside a Task.Run ? |
C_sharp : 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 , can anyone describe the specific concerns that might arise with Martin Neal 's implementation that are properly resolved by Jon Skeet 's more involved implementation <code> 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 = > { var nextBox = boxes [ Interlocked.Increment ( ref currentIndex ) ] ; PropagateResult ( completed , nextBox ) ; } , TaskContinuationOptions.ExecuteSynchronously ) ; } return boxes.Select ( box = > box.Task ) ; } private static void PropagateResult < T > ( Task < T > completedTask , TaskCompletionSource < T > completionSource ) { switch ( completedTask.Status ) { case TaskStatus.Canceled : completionSource.TrySetCanceled ( ) ; break ; case TaskStatus.Faulted : completionSource.TrySetException ( completedTask.Exception.InnerExceptions ) ; break ; case TaskStatus.RanToCompletion : completionSource.TrySetResult ( completedTask.Result ) ; break ; default : throw new ArgumentException ( `` Task was not completed . `` ) ; } } public static IEnumerable < Task < T > > InCompletionOrder < T > ( this IEnumerable < Task < T > > source ) { var tasks = source.ToList ( ) ; while ( tasks.Any ( ) ) { var t = Task.WhenAny ( tasks ) ; yield return t.Result ; tasks.Remove ( t.Result ) ; } } | Is there a reason to prefer one of these implementations over the other |
C_sharp : 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 gained by returning IQueryqble , instead ? Is there some etiquette here that prefers one of the three ? My guess is that the second is more efficient , but that it does n't really matter unless there are millions of wombats in the wombat table . And returning an IQueryable does n't seem to matter much since we 're only ever returning a single wombat.Thanks in advance ! <code> 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 ( wombatID ) ; return db.Wombats.FirstOrDefault ( x = > x.ID == guid ) ; } | Compare efficiency of two different LINQ statements |
C_sharp : 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 introduce a FactType enum instead to do The suggestion has been raised because it is supposedly faster . I 'll admit that I 've not written any tests to try and discern the difference in performance , but I have two questions:1 ) Is 'querying on type ' like this inherently bad ? 2 ) Is n't adding a FactType enum just superfluous anyway , given that facts are strongly typed ? UPDATETo clarify , this is LINQ to objects and GdpFact : Fact.UPDATE 2We 've measured using current typical data ( 4 facts ) and the results are in : lookup on enum : 0.29660000000000003 millisecondslookup on type : 0.24530000000000002 millisecondsSo type lookup is faster in this context ! I will choose my accepted answer carefully . <code> .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_sharp : 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 that on a HexGrid the method GetDualPoint returns a TriPoint.Except ... I have a class full of generic algorithms , that operate on IGrids , for example : Now , the client suddenly has to know the little detail that the dual point of a HexPoint is a TriPoint , and we need to specify it as part of the type parameter list , even though it does not strictly matter for this algorithm : Ideally , I would like to make DualPoint a `` property '' of the type IPoint , so that HexPoint.DualPoint is the type TriPoint . Something that allows IGrid to look like this : and the function CalcShortestPath like this Of course , this is not possible , as far as I know.But is there a way I can change my design to mimic this somehow ? So thatIt expresses the relationship between the two typesIt prevents excessive type argument lists It prevents clients having to think too hard about how the concrete type `` specialises '' the type parameters of the interface the type implements.To give an indication of why this becomes a real problem : In my library IGrid actually has 4 type parameters , IPoint has 3 , and both will potentially increase ( up to 6 and 5 ) . ( Similar relations hold between most of these type parameters . ) Explicit overloads instead of generics for the algorithms are not practical : there are 9 concrete implementations of each of IGrid and IPoint . Some algorithms operate on two types of grids , and hence have a tonne of type parameters . ( The declaration of many functions are longer than the function body ! ) The mental burden was driven home when my IDE threw away all the type parameters during an automatic rename , and I had to put all the parameters back manually . It was not a mindless task ; my brain was fried.As requested by @ Iridium , an example showing when type inference fails . Obviously , the code below does not do anything ; it 's just to illustrate compiler behaviour . <code> 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 < HexPoint > { ... } class TriPoint : IPoint < TriPoint > { ... } class HexGrid : IGrid < HexPoint , TriPoint > { ... } class TriGrid : IGrid < TriPoint , HexPoint > { ... } TriPoint dual = hexGrid.GetDualPoint ( hexPoint , North ) ; static List < TPoint > CalcShortestPath < TPoint , TDualPoint > ( IGrid < TPoint , TDualPoint > grid , TPoint start , TPoint goal ) { ... } static List < TPoint > CalcShortestPath < TPoint , * > ( IGrid < TPoint , * > grid , TPoint start , TPoint goal ) { ... } interface IGrid < TPoint > where TPoint : IPoint < TPoint > //and TPoint has `` property '' DualPoint where DualPoint implements IPoint ... { IGrid < TPoint.DualPoint > GetDualGrid ( ) ; } static List < TPoint > CalcShortestPath < TPoint > ( IGrid < TPoint > grid , TPoint start , TPoint goal ) { ... } using System ; using System.Collections.Generic ; using System.Linq ; public interface IPoint < TPoint , TDualPoint > where TPoint : IPoint < TPoint , TDualPoint > where TDualPoint : IPoint < TDualPoint , TPoint > { } interface IGrid < TPoint , TDualPoint > where TPoint : IPoint < TPoint , TDualPoint > where TDualPoint : IPoint < TDualPoint , TPoint > { } class HexPoint : IPoint < HexPoint , TriPoint > { public HexPoint Rotate240 ( ) { return new HexPoint ( ) ; } //Normally you would rotate the point } class TriPoint : IPoint < TriPoint , HexPoint > { } class HexGrid : IGrid < HexPoint , TriPoint > { } static class Algorithms { public static IEnumerable < TPoint > TransformShape < TPoint , TDualPoint > ( IEnumerable < TPoint > shape , Func < TPoint , TPoint > transform ) where TPoint : IPoint < TPoint , TDualPoint > where TDualPoint : IPoint < TDualPoint , TPoint > { return from TPoint point in shape select transform ( point ) ; } public static IEnumerable < TPoint > TransformShape < TPoint , TDualPoint > ( IGrid < TPoint , TDualPoint > grid , IEnumerable < TPoint > shape , Func < TPoint , TPoint > transform ) where TPoint : IPoint < TPoint , TDualPoint > where TDualPoint : IPoint < TDualPoint , TPoint > { return from TPoint point in shape //where transform ( point ) is in grid select transform ( point ) ; } } class UserCode { public static void UserMethod ( ) { HexGrid hexGrid = new HexGrid ( ) ; List < HexPoint > hexPointShape = new List < HexPoint > ( ) ; //Add some items //Compiles var rotatedShape1 = Algorithms.TransformShape ( hexGrid , hexPointShape , point = > point.Rotate240 ( ) ) .ToList ( ) ; //Compiles var rotatedShape2 = Algorithms.TransformShape < HexPoint , TriPoint > ( hexPointShape , point = > point.Rotate240 ( ) ) .ToList ( ) ; //Does not compile var rotatedShape3 = Algorithms.TransformShape ( hexPointShape , point = > point.Rotate240 ( ) ) .ToList ( ) ; } } | Expressing type relationships and avoiding long type parameter lists in C # |
C_sharp : 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 ) , for which can be searched to know where do you have to fix some stuff.It 's to avoid warnings when compiling for empty catch clauses.Is there any other usecase or sense in that ? Is this good/bad coding style or practise ? Since this instruction does nothing , will it have some small impact on performance or will the compiler just remove it ? Which are better ways to do something like <code> try { //some Code } catch { 0.ToString ( ) ; } | Strange Exception Handling dummy instruction |
C_sharp : 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 some sort of coupling ? Like , What if I take a logger , ILogger , and create a file and database class that implement that interface.In my IoC , So why do I have to register or `` wire up '' anything ? Is n't this Dependency Injection via the Constructor ( Do I have fundamental misunderstanding ) ? I could put any logger in there that implemented ILogger.Would I create two of these ? <code> 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 logThis ( string message ) { //INSERT INTO table ... .. System.Console.WriteLine ( `` inserted into a databse table '' ) ; } } public class FileLogger : ILogger { public void logThis ( string message ) { System.Console.WriteLine ( `` logged via file '' ) ; } } public class DemoClass { public ILogger myLogger ; public DemoClass ( ILogger myLogger ) { this.myLogger = myLogger ; } public void logThis ( string message ) { this.myLogger.logThis ( message ) ; } } class Program { static void Main ( string [ ] args ) { DemoClass myDemo = new DemoClass ( new DatabaseLogger ( ) ) ; //Is n't this Dependency Injection ? myDemo.logThis ( `` this is a message '' ) ; Console.ReadLine ( ) ; } } } services.AddTransient < ILogger , DatabaseLogger > ( ) ; services.AddTransient < ILogger , FileLogger > ( ) ; | Why do I have to `` wire up '' Dependency Injection in ASP.NET MVC ? |
C_sharp : 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 into Dictionary like : Objects that implement ISomeInterface are loaded in runtime using Assembly and Activator.createInstance . In the moment of creation I do n't if objects implements ISomeInterface < int > or ISomeInterface < double > .Any help is very much appreciated . <code> 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 < ? > ( ) ; _objs.Add ( `` Object1 '' , new ObjectI ( ) ) ; _objs.Add ( `` Object2 '' , new ObjectII ( ) ) ; _objs.Add ( `` Object3 '' , new ObjectII ( ) ) ; foreach ( var keyVal in _objs ) { Console.WriteLine ( keyVal.Method ( ) ) ; } | Question about generics in C # comparing to Java |
C_sharp : 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 programmers ) define all of their data as properties.If the users want to use pre-existing classes that have `` normal '' fields ( as opposed to properties ) , I can not detect those accesses . Example : I can not detect accesses to y . However , I want to allow the use of pre-existing classes . As a compromise the users are responsible for notifying me whenever an access to that kind of data occurs . For example : Something like that . Believe me , I 've researched this very thoroughly and even directly analysing the bytecode to detect accesses is n't reliable due to possible indirections , etc . I really do need the users to notify me.And now my question : could you recommend an `` elegant '' way to perform these notifications ? ( Yes , I know this whole situation is n't `` elegant '' to begin with ; I 'm trying not to make it worse ; ) ) . How would you do it ? This is a problem for me because actually the situation is like this : I have the following class : If the user wants to do this : They must instead do something like this : Where Write will return a clone of notSoNice , which is what I wanted the set accessor to do anyway . However , using a string is pretty ugly : if later they refactor the field they 'll have to go over their Write ( `` notSoNice '' ) accesses and change the string.How can we identify the field ? I can only think of strings , ints and enums ( i.e. , ints again ) . But : We 've already discussed the problem with strings.Ints are a pain . They 're even worse because the user needs to remember which int corresponds to which field . Refactoring is equally difficult.Enums ( such as NOT_SO_NICE and Z , i.e. , the fields of SemiNiceClass ) ease refactoring , but they require the user to write an enum per class ( SemiNiceClass , etc ) , with a value per field of the class . It 's annoying . I do n't want them to hate me ; ) So why , I hear you ask , can we not do this ( below ) ? Because I need to know what field is being accessed , and semiNice.notSoNice does n't identify a field . It 's the value of the field , not the field itself.Sigh . I know this is ugly . Believe me ; ) I 'll greatly appreciate suggestions.Thanks in advance ! ( Also , I could n't come up with good tags for this question . Please let me know if you have better ideas , and I 'll edit them ) EDIT # 1 : Hightechrider 's suggestion : Expressions.I do n't know if Write ( x = > semiNice.y , 0 ) was meant to be based on the classes I wrote for my question ( SemiNiceClass , etc ) or if it 's just an example , but if it 's the former it does n't match the structure : there 's no y field in SemiNiceClass . Did you mean Write ( x = > semiNice.notSoNice.y , 0 ) ? I 'm not sure how you mean for me to use this ... I 'll post the code I 've written : How do I get that info in Write ? I ca n't find any way to extract that information out of the Func < , > . Also , why write semiNice.Write ( x = > semiNice.notSoNice.y , 50 ) ; instead of semiNice.Write ( ( ) = > semiNice.notSoNice.y , 50 ) ; , since we 're not using x for anything ? Thanks.EDIT # 2 : Hans Passant 's suggestion : replacing fields with properties.This is what I originally intended to do , but recompiling is not an option.EDIT # 3 : Ben Hoffstein 's suggestion : dynamic proxies ; LinFu.I 've already looked into this long and hard , and for relatively complex reasons I can not use it . It would be too long to explain , but rest assured : if I could use it , I would . It 's much , much neater than my current solution . <code> 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 ; } } SemiNiceClass semiNice ; ... semiNice.notSoNice.y = 0 ; semiNice.Write ( `` notSoNice '' ) .y = 0 ; semiNice.Write ( semiNice.notSoNice ) .y = 0 ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Test.MagicStrings { public class MagicStringsTest { public static void Main ( string [ ] args ) { SemiNiceClass semiNice = new SemiNiceClass ( ) ; // The user wants to do : semiNice.notSoNice.y = 50 ; semiNice.Write ( x = > semiNice.notSoNice.y , 50 ) ; } } public class SemiNiceClass { public NotSoNiceClass notSoNice { get ; set ; } public int z { get ; set ; } public SemiNiceClass ( ) { notSoNice = new NotSoNiceClass ( ) ; } public void Write ( Func < object , object > accessor , object value ) { // Here I 'd like to know what field ( y , in our example ) the user wants to // write to . } } public class NotSoNiceClass { public int y ; } } | An `` elegant '' way of identifying a field ? |
C_sharp : 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 'm thinking about making two dictionaries that will save all the discounts for each genre , like this : So now i need to check the genre of each book in order to find the highest discount , is there any better way to do it than : is there a way to select the correct dictionary without checking for the type ? or maybe even a way to do it without the dictionaries , or using one ? maybe somehow connect book type with the Enum ? will be glad to hear any suggestions for improvement . ( there are a lot of more discounts based on books name , date and author . Even some more book types that is why this way does n't seem right to me ) Thank you . <code> 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 List < TextBooksGenre > Genres { get ; set ; } } Dictionary < ReadingBooksGenre , int > _readingBooksDiscounts ; Dictionary < TextBooksGenre , int > _textBooksDiscounts ; private int GetDiscount ( Book b ) { int maxDiscount = 0 ; if ( b is ReadingBook ) { foreach ( var genre in ( b as ReadingBook ) .Genres ) { // checking if the genre is in discount , and if its bigger than other discounts . if ( _readingBooksDiscounts.ContainsKey ( genre ) & & _readingBooksDiscounts [ genere ] > maxDiscount ) { maxDiscount = _readingBooksDiscounts [ genere ] ; } } } else if ( b is TextBook ) { foreach ( var genre in ( b as TextBook ) .Genres ) { if ( _textBooksDiscounts.ContainsKey ( genre ) & & _textBooksDiscounts [ genere ] > maxDiscount ) { maxDiscount = _textBooksDiscounts [ genere ] ; } } } return maxDiscount ; } | selecting correct list of Enums from 2 derived classes |
C_sharp : 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 or WoodLet 's say the effect of choosing Pencil or Brush is really drastically different , and the same goes for the IPattern type . Would it be a bad idea to code the Drawer class with Generic concepts like this : One could then use that class like : I mostly used generic for collections and such and have n't really see generics used for that kind of thing . Should I ? <code> 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 > , Mosaic > ( ) ; | Using Generics in a non-collection-like Class |
C_sharp : 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 ? <code> 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 ) ; // Here model is full with all needed data } [ HttpPost ] public ActionResult ProfileSettings ( ProfileSettingsViewModel model ) { // Passed model is not good Context con = new Context ( ) ; con.Entry ( model.UserProfile ) .State = EntityState.Modified ; con.SaveChanges ( ) ; return RedirectToAction ( `` Index '' , `` Home '' ) ; } @ using ( Html.BeginForm ( `` ProfileSettings '' , `` User '' , FormMethod.Post , new { id = `` submitProfile '' } ) ) { < li > < label > First Name < /label > @ Html.TextBoxFor ( a = > a.UserProfile.FirstName ) < /li > < li > < label > Last Name < /label > @ Html.TextBoxFor ( a = > a.UserProfile.LastName ) < /li > ... < input type= '' submit '' value= '' Save '' / > ... | Model object incomplete when try to update |
C_sharp : 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 would not be modifiable.How to achieve that ? <code> 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 < Course > GetCourses ( ) { return _items ; } public Teacher ( ) { if ( _items == null ) { _items = new List < Course > ( ) ; } _items.Add ( new Course ( 1 , `` cpp '' ) ) ; _items.Add ( new Course ( 1 , `` java '' ) ) ; _items.Add ( new Course ( 1 , `` cs '' ) ) ; } public void Show ( ) { Console.WriteLine ( this._id ) ; Console.WriteLine ( this._message ) ; } public void ShowList ( ) { foreach ( Course c in _items ) { c.Show ( ) ; } } } class Course { 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 Course ( int id , string msg ) { _id = id ; _message = msg ; } private List < Teacher > _items ; public List < Teacher > GetTeachers ( ) { return _items ; } public Course ( ) { if ( _items == null ) { _items = new List < Teacher > ( ) ; } _items.Add ( new Teacher ( 1 , `` ttt '' ) ) ; _items.Add ( new Teacher ( 1 , `` ppp '' ) ) ; _items.Add ( new Teacher ( 1 , `` mmm '' ) ) ; } public void Show ( ) { Console.WriteLine ( this._id ) ; Console.WriteLine ( this._message ) ; } public void ShowList ( ) { foreach ( Teacher t in _items ) { t.Show ( ) ; } } } class Program { static void Main ( string [ ] args ) { Teacher t = new Teacher ( ) ; t.ID = 1 ; t.Message = `` Damn '' ; t.Show ( ) ; t.ShowList ( ) ; t.GetCourses ( ) .Clear ( ) ; t.Show ( ) ; t.ShowList ( ) ; Console.ReadLine ( ) ; } } | List < T > is cleared problem |
C_sharp : 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 : Anyone is able to write it 's own implementation of Predicate interface by creating class that implements PredicateAnyone is able to write it 's own implementation of Predicate interface by creating anonymous implementation during call of filtering methodThere predefined set of class implementing Predicate , that covers many standard situation , so in most cases there is no need to write new implementation . Also there is a utility class that provides several static methods like and , or , allOf , anyOf , that allows to combine Predicates given as input into a new predicate ( internally it will return anonymous implementation of new Predicate ) Now I would like to have similar design in C # ( 4.0 ) application . I can see two way of doing it - by mimic Java design , or by change Predicate into delegate : I can try to mimic Java design , but : As far as I know there is no such thing like anonymous implementation of interface in C # ( so no creation of new predicate at the moment of calling filter method , and my util class have not to be based on anonymous implementations , but second is not the real problem ) I feel this is not a C # -way of doing such thingsI can try achieve similar design using delegates . My filter method will take collection of object and Predicate delegate . In such case : I do n't know how to achieve situation when one is able to write some type that will `` implements '' delegate . I imagine situation when someone will just write class with method that match signature of delegate - I do n't feel good about this strategy , because if I have interface to implement - compiler will force me to have correct signature - and since I can not `` extends '' or `` implements '' delegate - compiler will tell that I 'm wrong only when I will try to pass `` reference '' to this method to my filtering method ( Of course it will still be compile time error ) .Anyone is able to write it 's own implementation of Predicate interface by passing lambda , or pointing to some method with signature that match Predicate delegate . So here will be the same as in JavaI do n't know how to achieve situation when I have predefined sets of Predicates . I can see of course that is simple from technical point of view - I can for example write one class with static methods that will match signature of delegate - each of method will cover one Predicate . But I have a feeling that this approach is little bit inconsistent - because there will be one place with predefined predicates , and user 's predicates will be defined in another places ( In Java , both predefined and user-defined predicates will be classes that implements interface ) If Predicate will be delegate - I can also write some Util class that can combine predicates in many ways . Here is also the same as in JavaMy question is - what in your opinion will be best way of achieve the same ( or as similar as possible ) design that I have in Java , that will be considered as correct , clean C # -approach of doing that ? I have few years of experience in programming in Java , but less that a year in C # , so I understand that maybe some problems that I see just does n't exist in C # world or are not considered as problems at all.EDIT : here is simplest ( I think ... ) possible example of how my Java code work : My `` domain '' object : Filtering class : Predicate interface : Two simple predefined implementations : Utility class : And finally , example of usage : <code> 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 ; } } public class Filter { public Collection < Person > filter ( Collection < Person > collection , Predicate predicate ) { Collection < Person > result = new LinkedList < Person > ( ) ; for ( Person person : collection ) { if ( predicate.test ( person ) ) { result.add ( person ) ; } } return result ; } } public interface Predicate { boolean test ( Person person ) ; } public class FirstNameStartsWithPredicate implements Predicate { private final String startsWith ; public FirstNameStartsWithPredicate ( String startsWith ) { this.startsWith = startsWith ; } public boolean test ( Person person ) { return person.getFirstName ( ) .startsWith ( startsWith ) ; } } public class LastNameEndsWithPredicate implements Predicate { private final String endsWith ; public LastNameEndsWithPredicate ( String endsWith ) { this.endsWith = endsWith ; } public boolean test ( Person person ) { return person.getSecondName ( ) .endsWith ( endsWith ) ; } } public final class PredicateUtils { public static Predicate and ( final Predicate first , final Predicate second ) { return new Predicate ( ) { public boolean test ( Person person ) { return first.test ( person ) & & second.test ( person ) ; } } ; } public static Predicate or ( final Predicate first , final Predicate second ) { return new Predicate ( ) { public boolean test ( Person person ) { return first.test ( person ) || second.test ( person ) ; } } ; } public static Predicate allwaysTrue ( ) { return new Predicate ( ) { public boolean test ( Person person ) { return true ; } } ; } } Collection < Person > persons = Arrays.asList ( new Person ( `` John '' , `` Done '' ) , new Person ( `` Jane '' , `` Done '' ) , new Person ( `` Adam '' , `` Smith '' ) ) ; Filter filter = new Filter ( ) ; // Predefined predicatesfilter.filter ( persons , new FirstNameStartsWithPredicate ( `` J '' ) ) ; filter.filter ( persons , new LastNameEndsWithPredicate ( `` e '' ) ) ; // anonymous implementationfilter.filter ( persons , new Predicate ( ) { public boolean test ( Person person ) { return person.getFirstName ( ) .equals ( `` Adam '' ) & & person.getSecondName ( ) .equals ( `` Smith '' ) ; } } ) ; // utility classfilter.filter ( persons , PredicateUtils.allwaysTrue ( ) ) ; filter.filter ( persons , PredicateUtils.and ( new FirstNameStartsWithPredicate ( `` J '' ) , new LastNameEndsWithPredicate ( `` e '' ) ) ) ; filter.filter ( persons , PredicateUtils.or ( new FirstNameStartsWithPredicate ( `` J '' ) , new FirstNameStartsWithPredicate ( `` A '' ) ) ) ; | How to achieve similar design ( from Java ) that use interface and implementing classes , using delegates in C # |
C_sharp : 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 string ? UPDATEThese lines simulate my problem , you can see the Persian number by tracing this code : The last append should be an English number , but it 's not . <code> 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 ' , 'نام خانوادگی ' , 'اتاق چهار تخته '' ) ; temp.Append ( `` ' , ' '' ) ; temp.Append ( `` 234234 '' ) ; | StringBuilder appends Persian Numbers |
C_sharp : 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 other methods can only be achieved by casting.I know how to cast , as etc ... but is this acceptable ? Is it a best practice ? Just wondering if there are other ways to handle such scenarios . <code> foreach ( var item in Items ) { item.Draw ( ) ; // The casting would go here . } | Casting and interface inheritance |
C_sharp : 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 . <code> new ClassA ( ) .MethodA ( param1 , param2 ) ; ClassA classA = new ClassA ( ) ; classA.MethodA ( param1 , param2 ) ; | Invoking nonstatic methods of a class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.