text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : How can I sort a list based on a pre-sorted list . I have a list which is already sorted . Say , my sorted list is Now , I want to sort any subset of the above list in the same order as the above list . That is , if I have as input { `` Developer '' , `` Junior Developer '' } , I want the output as { `` Junior Developer '' , `` Developer '' } If the input is { `` Project Lead '' , `` Junior Developer '' , `` Developer '' } , I want the output as How can I achieve the same ? <code> { `` Junior Developer '' , `` Developer '' , `` Senior Developer '' , `` Project Lead '' } { `` Junior Developer '' , `` Developer '' , `` Project Lead '' } . | Sort a List based on a Pre-Sorted List |
C_sharp : I am trying to do is to get filepath for my excel file . But I am unable to do so.File is in Document/Visual Studio 2013/Project/ProjectName/a.xlsxIs it wrong way to do it or is it correct way ? <code> string path = Path.Combine ( HttpContext.Current.Server.MapPath ( `` ~/ '' ) , '' a.xlsx '' ) ; string SheetName= '' Sheet1 '' ; | Get FilePath for my excel file with sheetname |
C_sharp : I am using Activiz.NET to render some STLs in a C # tool . The renderwindow and renderer settings are as follows.Running the tool on an STL on my system results in the following image ( which is as expected ) . ( Click image for full size ) However , when two of my colleagues run the same tool on the exact same STL , they get the following image as output . ( Click image for full size ) Could these artefacts be related to different hardware of our three systems ? Does anyone have a solution that would ensure that the render quality is always the same on all systems ? <code> window.SetMultiSamples ( 0 ) ; window.SetAlphaBitPlanes ( 1 ) ; renderer.SetOcclusionRatio ( 0.1 ) ; renderer.SetUseDepthPeeling ( 1 ) ; | VTK ( Activiz ) rendering differently on different hardware |
C_sharp : Let me show you part of my XAML code : When too much borders are created ( it is linked with an ObservableCollection ) , a vertical scroll bar appears , and my border does n't resize on its own . ( I would like to see the complete border , I don t want it to be cut at the end ) If anyone has an idea , thanks ! Do n't hesitate to ask , if you need more information ! Rgds , Flo <code> < ListBox Grid.Row= '' 1 '' ScrollViewer.HorizontalScrollBarVisibility= '' Disabled '' ScrollViewer.IsDeferredScrollingEnabled= '' True '' HorizontalAlignment= '' Stretch '' ItemsSource= '' { Binding } '' Margin= '' 1,1,0,0 '' Name= '' listBox_Faits '' Width= '' 290 '' VerticalAlignment= '' Stretch '' SelectionChanged= '' listBox_Faits_SelectionChanged '' > < ListBox.ItemTemplate > < DataTemplate > < Border BorderBrush= '' SlateGray '' BorderThickness= '' 0.5 '' Margin= '' 1,2,1,1 '' Width= '' { Binding ElementName=listBox_Faits , Path=Width } '' > | Resize my border when a VerticalScrollBar appear |
C_sharp : Consider the following code : Anything wrong with this approach ? Is there a more appropriate way to build an array , without knowing the size , or elements ahead of time ? <code> List < double > l = new List < double > ( ) ; //add unknown number of values to the listl.Add ( 0.1 ) ; //assume we do n't have these values ahead of time.l.Add ( 0.11 ) ; l.Add ( 0.1 ) ; l.ToArray ( ) ; //ultimately we want an array of doubles | Efficiency : Creating an array of doubles incrementally ? |
C_sharp : I came across following code and do n't know what does having from twice mean in this code . Does it mean there is a join between Books and CSBooks ? <code> List < Product > Books = new List < Product > ( ) ; List < Product > CSBooks = new List < Product > ( ) ; var AllBooks = from Bk in Books from CsBk in CSBooks where Bk ! = CsBk select new [ ] { Bk , CsBk } ; | does using `` from '' more than once is equivalent to have join ? |
C_sharp : In spite of the RFC stating that the order of uniquely-named headers should n't matter , the website I 'm sending this request to does implement a check on the order of headers.This works : This does n't work : The default HttpWebRequest seems to put the Host and Connection headers at the end , before the blank line , rather than just after the url.Is there any way ( using a fork of HttpWebRequest or some other library in Nuget even ) to specify the order of headers in a HttpWebRequest ? If possible , I 'd rather not start going down the route of implementing a proxy to sort them or having to code the whole thing up using a TcpClient.I 'd appreciate any hints at all on this.Update : With Fiddler running , header order in HttpWebrequest can be re-shuffled in CustomRules.cs . Still no closer to a solution without a proxy though . <code> GET https : //www.thewebsite.com HTTP/1.1Host : www.thewebsite.comConnection : keep-aliveAccept : */*User-Agent : Mozilla/5.0 etc GET https : //www.thewebsite.com HTTP/1.1Accept : */*User-Agent : Mozilla/5.0 etcHost : www.thewebsite.comConnection : keep-alive | Strict ordering of HTTP headers in HttpWebrequest |
C_sharp : We know all types inherit Equals from their base class , which is Object.Per Microsoft docs : Equals returns true only if the items being compared refer to the same item in memory.So we use Equals ( ) to compare object references , not the state of the object . Typically , this method is overridden to return true only if the objects being compared have the same internal state values.My Question : Can two objects point to the same item in memory but have different states ? If not why override Equals ? Thanks for answers that made this clear . For future readers here is an example of why we override : in this case , A and B always point to different memory so Equals is always false.However if : These two Employees are the same person , in this case , we need to check state and therefore override Equals.So in my case , the point of the matter is : it is possible that two different objects are stored in two different locations but still refer to same entity ( in my case Employee ) . <code> Employee A=New Employee ( ) ; Employee B=New Employee ( ) ; A.SSN=B.SSN ; A.LiceneNumber=B.LiceneNumber ; | What does .NET 's Equals method really mean ? |
C_sharp : I have a struct that has a field called typeHow do i access it in F # ? c # f # How do i access the type field of A ? <code> struct A { int type ; } let a = A ( ) let myThing = a.type //error because type is a reserved keyword | access .Net field from F # when the field name is a reserved keyword |
C_sharp : I wrote this quickly under interview conditions , I wanted to post it to the community to possibly see if there was a better/faster/cleaner way to go about it . How could this be optimized ? <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Stack { class StackElement < T > { public T Data { get ; set ; } public StackElement < T > Below { get ; set ; } public StackElement ( T data ) { Data = data ; } } public class Stack < T > { private StackElement < T > top ; public void Push ( T item ) { StackElement < T > temp ; if ( top == null ) { top = new StackElement < T > ( item ) ; } else { temp = top ; top = new StackElement < T > ( item ) ; top.Below = temp ; } } public T Pop ( ) { if ( top == null ) { throw new Exception ( `` Sorry , nothing on the stack '' ) ; } else { T temp = top.Data ; top = top.Below ; return temp ; } } public void Clear ( ) { while ( top ! = null ) Pop ( ) ; } } class TestProgram { static void Main ( string [ ] args ) { Test1 ( ) ; Test2 ( ) ; Test3 ( ) ; } private static void Test1 ( ) { Stack < string > myStack = new Stack < string > ( ) ; myStack.Push ( `` joe '' ) ; myStack.Push ( `` mike '' ) ; myStack.Push ( `` adam '' ) ; if ( myStack.Pop ( ) ! = `` adam '' ) { throw new Exception ( `` fail '' ) ; } if ( myStack.Pop ( ) ! = `` mike '' ) { throw new Exception ( `` fail '' ) ; } if ( myStack.Pop ( ) ! = `` joe '' ) { throw new Exception ( `` fail '' ) ; } } private static void Test3 ( ) { Stack < string > myStack = new Stack < string > ( ) ; myStack.Push ( `` joe '' ) ; myStack.Push ( `` mike '' ) ; myStack.Push ( `` adam '' ) ; myStack.Clear ( ) ; try { myStack.Pop ( ) ; } catch ( Exception ex ) { return ; } throw new Exception ( `` fail '' ) ; } private static void Test2 ( ) { Stack < string > myStack = new Stack < string > ( ) ; myStack.Push ( `` joe '' ) ; myStack.Push ( `` mike '' ) ; myStack.Push ( `` adam '' ) ; if ( myStack.Pop ( ) ! = `` adam '' ) { throw new Exception ( `` fail '' ) ; } myStack.Push ( `` alien '' ) ; myStack.Push ( `` nation '' ) ; if ( myStack.Pop ( ) ! = `` nation '' ) { throw new Exception ( `` fail '' ) ; } if ( myStack.Pop ( ) ! = `` alien '' ) { throw new Exception ( `` fail '' ) ; } } } } | See any problems with this C # implementation of a stack ? |
C_sharp : I have this code : How can I access a property of test object ? When I put a breakpoint , visual studio can see the variables of this object ... Why ca n't I ? I really need to access those . <code> object test = new { a = `` 3 '' , b = `` 4 '' } ; Console.WriteLine ( test ) ; //I put a breakpoint here | Accessing anonymous type variables |
C_sharp : I have the following code : However it returns different results whether it 's compiled from VS2012 or VS2015 ( both have `` standard '' settings ) In VS2012In VS2015 : VS2012 dissasembly : VS2015 dissasembly : As we can see the disassembly is not identical in both cases , is this normal ? Could this be a bug in VS2012 or VS2015 ? Or is this behaviour controlled by some specific setting that was changed ? thanks ! <code> float a = 0.02f * 28f ; double b = ( double ) a ; double c = ( double ) ( 0.02f * 28f ) ; Console.WriteLine ( String.Format ( `` { 0 : F20 } '' , b ) ) ; Console.WriteLine ( String.Format ( `` { 0 : F20 } '' , c ) ) ; 0,560000002384186000000,55999998748302500000 0,560000002384186000000,56000000238418600000 float a = 0.02f * 28f ; 0000003a mov dword ptr [ ebp-40h ] ,3F0F5C29h double b = ( double ) a ; 00000041 fld dword ptr [ ebp-40h ] 00000044 fstp qword ptr [ ebp-48h ] double c = ( double ) ( 0.02f * 28f ) ; 00000047 fld qword ptr ds : [ 001D34D0h ] 0000004d fstp qword ptr [ ebp-50h ] float a = 0.02f * 28f ; 001E2DE2 mov dword ptr [ ebp-40h ] ,3F0F5C29h double b = ( double ) a ; 001E2DE9 fld dword ptr [ ebp-40h ] 001E2DEC fstp qword ptr [ ebp-48h ] double c = ( double ) ( 0.02f * 28f ) ; 001E2DEF fld dword ptr ds : [ 1E2E7Ch ] 001E2DF5 fstp qword ptr [ ebp-50h ] | difference of float/double conversion betwen VS2012 and VS2015 |
C_sharp : This code results in the following output : GetDistinctValuesUsingWhere No1 : 1,2,3,4 GetDistinctValuesUsingWhere No2 : GetDistinctValuesUsingForEach No1 : 1,2,3,4 GetDistinctValuesUsingForEach No2 : 1,2,3,4I do n't understand why I do n't get any values in the row `` GetDistinctValuesUsingWhere No2 '' . Can anyone explain this to me ? UPDATE after the answer from Scott , I changed the example to the following : This will result in two times the output 1,2,3,4.However , if I just uncomment the line return Where2 ( items , capturedVariables ) ; and comment the lines foreach ( var i in items ) if ( capturedVariables.set.Add ( i ) ) yield return i ; in the method GetDistinctValuesUsingWhere2 , I will get the output 1,2,3,4 only once . This is altough the deleted lines and the now-uncommented method are exactly the same.I still do n't get it ... . <code> using System ; using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication { internal class Program { public static void Main ( ) { var values = new [ ] { 1 , 2 , 3 , 3 , 2 , 1 , 4 } ; var distinctValues = GetDistinctValuesUsingWhere ( values ) ; Console.WriteLine ( `` GetDistinctValuesUsingWhere No1 : `` + string.Join ( `` , '' , distinctValues ) ) ; Console.WriteLine ( `` GetDistinctValuesUsingWhere No2 : `` + string.Join ( `` , '' , distinctValues ) ) ; distinctValues = GetDistinctValuesUsingForEach ( values ) ; Console.WriteLine ( `` GetDistinctValuesUsingForEach No1 : `` + string.Join ( `` , '' , distinctValues ) ) ; Console.WriteLine ( `` GetDistinctValuesUsingForEach No2 : `` + string.Join ( `` , '' , distinctValues ) ) ; Console.ReadLine ( ) ; } private static IEnumerable < T > GetDistinctValuesUsingWhere < T > ( IEnumerable < T > items ) { var set=new HashSet < T > ( ) ; return items.Where ( i= > set.Add ( i ) ) ; } private static IEnumerable < T > GetDistinctValuesUsingForEach < T > ( IEnumerable < T > items ) { var set=new HashSet < T > ( ) ; foreach ( var i in items ) { if ( set.Add ( i ) ) yield return i ; } } } } private static IEnumerable < T > GetDistinctValuesUsingWhere2 < T > ( IEnumerable < T > items ) { var set = new HashSet < T > ( ) ; var capturedVariables = new CapturedVariables < T > { set = set } ; foreach ( var i in items ) if ( capturedVariables.set.Add ( i ) ) yield return i ; //return Where2 ( items , capturedVariables ) ; } private static IEnumerable < T > Where2 < T > ( IEnumerable < T > source , CapturedVariables < T > variables ) { foreach ( var i in source ) if ( variables.set.Add ( i ) ) yield return i ; } private class CapturedVariables < T > { public HashSet < T > set ; } | Where vs. foreach with if - why different results ? |
C_sharp : I have the following List : which after populating the list I end up with the following data : I have multiple SKU 's as the item can be supplied from more then one Warehouse location as it 's in stock . In the case of SKU001 , warehouse ID 2 has more stock than warehouse ID 3.I need to select the items from the least number of warehouse locations . What I 'm trying to end up with is something likeThis limits product selection to only 2 locations as SKU001 , SKU002 & SKU003 can all be obtained from warehouse ID 3 . Ideally selecting from a location with the most stock but limiting the number of locations is more important.I 'm using Linq to try and achieve this while trying to loop each List item but am struggling as Linq 's not a strong point for me . I tried to first get the highest count of repeating warehouse id 's usingbut am getting lost on the rest of the items . Any ideas on how I could achive this ? <code> public class Products { public string SKU ; public int WarehouseID ; } List < Products > products = new List < Products > ( ) ; ProductCode|WarehouseIDSKU001|2SKU001|3SKU002|3SKU003|3SKU004|1SKU004|5 SKU001|3SKU002|3SKU003|3SKU004|1 products.GroupBy ( i = > i ) .OrderByDescending ( grp = > grp.Count ( ) ) .Select ( grp = > grp.Key ) .FirstOrDefault ( ) ; | Selecting values from List |
C_sharp : I have a web application which is supposed to be composed as a series of plugins into a core infrastructure . A plugin is a compiled CLR dll + some content files which will be put in a certain location . I 'm using Autofac to scan and register types out of the assembly , and some fancy routing to serve controllers and assets from there . But , since each plugin assembly can contain a DbContext ( by convention each will use its own database ) , I ca n't quite figure out what to do there . Now I 've found a lot of stuff around how to use multiple contexts but it all requires knowing what these will be at development time . My application does not know what contexts will be used until runtime.What I 'm looking for ideally is would like is some way to doThough I would also somehow have to provide an ordered set of migrations to apply ( if using explicit migrations ) .Where I 'm stumbling currently is the standardsince it is a static singleton and each dbcontext in my system has its own initializer . <code> ApplyMigrations < MyDbContext , MyDbConfiguration > ( ) ; Database.SetInitializer ( ... ) | EF multi-context with a plugin-style system . How to apply migrations at runtime ? |
C_sharp : First of all I have to specify that I 'm working in Unity 5.3 and the new MonoDevelop does n't allow me to debug . Unity just crashes : ( So I have a list of `` goals '' that I need to sort based on 3 criterias : first should be listed the `` active '' goalsthen ordered by difficulty levelfinally randomly for goals of the same levelhere is a my code : When I run this code sometimes I get one or more active goals after inactive ones , but I do n't understand why . <code> public class Goal { public int ID ; public int Level ; public bool Active ; } ... List < Goal > goals ; goals.Sort ( ( a , b ) = > { // first chooses the Active ones ( if any ) var sort = b.Active.CompareTo ( a.Active ) ; if ( sort == 0 ) { // then sort by level sort = ( a.Level ) .CompareTo ( b.Level ) ; // if same level , randomize . Returns -1 , 0 or 1 return sort == 0 ? UnityEngine.Random.Range ( -1 , 2 ) : sort ; } else { return sort ; } } ) ; | What is wrong with my sorting ? |
C_sharp : I have a some small doubt with classes and objects . In a class I have 10 to 20 methods , ( shared below ) When creating a object for the above class . How many methods will be stored in memory ? Only the calling method or all the methods.Can you please help me on the above scenario . <code> public class tstCls { public void a1 ( ) { } void a2 ( ) { } void a3 ( ) { } void a4 ( ) { } void a5 ( ) { } void a6 ( ) { } void a7 ( ) { } void a8 ( ) { } void a9 ( ) { } } static void Main ( string [ ] args ) { tstCls objcls = new tstCls ( ) ; objcls.a1 ( ) ; } | How many methods in a class will be created in memory when an object is created in C # ? |
C_sharp : Disclaimer : I would love to be using dependency injection on this project and have a loosely coupled interface-based design across the board , but use of dependency-injection has been shot down in this project . Also SOLID design principles ( and design patterns in general ) are something foreign where I work and I 'm new to many of them myself . So take that into consideration when suggesting a better design to this problem.Here is a simplified version of the code I 'm working on , and as such it might seem contrived . If so I apologize . Consider the following classes : Say these two class are used as follows : However I now find out that I also need to perform foo.Operation1 in some implementations of helper.DoSomethingHelpful ( ) ; ? Potential workarounds I thought of would be : Have foo and helper have a bidirectional relationship . So that in DoSomethingHelpful we can call foo.Operation2Have foo implement IHelp interface and move the `` helper '' code into fooUse delegation and pass the method Operation2 as an Action < string > delegate into the constructor of Helper.None of these approaches seem to be ideal ( though I 've pretty much determined I do n't like option 1 and am worried about maintainability with option 3 if we find out later we need to pass in more delegates ) . This makes me wonder if there is a problem with the initial design of the Helper/Foo combo . Thoughts ? <code> // Foo is a class that wraps underlying functionality from another // assembly to create a simplified API . Think of this as a service layer class , // a facade-like wrapper . It contains a helper class that is specific to// foo . Other AbstractFoo implementations have their own helpers.public class Foo : AbstractFoo { private readonly DefaultHelper helper ; public override DefaultHelper Helper { get { return helper ; } } public Foo ( ) { helper = new Helper ( `` custom stuff '' ) ; } public override void Operation1 ( string value ) { Console.WriteLine ( `` Operation1 using `` + value ) ; } public override void Operation2 ( ) { Console.WriteLine ( `` Operation2 '' ) ; } } // Helper derives from a default implementation and allows us to// override it 's methods to do things specific for the class that // holds this helper . Sometimes we use a custom helper , sometimes// we use the default one.public class Helper : DefaultHelper { private readonly string customStuff ; public Helper ( string value ) { customStuff = value ; } public override void DoSomethingHelpful ( ) { Console.WriteLine ( `` I was helpful using `` + customStuff ) ; } } // foo referenced and used in one part of code var foo = new Foo ( ) ; foo.Operation2 ( ) ; // or foo.Operation1 ( ) ; // some other point in the program where we do n't have a reference to foo // but do have a reference to the helper helper.DoSomethingHelpful ( ) ; | Is there a better design option ? |
C_sharp : I am reading `` The D Programming Language '' by Andrei Alexandrescu and one sentence puzzled me . Consider such code ( p.138 ) : and call ( p.140 ) : Explanation ( paragraph below the code ) : If we squint hard enough , we do see that the intent of the caller in this case was to have T = double and benefit from the nice implicit conversion from int to double . However , having the language attempt combinatorially at the same time implicit conversions and type deduction is a dicey proposition in the general case , so D does not attempt to do all that.I am puzzled because such language as C # tries to infer the type — if it can not do this , user gets error , but if it can , well , it works . C # lives with it for several years and I did n't hear any story how this feature ruined somebody 's day.And so my questions is this — what dangers are involved with inferring types as in the example above ? I can see only advantages , it is easy to write generic function and it is easy to call it . Otherwise you would have to introduce more parameters in generic class/function and write special constrains expressing allowed conversions only for the sake of inferring types . <code> T [ ] find ( T ) ( T [ ] haystack , T needle ) { while ( haystack.length > 0 & & haystack [ 0 ] ! = needle ) { haystack = haystack [ 1 .. $ ] ; } return haystack ; } double [ ] a = [ 1.0 , 2.5 , 2.0 , 3.4 ] ; a = find ( a , 2 ) ; // Error ! ' find ( double [ ] , int ) ' undefined | What is wrong with inferred type of template and implicit type conversion ? |
C_sharp : We are not forced to fill the returned value from e.g . a method call into a declared variable of expected type , but what happens to it in that situation ? Where does the following returned value go/What happens to it : ? Obviously , if I wanted to see the result from the method call I would do the following : ( This question is NOT specific to value types , but also reference types ) <code> decimal d = 5.5m ; Math.Round ( d , MidpointRounding.AwayFromZero ) ; decimal d = 5.5m ; decimal d2 = Math.Round ( d , MidpointRounding.AwayFromZero ) ; // Returns 6 into // the variable `` d2 '' | Where does the returned value from e.g . a method call go if not filled into a declared variable of expected type ? |
C_sharp : I am using JwtBearer authentication to secure my API . I am adding [ Authorize ] above each API and it worked . I am using this code to add the authentication in the startup : I want a way to add the [ Authorize ] to a function in a service , or write a code in the function that works the same as [ Authorize ] . <code> services.AddAuthentication ( `` Bearer '' ) .AddJwtBearer ( `` Bearer '' , options = > { options.Authority = `` http : //localhost:1234 '' ; options.RequireHttpsMetadata = false ; options.Audience = `` test '' ; } ) ; | ASPNet Core : Use [ Authorize ] with function in service |
C_sharp : I have a strange situation that I ca n't duplicate consistently . I have a MVC website developed in .NET Core 3.0 and authorizes users with .NET Core Identity . When I run the site in a development environment locally everything works just fine ( the classic `` works on my machine ! '' ) . When I deploy it to my staging web server is when I begin to see the issue . Users can log in successfully , be authenticated , and redirected to the home page . Note : all controllers , except the one handling authentication , are decorated with the [ Authorize ] attribute and the [ AutoValidateAntiforgeryToken ] attribute . The home page loads just fine . However , there are a couple of ajax calls that run when the page is loaded that callback to the Home controller to load some conditional data and check to see if some Session level variables have been set yet . These ajax calls return a 401 Unauthorized . The problem is I ca n't get this behavior to repeat consistently . I actually had another user log in concurrently ( same application , same server ) and it worked just fine for them . I opened the developer console in Chrome and traced what I think is the problem down to one common ( or uncommon ) factor . The calls ( such as loading the home page , or the ajax calls that were successful for the other user ) that work have the `` .AspNetCore.Antiforgery '' , `` .AspNetCore.Identity.Application '' , and the `` .AspNetCore.Session '' cookies set in the request headers . The calls that do not work ( my ajax calls ) only have the `` .AspNetCore.Session '' cookie set . Another thing to note is that this behavior happens for every ajax call on the site . All calls made to the controller actions by navigation or form posting work fine.DOES N'T WORK : WORKS : What is strange to me is that another user can log in , and even i can log in occasionally after a new publish , and have those ajax calls working just fine with cookies set properly.Here is some of the code to be a little more specific . Not sure if it 's something I have set up wrong with Identity or Session configuration.Startup.csLogin Controller ActionHome Controller Base Controller_Layout.cshtml Javascript ( runs aforementioned ajax calls when the pages are loaded ) EDIT : What I 've found is the `` Cookie '' header with `` .AspNetCore.Antiforgery '' , `` .AspNetCore.Identity.Application '' , and the `` .AspNetCore.Session '' attributes is always set correctly in the ajax requests when running locally . When deployed it only sets the cookie with the session attribute . I found a setting I have in my Startup.cs that sets the cookie to HttpOnly : options.Cookie.HttpOnly = true ; Could this be causing my issue ? Would setting it to false work ? If that is unsafe , what are some work-arounds/alternate methods to my approach . I still need to implement the basic principal of user authentication AND be able to trigger ajax requests.ANOTHER EDIT : Today after I deployed the site again , I ran the site concurrently in Firefox and Chrome . Firefox sent the correct cookie after authenticating and is running fine . However , Chrome is still displaying the 401 behavior . <code> public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } public IWebHostEnvironment Env { get ; set ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServices ( IServiceCollection services ) { services.AddIdentity < User , UserRole > ( options = > { options.User.RequireUniqueEmail = true ; } ) .AddEntityFrameworkStores < QCAuthorizationContext > ( ) .AddDefaultTokenProviders ( ) ; ; services.AddDbContext < QCAuthorizationContext > ( cfg = > { cfg.UseSqlServer ( Configuration.GetConnectionString ( `` Authorization '' ) ) ; } ) ; services.AddSingleton < IConfiguration > ( Configuration ) ; services.AddControllersWithViews ( ) ; services.AddDistributedMemoryCache ( ) ; services.AddSession ( options = > { // Set a short timeout for easy testing . options.IdleTimeout = TimeSpan.FromHours ( 4 ) ; options.Cookie.HttpOnly = true ; // Make the session cookie essential options.Cookie.IsEssential = true ; } ) ; services.Configure < IdentityOptions > ( options = > { options.Password.RequireDigit = true ; options.Password.RequireLowercase = true ; options.Password.RequireNonAlphanumeric = true ; options.Password.RequireUppercase = true ; options.Password.RequiredLength = 6 ; options.Password.RequiredUniqueChars = 1 ; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes ( 30 ) ; options.Lockout.MaxFailedAccessAttempts = 10 ; options.Lockout.AllowedForNewUsers = true ; } ) ; services.ConfigureApplicationCookie ( options = > { //cookie settings options.ExpireTimeSpan = TimeSpan.FromHours ( 4 ) ; options.SlidingExpiration = true ; options.LoginPath = new Microsoft.AspNetCore.Http.PathString ( `` /Account/Login '' ) ; } ) ; services.AddHttpContextAccessor ( ) ; //services.TryAddSingleton < IActionContextAccessor , ActionContextAccessor > ( ) ; IMvcBuilder builder = services.AddRazorPages ( ) ; } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , IWebHostEnvironment env , IServiceProvider serviceProvider ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; } else { app.UseExceptionHandler ( `` /Error '' ) ; app.UseHsts ( ) ; } app.UseStaticFiles ( ) ; app.UseCookiePolicy ( ) ; app.UseRouting ( ) ; app.UseAuthentication ( ) ; app.UseAuthorization ( ) ; app.UseSession ( ) ; app.UseEndpoints ( endpoints = > { endpoints.MapControllerRoute ( name : `` default '' , pattern : `` { controller=Home } / { action=Index } / { id ? } '' ) ; endpoints.MapControllerRoute ( name : `` auth4 '' , pattern : `` { controller=Account } / { action=Authenticate } / { id ? } '' ) ; } ) ; } } [ HttpPost ] public async Task < IActionResult > Login ( LoginViewModel iViewModel ) { ViewBag.Message = `` '' ; try { var result = await signInManager.PasswordSignInAsync ( iViewModel.Email , iViewModel.Password , false , false ) ; if ( result.Succeeded ) { var user = await userManager.FindByNameAsync ( iViewModel.Email ) ; if ( ! user.FirstTimeSetupComplete ) { return RedirectToAction ( `` FirstLogin '' ) ; } return RedirectToAction ( `` Index '' , `` Home '' ) ; } else { ViewBag.Message = `` Login Failed . `` ; } } catch ( Exception ex ) { ViewBag.Message = `` Login Failed . `` ; } return View ( new LoginViewModel ( ) { Email = iViewModel.Email } ) ; } public class HomeController : BaseController { private readonly ILogger < HomeController > _logger ; public HomeController ( IConfiguration configuration , ILogger < HomeController > logger , UserManager < User > iUserManager ) : base ( configuration , iUserManager ) { _logger = logger ; } public async Task < IActionResult > Index ( ) { HomeViewModel vm = HomeService.GetHomeViewModel ( ) ; vm.CurrentProject = HttpContext.Session.GetString ( `` CurrentProject '' ) ; vm.CurrentInstallation = HttpContext.Session.GetString ( `` CurrentInstallation '' ) ; if ( ! string.IsNullOrEmpty ( vm.CurrentProject ) & & ! string.IsNullOrEmpty ( vm.CurrentInstallation ) ) { vm.ProjectAndInstallationSet = true ; } return View ( vm ) ; } public IActionResult CheckSessionVariablesSet ( ) { var currentProject = HttpContext.Session.GetString ( `` CurrentProject '' ) ; var currentInstallation = HttpContext.Session.GetString ( `` CurrentInstallation '' ) ; return Json ( ! string.IsNullOrEmpty ( currentProject ) & & ! string.IsNullOrEmpty ( currentInstallation ) ) ; } public IActionResult CheckSidebar ( ) { try { var sidebarHidden = bool.Parse ( HttpContext.Session.GetString ( `` SidebarHidden '' ) ) ; return Json ( new { Success = sidebarHidden } ) ; } catch ( Exception ex ) { return Json ( new { Success = false } ) ; } } } [ AutoValidateAntiforgeryToken ] [ Authorize ] public class BaseController : Controller { protected IConfiguration configurationManager ; protected SQLDBContext context ; protected UserManager < User > userManager ; public BaseController ( IConfiguration configuration , UserManager < User > iUserManager ) { userManager = iUserManager ; configurationManager = configuration ; } public BaseController ( IConfiguration configuration ) { configurationManager = configuration ; } protected void EnsureDBConnection ( string iProject ) { switch ( iProject ) { case `` A '' : DbContextOptionsBuilder < SQLDBContext > AOptionsBuilder = new DbContextOptionsBuilder < SQLDBContext > ( ) ; AOptionsBuilder.UseLazyLoadingProxies ( ) .UseSqlServer ( configurationManager.GetConnectionString ( `` A '' ) ) ; context = new SQLDBContext ( AOptionsBuilder.Options ) ; break ; case `` B '' : DbContextOptionsBuilder < SQLDBContext > BOptionsBuilder = new DbContextOptionsBuilder < SQLDBContext > ( ) ; BOptionsBuilder.UseLazyLoadingProxies ( ) .UseSqlServer ( configurationManager.GetConnectionString ( `` B '' ) ) ; context = new SQLDBContext ( BOptionsBuilder.Options ) ; break ; case `` C '' : DbContextOptionsBuilder < SQLDBContext > COptionsBuilder = new DbContextOptionsBuilder < SQLDBContext > ( ) ; COptionsBuilder.UseLazyLoadingProxies ( ) .UseSqlServer ( configurationManager.GetConnectionString ( `` C '' ) ) ; context = new SQLDBContext ( COptionsBuilder.Options ) ; break ; } } } < script type= '' text/javascript '' > var afvToken ; $ ( function ( ) { afvToken = $ ( `` input [ name='__RequestVerificationToken ' ] '' ) .val ( ) ; $ .ajax ( { url : VirtualDirectory + '/Home/CheckSidebar ' , headers : { `` RequestVerificationToken '' : afvToken } , complete : function ( data ) { console.log ( data ) ; if ( data.responseJSON.success ) { toggleSidebar ( ) ; } } } ) ; $ .ajax ( { url : VirtualDirectory + '/Home/CheckSessionVariablesSet ' , headers : { `` RequestVerificationToken '' : afvToken } , complete : function ( data ) { console.log ( data ) ; if ( data.responseJSON ) { $ ( ' # sideBarContent ' ) .attr ( 'style ' , `` ) ; } else { $ ( ' # sideBarContent ' ) .attr ( 'style ' , 'display : none ; ' ) ; } } } ) ; $ .ajax ( { url : VirtualDirectory + '/Account/UserRoles ' , headers : { `` RequestVerificationToken '' : afvToken } , complete : function ( data ) { if ( data.responseJSON ) { var levels = data.responseJSON ; if ( levels.includes ( 'Admin ' ) ) { $ ( '.adminSection ' ) .attr ( 'style ' , `` ) ; } else { $ ( '.adminSection ' ) .attr ( 'style ' , 'display : none ; ' ) ; } } } } ) ; } ) ; < /script > | Ajax Calls Return 401 When .NET Core Site Is Deployed |
C_sharp : I think I 've developed a cargo-cult programming habit : Whenever I need to make a class threadsafe , such as a class that has a Dictionary or List ( that is entirely encapsulated : never accessed directly and modified only by member methods of my class ) I create two objects , like so : In this case , I wrap all operations on _devices within a lock ( _devicesLock ) { block . I 'm beginning to wonder if this is necessary . Why do n't I just lock on the dictionary directly ? <code> public static class Recorder { private static readonly Object _devicesLock = new Object ( ) ; private static readonly Dictionary < String , DeviceRecordings > _devices ; static Recorder ( ) { _devices = new Dictionary < String , DeviceRecordings > ( ) ; WaveInCapabilities [ ] devices = AudioManager.GetInDevices ( ) ; foreach ( WaveInCapabilities device in devices ) { _devices.Add ( device.ProductName , new DeviceRecordings ( device.ProductName ) ) ; } } //cctor // For now , only support a single device . public static DeviceRecordings GetRecordings ( String deviceName ) { lock ( _devicesLock ) { if ( ! _devices.ContainsKey ( deviceName ) ) { return null ; } return _devices [ deviceName ] ; } } //GetRecordings } //class | Cargo-cult programming : locking on System.Object |
C_sharp : I 'm experimenting with WeakReference , and I 'm writing a code that checks if a weak reference is valid before returning a strong reference to the object.How should I prevent the GC collecting the object between the `` IsValid '' and the `` Target '' calls ? <code> if ( weakRef.IsValid ) return ( ReferencedType ) weakRef.Target ; else // Build a new object | Block garbage collector while analyzing weak references |
C_sharp : I have base class for my entitiesI have to use this strange construction Entity < T > where T : Entity < T > , because i want static method FromXElement to be strongly-typedAlso , i have some entities , like thatHow can i create a generic list of my entities , using base class ? <code> public class Entity < T > where T : Entity < T > , new ( ) { public XElement ToXElement ( ) { } public static T FromXElement ( XElement x ) { } } public class Category : Entity < Category > { } public class Collection : Entity < Collection > { } var list = new List < Entity < ? > > ( ) ; list.Add ( new Category ( ) ) ; list.Add ( new Collection ( ) ) ; | Create list of generics |
C_sharp : I want to retrieve values from a tree stored in another system . For example : To avoid typing errors and invalid keys , I want to check the name at compile time by creating an object or class with the tree structure in it : Is there an easy way to do this in C # without creating classes for each tree node ? Can I use anonymous classes or subclasses ? Should I create the code automatically ? <code> GetValue ( `` Vehicle.Car.Ford.Focus.Engine.Oil.Color '' ) GetValue ( Vehicle.Car.Ford.Focus.Engine.Oil.Color ) | Compile time tree structure |
C_sharp : I want to replace string which is a square bracket with another number . I am using regex replace method.Sample input : This is [ test ] version.Required output ( replacing `` [ test ] '' with 1.0 ) : This is 1.0 version.Right now regex is not replacing the special character . Below is the code which I have tried : There may be any special character in input and stringtoFind variables . <code> string input= `` This is [ test ] version of application . `` ; string stringtoFind = string.Format ( @ '' \b { 0 } \b '' , `` [ test ] '' ) ; Console.WriteLine ( Regex.Replace ( input , stringtoFind , `` 1.0 '' ) ) ; | Word boundaries not matching when the word starts or ends with special character like square brackets |
C_sharp : I am having the following preudo-codewhere the entire code has , let 's say 500 lines with lots of logic inside for statements . The problem is refactoring this into a readable and maintainable code and as a best practice for similar situations . Here are the possible solutions I found so far.1 : Split into methodsConsidering we extract each for into its own method , to improve readability , we end up with method2 , method3 and method4 . Each method has its own parameters and dependencies , which is good , except for method4 . Method4 depends on list1 which means that list1 must be passed to methods 2 and 3 as well . From my opinion , this becomes unreadable . Any developer looking at method2 will realize there is no point for list1 inside it , so he has to look down the chain until method4 to actually realize the dependency - > inefficient . Then , what happens if list4 or item4 changes and no longer needs a dependency on list1 ? I have to remove list1 parameter for method4 ( which should be done , naturally ) but also for methods 2 and 3 ( out of the scope of change ) - > again inefficient . Another side effect is that , in case on lots of dependencies and multiple levels , the number of parameters passed down will quickly increase . Think what happens if list4 also depends on list11 , list12 and list13 , all created at the level of list1.2 : Keep a long single methodThe advantage is that every list and item can access every parent list and item , which makes the further changes a one-liner . If list4 no longer depends on list1 , just remove/replace the code , without changing anything else . Obviously , the problem is that the method is couple hundred lines , which we all know it 's not good.3 . Best of both worlds ? The idea is to split into methods only the inner logical part of each for . This way the main method will decrease and we gain readability and possibly maintainability . Leaving the for in the main method , we are still able to access each dependency as a one-liner . We end up with something like this : But there is another problem . How do you name those compute methods in order to be readable ? Let 's say that I have a local variable instanceA or type ClassA which I populate from item2 . Class A contains a property named LastItem4 which needs to keep , let 's say , last item4 in order of creation date or whatever . If I use compute to create the instanceA , then this compute is only partial . Because LastItem4 property needs to be populated on item4 level , in a different compute method . So how to I call these 2 compute methods to suggest what I am actually doing ? Tough answer , in my opinion.4 . # regionLeave a single long method but use regions . This is a feature strictly used in some programming languages and seems to me like a patch , not as a best practice , but maybe it 's just me.I would like to know how would you do this refactoring ? Be aware that it may be even more complex than that . The fact that is a service is a bit misleading , the idea is that i do n't really like using disposable objects as method parameters , because you do n't know the intent without reading the actual method code . But I was expecting this in comments since others may feel otherwise.For the sake of example , let 's assume that the service is a 3rd party one , without the possibility to change the way it works . <code> using ( some web service/disposable object ) { list1 = service.get1 ( ) ; list2 = service.get2 ( ) ; for ( item2 in list2 ) { list3 = service.get3 ( depending on item2 ) ; for ( item3 in list3 ) { list4 = service.get4 ( depending on item3 and list1 ) ; for ( item4 in list4 ) { ... } } } } for ( item2 in list2 ) { compute ( ) ; list3 = service.get3 ( depending on item2 ) ; for ( item3 in list3 ) { compute ( item2 , eventually item1 ) list4 = service.get4 ( depending on item3 and list1 ) ; for ( item4 in list4 ) { ... } } } | Refactoring inner loops with lots of dependencies between levels |
C_sharp : I want to create an instance of FormsAuthenticationTicket ( over which I have no control , part of System.Web.Security ) using Autofixture AND making sure that the UserData ( of type string ) contains a valid XML stringThe problem is that UserData can only be set when instantiating the object using the following constructor : Where `` userData '' is a valid XML string.I can configure this type to use the greediest constructor , but that does not solves the problem of providing a valid XML string to userData.I could freeze the string type to make it always return a valid XML string , but I also care about other string values on my test.I am thinking a possible approach is to customize the algorithm for string generation ... but I have not parameters to know when to provide the XML like string . <code> var testTicket = fixture.Create < FormsAuthenticationTicket > ( ) ; public FormsAuthenticationTicket ( int version , string name , DateTime issueDate , DateTime expiration , bool isPersistent , string userData ) ; | Create an instance of FormsAuthenticationTicket with a valid XML string in UserData |
C_sharp : Variables : Current If statementQuestion : Instead of having multiple if statements , for each variable . How can I create 1 if statement to go through all these variables ? Something like this : <code> private string filePath1 = null ; private string filePath2 = null ; private string filePath3 = null ; private string filePath4 = null ; private string filePath5 = null ; private string filePath6 = null ; private string filePath7 = null ; private string filePath8 = null ; private string filePath9 = null ; private string filePath10 = null ; if ( string.IsNullOrEmpty ( filePath1 ) ) { errors.Add ( `` File Not Attached '' ) ; } if ( string.IsNullOrEmpty ( filePath2 ) ) { errors.Add ( `` File Not Attached '' ) ; } ... . if ( string.IsNullOrEmpty ( filePath + range ( 1 to 10 ) ) { errors.Add ( `` File Not Attached '' ) ; } | If statement with multiple variables ending with a number |
C_sharp : I 'm trying to diagnose issues updating Google Fusion Tables using CSV data via the API . Everything seems to work correctly code side of things with no errors reported but the data does not reflect the changes . Any ideas how I can diagnose what is going wrong ? I 've been using the Google.Apis.Fusiontables.v2 C # libraries ( v1.27.1.833 is latest I 've tried ) to update a fusion table daily . The process was working seamlessly for quite a while , but now no longer seems to work . I suspect the process has been broken for a month or more now.Everything seems to work from the code side of things , no errors reported . I 've also been debugging the process from within Visual Studio with no problems indicated - it just seems to work from the client side.In case it 's useful the C # method I 'm using is : The table I am attempting to update is - https : //fusiontables.google.com/DataSource ? docid=1ndrFm1g0iZpz5gszjz5Ij9r_KiQbNYRXVM2JNfv3The UpdatedUtc column indicates that a few updated rows are getting through , but not all of them.If I export my CSV stream to a physical file and created a new Fusion Table manually via the web UI this works perfectly and shows all the missing data I expect to be there.Here 's the zipped CSV file in case it 's useful - http : //www.paydirt.co.nz/stackoverflow/GoldPermits.zipThis is the test Fusion Table I imported the CSV file manually into - https : //www.google.com/fusiontables/DataSource ? docid=1Udnre88O8e1zokvnhrkmqdY7BbYD2OQtELdyz3uGExample of missing data in the live table updates : Compared to the test table created from the same data : The PERMIT_NUMBER 's for the 2 missing rows in the example are 60304 and 60247.Any ideas how I can investigate further what might be going wrong ? Maybe there 's some logs or logging options available somewhere I 'm unaware of ? Any help / ideas to explore is greatly appreciated . <code> fusiontablesService.Table.ReplaceRows ( tableId , stream , `` application/octet-stream '' ) .Upload ( ) ; | Diagnosing Google Fusion Table update using API to upload CSV issue |
C_sharp : Let 's think of it as a family tree , a father has kids , those kids have kids , those kids have kids , etc ... So I have a recursive function that gets the father uses Recursion to get the children and for now just print them to debug output window ... But at some point ( after one hour of letting it run and printing like 26000 rows ) it gives me a StackOverFlowException . So Am really running out of memory ? hmmm ? then should n't I get an `` Out of memory exception '' ? on other posts I found people were saying if the number of recursive calls are too much , you might still get a SOF exception ... Anyway , my first thought was to break the tree into smaller sub-strees..so I know for a fact that my root father always has these five kids , so Instead of Calling my method one time with root passed to it , I said ok call it five times with Kids of root Passes to it.. It helped I think..but still one of them is so big - 26000 rows when it crashes - and still have this issue.How about Application Domains and Creating new Processes at run time at some certain level of depth ? Does that help ? How about creating my own Stack and using that instead of recursive methods ? does that help ? here is also a high-level of my code , please take a look , maybe there is actually something silly wrong with this that causes SOF error : <code> private void MyLoadMethod ( string conceptCKI ) { // make some script calls to DB , so that moTargetConceptList2 will have Concept-Relations for the current node . // when this is zero , it means its a leaf . int numberofKids = moTargetConceptList2.ConceptReltns.Count ( ) ; if ( numberofKids == 0 ) return ; for ( int i = 1 ; i < = numberofKids ; i++ ) { oUCMRConceptReltn = moTargetConceptList2.ConceptReltns.get_ItemByIndex ( i , false ) ; //Get the concept linked to the relation concept if ( oUCMRConceptReltn.SourceCKI == sConceptCKI ) { oConcept = moTargetConceptList2.ItemByKeyConceptCKI ( oUCMRConceptReltn.TargetCKI , false ) ; } else { oConcept = moTargetConceptList2.ItemByKeyConceptCKI ( oUCMRConceptReltn.SourceCKI , false ) ; } //builder.AppendLine ( `` \t '' + oConcept.PrimaryCTerm.SourceString ) ; Debug.WriteLine ( oConcept.PrimaryCTerm.SourceString ) ; MyLoadMethod ( oConcept.ConceptCKI ) ; } } | Does creating new Processes help me for Traversing a big tree ? |
C_sharp : I can automatically register all types that implement interfaces with this statementHow can I specify a namespace for interfaces and implementations ? i.e : only interfaces in Framework.RepositoryInterfaces should get resolved by types in Framework.RepositoryImplementations . <code> IUnityContainer container = new UnityContainer ( ) ; container.RegisterTypes ( AllClasses.FromAssembliesInBasePath ( ) , WithMappings.FromMatchingInterface , WithName.Default , WithLifetime.Transient ) ; ICustomer result = container.Resolve < ICustomer > ( ) ; | Resolve dependencies only from specified namespace |
C_sharp : i 've got a disordered file with 500000 line which its information and date are like the following : Now how can i implement such a thing ? I 've tried the sortedList and sorteddictionary methods but there is no way for implemeting a new value in the list because there are some repetative values in the list . I 'd appreciate it if u suggest the best possible method .One more thing , i 've seen this question but this one uses the class while i go with File ! C # List < > Sort by x then y <code> for instance desired Result -- -- -- -- -- -- -- -- -- -- -- -- -- - 723,80 1,4 14,50 1,5 723,2 10,8 1,5 14,50 10,8 723,2 1,4 723,80 | How can I sort the file txt line 5000000 ? |
C_sharp : When you have nested co-routines like Is the StartCoroutine in yield return StartCoroutine ( Bar ( ) ) ; necessary ? Are we allowed to just do If we are allowed , does this have any impact on the program behavior/performance ? <code> void Update ( ) { if ( someTest ) { StartCoroutine ( Foo ( ) ) ; } } IEnumerator Foo ( ) { doStuff = true ; yield return StartCoroutine ( Bar ( ) ) ; doStuff = false ; } IEnumerator Bar ( ) { //Very important things ! } void Update ( ) { if ( someTest ) { StartCoroutine ( Foo ( ) ) ; } } IEnumerator Foo ( ) { doStuff = true ; yield return Bar ( ) ; doStuff = false ; } IEnumerator Bar ( ) { //Very important things ! } | Is a StartCoroutine needed for a call from inside one co-routine to another co-routine ? |
C_sharp : I just spent hours being confused by an NullReferenceException where I thought there should n't be one . I was constructing a class like so : whereBasically my IL was the following : and I finally figured that it must be that bar was not being instantiated . I constructed my class in C # and compiled it and found the only difference was that the following should be above the IL above : With these lines , my code now works as expected.So my questions are : Why do we need to explicitly call the base constructor to instantiate fields ? Is there a legitimate use of not calling the base constructor ? ... and if not , why does the CLR accept it as a valid program ? <code> public class MyClass : MyBase < Foo > { public MyClass ( ) { base.Method ( Foo.StaticField ) ; } } public class MyBase < T > { private SomeObject bar = new SomeObject ( ) ; public void Method ( object o ) { this.bar.AnotherMethod ( o ) ; // exception thrown here } } ctorIl.Emit ( OpCodes.Ldarg_0 ) ; ctorIl.Emit ( OpCodes.Ldsfld , staticField ) ; ctorIl.Emit ( OpCodes.Box , typeof ( FieldType ) ) ; ctorIl.Emit ( OpCodes.Call , parentMethod ) ; ctorIl.Emit ( OpCodes.Ret ) ; ctorIl.Emit ( OpCodes.Ldarg_0 ) ; ctorIl.Emit ( OpCodes.Call , parentCtor ) ; // as above | Why do we need to explicitly call parent constructor in MSIL ? |
C_sharp : I 've created a Generic Class to parse some data into another instance of a class ( MyClass1 ) . Since MyClass1 has only built-in C # types , my GenericMethod works fine . The problem starts to grow when MyClass1 has another MyClass2 property and I still want to invoke my GenericMethod to parse my data.I ca n't trigger my Generic Class method inside its scope since I need to change the type of T. Is there any way to solve this problem ? <code> public class MyClass1 { public int MyIntProperty { get ; set ; } public string MyStringProperty { get ; set ; } public MyClass2 MyClass2Property { get ; set ; } } public class MyClass2 { public int MyOtherIntProperty { get ; set ; } public string MyOtherStringProperty { get ; set ; } public bool MyOtherBoolProperty { get ; set ; } } public class MyGenericClass < T > where T : class { public static T MyGenericMethod ( ) { T o = ( T ) Activator.CreateInstance ( typeof ( T ) ) ; PropertyInfo [ ] pi = typeof ( T ) .GetProperties ( ) ; for ( int i = 0 ; i < pi.Count ( ) ; i++ ) { if ( pi [ i ] .Name == `` MyClass2Property '' ) { //How to proceed ? MyGenericClass < ? ? ? > .MyGenericMethod ( ) ; } else { pi [ i ] .SetValue ( o , Convert.ChangeType ( someValue , pi [ i ] .PropertyType ) , null ) ; } } } } public static void Main ( string [ ] args ) { MyClass1 mc1 = MyGenericClass < MyClass1 > .MyGenericMethod ( ) ; //Do something with mc1 } | How to trigger a Generic Class method recursively changing the type of T ? |
C_sharp : I have this loop : But instead I would like to have i for just numbers 1,2,4,5 and 7 and I will hardcode this.Is there a way I can do this with something like an array ? <code> for ( int i = 1 ; i < 10 ; i++ ) | Is there a way to code a for loop so that it does n't increment through a sequence ? |
C_sharp : It seems I 'm running into more woes with 'my most favorite datatype ' SqlDecimal.I 'm wondering if this should be considered a bug or not.When I multiply two small numbers in SQL I get the expected result . When I run the same numbers through a SQLCLR function the results are , well surprising.c # code : SQL Code : The outcome of this is : c = -0.00000100f = +0.00000100I know the 'absolute ' difference is 'minimal ' and I 've `` played down '' bigger errors blaming it on `` rounding differences '' ... But it 's going to be hard to explain to clients that negative times positive results in positive.And after all , T-SQL supports it fine ... I can try to work around it by using decimal ( 28,8 ) instead of decimal ( 38,8 ) but I 'll run into other ( totally unrelated ) issues then =/ The following console application exhibits the same problem , without having to get SQL Server/SQLCLR involved : Prints 0.000001 <code> using System.Data.SqlTypes ; using Microsoft.SqlServer.Server ; namespace TestMultiplySQLDecimal { public static class Multiplier { [ SqlFunction ( DataAccess=DataAccessKind.None , IsDeterministic = true , IsPrecise = true ) ] public static SqlDecimal Multiply ( SqlDecimal a , SqlDecimal b ) { if ( a.IsNull || b.IsNull ) return SqlDecimal.Null ; return a*b ; } } } USE tempdbGOIF DB_ID ( 'test ' ) IS NOT NULL DROP DATABASE testGOCREATE DATABASE testGOUSE testGOCREATE ASSEMBLY TestMultiplySQLDecimal FROM ' C : \Users\tralalalaa\Documents\visual studio 2015\Projects\TestMultiplySQLDecimal\TestMultiplySQLDecimal\bin\Release\TestMultiplySQLDecimal.dll'WITH PERMISSION_SET = SAFEGOCREATE FUNCTION dbo.fn_multiply ( @ a decimal ( 38,8 ) , @ b decimal ( 18,8 ) ) RETURNS decimal ( 38,8 ) EXTERNAL NAME TestMultiplySQLDecimal . [ TestMultiplySQLDecimal.Multiplier ] .MultiplyGODECLARE @ a decimal ( 38 , 8 ) , @ b decimal ( 18 , 8 ) , @ c decimal ( 38 , 8 ) , @ f decimal ( 38 , 8 ) SELECT @ a = -0.00000450 , @ b = 0.193 , @ c = NULL , @ f = NULLSELECT @ c = @ a * @ b , @ f = dbo.fn_multiply ( @ a , @ b ) SELECT multiply = null , c = @ c , f = @ f using System ; using System.Data.SqlTypes ; namespace PlayAreaCSCon { class Program { static void Main ( string [ ] args ) { var dec1 = new SqlDecimal ( -0.00000450d ) ; var dec2 = new SqlDecimal ( 0.193d ) ; dec1 = SqlDecimal.ConvertToPrecScale ( dec1 , 38 , 8 ) ; dec2 = SqlDecimal.ConvertToPrecScale ( dec2 , 18 , 8 ) ; Console.WriteLine ( dec1 * dec2 ) ; Console.ReadLine ( ) ; } } } | c # SqlDecimal flipping sign in multiplication of small numbers |
C_sharp : I am trying to setup a ESRI Local Server for displaying .mpk . I have a Model likein ViewModel.cs Class I haveAs you can see I am trying to implement the local server and dynamic layer in ViewModel.cs like but I do not know how to bind this service to the Model ? I tried but as you know the myModel does n't have any Map object . Update <code> public class Model { private string basemapLayerUri = `` http : //services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer '' ; private string mapPackage = `` D : \\App\\Data\\Canada.mpk '' ; public Model ( ) { } public string BasemapLayerUri { get { return this.basemapLayerUri ; } set { if ( value ! = this.basemapLayerUri ) { this.basemapLayerUri = value ; } } } public string MapPackage { get { return this.mapPackage ; } set { if ( value ! = this.mapPackage ) { this.mapPackage = value ; } } } } public class ViewModel : INotifyPropertyChanged { public Model myModel { get ; set ; } public event PropertyChangedEventHandler PropertyChanged ; public ViewModel ( ) { myModel = new Model ( ) ; this.CreateLocalServiceAndDynamicLayer ( ) ; } public string BasemapUri { get { return myModel.BasemapLayerUri ; } set { this.myModel.BasemapLayerUri = value ; OnPropertyChanged ( `` BasemapUri '' ) ; } } public async void CreateLocalServiceAndDynamicLayer ( ) { LocalMapService localMapService = new LocalMapService ( this.MAPKMap ) ; await localMapService.StartAsync ( ) ; ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer ( ) { ID = `` mpklayer '' , ServiceUri = localMapService.UrlMapService , } ; //myModel.Map.Layers.Add ( arcGISDynamicMapServiceLayer ) ; } public string MAPKMap { get { return myModel.MapPackage ; } set { this.myModel.MapPackage = value ; OnPropertyChanged ( `` MAPKMap '' ) ; } } protected void OnPropertyChanged ( [ CallerMemberName ] string member = `` '' ) { var eventHandler = PropertyChanged ; if ( eventHandler ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( member ) ) ; } } } public async void CreateLocalServiceAndDynamicLayer ( ) { LocalMapService localMapService = new LocalMapService ( this.MAPKMap ) ; await localMapService.StartAsync ( ) ; ArcGISDynamicMapServiceLayer arcGISDynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer ( ) { ID = `` mpklayer '' , ServiceUri = localMapService.UrlMapService , } ; //myModel.Map.Layers.Add ( arcGISDynamicMapServiceLayer ) ; } myModel.Map.Layers.Add ( arcGISDynamicMapServiceLayer ) ; using M_PK2.Models ; using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Linq ; using System.Runtime.CompilerServices ; using System.Text ; using System.Threading.Tasks ; using Esri.ArcGISRuntime.LocalServices ; using Esri.ArcGISRuntime.Controls ; using Esri.ArcGISRuntime.Layers ; namespace M_PK2.ViewModels { class ViewModel : ViewModelBase { private readonly LocalMapService localMapService ; private readonly Model myModel ; private LayerCollection layers ; public ViewModel ( ) { myModel = new Model ( ) ; layers = new LayerCollection ( ) ; localMapService = new LocalMapService ( myModel.MapPackage ) ; starting += onStarting ; starting ( this , EventArgs.Empty ) ; } private event EventHandler starting = delegate { } ; private async void onStarting ( object sender , EventArgs args ) { starting -= onStarting ; //optional // the following runs on background thread await localMapService.StartAsync ( ) ; // returned to the UI thread var serviceLayer = new ArcGISDynamicMapServiceLayer ( ) { ID = `` mpklayer '' , ServiceUri = localMapService.UrlMapService , } ; Layers.Add ( serviceLayer ) ; OnPropertyChanged ( nameof ( Layers ) ) ; //Notify UI } public LayerCollection Layers { get { return layers ; } } } public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { } ; protected void OnPropertyChanged ( [ CallerMemberName ] string member = `` '' ) { PropertyChanged ( this , new PropertyChangedEventArgs ( member ) ) ; } } } | Implementing MVVM with ArcGIS Runtime local server |
C_sharp : Here is demonstration of the problem : This become an issue if there are methods with many parameters ( e.g . ten of double type ) : Question : is there a way to validate parameters when calling method , so that programmer is less prone to do a mistake ? This is not an issue if parameter types are different . I thought what maybe wrapping into new types will help : And it does , but I am quite unsure if this method is efficient . I have doubts if this is a good idea at all . Is it ? Or is there better one ? I know what I can be absolutely safe if I always call method like this ( using named arguments method call ) This should n't bring any overhead in code , but a lot of typing . Wrapping is better because it is done once ( creating new type is easy ) , but it probably has overhead . <code> class Program { static double Func ( double a , double b ) { return a * 1000 + b * b ; } static void Main ( string [ ] args ) { var a = 1.1d ; var b = 2.2d ; Console.WriteLine ( Func ( a , b ) ) ; // this is the problem , function does n't recognize when a and b // `` accidentally '' exchanged , target is to make this row a compile-time error Console.WriteLine ( Func ( b , a ) ) ; } } double Func ( double parameter1 , double parameter2 , ... , double parameter10 ) ; class A { private double _value ; public static implicit operator A ( double value ) { return new A ( ) { _value = value } ; } public static implicit operator double ( A value ) { return value._value ; } } class B { private double _value ; public static implicit operator B ( double value ) { return new B ( ) { _value = value } ; } public static implicit operator double ( B value ) { return value._value ; } } class Program { static double Func ( A a , B b ) { return a * 1000 + b * b ; } static void Main ( string [ ] args ) { A a = 1.1d ; B b = 2.2d ; Console.WriteLine ( Func ( a , b ) ) ; Console.WriteLine ( Func ( b , a ) ) ; // compile-time error ! yay ! Console.WriteLine ( Func ( a , b ) + 123.123d - a * 2 ) ; // implicit conversion power Console.ReadKey ( ) ; } } Func ( a : a , b : b ) ; | Compile-time method call validation for multiple parameters of the same type |
C_sharp : I met with the strange behavior of the generic . Below is the code I use for testing.Output : I found it very strange that the second Console.WriteLine call displays a class , not an interface , because I use a generic type definition . Is this correct behaviour ? I 'm trying to implement generic type inference in my compiler . Suppose I have the code below.And I want to call this method as follows : In order to check the possibility of inference , I have to compare the type in the method signature , and type of arguments passed . But the code below returns false.Should I always use Type.GetGenericTypeDefinition for such comparisons ? <code> public static class Program { public static void Main ( ) { Type listClassType = typeof ( List < int > ) .GetGenericTypeDefinition ( ) ; Type listInterfaceType = listClassType.GetInterfaces ( ) [ 0 ] ; Console.WriteLine ( listClassType.GetGenericArguments ( ) [ 0 ] .DeclaringType ) ; Console.WriteLine ( listInterfaceType.GetGenericArguments ( ) [ 0 ] .DeclaringType ) ; } } System.Collections.Generic.List ` 1 [ T ] System.Collections.Generic.List ` 1 [ T ] public static class GenericClass { public static void GenericMethod < TMethodParam > ( IList < TMethodParam > list ) { } } GenericClass.GenericMethod ( new List < int > ( ) ) ; typeof ( GenericClass ) .GetMethods ( ) [ 0 ] .GetParameters ( ) [ 0 ] .ParameterType == listInterfaceType ; | Generic strange behaviour |
C_sharp : A question related to the C # /.NET compiler used in Visual Studio 2010 : During the development of a project , a colleague encountered a situation where the VS2010 compiler would crash when using existing code inside a lock . We took the code apart line-by-line to eventually come to the conclusion that using a yield return inside a foreach through an array within a lock statement would crash the compiler . The issue can be reproduced with the following code : We continued to test this reproduction sample on Visual Studio 2013 and it did not exhibit the same problem . This compiler issue seems to be related to the compiler used in VS2010 , and might or might not have the same problem in VS2012 ( we do not have access to it for testing purposes ) . Furthermore , we have tested that using a regular for loop does not crash . The question therefore is , why does the VS2010 compiler crash ? What is it doing that confuses it so much ? ( Yes , this is mostly a question for interests-sake to learn about the compiler ) <code> using System ; using System.Collections.Generic ; namespace PlayGround { public static class Program { private static readonly object SyncRoot = new object ( ) ; private static IEnumerable < int > EnumerableWithLock ( ) { lock ( SyncRoot ) { foreach ( var i in new int [ 1 ] ) { yield return i ; } } } public static void Main ( ) { foreach ( var i in EnumerableWithLock ( ) ) { Console.WriteLine ( i ) ; } } } } | Why does a yield in a foreach-iteration through an array within a lock crash the VS2010 compiler ? |
C_sharp : I 'm using an API where , unfortunately , calling a get property accessor has a side-effect . How can I ensure that : is n't optimized away by the compiler ? <code> public void Foo ( ) { var x = obj.TheProp ; // is it guarnateed to be accessed ? } | Ensure statement is not optimized `` away '' |
C_sharp : I started off by reading through this suggested question similar to mine , but there was no resolution : Why does MSTest.TestAdapter adds its DLLs into my NuGet package ? Quick Problem DescriptionI wrote a NuGet package , and each time I install it , NUnit and NUnit3TestAdapter .dll 's get added to the project I installed on . I want to find a solution that fixes this issue.Repro stepsI have pushed two git repositories that reproduce the issue I am describing.ClientLibrary / MainFramework ( project from which I generated NuGet package ) - https : //github.com/harbourc/client-library-repro-nuget-issueTargetProject ( project that package is to be installed on ) - https : //github.com/harbourc/target-project-repro-nuget-issueYou can clone both repositories , restore their NuGet packages , and reproduce the issue as follows : Locate ClientLibrary.1.0.0.nupkg in client-library-repro-nuget-issue/ClientLibrary/Open package manager console for target-project-repro-nuget-issue and runNote the NUnit and NUnit3TestAdapter .dll 's that are added into TargetProject -- even though TargetProject already has NUnit and NUnit3TestAdapter installed.Longer OverviewI have created my own NuGet package for internal use , called ClientLibrary , and I am attempting to install it on to another project , called TargetProject . Here is a quick breakdown of the structure : FullSolution.slnMainFramework.csprojClientLibrary.csproj -- > .nupkg generated from thisSeparate project : TargetProject.slnTargetProject.csproj -- > install .nupkg onto thisClientLibrary has a reference to MainFramework , and uses many methods from MainFramework.When installing ClientLibrary.1.0.0.nupkg onto TargetProject , the following .dll 's are getting added to TargetProject : If I delete these .dll 's , everything works fine , because TargetProject already has those packages installed anyway . They are not necessary , it 's just annoying to have to delete them when installing.Here is how I am adding ClientLibrary NuGet package to TargetProject : Build ClientLibrary and MainFramework projects to generate their .dllsChange directory into ClientLibrary folder and run nuget spec.nuspec file is generated : Run nuget pack -IncludeReferencedProjects -- Because ClientLibrary has a dependency on MainFramework ( and several other packages used by MainFramework ) Navigate to TargetProject , open Package Manager ConsoleRun Install-Package C : \Path\To\ClientLibrary.1.0.0.nupkgInstallation runs successfully , and then those .dll 's I am complaining about get added.Problem : MainFramework has NUnit and NUnit3TestAdapter NuGet packages installed . ClientLibrary does not . So , the .dll 's seem to be added because they are installed on MainFramework , but NOT installed on ClientLibrary . ( Remember , ClientLibrary references MainFramework.dll . ) There are other packages installed on both MainFramework and ClientLibrary , and these do not have .dll 's that get added to TargetProject upon installation , so I am assuming issue is caused by having packages present in MainFramework but NOT in ClientLibrary.I believe I can `` fix '' this issue by installing NUnit and NUnit3TestAdapter onto ClientLibrary , but ClientLibrary does n't actually use those packages at all , so it seems unnecessary.How can I install ClientLibrary onto TargetProject without including the NUnit and NUnit3TestAdapter .dll 's , and without having to install NUnit and NUnit3TestAdapter onto ClientLibrary ? If possible , I would like to tell ClientLibrary.1.0.0.nupkg to use the NUnit and NUnit3TestAdapter packages that are already installed on TargetProject.If the answer is `` Not possible '' , that is fine , but I would like an explanation -- my overall goal for this question is to gain a better understanding of how NuGet and dependencies work , and understand why this has been an issue in the first place . Thank you for reading . <code> Install-Package C : \Path\To\client-library-repro-nuget-issue\ClientLibrary\ClientLibrary.1.0.0.nupkg nunit.engine.api.dllnunit.engine.dllNUnit3.TestAdapter.dllNUnit3.TestAdapter.pdb < ? xml version= '' 1.0 '' ? > < package > < metadata > < id > ClientLibrary < /id > < version > 1.0 < /version > < title > Client Library < /title > < authors > Myself < /authors > < requireLicenseAcceptance > false < /requireLicenseAcceptance > < description > Client library for interacting with my application. < /description > < dependencies > < group targetFramework= '' .NETFramework4.7.2 '' / > < /dependencies > < /metadata > < /package > | Can I work around adding these .dlls when installing NuGet package ? |
C_sharp : Is there a property / method in Serilog where I could ( programmatically ) check the current configuration ? ( sinks , minimum level ) e.g . if have this config : How could I read this config later ? ( In my case the config is dynamically created outside my application ) <code> Log.Logger = new LoggerConfiguration ( ) .MinimumLevel.Debug ( ) .WriteTo.File ( `` log.txt '' ) .WriteTo.Console ( restrictedToMinimumLevel : LogEventLevel.Information ) .CreateLogger ( ) ; | Read current Serilog 's configuration |
C_sharp : I 've create a SPROC that saves an object and returns the id of the new object saved . Now , I 'd like to return an int not an int ? Thanks for helping <code> public int Save ( Contact contact ) { int ? id ; context.Save_And_SendBackID ( contact.FirstName , contact.LastName , ref id ) ; //How do I return an int instead of an int ? } | How do I convert int ? into int |
C_sharp : I have seen that is is possible to add compiled methods together . Does it make sense to do this ? I would intend to use the filter in place of a lambda expression to filter a repository of customers : Depending on business logic , I may or may not add the three compiled methods together , but pick and choose , and possibly add more compiled methods as I go.Can anyone explain if adding them together would build up a query string or not ? Anyone got a better suggestion ? I could chain `` Where '' statements and use regular lambda expressions , but I am intrigued by what you might gain from compiling methods and adding them up ! <code> Expression < Func < Customer , bool > > ln = c = > c.lastname.Equals ( _customer.lastName , StringComparison.InvariantCultureIgnoreCase ) ; Expression < Func < Customer , bool > > fn = c = > c.firstname.Equals ( _customer.firstName , StringComparison.InvariantCultureIgnoreCase ) ; Expression < Func < Customer , bool > > fdob = c = > c.DOB.ToString ( `` yyyyMMdd '' ) .Equals ( _customer.DOB.ToString ( `` yyyyMMdd '' ) ) ; var filter = ln.Compile ( ) + fn.Compile ( ) + fdob.Compile ( ) ; IEnumerable < Customer > customersFound = _repo.Customers.Where ( filter ) ; | What 's the purpose of adding compiled Func methods together ? |
C_sharp : I 'm writing a quadtree-like data structure which contains matrices of generic objects T. If four subnodes all contain defined matrices of T , I 'm going to aggregate them into a single , larger matrix , then delete the subnodes . Is there a more efficient way to do this than looping through every reference and copying it over ? Can I copy chunks of memory instead ? Example : <code> T [ , ] _leaf1 = new T [ 64,64 ] ; T [ , ] _leaf2 = new T [ 64,64 ] ; T [ , ] _leaf3 = new T [ 64,64 ] ; T [ , ] _leaf4 = new T [ 64,64 ] ; // Populate leafsT [ , ] _root = new T [ 128,128 ] ; CopyInto ( ref _root , ref _leaf1 , 64 , 64 ) ; CopyInto ( ref _root , ref _leaf2 , 0 , 64 ) ; CopyInto ( ref _root , ref _leaf3 , 0 , 0 ) ; CopyInto ( ref _root , ref _leaf4 , 64 , 0 ) ; | Efficiently copying a matrix of objects to a larger matrix of objects |
C_sharp : I have a class that has the variable `` Magic '' . This is a 4 char string . Can I do something like this in C # ? *Assume that `` chunkList '' is an IList/List of `` chunk '' objects . <code> string offset = chunkList [ `` _blf '' ] .offset ; | Can I use Square Brackets to pull a value from a class |
C_sharp : I 'm not wanting to start a flame war on micro-optimisation , but I am curious about something.What 's the overhead in terms of memory and performance of creating instances of a type that has no intrinsic data ? For example , a simple class that implements IComparer < T > may contain only a Compare method , and no properties or fields . Typical example code I 've seen just calls new FooComparer ( ) , wherever one of these is needed.I ca n't imagine the instantiation cost here is very much at all , but I 'm interested to know what it actually is . And how would it compare to , say , a static factory class that maintains a dictionary of types to comparers so that one comparer instance can be used everywhere it 's needed . <code> class FooComprarer : IComparer < Foo > { public int Compare ( Foo x , Foo y ) { // blah , blah } } | What 's the overhead of a data-less type ? |
C_sharp : Hey how can I detect when my ListView is scrolled up or down ? I have this : Do I need to do something with `` verticalBar.Height > verticalBar.ActualHeight '' ? <code> private void MainPage_OnLoaded ( object sender , RoutedEventArgs e ) { var scrollViewer = MyListView.GetFirstDescendantOfType < ScrollViewer > ( ) ; scrollViewer.ViewChanged += BarScroll ; } private void BarScroll ( object sender , ScrollViewerViewChangedEventArgs e ) { var scrollbars = ( sender as ScrollViewer ) .GetDescendantsOfType < ScrollBar > ( ) .ToList ( ) ; var verticalBar = scrollbars.FirstOrDefault ( x = > x.Orientation == Orientation.Vertical ) ; if ( verticalBar ) ( /*If ListView is scrolled up*/ ) { //Code when the ListView is scrolled up } else ( /*If ListView is scrolled down*/ ) { //Code for when the ListView is scrolled down } } | Detect when ListView is scrolled `` up '' or `` down '' ? Windows Phone 8.1 ListView |
C_sharp : I have problems with the `` order '' of the values of an enum . It 's a little difficult to explain , that 's why I wrote up some code : The output is : Enum A : TwoTwoTwoFourEnum B : ThreeThreeThreeFourEnum C : OneOneOneFourMy question is : WHY ! ? I ca n't find the logic to the output . Most of the time there is some logic to be found , so I hope you guys can shine some light on this issue.I used VS2010 / .Net 4.0 to compile and run the code . <code> class Program { public enum EnumA { One = 1 , Two = One , Three = Two , Four = 4 } public enum EnumB { One = 1 , Two = One , Four = 4 , Three = Two } public enum EnumC { Two = One , Three = Two , Four = 4 , One = 1 } static void Main ( string [ ] args ) { Console.WriteLine ( `` Enum A : '' ) ; Console.WriteLine ( EnumA.One ) ; Console.WriteLine ( EnumA.Two ) ; Console.WriteLine ( EnumA.Three ) ; Console.WriteLine ( EnumA.Four ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Enum B : '' ) ; Console.WriteLine ( EnumB.One ) ; Console.WriteLine ( EnumB.Two ) ; Console.WriteLine ( EnumB.Three ) ; Console.WriteLine ( EnumB.Four ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Enum C : '' ) ; Console.WriteLine ( EnumC.One ) ; Console.WriteLine ( EnumC.Two ) ; Console.WriteLine ( EnumC.Three ) ; Console.WriteLine ( EnumC.Four ) ; Console.WriteLine ( ) ; Console.ReadLine ( ) ; } } | Why ( and how ) does the order of an Enum influence the ToString value ? |
C_sharp : I 'm missing something basic , but I ca n't figure it out . Given : Over in another class I want to allow callers to be able to RegisterFor < SpecialEvent > ( x = > { ... } ) However , the _validTypes.Add line does not compile . It can not convert a Action < T > to an Action < EventBase > . The constraint specifies that T must be derived from EventBase , so what am I misunderstanding ? <code> abstract class EventBase { } class SpecialEvent : EventBase { } public class FooHandler { { internal Dictionary < Type , Action < EventBase > > _validTypes = new Dictionary < Type , Action < EventBase > > ( ) ; internal void RegisterFor < T > ( Action < T > handlerFcn ) where T : EventBase { _validTypes.Add ( typeof ( T ) , handlerFcn ) ; } } | Why is the generic parameter not casting ? |
C_sharp : I am trying to do some charting in LinqPad . I have some logs from an api and i know , what api was called and if the request was cached ( in our real case we resolve address with coordinates from bing api or we get addres from cache table if we have cached it ) i use this linqpad script : That is the result : Actually i want to have only 3 , columns per day but they have to be slacked ( to show in one column both total and cached values ) if i switch to SlackedColumns i have all values in one column together and is not what i want : Any ideas , how to do it ? Update : What i want is something like this ( but i prefer , that it is grouped on date , like linqpad is doing that ) : <code> var startDate = new DateTime ( 2019 , 1,1 ) ; var Requests = new [ ] { new { Date=startDate , Name = `` Api1 '' , Cached=true } , new { Date=startDate , Name = `` Api2 '' , Cached=true } , new { Date=startDate , Name = `` Api3 '' , Cached=true } , new { Date=startDate , Name = `` Api1 '' , Cached=true } , new { Date=startDate , Name = `` Api1 '' , Cached=false } , new { Date=startDate , Name = `` Api2 '' , Cached=false } , new { Date=startDate , Name = `` Api3 '' , Cached=false } , new { Date=startDate , Name = `` Api1 '' , Cached=false } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api3 '' , Cached=true } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api1 '' , Cached=false } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api2 '' , Cached=true } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api2 '' , Cached=false } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api1 '' , Cached=true } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api1 '' , Cached=false } , new { Date=startDate.AddDays ( 1 ) , Name = `` Api3 '' , Cached=true } , } ; Requests.GroupBy ( x= > x.Date ) .Chart ( c = > c.Key ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api1 '' ) , name : '' Api1 '' ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api2 '' ) , name : '' Api2 '' ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api3 '' ) , name : '' Api3 '' ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api1 '' & & x.Cached ) , name : `` Api1 Cached '' ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api2 '' & & x.Cached ) , name : `` Api2 Cached '' ) .AddYSeries ( c = > c.Count ( x= > x.Name== '' Api3 '' & & x.Cached ) , name : `` Api3 Cached '' ) .Dump ( ) ; | Linqpad Charting . Combination of Column and StackedColumn |
C_sharp : While going through our client 's code , I came across below interface in C # , which is having a member with `` this '' keyword.I am not aware of any such pattern or practice where interface member name starts with `` this '' . To understand more , I checked the implementation of this interface , however still not able to figure out its purpose.And here is the caller code : Unfortunately , I am not able to debug this code to see the things live . But very curious about it . If the implemented code is finally returning a string , then what is the use of `` this '' keyword out there ? <code> public interface ISettings { string this [ string key ] { get ; } } internal class SettingsManager : ISettings { public string this [ string key ] { get { return ConfigurationManager.AppSettings [ key ] ; } } ... ... } public static class Utility { public static ISettings Handler { get ; set ; } public static string Get ( string key , string defaultValue ) { var result = Handler [ key ] ; return Is.EmptyString ( result ) ? defaultValue : result ; } } | Interface member with `` this '' keyword |
C_sharp : I currently have the followingwould it be cleaner to do this ? is it safe ? <code> if ( ! RunCommand ( LogonAsAServiceCommand ) ) return ; if ( ! ServicesRunningOrStart ( ) ) return ; if ( ! ServicesStoppedOrHalt ( ) ) return ; if ( ! BashCommand ( CreateRuntimeBashCommand ) ) return ; if ( ! ServicesStoppedOrHalt ( ) ) return ; if ( ! BashCommand ( BootstrapDataBashCommand ) ) return ; if ( ! ServicesRunningOrStart ( ) ) return ; if ( ( RunCommand ( LogonAsAServiceCommand ) ) & & ( ServicesRunningOrStart ( ) ) & & ( ServicesStoppedOrHalt ( ) ) & & ( BashCommand ( CreateRuntimeBashCommand ) ) & & ( ServicesStoppedOrHalt ( ) ) & & ( BashCommand ( BootstrapDataBashCommand ) ) & & ( ServicesRunningOrStart ( ) ) ) { // code after `` return statements '' here } | c # is this design `` Correct '' ? |
C_sharp : I have the following html helper method : I have a need to put move it to into a helper library that is structured in this way : I am unable to figure out how to structure my HelperFactory class and the EditorBuilder class constructor to handle the generics correctly.This is what I tried and it did n't work : The end goal is to be able to use it in this manner : @ Html.Custom ( ) .CustomEditorFor ( model= > model.Property ) Any assistance would be greatly appreciated . <code> public static MvcHtmlString CustomEditorFor < TModel , TProperty > ( this HtmlHelper < TModel > helper , Expression < Func < TModel , TProperty > > expression , EditorOptions options , object htmlAttributes ) { } public class HtmlHelperExenion { public static Custom ( this HtmlHelper helper ) { return new HelperFactory ( helper ) ; } } public class HelperFactory { internal HtmlHelper HtmlHelper { get ; set ; } public HelperFactory ( HtmlHelper htmlHelper ) { this.HtmlHelper = htmlHelper ; } public virtual EditorBuilder CustomEditorFor ( parameters from static MvcHtmlString static method above go here ) { return new EditorBuilder ( parameters go here ) ; } } public static HelperFactory < TModel , TProperty > Custom < TModel , TProperty > ( this HtmlHelper < TModel > helper ) { return new HelperFactory < TModel , TProperty > ( helper ) ; } public class HelperFactory < TModel , TProperty > : HelperFactory { public HtmlHelper < TModel > HtmlHelper { get ; set ; } public HelperFactory ( HtmlHelper < TModel > htmlHelper ) : base ( ( HtmlHelper ) htmlHelper ) { this.HtmlHelper = htmlHelper ; } public virtual EditorBuilder < TModel , TProperty > CustomEditorFor ( Expression < Func < TModel , TProperty > > expression , EditorOptions options , object htmlAttributes ) { return new EditorBuilder < TModel , TProperty > ( this.HtmlHelper , expression , options , htmlAttributes ) ; } } public class EditorBuilder < TModel , TProperty > { public EditorBuilder ( HtmlHelper < TModel > helper , Expression < Func < TModel , TProperty > > expression , EditorOptions options , object htmlAttributes ) { } } | Convert static method with generic paramerter to a generic class |
C_sharp : I 'm developing an app with Entity Framework.I 've got a combo box with the names of the tables in the database.I have the following code : how can i avoid all these if-else checks ? Is it possible to get the name of a class from a string holding the name ? example : <code> string table = cbTables.SelectedItem.ToString ( ) ; using ( var dbContext = new Entities ( ) ) { if ( table.Equals ( `` Person '' ) ) { List < Person > list = ( from l in dbContext.People select l ) .ToList ( ) ; } else if ( table.Equals ( `` Student '' ) ) { List < Student > list = ( from u in dbContext.Student select u ) .ToList ( ) ; } else if ( table.Equals ( `` Grade '' ) ) { List < Grade > list = ( from p in dbContext.Grade select p ) .ToList ( ) ; } string = `` Person '' ; var str = //somethingList < str > list = ( from u in dbContext.str select u ) .ToList ( ) ; | Avoid a lot of if - else checks - Choose table from string using the entity framework |
C_sharp : Can you please tell me what kind of construct in C # is this.Code Golf : Numeric equivalent of an Excel column nameThough I am new to C # ( only two months exp so far ) , but since the time I have joined a C # team , I have never seen this kind of chaining . It really attracted me and I want to learn more about it.Please give some insight about this . <code> C.WriteLine ( C.ReadLine ( ) .Reverse ( ) .Select ( ( c , i ) = > ( c - 64 ) * System.Math.Pow ( 26 , i ) ) .Sum ( ) ) ; | What is this kind of chaining in C # called ? |
C_sharp : I 'm trying a simple comparison here , assignment does n't work as i would like ... here is the code , I ran my debugger ( In VS ) and when that assignment is called , the int on the right was equal to 50 , but the int on the left stayed equal to 0 . No idea what I 'm missing.This application is using the Abbyy FineReader 9.0 SDK and the documentation for FirstSymbolPosition says it returns a read-only LongEDIT : the code has been stripped of all features to make it easier for viewers to see where the problem is . I would appreciate answers for the original questions and anything else with the code that is bugging you as a comment please . <code> int returnDateIndex ( Paragraph para ) { long firstIndex = 0 ; for ( int i = 0 ; i < para.Words.Count ; i++ ) { if ( para.Words [ i ] .Text == `` Second '' ) { if ( para.Words [ i - 1 ] .Text == `` First '' ) { firstIndex = para.Words [ i ] .FirstSymbolPosition ; } } } return ( int ) firstIndex ; } | C # Noob with a question : Int assignment not working as expected |
C_sharp : In my controller I need to call a method BlockingHttpRequest ( ) which makes an http request . It is relatively slow running , and blocks the thread.I am not in a position to refactor that method to make it async.Is it better to wrap this method in a Task.Run to at least free up a UI/controller thread ? I 'm not sure if this really improves anything , or just makes more work.In practice I have a couple of situations like this , where BlockingHttpRequest ( ) takes 500ms and 5000ms respectively.I understand that Task.Run ( ) will not make my function return sooner.I thought that there might be some benefit of increased throughput . By freeing up the controller 's thread , does that make it available to other users ? This would imply that in MVC there is a difference between controller threads and background worker threads . <code> public class MyController : Controller { public async Task < PartialViewResult > Sync ( ) { BlockingHttpRequest ( ) ; return PartialView ( ) ; } public async Task < PartialViewResult > Async ( ) { await Task.Run ( ( ) = > BlockingHttpRequest ( ) ) ; return PartialView ( ) ; } } | Can you increase throughput by using Task.Run on synchronous code in a controller ? |
C_sharp : The documented derivation constraint uses a where T : clause and the sample code that I 'm tinkering with iswhere IPassClass is an interface.Code from a third-party that I am using has the formatBoth result in the same behaviour in my code , but are they the same and if not what is the difference ? <code> public class TwoThingsIPC < T > where T : IPassClass { ... } public class TwoThingsIPC < IPassClass > { ... } | Which is the preferred syntax for a Generic Class Derivation Constraint ? |
C_sharp : I want a generic way to convert an asynchronous method to an observable . In my case , I 'm dealing with methods that uses HttpClient to fetch data from an API.Let 's say we have the method Task < string > GetSomeData ( ) that needs to become a single Observable < string > where the values is generated as a combination of : Repeated periodic calls to GetSomeData ( ) ( for example every x seconds ) Manually triggered calls to GetSomeData ( ) at any given time ( for example when user hits refresh ) .Since there is two ways to trigger execution of GetSomeData ( ) concurrency can be an issue . To avoid demanding that GetSomeData ( ) is thread-safe , I want to limit the concurrency so that only one thread is executing the method at the same time . As a consequence I need to handle overlapping requests with some strategy . I made a ( kind of ) marble diagram trying to describe the problem and wanted outcomeMy instinct tells me there is a simple way to achieve this , so please give me some insights : ) This is the solution I 've got so far . It unfortunately does n't solve the concurrency problem.Extension method for repeating with delay : An example of a service containing the method to generate the observableUsed like this ( data race will occur ) : <code> public class ObservableCreationWrapper < T > { private Subject < Unit > _manualCallsSubject = new Subject < Unit > ( ) ; private Func < Task < T > > _methodToCall ; private IObservable < T > _manualCalls ; public IObservable < T > Stream { get ; private set ; } public ObservableCreationWrapper ( Func < Task < T > > methodToCall , TimeSpan period ) { _methodToCall = methodToCall ; _manualCalls = _manualCallsSubject.AsObservable ( ) .Select ( x = > Observable.FromAsync ( x = > methodToCall ( ) ) ) .Merge ( 1 ) ; Stream = Observable.FromAsync ( ( ) = > _methodToCall ( ) ) .DelayRepeat ( period ) .Merge ( _manualCalls ) ; } public void TriggerAdditionalCall ( ) { _manualCallsSubject.OnNext ( Unit.Default ) ; } } static class Extensions { public static IObservable < T > DelayRepeat < T > ( this IObservable < T > source , TimeSpan delay ) = > source .Concat ( Observable.Create < T > ( async observer = > { await Task.Delay ( delay ) ; observer.OnCompleted ( ) ; } ) ) .Repeat ( ) ; } class SomeService { private int _ticks = 0 ; public async Task < string > GetSomeValueAsync ( ) { //Just a hack to dermine if request was triggered manuall or by timer var initiatationWay = ( new StackTrace ( ) ) .GetFrame ( 4 ) .GetMethod ( ) .ToString ( ) .Contains ( `` System.Threading.CancellationToken '' ) ? `` manually '' : `` by timer '' ; //Here we have a data race ! We would like to limit access to this method var valueToReturn = $ '' { _ticks } ( { initiatationWay } ) '' ; await Task.Delay ( 500 ) ; _ticks += 1 ; return valueToReturn ; } } static async Task Main ( string [ ] args ) { //Running this program will yield non deterministic results due to data-race in GetSomeValueAsync var someService = new SomeService ( ) ; var stopwatch = Stopwatch.StartNew ( ) ; var observableWrapper = new ObservableCreationWrapper < string > ( someService.GetSomeValueAsync , TimeSpan.FromMilliseconds ( 2000 ) ) ; observableWrapper.Stream .Take ( 6 ) .Subscribe ( x = > { Console.WriteLine ( $ '' { stopwatch.ElapsedMilliseconds } | Request : { x } fininshed '' ) ; } ) ; await Task.Delay ( 4000 ) ; observableWrapper.TriggerAdditionalCall ( ) ; observableWrapper.TriggerAdditionalCall ( ) ; Console.ReadLine ( ) ; } | Create observable from periodic async request |
C_sharp : Assume i want to create an alias of a type in C # using a hypothetical syntax : Then i go away and create a few thousand files that use Currency type.Then i realize that i prefer to use FCL types : Excellent , all code still works ... .months later ... Wait , i 'm getting some strange rounding errors . Oh that 's why , System.Single only has 7 digits of precision . Lets up that to 15 digits : ... years later ... Ohhhh , floating point is n't exact ; multiplying $ 0.0011/unit * 217,384 units exposes some limitations of using floating point . And accountants are sticklers against `` accounting irregularities '' . No problem : ... years later ... International applications ? Currency codes . Hmmmm . Thank you CodeProject : ... later ... Ooo , patterns and practices . Let 's obfuscate some of that code : And during all this nonsense code did n't break.i know C # does n't support this level of encapsulation and resilency with the syntax i made up.But can anyone suggest a syntax that can simulate what people have been trying to accomplish ( including myself ) ? <code> Currency = float ; Currency = System.Single ; Currency = System.Double ; Currency = System.Decimal ; Currency = Money ; Currency = ICurrency ; | Techniques for aliasing in C # ? |
C_sharp : Essentially , will more memory be used by instances of Foo when its value is acquired like this : or like this ? That is , is memory used per-method per-object or per-type ? <code> public class Foo { internal double bar ; double GetBar ( ) { return bar ; } } public class Foo { internal double bar ; } public static class FooManager { public static double GetBar ( Foo foo ) { return foo.bar ; } } | Does it cost more memory to load classes with more methods ? |
C_sharp : Background I am creating a custom wpf panel . To help lay out the child items it uses a secondary list ( similar to Grid.RowDefinitions or Grid.ColumnDefinitions ) that I call `` layouts '' . Each layout has a couple dependency properties , and child items use an attached property to determine where they 're placed as seen below.Obviously , things are simplified a bit , but long story short : I need to process the layouts as they are added before the `` Arrange '' process can occur . I have created a custom collection and I can see the items as they are added ( see code below ) , but the items just have their default properties.However , when I look at the collection after the panel has been initialized the properties are all set correctly . Which brings me to my question : QuestionAt what point during the process between XAML and initialization of the panel do the items get assigned their properties , and how are they assigned ? I need to somehow hook on to that and run a bit of code . <code> < Panel > < Panel.Layouts > < Layout/ > < Layout Attachment= '' Right '' / > < Layout Attachment= '' Left '' Target= '' 0 '' / > < /Panel.Layouts > < ChildItem Panel.Layout= '' 0 '' / > < ChildItem Panel.Layout= '' 1 '' / > < ChildItem Panel.Layout= '' 2 '' / > < Panel/ > LayoutCollection : IList { public int IList.Add ( object value ) { // When first starting , this line always returns the default value , not the one set in XAML Attachment a = ( value as Layout ) .Attachment ; // Other code happens below ... } } | When do declared XAML list items have their dependency properties set ? |
C_sharp : I have doubt about these two aspects ; First one ; Second one ; What happens if we dont assign the newly created instance to a variable and directly call the method ? I see some difference between two way on IL code.This one below is IL output of first c # codeAnd this one is the IL output of the second c # codeCould you please inform me ? <code> Test test = new Test ( ) ; result = test.DoWork ( _param ) ; result = new Test ( ) .DoWork ( _param ) ; IL_0000 : ldstr `` job `` IL_0005 : stloc.0 IL_0006 : newobj instance void Works.Test : :.ctor ( ) IL_000b : stloc.1 IL_000c : ldloc.1 IL_000d : ldloc.0 IL_000e : callvirt instance string Works.Test : :DoWork ( string ) IL_0013 : pop IL_0014 : ret IL_0000 : ldstr `` job `` IL_0005 : stloc.0 IL_0006 : newobj instance void Works.Test : :.ctor ( ) IL_000b : ldloc.0 IL_000c : call instance string Works.Test : :DoWork ( string ) IL_0011 : pop IL_0012 : ret | Calling method of non-assigned class |
C_sharp : Our company is switching the SMTP mail server to Office 365 . The key issue is the new SMTP server `` smtp.office365.com '' only supports TLS encryption . Thus I can not use CredentialCache.DefaultNetworkCredentials to encode my Windows log-in password automatically.Previously this works without any issue . But if I now change the above snippet to : I 'm now getting : But if I specify my Windows login username and password in the code it works fine : So : Is it possible to encode the password using DefaultNetworkCredentials but make it workable under TLS encryption ? If 1. is not possible , is there a better way to encode my Windows password somewhere else without directly revealing it as plaintext in the code ? <code> var smtpClient = new SmtpClient ( `` smtp.oldserver.com '' ) { Credentials = CredentialCache.DefaultNetworkCredentials } ; const string from = `` myemail @ xyz.com '' ; const string recipients = `` myemail @ xyz.com '' ; smtpClient.Send ( from , recipients , `` Test Subject '' , `` Test Body '' ) ; var smtpClient = new SmtpClient ( `` smtp.office365.com '' ) ; smtpClient.EnableSsl = true ; smtpClient.Port = 587 ; smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials ; Unhandled Exception : System.Net.Mail.SmtpException : The SMTP server requires a secure connection or the client was not authenticated . The server response was : 5.7.57 SMTP ; Client was not authenticated to send anonymous mail during MAIL FROM smtpClient.Credentials = new NetworkCredential ( `` myemail @ xyz.com '' , `` mypassword '' ) ; | Use DefaultNetworkCredential under TLS encryption ? |
C_sharp : A question came up during a code review the other day about how quickly a using block should be closed . One camp said , 'as soon as you are done with the object ' ; the other , 'sometime before it goes out of scope'.In this specific example , there are a DataTable and a SqlCommand object to be disposed . We need to reference both in a single statement , and we need to iterate the DataTable.Camp 1 : Reasoning : Dispose the SqlCommand as soon as you are done using it . Do n't start potentially long operations , such as iterating the table , within another object 's using block.Camp 2 : Reasoning : This code is much cleaner . All objects are guaranteed to be disposed no matter what , and none are really resource-intensive , so it is not important to dispose any immediately.I 'm in Camp 2 . Where are you , and why ? Edit : Several people have pointed out that DataTable need not be disposed ( see Corey Sunwold 's answer ) and that Camp 1 's original example is uglier than it needs to be . Here are some revised examples that also take into account the fact that most of the time , I have to set some properties on the SqlCommand . If anyone has seen or can think of a better example to support either position , please share it.Camp 1 , version 2 : Camp 2 , version 2 : I think most people will agree that the readability argument is now much reduced , and that this is not the best example of what I am trying to ask . ( That is especially true once I tell you that the SqlConnection is closed before the GetDataTable ( ) method exits , and there is no measurable performance difference for the data used in this instance . ) If I may add to my question this late , are there instances where it does make a difference whether I dispose the object immediately ? For example , as Gregory Higley mentioned , a shared resource like an OS handle.Edit : ( Explaining my choice of answer ) Many thanks to all who contributed opinions , examples , and other helpful feedback ! We seem to be split about evenly , but what stands out from everyone 's answers is the idea that 'camp 1 is definitely right , but depending on the object , camp 2 may be okay ' . I meant this to be a general discussion of disposal of all types of objects , but I chose a bad example to illustrate it . Since much of the discussion focused on that particular example , I have chosen the answer that gave me important information about the specific objects in use , and proved that I need to consider each object carefully when making this kind of decision . ( It would be difficult to choose a 'best answer ' to a question as vague as what is in my title , anyway . ) Future readers with the same dilemma , please see all the answers below , as many of them raise interesting points . <code> List < MyObject > listToReturn = new List < MyObject > ( ) ; DataTable dt = null ; try { using ( InHouseDataAdapter inHouseDataAdapter = new InHouseDataAdapter ( ) ) using ( SqlCommand cmd = new SqlCommand ( ) ) { dt = inHouseDataAdapter.GetDataTable ( cmd ) ; } foreach ( DataRow dr in dt.Rows ) { listToReturn.Add ( new MyObject ( dr ) ) ; } } finally { if ( dt ! = null ) { dt.Dispose ( ) ; } } List < MyObject > listToReturn = new List < MyObject > ( ) ; using ( InHouseDataAdapter inHouseDataAdapter = new InHouseDataAdapter ( ) ) using ( SqlCommand cmd = new SqlCommand ( ) ) using ( DataTable dt = inHouseDataAdapter.GetDataTable ( cmd ) ) { foreach ( DataRow dr in dt.Rows ) { listToReturn.Add ( new MyObject ( dr ) ) ; } } DataTable dt = null ; using ( InHouseDataAdapter inHouseDataAdapter = new InHouseDataAdapter ( _connectionString ) ) using ( SqlCommand cmd = new SqlCommand ( `` up_my_proc '' ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.Parameters.Add ( `` @ class_id '' , 27 ) ; dt = inHouseDataAdapter.GetDataTable ( cmd ) ; } foreach ( DataRow dr in dt.Rows ) { listToReturn.Add ( new MyObject ( dr ) ) ; } using ( InHouseDataAdapter inHouseDataAdapter = new InHouseDataAdapter ( _connectionString ) ) using ( SqlCommand cmd = new SqlCommand ( `` up_my_proc '' ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.Parameters.Add ( `` @ class_id '' , 27 ) ; DataTable dt = inHouseDataAdapter.GetDataTable ( cmd ) ; foreach ( DataRow dr in dt.Rows ) { listToReturn.Add ( new MyObject ( dr ) ) ; } } | How quickly should I close a using block ? |
C_sharp : I want to check some locking behaviors and i ca n't understand this : I thought that this should not work due to the fact i am doing the synchronization on an integer value . First Boxing , then Unboxing and i should get a System.Threading.SynchronizationLockException because of the missing sync block root ( i know this is specific to reference types ) .I am not going to fool myself , even if this works for a few iterations , it 's not really synchronized.. so , taking into consideration the non atomic property of the increment operation .. i will not get deterministic results.. i am aware of this.Indeed , when i get rid of that Thead.Sleep and put a Wait on the Task.. the exception comes into place . I think an exception should be thrown here : Monitor.Exit ( sync ) but what catches it ? Update 1 : pic added . <code> static void Main ( string [ ] args ) { for ( int i = 0 ; i < 10 ; i++ ) { Task.Factory.StartNew ( ( ) = > { MultithreadedMethod ( ) ; } ) ; } Thread.Sleep ( 2000 ) ; Console.WriteLine ( count ) ; } static int count = 0 ; private static readonly int sync = 5 ; public static void MultithreadedMethod ( ) { if ( Monitor.TryEnter ( sync ) ) { count++ ; Monitor.Exit ( sync ) ; } } Task.Factory.StartNew ( ( ) = > { MultithreadedMethod ( ) ; } ) .Wait ( ) ; | Locking on a primitive type |
C_sharp : I was all excited at writing this generic function when the compiler threw an error ( unable to cast T to System.Web.UI.Control ) I basically pass it a type when I call it , and it look for all controls of that type . The error occurs on l.Add ( ( T ) ctrl ) ; Am I missing something or am I just out of luck ? <code> private List < T > RecurseTypes < T > ( Control ctrls ) { var l = new List < T > ( ) ; foreach ( var ctrl in ctrls.Controls ) if ( ctrl.GetType ( ) is T ) l.Add ( ( T ) ctrl ) ; return l ; } | My first generic casting ( C # ) |
C_sharp : I have the following code : If I compile and run this using an x86 configuration in Visual Studio , then I get the following output : If I instead compile as x64 I get this : I realize that using 32 och 64 bit compilation must affect how double values are handled by the system , but given that C # defines double as being 64 bit , should n't the result of this operation be the same independently of what compilation configuration I use ? Additional observationBased on a comment regarding double.Parse I wrote this code : I get the following output when compiling as x86 : But I get this when I compile as x64 : Notice how the values differ in the x64 version , but not in the x86 version . <code> var d = double.Parse ( `` 4796.400000000001 '' ) ; Console.WriteLine ( d.ToString ( `` G17 '' , CultureInfo.InvariantCulture ) ) ; 4796.4000000000005 4796.4000000000015 var d0 = double.Parse ( `` 4796.400000000001 '' ) ; double d1 = 4796.400000000001 ; Console.WriteLine ( `` d0 : `` + d0.ToString ( `` G17 '' , CultureInfo.InvariantCulture ) ) ; Console.WriteLine ( `` d1 : `` + d1.ToString ( `` G17 '' , CultureInfo.InvariantCulture ) ) ; d0 : 4796.4000000000005d1 : 4796.4000000000005 d0 : 4796.4000000000015d1 : 4796.4000000000005 | On double parsing in C # |
C_sharp : I am trying to retrieve a value of private property via reflectionWhere is my mistake ? I will need to use object to pass instance , because some of private properties will be declared in the A or B . And even hiding ( with new ) Base properties sometimes . <code> // definitionpublic class Base { private bool Test { get { return true ; } } } public class A : Base { } public class B : Base { } // nowobject obj = new A ( ) ; // or new B ( ) // worksvar test1 = typeof ( Base ) .GetProperty ( `` Test '' , BindingFlags.Instance | BindingFlags.NonPublic ) ; if ( test1 ! = null ) // it 's not null if ( ( bool ) test1.GetValue ( obj , null ) ) // it 's true ... // does n't works ! var test2 = obj.GetType ( ) .GetProperty ( `` Test '' , BindingFlags.Instance | BindingFlags.NonPublic ) ; if ( test2 ! = null ) // is null ! ... | typeof ( ) works , GetType ( ) does n't works when retrieving property |
C_sharp : I have these lines in my view.cshtml : But now there is a red line under ; in javascript codes and the error is Syntax error.What is the problem ? <code> $ ( `` document '' ) .ready ( function ( ) { @ { var cx = Json.Encode ( ViewBag.x ) ; var cy = Json.Encode ( ViewBag.y ) ; } var x = @ cx ; var y = @ cy ; } ) ; | How to fill javascript variables with c # ones ? |
C_sharp : I 'm new to functional way of thinking in C # ( well ... not limited to language ) . Let 's say there 's method : Concept1 . ValidationWhen invalid input is given , I should return something like Either < IEnumerable < ValidationError > , T > .2 . ExecutionWhen calling DB/API/ ... which could throw , I should return Either < Exception , T > .3 . Some or none recordBecause entry may or may not exist I 'm returning Option < T > .Final signatureIf you combine all above , you end up with this : I can introduce types such as : Validation < T > ( ~ : Either < IEnumerable < ValidationError > , T > ) Result < T > ( ~ : Either < Exception , T > ) Now , signature of my method would look like : UsageImperative implementationQuestionAs you can see signature of method is still quite odd - at first sight it gives you `` validation '' , but I 'm really asking for T. Usage is also not very pretty looking , but indeed more concise than imperative one.Is this correct approach ? Is there way how to improve signature/readability of code ? <code> T LoadRecord < T > ( int id ) Either < IEnumerable < ValidationError > , Either < Exception , Option < T > > LoadRecord < T > ( int id ) Validation < Result < Option < T > > > LoadRecord < T > ( int id ) return LoadRecord < User > ( 1 ) .Match ( vl = > BadRequest ( ) , vr = > vr.Match ( el = > StatusCode ( 500 ) , er = > er.Some ( u = > Ok ( u ) ) .None ( NotFound ( ) ) ; try { var u = LoadRecord < User > ( id ) ; if ( u == null ) { return NotFound ( ) ; } return Ok ( u ) ; } catch ( ValidationException ) { return BadRequest ( ) ; } catch ( Exception ) { return StatusCode ( 500 ) ; } | C # FP : Validation and execution with error handling functional way - space for improvement ? |
C_sharp : I have a query which should be ordered like that : But if any object is null ( totally by design ) this query fails.How can I put null values at the end or skip ordering if object is null ? ADDED : as @ LasseV.Karlsen mentioned I might have ANOTHER problem.I really got ArgumentNullException , but the reason was not behind some object were null ( I saw it in debugger and falsely thought that it was my problem ) .The real reason was as @ RaphaëlAlthaus mentioned that I did n't implement IComparable < > at ANY of my classes in MonthClosureViewModel ... After I 've done it everything start working as intended even if object is null <code> var list = new List < MonthClosureViewModel > ( ) ; var orderedList = list .OrderByDescending ( x = > x.Project ) .ThenByDescending ( x = > x.ChargeLine ) .ThenByDescending ( x = > x.DomesticSite ) // < - x.DomesticSite might be null sometimes .ThenByDescending ( x = > x.ChargeSite ) // < - x.ChargeSite might be null sometimes .ThenByDescending ( x = > x.RateGroup ) .ThenByDescending ( x = > x.ApprovedHrs ) .ThenByDescending ( x = > x.NotApprovedHrs ) ; public class MonthClosureViewModel { public Project Project { get ; set ; } public ChargeLine ChargeLine { get ; set ; } public Site DomesticSite { get ; set ; } public Site ChargeSite { get ; set ; } public RateGroup RateGroup { get ; set ; } public decimal Rate { get ; set ; } public decimal ApprovedHrs { get ; set ; } public decimal NotApprovedHrs { get ; set ; } } | Skip ThenBy on nullable objects |
C_sharp : I have to parse out the system name from a larger string . The system name has a prefix of `` ABC '' and then a number . Some examples are : the full string where i need to parse out the system name from can look like any of the items below : before I saw the last one , i had this code that worked pretty well : but it fails on the last example where there is a bunch of other text before the ABC.Can anyone suggest a more elegant and future proof way of parsing out the system name here ? <code> ABC500ABC1100ABC1300 ABC1100 - 2pplABC1300ABC 1300ABC-1300Managers Associates Only ( ABC1100 - 2ppl ) string [ ] trimmedStrings = jobTitle.Split ( new char [ ] { '- ' , '– ' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( s = > s.Trim ( ) ) .ToArray ( ) ; return trimmedStrings [ 0 ] ; | In C # , what is the best way to parse out this value from a string ? |
C_sharp : I 'm making a query on a MethodInfo [ ] where I 'm trying to find all the methods that have a return type of void , and has only one parameter of a certain type . I want to do it in the most minimalistic and shortest way.One way to do it would be : orBut there 's a redundant GetParameters call - One call should be enough . So I thought I could cache that to an anonymous type like so : But it did n't work , I got errors saying there 's no Length nor an indexer for the anonymous type p which is of type ParameterInfo [ ] Is this the shortest way of writing this query ? if so , how can I get the anonymous type to work ? if not , what 's the shortest way of doing this ? ( get all methods of void return , and of one param where that param is of a certain type ) Thanks for any help : ) <code> var validMethods = methods.Where ( m = > m.ReturnType == typeof ( void ) & & m.GetParameters ( ) .Length == 1 & & m.GetParameters ( ) [ 0 ] .ParameterType == wantedType ) ; var validMethods = methods .Where ( m = > m.ReturnType == typeof ( void ) ) .Where ( m.GetParameters ( ) .Length == 1 & & m.GetParameters ( ) [ 0 ] .ParameterType == wantedType ) ; var validMethods = methods .Where ( m = > m.ReturnType == typeof ( void ) ) .Select ( m = > new { Params = m.GetParameters ( ) } ) .Where ( p = > p.Length == 1 & & p [ 0 ] .ParameterType == transition.eventType ) ; | Shorten this LINQ query via the help of an anonymous type ? |
C_sharp : I inherited some source code that I am just starting to dig though , and i found the previous owner has made some use of the using directive as an alias for a List < T > , but I 've never seen this specific approach before.Both of these elements are used quite heavily within the code and are also return types from several of the key methods within the code . I get what he was trying to accomplish with using a simple name rather than repeating List < type1 > and List < List < type1 > > over and over again . I 'm debating whether to create a real type to replace the using statements , but before i spend the time , I was wondering if there were any pros/cons to keeping the current implementation . <code> namespace MyNamespace { using pType1 = List < type1 > ; using pType2 = List < List < type1 > > ; // classes here } | Using Directive to declare a pseudo-type in C # |
C_sharp : I 've developed a simple app , which just have to upload files from a folder to Azure Blob Storage , I runs fine when I run in from VS , but in the published app I get this error once in a while : ved System.IO.__Error.WinIOError ( Int32 errorCode , String , maybeFullPath ) ved System.IO.FileStream.Init ( String path , FileMode mode , FileAccess access , Int32 rights , Boolean useRights , FileShare share , Int32 bufferSize , FileOptions options , SECURITY_ATTRIBUTES secAttrs , String msgPath , Boolean bFromProxy , Boolean useLongPath , Boolean checkHost ) ved System.IO.FileStream..ctor ( String path , FileMode mode , FileAccess access ) ved Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromFile ( String path , FileMode mode , AccessCondition accessCondition , BlobRequestOptions options , OperationsContext operationContext ) ved Program.MainWindow.Process ( object sender , NotifyCollectionChangedEventArgs e ) My code for uploading looks like this : It is the IOException in the catch that gets hit once in a while , any idea how to fix this ? If I go through the docs , I just get informed that the exception occour if a storage service error occoured . Any idea how to investigate the further ? https : //docs.microsoft.com/en-us/java/api/com.microsoft.azure.storage.blob._cloud_blob.uploadfromfile ? view=azure-java-legacy # com_microsoft_azure_storage_blob__cloud_blob_uploadFromFile_final_String_ <code> private void Process ( object sender , NotifyCollectionChangedEventArgs e ) { if ( paths.Count > 0 ) { var currentPath = paths.Dequeue ( ) ; CloudStorageAccount storageAccount = CloudStorageAccount.Parse ( UserSettings.Instance.getConnectionString ( ) ) ; CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient ( ) ; CloudBlobContainer blobContainer = blobClient.GetContainerReference ( UserSettings.Instance.getContainer ( ) ) ; CloudBlockBlob b = blobContainer.GetBlockBlobReference ( System.IO.Path.GetFileName ( currentPath ) ) ; try { b.UploadFromFile ( currentPath , FileMode.Open ) ; } catch ( StorageException s ) { throw new System.InvalidOperationException ( `` Could not connect to the specified storage account . Please check the configuration . `` ) ; } catch ( IOException exc ) { throw new System.InvalidOperationException ( exc.StackTrace ) ; } } } | IOException when uploading to Blob Storage in published app |
C_sharp : I am reading Beginning C # to refresh my memory on C # ( background in C++ ) .I came across this snippet in the book : The snippet above will not compile - because according to the book , the variable text is not initialized , ( only initialized in the loop - and the value last assigned to it is lost when the loop block is exited.I ca n't understand why the value assigned to an L value is lost just because the scope in which the R value was created has been exited - even though the L value is still in scope.Can anyone explain why the variable text loses the value assigned in the loop ? . <code> int i ; string text ; for ( i = 0 ; i < 10 ; i++ ) { text = `` Line `` + Convert.ToString ( i ) ; Console.WriteLine ( `` { 0 } '' , text ) ; } Console.WriteLine ( `` Last text output in loop : { 0 } '' , text ) ; | Variable scope in C # |
C_sharp : I am trying to use Selenium to enter SQL code into a Code Mirror textbox . I 'll use the site http : //www.gudusoft.com/sqlflow/ # / as an example for the purposes of this question.My Problem : I am unable to submit MSSQL SQL code into the code text box if the code contains a carriage return or line feed.As a work around , I am removing all of them before writing it to the textbox using a JavaScript function but the end result is very ugly word-wrapped SQL.I 've also tried using the SendKeys method on a Selenium webElement object to send the code into the textbox , but I am unsure which element to `` Find . '' Using SendKeys requires that the textbox be selected and when I try to invoke the Click '' and `` SendKeys '' method on that object , I often get a error that the element does not permit user interaction.If I could consistently find an element that I could interact with , like a TextArea , I would try to paste the contents of my clipboard into it rather than send a very large number of keystrokes to the textbox . For example , the following usually gives me the `` unable to interact with this object '' error but occasionally works , depending on the current content of the textbox , presumably.I 'm thinking that my best chance of setting the text is using the Execute script method to execute the setValue JavaScript method on the CodeMirror object as shown below . Again , this works if the SQL has no CR / LF characters but how do I change my code to allow for these characters ? I 've seen many many postings on this but my JavaScript knowledge may not be good enough to get me to the end result . I 'm hoping that someone can reconstruct a working example using the following code . Here 's the relatively short instructions.Create a C # project ( Console app , winForms , etc ) and add the following 3 Nuget packages : Create a class `` SeleniumHelperGudusoft '' and paste in the following code : Exercise the code in the above class to try pasting in two different SQLs , one without line feed characters and one with.I get the following error on the second call to the SetSqlText method on the line : How can I modify the example to get the second query to be entered into the CodeMirror textbox ? UpdateCode Mirror documentation is found here : https : //codemirror.net/doc/manual.htmlHere 's a full Call stack of the error : <code> Clipboard.SetText ( sql ) ; var txtbx = codeMirror.FindElement ( By.CssSelector ( `` textarea '' ) ) ; txtbx.Click ( ) ; txtbx.SendKeys ( OpenQA.Selenium.Keys.Control + `` v '' ) ; Selenium.Chrome.WebDriverSelenium.WebDriverSelenium.WebDriver.ChromeDriver using OpenQA.Selenium ; using OpenQA.Selenium.Chrome ; namespace SqlSmoke.Classes { public class SeleniumHelperGudusoft { private IWebDriver driver ; public SeleniumHelperGudusoft ( ) { var chromeDriverService = ChromeDriverService.CreateDefaultService ( ) ; chromeDriverService.HideCommandPromptWindow = false ; ChromeOptions options = new ChromeOptions ( ) ; options.AddAdditionalCapability ( `` useAutomationExtension '' , false ) ; this.driver = new ChromeDriver ( chromeDriverService , options ) ; } public void NavigateToMain ( ) { driver.Url = @ '' http : //www.gudusoft.com/sqlflow/ # / '' ; } public void SetLanguageToMsSql ( ) { string languageButtoncssSelector = `` # Root > div > div.Main > div > div.Route.Row.x-start.y-stretch > div.SQLFlowEditor > div.SQLFlowEditorOperations.Row.x-start.y-center > div.DbVendor > div > div > svg '' ; var languageButton = driver.FindElement ( By.CssSelector ( languageButtoncssSelector ) ) ; languageButton.Click ( ) ; string msSqlCssSelector = `` # Root > div > div.Main > div > div.Route.Row.x-start.y-stretch > div.SQLFlowEditor > div.SQLFlowEditorOperations.Row.x-start.y-center > div.DbVendor > ul > li : nth-child ( 10 ) '' ; var msSql = driver.FindElement ( By.CssSelector ( msSqlCssSelector ) ) ; msSql.Click ( ) ; } public void SetSqlText ( string sql ) { IJavaScriptExecutor js = ( IJavaScriptExecutor ) driver ; var codeMirror = driver.FindElement ( By.ClassName ( `` CodeMirror '' ) ) ; js.ExecuteScript ( `` arguments [ 0 ] .CodeMirror.setValue ( \ '' '' + sql + `` \ '' ) ; '' , codeMirror ) ; // < < < < -- -- Fails here with the error message shown below in my post } public void ClickVisualizeButton ( ) { string buttonCssSelector = `` # Visualize > div '' ; var button = driver.FindElement ( By.CssSelector ( buttonCssSelector ) ) ; button.Click ( ) ; } } } string sql ; var lineageHelper = new SeleniumHelperGudusoft ( ) ; lineageHelper.NavigateToMain ( ) ; lineageHelper.SetLanguageToMsSql ( ) ; sql = `` SELECT COL1 , nCOL2 FROM TABLE1 '' ; //all on one line workslineageHelper.SetSqlText ( sql ) ; lineageHelper.ClickVisualizeButton ( ) ; sql = `` SELECT COL1 , \r\nCOL2 FROM TABLE1 '' ; lineageHelper.SetSqlText ( sql ) ; // < < < -- -- - Fails here with the following error messagelineageHelper.ClickVisualizeButton ( ) ; js.ExecuteScript ( `` arguments [ 0 ] .CodeMirror.setValue ( \ '' '' + sql + `` \ '' ) ; '' , codeMirror ) ; Message `` javascript error : Invalid or unexpected token\n ( Session info : chrome=84.0.4147.105 ) '' string OpenQA.Selenium.WebDriverException HResult=0x80131500 Message=javascript error : Invalid or unexpected token ( Session info : chrome=84.0.4147.105 ) Source=WebDriver StackTrace : at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError ( Response errorResponse ) at OpenQA.Selenium.Remote.RemoteWebDriver.Execute ( String driverCommandToExecute , Dictionary ` 2 parameters ) at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand ( String script , String commandName , Object [ ] args ) at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript ( String script , Object [ ] args ) at MyNAME.Selenium.SeleniumHelperGudusoft.SetSqlText ( String sql ) in C : \Users\MYLANID\Desktop\SqlSmoke Code\MyNAME.Selenium\SeleniumHelper.cs : line 41 at MyNAME.Selenium.Form1.button3_Click ( Object sender , EventArgs e ) in C : \Users\MYLANID\Desktop\SqlSmoke Code\MyNAME.Selenium\Form1.cs : line 201 at System.Windows.Forms.Control.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnMouseUp ( MouseEventArgs mevent ) at System.Windows.Forms.Control.WmMouseUp ( Message & m , MouseButtons button , Int32 clicks ) at System.Windows.Forms.Control.WndProc ( Message & m ) at System.Windows.Forms.ButtonBase.WndProc ( Message & m ) at System.Windows.Forms.Button.WndProc ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.WndProc ( Message & m ) at System.Windows.Forms.NativeWindow.DebuggableCallback ( IntPtr hWnd , Int32 msg , IntPtr wparam , IntPtr lparam ) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW ( MSG & msg ) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop ( IntPtr dwComponentID , Int32 reason , Int32 pvLoopData ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.Run ( Form mainForm ) at MyNAME.Selenium.Program.Main ( ) in C : \Users\MYLANID\Desktop\SqlSmoke Code\MyNAME.Selenium\Program.cs : line 19 | Using C # and Selenium to enter multi lined SQL text into a Code Mirror textbox on a webpage |
C_sharp : I have a string which contains multiple items separated by commas : As you can see some elements contain Whitespaces , My object is to remove all the whitespaces , This is my code : And this is my result : it works well , But I ask if there is another more optimized way to get the same result ? <code> string RESULT = `` D_CA , P_AMOUNT , D_SH , D_CU , D_TO , D_GO , D_LE , D_NU , D_CO , D_MU , D_PMU , D_DP , P_COMMENT `` ; RESULT.Split ( ' , ' ) .ToList ( ) .ForEach ( p = > if ( p.Contains ( `` `` ) ) { RESULT = RESULT.Replace ( p , p.Trim ( ) ) ; } } ) ; `` D_CA , P_AMOUNT , D_SH , D_CU , D_TO , D_GO , D_LE , D_NU , D_CO , D_MU , D_PMU , D_DP , P_COMMENT '' | Remove whitespace in elements in string C # |
C_sharp : In an MFC program , you can determine whether the application shortcut had the Run value set to `` Minimized '' by checking the value of m_nCmdShow . Is there an equivalent way to do this in c # ? To clarify , I do n't want to set the state of a particular form . If you look at the properties for a shortcut , there is a `` Run '' option . You can set this value to Normal Window , Minimized , or Maximized . In C++ you can read what that startup value was set to by looking at m_nCmdShow . I need to do the same thing in C # .UpdateThis attempt : always reports Normal , no matter what the shortcut is set to . <code> [ STAThread ] static void Main ( string [ ] args ) { ProcessStartInfo processInfo = Process.GetCurrentProcess ( ) .StartInfo ; MessageBox.Show ( processInfo.WindowStyle.ToString ( ) ) ; ... } | Is there a c # equivalent of m_nCmdShow ? |
C_sharp : This is a question similar to this one here.Is there a built-in method that converts an array of byte to hex string ? More specifically , I 'm looking for a built in function for <code> /// < summary > /// Convert bytes in a array Bytes to string in hexadecimal format /// < /summary > /// < param name= '' Bytes '' > Bytes array < /param > /// < param name= '' Length '' > Total byte to convert < /param > /// < returns > < /returns > public static string ByteToHexString ( byte [ ] Bytes , int Length ) { Debug.Assert ( Length < = Bytes.GetLength ( 0 ) ) ; StringBuilder hexstr = new StringBuilder ( ) ; for ( int i = 0 ; i < Length ; i++ ) { hexstr.AppendFormat ( `` { 0,02 : X } '' , Bytes [ i ] ) ; } hexstr.Replace ( ' ' , ' 0 ' ) ; //padd empty space to zero return hexstr.ToString ( ) ; } | Builtin Function to Convert from Byte to Hex String |
C_sharp : In this scenario what would be the value of Result if myObject is null ? <code> var result = myObject ? .GetType ( ) ; | C # 6 null propagation what value is set when object is null |
C_sharp : I 'm running into a problem with the following pseudoquery : It runs but the generated SQL statement that LINQ sends to SQL Server is absurd . The actual implementation follows a similar setup as above with 7 or so more columns that each have a .Sum ( ) calculation . The generated SQL has somewhere around 10-11 nested SELECT statements with no INNER JOIN and , of course , takes forever to run.I tested out another implementation of the query : This version generates far more reasonable SQL with a single SUB-SELECT and an INNER JOIN statement ( it also runs damn near instantly ) . The thing I hate about this is that the first LINQ query is , IMHO , far more straight-forward and concise whereas the second seems rather redundant since I end up having to define all the columns I want from table1 twice.Why do these two similar queries perform so much differently on the server and why does query 2 end up being far more efficient even though it 's code is far less expressive ? Is there a way I can rewrite the first query to be as efficient as the second ? <code> var daily = from p in db.table1 group p by new { key1 , key2 } into g join d in db.table2 on new { p.key1 , p.key2 } equals { d.key1 , d.key2 } select new { col1 = g.Key.key1 col2 = g.Sum ( a = > a.column2 ) col3 = d.column3 } ; var daily = from p in ( from p in db.table1 group p by new { key1 , key2 } into g select new { col1 = g.Key.key1 , col2 = g.Sum ( a = > a.column2 ) } ) join d in db.table2 on new { p.key1 , p.key2 } equals new { d.key1 , d.key2 } select new { col1 = p.col1 , col2 = p.col2 , col3 = d.column3 } ; | Two similar LINQ queries , completely different generated SQL |
C_sharp : This question is an extension of Cristi Diaconescu 's about the illegality of field initializers accessing this in C # .This is illegal in C # : Ok , so the reasonable explanation to why this is illegal is given by , among others , Eric Lippert : In short , the ability to access the receiver before the constructor body runs is a feature of marginal benefits that makes it easier to write buggy programs . The C # language designers therefore disabled it entirely . If you need to use the receiver then put that logic in the constructor body.Also , the C # specifications are pretty straightforward ( up to a point ) : A variable initializer for an instance field can not reference the instance being created . Thus , it is a compile-time error to reference this in a variable initializer , as it is a compile-time error for a variable initializer to reference any instance member through a simple-name.So my question is : what does `` through a simple-name '' mean ? Is there some alternative mechanism where this would be legal ? I am certain that almost every word in the specification is there for a very specific reason , so what is the reason of limiting the illegality of this particular code to references through simple names ? EDIT : I 've not worded my question too well . I 'm not asking for the definition of `` simple-name '' , I am asking about the reason behind limiting the illegality to that particular scenario . If it is always illegal to reference any instance member in any which way , then why specify it so narrowly ? And if its not , then what mechanism would be legal ? <code> class C { int i = 5 ; double [ ] dd = new double [ i ] ; //Compiler error : A field initializer can not reference the non-static field , method , or property . } | Field initializer accessing 'this ' reloaded |
C_sharp : It is posible in C # to decide in constructor , which other override constructor use ? This below code does n't compile ! I do n't know which invocation use . <code> public IntRange ( int val , bool isMax ) : isMax ? this ( ) : this ( ) { if ( isMax ) { IntRange ( 0 , val ) ; } else { IntRange ( val , int.MaxValue ) ; } } | Can a constructor include logic that determines which other constructor overrides to call ? |
C_sharp : This surprised me - the same arithmetic gives different results depending on how its executed : ( Tested in Linqpad ) What 's going on ? Edit : I understand why floating point arithmetic is imprecise , but not why it would be inconsistent.The venerable C reliably confirms that 0.1 + 0.2 == 0.3 holds for single-precision floats , but not double-precision floating points . <code> > 0.1f+0.2f==0.3fFalse > var z = 0.3f ; > 0.1f+0.2f==zTrue > 0.1f+0.2f== ( dynamic ) 0.3fTrue | Floating point inconsistency between expression and assigned object |
C_sharp : I have an iterative C # loop which fills out a checkboard pattern of up to 5 columns.The values are paired , it 's always a Headline and multiple Values for each column , and it 's combining the values to a non-repetitative combination.Starting with the simplest solution I could imagine , and after looking at it , I thought there must be a better approach to this problem by doing this recursively.Below is an example of what I 've tried so far : The containers consist of a list of strings ( the values ) and a key ( the headline ) .It 's a shortend version OfferVariant counts up to 5 in the real example.I cant change the inital checkboard structure since its given by a existing database.Below is an illustration of the data input and output for 2 containers consisting of : Container 1 : Key : PieValues : Raspberry StrawberryContainer 2 : Key : DrinkValues : Cola , CoffeeThe generated output would consist of 4 rows containingedit due the fact its easyly missunderstood as its illustrated hereThe Result will be a Row in a Database consisting of 4 columnsEtOfferVariant is a ORM Poco containing those columns <code> List < EtOfferVariant > variants = new List < EtOfferVariant > ( ) ; _containers [ 0 ] .Variant.ForEach ( first = > { if ( _containers.Count > 1 ) { _containers [ 1 ] .Variant.ForEach ( second = > { if ( _containers.Count > 2 ) { _containers [ 2 ] .Variant.ForEach ( third = > { EtOfferVariant va = new EtOfferVariant ( ) ; va.OfferVariant1Type = _containers [ 0 ] .VariantKey ; va.OfferVariant1 = first ; va.OfferVariant2Type = _containers [ 1 ] .VariantKey ; va.OfferVariant2 = second ; va.OfferVariant3Type = third ; va.OfferVariant3 = _containers [ 3 ] .VariantKey ; variants.Add ( va ) ; } ) ; } else { EtOfferVariant va = new EtOfferVariant ( ) ; va.OfferVariant1Type = _containers [ 0 ] .VariantKey ; va.OfferVariant1 = first ; va.OfferVariant2Type = second ; va.OfferVariant2 = _containers [ 1 ] .VariantKey ; variants.Add ( va ) ; } } ) ; } else { EtOfferVariant va = new EtOfferVariant ( ) ; va.OfferVariant1Type = _containers [ 0 ] .VariantKey ; va.OfferVariant1 = first ; variants.Add ( va ) ; } } ) ; Column 1 | Column 2 | Column 3 | Column 4Pie | Raspberry | Drink | Cola Pie | Raspberry | Drink | CoffeePie | Strawberry| Drink | Cola Pie | Strawberry| Drink | Coffee | How to go from iterative approach to recursive approach |
C_sharp : Does the ? ? operator in C # use shortcircuiting when evaluating ? When myObject is non-null , the result of ExpressionWithSideEffects ( ) is not used , but will ExpressionWithSideEffects ( ) be skipped completely ? <code> var result = myObject ? ? ExpressionWithSideEffects ( ) ; | Does the `` ? ? `` operator use shortcircuiting ? |
C_sharp : This question is about static stack analysis of custom C # IL code and how to design the opcodes to satisfy the compiler.I have code that modifies existing C # methods by appending my own code to it . To avoid that the original method returns before my code is executed , it replaces all RET opcodes with a BR endlabel and adds that label to the end of the original code . I then add more code there and finally a RET.This all works fine in general but fails on certain methods . Here is a simple example : which is represented by this IL code : After my program modified it , the code looks like this : and I get an compile error : Could not execute post-long-event action . Exception : System.TypeInitializationException : An exception was thrown by the type initializer for FooBar -- - > System.InvalidProgramException : Invalid IL code in ( wrapper dynamic-method ) Foo : SomeMethod ( int ) : IL_0000 : ldnullIs there any simple way to replace RETs in a generic way and keep the static analyzer happy ? <code> public static string SomeMethod ( int val ) { switch ( val ) { case 0 : return `` string1 '' .convert ( ) ; case 1 : return `` string2 '' .convert ( ) ; case 2 : return `` string3 '' .convert ( ) ; // ... } return `` '' ; } .method public hidebysig static string SomeMethod ( int32 val ) cil managed { .maxstack 1 .locals val ( [ 0 ] int32 num ) L_0000 : ldarg.0 L_0001 : stloc.0 L_0002 : ldloc.0 L_0003 : switch ( L_002e , L_004f , L_0044 , ... ) L_002c : br.s L_0091 L_002e : ldstr `` string1 '' L_0033 : call string Foo : :convert ( string ) L_0038 : ret L_0039 : ldstr `` string2 '' L_003e : call string Foo : :convert ( string ) L_0043 : ret L_0044 : ldstr `` string3 '' L_0049 : call string Foo : :convert ( string ) L_004e : ret ... L_0091 : ldstr `` '' L_0096 : ret } .method public hidebysig static string SomeMethod ( int32 val ) cil managed { .maxstack 1 .locals val ( [ 0 ] int32 num ) L_0000 : ldarg.0 L_0001 : stloc.0 L_0002 : ldloc.0 L_0003 : switch ( L_002e , L_004f , L_0044 , ... ) L_002c : br.s L_0091 L_002e : ldstr `` string1 '' L_0033 : call string Foo : :convert ( string ) L_0038 : br L_009b // was ret L_0039 : ldstr `` string2 '' L_003e : call string Foo : :convert ( string ) L_0043 : br L_009b // was ret L_0044 : ldstr `` string3 '' L_0049 : call string Foo : :convert ( string ) L_004e : br L_009b // was ret ... L_0091 : ldstr `` '' L_0096 : br L_009b // was ret L_009b : my code here ... L_0200 : ret } | C # IL code modification - keep stack intact |
C_sharp : I have the following method : Question is : i dont want the user to wait for csv dump , which might take a while.If i use a thread for csvdump , will it complete ? before or after the return of output ? After csvdump is finished , i d like to notify another class to process the csv file . someMethod doesnt need to wait for csvdump to finish ? <code> public List < string > someMethod ( ) { // populate list of strings // dump them to csv file //return to output } | C # Threading in a method |
C_sharp : i want to create a dictionary like : Why ca n't I ? <code> Dictionary < string , < Dictionary < string , string > > > | Why ca n't I create a dictionary < string , dictionary < string , string > > ? |
C_sharp : In my function I receive objects implementing IMediaPanel interface : During the initialization I need to specify properties ' names , for which I 'm using C # 6.0 nameof keyword : This works fine , but with this expression : Visual Studio shows me the following error : The property 'MyNamespace.IMediaPanel.IsNextEntityExists ' has no getter.Searching `` nameof limitations '' did n't give me any answer about this issue , moreover official remarks does n't contain restriction about property getters : ... The following are worth mentioning that produce errors : predefined types ( for example , int or void ) , nullable types ( Point ? ) , array types ( Customer [ , ] ) , pointer types ( Buffer* ) , qualified alias ( A : :B ) , and unbound generic types ( Dictionary < , > ) , preprocessing symbols ( DEBUG ) , and labels ( loop : ) . ... Can anyone explain why there is this restriction and if there is any reference about that ? What reason can force nameof keyword to use property 's instance getter while it should ( as I guess ) just use general type information through Reflection ? ( at least in this particular case , when I ca n't directly point to an instance 's property due to unknown type , I just know that this instance implements the interface ) UpdateTo explain why @ Gusdor 's suggestion from comments is not working , I need to clarify how I call InitConnections function ( in simplified form ) : So if I use nameof ( panelControl.IsNextEntityExists ) inside Init function , it will produce an error because FrameworkElement does n't contains custom client 's IsNextEntityExists property.And if I use the same expression inside InitConnections function , I get an error about the getter - the same as with nameof ( IMediaPanel.IsNextEntityExists ) . Anyway , I found the answer , this 'getter ' error is a ReSharper 's bug ( see my own answer ) . <code> public interface IMediaPanel { bool IsListsAreaVisible { get ; } bool IsNextEntityExists { set ; } } private void InitConnections ( IMediaPanel panelControl ) { // Initialization logic } nameof ( IMediaPanel.IsListsAreaVisible ) nameof ( IMediaPanel.IsNextEntityExists ) public void Init ( FrameworkElement panelControl ) { // ... Other logic ... this.InitConnections ( ( IMediaPanel ) panelControl ) ; } | Using `` nameof '' keyword with set-only property |
C_sharp : I 'm working a project to replace a Resource Management system ( QuickTime Resource Manager on Mac and Windows ) that has been deprecated and I have been using the current model that Qt uses where data is retrieved from the resource file using a string key.For example , I may have an image in my resource file , `` HungryBear.png '' stored in my resource file . Qt , and my proposed system , would get it in a way depicted by the psuedocode : It is clear at that point what that image is , and where it can be found.In our current system , we use numbers . The problems with numbers is that one has to hunt down the resource file ( there can be many ) to find out what image ( or resource ) it is.An example of this : The first method is what I have seen in current systems that access resource file data . I 've been told that C # and Java uses it , I know that they do for string key-value pairs , etc.However , a peer of mine has expressed concern about changing the current system of using these number IDs for the string ids that I 'm proposing . There seem to be many benefits and they fix many of the issues we 've had with the current system . I want to have supporting documentation that the proposed system is better and desirable , so my question is this : Do you know of any research or discussion that demonstrates that using a string identifier ( hierarchical ) in code is better than using an arbitrary number ? NOTESI plan on using a zip file ( possibly uncompressed ) to contain the data files.We have a application-plugin environment . The application and each plugin can have its own resource files . Plugins may be able to access resource data in the application 's resource file.Here are some requirements that have been considered and I believe met : Software Developers shall be able to uniquely identify resources.Software Developers shall be able to name resources with meaningful names.Resources shall be associated with the parts of the application that need them.Localizers shall be able to easily identify resource files that have changed.Localizers shall be able to use their own tools to modify resource files.Customers shall be alerted in the event that the functionality they are using relies on deprecated calls . <code> image = GetImageResource ( `` BearPlugin/Images/HungryBear.png '' ) ; oldActiveResourceFile = GetActiveResourceFile ( ) ; // think of a stack of resource filesSetActiveResourceFile ( `` BearPlugin '' ) ; image = GetImageResource ( 1 ) ; // Perhaps other resources are retrieved and other functions called// Possibly introduce problems by calling functions that change `` Active Resource File '' SetActiveResourceFile ( oldActiveResourceFile ) ; | Why are string identifiers used to access resource data ? |
C_sharp : Consider the following piece of code : If you execute this , the variable en will get the value of TestEnum.BA . Now I have learned from this that enum flags should be unique , or you get these kind of unexpected things , but I do fail to understand what is happening here.The even weirder part is that when I add the [ Flags ] attribute to the TestEnum , it solves the problem and returns TestEnum.AA instead of TestEnum.BA , but for the original enum ( which is much larger , around ~200 members ) for which I have discovered this problem this does not make a difference.My understanding is that enums are a value type , so when you define your own flags it will store the value in memory as 0x01 in the case of for TestEnum.AA , and when you cast it from object to TestEnum it will do the lookup for that flag value and find TestEnum.BA.This is also confirmed by running the following line : Which will output : BASo my question is : what exactly is happening here ? And more importantly why does adding the Flags attribute make a difference ? <code> namespace ConsoleApplication1 { class Program { public static void Main ( string [ ] args ) { var en = ( TestEnum ) Enum.Parse ( typeof ( TestEnum ) , `` AA '' ) ; Console.WriteLine ( en.ToString ( ) ) ; Console.ReadKey ( ) ; } } public enum TestEnum { AA = 0x01 , AB = 0x02 , AC = 0x03 , BA = 0x01 , BB = 0x02 , BC = 0x03 } } var en = ( TestEnum ) ( object ) TestEnum.AA ; Console.WriteLine ( en.ToString ( ) ) ; | Enum.Parse returning unexpected members |
C_sharp : I am maintaining an ASP.NET MVC project . In the project the original developer has an absolute ton of interfaces . For example : IOrderService , IPaymentService , IEmailService , IResourceService . The thing I am confused about is each of these is only implemented by a single class . In other words : My understanding of interfaces has always been that they are used to create an architecture in which components can be interchanged easily . Something like : Furthermore , I do n't understand how these are being created and used . Here is the OrderService : These objects do n't seem be ever be created directly as in OrderService orderService = new OrderService ( ) it is always using the interface . I do n't understand why the interfaces are being used instead of the class implementing the interface , or how that even works . Is there something major that I am missing about interfaces that my google skills are n't uncovering ? <code> OrderService : IOrderServicePaymentService : IPaymentService Square : IShapeCircle : IShape public class OrderService : IOrderService { private readonly ICommunicationService _communicationService ; private readonly ILogger _logger ; private readonly IRepository < Product > _productRepository ; public OrderService ( ICommunicationService communicationService , ILogger logger , IRepository < Product > productRepository ) { _communicationService = communicationService ; _logger = logger ; _productRepository = productRepository ; } } | Am I confused about interfaces ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.