text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I 'm writing xml with XmlWriter . My code has lots of sections like this : The problem is that the ThirdPartyLibrary.Serialise method is unreliable . It can happen ( depending on the variable results ) that it does n't close all the tags it opens . As a consequence , my WriteEndElement line is perverted , consumed closing the library 's hanging tags , rather than writing < /payload > .Thus I 'd like to make a checked call to WriteEndElement that checks the element name , and throws an exception unless the cursor is at the expected element . You can think of this like XmlReader.ReadStartElement ( name ) which throws unless the cursor is at the expected place in the document.How can I achieve this ? Edit : A second use case for this extension method would be to make my own code more readable and reliable . <code> xml.WriteStartElement ( `` payload '' ) ; ThirdPartyLibrary.Serialise ( results , xml ) ; xml.WriteEndElement ( ) ; // < /payload > xml.WriteEndElement ( `` payload '' ) ;
How to check name of element with WriteEndElement
C_sharp : I am working with entity-framework . I have a partial class called Company that is generated by EF . The partial class looks like : The type 'BaseModels.Company ' already contains a definition for 'CompanyName ' '' What I want to do is create a derived class from Company that has an extra property.But I want to decorate the base type property CompanyName with a custom attribute.I went to the following location : How do I add an attribute to the field of the base class from child class ? Which does answer my question . The problem is if I marked the CompanyName property in the base class as `` virtual '' , then EF could regenerate the code which would override my stuff.I tried to define a partial class , but VS 2013 complained when I tried to add : by stating that the property name already existed.How would I get around this hurdle ? <code> public partial class Company { public string CompanyId { get ; set ; } public string CompanyName { get ; set ; } } public class MyCompany : Company { public string UploadName { get ; set ; } } public partial class Company { [ Renderer ( `` html '' ) ] public virtual string CompanyName { get ; set ; } }
Adding attributes to a derived type
C_sharp : We utilise a third party web service that returns XML which looks something like ( cut down for brevity ) : For a specific product code I need to obtain the realm name i.e . the inner text of : < a name= '' realm '' format= '' text '' > -u @ surfuk2 < /a > Because every element name is either < block > or < a > it 's a bit troublesome to parse with linq to xml or query expressions . Is the following the most effective/efficient/expressive way to get at the realm name for a specific product , e.g . 1235 : <code> < Response > < block name= '' availability '' > < block name= '' cqual '' > < a name= '' result-code '' format= '' text '' > L < /a > < /block > < block name= '' exchange '' > < a name= '' code '' format= '' text '' > MRDEN < /a > < /block > < block name= '' mqual '' > < a name= '' rate-adaptive '' format= '' text '' > G < /a > < /block > < /block > < block name= '' products '' > < block > < a name= '' product-id '' format= '' counting '' > 1235 < /a > < block name= '' realms '' > < block > < a name= '' realm '' format= '' text '' > -u @ surfuk1 < /a > < /block > < /block > < /block > < block > < a name= '' product-id '' format= '' counting '' > 1236 < /a > < block name= '' realms '' > < block > < a name= '' realm '' format= '' text '' > -u @ surfuk2 < /a > < /block > < /block > < /block > < block > < a name= '' product-id '' format= '' counting '' > 1237 < /a > < block name= '' realms '' > < block > < a name= '' realm '' format= '' text '' > -u @ surfuk3 < /a > < /block > < /block > < /block > < /block > < status no= '' 0 '' / > < /Response > List < XElement > products = response .Element ( `` Response '' ) .Elements ( `` block '' ) .Where ( x = > x.Attribute ( `` name '' ) .Value == `` products '' ) .Elements ( `` block '' ) .ToList ( ) ; //// I broke down the query to aid readability//string realm = products.Elements ( `` a '' ) .Where ( x = > x.Attribute ( `` name '' ) .Value == `` product-id '' ) .Where ( y = > y.Value == `` 1235 '' ) // hardcoded for example use .Ancestors ( ) .First ( ) .Elements ( `` block '' ) .Where ( z = > z.Attribute ( `` name '' ) .Value == `` realms '' ) .Elements ( `` block '' ) .Elements ( `` a '' ) .First ( ) .Value ;
Is this the most efficient way to express this XDocument query ?
C_sharp : When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword ? Since the method is declared abstract in its parent class it does n't have any implementation in the parent class , so why is the keyword override necessary here ? <code> public abstract class Person { public Person ( ) { } protected virtual void Greet ( ) { // code } protected abstract void SayHello ( ) ; } public class Employee : Person { protected override void SayHello ( ) // Why is override keyword necessary here ? { throw new NotImplementedException ( ) ; } protected override void Greet ( ) { base.Greet ( ) ; } }
Why is it required to have override keyword in front of abstract methods when we implement them in a child class ?
C_sharp : I 'm trying to project from my Order model to my OrderDTO model . Order has an enum . The problem is that projection does n't work if I try to to get the Description attribute from the Enum . Here it 's my code : OrderStatus.cs : Order.cs : OrderDTO.cs : With this following configuration in my AutoMapper.cs : Projection works , but I get an OrderDTO object like this : I do n't want Status property to be `` Sent '' , I want it to be as its associated Description attribute , in this case , `` Delivered '' .I have tried two solutions and none of them have worked : Using ResolveUsing AutoMapper function as explained here , but , as it 's stated here : ResolveUsing is not supported for projections , see the wiki on LINQ projections for supported operations.Using a static method to return the Description attribute in String by Reflection.But this gives me the following error : LINQ to Entities does not recognize the method 'System.String GetEnumDescription ( System.String ) ' method , and this method can not be translated into a store expression.Then , how can I achieve this ? <code> public enum OrderStatus { [ Description ( `` Paid '' ) ] Paid , [ Description ( `` Processing '' ) ] InProcess , [ Description ( `` Delivered '' ) ] Sent } public class Order { public int Id { get ; set ; } public List < OrderLine > OrderLines { get ; set ; } public OrderStatus Status { get ; set ; } } public class OrderDTO { public int Id { get ; set ; } public List < OrderLineDTO > OrderLines { get ; set ; } public string Status { get ; set ; } } cfg.CreateMap < Order , OrderDTO > ( ) .ForMember ( dest = > dest.Status , opt = > opt.MapFrom ( src = > src.Status.ToString ( ) ) ) ; - Id : 1 - OrderLines : List < OrderLines > - Sent //I want `` Delivered '' ! cfg.CreateMap < Order , OrderDTO > ( ) .ForMember ( dest = > dest.Status , opt = > opt.MapFrom ( src = > EnumHelper < OrderStatus > .GetEnumDescription ( src.Status.ToString ( ) ) ) ) ;
c # - Enum description to string with AutoMapper
C_sharp : Why is the behavior of Default Interface Methods changed in C # 8 ? In the past the following code ( When the Default interface methods was demo not released ) : has the following output : Console output : I am a default method in the interface ! I am an overridden default method ! But with the C # 8 last version the code above is producing the following output : Console output : I am an overridden default method ! I am an overridden default method ! Anyone can explain to me why this behavior is changed ? Note : <code> interface IDefaultInterfaceMethod { // By default , this method will be virtual , and the virtual keyword can be here used ! virtual void DefaultMethod ( ) { Console.WriteLine ( `` I am a default method in the interface ! `` ) ; } } interface IOverrideDefaultInterfaceMethod : IDefaultInterfaceMethod { void IDefaultInterfaceMethod.DefaultMethod ( ) { Console.WriteLine ( `` I am an overridden default method ! `` ) ; } } class AnyClass : IDefaultInterfaceMethod , IOverrideDefaultInterfaceMethod { } class Program { static void Main ( ) { IDefaultInterfaceMethod anyClass = new AnyClass ( ) ; anyClass.DefaultMethod ( ) ; IOverrideDefaultInterfaceMethod anyClassOverridden = new AnyClass ( ) ; anyClassOverridden.DefaultMethod ( ) ; } } IDefaultInterfaceMethod anyClass = new AnyClass ( ) ; anyClass.DefaultMethod ( ) ; ( ( IDefaultInterfaceMethod ) anyClass ) .DefaultMethod ( ) ; // STILL the same problem ! ? ?
How can I call the default method instead of the concrete implementation
C_sharp : Not a duplicate of this.I want to make a string have a max length . It should never pass this length . Lets say a 20 char length . If the provided string is > 20 , take the first 20 string and discard the rest . The answers on that question shows how to cap a string with a function but I want to do it directly without a function . I want the string length check to happen each time the string is written to.Below is what I do n't want to do : I was able to accomplish this with a property : Then I can easily use it whout calling a function to cap it : The problem with this is that every string I want to cap must have multiple variables defined for them . In this case , the _userName and the userName ( property ) variables.Any clever way of doing this without creating multiple variables for each string and at the-same time , not having to call a function each time I want to modify the string ? <code> string myString = `` my long string '' ; myString = capString ( myString , 20 ) ; // < -- Do n't want to call a function each timestring capString ( string strToCap , int strLen ) { ... } const int Max_Length = 20 ; private string _userName ; public string userName { get { return _userName ; } set { _userName = string.IsNullOrEmpty ( value ) ? `` '' : value.Substring ( 0 , Max_Length ) ; } } userName = `` Programmer '' ;
Cap string to a certain length directly without a function
C_sharp : I 'm trying to use the ticker data for the Coinigy websocket api , to get the stream of real time trades and prices of crypto assets.I 've tried the following demo with no success , and I get a response of : '' Socket is not authenticated '' <code> internal class MyListener : BasicListener { public void onConnected ( Socket socket ) { Console.WriteLine ( `` connected got called '' ) ; } public void onDisconnected ( Socket socket ) { Console.WriteLine ( `` disconnected got called '' ) ; } public void onConnectError ( Socket socket , ErrorEventArgs e ) { Console.WriteLine ( `` on connect error got called '' ) ; } public void onAuthentication ( Socket socket , bool status ) { Console.WriteLine ( status ? `` Socket is authenticated '' : `` Socket is not authenticated '' ) ; } public void onSetAuthToken ( string token , Socket socket ) { token = `` { 'apiKey ' : 'KEYXXXXXX ' , 'apiSecret ' : 'SECRETXXXX ' } '' ; // < -- -MY key and secret socket.setAuthToken ( token ) ; Console.WriteLine ( `` on set auth token got called '' ) ; } } internal class Program { public static void Main ( string [ ] args ) { var socket=new Socket ( `` wss : //sc-02.coinigy.com/socketcluster/ '' ) ; socket.setListerner ( new MyListener ( ) ) ; socket.setReconnectStrategy ( new ReconnectStrategy ( ) .setMaxAttempts ( 30 ) ) ; socket.connect ( ) ; //Other code calling the websocket ... .//Other code calling the websocket ... .//Other code calling the websocket ... . Console.ReadKey ( ) ; } }
Ca n't authenticate using Socketcluster V2 for Coinigy Exchange websocket ticker api
C_sharp : I have two objects : andAnd I would like to create a switch case where depending on the BugReportFilter choose my output will be a specific BugReportStaus.So I created a method CheckFilterThe problem is that in the case of a BugReportFilter.Open option I should return BugReportStatus.OpenAssigned AND BugReportStatus.OpenUnassigned , is there a way to concat this two options in a single return ? <code> public enum BugReportStatus { OpenUnassigned = 0 , OpenAssigned = 1 , ClosedAsResolved = 2 , ClosedAsRejected = 3 } public enum BugReportFilter { Open = 1 , ... Closed = 4 , } private BugReportStatus Checkfilter ( BugReportFilter filter ) { switch ( filter ) { case BugReportFilter.Open : return BugReportStatus.OpenAssigned ; case BugReportFilter.Closed : return BugReportStatus.ClosedAsResolved ; } } ;
Switch with enum and multiple return
C_sharp : The purpose of the interface IDisposable is to release unmanaged resources in an orderly fashion . It goes hand in hand with the using keyword that defines a scope after the end of which the resource in question is disposed of.Because this meachnism is so neat , I 've been repeatedly tempted to have classes implement IDisposable to be able to abuse this mechanism in ways it 's not intended for . For example , one could implement classes to handle nested contexts like this : Usage in calling code might look like this : ( Please note that this is just an example and not to the topic of this question . ) The fact that Dispose ( ) is called upon leaving the scope of the using statement can also be exploited to implement all sorts of things that depend on scope , e.g . timers . This could also be handled by using a try ... finally construct , but in that case the programmer would have to manually call some method ( e.g . Context.Pop ) , which the using construct could do for thon.This usage of IDisposable does not coincide with its intended purpose as stated in the documentation , yet the temptation persists . Are there concrete reasons to illustrate that this is a bad idea and dispell my fantasies forever , for example complications with garbage collection , exception handling , etc . Or should I go ahead and indulge myself by abusing this language concept in this way ? <code> class Context : IDisposable { // Put a new context onto the stack public static void PushContext ( ) { ... } // Remove the topmost context from the stack private static void PopContext ( ) { ... } // Retrieve the topmost context public static Context CurrentContext { get { ... } } // Disposing of a context pops it from the stack public void Dispose ( ) { PopContext ( ) ; } } using ( Context.PushContext ( ) ) { DoContextualStuff ( Context.CurrentContext ) ; } // < -- the context is popped upon leaving the block
Is abusing IDisposable to benefit from `` using '' statements considered harmful ?
C_sharp : A vs. BLately I have been confused why many would say that definitely A does a much faster processing compared to B . But , the thing is they would just say because somebody said so or because it is just the way it is . I suppose I can hear a much better explaination from here . How does the compiler treats these strings ? Thank you ! <code> A = string.Concat ( `` abc '' , '' def '' ) B = `` abc '' + `` def ''
addition of strings in c # , how the compiler does it ?
C_sharp : I have the following code : This code compiles , and it surprises my . The explicit convert should only accept a byte , not a double . But the double is accepted somehow . When I place a breakpoint inside the convert , I see that value is already a byte with value 2 . By casting from double to byte should be explicit.If I decompile my EXE with ILSpy , I see the next code : My question is : Where is that extra cast to byte coming from ? Why is that extra cast place there ? Where did my cast to Num < byte > go to ? EDITThe struct Num < T > is the entire struct , so no more hidden extra methods or operators.EDITThe IL , as requested : <code> public struct Num < T > { private readonly T _Value ; public Num ( T value ) { _Value = value ; } static public explicit operator Num < T > ( T value ) { return new Num < T > ( value ) ; } } ... double d = 2.5 ; Num < byte > b = ( Num < byte > ) d ; double d = 2.5 ; Program.Num < byte > b = ( byte ) d ; IL_0000 : nopIL_0001 : ldc.r8 2.5 // Load the double 2.5.IL_000a : stloc.0IL_000b : ldloc.0IL_000c : conv.u1 // Once again the explicit cast to byte.IL_000d : call valuetype GeneriCalculator.Program/Num ` 1 < ! 0 > valuetype GeneriCalculator.Program/Num ` 1 < uint8 > : :op_Explicit ( ! 0 ) IL_0012 : stloc.1IL_0013 : ret
Compiler replaces explicit cast to my own type with explicit cast to .NET type ?
C_sharp : Steps to reproduce : Open Visual Studio 2017 with latest update . Create a UWP project targetin 10240 ( this is not mandatory , it 's broken in all builds ) Install System.Memory from nuget packages ( click include prerelease ) Copy paste this code in to MainPage.csCopy paste this to MainPage.xamlSwitch from Debug to Release x64 and make sure `` Compile with .Net Native tool chain '' .Click Play.Receive this error : -- -- -- Build started : Project : App12 , Configuration : Release x64 -- -- -- App12 c : \Users\myuser\documents\visual studio 2017\Projects\App12\App12\bin\x64\Release\App12.exe Processing application code C : \Users\myuser.nuget\packages\microsoft.net.native.compiler\1.7.3\tools\Microsoft.NetNative.targets ( 697,5 ) : error : Internal compiler error : Object reference not set to an instance of an object . ========== Build : 0 succeeded , 1 failed , 0 up-to-date , 0 skipped ========== ========== Deploy : 0 succeeded , 0 failed , 0 skipped ==========What I 'm doing wrong ? This works in Debug and release without .NET Native . Thanks . <code> private void MainPage_Loaded ( object sender , RoutedEventArgs e ) { void Recursive ( ReadOnlySpan < char > param ) { if ( param.Length == 0 ) return ; tx1.Text += Environment.NewLine ; tx1.Text += new string ( param.ToArray ( ) ) ; Recursive ( param.Slice ( 1 ) ) ; } ReadOnlySpan < char > mySpan = `` Why things are always broken in Visual Studio '' .AsSpan ( ) ; Recursive ( mySpan ) ; } < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' > < TextBlock x : Name= '' tx1 '' HorizontalAlignment= '' Left '' FontSize= '' 48 '' TextWrapping= '' Wrap '' Text= '' TextBlock '' VerticalAlignment= '' Top '' / > < /Grid >
Span < T > and friends not working in .NET Native UWP app
C_sharp : I have just updated to the latest version of Xamarin studio , however when I try to build my solution using XBuild , through our continuous integration server it now generates the IPA file in a data time folder , ( within the usual bin\iphone\Ad-hoc folders ) e.g . : however I do not understand why it now does this - in the previous version it gave me a file as follows : Does anyone know how to get it back to setting the version number again , rather than putting it in a date time folder which makes it fairly impractical to copy the IPA to a release folder once I have finished building it . <code> Finisher3 2016-06-09 11-57-45\Finisher3.ipa Finisher3-1.68.1.1.ipa
Xamarin cycle 7 IOS IPA output now in a datetime folder
C_sharp : Lately , I 've been working on enabling more of the Visual Studio code analysis rules in my projects . However , I keep bumping into rule CA2227 : `` Collection properties should be read only '' .Say I have a model class like this : And I have a strongly-mapped view page : With ASP.NET MVC , I can write an action in my controller that will automatically bind this input to a class of type Foo : The problem with this approach , is that my List < string > auto property violates rule CA2227 . If I was n't doing model binding , I could make the property read only and populate the collection elsewhere . However , that approach wo n't work with the default model binder . For now I 've just been adding a suppression message when it occurs in a view model . Is there a way I can bind a collection of items in a model without violating CA2227 ? Or is adding a suppression message my best option here ? <code> public class Foo { public string Name { get ; set ; } public List < string > Values { get ; set ; } } @ using ( Html.BeginForm ( ) ) { @ Html.LabelFor ( m = > m.Name ) @ Html.EditorFor ( m = > m.Name ) for ( int i = 0 ; i < Model.Values.Count ; i++ ) { < br / > @ Html.LabelFor ( m = > Model.Values [ i ] ) ; @ Html.EditorFor ( m = > Model.Values [ i ] ) ; } < button type= '' submit '' > Submit < /button > } [ HttpPost ] public ActionResult ProcessForm ( Foo model ) { return View ( model ) ; }
CA2227 and ASP.NET Model Binding
C_sharp : In answering a question about double [ , ] , I added a screenshot of LINQPad 's output for that data structure : However , I got to wondering what a double [ , , ] looks like , and LINQPad wo n't visualize it for me . Additionally , I do n't understand the format of the data which goes into it : Can anyone visualize this for me ? <code> int [ , , ] foo = new int [ , , ] { { { 2 , 3 } , { 3 , 4 } } , { { 3 , 4 } , { 1 , 5 } } } ;
What does double [ , , ] represent ?
C_sharp : How come the conditional operator ( ? : ) does n't work when used with two types that inherit from a single base type ? The example I have is : Where the long form works fine : Both return types , RedirectToRouteResult and RedirectResult , inherit from ActionResult . <code> ActionResult foo = ( someCondition ) ? RedirectToAction ( `` Foo '' , '' Bar '' ) : Redirect ( someUrl ) ; ActionResult foo ; if ( someCondition ) { foo = RedirectToAction ( `` Foo '' , '' Bar '' ) ; } else { foo = Redirect ( someUrl ) ; }
Conditional operator does n't work with two types that inherit the same base type
C_sharp : I have been learning about locking on threads and I have not found an explanation for why creating a typical System.Object , locking it and carrying out whatever actions are required during the lock provides the thread safety ? ExampleAt first I thought that it was just being used as a place holder in examples and meant to be swapped out with the Type you are dealing with . But I find examples such as Dennis Phillips points out , does n't appear to be anything different than actually using an instance of Object.So taking an example of needing to update a private dictionary , what does locking an instance of System.Object do to provide thread safety as opposed to actually locking the dictionary ( I know locking the dictionary in this case could case synchronization issues ) ? What if the dictionary was public ? <code> object obj = new object ( ) lock ( obj ) { //code here } //what if this was public ? private Dictionary < string , string > someDict = new Dictionary < string , string > ( ) ; var obj = new Object ( ) ; lock ( obj ) { //do something with the dictionary }
Why magic does an locking an instance of System.Object allow differently than locking a specific instance type ?
C_sharp : Could you please explain the meaning of underscore ( _ ) in the WaitCallBack constructor ? <code> ThreadPool.QueueUserWorkItem ( new WaitCallback ( ( _ ) = > { MyMethod ( param1 , Param2 ) ; } ) , null ) ;
Meaning of the underscore in WaitCallback
C_sharp : I 'm working on an ASP.NET MVC 4.5 application . I need to populate a list in a dropdown . I t works fine , anyhow , when I click the field there is allways a server request.I 'd like to store the values after the initial load on the client side to speed up the application.I 'm using a ViewModel to populate the list in my Razor View.Do you know how to achieve an initial load of the this ? Here is my DataSource Controller : The Razor View : Many thanks and kind regards ! <code> public JsonResult GetBusinessLineList ( string id = null , string query = null ) { return Json ( Db.BusinessLine.AsQueryable ( ) .Where ( x = > x.Label.Contains ( query ) ) .Take ( 10 ) .Select ( x = > new { id = x.BusinessLineId , text = x.Label } ) .ToList ( ) , JsonRequestBehavior.AllowGet ) ; } < div class= '' form-group '' > @ Html.LabelFor ( model = > model.BusinessLineIdList , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.Select2AjaxFor ( model = > model.BusinessLineIdList , @ Url.Action ( `` GetBusinessLineList '' , `` DataSource '' ) , new { @ class = `` form-control '' ) ) < /div > < /div >
using c # linq to populate/load a list one time to enhance performance
C_sharp : I am using Entity Framework Core 2.2 with NetTopologySuite 1.15.1 and SQL Server 2016 . Having a column of type IPoint works great to the point I want to create an index on it.I have this tableAnd EF core handles it well while generating a migration thus producing the following code : However , as soon as I try to apply the migration to database , SqlException is thrown with the following message SqlException : Column 'Coordinates ' in table 'data.Locations ' is of a type that is invalid for use as a key column in an index or statistics.SQL Server does support indexes on columns of type geography.I believe the reason might be that EF Core is trying to create a regular index rather than spatial one.Am I doing something wrong or it 's just not supported ? Is there a way to tell EF Core that it should create spatial index ? <code> public class Location { public int Id { get ; set ; } public IPoint Coordinates { get ; set ; } public static void Register ( ModelBuilder modelBuilder ) { modelBuilder.Entity < Location > ( entity = > entity.HasIndex ( x = > new { x.Coordinates } ) ) ; } } migrationBuilder.CreateIndex ( name : `` IX_Locations_Coordinates '' , schema : `` data '' , table : `` Locations '' , column : `` Coordinates '' ) ;
Is there a way to declare a Spatial Index with EntityFrameworkCore 2.2 ?
C_sharp : Assuming I have an instance of an object that I know belongs to a subclass of a certain subtype passed to me through a reference of a supertype in C # , I 'm used to seeing typecasting done this Java-like way ( Assuming `` reference '' is of the supertype ) : But recently I 've come across examples of what appears to be the same thing done this way : Are those two completely equivalent ? Is there any difference ? <code> if ( reference is subtype ) { subtype t = ( subtype ) reference ; } if ( reference is subtype ) { subtype t = reference as subtype ; }
C # : Any difference whatsoever between `` ( subtype ) data '' and `` data as subtype '' typecasting ?
C_sharp : I have 2 collections of 2 different types but have almost the same set of fields.in one function , I need to iterate through one of the collections depending on one condition.I want to write only one code block that will cover both cases.Example : I have the following code : Now : I want to simplify this code to use the same logic only once ( as they are identical ) , something like the following ( P.S : I know the following code is not correct , I am just explaining what I want to do ) : The definition of Type1 & Type2 is similar to the following code ( Actually they are Entity objects ) : Update 1 : I have included some sample code I am using inside foreach block ( I am accessing a public properties of the 2 types ) .Update 2 : I have included sample Type1 & Type2 definitions , as you can see I have 2 common Public Properties in both classes which I want to update in foreach block.Update 3 : I am sorry for the confusion , Type1 & Type2 are derived from EntityObject ( They are both part of my entity model , and the Type1Collection & Type2Collection are actually EntityCollection of these 2 entities . <code> if ( condition1 ) { foreach ( var type1var in Type1Collection ) { // Do some code here type1var.Notes = `` note '' ; type1var.Price = 1 ; } } else { foreach ( var type2var in Type2Collection ) { // the same code logic is used here type2var.Notes = `` note '' ; type2var.Price = 1 ; } } var typecollection = Condition1 ? Type1Collection : Type2Collection ; foreach ( var typevar in TypeCollection ) { // the same code logic is used here typevar.Notes = `` note '' ; typevar.Price = 1 ; } public class Type1 : EntityObject { public int Type1ID { get ; set ; } public int Type1MasterID { get ; set ; } public String Notes { get ; set ; } public decimal Price { get ; set ; } } public class Type2 : EntityObject { public int Type2ID { get ; set ; } public int Type2MasterID { get ; set ; } public String Notes { get ; set ; } public decimal Price { get ; set ; } }
How to use the same foreach code for 2 collections ?
C_sharp : I have a OData V4 over Asp.net WebApi ( OWIN ) .Everything works great , except when I try to query a 4-level $ expand.My query looks like : I do n't get any error , but the last expand is n't projected in my response.More info : I 've set the MaxExpandDepth to 10.All my Entities are EntitySets.I 'm using the ODataConventionModelBuilder.I 've opened an SQL-profiler and could see that the query ( and the result ) is correct . It 's some filter that occurs after the query is executed.I 've searched the web and did n't find anything suitable.I 've tried different entity 4 level $ expands and they did n't work as well.Edit : I 've overridden the OnActionExecuted : The serialized value contains entity4.I still have no idea what component removes entity4 in the pipe.Edit # 2 : I 've create an adapter over DefaultODataSerializerProvider and over all the other ODataEdmTypeSerializer 's . I see that during the process the $ expand for entity4 exists and when the ODataResourceSerializer.CreateNavigationLink method is called on that navigationProperty ( entity4 ) then it returns null.I 've jumped into the source code and I could see that the SerializerContext.Items does n't include the entity4 inside it 's items and the SerializerContext.NavigationSource is null.To be specific with versions , I 'm using System.Web.OData , Version=6.1.0.10907 . <code> http : //domain/entity1 ( $ expand=entity2 ( $ expand=entity3 ( $ expand=entity4 ) ) ) public override void OnActionExecuted ( HttpActionExecutedContext actionExecutedContext ) { base.OnActionExecuted ( actionExecutedContext ) ; var objectContent = actionExecutedContext.Response.Content as ObjectContent ; var val = objectContent.Value ; var t = Type.GetType ( `` System.Web.OData.Query.Expressions.SelectExpandWrapperConverter , System.Web.OData '' ) ; var jc = Activator.CreateInstance ( t ) as JsonConverter ; var jss = new JsonSerializerSettings ( ) ; jss.Converters.Add ( jc ) ; var ser = JsonConvert.SerializeObject ( val , jss ) ; }
Asp.net WebApi OData V4 problems with nested $ expands
C_sharp : I wa n't to maintain a list of several BlockingCollectionsAnd the check in subthreads if any of the 'queues ' still have items pending : Is the usage of a List < T > in this case thread-safe if the number of items in the list do n't change after the initialisation ( the content of the blockinglists inside the collection will change offcourse ... ) ? Or should i opt for an array of BlockingCollection or the following construction : <code> List < BlockingCollection < ExtDocument > > a = new List < BlockingCollection < ExtDocument > > ( ) ; if ( a.Where ( x = > x.IsAddingCompleted ) .Count > 0 ) BlockingCollection < BlockingCollection < workitem > > a = new BlockingCollection < BlockingCollection < workitem > > ( ) ;
Is a List < BlockingCollection < T > > Thread safe ?
C_sharp : Java 8 has Supplier < T > for 0 parameter functions , Function < T , R > for 1 parameter functions , and BiFunction < T , U , R > for 2 parameter functions.What type represents a function or lambda expression that takes 3 parameters like inIn C # , Func < T , TResult > is overloaded for up to 16 parameters so we could writeDoes the Java standard libraries provide anything similar or do you have to write your own `` TriFunction '' interface to handle functions with 3 arguments ? <code> SomeType lambda = ( int x , double y , String z ) - > x ; // what is SomeType ? Func < int , double , string , int > lambda = ( int x , double y , string z ) = > x ;
In Java , what type represents a function or lambda expression that takes 3 parameters ?
C_sharp : I suspect the short answer to this question is `` no '' but I 'm interested in the ability to detect the use of the dynamic keyword at runtime in C # 4.0 , specifically as a generic type parameter for a method.To give some background , we have a RestClient class in a library shared among a number of our projects which takes a type parameter to specify a type that should be used when de-serializing the response , e.g . : Unfortunately ( due to reasons I wo n't get into here for the sake of brevity ) using dynamic as the type parameter in order to return a dynamic type does n't work properly - we 've had to add a second signature to the class to return a dynamic response type : However , using dynamic as the type parameter to the first method causes a very strange error that masks the actual problem and makes debugging the whole thing a headache . In order to help out the other programmers using the API , I 'd like to try and detect the use of dynamic in the first method so that either it wo n't compile at all or when used an exception is thrown saying something along the lines of `` use this other method if you want a dynamic response type '' .Basically either : orAre either of these things possible ? We 're using VS2010 and .Net 4.0 but I 'd be interested in a .Net 4.5 solution for future reference if it 's possible using newer language features . <code> public IRestResponse < TResource > Get < TResource > ( Uri uri , IDictionary < string , string > headers ) where TResource : new ( ) { var request = this.GetRequest ( uri , headers ) ; return request.GetResponse < TResource > ( ) ; } public IRestResponse < dynamic > Get ( Uri uri , IDictionary < string , string > headers ) { var request = this.GetRequest ( uri , headers ) ; return request.GetResponse ( ) ; } public IRestResponse < TResource > Get < TResource > ( Uri uri , IDictionary < string , string > headers ) where TResource is not dynamic public IRestResponse < TResource > Get < TResource > ( Uri uri , IDictionary < string , string > headers ) where TResource : new ( ) { if ( typeof ( TResource ) .isDynamic ( ) ) { throw new Exception ( ) ; } var request = this.GetRequest ( uri , headers ) ; return request.GetResponse < TResource > ( ) ; }
Detecting use of `` dynamic '' keyword as a type parameter at runtime
C_sharp : I find this issue very strange , possibly a XAML/Visual Studio bug . I am hoping someone else finds it less strange and has an explanation for why what I 'm doing is wrong , and/or a better work-around than just declaring the resources in a different order.I have this simple XAML : When I attempt to compile the project , I get the following error : 1 > ... MainWindow.xaml.cs ( 25,13,25,32 ) : error CS0103 : The name 'InitializeComponent ' does not exist in the current contextI understand the error 's meaning , but not why it happens . The XAML seems fine , there are no errors compiling it , but for some reason the auto-generated .g.i.cs file where InitializeComponent ( ) would normally be put is not being created or used ( i.e . even if the file is there from a previous successful compilation , it 's still not compiled into the assembly ) .If I simply reverse the order of the resources , it works fine : Additional information : A is any class in my project . For the purposes of this test , it was declared as class A { } , i.e . an empty class , but I first ran into this problem putting converter instances into the resources.If I use a built-in type instead of A , e.g . < system : String x : Key= '' a1 '' > Some string < /system : String > , the error does not happen.If I place an object of a built-in type as a resource in between the user-defined type A object and my array resource object , it also works fine ! In other words , it seems as though having one or more user-defined typed objects as the first resource elements , followed immediately by an array object , causes compilation to fail . Other combinations seem to work just fine.Can someone please explain either why this is expected behavior ( and what should I be doing to avoid it besides just rearranging my resources ) , or confirm that I 'm not entirely crazy in thinking this is a bug in the XAML build process ? Edit : Given the likelihood of this being an actual bug , I went ahead and opened a Connect bug report here : https : //connect.microsoft.com/VisualStudio/feedback/details/1441123/xaml-fails-to-compile-without-error-if-user-defined-object-is-first-resource-and-followed-immediately-by-x-array-resourceSee also related/similar Stack Overflow question : The name 'InitializeComponent ' does not exist in the current context : strange behaviour <code> < Window x : Class= '' TestSOAskArrayXaml.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : system= '' clr-namespace : System ; assembly=mscorlib '' xmlns : local= '' clr-namespace : TestSOAskArrayXaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < Window.Resources > < local : A x : Key= '' a1 '' / > < x : Array x : Key= '' listBoxItems '' Type= '' { x : Type system : Double } '' > < system : Double > 0.25 < /system : Double > < /x : Array > < /Window.Resources > < Grid/ > < /Window > < Window.Resources > < x : Array x : Key= '' listBoxItems '' Type= '' { x : Type system : Double } '' > < system : Double > 0.25 < /system : Double > < /x : Array > < local : A x : Key= '' a1 '' / > < /Window.Resources >
XAML fails to compile , but without any error message , if user-defined object is first resource and followed immediately by x : Array resource
C_sharp : In C # , there is not in-built notion of commutativity in the language . That is if I define a simple Vector class for instance : I will still need to define the symmetric operator + ( double d , Vector v ) or any expression of the form 2.1 * v will give a compilation error or fail at runtime in a dynamic scenario.My question is two-fold : First , are there any languages out there where you can define commutative operators without the need to define both possible operand combinations ? In other words , are there any languages aware of the concept of commutativity itself ? And second , was it ever considered in C # and scrapped as it really is just syntactic sugar to avoid a few additional keystrokes that does n't really add all that much richness to the language ( and would most probably need an additional reserved word ) ? <code> public struct Vector { private readonly double x , y , z ; ... public static Vector operator + ( Vector v , double d ) { ... } }
Commutativity in operators
C_sharp : I have read a few articles about how Span can be used to replace certain string operations . As such I have updated some code in my code base to use this new feature , however , to be able to use it in-place I then have to call .ToString ( ) . Does the .ToString ( ) effectively negate the benefit I get from using Span < T > rather than Substring as this would have to allocate memory ? In which case how do I reap the benefits if Span in this way , or is it just not possible ? <code> //return geofenceNamesString.Substring ( 0 , 50 ) ; Previous codereturn geofenceNamesString.AsSpan ( ) .Slice ( 0 , 50 ) .ToString ( ) ;
Using Span < T > as a replacement for Substring
C_sharp : I downloaded the Stable release of Reactive Extensions v1.0 SP1 from this site http : //msdn.microsoft.com/en-us/data/gg577610 , and I am using it in a .Net Framework 3.5 environment ( Visual Studio 2008 ) I tried using Reactive Extensions in a project , and noticed it was very slow to start up . Going to LinqPad , I entered the following `` C # Expression '' : I also referenced System.Reactive.dll and imported the System.Reactive.Linq namespace . When I run it , it takes 12 Seconds to compile & run.I opened Process Monitor and monitored LinqPad . I found that it is sending an HTTP request to 124.155.222.226 OR 124.155.22.59 . ( FYI LinqPad itself also phones home to 157.55.161.150 when you open it ) . With WireShark , I noticed it is sending an HTTP GET request to Does anyone know why it is phoning home like this when code compiles with Reactive.Extensions ? Furthermore , is there any way to turn it off , because a 12 second delay to phone home when devoloping the application ( AND running in production ) is particularlly inconvenient.NOTE : It phones home like this when you COMPILE the code ( or the JIT compiles it when debugging ) . It is not actually the run-time behavior that appears to be doing this . <code> ( new int [ 0 ] ) .ToObservable ( ) http : //crl.microsoft.com/pki/crl/products/MicCodSigPCA_08-31-2010.crl
Why does Reactive Extensions send a HTTP GET to microsoft ON COMPILATION ?
C_sharp : I have a .NET Core ( UWP solution ) application which has 3 different projects ( let 's call them A , B and C ) .A and B are Windows Runtime Components , and C is a simple Class Library.Projects A and B have a reference to the project C.I would like to access a class of the project C , whose the instance would be shared between projects A and B.I thought to a singleton pattern ( of course ) , using the Lazy method of .NET 4Problem is that the instance is not the same each time A and B projects access the instance . The Lazy method creates a new instance of the class because it seems not to be previously created . I wonder if I can share a singleton between different projects of a solution . I 've read that a project is associated to a process , and each process has its own memory space which can not be shared . Is there a solution to my issue ? EDIT : Here 's my implementation of my HubService class : Also , is it possible to share a singleton across different assemblies using tools like Castle Windsor , Ninject , Autofac or Unity ? <code> private static readonly Lazy < HubService > Lazy = new Lazy < HubService > ( ( ) = > new HubService ( ) , LazyThreadSafetyMode.ExecutionAndPublication ) ; private HubService ( ) { _asyncQueue = new AsyncQueue < Guid > ( ) ; } public static HubService Instance = > Lazy.Value ;
How to communicate across projects inside one .NET solution ?
C_sharp : I have set a filter to work upon a specific folder and all pages inside it . I need to access database using a claim . The problem is that I can not seem to register my filter with DI on startup services cause it does not find the database connectionthe filter.the error is InvalidOperationException : No database provider has been configured for this DbContext . A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider . If AddDbContext is used , then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.here is the whole startup classmy context <code> services.AddMvc ( ) .AddRazorPagesOptions ( options = > { options.AllowAreas = true ; options.Conventions.AuthorizeAreaFolder ( `` Administration '' , `` /Account '' ) ; options.Conventions.AuthorizeAreaFolder ( `` Production '' , `` /Account '' ) ; options.Conventions.AuthorizeAreaFolder ( `` Robotics '' , `` /Account '' ) ; options.Conventions.AddAreaFolderApplicationModelConvention ( `` Production '' , `` /FrontEnd '' , model = > model.Filters.Add ( new LockdownFilter ( new ProducaoRegistoService ( new ProductionContext ( ) ) , new UrlHelperFactory ( ) , new HttpContextAccessor ( ) ) ) ) ; } ) public class LockdownFilter : IAsyncPageFilter { private readonly IProducaoRegistoService _producaoRegistoService ; private readonly IUrlHelperFactory _urlHelperFactory ; private readonly IHttpContextAccessor _httpContextAccessor ; public LockdownFilter ( IProducaoRegistoService producaoRegistoService , IUrlHelperFactory urlHelperFactory , IHttpContextAccessor httpContextAccessor ) { _producaoRegistoService = producaoRegistoService ; _urlHelperFactory = urlHelperFactory ; _httpContextAccessor = httpContextAccessor ; } public async Task OnPageHandlerExecutionAsync ( PageHandlerExecutingContext context , PageHandlerExecutionDelegate next ) { int registoId ; if ( ! int.TryParse ( _httpContextAccessor.HttpContext.User.GetRegistoId ( ) , out registoId ) ) { // TODO } var registo = _producaoRegistoService.GetById ( registoId ) ; await next.Invoke ( ) ; } public async Task OnPageHandlerSelectionAsync ( PageHandlerSelectedContext context ) { await Task.CompletedTask ; } } public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServices ( IServiceCollection services ) { services.AddAuthentication ( options = > { } ) .AddCookie ( `` ProductionUserAuth '' , options = > { options.ExpireTimeSpan = TimeSpan.FromDays ( 1 ) ; options.LoginPath = new PathString ( `` /Production/FrontEnd/Login '' ) ; options.LogoutPath = new PathString ( `` /Production/FrontEnd/Logout '' ) ; options.AccessDeniedPath = new PathString ( `` /Production/FrontEnd/AccessDenied '' ) ; options.SlidingExpiration = true ; options.Cookie.Name = `` NoPaper.ProductionUser '' ; options.Cookie.Expiration = TimeSpan.FromDays ( 1 ) ; } ) .AddCookie ( `` ProductionAdminAuth '' , options = > { options.ExpireTimeSpan = TimeSpan.FromDays ( 1 ) ; options.LoginPath = new PathString ( `` /Production/BackOffice/Login '' ) ; options.LogoutPath = new PathString ( `` /Production/BackOffice/Logout '' ) ; options.AccessDeniedPath = new PathString ( `` /Production/BackOffice/AccessDenied '' ) ; options.SlidingExpiration = true ; options.Cookie.Name = `` NoPaper.ProductionAdmin '' ; options.Cookie.Expiration = TimeSpan.FromDays ( 1 ) ; } ) .AddCookie ( `` AdministrationAuth '' , options = > { options.ExpireTimeSpan = TimeSpan.FromDays ( 1 ) ; options.LoginPath = new PathString ( `` /Administration/Index '' ) ; options.LogoutPath = new PathString ( `` /Administration/Logout '' ) ; options.AccessDeniedPath = new PathString ( `` /Administration/AccessDenied '' ) ; options.SlidingExpiration = true ; options.Cookie.Name = `` NoPaper.Administration '' ; options.Cookie.Expiration = TimeSpan.FromDays ( 1 ) ; } ) ; services.AddAuthorization ( ) ; services.AddMemoryCache ( ) ; services.AddAutoMapper ( typeof ( Startup ) ) ; services.AddMvc ( ) .AddRazorPagesOptions ( options = > { options.AllowAreas = true ; options.Conventions.AuthorizeAreaFolder ( `` Administration '' , `` /Account '' ) ; options.Conventions.AuthorizeAreaFolder ( `` Production '' , `` /Account '' ) ; options.Conventions.AddAreaFolderApplicationModelConvention ( `` Production '' , `` /FrontEnd '' , model = > model.Filters.Add ( new LockdownFilter ( new ProducaoRegistoService ( new ProductionContext ( new DbContextOptions < ProductionContext > ( ) ) ) , new UrlHelperFactory ( ) , new HttpContextAccessor ( ) ) ) ) ; } ) .AddNToastNotifyToastr ( new ToastrOptions ( ) { ProgressBar = true , TimeOut = 3000 , PositionClass = ToastPositions.TopFullWidth , PreventDuplicates = true , TapToDismiss = true } ) .SetCompatibilityVersion ( CompatibilityVersion.Version_2_2 ) ; services.AddRouting ( options = > { options.LowercaseUrls = true ; options.LowercaseQueryStrings = true ; } ) ; services.AddDbContext < DatabaseContext > ( options = > { options.UseSqlServer ( Configuration.GetConnectionString ( `` DefaultConnection '' ) , sqlServerOptionsAction : sqlOptions = > { sqlOptions.EnableRetryOnFailure ( maxRetryCount : 2 , maxRetryDelay : TimeSpan.FromSeconds ( 1 ) , errorNumbersToAdd : null ) ; sqlOptions.MigrationsHistoryTable ( `` hEFMigrations '' , `` Admin '' ) ; } ) ; } ) ; services.AddDbContext < ProductionContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` DefaultConnection '' ) , c = > c.MigrationsHistoryTable ( `` hEFMigrations '' , `` Admin '' ) ) ) ; services.AddHttpContextAccessor ( ) ; services.AddSingleton < IFileProvider > ( new PhysicalFileProvider ( Path.Combine ( Directory.GetCurrentDirectory ( ) , `` wwwroot/files '' ) ) ) ; services.AddTransient < IAuthorizationHandler , HasArranqueActivoHandler > ( ) ; services.AddTransient < IAuthorizationHandler , HasArranqueInactivoHandler > ( ) ; services.AddTransient < IAuthorizationHandler , IsParagemNotOnGoingHandler > ( ) ; services.AddTransient < IAuthorizationHandler , IsParagemOnGoingHandler > ( ) ; services.AddTransient < Services.Interfaces.IUserService , Services.UserService > ( ) ; # region AreaProduction services.AddTransient < Production.Interfaces.IComponenteService , Production.ComponenteService > ( ) ; services.AddTransient < Production.Interfaces.IReferenciaService , Production.ReferenciaService > ( ) ; services.AddTransient < Production.Interfaces.IProducaoRegistoService , Production.ProducaoRegistoService > ( ) ; services.AddTransient < Production.Interfaces.IParagemService , Production.ParagemService > ( ) ; services.AddTransient < Production.Interfaces.ICelulaService , Production.CelulaService > ( ) ; services.AddTransient < Production.Interfaces.IUapService , Production.UapService > ( ) ; services.AddTransient < Production.Interfaces.ICelulaTipoService , CelulaTipoService > ( ) ; services.AddTransient < Production.Interfaces.IMatrizService , MatrizService > ( ) ; services.AddTransient < Production.Interfaces.IOperadorService , Production.OperadorService > ( ) ; services.AddTransient < Production.Interfaces.IEtiquetaService , Production.EtiquetaService > ( ) ; services.AddTransient < Production.Interfaces.IPokayokeService , Production.PokayokeService > ( ) ; services.AddTransient < Production.Interfaces.IGeometriaService , Production.GeometriaService > ( ) ; services.AddTransient < Production.Interfaces.IEmpregadoService , Production.EmpregadoService > ( ) ; services.AddTransient < Production.Interfaces.IPecaService , Production.PecaService > ( ) ; services.AddTransient < Production.Interfaces.IDefeitoService , Production.DefeitoService > ( ) ; services.AddTransient < Production.Interfaces.ITurnoService , Production.TurnoService > ( ) ; # endregion } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; } else { app.UseExceptionHandler ( errorApp = > { errorApp.Run ( async context = > { var exceptionHandlerPathFeature = context.Features.Get < IExceptionHandlerPathFeature > ( ) ; // Use exceptionHandlerPathFeature to process the exception ( for example , // logging ) , but do NOT expose sensitive error information directly to // the client . if ( exceptionHandlerPathFeature.Path.Contains ( `` /Administration/ '' ) || exceptionHandlerPathFeature.Path.Contains ( `` /administration/ '' ) ) { context.Response.Redirect ( `` /Administration/Error '' ) ; } if ( exceptionHandlerPathFeature.Path.Contains ( `` /Production/ '' ) || exceptionHandlerPathFeature.Path.Contains ( `` /production/ '' ) ) { context.Response.Redirect ( `` /Production/Error '' ) ; } } ) ; } ) ; } app.UseNToastNotify ( ) ; app.UseAuthentication ( ) ; app.UseStaticFiles ( ) ; app.UseMvc ( routes = > { routes.MapRoute ( name : `` areas '' , template : `` { area : exists } / { controller=Home } / { action=Index } / { id ? } '' ) ; routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ; } } public class ProductionContext : DbContext { //static LoggerFactory object public static readonly ILoggerFactory loggerFactory = new LoggerFactory ( new [ ] { new ConsoleLoggerProvider ( ( _ , __ ) = > true , true ) } ) ; public ProductionContext ( ) { } public ProductionContext ( DbContextOptions < ProductionContext > options ) : base ( options ) { } protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { optionsBuilder.UseLoggerFactory ( loggerFactory ) //tie-up DbContext with LoggerFactory object .EnableSensitiveDataLogging ( ) ; } ... }
ASP .NET Core Inject Service in custom page filter
C_sharp : There a section in my code where I need to invert a matrix . That can only reasonably be done on a square matrix , in this case a 3x3 square matrix . The tool I 'm using to invert the matrix kept saying that my array was n't a proper square.So I did a little test : First one comes up as `` 3 '' . Second one comes up as `` 3 '' . Third one comes up as an IndexOutOfRangeException . Am I just overlooking something extremely obvious or ... is this a little weird ? ( Note : This is code from C # using .Net 2.0 ) <code> double [ , ] x = new double [ 3 , 3 ] ; MessageBox.Show ( x.GetLength ( 0 ) .ToString ( ) ) ; MessageBox.Show ( x.GetLength ( 1 ) .ToString ( ) ) ; MessageBox.Show ( x.GetLength ( 2 ) .ToString ( ) ) ;
Baffling Index-Out-Of-Bounds
C_sharp : Here is a very basic example of method overloading , two methods with the same name but with different signatures : Now let 's say I define two generic interfaces , sharing the exact same name but with different number of type parameters , such as : Can I say this represents `` generic interface overloading '' ? Or does the `` overloading '' term only applies to methods in such a context ? Still it looks kind of very similar to method overloading , in the sense that we are keeping an exact same name but varying the parameters.If I ca n't say `` generic interface overload/overloading '' what can I say about these two different interfaces sharing the same name ? Thanks and sorry if this is a dumb question , but googling arround `` generic interface overload '' or `` generic interface overloading '' does n't give me much but results concerning interface methods overloading , which is not what I 'm interested in . <code> int MyMethod ( int a ) int MyMethod ( int a , string b ) IMyInterface < T > IMyInterface < T1 , T2 >
Generic interface overloading . Valid terminology ?
C_sharp : I am building an application that uses quite a few commands , and they are cluttering up my viewmodel . MVVM is new to me , so sorry if this question is a bit stupid . Is there a way to reduce the clutter ? For example here you can see the a part of the clutter.. <code> private void InitializeCommands ( ) { LogoutCommand = new RelayCommand ( Logout ) ; OpenCommand = new RelayCommand ( SetImage ) ; SaveCommand = new RelayCommand ( SaveImage , SaveImageCanExecute ) ; UploadToFlickrCommand = new RelayCommand ( UploadToFlickr ) ; CropCommand = new RelayCommand ( SetCropMouseEvents ) ; RemoveRedEyeCommand = new RelayCommand ( SetRemoveRedEyeMouseEvents ) ; TextInputCropCommand = new RelayCommand ( CropFromText ) ; ReloadImageCommand = new RelayCommand ( ReloadImage ) ; FlipYCommand = new RelayCommand ( FlipY ) ; Rotate90RCommand = new RelayCommand ( Rotate90R ) ; FlipXCommand = new RelayCommand ( FlipX ) ; ToGrayscaleCommand = new RelayCommand ( ToGrayscale ) ; ToSepiaCommand = new RelayCommand ( ToSepia ) ; WindowClosingCommand = new RelayCommand ( WindowClosing ) ; EffectsViewCommand = new RelayCommand ( ( ) = > CurrentToolView = new EffectsView ( ) ) ; AddTextCommand = new RelayCommand ( ( ) = > CurrentToolView = new AddTextView ( ) ) ; ResizeCommand = new RelayCommand ( ( ) = > CurrentToolView = new ResizeView ( ) ) ; CropViewCommand = new RelayCommand ( ( ) = > CurrentToolView = new CropView ( ) ) ; RedEyeCommand = new RelayCommand ( ( ) = > CurrentToolView = new RedEyeView ( ) ) ; RotateViewCommand = new RelayCommand ( ( ) = > CurrentToolView = new RotateView ( ) ) ; ExitCommand = new RelayCommand ( ( ) = > Application.Current.Shutdown ( ) ) ; FullscreenCommand = new RelayCommand ( ( ) = > { var fs = new FullscreenView { FullscreenImage = CurrentImage.LoadedImage } ; fs.Show ( ) ; } ) ; HandleDropCommand = new RelayCommand < DragEventArgs > ( e = > OnFileDrop ( this , e ) ) ; Messenger.Default.Register < User > ( this , `` UserLogin '' , SetUser ) ; Messenger.Default.Register < FlickrAccount > ( this , `` AddedAccount '' , AddAccount ) ; Messenger.Default.Register < string > ( this , `` INeedAUser '' , SendUser ) ; Messenger.Default.Register < string > ( this , `` INeedAImage '' , SendImage ) ; }
How can I avoid command clutter in the ViewModel ?
C_sharp : Here 's an example of what I 'm talking about ... Me.MyValue gives a warning in VB.NET and ( the equivalent code gives ) an error in C # . Is there a particular reason for this ? I find it more intuitive/natural to access the shared function using 'Me.MyValue ' - but I avoid it to keep my warnings at 0.Did someone else just decide 'Nah , it makes more sense to do it the other way ' or is there some technical reason I do n't understand ? EDIT : Thanks everyone . I was thinking of it wrong , more like a 'sub class ' in OOP . Even if something is declared in the base class , you access it through the instance you have . But that relationship is not the same with shared or static . <code> Public Class Sample1 Public Shared Function MyValue ( ) As Integer Return 0 End Function Public Sub Code ( ) Dim ThisIsBad = Me.MyValue Dim ThisIsGood = Sample1.MyValue End SubEnd Class
Why Should n't You Access a Shared/static Member Through An Instance Variable ?
C_sharp : I have a Text file which contains a repeated string called `` map '' for more than 800 now I would like to replace them with map to map0 , map1 , map2 , ... ..map800.I tried this way but it didnt work for me : Can you please let me know how I can do this ? <code> void Main ( ) { string text = File.ReadAllText ( @ '' T : \File1.txt '' ) ; for ( int i = 0 ; i < 2000 ; i++ ) { text = text.Replace ( `` map '' , `` map '' +i ) ; } File.WriteAllText ( @ '' T : \File1.txt '' , text ) ; }
Issue on Replacing Text with Index Value in C #
C_sharp : In a C # 8 project , I am using nullable reference types and am getting an unexpected ( or at least , unexpected to me ) CS8629 warning , I 've decided to use GetValueOrDefault ( ) as a workaround , but I 'd like to know how to prove to the compiler that x.DataInt ca n't be null if singleContent is checked.Note that the type of x.DataInt is int ? . <code> bool singleContent = x.DataInt ! = null ; bool multiContent = x.DataNvarchar ! = null ; if ( singleContent & & multiContent ) { throw new ArgumentException ( `` Expected data to either associate a single content node or `` + `` multiple content nodes , but both are associated . `` ) ; } if ( singleContent ) { var copy = x.DataInt.Value ; // CS8629 here newPropertyData.DataNvarchar = $ '' umb : // { type.UdiType } / { Nodes [ copy ] .UniqueId.ToString ( `` N '' ) } '' ; }
Nullable reference types unexpected CS8629 Nullable value type may be null with temporary variables
C_sharp : Does there exist a method in C # to get the relative path given two absolute path inputs ? That is I would have two inputs ( with the first folder as the base ) such asandThen the output would be <code> c : \temp1\adam\ c : \temp1\jamie\ ..\jamie\
Does there exist a method in C # to get the relative path given two absolute path inputs ?
C_sharp : I am trying to run several tasks at the same time and I came across an issue I ca n't seem to be able to understand nor solve.I used to have a function like this : That I wanted to call in a for loop using Task.Run ( ) . However I could not find a way to send parameters to this Action < int , bool > and everyone recommends using lambdas in similar cases : I thought using local variables in lambdas would `` capture '' their values but it looks like it does not ; it will always take the value of index as if the value would be captured at the end of the for loop . The index variable is evaluated at 400 in the lambda at each iteration so of course I get an IndexOutOfRangeException 400 times ( items.Count is actually MAX ) .I am really not sure about what is happening here ( though I am really curious about it ) and I do n't know how to do what I am trying to achieve either . Any hints are welcome ! <code> private void async DoThings ( int index , bool b ) { await SomeAsynchronousTasks ( ) ; var item = items [ index ] ; item.DoSomeProcessing ( ) ; if ( b ) AVolatileList [ index ] = item ; //volatile or not , it does not work else AnotherVolatileList [ index ] = item ; } for ( int index = 0 ; index < MAX ; index++ ) { //let 's say that MAX equals 400 bool b = CheckSomething ( ) ; Task.Run ( async ( ) = > { await SomeAsynchronousTasks ( ) ; var item = items [ index ] ; //here , index is always evaluated at 400 item.DoSomeProcessing ( ) ; if ( b ) AVolatileList [ index ] = item ; //volatile or not , it does not work else AnotherVolatileList [ index ] = item ; } }
Parameters in asynchronous lambdas
C_sharp : I 've recently started creating a WPF application , and am just hoping that someone can confirm to me that I 'm building my overall system architecture properly , or correct me if I 'm heading off in the wrong direction somewhere . Especially since I 'm trying to do MVVM , there are a lot of layers involved , and I 'm not sure I 'm doing things properly.Here 's a simplified description of the system : Data is stored in an SQL Server database , which is accessed through Linq to SQL . Let 's say that the database contains two tables , USERS and USER_GROUPS . Each table has an auto-generated Linq to SQL class , DB_USER and DB_USER_GROUP.Now in the application , I want to display a ListBox with each ListBoxItem containing various UI elements for displaying/modifying the users ' info , which is done using a DataTemplate.I have a view model class for the window , which uses a Linq to SQL query ( joining the two tables ) to populate an ObservableCollection < User > named UserList , which the ListBox in the window has bound as its ItemsSource . User is a class implementing INotifyPropertyChanged that handles all the formatting/getting/setting of database data into what 's needed by the WPF controls . The section of code handling this is something like : So the User class is constructed with private properties for a DB_USER , a DB_USER_GROUP , and the database DataContext class . All of a User 's public properties basically wrap the relevant columns , with their get methods returning the values for WPF to use , and set changing the column ( s ) and then calling SubmitChanges ( ) on the private DataContext property to update the database.This is all working fine , but it feels a little unwieldy , so I 'm just wondering if I 've missed something that would make it cleaner . Specifically , storing a DataContext inside each element of UserList seems odd , but I was n't sure of a better method to be able to update the database whenever data was changed in the UI.Any feedback is appreciated , and please let me know if anything 's unclear , I 'm not sure how well I 've explained it . <code> DBDataContext db = new DBDataContext ( ) ; var allUsers = from user in db.USERs .Where ( u = > u.ENABLED == true ) from group in db.USER_GROUPs .Where ( g = > g.GROUPID == u.GROUPID ) .DefaultIfEmpty ( ) select new { user , group } ; foreach ( var user in allUsers ) { User u = new User ( db , user.user , user.group ) ; UserList.Add ( u ) ; }
MVVM design feels too unwieldy , am I doing it wrong ?
C_sharp : When I have a BigInteger whose size exceeds 2 gigabits ( that 's ¼ gigabyte ; I found this threshold by trial and error ) , the logarithm method gives a wrong answer . This simple code illustrates : Of course we must have a positive log for a number exceeding 1 , a zero log for the number 1 , and a negative log for a number between 0 and 1 ( no integers there ) . My numbers i1 and i2 above are greater than 1 since , by convention , when the most significant byte is between 0 and 127 , that means positive BigInteger.Now , if you read the documentation for BigInteger.Log , they claim it might throw if the logarithm `` is out of range of the Double data type '' . Now , clearly that would require a computer with a memory storage of more than 1E+300 bytes , and the observable universe is much too small to contain such a computer , so I guess that will never happen.So why does n't this work ? PS ! Size over 2 ^^ 31 bits means that the actual value of the BigInteger is over 2 ^^ ( 2 ^^ 31 ) , or approximately circa 8.8E+646456992.UPDATE : I sent in a bug report to Microsoft Connect . After having read the discussions I have also become aware that because of the design of BigInteger and the upper limit of 2 gigabyte for the size of one single object , a BigInteger can never be over 2 gigabyte ( no matter how much memory you have ) . This bug happens , therefore , when the BigInteher is between ¼ and 2 gigabytes . <code> byte [ ] bb ; bb = new byte [ 150000001 ] ; bb [ 150000000 ] = 1 ; // sets most significant byte to one var i1 = new BigInteger ( bb ) ; double log1 = BigInteger.Log ( i1 ) ; Console.WriteLine ( log1 ) ; // OK , writes 831776616.671934 bb = new byte [ 300000001 ] ; bb [ 300000000 ] = 1 ; // sets most significant byte to one var i2 = new BigInteger ( bb ) ; double log2 = BigInteger.Log ( i2 ) ; Console.WriteLine ( log2 ) ; // Broken , gives negative number , should be twice 831776616.671934
Wrong logarithm of BigInteger when size of BigInteger exceeds ¼ gigabyte
C_sharp : I have an xml of the following format : I 'd like to sort the list of customers based on their names , and return the document in the following format : I am using c # and currently xmldocument.thank you <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < contactGrp name= '' People '' > < contactGrp name= '' Developers '' > < customer name= '' Mike '' > < /customer > < customer name= '' Brad '' > < /customer > < customer name= '' Smith '' > < /customer > < /contactGrp > < contactGrp name= '' QA '' > < customer name= '' John '' > < /customer > < customer name= '' abi '' > < /customer > < /contactGrp > < /contactGrp > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < contactGrp name= '' People '' > < contactGrp name= '' Developers '' > < customer name= '' Brad '' > < /customer > < customer name= '' Mike '' > < /customer > < customer name= '' Smith '' > < /customer > < /contactGrp > < contactGrp name= '' QA '' > < customer name= '' abi '' > < /customer > < customer name= '' John '' > < /customer > < /contactGrp > < /contactGrp >
sorting entire xdocument based on subnodes
C_sharp : I have some fairly complex Entity Framework queries throughout my codebase and I decided to centralize the logic into the models . Basically , picture a bunch of controllers with large queries and lots of repeated code in their expression trees . So I took out parts of those expression trees and moved them to the models , allowing for less repetition.For example , let 's say I often need to fetch models called Entity which are in a state of Not Deleted . On my Entity model I have : ( This is one of the smaller examples , mostly just checking for valid data before trying to examine that data . ) And using it would look like : I 'm finding , however , that while sometimes I want records which are not deleted , other times I want records which are deleted . To do that , is there a way to invert the logic from the consuming code ? Something conceptually akin to this ( which obviously does n't work ) : I 'd prefer not to have two Func < > s on the object , one for IsDeleted and one for IsNotDeleted which are nearly identical . The Func < > returns a bool , is there a syntax to call the inverse of it when putting it in a .Where ( ) clause ? <code> public static Func < Entity , bool > IsNotDeleted = e = > e.Versions ! = null ? e.Versions.OrderByDescending ( v = > v.VersionDate ) .FirstOrDefault ( ) ! = null ? e.Versions.OrderByDescending ( v = > v.VersionDate ) .First ( ) .ActivityType ! = VersionActivityType.Delete : false : false ; var entities = EntityRepository.Entities.Where ( Entity.IsNotDeleted ) .Where ( ... var entities = EntityRepository.Entities.Where ( ! Entity.IsDeleted ) .Where ( ...
Logical Inverse of a Func < T , bool >
C_sharp : We have a Teams bot that posts messages in MS Teams . The first activity of a new conversation is always an adaptive card and once in a while , we update that with a new card . This worked OK until I made a new Team with this bot.The update we are trying with UpdateActivityAsync , return NotFound.After some troubleshooting , I noticed the following : The new team has a different name : 19 : ... @ thread.tacv2 as opposed to 19 : ... @ thread.skype.When I use an older team , it works as expected.When I update the activity with text only ( so no adaptive card as attachment ) it will always update as expected.After an update with a text , we are able to update with an adaptive card ONCE . After one update with an adaptive card , any subsequent updates with adaptive cards will return NotFound.So , as a workaround , I now first update with text and immediately after that I send the update with the card . Which is a bad UI thing ( flickering ) but it works for now.We use the old bot framework version 3 , which I know is not maintained anymore , but as far as I can find , it should still work ( no plans to discontinue operation ) . Also given the above points ( specifically point 4 ) I would expect it uses the same calls under the hood.So , this works for older teams , but not for a team with @ thread.tacv2And for teams with @ thread.tacv2 we now have to use thisThe exception does not provide too many details : Operation returned an invalid status code 'NotFound'Conversation not found.Does anyone know how to avoid this change between teams and allow updates of activity with cards ? Also ( and this is much less important , but I think it 's useful to add ) I noticed that sometimes ( I 've seen it twice now ) Teams seems unable to render the adaptive card and displays URIObject XML instead , containing error : cards.unsupported . However , if I exit the client and restart it , it renders fine ... I have never seen this so far in the old channels.Teams client version 1.3.00.362 ( 64-bit ) ( no dev mode ) .Normal Azure tenant ( no preview/trial ) EDIT 11/05/2020 It seems that this also happens on teams with the 'old ' name ( @ thread.skype ) . So the ' @ thread.tacv2 ' seems unrelated . <code> await connector.Conversations.UpdateActivityAsync ( teamsConversationId , activityId , ( Activity ) messageWithCard ) ; var messageWithText = Activity.CreateMessageActivity ( ) ; messageWithText.ChannelId = teamsConversationId ; messageWithText.Id = activityId ; messageWithText.Type = ActivityTypes.Message ; messageWithText.Text = `` Updated '' ; await connector.Conversations.UpdateActivityAsync ( teamsConversationId , activityId , ( Activity ) messageWithText ) ; await connector.Conversations.UpdateActivityAsync ( teamsConversationId , activityId , ( Activity ) messageWithCard ) ;
Teams UpdateActivity events difference when you test in newly created teams
C_sharp : What are the cons of some code like this : <code> public class Class1 { public object Property1 { set { // Check some invariant , and null // throw exceptions if not satisfied // do some more complex logic //return value } } }
Why is considered best practice to have no complex logic in class properties ?
C_sharp : I 'm using a third party API dll , bloomberg SAPI for those who know / have access to it.Here 's my problem : All of the above is from the F12 / Go to definition / object browser in VS2010 . Now when i try and use this code : This does not compile ... standard compiler error - no definition / extension method 'Dispose ' could be found.How is this possible ? ? ? They 've made an assembly and explicitly edited it 's metadata ? I do n't know if it 's legally possible to hide ( to exclusion ) a public method ... . <code> [ ComVisible ( true ) ] public interface IDisposable { //this is from mscorlib 2.0.0.0 - standard System.IDisposable void Dispose ( ) ; } public abstract class AbstractSession : IDisposable { } //method signatures and commentspublic class Session : AbstractSession { } //method signatures and comments ( from assembly metadata ) ( new Session ( ) ) .Dispose ( ) ;
How can a dispose method be hidden ?
C_sharp : Is there any behavioural difference between : And : Both throw exceptions of null object , if s is null . The first example is more readable as it shows exactly where the error occurs ( the exception bit is right next to the line which will cause the exception ) .I have seen this coding style a lot on various blogs by various coders of all sorts of skill levels , but why not just perform the main logic by checking if s is not null and thus save the exception from ever being raised ? Is there a downside to this approach ? Thanks <code> if ( s == null ) // s is a string { throw new NullReferenceException ( ) ; } try { Console.Writeline ( s ) ; } catch ( NullReferenceException Ex ) { // logic in here }
throw new Exception vs Catch block
C_sharp : I am having a very peculiar problem : the ToList ( ) extension method is failing to convert results to a list . here is my code , standard boilerplate linq query , I converted ToList ( ) twice for good measureyet the assets are still a list of System.Data.Entities.DynamicProxies ... .I 've never had this problem before . <code> var assets = new List < Asset > ( ) ; using ( var ctx = new LeaseContext ( ) ) { assets = ctx.Assets.OrderBy ( o = > o.Reference ) .Where ( w = > w.Status == AssetStatus.Active ) .ToList ( ) ; assets.ToList ( ) ; } return assets ;
Linq ToList ( ) fails to trigger Immediate Execution
C_sharp : I have a performance problem on certain computers with the following query : Apparently ToList ( ) can be quite slow in certain queries , but with what should I replace it ? <code> System.Diagnostics.EventLog log = new System.Diagnostics.EventLog ( `` Application '' ) ; var entries = log.Entries .Cast < System.Diagnostics.EventLogEntry > ( ) .Where ( x = > x.EntryType == System.Diagnostics.EventLogEntryType.Error ) .OrderByDescending ( x = > x.TimeGenerated ) .Take ( cutoff ) .Select ( x = > new { x.Index , x.TimeGenerated , x.EntryType , x.Source , x.InstanceId , x.Message } ) .ToList ( ) ;
Optimizing a LINQ reading from System.Diagnostics.EventLog
C_sharp : I am using LinqPad and in that I was looking at the IL code ( compiler optimization switched on ) generated for the following Interface & the class that implements the interface : IL Code : Surprisingly I do n't see any IL code for the interface . Is this because of the way LinqPad works or the C # compiler treats the interfaces in a different manner ? <code> public interface IStockService { [ OperationContract ] double GetPrice ( string ticker ) ; } public class StockService : IStockService { public double GetPrice ( string ticker ) { return 93.45 ; } } IStockService.GetPrice : StockService.GetPrice : IL_0000 : ldc.r8 CD CC CC CC CC 5C 57 40 IL_0009 : ret StockService..ctor : IL_0000 : ldarg.0 IL_0001 : call System.Object..ctorIL_0006 : ret
IL Code of an interface
C_sharp : I 'm currently working on a simple way to implement a intrusive tree structure in C # . As I 'm mainly a C++ programmer , I immediatly wanted to use CRTP . Here is my code : This works but ... I ca n't understand why I have to cast when calling a_node.SetParent ( ( T ) this ) , as I 'm using generic type restriction ... C # cast has a cost , and I 'd like not to spread this cast in each intrusive collection implementation ... <code> public class TreeNode < T > where T : TreeNode < T > { public void AddChild ( T a_node ) { a_node.SetParent ( ( T ) this ) ; // This is the part I hate } void SetParent ( T a_parent ) { m_parent = a_parent ; } T m_parent ; }
C # - Intrusive tree structure , using CRTP
C_sharp : I 'm learning for the Microsoft Exam 70-483 . In this exercise the correct answers are A and F. In my opinion E is correct too . I think E is fully equivalent to A + F. Is it true ? Question : You are creating a class named Employee . The class exposes a string property named EmployeeType . The following code segment defines the Employee class . ( Line numbers are included for reference only . ) The EmployeeType property value must be accessed and modified only by code within the Employee class or within a class derived from the Employee class.You need to ensure that the implementation of the EmployeeType property meets the requirements . Which two actions should you perform ? ( Each correct answer represents part of the complete solution . Choose two. ) A . Replace line 05 with the following code segment : protected get ; B . Replace line 06 with the following code segment : private set ; C. Replace line 03 with the following code segment : public string EmployeeTypeD . Replace line 05 with the following code segment : private get ; E. Replace line 03 with the following code segment : protected string EmployeeTypeF . Replace line 06 with the following code segment : protected set ; <code> 01 public class Employee02 { 03 internal string EmployeeType04 { 05 get ; 06 set ; 07 } 08 }
In C # specify access modifier for a method is equivalent to get and set
C_sharp : Is this thread safe ? Specifically , is it possible for the GetMyObject ( ) method to return null ? I understand it is possible for two threads to get a different instance of MyObject but I do n't care about that . I just want to make sure it is safe to assume GetMyObject ( ) will never return null . <code> class Foo { private static MyObject obj ; public static MyObject GetMyObject ( ) { MyObject o = obj ; if ( o == null ) { o = new MyObject ( ) ; obj = o ; } return o ; } public static void ClearMyObject ( ) { obj = null ; } } class MyObject { }
Is Object Assignment Thread Safe ?
C_sharp : I have a simple Money type with an implicit cast from decimal : And I defined a Sum ( ) overload to operate on those values : What I did n't expect was for this extension method to interfere with the existing Sum ( ) extension methods : The error is `` Can not implicitly convert type 'Money ' to 'int ' . An explicit conversion exists ( are you missing a cast ? ) '' . Is it correct that the compiler favors int = > decimal = > Money implicit conversions over resolving an overload that 's an exact match ? <code> struct Money { decimal innerValue ; public static implicit operator Money ( decimal value ) { return new Money { innerValue = value } ; } public static explicit operator decimal ( Money value ) { return value.innerValue ; } public static Money Parse ( string s ) { return decimal.Parse ( s ) ; } } static class MoneyExtensions { public static Money Sum < TSource > ( this IEnumerable < TSource > source , Func < TSource , Money > selector ) { return source.Select ( x = > ( decimal ) selector ( x ) ) .Sum ( ) ; } } var source = new [ ] { `` 2 '' } ; Money thisWorks = source.Sum ( x = > Money.Parse ( x ) ) ; int thisWorksToo = source.Sum ( new Func < string , int > ( x = > int.Parse ( x ) ) ) ; int thisDoesNot = source.Sum ( x = > int.Parse ( x ) ) ;
Unexpected effect of implicit cast on delegate type inference
C_sharp : I decided to make the control and then reuse . as directives in angular.but only reached Ads.BoxPickerControl in xaml for exampleregister and call in content page and successfully caught target invocation exceptionWhat have I done wrong ? <code> namespace Chainhub.Forms.UI.Controls { public partial class BoxPickerControl : ContentView { public BoxPickerControl ( ) { InitializeComponent ( ) ; } } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ContentView xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' x : Class= '' Chainhub.Forms.UI.Controls.BoxPickerControl '' > < StackLayout > < StackLayout > < StackLayout BackgroundColor= '' # 383940 '' Padding= '' 5,5,5,5 '' Orientation= '' Horizontal '' > < StackLayout HorizontalOptions= '' StartAndExpand '' > < Label Text= '' Categories '' TextColor= '' White '' > < /Label > < /StackLayout > < /ContentView > < controls : BoxPickerControl > < /controls : BoxPickerControl >
How to make the components , followed by reuse in XAML ?
C_sharp : I 've written a hosted Chrome Web App which authenticates the user with OAuth 2.0 using the Google APIs Client Library for .NET . Now I want to add payments to our application using the in-built Chrome Web Store Payments.Looking at the documentation it appears that I need an OpenID URL in order to check for payment.How can I get this UserID/OpenID URL since I 'm using OAuth instead of OpenID authentication ? <code> var service = new Google.Apis.Oauth2.v2.Oauth2Service ( new BaseClientService.Initializer { HttpClientInitializer = userCredential , ApplicationName = `` My App Name '' , } ) ; HttpResponseMessage message = await service.HttpClient.GetAsync ( string.Format ( `` https : //www.googleapis.com/chromewebstore/v1/licenses/ { 0 } / { 1 } '' , appId , fedId // Where do I get this ? ? ) ) ;
Can I use Chrome Web Store payments with OAuth 2.0
C_sharp : I often find myself writing a property that is evaluated lazily . Something like : It is not much code , but it does get repeated a lot if you have a lot of properties.I am thinking about defining a class called LazyProperty : This would enable me to initialize a field like this : And then the body of the property could be reduced to : This would be used by most of the company , since it would go into a common class library shared by most of our products.I can not decide whether this is a good idea or not . I think the solutions has some pros , like : Less codePrettier codeOn the downside , it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class . What do you think ? Is this a good idea or should I abandon it ? Also , is the implicit operator a good idea , or would you prefer to use the Value property explicitly if you should be using this class ? Opinions and suggestions are welcomed : - ) <code> if ( backingField == null ) backingField = SomeOperation ( ) ; return backingField ; public class LazyProperty < T > { private readonly Func < T > getter ; public LazyProperty ( Func < T > getter ) { this.getter = getter ; } private bool loaded = false ; private T propertyValue ; public T Value { get { if ( ! loaded ) { propertyValue = getter ( ) ; loaded = true ; } return propertyValue ; } } public static implicit operator T ( LazyProperty < T > rhs ) { return rhs.Value ; } } first = new LazyProperty < HeavyObject > ( ( ) = > new HeavyObject { MyProperty = Value } ) ; public HeavyObject First { get { return first ; } }
Implementing a `` LazyProperty '' class - is this a good idea ?
C_sharp : What does if ( ( a & b ) == b ) mean in the following code block ? Why is it not like this ? <code> if ( ( e.Modifiers & Keys.Shift ) == Keys.Shift ) { lbl.Text += `` \n '' + `` Shift was held down . `` ; } if ( e.Modifiers == Keys.Shift ) { lbl.Text += `` \n '' + `` Shift was held down . `` ; }
What does this statement mean in C # ?
C_sharp : Here we have a Grid with a Button . When the user clicks the button , a method in a Utility class is executed which forces the application to receive a click on Grid . The code flow must stop here and not continue until the user has clicked on the Grid.I have had a similar question before here : Wait till user click C # WPFIn that question , I got an answer using async/await which works , but since I am going to use it as part of an API , I do not want to use async/await , since the consumers will have then to mark their methods with async which I do not want.How do I write Utility.PickPoint ( Grid grid ) method to achieve this goal ? I saw this which may help but did not fully understood it to apply here to be honest : Blocking until an event completesConsider it as something like Console.ReadKey ( ) method in a Console application . When we call this method , the code flow stops until we enter some value . The debugger does not continue until we enter something . I want the exact behavior for PickPoint ( ) method . The code flow will stop until the user clicks on the Grid . <code> < Window x : Class= '' WpfApp1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : WpfApp1 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 450 '' Width= '' 800 '' > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' 3* '' / > < RowDefinition Height= '' 1* '' / > < /Grid.RowDefinitions > < Grid x : Name= '' View '' Background= '' Green '' / > < Button Grid.Row= '' 1 '' Content= '' Pick '' Click= '' ButtonBase_OnClick '' / > < /Grid > < /Window > public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private void ButtonBase_OnClick ( object sender , RoutedEventArgs e ) { // do not continue the code flow until the user has clicked on the grid . // so when we debug , the code flow will literally stop here . var point = Utility.PickPoint ( View ) ; MessageBox.Show ( point.ToString ( ) ) ; } } public static class Utility { public static Point PickPoint ( Grid grid ) { } }
How to block code flow until an event is fired in C #
C_sharp : I have a picture that I elaborate with my program to obtain a list of coordinates.Represented in the image there is a matrix.In an ideal test i would get only the sixteen central points of each square of the matrix.But in actual tests i take pretty much noise points.I want to use an algorithm to extrapolate from the list of the coordinates , the group formed by 16 coordinates that best represent a matrix.The matrix can have any aspect ratio ( beetween a range ) and can result a little rotated.But is always an 4x4 matrix.The matrix is not always present in the image , but is not a problem , i need only the best matching.Of course the founded point are always more than 16 ( or i skip ) Example of founded points : Example of desidered result : If anyone can suggest me a preferred way to do this would be great.Im thinking about the euclidean distance beetween points.at the end if i have 16 points in the list , this could be a matrix.Any better suggestion ? Thank you <code> For each point in the list : 1. calculate the euclidean distance ( D ) with the others 2. filter that points that D * 3 > image.widht ( or height ) 3. see if it have at least 2 point at the same ( more or less ) distance , if not skip 4. if yes put the point in a list and for each same-distance founded points : go to 2nd step .
Recognize a Matrix in a group of points
C_sharp : I want to calculate a unified diff comparing two documents . ( The diff is to go in an email , and Wikipedia says unified diff is the best plain text diff format . ) Team Foundation has a command line interface do that ( Example files at https : //gist.github.com/hickford/5656513 ) Brilliant , but I 'd rather use a library than start an external process , for the usual reasons.Searching MSDN , I found Team Foundation has a .NET library Microsoft.TeamFoundation.VersionControl . However , the documentation did n't give any examples of calculating a diff.How do I calculate a unified diff with the Team Foundation library ? Edit : I tried the method Difference.DiffItems but it did n't work—the file diff.txt was left empty . <code> > tf diff /format : unified alice.txt bob.txt- Alice started to her feet , + Bob started to her feet , var before = @ '' c : \alice.txt '' ; var after = @ '' c : \bob.txt '' ; var path = @ '' c : \diff.txt '' ; using ( var w = new StreamWriter ( path ) ) { var options = new DiffOptions ( ) ; options.OutputType = DiffOutputType.Unified ; options.StreamWriter = w ; Difference.DiffFiles ( before , FileType.Detect ( before , null ) , after , FileType.Detect ( after , null ) , options ) ; } Console.WriteLine ( File.ReadAllText ( path ) ) ;
How to use Team Foundation 's library to calculate unified diff ?
C_sharp : I have just went through one of my projects and used a bunch of the new c # 6 features like the null propagation operator handler ? .Invoke ( null , e ) , which builds in Visual Studio . However , when I run my script to publish out the NuGet packages , I get compilation errors saying : It would appear NuGet is using an older version of the compiler , but I was wondering if anyone knew a work around or configuration that could be set to resolve the issue . <code> EventName.cs ( 14,66 ) : error CS1056 : Unexpected character ' $ 'EventName.cs ( 69,68 ) : error CS1519 : Invalid token '= ' in class , struct , or interface member declarationEventName.cs ( 69,74 ) : error CS1520 : Method must have a return type
NuGet Pack -Build does not seem to understand c # 6.0
C_sharp : Maintenance EditAfter using this approach for a while I found myself only adding the exact same boilerplate code in every controller so I decided to do some reflection magic . In the meantime I ditched using MVC for my views - Razor is just so tedious and ugly - so I basically use my handlers as a JSON backend . The approach I currently use is to decorate my queries/commands with a Route attribute that is located in some common assembly like this : I then implemented an MVC host that extracts the annotated commands/queries and generates the controllers and handlers for me at startup time . With this my application logic is finally free of MVC cruft . The query responses are also automatically populated with validation messages . My MVC applications now all look like this : After realizing I really do n't use MVC outside the host - and constantly having issues with the bazillion dependencies the framework has - I implemented another host based on NServiceKit . Nothing had to be changed in my application logic and the dependencies are down to System.Web , NServiceKit and NServiceKit.Text that takes good care of the model binding . I know it 's a very similar approach to how NServiceKit/ServiceStack does their stuff but I 'm now totally decoupled from the web framework in use so in case a better one comes along I just implement another host and that 's it.The situationI 'm currently working on an ASP.NET MVC site that 's implementing the businesslogic-view separation via the IQueryHandler and ICommandHandler abstractions ( using the almighty SimpleInjector for dependency injection ) .The ProblemI 've got to attach some custom validation logic to a QueryHandler via a decorator and that 's working pretty well in and of itself . The problem is that in the event of validation errors I want to be able to show the same view that the action would have returned but with information on the validation error of course . Here is a sample for my case : In this scenario I have some business logic that 's handled by the queryHandler that is decorated with a ValidationQueryHandlerDecorator that throws ValidationExceptions when it is appropriate . What I want it to doWhat I want is something along the lines of : I 've been thinking about a special ValidationErrorHandlerAttribute but then I 'm losing the context and I ca n't really return the proper view . The same goes with the approach where I just wrap the IQueryHandler < , > with a decorator ... I 've seen some strange pieces of code that did some string sniffing on the route and then instantiating a new controller and viewmodel via Activator.CreateInstance - that does n't seem like a good idea.So I 'm wondering whether there is a nice way to do this ... maybe I just do n't see the wood from the trees . Thanks ! <code> [ Route ( `` items/add '' , RouteMethod.Post ) ] public class AddItemCommand { public Guid Id { get ; set ; } } [ Route ( `` items '' , RouteMethod.Get ) ] public class GetItemsQuery : IQuery < GetItemsResponse > { } // The response inherits from a base type that handles// validation messages and the likepublic class GetItemsResponse : ServiceResponse { } + MvcApp +- Global.asax +- Global.asax.cs - Startup the host and done +- Web.config public class HomeController : Controller { private readonly IQueryHandler < SomeQuery , SomeTransport > queryHandler ; public ActionResult Index ( ) { try { var dto = this.queryHandler.Handle ( new SomeQuery { /* ... */ } ) ; // Doing something awesome with the data ... return this.View ( new HomeViewModel ( ) ) ; } catch ( ValidationException exception ) { this.ModelState.AddModelErrors ( exception ) ; return this.View ( new HomeViewModel ( ) ) ; } } } public class HomeController : Controller { private readonly IQueryHandler < SomeQuery , SomeTransport > queryHandler ; public ActionResult Index ( ) { var dto = this.queryHandler.Handle ( new SomeQuery { /* ... */ } ) ; // Doing something awesome with the data ... // There is a catch-all in place for unexpected exceptions but // for ValidationExceptions I want to do essentially the same // view instantiation but with the model errors attached return this.View ( new HomeViewModel ( ) ) ; } }
How to move validation handling from a controller action to a decorator
C_sharp : The recent additions to C # 7 are great and now in the latest release we can pass ValueType ( struct ) instances to functions by-reference ( 'by-ref ' ) more efficiently by using the new in keyword.Using either in or ref in the method declaration means that you avoid the extra 'memory-blt ' copy of the entire struct which is normally required in order to preserve by-value semantics . With in , you get this benefit ( passing a pointer to the source ValueType itself ) , but unlike ref , the callee wo n't be allowed to modify that target ( enforcement by the compiler ) .In addition to improving the rigor of design intent , in has an added benefit over ref that the call-site syntax is more relaxed than with ref . In fact , you do n't need to mention the in keyword at the call-site ; it 's optional.Anyway , I noticed that apparently you can define C # operator overloads using in-attributed arguments.This is great if the by-ref semantics actually do prevail in the runtime behavior . But I would find that surprising , because even though C # lets you omit the in keyword in method calls , the generated code at the call site does need to be different . Namely , it needs to emit ( e.g . ) OpCodes.Ldflda instead of OpCodes.Ldfld , and so forth . And then there 's also the fact that operator overloads do n't have a traditional method `` call site '' that could be decorated with the ( albeit , optional ) in keyword : So , does anyone know if the compiler , JIT , and runtime will honor what the code seems to be allowed to express , such that calls to operator overloads with in-parameters will actually obtain by-ref semantics ? I could n't find any mention of the situation in the docs . Since the code shown above basically continues to work as it did without the in markings , I suppose the alternative would be that the in keyword is just silently ignored here ? <code> public static bool operator == ( in FILE_ID_INFO x , in FILE_ID_INFO y ) = > eq ( in x , in y ) ; // works : -- -- -^ -- -- -^ var fid1 = default ( FILE_ID_INFO ) ; var fid2 = default ( FILE_ID_INFO ) ; bool q = fid1 == fid2 ; // ^ -- - in ? -- -^
C # 7 'in ' parameters allowed with operator overloading
C_sharp : Is it bad to have expensive code at the start of an async method , before the first await is called ? Should this code be wrapped with a TaskEx.Run instead ? <code> public async Task Foo ( ) { // Do some initial expensive stuff . // ... // First call to an async method with await . await DoSomethingAsync ; }
Can async methods have expensive code before the first 'await ' ?
C_sharp : i 'm not sure how the Windows kernel handles Thread timing ... i 'm speaking about DST and any other event that affects the time of day on Windows boxes.for example , Thread .Sleep will block a thread from zero to infinite milliseconds.if the kernel uses the same `` clock '' as that used for time of day , then when ( a ) someone manually changes the time of day , or ( b ) some synchronization to a time server changes the time of day , or ( c ) Daylight Saving Time begins or ends and the system has been configured to respond to these two DST events , et cetera , are sleeping threads in any way affected ? i.e. , does the kernel handle such events in such a way that the programmer need do nothing ? N.B . : for non-critical applications , this is likely a who cares ? situation.For critical applications , knowing the answer to this question is important because of the possibility that one must program for such exception conditions.thank youedit : i thought of a simple test which i 've run in LINQPad 4. the test involved putting the thread to sleep , starting a manual timer at approximately the same time as the thread was put to sleep , and then ( a ) moving the time ahead one hour , then for the second test , moving the time back two hours ... in both tests , the period of sleep was not affected.Bottom line : with Thread.Sleep , there is no need to worry about events that affect the time of day.here 's the trivial c # code : <code> Int32 secondsToSleep ; String seconds ; Boolean inputOkay ; Console.WriteLine ( `` How many seconds ? `` ) ; seconds = Console.ReadLine ( ) ; inputOkay = Int32.TryParse ( seconds , out secondsToSleep ) ; if ( inputOkay ) { Console.WriteLine ( `` sleeping for { 0 } second ( s ) '' , secondsToSleep ) ; Thread.Sleep ( secondsToSleep * 1000 ) ; Console.WriteLine ( `` i am awake ! `` ) ; } else Console.WriteLine ( `` invalid input : [ { 0 } ] '' , seconds ) ;
Is .NET Thread.Sleep affected by DST ( or system time ) changes ?
C_sharp : I looked around for this and could not find an answer . Say I have this code : T could be any class , even a Nullable < > . Does performing the check above cause boxing if T is a value type ? My understanding is that this is the same as calling ReferenceEquals which takes two object arguments , either of which would cause boxing if T was a value type , if I understand correctly.If the above does cause boxing , is there a more preferred way to do this without causing the box to occur ? I know there is default ( T ) but in the case of int that is 0 , and I am looking to see if this value is null without boxing it . Also , I am looking to do this in a way that satisfies both value and reference types . <code> class Command < T > : ICommand < T > { public void Execute ( T parameter ) { var isNull = parameter == null ; // ... } }
Does Performing a Null Check on a Generic Cause Boxing ?
C_sharp : I 'm working on my first WinForms application ... I typically write web apps ... A strange thing is happening with my application today . If I run the application on my computer , or my co-worker runs it on his computer , my MessageBoxes are modal only to my application . This is the desired behavior . My users will need to be able to make manual edits in a separate application if a message box appears , and clicking `` OK '' in the message box will `` unpause '' my application and allow them to continue.We just went to install a beta of the application on two end users ' computers this afternoon and for some reason when we run the application on either of their computers the message boxes are modal to the desktop - nothing else can receive focus until `` OK '' is clicked . This behavior causes a HUGE issue for my application.I do n't know what could be different on the users ' machines to cause this behavior.My computer - Win7 64-bit , my co-worker 's computer - Win7 32-bit , two users ' computers are Win7 32-bit . All have .Net Framework 4.5 or 4.5.1 installed.Any advice ? UPDATES:2014.11.17 - code snippet <code> DialogResult result = MessageBox.Show ( `` The Style field did not pass validation . Please manually fix the data then click OK to continue . `` , `` WARNING '' , MessageBoxButtons.OK , MessageBoxIcon.Warning , MessageBoxDefaultButton.Button1 ) ;
MessageBox is modal to the desktop
C_sharp : I noticed that when I navigate to the same entity object via a different `` member path '' I get a different object . ( I 'm using change-tracking proxies , so I get a different change-tracking proxy object . ) Here is an example to show what I mean.Even though joesInfo1 & joesInfo2 refer to the same record in the DB ( the same entity ) , they are different objects . I thought that Entity Framework made sure to use the same object in these cases.Question # 1 : Is this really how it is ? Or is my observation wrong ? This is a problem when eager loading via Include . For example , So , it looks like to get eager loading to work , you have to specify all possible `` member access paths '' that you will take in your program . This is not possible in some cases like this one . Because your Person object might be floating around in your program and the navigation properties `` Parent '' or `` Children '' could be called on it ( and it 's parents/children ) any number of times.Question # 2 : Is there any way to get this to work without specifying all of the `` member access paths '' that you will take in your program ? Thanks.ANSWER : So , here 's what I have concluded , based on bubi 's answer.It is possible to get different `` entity objects '' if you use AsNoTracking ( ) . ( In other words , in the example above , depending on what path you take to get to the `` Joe '' Person entity , it 's possible that you will get a different object . ) If you do n't use AsNoTracking all the Joes will be the same object . Here is what this means : You CAN eagerly load a whole hierarchical or recursive object graph and use it outside of a context . How ? JUST DO N'T USE AsNoTracking ( ) . <code> var joesInfo1 = context.People.Single ( p = > p.Name == `` Joe '' ) .Info ; var joesInfo2 = context.People.Single ( p = > p.Name == `` Joe 's Dad '' ) .Children.Single ( p = > p.Name == `` Joe '' ) .Info ; IQueryable < Person > allPeople = null ; using ( context ) { allPeople = context.People //.AsNoTracking ( ) .Include ( p = > p.Info ) .Include ( p = > p.Children ) .Include ( p = > p.Parent ) .ToList ( ) ; } var joesInfo1 = allPeople.Single ( p = > p.Name == `` Joe '' ) .Info ; // OK , Info is already there because it was eagerly loadedvar joesInfo2 = allPeople.Single ( p = > p.Name == `` Joe 's Dad '' ) .Children.Single ( p = > p.Name == `` Joe '' ) .Info ; // ERROR : `` Object context disposed ... '' , Info is not in the Person object , even though the Person object refers to the same entity ( Joe ) as above .
Entity Framework - Different proxy objects for the same entity . And Include behavior with multiple paths to same destination
C_sharp : Consider the following code : This yields the following output : Exception received : A task was canceled.My question is simple : How do I get at the original InvalidOperationException ( `` TEST '' ) ; rather than a System.Threading.Tasks.TaskCanceledException ? Note that if you remove the .ContinueWith ( ) part , this works as I expected and the output in that case is Exception received : TEST . ( Also note that this example is using .Net 4.5 , but the original code must use .Net 4.0 ) SOLUTIONThanks to the answers , this is now working . I chose the following solution - I needed to wait on both the original task AND the continuation task : <code> using System ; using System.Linq ; using System.Threading ; using System.Threading.Tasks ; namespace Demo { static class Program { static void Main ( ) { var tasks = new Task [ 1 ] ; tasks [ 0 ] = Task.Run ( ( ) = > throwExceptionAfterOneSecond ( ) ) .ContinueWith ( task = > { Console.WriteLine ( `` ContinueWith ( ) '' ) ; } , TaskContinuationOptions.NotOnFaulted ) ; try { Task.WaitAll ( tasks ) ; } catch ( AggregateException ex ) { Console.WriteLine ( `` Exception received : `` + ex.InnerExceptions.Single ( ) .Message ) ; } } static void throwExceptionAfterOneSecond ( ) { Thread.Sleep ( 1000 ) ; throw new InvalidOperationException ( `` TEST '' ) ; } } } using System ; using System.Linq ; using System.Threading ; using System.Threading.Tasks ; namespace Demo { static class Program { static void Main ( ) { var tasks = new Task [ 2 ] ; tasks [ 0 ] = Task.Run ( ( ) = > throwExceptionAfterOneSecond ( ) ) ; tasks [ 1 ] = tasks [ 0 ] .ContinueWith ( task = > { if ( task.Status == TaskStatus.RanToCompletion ) Console.WriteLine ( `` ContinueWith ( ) '' ) ; } ) ; try { Task.WaitAll ( tasks ) ; } catch ( AggregateException ex ) { Console.WriteLine ( `` Exception received : `` + ex.InnerExceptions.Single ( ) .Message ) ; } Console.WriteLine ( `` Done . `` ) ; } static void throwExceptionAfterOneSecond ( ) { Thread.Sleep ( 1000 ) ; throw new InvalidOperationException ( `` TEST '' ) ; } } }
How to get the original exception when using ContinueWith ( ) ?
C_sharp : I am using EF and have a database table which has a number of date time fields which are populated as various operations are performed on the record.I am currently building a reporting system which involves filtering by these dates , but because the filters ( is this date within a range , etc ... ) have the same behavior on each field , I would like to reuse my filtering logic so I only write a single date filter and use it on each field.My initial filtering code looks something like : This works fine , but I would prefer to reduce the duplicated code in the 'Where ' methods as the filter algorithm is the same for each date field.What I would prefer is something that looks like the following ( I will create a class or struct for the filter values later ) where I can encapsulate the match algorithm using maybe an extension method : Where the extension method could look something like : Using the above code , if my filtering code is as follows : I get the following exception : The problem I have is the use of Invoke to get the particular field being queried as this technique does not resolve nicely to SQL , because if I modify my filtering code to the following it will run without errors : The issue with this is that the code ( using ToList on the entire table before filtering with the extension method ) pulls in the entire database and queries it as objects instead of querying the underlying database so it is not scaleable.I have also investigated using the PredicateBuilder from Linqkit , but it could not find a way to write the code without using the Invoke method.I know there are techniques where one can express parts of the query as strings which include field names , but I would prefer to use a more type safe way of writing this code.Also , in an ideal world I could redesign the database to have multiple 'date ' records related to a single 'item ' record , but I am not at liberty to change the database schema in this way.Is there another way I need to write the extension so it does n't use Invoke , or should I be tackling reuse of my filtering code in a different way ? <code> DateTime ? dateOneIsBefore = null ; DateTime ? dateOneIsAfter = null ; DateTime ? dateTwoIsBefore = null ; DateTime ? dateTwoIsAfter = null ; using ( var context = new ReusableDataEntities ( ) ) { IEnumerable < TestItemTable > result = context.TestItemTables .Where ( record = > ( ( ! dateOneIsAfter.HasValue || record.DateFieldOne > dateOneIsAfter.Value ) & & ( ! dateOneIsBefore.HasValue || record.DateFieldOne < dateOneIsBefore.Value ) ) ) .Where ( record = > ( ( ! dateTwoIsAfter.HasValue || record.DateFieldTwo > dateTwoIsAfter.Value ) & & ( ! dateTwoIsBefore.HasValue || record.DateFieldTwo < dateTwoIsBefore.Value ) ) ) .ToList ( ) ; return result ; } DateTime ? dateOneIsBefore = null ; DateTime ? dateOneIsAfter = null ; DateTime ? dateTwoIsBefore = null ; DateTime ? dateTwoIsAfter = null ; using ( var context = new ReusableDataEntities ( ) ) { IEnumerable < TestItemTable > result = context.TestItemTables .WhereFilter ( record = > record.DateFieldOne , dateOneIsBefore , dateOneIsAfter ) .WhereFilter ( record = > record.DateFieldTwo , dateTwoIsBefore , dateTwoIsAfter ) .ToList ( ) ; return result ; } internal static IQueryable < TestItemTable > WhereFilter ( this IQueryable < TestItemTable > source , Func < TestItemTable , DateTime > fieldData , DateTime ? dateIsBefore , DateTime ? dateIsAfter ) { source = source.Where ( record = > ( ( ! dateIsAfter.HasValue || fieldData.Invoke ( record ) > dateIsAfter.Value ) & & ( ! dateIsBefore.HasValue || fieldData.Invoke ( record ) < dateIsBefore.Value ) ) ) ; return source ; } IEnumerable < TestItemTable > result = context.TestItemTables .WhereFilter ( record = > record.DateFieldOne , dateOneIsBefore , dateOneIsAfter ) .WhereFilter ( record = > record.DateFieldTwo , dateTwoIsBefore , dateTwoIsAfter ) .ToList ( ) ; A first chance exception of type 'System.NotSupportedException ' occurred in EntityFramework.SqlServer.dllAdditional information : LINQ to Entities does not recognize the method 'System.DateTime Invoke ( RAC.Scratch.ReusableDataFilter.FrontEnd.TestItemTable ) ' method , and this method can not be translated into a store expression . IEnumerable < TestItemTable > result = context.TestItemTables .ToList ( ) .AsQueryable ( ) .WhereFilter ( record = > record.DateFieldOne , dateOneIsBefore , dateOneIsAfter ) .WhereFilter ( record = > record.DateFieldTwo , dateTwoIsBefore , dateTwoIsAfter ) .ToList ( ) ;
How to reuse a field filter in LINQ to Entities
C_sharp : I 'm attempting to save an array of FileInfo and DirectoryInfo objects for use as a log file . The goal is to capture an image of a directory ( and subdirectories ) at a point in time for later comparison . I am currently using this class to store the info : I have tried XML and Binary serializing my class with no luck . I have also tried creating a new class that does not contain the actual FileInfo but only selected attributes : I 've also had no luck serializing this . I could list the errors I 've encountered with my various attempts , but it would probably be easier to select the best approach first . Here is my serialization code : <code> public class myFSInfo { public FileSystemInfo Dir ; public string RelativePath ; public string BaseDirectory ; public myFSInfo ( FileSystemInfo dir , string basedir ) { Dir = dir ; BaseDirectory = basedir ; RelativePath = Dir.FullName.Substring ( basedir.Length + ( basedir.Last ( ) == '\\ ' ? 1 : 2 ) ) ; } private myFSInfo ( ) { } /// < summary > /// Copies a FileInfo or DirectoryInfo object to the specified path , creating folders and overwriting if necessary . /// < /summary > /// < param name= '' path '' > < /param > public void CopyTo ( string path ) { if ( Dir is FileInfo ) { var f = ( FileInfo ) Dir ; Directory.CreateDirectory ( path.Substring ( 0 , path.LastIndexOf ( `` \\ '' ) ) ) ; f.CopyTo ( path , true ) ; } else if ( Dir is DirectoryInfo ) Directory.CreateDirectory ( path ) ; } } public class myFSModInfo { public Type Type ; public string BaseDirectory ; public string RelativePath ; public string FullName ; public DateTime DateModified ; public DateTime DateCreated ; public myFSModInfo ( FileSystemInfo dir , string basedir ) { Type = dir.GetType ( ) ; BaseDirectory = basedir ; RelativePath = dir.FullName.Substring ( basedir.Length + ( basedir.Last ( ) == '\\ ' ? 1 : 2 ) ) ; FullName = dir.FullName ; DateModified = dir.LastWriteTime ; DateCreated = dir.CreationTime ; } private myFSModInfo ( ) { } /// < summary > /// Copies a FileInfo or DirectoryInfo object to the specified path , creating folders and overwriting if necessary . /// < /summary > /// < param name= '' path '' > < /param > public void CopyTo ( string path ) { if ( Type == typeof ( FileInfo ) ) { Directory.CreateDirectory ( path.Substring ( 0 , path.LastIndexOf ( `` \\ '' ) ) ) ; File.Copy ( FullName , path , true ) ; } else if ( Type == typeof ( DirectoryInfo ) ) Directory.CreateDirectory ( path ) ; } public void Delete ( ) { if ( Type == typeof ( FileInfo ) ) File.Delete ( FullName ) ; else if ( Type == typeof ( DirectoryInfo ) ) Directory.Delete ( FullName ) ; } } public void SaveLog ( string savepath , string dirpath ) { var dirf = new myFSModInfo [ 1 ] [ ] ; string [ ] patharr = { dirpath } ; GetFSInfo ( patharr , dirf ) ; var mySerializer = new System.Xml.Serialization.XmlSerializer ( typeof ( myFSModInfo [ ] ) ) ; var myWriter = new StreamWriter ( savepath ) ; mySerializer.Serialize ( myWriter , dirf [ 0 ] ) ; myWriter.Close ( ) ; /*var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ( ) ; FileStream fs = new FileStream ( savepath , FileMode.Create , FileAccess.Write ) ; bf.Serialize ( fs , dirf [ 0 ] ) ; */ }
Saving FileSystemInfo Array to File
C_sharp : I 'm perhaps being a bit lazy asking this here , but I 'm just getting started with LINQ and I have a function that I am sure can be turned into two LINQ queries ( or one nested query ) rather than a LINQ and a couple of foreach statements . Any LINQ gurus care to refactor this one for me as an example ? The function itself loops through a list of .csproj files and pulls out the paths of all the .cs files included in the project : <code> static IEnumerable < string > FindFiles ( IEnumerable < string > projectPaths ) { string xmlNamespace = `` { http : //schemas.microsoft.com/developer/msbuild/2003 } '' ; foreach ( string projectPath in projectPaths ) { XDocument projectXml = XDocument.Load ( projectPath ) ; string projectDir = Path.GetDirectoryName ( projectPath ) ; var csharpFiles = from c in projectXml.Descendants ( xmlNamespace + `` Compile '' ) where c.Attribute ( `` Include '' ) .Value.EndsWith ( `` .cs '' ) select Path.Combine ( projectDir , c.Attribute ( `` Include '' ) .Value ) ; foreach ( string s in csharpFiles ) { yield return s ; } } }
How can I combine this code into one or two LINQ queries ?
C_sharp : as a small ( large ) hobby project I 've set out to make a ( very primitive ) ssh-2.0 client in C # .This is to explore and better understand DH and help flourish my encryption familiarities : ) As per RFC 4253 , I 've begun the initial connection like this : ( leaving out irrelevant presetting of vars etc . ) As you can see on page 16 of RFC 4253 , I 'm expected to give 10 name-lists . Are these simply suppose to be strings , or how do I mark start/end of each list ( simply by newline \n ) ? Am I even on the right track here ? ( keep in mind I will handle DH and encryption past this point . My question is solely based on the initial contact so far ) .Any help or comments are welcomed and appreciated , PS : I 'm aware libraries exist , but this is not relevant to my project . <code> Random cookie_gen = new Random ( ) ; while ( ( ssh_response = unsecure_reader.ReadLine ( ) ) ! = null ) { MessageBox.Show ( ssh_response ) ; if ( ssh_response.StartsWith ( `` SSH-2.0- '' ) { // you told me your name , now I 'll tell you mine ssh_writer.Write ( `` SSH-2.0-MYSSHCLIENT\r\n '' ) ; ssh_writer.Flush ( ) ; // now I should write up my supported ( which I 'll keep to the required as per rfc 4253 ) ssh_writer.Write ( 0x20 ) ; // SSH_MSG_KEXINIT byte [ ] cookie = new byte [ 16 ] ; for ( int i = 0 ; i < 16 ; i++ ) cookie [ i ] = Convert.ToByte ( cookie_gen.Next ( 0 , 10 ) ) ; ssh_writer.Write ( cookie ) ; // cookie // and now for the name-list // This is where I 'm troubled // `` Footer '' ssh_writer.Write ( 0x00 ) ; // first_kex_packet_follows ssh_writer.Write ( 0x00 ) ; // 0 ssh_writer.Flush ( ) ; } }
primitive ssh connection ( lowlevel )
C_sharp : I have a class library with 2 public classes that inherit from an abstract class . On the abstract class I have a protected field that should only be accessible to the inherited classes . The type used for the field is that of an internal class.For example I have : Now I understand that this wo n't work because if one of the classes deriving from MyAbstract class is extended outside of the assembly , access to myField would be illegal.My question is how can I get things working while keeping MyInternalClass internal ( it should not be accessible outside the assembly ) and allowing classes within the assembly to extend MyAbstractClass with access to myField ? <code> internal class MyInternalClass { ... } public abstract class MyAbstractClass { protected MyInternalClass myField ; }
Using an internal type used as protected field
C_sharp : I need to export a collection of items in camel casing , for this I use a wrapper.The class itself : This serializes fine : The wrapper : This however capitalizes the wrapped Examples for some reason , I tried to override it with XmlElement but this does n't seem to have the desired effect : Who can tell me what I am doing wrong or if there is an easier way ? <code> [ XmlRoot ( `` example '' ) ] public class Example { [ XmlElement ( `` exampleText '' ) ] public string ExampleText { get ; set ; } } < example > < exampleText > Some text < /exampleText > < /example > [ XmlRoot ( `` examples '' ) ] public class ExampleWrapper : ICollection < Example > { [ XmlElement ( `` example '' ) ] public List < Example > innerList ; //Implementation of ICollection using innerList } < examples > < Example > < exampleText > Some text < /exampleText > < /Example > < Example > < exampleText > Another text < /exampleText > < /Example > < /examples >
XMLSerializer keeps capitalizing items in collection
C_sharp : I have 3 classes that are essentially the same but do n't implement an interface because they all come from different web services . e.g.Service1.Object1Service2.Object1Service3.Object1They all have the same properties and I am writing some code to map them to each other using an intermediary object which implements my own interface IObject1I 've done this using genericsMy client code looks like : What I want to do is get rid of the CheckObject1Types method and use constraints instead so that I get a build error if the types are n't valid , because at the moment I can call this method with any type and the ArgumentException is thrown by the CheckObject1Types method.So I 'd like to do something like : Any ideas ? Edit : I do n't want to change the Reference.cs files for each webservice because all it takes is a team mate to update the web reference and BAM ! broken code . <code> public static T [ ] CreateObject1 < T > ( IObject1 [ ] properties ) where T : class , new ( ) { //Check the type is allowed CheckObject1Types ( `` CreateObject1 < T > ( IObject1 [ ] ) '' , typeof ( T ) ) ; return CreateObjectArray < T > ( properties ) ; } private static void CheckObject1Types ( string method , Type type ) { if ( type == typeof ( Service1.Object1 ) || type == typeof ( Service2.Object1 ) || type == typeof ( Service3.Object1 ) || type == typeof ( Service1.Object1 [ ] ) || type == typeof ( Service2.Object1 [ ] ) || type == typeof ( Service3.Object1 [ ] ) ) { return ; } throw new ArgumentException ( `` Incorrect type passed to ServiceObjectFactory : : '' + method + `` . Type : '' + type.ToString ( ) ) ; } //properties is an array of my intermediary objectsObject1 [ ] props = ServiceObjectFactory.CreateObject1 < Object1 > ( properties ) ; public static T [ ] CreateObject1 < T > ( IObject1 [ ] properties ) where T : class , new ( ) , Service1.Object1|Service2.Object1|Service3.Object1 { return CreateObjectArray < T > ( properties ) ; }
C # Generics : Can I constrain to a set of classes that do n't implement an interface ?
C_sharp : I have a method Parameters : But it returns me `` السبت , 30 ذو الحجة '' . October 1st is Saturday . Why it seems return me September 30 , Saturday ? Anything wrong at my side ? <code> DateToString ( DateTime datetime , string format , CultureInfo cultrueInfo ) { return datetime.ToString ( format , cultureInfo ) ; } datetime : { 10/1/2016 12:00:00 AM } format : `` ddd , dd MMM '' cultureInfo : { ar-SA }
What is expected datetime string for ar-sa culture ?
C_sharp : I 'm calling out to a SOAP service which uses Windows authentication . This is my configuration : And I 'm setting up the credentials manually here , as the user is on a different domain : I 've noticed that every call I do through the client proxy is resulting in three trips : If this only happened on the first call it would n't be so terrible , but it happens on all subsequent calls to the same client proxy instance.The server I 'm calling out to is n't under my control and has a not insignificant amount of latency , so I 'd love to find a way to remove these redundant trips . Is it possible ? <code> new BasicHttpBinding { Security = new BasicHttpSecurity { Mode = BasicHttpSecurityMode.TransportCredentialOnly , Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.Windows } } , } ; client.ClientCredentials.Windows.ClientCredential.Domain = `` ... '' ; client.ClientCredentials.Windows.ClientCredential.UserName = `` ... '' ; client.ClientCredentials.Windows.ClientCredential.Password = `` ... '' ; Request : POST /EndPoint ( no auth ) Response : 401 Unauthorized , WWW-Authenticate : NegotiateRequest : POST /EndPoint , Authorization : NegotiateResponse : 401 Unauthorized , WWW-Authenticate : Negotiate < gunk > Request : Post /EndPoint , Authorization : Negotiate < gunk > Response : 200 OK
Preventing negotiation handshake on subsequent service calls
C_sharp : I ’ m creating a small application ( a phonebook ) , actually I already created it using ms access as a database , but now , I ’ m learning XML and planning to use it as a database for this app ( just for fun and educational purposes ) . Here ’ s the diagram in my access database.And I created two XML files with the same structure as for the two access tables . ContactList TableContactNumbers TableThis is how my simple app should look like : In my original app , I used INNER JOIN statement to retrieve the contact numbers of a particular contact . But now , I have no idea how to do it since I ’ m using 2 XML files as the tables ( corresponding to the two ms access tables ) . Is it still possible to query and link these two XML files and achieved the same functionality as my first application ( using access ) version does ? For now , this is what I only have : <code> < ? xml version= '' 1.0 '' standalone= '' yes '' ? > < ContactList > < xs : schema id= '' ContactList '' xmlns= '' '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' xmlns : msdata= '' urn : schemas-microsoft-com : xml-msdata '' > < xs : element name= '' ContactList '' msdata : IsDataSet= '' true '' msdata : UseCurrentLocale= '' true '' > < xs : complexType > < xs : choice minOccurs= '' 0 '' maxOccurs= '' unbounded '' > < xs : element name= '' Contact '' > < xs : complexType > < xs : sequence > < xs : element name= '' ContactID '' type= '' xs : int '' minOccurs= '' 0 '' / > < xs : element name= '' Name '' type= '' xs : string '' minOccurs= '' 0 '' / > < /xs : sequence > < /xs : complexType > < /xs : element > < /xs : choice > < /xs : complexType > < /xs : element > < /xs : schema > < Contact > < ContactID > 1 < /ContactID > < Name > Peter < /Name > < /Contact > < Contact > < ContactID > 2 < /ContactID > < Name > John < /Name > < /Contact > < /ContactList > < ? xml version= '' 1.0 '' standalone= '' yes '' ? > < ContactNumbers > < xs : schema id= '' ContactNumbers '' xmlns= '' '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' xmlns : msdata= '' urn : schemas-microsoft-com : xml-msdata '' > < xs : element name= '' ContactNumbers '' msdata : IsDataSet= '' true '' msdata : UseCurrentLocale= '' true '' > < xs : complexType > < xs : choice minOccurs= '' 0 '' maxOccurs= '' unbounded '' > < xs : element name= '' Numbers '' > < xs : complexType > < xs : sequence > < xs : element name= '' ContactID '' type= '' xs : int '' minOccurs= '' 0 '' / > < xs : element name= '' Mobile '' type= '' xs : string '' minOccurs= '' 0 '' / > < xs : element name= '' Office '' type= '' xs : string '' minOccurs= '' 0 '' / > < xs : element name= '' Home '' type= '' xs : string '' minOccurs= '' 0 '' / > < /xs : sequence > < /xs : complexType > < /xs : element > < /xs : choice > < /xs : complexType > < /xs : element > < /xs : schema > < Numbers > < ContactID > 1 < /ContactID > < Mobile > +63-9277-392607 < /Mobile > < Office > 02-890-2345 < /Office > < Home > 0 < /Home > < /Numbers > < Numbers > < ContactID > 2 < /ContactID > < Mobile > +62-9277-392607 < /Mobile > < Office > 02-890-2345 < /Office > < Home > 1 < /Home > < /Numbers > < /ContactNumbers > using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace TestXML { public partial class Form1 : Form { OpenFileDialog openFileDialog1 = new OpenFileDialog ( ) ; DataSet ds = new DataSet ( ) ; DataView dv = new DataView ( ) ; public Form1 ( ) { InitializeComponent ( ) ; } private void btnBrowse_Click ( object sender , EventArgs e ) { try { openFileDialog1.Filter = `` XML Document ( *.xml ) |*.xml '' ; openFileDialog1.FileName = `` '' ; openFileDialog1.InitialDirectory = Environment.GetFolderPath ( Environment.SpecialFolder.MyDocuments ) ; if ( openFileDialog1.ShowDialog ( ) == DialogResult.OK ) { txtDirectory.Text = openFileDialog1.FileName ; btnLoad.Enabled = true ; } } catch ( Exception x ) { btnLoad.Enabled = false ; MessageBox.Show ( `` Something went wrong ! \n '' + x.Message , `` Ooops ! `` , MessageBoxButtons.OK , MessageBoxIcon.Exclamation ) ; } } private void btnLoad_Click ( object sender , EventArgs e ) { dgContactList.DataSource = LoadXML ( ) ; } private DataView LoadXML ( ) { try { ds.Clear ( ) ; ds.ReadXml ( txtDirectory.Text , XmlReadMode.ReadSchema ) ; dv = ds.Tables [ 0 ] .DefaultView ; lblStatus.Text = `` XML is loaded successfully '' ; } catch ( Exception x ) { MessageBox.Show ( `` Something went wrong ! \n '' + x.Message , `` Ooops ! `` , MessageBoxButtons.OK , MessageBoxIcon.Exclamation ) ; lblStatus.Text = `` '' ; } return dv ; } } }
How to query this two XML files using C # ?
C_sharp : I do n't understand why the following behaves the way it does at all . I do n't even know if it 's caused by hiding or something else.The questions are : Why does c.c ( ) produce System.String while c.b ( ) produces System.Int32 ? Why does d.d ( ) and d.b ( ) both produce System.String and not behave in exactly the same way as the class C ? <code> class A < T > { public class B : A < int > { public void b ( ) { Console.WriteLine ( typeof ( T ) .ToString ( ) ) ; } public class C : B { public void c ( ) { Console.WriteLine ( typeof ( T ) .ToString ( ) ) ; } } public class D : A < T > .B { public void d ( ) { Console.WriteLine ( typeof ( T ) .ToString ( ) ) ; } } } } class Program { static void Main ( string [ ] args ) { A < string > .B.C c = new A < string > .B.C ( ) ; A < string > .B.D d = new A < string > .B.D ( ) ; c.c ( ) ; c.b ( ) ; d.d ( ) ; d.b ( ) ; } }
typeof ( T ) within generic nested types
C_sharp : All , I have a method that returns a List . This method is used to return the parameters of SQL StoredProcedures , Views and Functions depending on name . What I want to do is create a list of objects and return this list to the caller . The method is belowI clearly ca n't instantiate T via new and pass to the constructor , but it should be clear what I am attempting to do . Is there a way to do what I want with out three additional methods ? Note . The main issue is that the number of parameters I am passing to T can either be two OR three.Thanks for your time.Edit : The structs I use are as follows <code> private List < T > GetInputParameters < T > ( string spFunViewName ) { string strSql = String.Format ( `` SELECT PARAMETER_NAME , DATA_TYPE FROM INFORMATION_SCHEMA.PARAMETERS `` + `` WHERE SPECIFIC_NAME = ' { 0 } ' AND PARAMETER_MODE = 'IN ' ; '' , spFunViewName ) ; List < string [ ] > paramInfoList = new List < string [ ] > ( ) ; DataTable paramDt = Utilities.DTFromDB ( conn , `` InputParmaters '' , strSql ) ; if ( paramDt ! = null ) { Converter < DataRow , string [ ] > rowConverter = new Converter < DataRow , string [ ] > ( Utilities.RowColConvert ) ; paramInfoList = Utilities.ConvertRowsToList < string [ ] > ( paramDt , rowConverter ) ; } else return null ; // Build the input parameter list . List < T > paramList = new List < T > ( ) ; foreach ( string [ ] paramInfo in paramInfoList ) { T t = new T ( paramInfo [ NAME ] , paramInfo [ TYPE ] , Convert.ToInt32 ( paramInfo [ CHARMAXLEN ] ) ) ; columnList.Add ( column ) ; } return columnList ; } public struct Database { public string name { get ; set ; } public string filename { get ; set ; } public List < Table > tables { get ; set ; } public List < StoredProcedure > sps { get ; set ; } public List < Function > funcs { get ; set ; } public List < View > views { get ; set ; } public Database ( string name , string filename ) { this.name = name ; this.filename = filename ; } } protected internal struct StoredProcedure { public string name { get ; set ; } public List < string [ ] > parameters { get ; set ; } public StoredProcedure ( string name , List < string [ ] > parameters ) { this.name = name ; this.parameters = parameters ; } } protected internal struct Function { public string name { get ; set ; } public string output { get ; set ; } public List < string [ ] > parameters { get ; set ; } public Function ( string name , string output , List < string [ ] > parameters ) { this.name = name ; this.output = output ; this.parameters = parameters ; } } protected internal struct View { public string name { get ; set ; } public List < string [ ] > parameters { get ; set ; } public View ( string name , List < string [ ] > parameters ) { this.name = name ; this.parameters = parameters ; } }
C # Generics Instantiation
C_sharp : I have a set of data that contains a type , a date , and a value.I want to group by the type , and for each set of values in each group I want to pick the one with the newest date.Here is some code that works and gives the correct result , but I want to do it all in one linq query rather than in the iteration . Any ideas how I can achieve the same result as this with purely a linq query ... ? <code> using System ; using System.Linq ; using System.Collections.Generic ; public class Program { public static void Main ( ) { var mydata = new List < Item > { new Item { Type = `` A '' , Date = DateTime.Parse ( `` 2016/08/11 '' ) , Value = 1 } , new Item { Type = `` A '' , Date = DateTime.Parse ( `` 2016/08/12 '' ) , Value = 2 } , new Item { Type = `` B '' , Date = DateTime.Parse ( `` 2016/08/20 '' ) , Value = 3 } , new Item { Type = `` A '' , Date = DateTime.Parse ( `` 2016/08/09 '' ) , Value = 4 } , new Item { Type = `` A '' , Date = DateTime.Parse ( `` 2016/08/08 '' ) , Value = 5 } , new Item { Type = `` C '' , Date = DateTime.Parse ( `` 2016/08/17 '' ) , Value = 6 } , new Item { Type = `` B '' , Date = DateTime.Parse ( `` 2016/08/30 '' ) , Value = 7 } , new Item { Type = `` B '' , Date = DateTime.Parse ( `` 2016/08/18 '' ) , Value = 8 } , } ; var data = mydata.GroupBy ( _ = > _.Type ) ; foreach ( var thing in data ) { # region // How can I remove this section and make it part of the group by query above ... ? var subset = thing.OrderByDescending ( _ = > _.Date ) ; var top = subset.First ( ) ; # endregion Console.WriteLine ( $ '' { thing.Key } { top.Date.ToString ( `` yyyy-MM-dd '' ) } { top.Value } '' ) ; } } public class Item { public string Type { get ; set ; } public DateTime Date { get ; set ; } public int Value { get ; set ; } } } // Output : // A 2016-08-12 2// B 2016-08-30 7// C 2016-08-17 6
How do I order the elements in a group by linq query , and pick the first ?
C_sharp : Imagine two bitmasks , I 'll just use 8 bits for simplicity : The 2nd , 4th , and 6th bits are both 1 . I want to pick one of those common `` on '' bits at random . But I want to do this in O ( 1 ) .The only way I 've found to do this so far is pick a random `` on '' bit in one , then check the other to see if it 's also on , then repeat until I find a match . This is still O ( n ) , and in my case the majority of the bits are off in both masks . I do of course & them together to initially check if there 's any common bits at all.Is there a way to do this ? If so , I can increase the speed of my function by around 6 % . I 'm using C # if that matters . Thanks ! Mike <code> 0110101010111011
Need a way to pick a common bit in two bitmasks at random
C_sharp : I currently have a query which not takes a long time and sometimes crashes because of the amount of data in the database.Can someone notice anything i can do to help speed it up ? EDITIve cut the query down . But even this is performing now worse than before ? <code> public IList < Report > GetReport ( CmsEntities context , long manufacturerId , long ? regionId , long ? vehicleTypeId ) { var now = DateTime.Now ; var today = new DateTime ( now.Year , now.Month , 1 ) ; var date1monthago = today.AddMonths ( -1 ) ; var date2monthago = today.AddMonths ( -2 ) ; var date3monthago = today.AddMonths ( -3 ) ; var date4monthago = today.AddMonths ( -4 ) ; var date5monthago = today.AddMonths ( -5 ) ; var date6monthago = today.AddMonths ( -6 ) ; today = TimeManager.EndOfDay ( new DateTime ( now.AddMonths ( -1 ) .Year , today.AddMonths ( -1 ) .Month , DateTime.DaysInMonth ( now.Year , today.AddMonths ( -1 ) .Month ) ) ) ; var query = from item in context.Invoices where item.Repair.Job.Bodyshop.Manufacturer2Bodyshop.Select ( x = > x.ManufacturerId ) .Contains ( manufacturerId ) & & ( item.InvoiceDate > = date6monthago & & item.InvoiceDate < = today ) & & ( regionId.HasValue & & regionId.Value > 0 ? item.Repair.Job.Bodyshop.Manufacturer2Bodyshop.Select ( x = > x.RegionId ) .Contains ( regionId.Value ) : true ) & & ( item.InvType == `` I '' || item.InvType == null ) & & ( vehicleTypeId.HasValue & & vehicleTypeId.Value > 0 ? item.Repair.Job.Vehicle.Model.VehicleTypes.Select ( x = > x.Id ) .Contains ( vehicleTypeId.Value ) : true ) select item ; var query2 = from item in query group item by new { item.Repair.Job.Bodyshop } into g let manufJobs = query.Where ( x = > x.Repair.Job.Vehicle.Model.ManufacturerId == manufacturerId & & x.Repair.Job.BodyshopId == g.Key.Bodyshop.Id ) let allJobs = query.Where ( x = > x.Repair.Job.BodyshopId == g.Key.Bodyshop.Id ) select new tReport { MonthSixManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date6monthago.Month & & x.InvoiceDate.Year == date6monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthSixJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date6monthago.Month & & x.InvoiceDate.Year == date6monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthFiveManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date5monthago.Month & & x.InvoiceDate.Year == date5monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthFiveJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date5monthago.Month & & x.InvoiceDate.Year == date5monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthFourManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date4monthago.Month & & x.InvoiceDate.Year == date4monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthFourJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date4monthago.Month & & x.InvoiceDate.Year == date4monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthThreeManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date3monthago.Month & & x.InvoiceDate.Year == date3monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthThreeJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date3monthago.Month & & x.InvoiceDate.Year == date3monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthTwoManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date2monthago.Month & & x.InvoiceDate.Year == date2monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthTwoJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date2monthago.Month & & x.InvoiceDate.Year == date2monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthOneManufJobTotal = manufJobs.Where ( x = > x.InvoiceDate.Month == date1monthago.Month & & x.InvoiceDate.Year == date1monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , MonthOneJobTotal = allJobs.Where ( x = > x.InvoiceDate.Month == date1monthago.Month & & x.InvoiceDate.Year == date1monthago.Year ) .GroupBy ( x = > x.Repair.Job ) .Count ( ) , ManufTotal = manufJobs.GroupBy ( x = > x.Repair.Job ) .Count ( ) , Total = allJobs.GroupBy ( x = > x.Repair.Job ) .Count ( ) , PercentageOf = ( ( decimal ) manufJobs.GroupBy ( x = > x.Repair.Job ) .Count ( ) / ( decimal ) allJobs.GroupBy ( x = > x.Repair.Job ) .Count ( ) ) * 100 } ; return query2.OrderBy ( x = > x ) .ToList ( ) ; } var query = from item in context.Invoices.AsNoTracking ( ) where item.Repair.Job.Bodyshop.Manufacturer2Bodyshop.Any ( x = > x.ManufacturerId == manufacturerId ) & & ( item.InvoiceDate > = date12monthago & & item.InvoiceDate < = today ) & & ( item.InvType == `` I '' || item.InvType == null ) select item ; if ( regionId.HasValue & & regionId.Value > 0 ) { query = query.Where ( item = > item.Repair.Job.Bodyshop.Manufacturer2Bodyshop.Select ( x = > x.RegionId ) .Contains ( regionId.Value ) ) ; } if ( vehicleTypeId.HasValue & & vehicleTypeId.Value > 0 ) { query = query.Where ( item = > item.Repair.Job.Vehicle.Model.VehicleTypes.Select ( x = > x.Id ) .Contains ( vehicleTypeId.Value ) ) ; } var query2 = from item in hey group item by new { item.Repair.Job.Bodyshop , item.InvoiceDate.Month } into m select new TReport { Bodyshop = m.Key.Bodyshop.Name , Bays = m.Key.Bodyshop.Bays , Region = m.Key.Bodyshop.Manufacturer2Bodyshop.FirstOrDefault ( x = > x.ManufacturerId == manufacturerId ) .Region.Name , BodyshopCode = m.Key.Bodyshop.Manufacturer2Bodyshop.FirstOrDefault ( x = > x.ManufacturerId == manufacturerId ) .BodyshopCode , Total = m.Count ( ) , ManufTotal = m.Where ( x = > x.Repair.Job.Vehicle.Model.ManufacturerId == manufacturerId ) .Count ( ) , Totals = m.GroupBy ( j = > j.InvoiceDate.Month ) .Select ( j = > new TPercentReportInner { Month = j.Key , ManufTotal = j.Where ( x = > x.Repair.Job.Vehicle.Model.ManufacturerId == manufacturerId ) .Count ( ) , AllTotal = j.Count ( ) } ) } ;
Speeding up a linq entitiy query
C_sharp : How can I get class semantic model ( ITypeSymbol ) from ClassDeclarationSyntax in Roslyn ? From this syntax tree : it seems to me that the only point I can use is ClassDeclaration as tokens like IdentifierToken can not be passed to the GetSymbolInfo method . But when I writethe result is ... so no match . I wonder if the problem is that I am asking for wrong syntax element , or the issue is in fact I am asking in the moment I analyze attribute of the class and the class itself is not yet prepared . <code> context.SemanticModel.GetSymbolInfo ( classDeclaration ) context.SemanticModel.GetSymbolInfo ( classDeclaration ) { Microsoft.CodeAnalysis.SymbolInfo } CandidateReason : None CandidateSymbols : Length = 0 IsEmpty : true Symbol : null _candidateSymbols : Length = 0
How to get class semantic model from class syntax tree ?
C_sharp : I have used two project for my site . One for Mvc project and Api project.I have added below code in web.config file which is in Api project , Action method as below which is in Api project , and ajax call as below which is in Mvc project , But yet showing errors as below , OPTIONS http : //localhost:55016/api/ajaxapi/caselistmethod 405 ( Method Not Allowed ) XMLHttpRequest can not load http : //localhost:55016/api/ajaxapi/caselistmethod . Response for preflight has invalid HTTP status code 405but without Header its working fine . I need to pass header also . So please give any suggestion.Thanks ... <code> Access-Control-Allow-Origin : *Access-Control-Allow-Methods : GET , POST , PUT , DELETEAccess-Control-Allow-Headers : Authorization [ HttpPost ] [ Route ( `` api/ajaxapi/caselistmethod '' ) ] public List < CaseValues > AjaxCaseListMethod ( ) { List < CaseValues > caseList = new List < CaseValues > ( ) ; return caseList ; } $ .ajax ( { type : `` POST '' , url : `` http : //localhost:55016/api/ajaxapi/caselistmethod '' , beforeSend : function ( request ) { request.setRequestHeader ( `` Authorization '' , getCookie ( `` Token '' ) ) ; } , success : function ( response ) { } } ) ;
Header ca n't pass in ajax using cross domain
C_sharp : I 'm trying to position a rectangle in the center of a grid with a restricted height , like so : I 've expected it to look like that : But instead it looks like that : I know the my child rectangle is bigger and it is understandable that it clips , however , my ClipToBounds have no effect of anything . After reading around , I found that indeed Grid does not respect `` ClipToBounds '' .I tried to use Canvas , as suggested in the aforementioned article by Dr.Wpf but I ca n't seem to get it right.Is there anything I can do to make it look like the 1st picture , without resorting to C # code ? Thanks ! <code> < Grid ClipToBounds= '' False '' > < Grid Background= '' LightBlue '' Height= '' 10 '' ClipToBounds= '' False '' Margin= '' 0,27,0,79 '' > < Rectangle Height= '' 40 '' Width= '' 20 '' Fill= '' Black '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' ClipToBounds= '' False '' / > < /Grid > < /Grid >
Centering a large rectangle inside a grid which dimensions are smaller ( and ClipToBounds does n't work )
C_sharp : This code resizes an image and saves it to disk.But if I want to use the graphics class to set the interpolation , how do I save it ? The graphics class has a save method , but it does n't take any parameters . How do I save it to disk like the bitmap ? Heres a modified code snippet : I just need to set the interpolation and then save it to disk . <code> using ( var medBitmap = new Bitmap ( fullSizeImage , newImageW , newImageH ) ) { medBitmap.Save ( HttpContext.Current.Server.MapPath ( `` ~/Media/Items/Images/ '' + itemId + `` .jpg '' ) , ImageFormat.Jpeg ) ; } using ( var medBitmap = new Bitmap ( fullSizeImage , newImageW , newImageH ) ) { var g = Graphics.FromImage ( medBitmap ) ; g.InterpolationMode = InterpolationMode.HighQualityBicubic ; //What do I do now ? medBitmap.Save ( HttpContext.Current.Server.MapPath ( `` ~/Media/Items/Images/ '' + itemId + `` .jpg '' ) , ImageFormat.Jpeg ) ; }
How to save a bitmap after setting interpolation with graphics class
C_sharp : I am looking at code that is essentially passing an id around , for example : But instead of using an int , it used a PersonId object.The PersonId object is just an int with some hand-cranked code to make it nullable . So was this created in old .NET when nullable ints were n't available or is there a higher purpose for wrapping simple types in a class ? <code> GetPersonById ( int personId ) GetPersonById ( PersonId personId ) public sealed class PersonId { private PersonId ( ) { _isNull = true ; _value = 0 ; } private PersonId ( int value ) { _isNull = false ; _value = value ; } // and so on ! }
What benefit is there in wrapping a simple type in a class ?
C_sharp : Consider this snippet of code : In the above code , I can not delete the `` else return ( false ) '' statement - the compiler warns that not all code paths return a value . But in the following code , which uses a lambda ... I do not have to have an `` else '' statement - there are no compiler warnings and the logic works as expected . What mechanism is at play here to make me not have an `` else '' statement in my lambda ? <code> Func < int , bool > TestGreaterThanOne = delegate ( int a ) { if ( a > 1 ) return ( true ) ; else return ( false ) ; } ; Func < int , bool > TestGreaterThanOne = a = > a > 1 ;
Why do lambdas in c # seem to handle boolean return values differently ?
C_sharp : I wonder if there is a way , in C # , to have a type based on a primitive type , and duplicate it to use other primitives instead.I know it 's not very clear , I do n't really know how to explain this ( and english is not my mother-tongue , sorry for that ... ) , so I 'll try to explain it using pseudo-code.A quick example : The problem is that I 'd like to have a float and a int32 version of this type.What i 'm doing actually ( valid C # code ) : It works but it 's not `` sexy '' , and in case of extensive casts using the AsXXX methods , there will inevitably be an impact on performances.Ideally , I would have arithmetics methodes on all of three types , but it would be a pain to maintain ... What would be the ideal solution ( pseudo-code , not valid C # ) : I know this is n't possible in C # for the moment , but here is the true question : Do you have any idea on how to nicely and efficiently handle this ? What I 've been thinking to ( pseudo-code , not valid C # ) : That way , I would n't have duplicated code , easier to maintainWaiting for your ideas : ) PS : If a moderator have ideas on how to better format my question , feel free to edit it : ) <code> public struct Vector2d { public double X ; public double Y ; //Arithmetic methods : Length , normalize , rotate , operators overloads , etc ... } //This type contains all useful methodspublic struct Vector2d { public float X ; public float Y ; public Vector2f AsFloat ( ) { return new Vector2f ( ( float ) X , ( float ) Y ) ; } public Vector2f AsInteger ( ) { return new Vector2i ( ( int ) X , ( int ) Y ) ; } //Arithmetic methods } //These types are only here to be casted from/to , all the arithmetics methods are on the double-based typepublic struct Vector2f { public float X ; public float Y ; public Vector2f AsDouble ( ) { return new Vector2d ( X , Y ) ; } public Vector2f AsInteger ( ) { return new Vector2i ( ( int ) X , ( int ) Y ) ; } } public struct Vector2i { public int X ; public int Y ; public Vector2f AsFloat ( ) { return new Vector2f ( X , Y ) ; } public Vector2f AsDouble ( ) { return new Vector2d ( X , Y ) ; } } public struct Vector2 < T > where T : numeric { public T X ; public T Y ; public T Length { return ( T ) Math.Sqrt ( X * X + Y * Y ) ; } //Other arithmetic methods } //The TYPE defined constant should be used by Vector2Body instead of plain typed `` double '' , `` float '' , etc ... public struct Vector2d { # define TYPE double # import Vector2Body } public struct Vector2f { # define TYPE float # import Vector2Body } public struct Vector2i { # define TYPE int # import Vector2Body }
Discussion on generic numeric type in C #
C_sharp : I´m creating an application that converts text to Braille . Converting to Braille is not a problem , but I don´t know how to convert it back.Example 1 : Converting numbers to Braille Example 2 : Converting capitals to BrailleI have a problem converting Braille back to normal . I ca n't just convert every a to 1 and so on . The numbers can be checked by the # and then change the chars after it to the next space , but I dont know how . The comma before the letter is harder to separate from other commas in the text.Here is my class for converting to braille : <code> 1 = # a123 = # abc12 45 = # ab # de Jonas = , jonasJONAS = , ,jonas using System ; using System.Collections.Generic ; using System.Text ; using System.Drawing ; namespace BrailleConverter { class convertingBraille { public Font getIndexBrailleFont ( ) { return new Font ( `` Index Braille Font '' , ( float ) 28.5 , FontStyle.Regular ) ; } public Font getPrintableFontToEmbosser ( ) { return new Font ( `` Lucida Console '' , ( float ) 28.5 , FontStyle.Regular ) ; //return new Font ( `` Index Black Text Font '' , ( float ) 28.5 , FontStyle.Regular ) ; } public string convertCapitalsToUnderscore ( string text ) { if ( string.IsNullOrEmpty ( text ) ) { return `` '' ; } text = `` `` + text ; text = text.Replace ( ' . ' , '\ '' ) ; text = text.Replace ( ' , ' , ' 1 ' ) ; text = text.Replace ( ' ? ' , ' 5 ' ) ; text = text.Replace ( ' ! ' , ' 6 ' ) ; text = text.Replace ( ' : ' , ' 3 ' ) ; text = text.Replace ( '= ' , ' 7 ' ) ; text = text.Replace ( '+ ' , ' 4 ' ) ; text = text.Replace ( '* ' , ' 9 ' ) ; text = text.Replace ( ' é ' , '= ' ) ; StringBuilder newText = new StringBuilder ( text.Length * 2 ) ; newText.Append ( text [ 0 ] ) ; bool firstCapLetterInWord = true ; for ( int i = 1 ; i < text.Length ; i++ ) { char letter = text [ i ] ; // Aktuell bokstav char nextLetter = ' ' ; // Nästa bokstav try { nextLetter = text [ i + 1 ] ; } catch { } // Är det stor bokstav ? if ( char.IsUpper ( letter ) ) { // Är nästa bokstav stor ? if ( char.IsUpper ( nextLetter ) ) { // Är det början av ett helt ord med caps ? if ( firstCapLetterInWord ) { newText.Append ( `` , , '' ) ; // 2 st understräck framför ordet firstCapLetterInWord = false ; // Ändra så att inte nästa bokstav får 2 st understräck } } else // Annars bara ett understräck { if ( firstCapLetterInWord ) { newText.Append ( `` , '' ) ; // Sätt understräck framför bokstav } firstCapLetterInWord = true ; // Förbereda för nästa capsord } } newText.Append ( text [ i ] ) ; } string finishedText = newText.ToString ( ) .TrimStart ( ) ; // Ta bort mellanslaget i början finishedText = finishedText.ToLower ( ) ; finishedText = finishedText.Replace ( ' å ' , '* ' ) ; finishedText = finishedText.Replace ( ' ä ' , ' > ' ) ; finishedText = finishedText.Replace ( ' ö ' , ' [ ' ) ; return finishedText ; } public string convertNumbersToBrailleNumbers ( string text ) { if ( string.IsNullOrEmpty ( text ) ) { return `` '' ; } text = `` `` + text ; StringBuilder newText = new StringBuilder ( text.Length * 2 ) ; newText.Append ( text [ 0 ] ) ; bool firstNumberInNumber = true ; for ( int i = 1 ; i < text.Length ; i++ ) { char letter = text [ i ] ; // Aktuell tecken char nextLetter = ' ' ; // Nästa tecken try { nextLetter = text [ i + 1 ] ; } catch { } char convertedChar = text [ i ] ; // Är tecknet en siffra ? if ( char.IsNumber ( letter ) ) { // Är nästa tecken en siffra ? if ( char.IsNumber ( nextLetter ) ) { // Är det början av ett flertaligt nummer ? if ( firstNumberInNumber ) { newText.Append ( ' # ' ) ; // Brädkors framför nummret firstNumberInNumber = false ; // Ändra så att inte nästa siffra får brädkors } } else // Annars bara ett understräck { if ( firstNumberInNumber ) { newText.Append ( ' # ' ) ; // Sätt brädkors framför siffran } firstNumberInNumber = true ; // Förbereda för nästa flertaliga nummer } } newText.Append ( convertedChar ) ; } string finishedText = newText.ToString ( ) .TrimStart ( ) ; finishedText = finishedText.Replace ( ' 1 ' , ' a ' ) ; finishedText = finishedText.Replace ( ' 2 ' , ' b ' ) ; finishedText = finishedText.Replace ( ' 3 ' , ' c ' ) ; finishedText = finishedText.Replace ( ' 4 ' , 'd ' ) ; finishedText = finishedText.Replace ( ' 5 ' , ' e ' ) ; finishedText = finishedText.Replace ( ' 6 ' , ' f ' ) ; finishedText = finishedText.Replace ( ' 7 ' , ' g ' ) ; finishedText = finishedText.Replace ( ' 8 ' , ' h ' ) ; finishedText = finishedText.Replace ( ' 9 ' , ' i ' ) ; finishedText = finishedText.Replace ( ' 0 ' , ' j ' ) ; return finishedText ; } public string convertBackToPrint ( string oldText ) { string newText = oldText.Replace ( `` , '' , `` '' ) ; newText = newText.Replace ( `` # '' , `` '' ) ; newText = newText.Replace ( `` * '' , `` å '' ) ; newText = newText.Replace ( `` > '' , `` ä '' ) ; newText = newText.Replace ( `` [ `` , `` ö '' ) ; newText = newText.Replace ( '\ '' , ' . ' ) ; newText = newText.Replace ( ' 1 ' , ' , ' ) ; newText = newText.Replace ( ' 5 ' , ' ? ' ) ; newText = newText.Replace ( ' 6 ' , ' ! ' ) ; newText = newText.Replace ( ' 3 ' , ' : ' ) ; newText = newText.Replace ( ' 7 ' , '= ' ) ; newText = newText.Replace ( ' 4 ' , '+ ' ) ; newText = newText.Replace ( ' 9 ' , '* ' ) ; newText = newText.Replace ( '= ' , ' é ' ) ; return newText ; } } }
Replace numbers of char after a specific char
C_sharp : Is it possible , without employing pinvoke , to restart a PC using .NET ? I kind of just repeated the title , but I 'm not too sure how to elaborate much further ! Edit : I should have mentioned that do n't want to use `` shutdown -r '' as a solution.I was really after a pure .NET way , something like : Environment.ShutDown ( ) ; In other words , something that is maintained with .NET as new versions of Windows arise.Edit 2 : Please stop asking `` what 's wrong with p/invoke '' . Those sort of answers are exactly what SO users seem to love ; the supposed `` lateral '' approach to answering a question . However , although there is no real problem with p/invoke and I will happily use it , what on earth is wrong with asking if .NET has a more official way of achieving something ? If it 's in .NET then any API changes between OSes will ( most likely ) get reflected . Whatever the reason , it 's not a crime to seek to minimise DLL import usage is it ? I 'm sure if I included something in a question like : And you could just do : Everyone one here would scream : `` what is wrong with using SomeNamespace.ClimbWall ( ) ; ? ? `` Sigh . <code> [ DllImport ( `` something32.dll '' ) ] static extern int ClimbWall32Ex ( IntPtr32 blah ) ; SomeNamespace.ClimbWall ( ) ;
Is it possible to restart a PC using `` pure '' .NET and *without* using p/invoke ?
C_sharp : I am trying to design a browser that will fetch site updates programmatically . I am trying to do this with async/await methods but when I try and run the program it seems to just hang on response.Wait ( ) ; . not sure why or whats happening . browser class : :Also , for my intended purposes , is it ok to make browser a static function , or does that not make sense ? Sorry for the questions , new to c # <code> public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; var urls = sourceUrls ( ) ; Task < HttpResponseMessage > response = login ( urls [ 0 ] ) ; response.Wait ( ) ; Console.Write ( `` Complete '' ) ; } private List < Site > sourceUrls ( ) { var urls = new List < Site > ( ) ; urls.Add ( new Site ( `` http : //yahoo.com '' , `` test '' , `` test '' ) ) ; return urls ; } } static public class Browser { private static CookieContainer cc = new CookieContainer ( ) ; private static HttpClientHandler handler = new HttpClientHandler ( ) ; public static HttpClient browser = new HttpClient ( handler ) ; static Browser ( ) { handler.CookieContainer = cc ; } static public async Task < HttpResponseMessage > login ( Site site ) { var _postData = new Dictionary < string , string > { { `` test '' , `` test '' } } ; FormUrlEncodedContent postData = new FormUrlEncodedContent ( _postData ) ; HttpResponseMessage response = await browser.PostAsync ( site.url , postData ) ; return response ; } }
async httpclient operation
C_sharp : What 's the best way to convert the quotient of two C # BigIntegers while retaining as much precision as possible ? My current solution is : I 'm guessing this is suboptimal . <code> Math.Exp ( BigInteger.Log ( dividend ) - BigInteger.Log ( divisor ) ) ;
Getting quotient of two BigIntegers as double
C_sharp : When I debug/run , using IIS Express , and browse to http : //localhost:1234/People , IIS Express tries to browse the People directory instead of executing the People route , and I get a 403.14 HTTP error . So I disabled the StaticFile handler in the Web.config and refreshed . Now I get a 404.4 HTTP error : I know that the route works because if I rename the RoutePrefix , e.g . PeopleTest , then the route is executed and I get the response I expect.How can I convince IIS/Express to prefer MVC routes over static files/directories ? I am using attribute routing ; the relevant code is below : Web.configGlobal.asaxStartup\WebApiConfigPeople\PeopleControllerNote that since I 'm using attribute routing , I am using a non-standard folder structure . E.g . I do n't have the Controllers/Models/Views folders , instead I have root folders for each business area ( e.g . ~\People contains the controllers/models/etc . for the `` People '' business area ) .What I 've TriedSetting RAMMFAR.Removing and re-adding ExtensionlessUrlHandler-Integrated-4.0 . <code> < system.webServer > < modules > < remove name= '' FormsAuthentication '' / > < /modules > < handlers > < remove name= '' ExtensionlessUrlHandler-Integrated-4.0 '' / > < remove name= '' OPTIONSVerbHandler '' / > < remove name= '' TRACEVerbHandler '' / > < remove name= '' StaticFile '' / > < add name= '' ExtensionlessUrlHandler-Integrated-4.0 '' path= '' * . '' verb= '' * '' type= '' System.Web.Handlers.TransferRequestHandler '' preCondition= '' integratedMode , runtimeVersionv4.0 '' / > < /handlers > < /system.webServer > GlobalConfiguration.Configure ( WebApiConfig.Register ) ; FilterConfig.RegisterGlobalFilters ( GlobalFilters.Filters ) ; BundleConfig.RegisterBundles ( BundleTable.Bundles ) ; AutofacConfig.Configure ( ) ; namespace MyApi.Startup { public static class WebApiConfig { public static void Register ( HttpConfiguration config ) { config.MapHttpAttributeRoutes ( ) ; } } } namespace MyApi.People { [ RoutePrefix ( `` People '' ) ] public partial class PagesController : BaseController { [ Route ] [ HttpGet ] [ ResponseType ( typeof ( IEnumerable < Person > ) ) ] public IHttpActionResult Get ( ) { ... } } }
ASP.NET MVC5 refuses to map a route which matches a physical path
C_sharp : I have a List < someObject > and an extention method to someObject called Process.Consider the followingbut I wanted multiple Tasks to work on the same list , to avoid locking I cloned the list and divided it into 2 lists , then started 2 separate Tasks to process , the speed has almost doubled.I was wondering if there are built in things in .NET that could help me achieve such things in a dynamic way and with cleaner syntax ? <code> private void processList ( List < someObject > list ) { Task.Factory.StartNew ( ( ) = > { foreach ( var instance in list ) { instance.Process ( ) ; } } ) ; }
Starting tasks in a dynamic way