lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a method that returns a new list ( it pertains to a multiple choice answer ) : If I examine the result of this method - I see the correct data , e.g . Red = False , Green = True , Blue = FalseI then try to filter the returned result using the LINQ Where extension method : When I materialise tmpA , 2 things happe...
public static List < questionAnswer > GetAnswersWithSelections ( this Questions_for_Exam__c question ) { List < questionAnswer > answers = new List < questionAnswer > ( ) ; answers.Add ( new questionAnswer ( ) { Ordinal = 1 , AnswerText = question.AN1__c , Selected = ( bool ) question.Option1__c } ) ; ... return answer...
LINQ WHERE method alters source collection
C#
Given documentation for string.StartsWith and this snippet ( targeting .net core 2.x ) : This method compares the value parameter to the substring at the beginning of this string that is the same length as value , and returns a value that indicates whether they are equal . To be equal , value must be an empty string ( ...
static void Main ( string [ ] args ) { var unicodeCtrl = `` \u0000 '' ; var str = `` x '' ; Console.WriteLine ( $ '' Is it empty = > { unicodeCtrl == string.Empty } '' ) ; Console.WriteLine ( $ '' Lenghts = > { str.Length } { unicodeCtrl.Length } '' ) ; Console.WriteLine ( $ '' Are they equal = > { str == unicodeCtrl }...
Inconsistent string.StartsWith on different platforms
C#
In my app I 'm creating folders for archiving old stuff from a harddisc.When creating a new folder I must copy all NTFS rights ( Groups / Users ) from the source folder to the newly created destination folder.Here is what I 've written so far : Is this really all I ought to do or am I missing something important ?
FileSecurity fileSecurity = File.GetAccessControl ( filenameSource , AccessControlSections.All ) ; FileAttributes fileAttributes = File.GetAttributes ( filenameSource ) ; File.SetAccessControl ( filenameDest , fileSecurity ) ; File.SetAttributes ( filenameDest , fileAttributes ) ;
How do I copy security information when creating a new folder ?
C#
I need to assign continuous Ids for some threads when i 'm creating them , and does n't matter what starting id is ( like 11 , 12 , 13 , .. or 9 , 10 , 11 ) This is what i have done , here i am creating 4 threads and invoke My_function ( ) it seems working but can i be guaranteed that i always assign continuous id 's f...
for ( byte i = 0 ; i < 4 ; i++ ) { myThreadArray [ i ] = new Thread ( new ParameterizedThreadStart ( My_function ) ) ; myThreadArray [ i ] .Start ( i ) ; }
how to make threads with continuous id 's
C#
I have a method that uses recursion to traverse a tree and update the items.Currently the method takes pretty long to process all the items , so i started optimizing things . Among those things is the use of a dictionary instead of executing a DB query for each item.The dictionary is defined asThe key type is defined a...
System.Collections.Generic.Dictionary < EffectivePermissionKey , MyData > private struct EffectivePermissionKey { // http : //blog.martindoms.com/2011/01/03/c-tip-override-equals-on-value-types-for-better-performance/ public override bool Equals ( object aObject ) { if ( aObject == null ) return false ; else return aOb...
Why is my dictionary performing poorly with composite keys in C # ?
C#
Example : I want the output same charterers as per given input string length . The output should be `` aaaaa '' .I dont like to use own FOR or While loops logic , is there any alternatives to accomplish it .
string input = `` super '' ; string rep = `` a '' ;
How to replace whole characters in a string as same characters in c # ?
C#
I inherited some code and ca n't figure out one piece of it : Can anyone tell what 's happening here ?
byte [ ] b = new byte [ 4 ] { 3 , 2 , 5 , 7 } ; int c = ( b [ 0 ] & 0x7f ) < < 24 | b [ 1 ] < < 16 | b [ 2 ] < < 8 | b [ 3 ] ;
Need help understanding usage of bitwise operators
C#
Shortly , The new C # 6.0 Auto-Implemented Property allows us to make thisNow in somewhere , I changed the property IsSoundEffects = false , So accessing it will be false.hmm , So how to get the actual real default compile-time auto-implemented property value.Something Like : Type.GetPropertyDefaultValue ( IsSoundEffec...
public static bool IsSoundEffects { get ; set ; } = true ; // C # 6.0 allows this default ( IsSoundEffects ) // idk , something like that
How to get default compile-time value of Auto-Implemented property C # 6.0 after it changed ?
C#
I 've started using nullable reference types in C # 8 . So far , I 'm loving the improvement except for one small thing.I 'm migrating an old code base , and it 's filled with a lot of redundant or unreachable code , something like : Unfortunately , I do n't see any warning settings that can flag this code for me ! Was...
void Blah ( SomeClass a ) { if ( a == null ) { // this should be unreachable , since a is not nullable } }
In C # 8 , how do I detect impossible null checks ?
C#
Here are a few example of classes and properties sharing the same identifier : This problem occurs more frequently when using POCO with the Entity Framework as the Entity Framework uses the Property Name for the Relationships.So what to do ? Use non-standard class names ? YukOr use more descriptive Property Names ? Les...
public Coordinates Coordinates { get ; set ; } public Country Country { get ; set ; } public Article Article { get ; set ; } public Color Color { get ; set ; } public Address Address { get ; set ; } public Category Category { get ; set ; } public ClsCoordinates Coordinates { get ; set ; } public ClsCountry Country { ge...
How to avoid using the same identifier for Class Names and Property Names ?
C#
I wrote the following method to determine the max file size : Code Complete recommends to `` use recursion selectively '' . That being the case , I was wondering if the community thought this was a valid use of recursion . If not , is there a better technique of doing this ? EDIT : I ca n't use LINQ because its not ava...
public static long GetMaxFileSize ( string dirPath , long maxFileSize ) { DirectoryInfo [ ] dirInfos = new DirectoryInfo ( dirPath ) .GetDirectories ( ) ; foreach ( DirectoryInfo dirInfo in dirInfos ) { DirectoryInfo [ ] subDirInfos = dirInfo.GetDirectories ( ) ; foreach ( DirectoryInfo subDirInfo in subDirInfos ) maxF...
Is Recursion the Best Option for Determining the Max File Size in a Directory
C#
Same different behavior can be founded when compiling Expression.Convert for this conversions : Single - > UInt32Single - > UInt64Double - > UInt32Double - > UInt64Looks strange , is n't it ? < === Added some my research === > I 'm looked at the compiled DynamicMethod MSIL code using DynamicMethod Visualizer and some r...
using System ; using System.Linq.Expressions ; class Program { static void Main ( ) { Expression < Func < float , uint > > expr = x = > ( uint ) x ; Func < float , uint > converter1 = expr.Compile ( ) ; Func < float , uint > converter2 = x = > ( uint ) x ; var aa = converter1 ( float.MaxValue ) ; // == 2147483648 var b...
Is this is an ExpressionTrees bug ?
C#
I 'm getting the error `` FormatException was unhandled '' - on this : I need to be able to do addition and division so that 's why I 'm trying to convert them into an integer . So I 'm not sure how to handle this , would I need to convert them back to string ? The Code : The Hours.txt file includes this : I 'm just tr...
List < int > myStringList = LoadHours.ConvertAll ( s = > Int32.Parse ( s ) ) ; //string txt = `` Account : xxx123xxx\r\nAppID 10 : 55 Hours 4 Minutes\r\n\r\nAccount : xxx124xxx\r\nAppID 730 : 62 Hours 46 Minutes\r\nAppID 10 : 3 Hours 11 Minutes\r\n\r\nAccount : xxx125xxx\r\nAppID 10 : 0 Hours 31 Minutes\r\n '' ; string...
C # - An unhandled exception of type System.FormatException - List String to List int
C#
We 've been using a legacy version ( 3.9.8 ) of ServiceStack for a while now and I decided to try an upgrade to the latest version ( 3.9.70 ) and while it was a clean , no hassle package upgrade - everything compiles and runs - every service URL now returns a `` Handler for Request not found '' 404 result.An example of...
routes.IgnoreRoute ( `` servicestack/ { *pathInfo } '' ) ; < add path= '' servicestack '' name= '' ServiceStack.Factory '' type= '' ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory , ServiceStack '' verb= '' * '' preCondition= '' integratedMode '' resourceType= '' Unspecified '' allowPathInfo= '' true '' /...
404 after upgrading ServiceStack from 3.9.8 to 3.9.70 ( new API )
C#
We are seeing a memory leak with one of our WCF applications and I was wondering if someone could clarify something for me . Using windbg I ran ! finalizequeue and it shows thousands of objects in each Heap set as `` Ready for finalization '' . That tells me that the finalizer thread is stuck . So I ran the ! Threads c...
Heap 0generation 0 has 464 finalizable objects ( 0000000033877190- > 0000000033878010 ) generation 1 has 52 finalizable objects ( 0000000033876ff0- > 0000000033877190 ) generation 2 has 19958 finalizable objects ( 0000000033850040- > 0000000033876ff0 ) Ready for finalization 228791 objects ( 0000000033878010- > 0000000...
Finalizer Thread Id
C#
According to MSDN Libraryusing Statement ( C # Reference ) Defines a scope , outside of which an object or objects will be disposed.But I got this code posted here by some user and I got confused about this : ( please see my comment on the code ) In the above code , does the using statement properly used ? I 'm confuse...
using ( OleDBConnection connection = new OleDBConnection ( connectiongString ) ) { if ( connection.State ! = ConnectionState.Open ) connection.Open ( ) ; string sql = `` INSERT INTO Student ( Id , Name ) VALUES ( @ idParameter , @ nameParameter ) '' ; using ( OleDBCommand command = connection.CreateCommand ( ) ) { comm...
Confused using `` using '' Statement C #
C#
I have a model where I am using a discriminator.As I can not share the original code , here is a mockupNow I want my entities to be sorted by the Discriminator , having SomeDog first and only after these , having my Dog entities.Is there any way to actually sort on my Discriminator ? Or do I have to find a workaround ?
public class Dog { } public class SomeDog : Dog { }
Sort on discriminator - EF
C#
I 'm writing a bijective dictionary class , but I want to ensure the two generic types are not the same type for two reasons.Firstly , I would like it to implement the IDictionary interface in both directions , but gives me `` 'BijectiveDictionary < TKey , TValue > ' can not implement both 'IDictionary < TKey , TValue ...
public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TValue > , IDictionary < TValue , TKey > public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TValue > where TValue : TKey { // Optimized solution } public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TV...
Using Where to specify different generics
C#
The ProblemConsider these two extension methods which are just a simple map from any type T1 to T2 , plus an overload to fluently map over Task < T > : Now , when I use the second overload with a mapping to a reference type ... ... I get the following error : CS0121 : The call is ambiguous between the following methods...
public static class Ext { public static T2 Map < T1 , T2 > ( this T1 x , Func < T1 , T2 > f ) = > f ( x ) ; public static async Task < T2 > Map < T1 , T2 > ( this Task < T1 > x , Func < T1 , T2 > f ) = > ( await x ) .Map ( f ) ; } var a = Task .FromResult ( `` foo '' ) .Map ( x = > $ '' hello { x } '' ) ; // ERRORvar b...
How to explain this `` call is ambiguous '' error ?
C#
I wish to transform code like : To : As a first step in making the code more readable , I am willing to use a 3rd party refactoring tool if need be . ( Please do not tell me to use parameter objects and factor methods etc , these may come later once I can at least read the code ! )
var p = new Person ( `` Ian '' , `` Smith '' , 40 , 16 ) var p = new Person ( surname : `` Ian '' , givenName : '' Smith '' , weight:40 , age:16 )
Is there any tools to help me refactor a method call from using position-based to name-based parameters
C#
In my Web API controller method , before I map the UpdatePlaceDTO to PlaceMaster , I make a database call to populate the properties that are not covered by the Map but for some reason AutoMapper makes those properties null.I 've tried many of the solutions to IgnoreExistingMembers but none of them work.This is what I ...
var mappedPlaceMaster = _mapper.Map < PlaceMaster > ( placeMasterDTO ) ; // mappedPlaceMaster.EntityId is null public class PlaceMapperProfile : Profile { protected override void Configure ( ) { // TO DO : This Mapping doesnt work . Need to ignore other properties //CreateMap < UpdatePlaceDto , PlaceMaster > ( ) // .Fo...
AutoMapper 4.2 not ignoring properties in profile
C#
In Microsoft 's example for how to use the PixelShader they use a singleton . I 've seen the same pattern in other places , and here they say The pixel shader is stored in a private static field _pixelShader . This field is static , because one instance of the compiled shader code is enough for the whole class.We 've s...
// Attach/detach effect as UI element is loaded/unloaded . This avoids // a memory leak in the shader code as described here : element.Loaded += ( obj , args ) = > { effect.PixelShader = ms_shader ; element.Effect = effect ; } ; element.Unloaded += ( obj , args ) = > { effect.PixelShader = null ; element.Effect = null ...
Should using a singleton PixelShader be a best practice ?
C#
I need to make the graph and I want to the edges and the vertices to be generic typeBut , the edge required the vertex type and the vertex required the edge typeWhat should I do ?
public interface IVertex < TVertex , TEdge > where TVertex : IVertex < ? > where TEdge : IEdge < ? > { bool AddEdge ( TEdge e ) ; TEdge FindEdge ( TVertex v ) ; } public interface IEdge < TVertex > where TVertex : IVertex < ? > { TVertex From { get ; } }
Looping generic type in c #
C#
We have a Single Page App which calls our back-end services ( C # and Python ) , authorizing these requests using the Auth0 SPA flow.Our back end services only make requests to each other as part of processing a request from an SPA user , so currently we just forward the Authorization header from the SPA request , usin...
sub : SPA-USER-IDaud : SPA-CLIENT-ID sub : SERVICE-ID @ clientsaud : API-IDscope : `` ''
Using Auth0 to Authorize API requests from both our SPA and our other back-end services
C#
I have a console application and website that use the same System.Runtime.Serialization.Primitives.dll assembly . However , when I run the website , my assembly is the one on the right , but if I run consolation application , the DLL for the website turns to the one on the left and causes errors . Both projects are v4....
< dependentAssembly > < assemblyIdentity name= '' System.Runtime.Serialization.Primitives '' publicKeyToken= '' b03f5f7f11d50a3a '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-4.1.2.0 '' newVersion= '' 4.1.2.0 '' / > < /dependentAssembly >
Different DLL but should be the same in console application and website
C#
When I call an async method and get a task back , will that immediately throw or will it wait until I await the task ? In other words , will this code work ? Or will I have to wrap the method call in the try-block as well ?
Task task = ThisMethodWillThrow ( ) ; try { await task ; } catch ( Exception e ) { Console.WriteLine ( `` oops '' ) ; }
Do async methods throw exceptions on call or on await ?
C#
For all of my POCOs , the navigation and collection properties are all null.Let me provide some background . I have a complex code first project using EF 4.3.1 . Proxy generation was disabled . Collection and navigation properties were managed manually.I 'm now enabling proxy creation and lazy loading . When debugging ...
public virtual NavigationType NavigationName { get ; set ; } public virtual ICollection < CollectionType > CollectionName { get ; set ; } modelBuilder.Entity < TEntity > ( ) .Map ( m = > { m.MapInheritedProperties ( ) ; m.ToTable ( `` TableName '' ) ; } ) ;
code first auto gen proxy class navigation and collection properties are null
C#
( Apologies for the long setup . There is a question in here , I promise . ) Consider a class Node that has an immutable unique ID that is assigned at construction time . This ID is used for serialization when persisting the object graph , among other things . For example , when an object is deserialized , it gets test...
interface INode { NodeID ID { get ; } // ... other awesome stuff } class Node : INode { readonly NodeID _id = NodeID.CreateNew ( ) ; NodeID INode.ID { get { return _id ; } } // ... implement other awesome stuff public override bool Equals ( object obj ) { var node = obj as INode ; return ReferenceEquals ( node , null )...
How do immutable ID properties affect .NET equality ?
C#
I 'm trying to create a shared library project containing some POCO classes used to serialize data among multiple clients ( WPF / SL5 / Asp.Net ) . Before Asp.Net vNext , I was using PCL without problem . Now MVC 6 is there , I tried to add Asp.Net Core 5 target to the PCL , but it seems impossible : I guess the corres...
`` frameworks '' : { `` dotnet '' : { } , `` dnx46 '' : { } , `` dnxcore50 '' : { } , `` sl5 '' : { } } Error CS0518 : Predefined type 'System.Object ' is not defined or imported Error CS0246 : The type or namespace name 'String ' could not be found ( are you missing a using directive or an assembly reference ? )
Class Library Package : sl5 target issue
C#
So , I have the airdrop feature working but I need different things to happen if the user presses accept and if the user presses deny for the airdrop request . Currently , the same actions happen whether the user accepts or denies the airdrop request . I 'm using which has this signature : The problem is none of these ...
activityViewController.SetCompletionHandler ( HandleActivityViewControllerCompletion ) ; private async void HandleActivityViewControllerCompletion ( NSString activityType , bool completed , NSExtensionItem [ ] returnedItems , NSError error )
Is there a way to detect if user presses accept or deny for Airdrop request ?
C#
I 've implemented simple IQueryable and IQueryProvider classes that collect statistical data on LINQ expression trees . This part works fine . Next , I would like to pass the expression tree off to the default LINQ-to-Objects provider for evaluation , since I do n't need to execute it any differently . In order words ,...
IQueryProvider IQueryable.Provider { get { return _my_provider.OriginalIEnum ( ) .AsQueryable ( ) .Provider ; } }
LINQ passthrough provider ?
C#
I expected the following lines of code to throw an exception since I am accessing the Value property of a nullable variable that is assigned a value of null . However , I do not get any exception when I execute the below : But when I do : I do get an exception , as could be expected.But what is the difference between t...
int ? x=null ; Console.WriteLine ( x.Value==null ) ; Console.WriteLine ( x.Value ) ;
Why does this code not throw an exception ?
C#
I have code like this : How can I write this code in a convenient way such that : There is no nullability warning , because the type nonNullItems is inferred as IEnumerable < string > .I do n't need to add unchecked non-nullability assertions like item ! ( because I want to benefit from the compilers sanity checking , ...
IEnumerable < string ? > items = new [ ] { `` test '' , null , `` this '' } ; var nonNullItems = items.Where ( item = > item ! = null ) ; //inferred as IEnumerable < string ? > var lengths = nonNullItems.Select ( item = > item.Length ) ; //nullability warning hereConsole.WriteLine ( lengths.Max ( ) ) ; var notNullItems...
Is there a convenient way to filter a sequence of C # 8.0 nullable references , retaining only non-nulls ?
C#
I have part of a code that has dependencies that look as follows : My module configuration looks as followsAs can be seen , I have circular dependencies in my classes which I was able to resolve by using the ..PropertiesAutowired ( PropertyWiringFlags.AllowCircularDependencies ) ... My Question : What exactly does this...
public class MyPage : Page //ASPX WebForms page { public IPersonBl PersonBl { get ; set ; } } public class PersonBl : IPersonBl { public PersonBl ( ISomeMagicBl magicBl ) { ... } } public class SomeMagicBl : ISomeMagicBl { public IPersonBl PersonBl { get ; set ; } public SomeMagicBl ( /*Other dependencies*/ ) { ... } }...
AutoFac : What does PropertyWiringFlags.AllowCircularDependencies do ?
C#
I 've created a rollback/retry mechanism using the Command Pattern and a custom retry mechanism with the RetryCount and timeout threshold properties as input ( As described here Which is the best way to add a retry/rollback mechanism for sync/async tasks in C # ? ) . I also tried the Polly framework instead and it is g...
//Pseudo-code ... CommandHandler actionManager1 = new Action1Manager ( ) ; CommandHandler actionManager2 = new Action2Manager ( ) ; CommandHandler actionManager2 = new Action3Manager ( ) ; actionManager1.SetNextObjManager ( Action2Manager ) ; actionManager2.SetNextObjManager ( Action3Manager ) ; actionManager1.ProcessA...
How to create a strategy decision mechanism based on the results combinations of multi-commands in C #
C#
I have this : And my utility class for databinding does this : But PropertyInfo.CanWrite does not care whether the set is publicly accessible , only that it exists.How can I determine if there 's a public set , not just any set ?
public string Log { get { return log ; } protected set { if ( log ! = value ) { MarkModified ( PropertyNames.Log , log ) ; log = value ; } } } PropertyInfo pi = ReflectionHelper.GetPropertyInfo ( boundObjectType , sourceProperty ) ; if ( ! pi.CanWrite ) SetReadOnlyCharacteristics ( boundEditor ) ;
How do I tell if a class property has a public set ( .NET ) ?
C#
How do I know if a class in C # is unmanaged , so that if I use it in a self defined class I know whether I have to implement the IDisposable interface ? If I get this article on the MSDN network right , I always have to implement the IDisposible interface when I use an unmanaged resource.So I 've created a little exam...
class TestClass { private StreamReader reader ; public UsingTestClass ( ) { reader = File.OpenText ( `` C : \\temp\\test.txt '' ) ; string s ; while ( ! string.IsNullOrEmpty ( s = reader.ReadLine ( ) ) ) { Console.WriteLine ( s ) ; } } }
How do I know if a class is a wrapper for an unmanaged resource
C#
When a class is IComparable , then we know everything to overload the < , > and == operators due to the CompareTo functionality , right ? Then why are n't these overloaded automatically ? Take a look at the example below : I was wondering why something like this would n't work by default : We know that obj1 < obj2 == t...
public class MyComparable : IComparable < MyComparable > { public int Value { get ; } public MyComparable ( int value ) { Value = value ; } public int CompareTo ( MyComparable other ) = > Value.CompareTo ( other.Value ) ; } MyComparable obj1 = new MyComparable ( 1 ) , obj2 = new MyComparable ( 2 ) ; if ( obj1 < obj2 ) ...
Why are the comparison operators not automatically overloaded with IComparable ?
C#
I have a particular situation where I need to trap exceptions and return an object to the client in place of the exception . I can not put the exception handling logic at a higher level i.e . wrap Foo within a try clause.It 's best to demonstrate with some sample code . The exception handling logic is clouding the inte...
public class Foo { public Bar SomeMethodThatCanThrowExcepetion ( ) { try { return new Bar ( ) .Execute ( ) ; } catch ( BazException ex ) { WriteLogMessage ( ex , Bar.ErrorCode ) ; return new Bar ( ) { ErrorMessage = ex.Message , ErrorCode = Bar.ErrorCode ; } } } public Baz SomeMethodThatCanThrowExcepetion ( SomeObject ...
How can I make this exception handling code adhere to the DRY principle ?
C#
I 'm reviewing some code on the project I recently joined , and in a C # Win Forms Application for .NET 3.5 I found this : When I click `` EndPoint/Go To Definition '' it says `` Can not Navigate to Endpoint '' but the project as a whole is pretty small and compiles/runs without error , so it 's not a missing reference...
public void foo ( ) { //Normal code for function foo.//This is at the end and it is left-indented just as I put it here.EndPoint : { } }
EndPoint : Syntax in C # - what is this ?
C#
i 'm trying to do for an expression tree and try to let it return a simple int value . but it not working anymore
var method = typeof ( Console ) .GetMethod ( `` WriteLine '' , new Type [ ] { typeof ( string ) } ) ; var result = Expression.Variable ( typeof ( int ) ) ; var block = Expression.Block ( result , Expression.Assign ( result , Expression.Constant ( 0 ) ) , Expression.IfThenElse ( Expression.Constant ( true ) , Expression...
How to return value in ExpressionTree
C#
I created labels and textboxes dynamically . everything goes fine , but the second label does n't want to appear at all . where i am wrong ? this is my code in C # :
private void checkedListBox1_SelectedIndexChanged ( object sender , EventArgs e ) { OracleDataReader reader ; int x = 434 ; int y = 84 ; int i = 0 ; try { conn.Open ( ) ; foreach ( var itemChecked in checkedListBox1.CheckedItems ) { Label NewLabel = new Label ( ) ; NewLabel.Location = new Point ( x + 100 , y ) ; NewLab...
where I am wrong ? creating labels dynamically c #
C#
I have a string in the following format.My desired output should be something like this below : But currently , I get the one below : I am very new to C # and any help would be appreciated .
string instance = `` { 112 , This is the first day 23/12/2009 } , { 132 , This is the second day 24/12/2009 } '' private void parsestring ( string input ) { string [ ] tokens = input.Split ( ' , ' ) ; // I thought this would split on the , seperating the { } foreach ( string item in tokens ) // but that does n't seem t...
Efficiently split a string in format `` { { } , { } , ... } ''
C#
I 'm trying to iterate through some files and fetch their shell icons ; to accomplish this , I 'm using DirectoryInfo.EnumerateFileSystemInfos and some P/Invoke to call the Win32 SHGetFileInfo function . But the combination of the two seems to corrupt memory somewhere internally , resulting in ugly crashes.I 've boiled...
using System ; using System.Linq ; using System.Collections.Generic ; using System.Diagnostics ; using System.IO ; using System.Runtime.InteropServices ; using System.Windows ; using System.Windows.Interop ; using System.Windows.Media.Imaging ; namespace IconCrashRepro { // Compile for .NET 4 ( I 'm using 4.5.1 ) . // ...
Why does this interop crash the .NET runtime ?
C#
I 'm using WindowsPrincipal 's IsInRole method to check group memberships in WPF and Winforms apps . I 'm generating an identity token which can be for any AD user ( not necessarily the user who 's actually logged into the computer -- depending on what I 'm doing I do n't necessarily authenticate , I just use the basic...
Using System.Security.Principal ; WindowsIdentity impersonationLevelIdentity = new WindowsIdentity ( `` Some_UserID_That_Isn't_Me '' , null ) ; WindowsPrincipal identityWindowsPrincipal = new WindowsPrincipal ( impersonationLevelIdentity ) ; If ( identityWindowsPrincipal.IsInRole ( `` AN_AD_GROUP '' ) ) { ... Imports S...
IsInRole Getting New Security Token
C#
Just playing around with concurrency in my spare time , and wanted to try preventing torn reads without using locks on the reader side so concurrent readers do n't interfere with each other.The idea is to serialize writes via a lock , but use only a memory barrier on the read side . Here 's a reusable abstraction that ...
public struct Sync < T > where T : struct { object write ; T value ; int version ; // incremented with each write public static Sync < T > Create ( ) { return new Sync < T > { write = new object ( ) } ; } public T Read ( ) { // if version after read == version before read , no concurrent write T x ; int old ; do { // l...
C # /CLR : MemoryBarrier and torn reads
C#
Given the following function : I would like to accomplish this . The function GetValue ( ) can be called from different parts of the program . While GetValueFromServer ( ) is running I do n't want to initiate another call to it . All calls to to GetValue ( ) while GetValueFromServer ( ) is running should return the sam...
public async Task < int > GetValue ( ) { var value = await GetValueFromServer ( ) ; return value ; } 0.0 : var a = await GetValue ( ) 0.1 : call to GetValueFromServer ( ) 0.3 : var b = await GetValue ( ) ; 0.6 : var c = await GetValue ( ) ; 0.7 : GetValueFromServer ( ) returns 1 0.9 : var d = await GetValue ( ) ; 1.0 :...
Return the same value for multiple function calls while a request is ongoing using async/await
C#
Is it a bad practice or code smell to use an IoC container while installing dependencies ? This is my composition root : My AutoMapperProfileInstallerneeds to resolve a profile which contains dependencies in order to initialize the mapperThis feels wrong on many levels , what would be a better way to initialize AutoMap...
public void Install ( IWindsorContainer container , IConfigurationStore store ) { Assembly modelAssembly = typeof ( UserLoginModel ) .Assembly ; Assembly controllerAssembly = typeof ( HomeController ) .Assembly ; container.Install ( new MvcInfrastructureInstaller ( modelAssembly , viewAssembly , controllerAssembly , ap...
Is it a bad practice or code smell to use an IoC container while installing dependencies ?
C#
I am currently working on windows phone 8 and I have created a ListBox with Ellipse inside it to show images . Now I want to change the Stroke Colour for it when user selects any item in ListBox . My ListBox XAML code and its DataTemplate is belowDataTemplateI know how to change foreground of an entire list item , but ...
< ListBox x : Name= '' OwnerList '' ScrollViewer.HorizontalScrollBarVisibility= '' Auto '' ScrollViewer.VerticalScrollBarVisibility= '' Disabled '' ItemsPanel= '' { StaticResource FileItemsPanel } '' ItemTemplate= '' { StaticResource OwnerListTemplate } '' SelectionMode= '' Multiple '' SelectionChanged= '' OwnerList_Se...
How to change stroke of Ellipse when ListBox item is selected in Windows Phone 8 ?
C#
I have been doing a little work with regex over the past week and managed to make a lot of progress , however , I 'm still fairly n00b . I have a regex written in C # : For some reason , when calling the regular expression IsMethodRegex.IsMatch ( ) it hangs for 30+ seconds on the following string : Does anyone how the ...
string isMethodRegex = @ '' \b ( public|private|internal|protected ) ? \s* ( static|virtual|abstract ) ? `` + @ '' \s* ( ? < returnType > [ a-zA-Z\ < \ > _1-9 ] * ) \s ( ? < method > [ a-zA-Z\ < \ > _1-9 ] + ) \s*\ '' + @ '' ( ( ? < parameters > ( ( [ a-zA-Z\ [ \ ] \ < \ > _1-9 ] *\s* [ a-zA-Z_1-9 ] *\s* ) [ , ] ? \s* ...
Regular Expressions in C # running slowly
C#
I have a snippet of code that I thought would work because of closures ; however , the result proves otherwise . What is going on here for it to not produce the expected output ( one of each word ) ? Code : Output :
string [ ] source = new string [ ] { `` this '' , `` that '' , `` other '' } ; List < Thread > testThreads = new List < Thread > ( ) ; foreach ( string text in source ) { testThreads.Add ( new Thread ( ( ) = > { Console.WriteLine ( text ) ; } ) ) ; } testThreads.ForEach ( t = > t.Start ( ) ) otherotherother
Odd ( loop / thread / string / lambda ) behavior in C #
C#
I just started looking at IL a bit and I 'm curious if my attempt ( shown below ) to remove excess code from the output of the compiler had any unintended side effects.A couple of quesiton about the results : What is the purpose of the nop operations in the original ? What is the purpose of the br.s at the end of the m...
class Program { public static int Main ( ) { return Add ( 1 , 2 ) ; } public static int Add ( int a , int b ) { return a + b ; } } .method public hidebysig static int32 Main ( ) cil managed { .entrypoint .maxstack 2 .locals init ( int32 V_0 ) IL_0000 : nop IL_0001 : ldc.i4.1 IL_0002 : ldc.i4.2 IL_0003 : call int32 Prog...
Questions about hand coded IL based on disassembled simple C # code
C#
I 'm trying to register a user using C # in asp.net and then put their details into my database . Everything seems to work fine but the details do n't go into the database.Here 's what I have so far : and on the web.config page I have the connection string : Any idea what I 'm doing wrong ? Any help would be appreciate...
protected void CreateUser_Click ( object sender , EventArgs e ) { var manager = Context.GetOwinContext ( ) .GetUserManager < ApplicationUserManager > ( ) ; var signInManager = Context.GetOwinContext ( ) .Get < ApplicationSignInManager > ( ) ; var user = new ApplicationUser ( ) { UserName = Email.Text , Email = Email.Te...
Enter user details into database after registration
C#
Why if I write it compiles.And in case if I write It does n't ? It 's clear that from pure functional point of view the declaration of the variable in the second example is useless , but why it magically becomes usefull in first example , so ? The IL code produced by both examples is exactly the same . EDIT : Forgot to...
void Main ( ) { string value = @ '' C : \ '' ; if ( ! string.IsNullOrEmpty ( value ) ) { string sDirectory = Path.GetDirectoryName ( value ) ; } } void Main ( ) { string value = @ '' C : \ '' ; if ( ! string.IsNullOrEmpty ( value ) ) string sDirectory = Path.GetDirectoryName ( value ) ; } IL_0000 : ldstr `` C : \ '' IL...
Why this compile error
C#
I have an extension method for testing so I can do this : The extension method : This shows : Is there any hack I can pull off to get the name of the property `` BrainsConsumed '' from within my extension method ? Bonus points would be the instance variable and type Zombie.UPDATE : The new ShouldBe : and this prints ou...
var steve = new Zombie ( ) ; steve.Mood.ShouldBe ( `` I 'm hungry for brains ! `` ) ; public static void ShouldBe < T > ( this T actual , T expected ) { Assert.That ( actual , Is.EqualTo ( expected ) ) ; } Expected : `` I 'm hungry for brains ! `` But was : `` I want to shuffle aimlessly '' public static void ShouldBe ...
Is this possible in C # ?
C#
Is there any ready to use solution to group events ? Say I have two events : A and B.I want a Method M to be executed when A and B have been fired , they do not need to fire exactly at the same time . Something like : Group event G fires after both , A and B have fired . I need to register Method M only at Group event ...
Events : A | B | G1 F 0 02 0 F F3 0 F 0 4 0 F 0 5 0 F 0 6 F 0 F7 F 0 08 0 F F9 0 0 0 10 F F F
grouping events in C #
C#
This is my code : My code takes a set of cards and represents your maximum possible score when playing against a deterministic opponent . After each of your opponent 's plays you have 2 choices until cards are all picked . Is there a way to somehow store my results of the iterations so I can improve my algorithm ? So t...
static int cardGameValue ( List < int > D , int myScore , int opponentScore ) { if ( D.Count == 0 ) return myScore ; else if ( D.Count == 1 ) { opponentScore += D [ 0 ] ; return myScore ; } else { if ( D [ 0 ] < = D [ D.Count - 1 ] ) { opponentScore += D [ D.Count - 1 ] ; D.RemoveAt ( D.Count - 1 ) ; } else { opponentS...
Improving recursion method in C #
C#
This is my first post here , hoping to start also posting more often in the future : ) I have been trying to learn to use Castle Windsor rather than using Ninject but there 's one feature I have n't been able to sort of `` translate '' to use in Windsor , and that is WhenInjectedInto . Here 's one example taken from Pr...
kernel.Bind < IValueCalculator > ( ) .To < LinqValueCalculator > ( ) ; kernel.Bind < IDiscountHelper > ( ) .To < FlexibleDiscountHelper > ( ) .WhenInjectedInto < LinqValueCalculator > ( ) ; container.Register ( Component.For < IValueCalculator > ( ) .ImplementedBy < LinqValueCalculator > ( ) ) ; container.Register ( Co...
Ninject feature ( WhenInjectedInto ) equivalent in Windsor
C#
What should I put in the ? ? to force objects that inherit from both Animal and IHasLegs ? I do n't want to see a Snake in that cage neither a Table. -- -- -- -- -- -- -- EDIT -- -- -- -- -- -- -- Thank you all for your answers , but here is the thing : What I actually want to do is this : TextBox/ComboBox is of course...
// interfacepublic interface IHasLegs { ... } // base classpublic class Animal { ... } // derived classes of Animalpublic class Donkey : Animal , IHasLegs { ... } // with legspublic class Lizard : Animal , IHasLegs { ... } // with legspublic class Snake : Animal { ... } // without legs// other class with legspublic cla...
C # declare both , class and interface
C#
I stumbled across a method in my code where a rounded value is calculated wrong in my code.I am aware about the problem with comparing double values generated unexpected results.ExampleExplanation here : http : //csharpindepth.com/Articles/General/FloatingPoint.aspxHowever , until now , I expected the Math.Round ( ) me...
double x = 19.08 ; double y = 2.01 ; double result = 21.09 ; if ( x + y == result ) { // this is never reached } var decimals = 2 ; var value1 = 4.725 ; var value2 = 4.725M ; var result1 = Math.Round ( value1 , decimals , MidpointRounding.ToEven ) ; var result2 = Math.Round ( value1 , decimals , MidpointRounding.AwayFr...
Math.Round ( ) yields unexpected result for double
C#
I have a list of lists that contain integers ( this list can be any length and can contain any number of integers : What I want to do next is combine the lists where any integer matches any integer from any other list , in this case : I have tried many different approaches but am stuck for an elegant solution .
{ { 1,2 } , { 3,4 } , { 2,4 } , { 9,10 } , { 9,12,13,14 } } result = { { 1,2,3,4 } , { 9,10,12,13,14 } }
Combine similar character in string in C #
C#
I have a data source that is comma-delimited , and quote-qualified . A CSV . However , the data source provider sometimes does some wonky things . I 've compensated for all but one of them ( we read in the file line-by-line , then write it back out after cleansing ) , and I 'm looking to solve the last remaining proble...
`` foobar '' , 356 , `` Lieu-dit `` chez Métral '' , Chilly , FR '' , `` -1,000.09 '' , 467 , `` barfoo '' , 1,345,456,235,231 , `` 935.18 '' `` foobar '' , 356 , `` Lieu-dit chez Métral , Chilly , FR '' , `` -1,000.09 '' , 467 , `` barfoo '' , 1,345,456,235,231 , `` 935.18 ''
Regular Expression to match a quoted string embedded in another quoted string
C#
In C # , I have a simple 3D vector class.the output is , vector a= 10 , 5 , 10vector b= 10 , 5 , 10I assign a before i change a.x to 10 . So i was expecting vector a= 10 , 5 , 10vector b= 0 , 5 , 10From what i understand = operator assigns a reference to object like a pointer ? And in C # i cant overload = operator . D...
static void Main ( string [ ] args ) { Vector3D a , b ; a = new Vector3D ( 0 , 5 , 10 ) ; b = new Vector3D ( 0 , 0 , 0 ) ; b = a ; a.x = 10 ; Console.WriteLine ( `` vector a= '' + a.ToString ( ) ) ; Console.WriteLine ( `` vector b= '' + b.ToString ( ) ) ; Console.ReadKey ( ) ; }
c # = operator problem
C#
I have this code to combine 2 different csv files . My BoxData = data1 ; data2 ; data3 ; data4 ; data5At the moment data2 to data5 is getting in JobStart file . Data5 should n't be included inside JobStart file . I want to set data5 as a global variable.How can I do this , I just can not figure this out , need help . T...
try { var jobStartLine = File.OpenText ( PackAuftrag ) .ReadLine ( ) ; var comparisonField = jobStartLine.Split ( ' ; ' ) [ 4 ] ; foreach ( var line in File.ReadAllLines ( BoxData ) ) { var fields = line.Split ( new char [ ] { ' ; ' } , 2 ) ; if ( comparisonField == fields [ 0 ] ) { File.WriteAllLines ( JobStart , new ...
How to Ignore a field and set the ignored field as a global variable within the function ?
C#
I am trying to list all objects ( Cube , dimension , partition , ... ) found in a SSAS server . I am able to do that using the following project : GitHub - SSASAMODBI am trying to retrieve the relevant directory ( within the data directory ) for each object . I am unable to do that since files names contains some Incre...
|Data Dir|\ < SSASDB > \TestCube.0.cub |Data Dir|\ < SSASDB > \TestCube.1.cub
Retrieve multidimensional database objects directories
C#
I have a utility I 'm testing with a few other people , that takes screenshots of another window and then uses OpenCV to find smaller images within that screenshot.That 's working without a problem , however , I 'm trying to make it more efficient , and was wondering , rather than taking a screenshot of the window ever...
public static bool ContainsImage ( Detection p_Detection , out long elapsed ) { Stopwatch stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; Image < Gray , byte > imgHaystack = new Image < Gray , byte > ( CaptureApplication ( p_Detection.WindowTitle ) ) ; Image < Gray , byte > imgNeedle = new Image < Gray , byte > (...
Alternative to taking rapid screenshots of a window
C#
Consider the following code , the first demonstrates that the `` cleanup '' executes when we 're finished iterating over the IEnumerable of strings . The second pass is what is causing me grief . I need to be able abandon the IEnumerable before reaching the end , and then have the clean up code execute . But if you run...
static void Main ( string [ ] args ) { // first pass foreach ( String color in readColors ( ) ) Console.WriteLine ( color ) ; // second pass IEnumerator < string > reader = readColors ( ) .GetEnumerator ( ) ; if ( reader.MoveNext ( ) ) { Console.WriteLine ( reader.Current ) ; reader.Dispose ( ) ; } } static IEnumerable...
How can I abandon an IEnumerator without iterating to the end ?
C#
I 'm porting Haskell's/LiveScript each function to C # and I 'm having some troubles . The signature of this function is ( a → Undefined ) → [ a ] → [ a ] and I work very well with typing and lambda expressions in Haskell or LS , but C # makes me confused . The final use of this extension method should be : And , with ...
String [ ] str = { `` Haskell '' , `` Scheme '' , `` Perl '' , `` Clojure '' , `` LiveScript '' , `` Erlang '' } ; str.Each ( ( x ) = > Console.WriteLine ( x ) ) ; HaskellSchemePerlClojureLiveScriptErlang public static void Each < T > ( this IEnumberable < T > list , Action closure ) { foreach ( var result in list ) { ...
Mixing extension methods , generics and lambda expressions
C#
i am trying to add field in json while deserializing the response from server and then storing it into database here is the model of Response QuotationConverter code where i am fetching customer name from another json and store it into quotationhere is the JsonConverterJson received from serverexpected json Quotation m...
public class Response : RealmObject { [ JsonConverter ( typeof ( QuotationConverter ) ) ] [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public IList < Quotation > quotationsList { get ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public IList < Order > ordersList { get ; } } ...
unable to update existing json list using jsonconverter
C#
I have a dozen methods in my project ( C # 2.0 ) that look like this : ... but for different 'entity ' classes . ( Okay , not quite that trivial , I 've simplified the code here . ) It looks like a good candidate for generics and I came up with this : And of course I get the `` Can not create an instance of the type pa...
internal bool ValidateHotelStayEntity ( DataRow row ) { return ( new HotelStayEntity ( row ) ) .Validate ( ) ; } internal bool ValidateEntity < T > ( DataRow row ) where T : EntityBase { return ( new T ( row ) ) .Validate ( ) ; }
Generics without new ( )
C#
Why does this program print `` Child Name '' instead of `` Base Name '' ? I expect that when I cast child to INamedObject , Name property of INamedObject explicit implementation will be invoked . But what happens is that Child.Name property is called.Why when I declare Child class like that ( removing INamedObject from...
using System ; class Program { static void Main ( string [ ] args ) { var child = new Child ( ) ; Console.WriteLine ( ( ( INamedObject ) child ) .Name ) ; Console.ReadLine ( ) ; } } interface INamedObject { string Name { get ; } } class Base : INamedObject { string INamedObject.Name { get { return `` Base Name '' ; } }...
Why explicit interface implementation works that way ?
C#
I have an Entity Framework Code First model for which I made a static generic class which has a search method which is called for every item in a list.Admitting that this is over my head , I thought making the class static would improve code clarity and maybe even performance as one does not have to create instances in...
public static class SearchUserVisibleProperties < T > { private static List < PropertyInfo > userVisibleProperties { get ; set ; } static SearchUserVisibleProperties ( ) { userVisibleProperties = typeof ( T ) .GetProperties ( ) .Where ( prop = > Attribute.IsDefined ( prop , typeof ( UserVisibleAttribute ) ) ) .ToList (...
Does calling MakeGenericType ( ... ) multiple times create a new type every time ?
C#
Trying to study how C # reacts to overflows , I wrote this simple code : I get this output : I find surprising that it ran so well , as the int subtraction in diff should give a result greater than int.MaxValue.However , if I write this , which seems to be equivalent to the above code : C # wo n't even compile , becaus...
static uint diff ( int a , int b ) { return ( uint ) ( b - a ) ; } static void Main ( string [ ] args ) { Console.Out.WriteLine ( int.MaxValue ) ; uint l = diff ( int.MinValue , int.MaxValue ) ; Console.Out.WriteLine ( l ) ; Console.In.ReadLine ( ) ; } 21474836474294967295 uint l = ( uint ) ( int.MaxValue - int.MinValu...
Why does n't this program overflow ?
C#
We currently have a little situation on our hands - it seems that someone , somewhere forgot to close the connection in code . Result is that the pool of connections is relatively quickly exhausted . As a temporary patch we added Max Pool Size = 500 ; to our connection string on web service , and recycle pool when all ...
SELECT SPIdFROM MASTER..SysProcessesWHERE DBId = DB_ID ( 'MyDb ' ) and last_batch < DATEADD ( MINUTE , -15 , GETDATE ( ) ) DBCC INPUTBUFFER ( 61 )
All connections in pool are in use
C#
I am reading up on c # arrays so my question is initially on arrays.What does declaring an array actually mean ? I know you declare a variable of type array . When I have the following , what is actually happening ? Is it in memory by the time it is declared ? If not then where is it ? Is the array actually created her...
int [ ] values ; int [ ] values = new int [ ] { 1 , 2 , 3 } ; int value ; int value = 1 ;
What does declaring and instantiating a c # array actually mean ?
C#
I am using LINQ : Desired result : I tried but fail : How can I do this using LINQ ?
List < String > listA = new List < string > { `` a '' , `` b '' , `` c '' , `` d '' , `` e '' , `` f '' , `` g '' } ; List < String > listB = new List < string > { `` 1 '' , `` 2 '' , `` 3 '' } ; { `` a '' , `` 1 '' , `` b '' , `` 2 '' , `` c '' , `` 3 '' , `` d '' , `` 1 '' , `` e '' , `` 2 '' , `` f '' , `` 3 '' , ``...
Join two lists of different length
C#
I have a huge problem with the following code : the problem is , C # uses the system date separator instead of always using `` / '' as i specified . If I run that code , I get the following output : but if I go to `` control panel '' - > `` regional and language options '' and change the date separator to `` - '' , I g...
DateTime date = DateTime.Now ; String yearmonthday = date.ToString ( `` yyyy/MM/dd '' ) ; MessageBox.Show ( yearmonthday ) ; 2011/03/18 2011-03-18
c # Date component bug or am i missing something ?
C#
I recently came across this SO article and tweaked it for my scenario which follows : Running this program gives the following expected result : However change this : To this ( using Object Initializer syntax ) : Gives the following output : What 's going on here ? Why would lifetime of the reference be different just ...
using System ; using System.Collections.Generic ; namespace ConsoleApplication18 { class Program { static void Main ( string [ ] args ) { Manager mgr = new Manager ( ) ; var obj = new byte [ 1024 ] ; var refContainer = new RefContainer ( ) ; refContainer.Target = obj ; obj = null ; mgr [ `` abc '' ] = refContainer.Targ...
Why does using an Object Initializer keep an object alive ?
C#
I 'm trying to implement an Audit Trail ( track what changed , when and by whom ) on a selection of classes in Entity Framework Core.My current implementation relies on overriding OnSaveChangesAsync : This is simple , clean and very easy to use ; any entity that needs an audit trail only needs to inherit AuditableEntit...
public override Task < int > SaveChangesAsync ( bool acceptAllChangesOnSuccess , CancellationToken cancellationToken = default ) { var currentUserFullName = _userService.CurrentUserFullName ! ; foreach ( var entry in ChangeTracker.Entries < AuditableEntity > ( ) ) { switch ( entry.State ) { case EntityState.Added : ent...
EF Core - how to audit trail with value objects
C#
I have come across this odd behaviour : when my projects settings are set to Any CPU and Prefer 32-bit on a 64bit Windows 7 OS the .Net 4.5program below works as expected . If however I turn off Prefer 32-bit then when stepping through the program , I can see that the code never steps into the interface implementation ...
namespace BugCheck { interface IBroken { bool Broken < TValue > ( TValue gen , Large large ) ; } class Broke : IBroken { public bool Broken < TValue > ( TValue gen , Large large ) { return true ; } } struct Large { int a , b , c ; } class Program { static void Main ( string [ ] args ) { //32bit can step in . 64bit ca n...
Odd debugger behavior with Interface and Generics on 64bit OS when toggling 'Prefer 32-Bit
C#
I long for those sweet optional arguments from the days when I programmed in C++ more . I know they do n't exist in C # , but my question is Why . I think method overloading is a poor substitute which makes things messy very quickly . I just do not understand what the reasoning is . The C # compiler would obviously not...
void foo ( int x , int y , int z=0 ) { //do stuff ... } //is so much more clean thanvoid foo ( int x , int y ) { foo ( x , y,0 ) ; } void foo ( int x , int y , int z ) { //do stuff }
What is the reasoning for C # not supporting optional/default arguments ?
C#
I just saw a brand-new video on the Rx framework , and one particular signature caught my eye : At 23:55 , Bart de Smet says : The earliest version would be Action of Action.If Action is a parameterized type , how can it appear unparameterized inside the angle brackets again ? Would n't it have to be Action < Action < ...
Scheduler.schedule ( this IScheduler , Action < Action > )
What does Action < Action > mean ?
C#
I have an issue with binding on Xamarin.iOS.I have 2 libraries : libA.alibB.aAnd libB.a is depend on libA.a classes . In libA I have this class : And in libB I have this code : I have no source code of libA.a and libB.a but only universal static libraries and headers.I tried to add libA binding project and final A.dll ...
namespace ABC { [ BaseType ( typeof ( NSObject ) ) ] public partial interface ClassAbc { [ Export ( `` setString : '' ) ] void SetString ( string abc ) ; } } namespace ABCUsage { [ BaseType ( typeof ( NSObject ) ) ] public partial interface ClassAbcUsage { [ Export ( `` setAbc : '' ) ] void SetAbc ( ClassAbc abc ) ; } ...
Create binding for 2 dependent static libraries in Xamarin.iOS
C#
I 'm new to C # ( worked in PHP , Python , and Javascript ) and I 'm trying to more or less make a duplicate of another page and change some things - to make a form and database submission.Anyway , here 's the code : I really have little idea what I 'm doing - I 'm reading the tutorials , but C # is a significantly dif...
public partial class commenter : System.Web.UI.Page { string employee_reviewed ; //public Commenter ( ) ; public void SaveBtn_Click ( object sender , EventArgs e ) { if ( CommentTB.Text == `` Please enter a comment . '' ) { String csname = `` Email Error '' ; Type cstype = this.GetType ( ) ; ClientScriptManager cs = Pa...
New to C # - trying to write code to do a simple function
C#
As C # lacks support for freestanding functions , I find it hard to find a place to put conversion functions . For example , I 'd like to convert an enum to a number . In C++ , I would make the following freestanding function for this : How can I elegantly do this in C # ? Should I make a dummy static class for holding...
UINT32 ConvertToUint32 ( const MyEnum e ) ; Person ConvertToPerson ( const SpecialPersonsEnum e ) ;
Where to put conversion functions ?
C#
I 'm looking to see if there is a method or tool to view how things like closures or query expressions are created by the c # compiler `` under the hood '' . I 've noticed that many blog posts dealing with these issues will have the original code with syntactic sugar and the underlying c # code that the compiler conver...
var query = from x in myList select x.ToString ( ) ; var query = myList.Select ( x= > x.ToString ( ) ) ;
How to view c # compiler output of syntactic sugar
C#
I have a handy utility method which takes code and spits out an in-memory assembly . ( It uses CSharpCodeProvider , although I do n't think that should matter . ) This assembly works like any other with reflection , but when used with the dynamic keyword , it seems to fail with a RuntimeBinderException : 'object ' does...
var assembly = createAssembly ( `` class Dog { public string Sound ( ) { return \ '' woof\ '' ; } } '' ) ; var type = assembly.GetType ( `` Dog '' ) ; Object dog = Activator.CreateInstance ( type ) ; var method = type.GetMethod ( `` Sound '' ) ; var test1Result = method.Invoke ( dog , null ) ; //This returns `` woof ''...
Attempting to bind a dynamic method on a dynamically-created assembly causes a RuntimeBinderException
C#
I have a device that transmits binary data . To interpret the data I have defined a struct that matches the data format . The struct has a StuctLayoutAttribute with LayoutKind.Sequential . This works as expected , e.g : Now I wish to treat one struct similar to an other struct , so I experimented with the structure imp...
[ StructLayout ( LayoutKind.Sequential ) ] struct DemoPlain { public int x ; public int y ; } Marshal.OffsetOf < DemoPlain > ( `` x '' ) ; // yields 0 , as expectedMarshal.OffsetOf < DemoPlain > ( `` y '' ) ; // yields 4 , as expectedMarshal.SizeOf < DemoPlain > ( ) ; // yields 8 , as expected interface IDemo { int Pro...
Where does C # store a structure 's vtable when unmarshalling using [ StructLayout ( LayoutKind.Sequential ) ]
C#
I 'm writing an application that creates a `` Catalog '' of files , which can be attributed with other meta data files such as attachments and thumbnails.I 'm trying to abstract the interface to a catalog to the point where a consumer of a catalog does not need to know about the underlying file system used to store the...
public interface IFileSystemAdaptor : IDisposable { void WriteFileData ( string fileName , Stream data ) ; Stream ReadFileData ( string filename ) ; void DeleteFileData ( string filename ) ; void ClearAllData ( ) ; void WriteMetaFileData ( string filename , string path , Stream data ) ; Stream ReadMetaFileData ( string...
Who should be responsible for closing a stream
C#
Here is some code to return a linear function ( y=ax+b ) .I could do the same thing with expression trees , but I 'm not sure it is worth the effort.I know that the lambda will capture the parameters , which is a downside . Are there any more pros/cons which I 'm not aware of ? My main question is , is it worth it to u...
public static Func < double , double > LinearFunc ( double slope , double offset ) { return d = > d * slope + offset ; }
Creating a Func < > dynamically - Lambdas vs . Expression trees
C#
I have an abstract class : and I have a List < A > a and I want to get a first item of given type T : Is there a way to do it ? Edit : It shows : The type parameter 'T ' can not be used with the 'as ' operator because it does not have a class type constraint nor a 'class ' constraint
abstract class A { // some stuff float val = 0 ; abstract float Foo ( ) ; } class B1 : A { override float Foo ( ) { Console.WriteLine ( `` B1 : `` + val ) ; } } class B2 : A { override float Foo ( ) { Console.WriteLine ( `` B2 : `` + val ) ; } } public T GetTypeFromList < T > ( ) { foreach ( var item in a ) { T tmp = i...
How to cast abstract class into type T ?
C#
I am trying to optimize my code and was running VS performance monitor on it.It shows that simple assignment of float takes up a major chunk of computing power ? ? I do n't understand how is that possible.Here is the code for TagData : So all I am really doing is : I am confused .
public class TagData { public int tf ; public float tf_idf ; } float tag_tfidf = td.tf_idf ;
C # huge performance drop assigning float value
C#
Suppose we have a list of strings like below : There are some items with the length of more than 3.By the help of Linq I want to divide them into new items in the list , so the new list will have these items : Do n't ask me why Linq . I am a Linq fan and do n't like unLinq code : D
List < string > myList = new List < string > ( ) { `` one '' , `` two '' , `` three '' , `` four '' } ; { `` one '' , `` two '' , `` thr '' , `` ee '' , `` fou '' , `` r '' } ;
Modify list of strings to only have max n-length strings ( use of Linq )
C#
After reading a lot about immutability in C # , and understading it 's benefits ( no side effects , safe dictionary keys , multithreading ... ) a question has come to my mind : Why there is not a keyword in C # for asserting that a class ( or struct ) is immutable ? This keyword should check at compile time that there ...
public immutable class MyImmutableClass { public readonly string field ; public string field2 ; //This would be a compile time error public readonly AnyMutableType field3 ; //This would be a compile time error public string Prop { get ; } public string Prop2 { get ; set ; } //This would be a compile time error public A...
Guaranteeing immutability in c #
C#
I have public functions like this : Basically I want to individually handle reference types and nullable types . It compiles ; until i call for value types . For reference types it compiles.What real ambiguity is here ? When T is int , cant it call the struct overload appropriately ? Also : Why is the compiler only det...
public static T Get < T > ( this Mango m , T defaultValue = default ( T ) ) where T : class { //do something ; return something ; } public static T ? Get < T > ( this Mango m , T ? defaultValue = default ( T ? ) ) where T : struct { //do something ; return something ; } mango.Get < string > ( ) ; // compiles..mango.Get...
Compiler not calling appropriate generic overload when passed with value type
C#
I am currently optimizing a low-level library and have found a counter-intuitive case . The commit that caused this question is here.There is a delegateand an instance methodOn this line , if I use the method as a delegate , the program allocates many GC0 for the temp delegate wrapper , but the performance is 10 % fast...
public delegate void FragmentHandler ( UnsafeBuffer buffer , int offset , int length , Header header ) ; public void OnFragment ( IDirectBuffer buffer , int offset , int length , Header header ) { _totalBytes.Set ( _totalBytes.Get ( ) + length ) ; } var fragmentsRead = image.Poll ( OnFragment , MessageCountLimit ) ; Fr...
C # Why using instance method as delegate allocates GC0 temp objects but 10 % faster than a cached delegate
C#
The problem : I have Dictionary < String , String > that I need an alias to , but I also need to serialize/deserialize it.Solutions I 've tried : but that work because I would have to create a Deserialization constructor and that would be a bit silly when Dictionary already can be deserialized.I also triedbut I need th...
class Foo : Dictionary < String , String > { } using Foo = System.Collections.Generic.Dictionary < String , String > ;
C # Typedef that preserves attributes
C#
Possible Duplicate : What do two question marks together mean in C # ? I just came across the code below and not really sure what it means and ca n't google it because google omits the ? ? Is the second line some sort of if else statement , what does the ? ? mean
int ? x = 32 ; int y = x ? ? 5 ;
Is this an if else statement
C#
I 've thought of this before and it came to mind again when reading this question.Are there any plans for `` extension properties '' in a future version of C # ? It seems to me they might be pretty stright-forward to implement with a little more `` compiler magic '' . For example , using get_ and set_ prefixes on exten...
public class Foo { public string Text { get ; set ; } } public static class FooExtensions { public static string get_Name ( this Foo foo ) { return foo.Text ; } public static void set_Name ( this Foo foo , string value ) { foo.Text = value ; } }
Are there any plans for `` extension properties '' in a future version of C # ?
C#
I am on Admin area now want to send the values to Account Controller which is in default area how i can send this is my other action in Account Controller where i want to redirect my code
ChangePasswordModel mode = new ChangePasswordModel ( ) ; mode.ConfirmPassword = password ; mode.NewPassword = password ; mode.OldPassword = user.Password ; return RedirectToAction ( `` ChangePassword '' , `` Account '' , new { area = '/ ' } , new { model = mode } ) ; [ Authorize ] [ HttpPost ] public ActionResult Chang...
Redirect action to action in other area with model as parmenter