lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | 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 clos... | xml.WriteStartElement ( `` payload '' ) ; ThirdPartyLibrary.Serialise ( results , xml ) ; xml.WriteEndElement ( ) ; // < /payload > xml.WriteEndElement ( `` payload '' ) ; | How to check name of element with WriteEndElement |
C# | 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 decorat... | 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# | 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... | < 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 '' >... | Is this the most efficient way to express this XDocument query ? |
C# | 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 ? | 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... | Why is it required to have override keyword in front of abstract methods when we implement them in a child class ? |
C# | 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 : Projectio... | 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 Ord... | c # - Enum description to string with AutoMapper |
C# | 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 c... | 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 IDefaultInte... | How can I call the default method instead of the concrete implementation |
C# | 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 ... | 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.... | Cap string to a certain length directly without a function |
C# | 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 '' | 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.Wr... | Ca n't authenticate using Socketcluster V2 for Coinigy Exchange websocket ticker api |
C# | 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.Op... | 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.OpenAssi... | Switch with enum and multiple return |
C# | 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 I... | 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... | Is abusing IDisposable to benefit from `` using '' statements considered harmful ? |
C# | 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 strin... | A = string.Concat ( `` abc '' , '' def '' ) B = `` abc '' + `` def '' | addition of strings in c # , how the compiler does it ? |
C# | 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.I... | 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... | Compiler replaces explicit cast to my own type with explicit cast to .NET type ? |
C# | 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 R... | 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 al... | Span < T > and friends not working in .NET Native UWP app |
C# | 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 - i... | 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# | 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... | 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.Edit... | CA2227 and ASP.NET Model Binding |
C# | 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 th... | int [ , , ] foo = new int [ , , ] { { { 2 , 3 } , { 3 , 4 } } , { { 3 , 4 } , { 1 , 5 } } } ; | What does double [ , , ] represent ? |
C# | 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 . | 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# | 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 mean... | 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# | Could you please explain the meaning of underscore ( _ ) in the WaitCallBack constructor ? | ThreadPool.QueueUserWorkItem ( new WaitCallback ( ( _ ) = > { MyMethod ( param1 , Param2 ) ; } ) , null ) ; | Meaning of the underscore in WaitCallback |
C# | 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... | 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... | using c # linq to populate/load a list one time to enhance performance |
C# | 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 appl... | 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_Coordina... | Is there a way to declare a Spatial Index with EntityFrameworkCore 2.2 ? |
C# | 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 b... | 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# | 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 th... | 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 ? ... | How to use the same foreach code for 2 collections ? |
C# | 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 ODataConv... | 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 = obj... | Asp.net WebApi OData V4 problems with nested $ expands |
C# | 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 collectio... | 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# | 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 ... | 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# | 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 ... | 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 > heade... | Detecting use of `` dynamic '' keyword as a type parameter at runtime |
C# | 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... | < 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=... | XAML fails to compile , but without any error message , if user-defined object is first resource and followed immediately by x : Array resource |
C# | 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 q... | public struct Vector { private readonly double x , y , z ; ... public static Vector operator + ( Vector v , double d ) { ... } } | Commutativity in operators |
C# | 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 ... | //return geofenceNamesString.Substring ( 0 , 50 ) ; Previous codereturn geofenceNamesString.AsSpan ( ) .Slice ( 0 , 50 ) .ToString ( ) ; | Using Span < T > as a replacement for Substring |
C# | 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 e... | ( 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# | 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 share... | 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# | 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 provid... | services.AddMvc ( ) .AddRazorPagesOptions ( options = > { options.AllowAreas = true ; options.Conventions.AuthorizeAreaFolder ( `` Administration '' , `` /Account '' ) ; options.Conventions.AuthorizeAreaFolder ( `` Production '' , `` /Account '' ) ; options.Conventions.AuthorizeAreaFolder ( `` Robotics '' , `` /Account... | ASP .NET Core Inject Service in custom page filter |
C# | 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... | 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# | 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 doe... | int MyMethod ( int a ) int MyMethod ( int a , string b ) IMyInterface < T > IMyInterface < T1 , T2 > | Generic interface overloading . Valid terminology ? |
C# | 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.. | private void InitializeCommands ( ) { LogoutCommand = new RelayCommand ( Logout ) ; OpenCommand = new RelayCommand ( SetImage ) ; SaveCommand = new RelayCommand ( SaveImage , SaveImageCanExecute ) ; UploadToFlickrCommand = new RelayCommand ( UploadToFlickr ) ; CropCommand = new RelayCommand ( SetCropMouseEvents ) ; Rem... | How can I avoid command clutter in the ViewModel ? |
C# | 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... | 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# | 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 ? | 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# | 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 th... | 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 ... | Nullable reference types unexpected CS8629 Nullable value type may be null with temporary variables |
C# | 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 | 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# | 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 recomm... | 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++ ) { //l... | Parameters in asynchronous lambdas |
C# | 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 ... | 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 ) ;... | MVVM design feels too unwieldy , am I doing it wrong ? |
C# | 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 n... | 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 t... | Wrong logarithm of BigInteger when size of BigInteger exceeds ¼ gigabyte |
C# | 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 | < ? 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=... | sorting entire xdocument based on subnodes |
C# | 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 model... | 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 = EntityReposito... | Logical Inverse of a Func < T , bool > |
C# | 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 troubleshoo... | await connector.Conversations.UpdateActivityAsync ( teamsConversationId , activityId , ( Activity ) messageWithCard ) ; var messageWithText = Activity.CreateMessageActivity ( ) ; messageWithText.ChannelId = teamsConversationId ; messageWithText.Id = activityId ; messageWithText.Type = ActivityTypes.Message ; messageWit... | Teams UpdateActivity events difference when you test in newly created teams |
C# | What are the cons of some code like this : | 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# | 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 ... | [ 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 me... | How can a dispose method be hidden ? |
C# | 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 ... | 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# | 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... | 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# | 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 ? | 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 ... | Optimizing a LINQ reading from System.Diagnostics.EventLog |
C# | 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 ... | 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..cto... | IL Code of an interface |
C# | 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 ..... | 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# | 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 d... | 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# | 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 . | 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# | 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 co... | 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 MoneyExte... | Unexpected effect of implicit cast on delegate type inference |
C# | 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 ? | 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/... | How to make the components , followed by reuse in XAML ? |
C# | 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... | 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/ {... | Can I use Chrome Web Store payments with OAuth 2.0 |
C# | 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 coul... | 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 ) ... | Implementing a `` LazyProperty '' class - is this a good idea ? |
C# | What does if ( ( a & b ) == b ) mean in the following code block ? Why is it not like this ? | 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# | 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 ... | < 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-compatibil... | How to block code flow until an event is fired in C # |
C# | 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 li... | 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 2... | Recognize a Matrix in a group of points |
C# | 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 lib... | > 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 = DiffOu... | How to use Team Foundation 's library to calculate unified diff ? |
C# | 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 a... | 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# | 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 ap... | [ 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 G... | How to move validation handling from a controller action to a decorator |
C# | 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 wh... | 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# | 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 ? | 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# | 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... | 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 ( sec... | Is .NET Thread.Sleep affected by DST ( or system time ) changes ? |
C# | 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 ca... | 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# | 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 ne... | 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# | 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 (... | 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 ( ) .Inclu... | Entity Framework - Different proxy objects for the same entity . And Include behavior with multiple paths to same destination |
C# | 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... | 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 ( ) ''... | How to get the original exception when using ContinueWith ( ) ? |
C# | 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 behavi... | 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.D... | How to reuse a field filter in LINQ to Entities |
C# | 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... | 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 myFS... | Saving FileSystemInfo Array to File |
C# | 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 i... | 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 ( p... | How can I combine this code into one or two LINQ queries ? |
C# | 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 c... | 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 ( ) ; //... | primitive ssh connection ( lowlevel ) |
C# | 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 ... | internal class MyInternalClass { ... } public abstract class MyAbstractClass { protected MyInternalClass myField ; } | Using an internal type used as protected field |
C# | 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 d... | [ 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 '' ) ... | XMLSerializer keeps capitalizing items in collection |
C# | 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... | 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 typ... | C # Generics : Can I constrain to a set of classes that do n't implement an interface ? |
C# | 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 ? | 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# | 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 i... | new BasicHttpBinding { Security = new BasicHttpSecurity { Mode = BasicHttpSecurityMode.TransportCredentialOnly , Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.Windows } } , } ; client.ClientCredentials.Windows.ClientCredential.Domain = `` ... '' ; client.ClientCredentials.Windo... | Preventing negotiation handshake on subsequent service calls |
C# | 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 sa... | < ? 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 : UseCu... | How to query this two XML files using C # ? |
C# | 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 sam... | 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 ( ) ) ; } } }... | typeof ( T ) within generic nested types |
C# | 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 construc... | 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... | C # Generics Instantiation |
C# | 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 ide... | 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 '' ) , Valu... | How do I order the elements in a group by linq query , and pick the first ? |
C# | 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 al... | 0110101010111011 | Need a way to pick a common bit in two bitmasks at random |
C# | 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 ? | 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.... | Speeding up a linq entitiy query |
C# | 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 t... | 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# | 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/... | 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... | Header ca n't pass in ajax using cross domain |
C# | 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 ar... | < 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# | 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 interpolati... | 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 ... | How to save a bitmap after setting interpolation with graphics class |
C# | 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 fo... | 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# | 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 wo... | 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# | 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 exa... | 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 ) ... | Discussion on generic numeric type in C # |
C# | 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 ... | 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 , Font... | Replace numbers of char after a specific char |
C# | 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.Shu... | [ 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# | 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 ... | 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.... | async httpclient operation |
C# | 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 . | Math.Exp ( BigInteger.Log ( dividend ) - BigInteger.Log ( divisor ) ) ; | Getting quotient of two BigIntegers as double |
C# | 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... | < 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= '' ExtensionlessUr... | ASP.NET MVC5 refuses to map a route which matches a physical path |
C# | 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... | private void processList ( List < someObject > list ) { Task.Factory.StartNew ( ( ) = > { foreach ( var instance in list ) { instance.Process ( ) ; } } ) ; } | Starting tasks in a dynamic way |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.