lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a .Net library supplied by a third party . I did reflection on one of their classes and found a member method . The signature was ... So , I wanted to call this method through reflection and got the exception `` ByRef return value not supported in reflection invocation . `` Here is what I 've tried ... I have tr...
Byte & FooBar ( ) var strm = new TheirClass ( ) ; var t = strm.GetType ( ) ; var ms = t.GetMembers ( BindingFlags.Static|BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public ) ; foreach ( var m in ms ) { Debug.WriteLine ( String.Format ( `` Name : { 0 } : { 1 } '' , m.Name , m.ToString ( ) ) ) ; // ... ...
How do I work around the error `` ByRef return value not supported in reflection invocation '' in C # ?
C#
I 'm trying to write a simple program that would connect to remote machines and query the indexing status.Here 's the code that does it on my machine . This works OK.However , when I call GetCatalog on `` mycomputername.SystemIndex '' instead of `` SystemIndex '' , I get An unhandled exception of type 'System.Runtime.I...
using System ; using Microsoft.Search.Interop ; namespace IndexStatus { class Program { static void Main ( string [ ] args ) { CSearchManager manager = new CSearchManager ( ) ; CSearchCatalogManager catalogManager = manager.GetCatalog ( `` SystemIndex '' ) ; _CatalogPausedReason pReason ; _CatalogStatus pStatus ; Conso...
Ca n't query SystemIndex on my own machine when I specify the machine name
C#
I have been through the Identity Server 4 QuickStart for using Entity Framework for persistent storage of configuration and operational data . In the QuickStart , the ApiResources are loaded into the database in code . The Api secret is set with in the ApiResource constructor . When , in Startup.InitializeDatabase , th...
new ApiResource ( `` api1 '' , `` My API '' ) { ApiSecrets = { new Secret ( `` secret '' .Sha256 ( ) ) } } foreach ( var resource in Config.GetApiResources ( ) ) { context.ApiResources.Add ( resource.ToEntity ( ) ) ; } context.SaveChanges ( ) ; K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=
How to insert Identity Server 4 persisted ApiSecret values using T-SQL
C#
We have a Web Service using WebApi 2 , .NET 4.5 on Server 2012 . We were seeing occasional latency increases by 10-30ms with no good reason . We were able to track down the problematic piece of code to LOH and GC.There is some text which we convert to its UTF8 byte representation ( actually , the serialization library ...
public void PerfTestMeasureGetBytes ( ) { var text = File.ReadAllText ( @ '' C : \Temp\ContactsModelsInferences.txt '' ) ; var smallText = text.Substring ( 0 , 85000 + 100 ) ; int count = 1000 ; List < double > latencies = new List < double > ( count ) ; for ( int i = 0 ; i < count ; i++ ) { Stopwatch sw = new Stopwatc...
Extensive use of LOH causes significant performance issue
C#
I 'm writing a library which includes scheduling functionality ( not the standard TaskScheduler , IScheduler ... ) based on .Net Tasks . I 'm using TaskCompletionSource , and Task.Status is critical for representing the status of underlying operations , including TaskStatus.Created , i.e . created but not yet started ....
private TaskCompletionSource < TResult > tcs ; private async Task < TResult > CreateStartCompleteAsync ( ) { await tcs.Task ; if ( tcs.Task.IsCanceled ) { throw new OperationCanceledException ( `` '' ) ; } else if // etc . } public ColdTaskCompletionSource ( ) { tcs = new TaskCompletionSource < TResult > ( ) ; Task = n...
Create ice cold TaskCompletionSource ?
C#
Background : In the spirit of `` program to an interface , not an implementation '' and Haskell type classes , and as a coding experiment , I am thinking about what it would mean to create an API that is principally founded on the combination of interfaces and extension methods . I have two guidelines in mind : Avoid c...
interface IApple { } static void Eat ( this IApple apple ) { Console.WriteLine ( `` Yummy , that was good ! `` ) ; } interface IRottenApple : IApple { } static void Eat ( this IRottenApple apple ) { Console.WriteLine ( `` Eat it yourself , you disgusting human , you ! `` ) ; } sealed class RottenApple : IRottenApple { ...
`` Program to an interface '' using extension methods : When does it go too far ?
C#
I have a Report object that has Recipients property ( of String datatype ) . The Recipients property will hold all the recipients ’ email address in comma separated string . I need to create a “ Collection ” of Email objects from the comma separated string . I have the following code that uses a List of string to get t...
Report report = new Report ( ) ; report.Recipients = `` test @ test.com , demo @ demo.com '' ; List < string > emailAddressList = new List < string > ( report.Recipients.Split ( ' , ' ) ) ; Collection < Email > emailObjectCollection = new Collection < Email > ( ) ; foreach ( string emailAddress in emailAddressList ) { ...
How to avoid redundant List using LINQ
C#
Reference : How can a dynamic be used as a generic ? This enters with CheckEntity ( 16 , '' Container '' ) ; . After the first line runs , AnyObject becomes a blank Assembly.Models.DbModels.Container when inspected with the debugger . If var AnyType = AnyObject.GetType ( ) ; is used , then AnyType shows as Assembly.Mod...
public void CheckEntity ( int entityId , string entityType = null ) { dynamic AnyObject = Activator.CreateInstance ( `` Assembly '' , '' Assembly.Models.DbModels . '' + entityType ) .Unwrap ( ) ; CheckWithInference ( AnyObject , entityId ) ; } private static void CheckWithInference < T > ( T ignored , int entityId ) wh...
GetOriginalTypeParameterType throws Object reference not set to an instance of an object exception
C#
Here comes a silly question . I 'm playing with the parse function of System.Single and it behaves unexpected which might be because I do n't really understand floating-point numbers . The MSDN page of System.Single.MaxValue states that the max value is 3.402823e38 , in standard form that isIf I use this string as an a...
340282300000000000000000000000000000000
Parsing floats with Single.Parse ( )
C#
I am seeking some advice on what is the recommend way to use 'constant ' strings within my classes , e.g.The reason I would like to implement these , i.e . either via a const or via a getter , is because throughout my class ( es ) , I have methods and constructors that use these strings as parameters and I was thinking...
public string EmployeesString { get { return `` Employees '' ; } } const string EmployeeString = `` Employee '' ; DoSomething ( this.EmployeeString , employee ) ;
Design Advice on Getter or Const for String in Classes - what are others doing ?
C#
My following C # code is obviously a hack so how do I capture the index value in the Where method ?
string [ ] IntArray = { `` a '' , `` b '' , `` c '' , `` b '' , `` b '' } ; int index=0 ; var query = IntArray.Where ( ( s , i ) = > ( s== '' b '' ) & ( ( index=i ) ==i ) ) ; // '' & '' and `` ==i '' only exists to return a bool after the assignment ofindex foreach ( string s in query ) { Console.WriteLine ( `` { 0 } i...
Is there a way to capture the index value in a LINQ Where method in C # ?
C#
I have no other developers to ask for advice or `` what do you think - I 'm thinking this '' so please , if you have time , have a read and let me know what you think.It 's easier to show than describe , but the app is essentially like a point of sale app with 3 major parts : Items , OrderItems and the Order.The item c...
public class Item : IComparable < OrderItem > , IEquatable < OrderItem > { public Int32 ID { get ; set ; } public String Description { get ; set ; } public decimal Cost { get ; set ; } public Item ( Int32 id , String description , decimal cost ) { ID = id ; Description = description ; Cost = cost ; } // Extraneous Deta...
Should I incorporate list of fees/discounts into an order class or have them be itemlines
C#
Can someone help me to understand following codeIs it valid to assign a disposing object to MyFont property ?
public Font MyFont { get ; set ; } void AssignFont ( ) { using ( Font f = new Font ( `` Shyam '' ,2 ) ) { this.MyFont = f ; } }
C # using statement more understanding
C#
Consider this MCVE class : When I evaluate and print such an object in C # Interactive , it looks like this : That 's not useful . I 'd like it to look like this : How do I do that ? I 've tried overriding ToString like this : This does n't produce quite what I 'd like : There 's at least three issues with this output ...
public class Foo < T > { private readonly T value ; public Foo ( T value ) { this.value = value ; } } > new Foo < string > ( `` bar '' ) Foo < string > { } Foo < string > { `` bar '' } public override string ToString ( ) { return $ '' Foo { typeof ( T ) } { { { value } } } '' ; } > new Foo < string > ( `` bar '' ) [ Fo...
Custom print of object in C # Interactive
C#
I 'm trying to deep clone an object which contains a System.Random variable . My application must be deterministic and so I need to capture the the random object state . My project is based on .Net Core 2.0.I 'm using some deep clone code from here ( How do you do a deep copy of an object in .NET ( C # specifically ) ?...
using System ; using System.IO ; using System.Runtime.Serialization.Formatters.Binary ; namespace RandomTest { class Program { static void Main ( string [ ] args ) { Container C = new Container ( ) ; Container CopyC = DeepClone ( C ) ; } public static T DeepClone < T > ( T obj ) { using ( var ms = new MemoryStream ( ) ...
Deep clone of System.Random
C#
I want to create a simple ASP.Net form , that will get birth dates.I have a model with this property : and in my view ( is using the datepicker ) : The only one setting on my javascript datepicker is : because I want show dates without times.Now , I ca n't save , because of the validation error : The value '12/23/2000 ...
[ DataType ( DataType.Date ) ] public DateTime ? BirthDate { get ; set ; } @ Html.LabelFor ( model = > model.BirthDate ) @ Html.TextBoxFor ( model = > model.BirthDate , new { @ class = `` form-control date-picker '' } ) @ Html.ValidationMessageFor ( model = > model.BirthDate , `` '' , new { @ class = `` text-danger '' ...
Posting valid DateTimes from anywhere
C#
I 'm using VS2017 on Windows 10 to work on a C # project . It is a really small console app that does nothing but require administrator privileges and then runs an HTA.The code references only these .NET assemblies : Since all of these exist in .NET since 2.0 and forward , it seems it should be possible to create the a...
using System ; using System.Diagnostics ; using System.IO ; < startup useLegacyV2RuntimeActivationPolicy= '' true '' > < supportedRuntime version= '' v2.0.50727 '' / > < supportedRuntime version= '' v4.0 '' / > < /startup >
Create a .NET app that works on any .NET version if only basic requirements
C#
Using Entity Framework one often writes queries such asWhat really makes my stomach churn is the `` Customer '' string argument . I have a hard time believing that EF does not generate table names as constants somewhere . Does anyone know a better approach than to using a string ? for the Include fetch option ?
var orders = from o in context.Orders.Include ( `` Customer '' ) where o.OrderDate.HasValue & & o.OrderDate.Value.Year == 1997 orderby o.Freight select o ;
Entity framework autogenerated table names
C#
Somehow EF disposes the ObjectContext in between two queries , without any further notice , but apparently not randomly and not due to a timeout.I added the using so the example is self contained but it does the same with the DbContext used in the whole application.Notice db is not yet disposed by using so this is out ...
using ( MyDbContext db = new MyDbContext ( ) ) { //I am sure these are unique Employee emp = db.Employees.Single ( e = > e.FirstName == `` Bob '' & & e.LastName == `` Morane '' ) ; Node node = db.Nodes.Single ( n = > n.ShortName == `` stuff '' ) ; //Here the request throws // `` ObjectContext instance has been disposed...
ObjectContext has been disposed throwed by EnsureConnection ( ) in consecutive queries ( No navigation properties used and no using ( ) )
C#
I have a UWP project with two monitors that I want to use to open a new window on a secondary monitor . The application includes three parts : Open Main Page on first monitorCreate new pageOpen on secondary monitorI wrote the first and second parts correctly , but I ca n't find a solution for the third part.Please help...
public sealed partial class MainPage : Page { public MainPage ( ) { this.InitializeComponent ( ) ; //called creat new page function NewWindow ( ) ; } private async void NewWindow ( ) { var myview = CoreApplication.CreateNewView ( ) ; int newid = 0 ; await myview.Dispatcher.RunAsync ( CoreDispatcherPriority.Normal , ( )...
Open new window on secondary monitor in UWP
C#
Here 's a little LinqToSql GOTCHA : Guess what - if you pass a null State object to this method , you get a null reference exception ! It seems that LinqToSql does n't use the || shortcut operator as a shortcut ! Answer credit goes to whoever proposes the best explanation & workaround for this .
// Returns the number of counties in a state , // or all counties in the USA if the state is nullpublic static int CountCounties ( State s ) { var q = from cy in County.GetTable ( ) // my method to get the ITable where ( s == null || s.Code == cy.StateCode ) // shortcut OR operator , right ... ? select cy ; return q.Co...
Conditional shortcuts in LinqToSql query
C#
I am modifying the default analyzer project that comes from the code analyzer template to try and get it to report at all of the declarations for a partial class.I have modified the code to : In two separate files , I have partial classes like this : I put breakpoints on the ReportDiagnostic and am seeing it called for...
public override void Initialize ( AnalysisContext context ) { context.RegisterSymbolAction ( AnalyzeSymbol , SymbolKind.NamedType ) ; } private static void AnalyzeSymbol ( SymbolAnalysisContext context ) { var namedTypeSymbol = ( INamedTypeSymbol ) context.Symbol ; // Find just those named type symbols with names conta...
ReportDiagnostic on Partial Classes
C#
I have a CheckBoxList control that contains dynamically generated checkbox items . This checkboxlist will contain usernames . I am using Gravatar control from AjaxControlToolkit to allow users to have their own profile pictures . What I want is that when a checkbox with username as a text is added to the CheckBoxList ,...
< table class= '' style1 '' > < tr > < td align= '' right '' style= '' padding : 5px '' width= '' 25 % '' > Username/Email : < /td > < td style= '' padding : 5px '' > < asp : TextBox ID= '' TextBox1 '' runat= '' server '' > < /asp : TextBox > & nbsp ; < asp : Button ID= '' Button1 '' runat= '' server '' CssClass= '' ne...
How to add AjaxControlToolkit 's Gravatar Control before or after checkbox in checkboxlist control
C#
I was investigating some strange object lifetime issues , and came across this very puzzling behaviour of the C # compiler : Consider the following test class : The compiler generates the following : The original class contains two lambdas : s = > hashSet.Add ( s ) and ( ) = > File.OpenRead ( file ) . The first closes ...
class Test { delegate Stream CreateStream ( ) ; CreateStream TestMethod ( IEnumerable < string > data ) { string file = `` dummy.txt '' ; var hashSet = new HashSet < string > ( ) ; var count = data.Count ( s = > hashSet.Add ( s ) ) ; CreateStream createStream = ( ) = > File.OpenRead ( file ) ; return createStream ; } }...
Is this closure combination behaviour a C # compiler bug ?
C#
I 'm trying to create a method which returns a list of whichever type the user wants . To do this I 'm using generics , which I 'm not too familiar with so this question may be obvious . The problem is that this code does n't work and throws the error message Can not convert type Systems.Collections.Generic.List < Cata...
private List < T > ConvertToList < T > ( Category cat ) { switch ( cat ) { case Category.Brands : return ( List < T > ) collection.Brands.ToList < Brand > ( ) ; } ... } private IList < T > ConvertToList < T > ( Category cat ) { switch ( cat ) { case Category.Brands : return ( IList < T > ) collection.Brands.ToList < Br...
Can use IList but not List in generic method
C#
We 'll start with a standalone story , just so you understand why : I want to treat any actions that change data against the same interface : ICommandThere are things that exist out there called ICommandHandlers that handle any command I want.So , if I want a CreatePersonCommand I 'd need a CreatePersonCommandHandler o...
// The e.g . CreatePersonCommand , with TResult being Person , as an example.public interface ICommand < TResult > { } //This handles the command , so CreatePersonCommandHandlerpublic interface ICommandHandler < in TCommand , out TResult > where TCommand : ICommand < TResult > { TResult Handle ( TCommand command ) ; } ...
RegisterOpenGeneric with SimpleInjector resolves incorrect type
C#
Related question : Accessing a Class property without using dot operatorI 've created a class called MyDouble looks like thisI am able to do all kinds of operations on MyDouble . Examples : However , this still throws an errorHow can I define it such that an operation like ( Int64 ) a automatically converts to ( Int64 ...
class MyDouble { double value ; //overloaded operators and methods } MyDouble a = 5.0 ; a += 3.0 ; ... etc MyDouble a = 5.0 ; long b = ( Int64 ) a ; //errorlong b = ( int64 ) a.value ; //works
Casting my Class to Int64 , Double etc
C#
Hopefully someone can explain this to me . Sorry if it 's a repeat , the keywords to explain what I 'm seeing are beyond me for now..here is some code that compilesand here is some code that does notBy adding the constructor overload , this apparently creates ambiguity but I 'm not sure why . Math.Sqrt is not overloade...
class Program { static void Main ( string [ ] args ) { new Transformer < double , double > ( Math.Sqrt ) ; } } class Transformer < Tin , Tout > { Func < Tin , Task < Tout > > actor ; public Transformer ( Func < Tin , Tout > actor ) { this.actor = input = > Task.Run < Tout > ( ( ) = > actor ( input ) ) ; } } class Progr...
C # Call is Ambiguous when passing a method group as delegate
C#
In the example below , is there a way for a method of the implementing class to explicitly tell the compiler which interface member it implements ? I know it 's possible to resolve ambiguity between interfaces , but here it is within one interface .
interface IFoo < A , B > { void Bar ( A a ) ; void Bar ( B b ) ; } class Foo : IFoo < string , string > { public void Bar ( string a ) { } public void Bar ( string b ) { } // ambiguous signature }
How to resolve ambiguous interface method signatures , occuring when multiple generic type arguments are identical
C#
I have this code : When I run the code in a Console Application , everything works fine , stream.IsAuthenticated and stream.IsMutuallyAuthenticated return true and stream.LocalCertificate contains the correct certificate object.However when running the exact same code in a Windows Service ( as LOCAL SYSTEM user ) , alt...
string certificateFilePath = @ '' C : \Users\Administrator\Documents\Certificate.pfx '' ; string certificateFilePassword = `` Some Password Here '' ; X509Certificate clientCertificate = new X509Certificate ( certificateFilePath , certificateFilePassword ) ; TcpClient client = new TcpClient ( host , port ) ; SslStream s...
SslStream Authentication fails under LOCAL SYSTEM account
C#
I have a simple question for you ( i hope ) : ) I have pretty much always used void as a `` return '' type when doing CRUD operations on data.Eg . Consider this code : and then considen this code : It actually just comes down to whether you should notify that something was inserted ( and went well ) or not ?
public void Insert ( IAuctionItem item ) { if ( item == null ) { AuctionLogger.LogException ( new ArgumentNullException ( `` item is null '' ) ) ; } _dataStore.DataContext.AuctionItems.InsertOnSubmit ( ( AuctionItem ) item ) ; _dataStore.DataContext.SubmitChanges ( ) ; } public bool Insert ( IAuctionItem item ) { if ( ...
CRUD operations ; do you notify whether the insert , update etc . went well ?
C#
I 'm trying to figure out how to properly pass properties through multiple classes . I know I can just implement INotifyPropertyChanged in each class and listen for changes on the property , but this seems to be quite a lot of unnecessary code.The situation : I have a class ( let 's call it Class1 ) with two dependency...
public class Class1 { public static readonly DependencyProperty FilterProperty = DependencyProperty.Register ( `` Filter '' , typeof ( Filter ) , typeof ( Class1 ) , new FrameworkPropertyMetadata ( null ) ) ; public static readonly DependencyProperty FilterStatementProperty = DependencyProperty.Register ( `` FilterStat...
Propagate property changes through multiple classes
C#
I have a collection of variables in my viewmodel : The ObservableVariable class has two properties : string Name , and bool Selected ; the class implements INotifyPropertyChanged , My goal is to have this collection bound to a checklist in a WPF view , and to have a 'select all ' checkbox bound to that list implemented...
public ObservableCollection < ObservableVariable > Variables { get ; } = new ObservableCollection < ObservableVariable > ( ) ; < CheckBox Content= '' Select All '' Name= '' SelectAllCheckbox '' > < /CheckBox > ... < ListBox ItemsSource= '' { Binding Variables } '' > < ListBox.ItemTemplate > < DataTemplate > < CheckBox ...
WPF Multibinding not Updating Source when Expected ; Checkboxes with 'Select All '
C#
I am binding DataGrid.ItemsSource property to the List < PersonDetails > object . I am getting datas through Silverlight-enabled WCF Service . So the PersonDetails class is implemented in Web Project . Each DataGrid 's header text is changing as i want if the class is located in Silverlight project . But then I can not...
[ DataContract ] public class PersonGeneralDetails { // Properties [ DataMember ] [ DisplayAttribute ( Name = `` Sira '' ) ] public int RowNumber { get ; set ; } [ DataMember ] [ DisplayAttribute ( Name = `` Seriyasi '' ) ] public string SerialNumber { get ; set ; } }
DisplayAttribute name property not working in Silverlight
C#
From my recent question , I try to centralize the domain model by including some silly logic in domain interface . However , I found some problem that need to include or exclude some properties from validating.Basically , I can use expression tree like the following code . Nevertheless , I do not like it because I need...
public void IncludeProperties < T > ( params Expression < Func < IUser , object > > [ ] selectedProperties ) { // some logic to store parameter } IncludeProperties < IUser > ( u = > u.ID , u = > u.LogOnName , u = > u.HashedPassword ) ;
What 's the best way to define & access selected properties in C # ?
C#
I 'm trying to get a list of items to update whenever a message is received from a message queue.This only seems to work every other time a message is received though . It 's definitely hitting the anonymous method inside the SubscribeAsync call each time , and I ca n't work out why it 's not updating every time . I 'm...
@ page `` / '' @ inject IMessageQueueHelperFactory MessageQueueHelperFactory @ inject ILogger < Index > Logger @ using Microsoft.Extensions.Logging @ using Newtonsoft.Json < ul class= '' list-group '' > @ foreach ( var user in Users ) { < li class= '' list-group-item '' > @ user < /li > } < /ul > @ code { private List ...
Update list of items in Blazor from another thread
C#
So I have run into an interesting problem where I am getting duplicate keys in C # Dictionary when using a key of type PhysicalAddress . It is interesting because it only happens after a very long period of time , and I can not reproduce it using the same code in a unit test on a completely different machine . I can re...
private void ProcessMessages ( ) { IDictionary < PhysicalAddress , TagData > displayableTags = new Dictionary < PhysicalAddress , TagData > ( ) ; while ( true ) { try { var message = incomingMessages.Take ( cancellationToken.Token ) ; VipTagsDisappeared tagsDisappeared = message as VipTagsDisappeared ; if ( message is ...
Duplicate keys in Dictionary when using PhysicalAddress as the key
C#
Hello fellow StackOverflow users ( or Stackoverflowers ? ) : I 'm learning-by-coding WPF . I read several articles/saw several screencasts , and coming from a WEB dev background , I fired up VS2010 and started doing a sample application that would help me learn the basics.I read some about MVVM too , and started using ...
public class MainWindowViewModel { private ObservableCollection < Order > openOrders ; private Address deliveryAddress ; private Order newOrder ; /* Wrappers for the OpenOrders Collection */ /* Wrappers for Delivery Address */ /* Wrappers for New Order */ /* Command Bindings */ }
WPF MVVM Doubts
C#
Given the following class , how would you go about writing a unit test for it ? I have read that any test that does file IO is not a unit test , so is this an integration test that needs to be written ? I am using xUnit and MOQ for testing and I am very new to it , so maybe I could MOQ the file ? Not sure .
public class Serializer { public static T LoadFromXmlFile < T > ( string path ) where T : class { var serializer = new XmlSerializer ( typeof ( T ) ) ; using ( var reader = new StreamReader ( path ) ) { return serializer.Deserialize ( reader ) as T ; } } public static void SaveToXmlFile < T > ( T instance , string path...
How do you test code that does file IO ?
C#
I have an SQL connection service that I 'm trying to build . I essentially do this : DoStuffWithSqlAsync operates like this : And RunQueryAsync operates like this : The problem I 'm running into is that DoStuffWithSqlAsync continuously fails with a System.InvalidOperationException stating that conn is in a closed state...
var data = await GetDataFromFlatFilesAsync ( dir ) .ConfigureAwait ( false ) ; using ( var conn = new SqlConnection ( MyConnectionString ) ) { try { conn.Open ( ) ; var rw = new SqlReaderWriter ( conn ) ; await DoStuffWithSqlAsync ( rw , data ) .ConfigureAwait ( false ) ; } catch ( Exception ex ) { // Do exceptional st...
SqlConnection closes unexpectedly inside using statement
C#
In C # 5 , they introduced the Caller Info attributes . One of the useful applications is , quite obviously , logging . In fact , their example given is exactly that : I am currently developing an application and I am at the point where I would like to introduce the usage of the caller info in my logging routines . Ass...
public void TraceMessage ( string message , [ CallerMemberName ] string memberName = `` '' , [ CallerFilePath ] string sourceFilePath = `` '' , [ CallerLineNumber ] int sourceLineNumber = 0 ) { Trace.WriteLine ( `` message : `` + message ) ; Trace.WriteLine ( `` member name : `` + memberName ) ; Trace.WriteLine ( `` so...
How I can I do TDD with Caller Info attributes ?
C#
I read that when in a catch block , I can rethrow the current exception using `` throw ; '' or `` throw ex ; '' .From : http : //msdn.microsoft.com/en-us/library/ms182363 % 28VS.80 % 29.aspx '' To keep the original stack trace information with the exception , use the throw statement without specifying the exception . '...
try { try { try { throw new Exception ( `` test '' ) ; // 13 } catch ( Exception ex1 ) { Console.WriteLine ( ex1.ToString ( ) ) ; throw ; // 16 } } catch ( Exception ex2 ) { Console.WriteLine ( ex2.ToString ( ) ) ; // expected same stack trace throw ex2 ; // 20 } } catch ( Exception ex3 ) { Console.WriteLine ( ex3.ToSt...
Why do `` throw '' and `` throw ex '' in a catch block behave the same way ?
C#
I have a kind a simple question but I 'm surprised.This code works : Why do n't I have to do itemID.ToString ( ) in this case ?
int itemID = 1 ; string dirPath = @ '' C : \ '' + itemID + @ '' \abc '' ;
int to string without explicit conversion ?
C#
The problem is this : I have a form that accepts a TextBox text and 2 buttons , one to save the text into the database and the other one to cancel and close the form . The form also has an ErrorProvider that 's used in the TextBox.Validating event like this : It does what is expected , to not let the user to do anythin...
private void txtNombre_Validating ( object sender , CancelEventArgs e ) { string errorMsg ; if ( ! ValidateText ( txtNombre.Text , out errorMsg ) ) { // Cancel the event and select the text to be corrected by the user . e.Cancel = true ; txtNombre.Select ( 0 , txtNombre.Text.Length ) ; // Set the ErrorProvider error wi...
In a textbox validating event , how to ignore clicks to a certain button ?
C#
Disclaimer : It is well known that catch ( ex ) { throw ex ; } is bad practice . This question is not about that.While digging through Microsoft reference sources , I noticed the following pattern in a lot of methods : No logging , no debugging code—just a plain simple catch { throw ; } .Since , obviously , the guys at...
try { ... } catch { throw ; }
Is there any technical reason to write a catch block containing only a throw statement ?
C#
I 'm trying to create a not in clause with the NHibernate Criteria API using NHLambdaExtensions . Reading the documentation I was able to implement the in clause by doingHowever , when I wrap it around SqlExpression.Not I get the errorI 'm using this piece of codeHow can I accomplish this ? Using the regular Criteria A...
.Add ( SqlExpression.In < Zone > ( z = > zoneAlias.ZoneId , new int [ ] { 1008 , 1010 } ) ) Error 5 The best overloaded method match for 'NHibernate.LambdaExtensions.SqlExpression.Not < oms_dal.Models.Zone > ( System.Linq.Expressions.Expression < System.Func < oms_dal.Models.Zone , bool > > ) ' has some invalid argumen...
How do I express “ not in ” using lambdas ?
C#
For a dynamic binary translation simulator , I need to generate collectible .NET assemblies with classes that access static fields . However , when using static fields inside collectible assemblies , execution performance is by factor of 2-3 lower compared to non-collectible assemblies . This phenomen is not present in...
Testing non-collectible const multiply : Elapsed : 8721.2867 msTesting collectible const multiply : Elapsed : 8696.8124 msTesting non-collectible field multiply : Elapsed : 10151.6921 msTesting collectible field multiply : Elapsed : 33404.4878 ms using System ; using System.Reflection ; using System.Reflection.Emit ; u...
Static field access in collectible dynamic assemblies lacks performance
C#
This is something I encountered while using the C # IList collectionsAs far as I know , in C # ( on the contrary of C++ ) when we create an object with this syntax , the object type get the right side ( assignment ) and not the left one ( declaration ) .Do I miss something here ! EDITI still do n't get it , even after ...
IList < MyClass > foo = new List < MyClass > ( ) ; var bar = new List < MyClass > ( ) ; foo.AddRange ( ) // does n't compilebar.AddRange ( ) // compile
Object assignment in C #
C#
I 've been at this for a few days now . My original ( and eventual ) goal was to use CommonCrypto on iOS to encrypt a password with a given IV and key , then successfully decrypt it using .NET . After tons of research and failures I 've narrowed down my goal to simply producing the same encrypted bytes on iOS and .NET ...
static byte [ ] EncryptStringToBytes_Aes ( string plainText , byte [ ] Key , byte [ ] IV ) { byte [ ] encrypted ; // Create an Aes object // with the specified key and IV . using ( Aes aesAlg = Aes.Create ( ) ) { aesAlg.Padding = PaddingMode.PKCS7 ; aesAlg.KeySize = 256 ; aesAlg.BlockSize = 128 ; // Create an encryptor...
iOS & .NET Produce Different AES256 Results
C#
I need help with GDAL . The string value with Chinese symbols is not readed/saved correctly ( C # ) .For SAVING grid value we using : private static extern void GDALRATSetValueAsString ( IntPtr handle , int row , int field , [ In ] [ MarshalAs ( UnmanagedType.LPStr ) ] string value ) ; method ( c # ) to save string val...
private static extern IntPtr GDALRATGetValueAsString ( IntPtr handle , int row , int field ) ; var pointer = GDALRATGetValueAsString ( GDALRasterAttributeTableH , row , field ) ; a ) var b = Marshal.PtrToStringUni ( pointer ) ; // value : `` 㼿汆浡潷摯䌠2 '' b ) var a = Marshal.PtrToStringAnsi ( pointer ) ; // value : `` ? ?...
GDAL GDALRATSetValueAsString ( ) how to save Chinese characters ( c # ) ?
C#
I am currently using Visual Studio Express C++ 2008 , and have some questions about catch block ordering . Unfortunately , I could not find the answer on the internet so I am posing these questions to the experts.I notice that unless catch ( ... ) is placed at the end of a catch block , the compilation will fail with e...
catch ( MyException ) { } catch ( ... ) { } catch ( ... ) { } catch ( MyException ) { }
Questions regarding ordering of catch statements in catch block - compiler specific or language standard ?
C#
I have a bunch of methods that take the WPF 's WriteableBitmap and read from its BackBuffer directly , using unsafe code.It 's not entirely clear whether I should use GC.KeepAlive whenever I do something like this : On the one hand , there remains a reference to bmp on MyMethod 's stack . On the other , it seems like r...
int MyMethod ( WriteableBitmap bmp ) { return DoUnsafeWork ( bmp.BackBuffer ) ; } int MyMethod ( ) { WriteableBitmap bmp1 = getABitmap ( ) ; var ptr = bmp.BackBuffer ; WriteableBitmap bmp2 = getABitmap ( ) ; return DoUnsafeWork ( ptr , bmp2 ) ; }
Is GC.KeepAlive required here , or can I rely on locals and arguments keeping an object alive ?
C#
I want to have an enum as in : How to achieve this ? Is there a better way to do this ? It 's gon na be used for an instance of an object where it 's gon na be serialized/deserialized . It 's also gon na populate a dropdownlist .
enum FilterType { Rigid = `` Rigid '' , SoftGlow = `` Soft / Glow '' , Ghost = `` Ghost '' , }
Possible to have strings for enums ?
C#
I have a class that calls out to an internet service to get some data : Currently I have two providers : HttpDataProvider and FileDataProvider . Normally I will wire up to the HttpDataProvider but if the external web service fails , I 'd like to change the system to bind to the FileDataProvider . Something like : So wh...
public class MarketingService { private IDataProvider _provider ; public MarketingService ( IDataProvider provider ) { _provider = provider ; } public string GetData ( int id ) { return _provider.Get ( id ) ; } } public string GetData ( int id ) { string result = `` '' ; try { result = GetData ( id ) ; // call to HttpD...
programmatically change a dependency in Castle Windsor
C#
I have an interface called Identifiable < TId > that contains a single property Id of the given type . I want to create a generic class that takes one of these as a type parameter . It should be generic because I want to return concrete type , call other generic methods from within it and use things like typeof ( T ) ....
public class ClassName < T , TId > where T : Identifiable < TId >
Is it possible to implement this interface generically so that it can be passed only one type parameter ?
C#
The MSDN recommends putting any instantiation of classes that implement IDisposable into a using block . Or alternatively , if it is being instantiated within a try-catch block , then Dispose in Finally.Are there any problems with using a using block within a try-catch block like so ? Of course I can just call Dispose ...
try { using ( Foo bar = new Foo ( ) ) { bar.doStuff ( ) ; } } catch ( Exception e ) { //vomit e }
Are there any issues with using block for an IDisposable within a try catch block ?
C#
Can anybody shed any light on why this unit test is failing in Visual Studio 2013 ?
[ TestMethod ] public void Inconceivable ( ) { int ? x = 0 ; Assert.AreEqual ( typeof ( int ? ) , x.GetType ( ) ) ; }
Is the C # compiler optimizing nullable types ?
C#
I 'd like to ensure that two interfaces are never found on the same class at compile-time , similar to how AttributeUsage checks custom Attributes at compile-time.e.g . : I can obviously do this at runtime with reflection , but I 'm interested in a compile-time solution.I 'd imagine that one probably does n't exist out...
[ InterfaceUsage ( MutuallyExclusive = typeof ( B ) ) ] interface A { // ... } interface B { // ... } class C : A , B { //should throw an error on compile time // ... }
Ensure mutually exclusive interfaces at compile-time ?
C#
Suppose I have a collection of strings : And I would like to generate a comma separated values from the list into something like : Notice the lack of `` , `` at the end.I am aware that there are dozens of ways to generate this : use for-loop and string.Format ( ) or StringBuilder.use integer counter and remove the endi...
`` foo '' '' bar '' '' xyz '' `` foo , bar , xyz '' if ( strs.Count ( ) > 0 ) { var sb = new StringBuilder ( ) ; foreach ( var str in strs ) sb.AppendFormat ( `` { 0 } , `` , str ) ; return sb.Remove ( 0 , 2 ) .ToString ( ) ; }
Generating Comma Separated Values
C#
I 'm getting quite annoyed with a feature of Resharper that I just can not find how to disable independently.With Resharper turned off , whenever I type prop in VS2015 and press TAB , I get the following auto-generated code : and I 'm then able to switch between int and MyProperty repeatedly by pressing TAB again.I 'm ...
public int MyProperty { get ; set ; }
Resharper - Disable 'help ' when using `` prop '' shortcut in C #
C#
I create objects by initializing the fields in this way : Is it always for field `` a '' to be initialized before field `` b '' ? Otherwise , an unpleasant error can occur when the values from the stream are subtracted in a different order . Thanks ! UPD : In the comments , many did not understand what I mean.I will cl...
class Example { public int a ; public int b ; } var obj = new Example { a = stream.ReadInt ( ) , b = stream.ReadInt ( ) } ; var obj = new Example { a = stream.ReadInt ( ) , b = stream.ReadInt ( ) } ; var a = stream.ReadInt ( ) ; var b = stream.ReadInt ( ) ; var obj = new Example { a = a , b = b } ;
C # The order of fields initialization
C#
I want to put all the signatures of Windows API functions I 'm using in programs in one class , such as WinAPI , and in a file WinAPI.cs I will include in my projects . The class will be internal static and the methods public static extern . ( Something like the huge NativeMethods.cs from the .NET Framework source code...
[ DllImport ( `` user32.dll '' ) ] internal static extern bool ShowWindow ( IntPtr hWnd , int nCmdShow ) ; [ StructLayout ( LayoutKind.Sequential ) ] public struct POINT { public int X ; public int Y ; } public const int WH_JOURNALPLAYBACK = 1 ; public static readonly int WM_GETTEXT = 0x0D ;
Big C # source file with Windows API method signatures , structures , constants : will they all be included in the final .exe ?
C#
I generated a .cur file to use it in my WPF application , the pointing position by default is left top corner , and I want to set it to the center.I found some threads here that help resolve that problem by setting the HotSpots , where you can do stuff like this : The problem is that is in WindosForms . In WPF the Curs...
public static Cursor CreateCursorNoResize ( Bitmap bmp , int xHotSpot , int yHotSpot ) { IntPtr ptr = bmp.GetHicon ( ) ; IconInfo tmp = new IconInfo ( ) ; GetIconInfo ( ptr , ref tmp ) ; tmp.xHotspot = xHotSpot ; tmp.yHotspot = yHotSpot ; tmp.fIcon = false ; ptr = CreateIconIndirect ( ref tmp ) ; return new Cursor ( pt...
How to change the pointing position of a mouse cursor in WPF
C#
This is a question based on the article `` Closing over the loop variable considered harmful '' by Eric Lippert.It is a good read , Eric explains why after this piece of code all funcs will return the last value in v : And the correct version looks like : Now my question is how and where are those captured 'v2 ' variab...
var funcs = new List < Func < int > > ( ) ; foreach ( var v in values ) { funcs.Add ( ( ) = > v ) ; } foreach ( var v in values ) { int v2 = v ; funcs.Add ( ( ) = > v2 ) ; }
How|Where are closed-over variables stored ?
C#
The following piece of C # code does not compile : This behaviour is correct according to the C # 4.0 specification ( paragraph 10.1.4.1 ) : While determining the meaning of the direct base class specification A of a class B , the direct base class of B is temporarily assumed to be object . Intuitively this ensures tha...
public class A { public interface B { } } public class C : A , C.B // Error given here : The type name ' B ' does not exist in the type ' C ' . { } public class D : C.B // Compiles without problems if we comment out ' C.B ' above . { } // The next three classes should really be interfaces , // but I 'm going to overrid...
Why ca n't the meaning of a base class specification recursively depend on itself in C # ?
C#
Microsoft 's documention of Parallel.For contains the following method : In this method , potentially multiple threads read values from matA and matB , which were both created and initialized on the calling thread , and potentially multiple threads write values to result , which is later read by the calling thread . Wi...
static void MultiplyMatricesParallel ( double [ , ] matA , double [ , ] matB , double [ , ] result ) { int matACols = matA.GetLength ( 1 ) ; int matBCols = matB.GetLength ( 1 ) ; int matARows = matA.GetLength ( 0 ) ; // A basic matrix multiplication . // Parallelize the outer loop to partition the source array by rows ...
Memory barriers in Parallel.For
C#
For methods where ... there exists a static one-to-one mapping between the input and the output , andthe cost of creating the output object is relatively high , andthe method is called repeatedly with the same input ... there is a need for caching result values.In my code the following result value caching pattern is r...
private static Map < Input , Output > fooResultMap = new HashMap < Input , Output > ( ) ; public getFoo ( Input input ) { if ( fooResultMap.get ( input ) ! = null ) { return fooResultMap.get ( input ) ; } Output output = null ; // Some code to obtain the object since we do n't have it in the cache . fooResultMap.put ( ...
Which languages have support for return value caching without boilerplate code ?
C#
I came across a behavior that surprises me . Given the following two classes : I can write code like this : The IDE makes it confusing , too , because , while it allows the assignment , it also indicates that the overridden property is read-only : Furthermore , this override is only allowed when I 'm using the base cla...
class Parent { public virtual bool Property { get ; set ; } } class Child : Parent { public override bool Property { get = > base.Property ; } } Child child = new Child ( ) ; child.Property = true ; // this is allowed
Why can a full property in C # be overridden with only a getter but it can still be set ?
C#
I have a question regarding raising base class events . I am currently reading the MSDN C # Programming Guide and I can not understand one thing from the below article : http : //msdn.microsoft.com/en-us/library/vstudio/hy3sefw3.aspxOK , so we are registering the delegate with an event and we 'll be calling the private...
public void AddShape ( Shape s ) { _list.Add ( s ) ; s.ShapeChanged += HandleShapeChanged ; } public void Update ( double d ) { radius = d ; area = Math.PI * radius * radius ; OnShapeChanged ( new ShapeEventArgs ( area ) ) ; } protected override void OnShapeChanged ( ShapeEventArgs e ) { base.OnShapeChanged ( e ) ; }
Why can a base class event call a private method ?
C#
I have the following classes and I am trying to call Compare method from ExportFileBaseBL class but I get the errorCannot implicitly convert type 'Class1 ' to 'T ' . An explicit conversion exists ( are you missing a cast ? ) Should n't the type conversion be implicit ? Am I missing something ?
public abstract class Class1 < T > where T : Class2 { public abstract Class1 < T > Compare ( Class1 < T > otherObj ) ; } public abstract class Class3 < T , U > where T : Class1 < U > where U : Class2 { public T Compare ( T obj1 , T obj2 ) { if ( obj1.Prop1 > obj2.Prop1 ) { return obj1.Compare ( obj2 ) ; // Compiler Err...
C # Generics - Calling generic method from a generic class
C#
I 've been toying with parallelism and I 'm having some trouble understanding what 's going on in my program.I 'm trying to replicate some of the functionality of the XNA framework . I 'm using a component-style setup and one way I thought of making my program a little more efficient was to call the Update method of ea...
public void Update ( GameTime gameTime ) { Task [ ] tasks = new Task [ engineComponents.Count ] ; for ( int i = 0 ; i < tasks.Length ; i++ ) { tasks [ i ] = new Task ( ( ) = > engineComponents [ i ] .Update ( gameTime ) ) ; tasks [ i ] .Start ( ) ; } Task.WaitAll ( tasks ) ; } Task [ ] tasks = new Task [ engineComponen...
C # Tasks not working as expected . Bizarre error
C#
Given a collection of disparate objects , is it possible to find the most-specific base class they all share ? For instance , given objects with these class hierarchies ... ( For fun ... http : //www.wired.com/autopia/2011/03/green-machine-bike-is-a-big-wheel-for-grownups ) Is it possible to write a function with this ...
object - > Vehicle - > WheeledVehicle - > Car - > SportsCarobject - > Vehicle - > WheeledVehicle - > Busobject - > Vehicle - > WheeledVehicle - > MotorCycleobject - > Vehicle - > WheeledVehicle - > Tricycle - > BigWheelobject - > Vehicle - > WheeledVehicle - > Tricycle - > Green Machine public Type GetCommonBaseType ( ...
How can you programmatically find the deepest common base type from a bunch of subclasses ?
C#
It all started with a trick question that someone posed to me.. ( It 's mentioned in the book - C # in a nutshell ) Here 's the gist of it.The above does n't seem right . a should always be == to itself ( reference equality ) & both should be consistent.Seems like Double overloads the == operator . Confirmed by reflect...
Double a = Double.NaN ; Console.WriteLine ( a == a ) ; // = > falseConsole.WriteLine ( a.Equals ( a ) ) ; // = > true [ __DynamicallyInvokable ] public static bool operator == ( double left , double right ) { return ( left == right ) ; } var x = `` abc '' ; var y = `` xyz '' ; Console.WriteLine ( x == y ) ; // = > fals...
When is Double 's == operator invoked ?
C#
We have a controller which expects some parameters in a get route , but the OData functions like $ top is n't working.According to the docs it ( custom query options ) should work fine just declaring the @ prefix at the custom options but it 's not : Using @ as the prefix ( as suggested at docs ) the parameter filtro i...
~/ProdutosRelevantes ? $ top=5 & filtro.Cnpjs [ 0 ] =00000000000001 & filtro.DataInicio=2018-01-01 & filtro.DataFim=2018-12-01 & filtro.IndMercado=2 & [ HttpGet ] public IHttpActionResult ProdutosRelevantes ( [ FromUri ] ParametrosAnalise filtro ) { var retorno = GetService ( ) .GetProdutosRelevantes ( filtro ) ; retur...
Get route using OData and custom query options
C#
Somewhere in the back of my head a tiny voice is telling me `` the C # code below smells '' .The constant STR_ConnectionString is used in other places in the code as well.How to get rid of the smell ?
private const string STR_ConnectionString = `` ConnectionString '' ; private readonly string upperCaseConnectionString = STR_ConnectionString.ToUpperInvariant ( ) ; // a lot further onstring keyAttributeValue = keyAttribute.Value ; if ( keyAttributeValue.ToUpperInvariant ( ) .StartsWith ( upperCaseConnectionString ) ) ...
C # : better way than to combine StartsWith and two ToUpperInvariant calls
C#
Do C # console applications appear in the task manager ? I 'm trying to get it both to appear , and the Publisher and Process Name columns to be what I expect.In my AssemblyInfo.cs I have done this : But while my console app is running ( ran from command line as the current user ) I do n't see any of these values in th...
[ assembly : AssemblyTitle ( `` Test Title '' ) ] [ assembly : AssemblyDescription ( `` Test Desc '' ) ] [ assembly : AssemblyCompany ( `` Test Company '' ) ] [ assembly : AssemblyProduct ( `` Test Product '' ) ]
Does a C # ( .NET 4.5 ) application appear in the Windows ' Task Manager ?
C#
Can someone please explain to me the following method ? I do n't quite understand what it does , and how it does it .
private List < Label > CreateLabels ( params string [ ] names ) { return new List < Label > ( names.Select ( x = > new Label { ID = 0 , Name = x } ) ) ; }
Help understanding some C # code
C#
This seems odd to me , but I remember a thread where Eric Lippert commented on the inability ( by design , or at least convention , I think ) of C # to overload methods based on return type , so perhaps it 's in some convoluted way related to that.Is there any reason this does not work : But this does : From a certain ...
public static T Test < T > ( ) where T : new ( ) { return new T ( ) ; } // ElsewhereSomeObject myObj = Test ( ) ; var myObj = Test < SomeObject > ( ) ;
Is the C # compiler unable to infer method type parameters by expected return type ?
C#
I have a distributed system of actors , some on Windows , and some on Linux machine . Sometimes one actor may need to connect other actor and make some communications . Of course , there are cases when one of them is on Windows , and other is on Linux system.Actors connect each other via ActorSelection . There problem ...
static void Main ( string [ ] args ) { ActorSystem system = ActorSystem.Create ( `` TestSystem '' ) ; system.ActorOf ( Props.Create ( ( ) = > new ConnectActor ( ) ) , `` test '' ) ; while ( true ) { var address = Console.ReadLine ( ) ; if ( string.IsNullOrEmpty ( address ) ) { system.Terminate ( ) ; return ; } var remo...
Akka.NET Remote between Linux and Windows
C#
I 'm currently working on a website which is being developed using Asp.Net and C # . I 'm making use of Asp.Net Handler to allow users to download files . I can download the files no problem . However I need to log which files were downloaded successfully . This part does n't seem to work correctly for me . E.g . if I ...
public void ProcessRequest ( HttpContext context ) { string logFilePath = `` PathToMyLogFile '' ; string filePath = Uri.UnescapeDataString ( context.Request.QueryString [ `` file '' ] ) ; string fileName = Path.GetFileName ( filePath ) ; if ( context.Response.IsClientConnected ) //Should n't this tell me if the client ...
Using Handler to keep track of files
C#
I 'm trying to get non-standard-format data from the clipboard using DataPackageView.GetDataAsync . I am stumped on converting the returned system.__ComObject to a string . Here is the code : I am looking for a solution that will work with any non-standard clipboard format . `` FileName '' is an easily testable format ...
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent ( ) ; if ( dataPackageView.Contains ( `` FileName '' ) ) { var data = await dataPackageView.GetDataAsync ( `` FileName '' ) ; // How to convert data to string ? } OpenClipboard ( nullptr ) ; UINT clipboarFormat = RegisterClipboardFormat ( ...
How to get string from dataPackageView.GetDataAsync ( )
C#
So I am looking at this question and the general consensus is that uint cast version is more efficient than range check with 0 . Since the code is also in MS 's implementation of List I assume it is a real optimization . However I have failed to produce a code sample that results in better performance for the uint vers...
class TestType { public TestType ( int size ) { MaxSize = size ; Random rand = new Random ( 100 ) ; for ( int i = 0 ; i < MaxIterations ; i++ ) { indexes [ i ] = rand.Next ( 0 , MaxSize ) ; } } public const int MaxIterations = 10000000 ; private int MaxSize ; private int [ ] indexes = new int [ MaxIterations ] ; public...
Code sample that shows casting to uint is more efficient than range check
C#
I am building an ASP.NET Core application which will need to handle large file uploads— as much as 200GB . My goal is to write these files to disk and capture an MD5 Hash at the same time.I 've already gone through and created my own method to identify the file stream from an HTTP client request as outlined in Uploadin...
// removed the curly brackets from using statements for readability on Stack Overflowvar md5 = MD5.Create ( ) ; using ( var targetStream = File.OpenWrite ( pathAndFileName ) ) using ( var cryptoStream = new CryptoStream ( targetStream , md5 , CryptoStreamMode.Write ) ) using ( var sourceStream = fileNameAndStream.FileS...
How does asynchronous file hash and disk write actually work ?
C#
When I used to develop in C++ , I remember that Visual Studio had an entry in its Autos window whenever returning from a function call . This entry would tell me what value was returned from that function.One might argue that if a function returns a value , then you should set a variable to that value , i.e.But as a co...
int i = GetRandomInt ( ) ; CycleTushKicker ( GetRandomInt ( ) ) ;
Return value in Visual Studio 's Autos window
C#
I 'm implementing some 32-bit float trigonometry in C # using Mono , hopefully utilizing Mono.Simd . I 'm only missing solid range reduction currently.I 'm rather stuck now , because apparently Mono 's SIMD extensions does not include conversions between floats and integers , meaning I have no access to rounding/trunca...
// here 's another more correct attempt : float fmodulus ( float val , int domain ) { const int mantissaMask = 0x7FFFFF ; const int exponentMask = 0x7F800000 ; int ival = * ( int* ) & val ; int mantissa = ival & mantissaMask ; int rawExponent = ival & exponentMask ; int exponent = ( rawExponent > > 23 ) - ( 129 - domai...
Floating point range reduction
C#
Let 's say I have a method : It 's clear that I should use ArgumentNullException as it shown above to validate that user is not null . Now how can I validate that user.Name is not empty ? Would it be a good practice to do like that :
public void SayHello ( User user ) { if ( user == null ) throw new ArgumentNullException ( `` user '' ) ; Console.Write ( string.Format ( `` Hello from { 0 } '' , user.Name ) ) ; } if ( string.IsNullOrWhiteSpace ( user.Name ) ) throw new ArgumentNullException ( `` user '' , `` Username is empty '' ) ;
ArgumentNullException for nested members
C#
Perhaps a useless question : One of exceptions thrown by the above method is also OverflowException : The sum of the elements in the sequence is larger than Int64.MaxValue.I assume reason for this exception is that sum of the averaged values is computed using variable S of type long ? But since return value is of type ...
public static double Average < TSource > ( this IEnumerable < TSource > source , Func < TSource , int > selector )
Enumerable.Average and OverflowException
C#
Apologies if this is already answered on this site or in the extensive ServiceStack documentation - I have looked , but if it does exist , I would appreciate a pointer ! I 've been trying to knock up an example service stack ( 1.0.35 ) service which demonstrates the usage of OAuth2 using .NET core ( not .NET 4.5.x ) .I...
namespace ServiceStackAuthTest1 { public class Program { public static void Main ( string [ ] args ) { IWebHost host = new WebHostBuilder ( ) .UseKestrel ( ) .UseContentRoot ( Directory.GetCurrentDirectory ( ) ) .UseStartup < Startup > ( ) .UseUrls ( `` http : //*:40000/ '' ) .Build ( ) ; host.Run ( ) ; } } public clas...
OAuth2 authentication plugin for ServiceStack .NET Core
C#
I 'm currently making my own very basic generic list class ( to get a better understanding on how the predefined ones work ) . Only problem I have is that I ca n't reach the elements inside the array as you normally do in say using `` System.Collections.Generic.List '' . This works fine , but when trying to access `` w...
GenericList < type > list = new GenericList < type > ( ) ; list.Add ( whatever ) ; list [ 0 ] ;
generic list class in c #
C#
So I have just caught this bug in our code : Is the order of execution in function invocation specified regarding the order of parameters ? What is written here is : Which means that the first parameter 's reference is saved before the second parameter 's function is invoked.Is this defined behavior ? I could not find ...
class A { public int a ; } var x = new A ( ) ; x.a = 1 ; A qwe ( ref A t ) { t = new A ( ) ; t.a = 2 ; return t ; } void asd ( A m , A n ) { Console.WriteLine ( m.a ) ; Console.WriteLine ( n.a ) ; } asd ( x , qwe ( ref x ) ) ; asd ( x , qwe ( ref x ) ) ; 1222
What is C # order of execution in function call with ref ?
C#
So , the quote comes from `` Dependency Injection in .NET '' . Having that in consideration , is the following class wrongly designed ? So this FallingPiece class has the responsibility of controlling the current falling piece in a tetris game . When the piece hits the bottom or some other place , raises an event signa...
class FallingPiece { //depicts the current falling piece in a tetris game private readonly IPieceGenerator pieceGenerator ; private IPiece currentPiece ; public FallingPiece ( IPieceGenerator pieceGenerator ) { this.pieceGenerator = pieceGenerator ; this.currentPiece = pieceGenerator.Generate ( ) ; //I 'm performing wo...
`` Classes should never perform work involving Dependencies in their constructors . ''
C#
This example is a simplification of the real problem , but how can I get this to compile ? I would expect the generics constraints to propagate.Since T is a TClass and TClass is a class , why isnt T a class ? EDIT : This actually works . Eric Lippert made me think , thanks.Since T is a TClass and TClass is a TAnotherTy...
public class MyClass < TClass > where TClass : class { public void FuncA < Ta > ( ) where Ta : class { } public void FuncB < Tb > ( ) where Tb : TClass { } public void Func < T > ( ) where T : TClass { FuncA < T > ( ) ; FuncB < T > ( ) ; } } public class MyClass < TClass , TAnotherType > where TClass : TAnotherType { p...
C # generics contraints propagation
C#
My colleague keeps telling me of the things listed in comments.I am confused.Can somebody please demystify these things for me ?
class Bar { private int _a ; public int A { get { return _a ; } set { _a = value ; } } private Foo _objfoo ; public Foo OFoo { get { return _objfoo ; } set { _objfoo = value ; } } public Bar ( int a , Foo foo ) { // this is a bad idea A = a ; OFoo = foo ; } // MYTHS private void Method ( ) { this.A //1 - this._a //2 - ...
C # myths about best practices ?
C#
I get a ProtoException ( `` Possible recursion detected ( offset : 4 level ( s ) ) : o EOW '' ) when serializing a tree structure like so : The tree implementation : Am I decorating with the wrong attributes or have I simply designed a non-serializable tree ? Edit : tried this to no avail :
var tree = new PrefixTree ( ) ; tree.Add ( `` racket '' .ToCharArray ( ) ) ; tree.Add ( `` rambo '' .ToCharArray ( ) ) ; using ( var stream = File.Open ( `` test.prefix '' , FileMode.Create ) ) { Serializer.Serialize ( stream , tree ) ; } [ ProtoContract ] public class PrefixTree { public PrefixTree ( ) { _nodes = new ...
Serialize prefix tree
C#
I defined this method : For converting Lists of Type 1 to Lists of Type 2.Unfortunately I forgot , that C # compiler can not say at this stage that T1 is convertible to T2 , so it throws error : error CS0030 : Can not convert type T1 to T2Can someone direct me how to do it properly ? I need this method for now only to ...
public static List < T2 > ConvertList < T1 , T2 > ( List < T1 > param ) where T1 : class where T2 : class { List < T2 > result = new List < T2 > ( ) ; foreach ( T1 p in param ) result.Add ( ( T2 ) p ) ; return result ; } public static List < T2 > ConvertList < T1 , T2 > ( List < T1 > param ) where T2 : base of T1
Generic method and converting : how to define that Type 1 is convertible to Type 2
C#
When using a very simple expression as key to create an ILookup with Enumerable.ToLookup < TSource , TKey > Method ( IEnumerable < TSource > , Func < TSource , TKey > ) I can use a lambda expression : or a local function : I 'm curious if there is a difference in this simple case.In his answer to Local function vs Lamb...
var lk = myItems.ToLookup ( ( x ) = > x.Name ) ; var lk = myItems.ToLookup ( ByName ) ; string ByName ( MyClass x ) { return x.Name ; }
Performance of assigning a simple lambda expression or a local function to a delegate
C#
The aim is to see the list as a list of 'name's.Here 's the dictionary : Here 's the attribute 'name ' I 'm after : And here 's the problem : I just ca n't think how to make that line work ! Your advice is much appreciated ! Thanks
class Scripts { public Dictionary < int , Script > scripts = new Dictionary < int , Script > ( ) ; ... } class Script { public string name { get ; set ; } ... } public partial class MainForm : Form { Scripts allScripts ; public MainForm ( ) { InitializeComponent ( ) ; allScripts = new Scripts ( ) ; setupDataSources ( )...
C # Can I display an Attribute of an Object in a Dictionary as ListControl.DisplayMember ?
C#
I have a project where I am using C # 7 features . It builds fine locally , but when I build in Visual Studio Team Services , I get errors . All the errors point to this one project and they all look related to C # 7 : The project targets.NET 4.6.1 and references Microsoft.CodeDom.Providers.DotNetCompilerPlatform 1.0.3...
Identifier expected Invalid expression term 'int ' Syntax error , ' , ' expected Syntax error , ' > ' expected ) expected ; expected
Deploying C # 7 code to VSTS
C#
I am calling a function which returns a string containing XML data . How this function works is not important but the resulting xml can be different depending on the success of the function.Basically the function will return either the expect XML or an error formatted XML . Below are basic samples of what the two resul...
< SpecificResult > < Something > data < /Something > < /SpecificResult > < ErrorResult > < ErrorCode > 1 < /ErrorCode > < ErrorMessage > An Error < /ErrorMessage > < /ErrorResult > string xml = GetXML ( ) ; if ( ! IsError ( xml ) ) { //convert to known type and process }
Checking XML for expected structure
C#
I 'm trying to write a generic method that supplies parameters and calls a function , like this : The last line fails to compile with CS0411 . Is there any workaround to get type inference to work here ? Use case : using AutoFixture to generate function call parameters .
class MyClass { public int Method ( float arg ) = > 0 ; } TResult Call < T1 , TResult > ( Func < T1 , TResult > func ) = > func ( default ( T1 ) ) ; void Main ( ) { var m = new MyClass ( ) ; var r1 = Call < float , int > ( m.Method ) ; var r2 = Call ( m.Method ) ; // CS0411 }
C # method group type inference