text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I want to know which conversion is better ( regarding performance/speed and precision/most less loss ) for a simple math operation and what makes them different ? Example : Actually my question is about the conversion not the type itself . <code> double double1 = integer1 / ( 5 * integer2 ) ; var double2 = integer1 / ( 5.0 * integer2 ) ; var double3 = integer1 / ( 5D * integer2 ) ; var double4 = ( double ) integer1 / ( 5 * integer2 ) ; var double5 = integer1 / ( double ) ( 5 * integer2 ) ; var double6 = integer1 / ( ( double ) 5 * integer2 ) ; var double7 = integer1 / ( 5 * ( double ) integer2 ) ; var double8 = Convert.ToDouble ( integer1 / ( 5 * integer2 ) ) ; var double9 = integer1 / Convert.ToDouble ( 5 * integer2 ) ; | Which numeric type conversion is better for simple math operation ? |
C_sharp : Both of these classes contain another private class that raises events . These two classes then re-raise these events to clients.Unfortunately , each of the two classes has this exact same code : As you can see , I have to re-raise events from a private object . It is redundant . I tried using inheritance and placing this duplicate code in a base class but I keep getting errors like : The event 'BaseClass.Foo ' can only appear on the left hand side of += or -= ( except when used from within the type ) Does anyone know how to get rid of this duplicate code ? <code> public class FirstClass { public delegate void FooEventHandler ( string foo ) ; public delegate void BarEventHandler ( string bar ) ; public delegate void BazEventHandler ( string baz ) ; public event FooEventHandler Foo ; public event BarEventHandler Bar ; public event BazEventHandler Baz ; private PrivateObject privateObject ; public FirstClass ( ) { privateObject.Foo += FirstClass_Foo ; privateObject.Bar += FirstClass_Bar ; privateObject.Baz += FirstClass_Baz ; } private void FirstClass_Foo ( string foo ) { if ( Foo ! = null ) { Foo ( foo ) ; } } private void FirstClass_Bar ( string bar ) { if ( Bar ! = null ) { Bar ( bar ) ; } } private void FirstClass_Baz ( string baz ) { if ( Baz ! = null ) { Baz ( baz ) ; } } } | How do you refactor two classes with the same , duplicated events ? |
C_sharp : Well , I have this code : As you can see , I 'm trying to replace puts ( content ) by Console.WriteLine ( content ) but it would be need Regular Expressions and I did n't found a good article about how to do THIS.Basically , taking * as the value that is coming , I 'd like to do this : Then , if I receive : I want to get : <code> StreamReader sr = new StreamReader ( @ '' main.cl '' , true ) ; String str = sr.ReadToEnd ( ) ; Regex r = new Regex ( @ '' & '' ) ; string [ ] line = r.Split ( str ) ; foreach ( string val in line ) { string Change = val.Replace ( `` puts '' , '' System.Console.WriteLine ( ) '' ) ; Console.Write ( Change ) ; } string Change = val.Replace ( `` puts * '' , '' System.Console.WriteLine ( * ) '' ) ; puts `` Hello World '' ; System.Console.WriteLine ( `` Hello World '' ) ; | Regex replacing inside of |
C_sharp : I trying to get some values from database by using entity framework i have a doubt about Difference between new ClassName and new ClassName ( ) in entity framewrok queryCode 1Code 2You can see the changes from where i create a new StatusTypeModel and new StatusTypeModel ( ) object . The both queries are working for me . but i do n't know the differences between of code 1 and code 2 . <code> dbContext.StatusTypes.Select ( s = > new StatusTypeModel ( ) { StatusTypeId = s.StatusTypeId , StatusTypeName = s.StatusTypeName } ) .ToList ( ) ; dbContext.StatusTypes.Select ( s = > new StatusTypeModel { StatusTypeId = s.StatusTypeId , StatusTypeName = s.StatusTypeName } ) .ToList ( ) ; | Difference between new ClassName and new ClassName ( ) in entity framewrok query |
C_sharp : I have two methods with these signatures : Its an overload of the same method to take either a single object or a list of them . If I try to pass a List < 'T > to it , it resolves to the first method , when obviosly i want the second . I have to use list.AsEnumerable ( ) to get it to resolve to the second . Is there any way to make it resolve to the second regardless of whether the list is type T [ ] , IList < 'T > , List < 'T > , Collection < 'T > , IEnumerable < 'T > , etc . <code> void Method < T > ( T data ) { } void Method < T > ( IEnumerable < T > data ) { } | Generic overloaded method resolution problems |
C_sharp : Im a bit confused . I thought `` @ '' in c # ist a sign for to interpret text literally like @ '' C : \Users ... '' . It avoids the need of a double backslash.But why does paths also work if they contain double backslashes and the @ ? Fe : I that case the string must be literally `` C : \\Users\\text.txt '' - because of the previous `` @ '' - which is not a valid windows path ( EDIT : Thats wrong , it is a valid Path , only explorer wont accept it - thanks to Muctadir Dinar ) , so why does this work ? Thanks in advance <code> var temp = File.ReadAllText ( @ '' C : \\Users\\text.txt '' ) .ToString ( ) ; // no error | Why does a path work even if it contains an @ before `` \\ '' |
C_sharp : Very simple : The assumption is that all three should be true , but it turns out that equal2 is false - which does n't really make sense given that the first two MakeArrayType calls are equivalent and the resulting array types are the same . The only difference I can actually discern is that explicitly passing the rank of the array type as ' 1 ' yields a Type whose Name is `` Object [ * ] '' whereas omitting it yields `` Object [ ] '' .So I thought , perhaps the rank of object [ ] is n't 1 ( even though it clearly is ! ) - so I did this : The types now definitely have the same rank , but are not equal . This scenario is more like my current scenario as I try to build Array covariance into Rezolver - so I 'm recomposing array types by walking base hierarchies and using MakeArrayType with the original array type 's rank.So - can anyone explain why two array types with identical rank are not considered equal ? I realise there 's likely some nuance I 'm missing here , and that there are workarounds I can use , I 'm just curious as to what 's going on ! <code> var equal1 = typeof ( object [ ] ) == typeof ( object ) .MakeArrayType ( ) ; var equal2 = typeof ( object [ ] ) == typeof ( object ) .MakeArrayType ( 1 ) ; var equal3 = typeof ( object [ , ] ) == typeof ( object ) .MakeArrayType ( 2 ) ; var type1 = typeof ( object [ ] ) ; var type2 = type1.GetElementType ( ) .MakeArrayType ( type1.GetArrayRank ( ) ) ; var equal = type1 == type2 ; //false | Array types with same element type & rank not equal |
C_sharp : I have written a Direct3D 9 based rendering engine in c # using SlimDX . In a new project I now need to distribute pictures of a loaded 3d scene using a webservice . The problem is that in order to render anything at all I need a Direct3d device . Is there any way to create a direct3d device without a user being logged in to the system and the desktop not being locked ? If that is not possible , does anyone know of a workaround ? In the end I need either an executable which can be run from the task planner using some local user account or a service , which periodically renders pictures of the scene from certain viewpoints.The engine is split into two parts : the engine itself and the renderer . So if there 's no other way then I could also implement a new renderer using opengl or any other technology which allows for rendering without having a visible form.Edit : What I have so far is this : This is part of a minimal WindowsService . I put the important code into the OnContinue function because it 's easier to debug than the startup code . I gave this services the right to interact with the active desktop . when I run the service as a local systemaccount getting the desktop and windowstation works but the number of GraphicsAdapters still is 0 , when I run the service using a dedicated user account then I ca n't even open the WindowStation . Is there anything else I can try or which I 'm doing wrong ? I am testing this on a Windows 7 machine , while I am logged in since debugging becomes very difficult otherwise . Might this be a problem ? Thanks <code> protected override void OnContinue ( ) { base.OnContinue ( ) ; NativeFunctions.SafeWindowStationHandle hwinsta = NativeFunctions.WindowStation.OpenWindowStation ( `` WinSta0 '' , true , NativeFunctions.AccessMask.WINSTA_ALL_ACCESS ) ; if ( hwinsta == null || hwinsta.IsClosed || hwinsta.IsInvalid ) Marshal.ThrowExceptionForHR ( Marshal.GetLastWin32Error ( ) ) ; if ( NativeFunctions.WindowStation.SetProcessWindowStation ( hwinsta.DangerousGetHandle ( ) ) ) { NativeFunctions.SafeDesktopHandle ptrDesktop = NativeFunctions.WindowStation.OpenInputDesktop ( 0 , true , NativeFunctions.AccessMask.DESKTOP_CREATEWINDOW ) ; if ( ptrDesktop.IsClosed || ptrDesktop.IsInvalid ) return ; if ( ! NativeFunctions.WindowStation.SetThreadDesktop ( ptrDesktop.DangerousGetHandle ( ) ) ) return ; Log log = Logger.Instance.CreateLog ( `` DXService '' , true , true , false ) ; log.LogMessage ( `` Desktop set , creating D3D-Object . `` , LOGMESSAGELEVEL.CRITICAL , true ) ; Direct3D direct3D = new Direct3D ( ) ; log.LogMessage ( `` Direct3D object created , creating device . `` , LOGMESSAGELEVEL.CRITICAL , true ) ; if ( direct3D.AdapterCount == 0 ) { log.LogMessage ( `` FATAL : direct3D.AdapterCount == 0 '' ) ; } } } | Render 3D scene on locked system |
C_sharp : We have a generic extension method which works only for objects that supports both the INotifyCollectionChanged and IEnumerable interfaces . It 's written like this : The following compiles fine since ObservableCollection < string > implements both interfaces and thanks to the 'var ' keyword , knownType is strongly typed : However , we are trying to call this from a ValueConverter . The problem is the incoming value is of type object and even though we can test that the passed-in object does implement both interfaces , we ca n't figure out how to explicitly cast it so we can call that generic extension method . This does n't work ( obviously ) ... So how can you cast an object to multiple interfaces so you can call the generic ? Not even sure it 's possible . <code> public static class SomeExtensions { public static void DoSomething < T > ( this T item ) where T : INotifyCollectionChanged , IEnumerable { // Do something } } var knownType = new ObservableCollection < string > ( ) ; knownType.DoSomething ( ) ; object unknownType = new ObservableCollection < string > ( ) ; ( ( INotifyCollectionChanged , IEnumerable ) unknownType ) .DoSomething ( ) ; | How can you explicitly cast a variable of type 'object ' to satisfy a multi-typed generic constraint ? |
C_sharp : I am developing an Android app with Xamarin ( version 7.1 ) . It displays as map and draws PolyLines , doing so in OnCameraIdle ( ) .The MapFragment is generated programmatically in OnCreate . I am fetching the GoogleMap in OnResume via GetMapAsync and binding the listeners in OnMapReady.They work fine , but only in the beginning . As soon as the device is rotated ( portrait - > landscape OR vice versa ) , the camera movement does not trigger the listeners any more.The map works , however - I ( the user ) can still move the camera just fine . I ( the app ) just ca n't work with it anymore.This is the bare code , only map creation and handling . Everything else ( actual drawing ) is removed : As you can see in the following log excerpt , the listeners do work in the beginning , but once the device is rotated ( at least ) once , they are gone.I also tried calling SetMapListeners only once in the lifecycle , the first time OnMapReady is called , but that did not change anything.The interesting thing here for me is that when I switch back to the previous activity and open the map once again , it starts fresh and works again . However , as you see in the log , while rotating the device , the activity is also destroyed and freshly created . As far as I know , the fragment is not , so maybe that 's hint . I do n't know.I also tried removing the listeners in OnDestroy ( by setting null ) , but that , too , did not change anything.Have you got any idea what I might be doing wrong ? <code> public class MapActivity : Activity , IOnMapReadyCallback , GoogleMap.IOnCameraIdleListener , GoogleMap.IOnCameraMoveStartedListener { private GoogleMap _map ; private MapFragment _mapFragment ; private void InitializeMap ( ) { _mapFragment = MapFragment.NewInstance ( ) ; var tx = FragmentManager.BeginTransaction ( ) ; tx.Add ( Resource.Id.map_placeholder , _mapFragment ) ; tx.Commit ( ) ; } private void SetMapListeners ( ) { Log.Debug ( `` MyApp/ Map '' , `` SetMapListeners '' ) ; _map.SetOnCameraIdleListener ( this ) ; _map.SetOnCameraMoveStartedListener ( this ) ; } /* Activity */ protected override void OnCreate ( Bundle savedInstanceState ) { base.OnCreate ( savedInstanceState ) ; Log.Debug ( `` MyApp / Map '' , `` OnCreate '' ) ; SetContentView ( Resource.Layout.Map ) ; InitializeMap ( ) ; } protected override void OnStart ( ) { base.OnStart ( ) ; Log.Debug ( `` MyApp / Map '' , `` OnStart '' ) ; } protected override void OnResume ( ) { base.OnResume ( ) ; if ( _map == null ) _mapFragment.GetMapAsync ( this ) ; Log.Debug ( `` MyApp / Map '' , `` OnResume '' ) ; } protected override void OnPause ( ) { base.OnPause ( ) ; Log.Debug ( `` MyApp / Map '' , `` OnPause '' ) ; } protected override void OnStop ( ) { base.OnStop ( ) ; Log.Debug ( `` MyApp / Map '' , `` OnStop '' ) ; } protected override void OnDestroy ( ) { base.OnStop ( ) ; Log.Debug ( `` MyApp/ Map '' , `` OnDestroy '' ) ; } /* IOnMapReadyCallback */ public void OnMapReady ( GoogleMap googleMap ) { Log.Debug ( `` MyApp / Map '' , `` Map is ready ! `` ) ; _map = googleMap ; SetMapListeners ( ) ; } /* IOnCameraIdleListener */ public void OnCameraIdle ( ) { Log.Debug ( `` MyApp / Map '' , `` Camera is idle . `` ) ; // Drawing routine is called here } /* IOnCameraMoveStartedListener */ public void OnCameraMoveStarted ( int reason ) { Log.Debug ( `` MyApp / Map '' , `` Camera move started . `` ) ; } } 04-03 20:29:06.486 D/MyApp / Map ( 7446 ) : OnCreate04-03 20:29:06.688 I/Google Maps Android API ( 7446 ) : Google Play services client version : 1008400004-03 20:29:06.695 I/Google Maps Android API ( 7446 ) : Google Play services package version : 1029843804-03 20:29:07.394 D/MyApp / Map ( 7446 ) : OnStart04-03 20:29:07.399 D/MyApp / Map ( 7446 ) : OnResume04-03 20:29:07.432 D/MyApp / Map ( 7446 ) : Map is ready ! 04-03 20:29:07.438 D/MyApp / Map ( 7446 ) : SetMapListeners04-03 20:29:07.568 D/MyApp / Map ( 7446 ) : Camera is idle.04-03 20:29:09.231 D/MyApp / Map ( 7446 ) : Camera move started.04-03 20:29:09.590 D/MyApp / Map ( 7446 ) : Camera is idle.04-03 20:29:12.350 D/MyApp / Map ( 7446 ) : Camera move started.04-03 20:29:12.751 D/MyApp / Map ( 7446 ) : Camera is idle. # # Listeners are responding , now rotating the device.04-03 20:29:15.503 D/MyApp / Map ( 7446 ) : OnPause04-03 20:29:15.508 D/MyApp / Map ( 7446 ) : OnStop04-03 20:29:15.572 D/MyApp / Map ( 7446 ) : OnDestroy04-03 20:29:15.595 I/Google Maps Android API ( 7446 ) : Google Play services package version : 1029843804-03 20:29:15.596 D/MyApp / Map ( 7446 ) : OnCreate04-03 20:29:15.628 I/Google Maps Android API ( 7446 ) : Google Play services package version : 1029843804-03 20:29:15.655 D/MyApp / Map ( 7446 ) : OnStart04-03 20:29:15.655 D/MyApp / Map ( 7446 ) : OnResume04-03 20:29:15.690 D/MyApp / Map ( 7446 ) : Map is ready ! 04-03 20:29:15.691 D/MyApp / Map ( 7446 ) : SetMapListeners # # Map is rotated , camera position was preserved . # # Now moving the camera , but no listeners are responding.04-03 20:29:24.436 D/MyApp / Map ( 7446 ) : OnPause04-03 20:29:31.288 D/MyApp / Map ( 7446 ) : OnStop04-03 20:29:31.359 D/MyApp / Map ( 7446 ) : OnDestroy | How to preserve/rebind event listeners on MapFragment after rotating the device ( portrait / landscape ) ? |
C_sharp : Quick question . ( I was not able to find documentation about this anywhere ) When you do this : Does it creates a reference or actually copies the texture ? I would like to know it so I can take it into account when implementing related stuff . <code> Texture2D t1 ; t1 = content.Load < Texture2D > ( `` some texture '' ) ; Texture2D t2 ; t2 = t1 ; | ( Texture2D ) t1 = t2 ; Does it creates reference or a copy ? |
C_sharp : I 'm not after a solution here , more an explanation of what 's going on . I 've refactored this code to prevent this problem but I 'm intrigued why this call deadlocked . Basically I have a list of head objects and I need to load each ones details from a DB repository object ( using Dapper ) . I attempted to do this using ContinueWith but it failed : Can someone explain what caused this deadlock ? I tried to get my head round what has happened here but I 'm not sure . I 'm presuming it 's something to do with calling .Result in the ContinueWithAdditional informationThis is a webapi app called in an async contextThe repo calls are all along the lines of : I have since fixed this issue with the following code : <code> List < headObj > heads = await _repo.GetHeadObjects ( ) ; var detailTasks = heads.Select ( s = > _changeLogRepo.GetDetails ( s.Id ) .ContinueWith ( c = > new ChangeLogViewModel ( ) { Head = s , Details = c.Result } , TaskContinuationOptions.OnlyOnRanToCompletion ) ) ; await Task.WhenAll ( detailTasks ) ; //deadlock herereturn detailTasks.Select ( s = > s.Result ) ; public async Task < IEnumerable < ItemChangeLog > > GetDetails ( int headId ) { using ( SqlConnection connection = new SqlConnection ( _connectionString ) ) { return await connection.QueryAsync < ItemChangeLog > ( @ '' SELECT [ Id ] , [ Description ] , [ HeadId ] FROM [ dbo ] . [ ItemChangeLog ] WHERE HeadId = @ headId '' , new { headId } ) ; } } List < headObj > heads = await _repo.GetHeadObjects ( ) ; Dictionary < int , Task < IEnumerable < ItemChangeLog > > > tasks = new Dictionary < int , Task < IEnumerable < ItemChangeLog > > > ( ) ; //get details for each head and build the vm foreach ( ItemChangeHead head in heads ) { tasks.Add ( head.Id , _changeLogRepo.GetDetails ( head.Id ) ) ; } await Task.WhenAll ( tasks.Values ) ; return heads.Select ( s = > new ChangeLogViewModel ( ) { Head = s , Details = tasks [ s.Id ] .Result } ) ; | Why did my async with ContinueWith deadlock ? |
C_sharp : I have the following struct : Now , I want to write characters to the field MarketSymbol : The compiler throws an error , saying its unable to convert from char [ ] to char*.How do I have to write this ? Thanks <code> [ StructLayout ( LayoutKind.Sequential , Pack = 1 , CharSet = CharSet.Unicode ) ] unsafe public struct Attributes { public OrderCommand Command { get ; set ; } public int RefID { get ; set ; } public fixed char MarketSymbol [ 30 ] ; } string symbol = `` test '' ; Attributes.MarketSymbol = symbol.ToCharArray ( ) ; | C # ToCharArray does not work with char* |
C_sharp : I need to use enum as covariant type . Let 's say i have this code : and this code : I was trying to use Enum.I was trying to use IConvertible which is interface of Enum.But everytime it does n't work ( it was null ) .What should i use ? Or how can i do it ? ( I do n't want to use EnumColor in second part of code , because i want two independent codes joined only with interface . ) <code> public enum EnumColor { Blue = 0 , Red = 1 , } public class Car : IColoredObject < EnumColor > { private EnumColor m_Color ; public EnumColor Color { get { return m_Color ; } set { m_Color = value ; } } public Car ( ) { } } class Program { static void Main ( ) { Car car = new Car ( ) ; IndependentClass.DoesItWork ( car ) ; } } public interface IColoredObject < out EnumColorType > { EnumColorType Color { get ; } } public static class IndependentClass { public static void DoesItWork ( object car ) { IColoredObject < object > coloredObject = car as IColoredObject < object > ; if ( coloredObject == null ) Console.WriteLine ( `` It does n't work . '' ) ; else { Console.WriteLine ( `` It works . '' ) ; int colorNumber = ( int ) ( coloredObject.Color ) ; Console.WriteLine ( `` Car has got color number `` + colorNumber + `` . '' ) ; } } } IColoredObject < Enum > coloredObject = car as IColoredObject < Enum > ; IColoredObject < IConvertible > coloredObject = car as IColoredObject < IConvertible > ; | c # enum covariance does n't work |
C_sharp : I have stumbled upon an interesting scenario , which I could n't find a solution to . Suppose I have to find the majorant in a sequence ( the number that occurs at least n / 2 + 1 times , where n is the size of the sequence ) . This is my implementation : I 'm using SingleOrDefault ( ) , which returns the element if it 's found in the sequence or the default value for the type : in this case , it will return 0 as it 's the default value for an int . For example , my method returns 3 for the following sequence : which is the expected behaviour.However , what happens if the majorant in the sequence is zero ( 0 ) ? It would return 0 , but that way , how could I determine whether it 's the zero from SingleOrDefault ( ) as a default value , or the majorant ? Perhaps , I could use Single ( ) , but that would throw an exception which is pretty much incorrent . I could also catch this exception , but this seems a bad practice to me . So my question is , what 's the preferred way to handle this situation ? <code> public static int FindMajorant ( IList < int > numbers ) { return numbers .GroupBy ( x = > x ) .Where ( g = > g.Count ( ) > = numbers.Count / 2 + 1 ) .Select ( g = > g.Key ) .SingleOrDefault ( ) ; } List < int > sampleNumbers = new List < int > ( ) { 2 , 2 , 3 , 3 , 2 , 3 , 4 , 3 , 3 } ; | SingleOrDefault ( ) when the sequence contains the default value |
C_sharp : I have a ListBox whose ItemTemplate looks like this : Column is a simple class which looks like this : The EditableTextBlock is a UserControl that turns into a TextBox when double clicked and turns back into a TextBlock when Lost Focus . It also has a Property called IsInEditMode which is by default false . When it is true , TextBox is shown.The Question : The ItemsSouce of the ListBox is an ObservableCollection < Column > . I have a button which adds new Columns to the collection . But my problem is that I want IsInEditMode to be turned true for newly added EditableTextBlocks by that Button . But I can only access Column in the ViewModel . How will I access the EditableTextBlock of the specified Column in the ItemsSource collection ? The only solution I can come up with is deriving a class from Column and adding a property for that ( eg : name : IsInEditMode ) ( Or maybe a wrapper class . Here 's a similar answer which suggestes using a wrapper class ) and Binding to that property in the DataTemplate like so : But I do n't want this . I want some way to do this in XAML without deriving classes and adding unnecessary code . ( And also adhering to MVVM rules ) <code> < DataTemplate DataType= '' local : Column '' > < utils : EditableTextBlock x : Name= '' editableTextBlock '' Text= '' { Binding Name , Mode=TwoWay } '' / > < /DataTemplate > public Column ( string name , bool isVisibleInTable ) { Name = name ; IsVisibleInTable = isVisibleInTable ; } public string Name { get ; set ; } public bool IsVisibleInTable { get ; set ; } < DataTemplate DataType= '' local : DerivedColumn '' > < utils : EditableTextBlock x : Name= '' editableTextBlock '' Text= '' { Binding Name , Mode=TwoWay } '' IsInEditMode= '' { Binding IsInEditMode } '' / > < /DataTemplate > | Get DataTemplate from data object in ListBox |
C_sharp : I am modifiying the foreign key property on an entity in code , by modifiying the Id only : I have found , after persisting , that this only works as expected , when the corresponding navigation property ServiceLevel was null by accident . If it still holds the `` old '' object , the change will not hit the database.This means , I need to doDoes that mean , that changing the object is `` stronger '' than changing the id only ? Should I always set the related object to null in such situations ? Update ( per Tim Copenhaver 's comment ) : The entity in question is a copy ( with the mentioned modification ) of an existing one . It uses Automapper for copying , and maps everything except the primary key and one unrelated property . Automapper creates a shallow copy AFAIK . Thus , the situation for the copy will be that the updated Id and the untouched object reference will not match at the moment of adding it to the context . I guess , that EF then decides that the `` object reference is stronger '' . <code> ElementData.ServiceLevelId = parameter.ServiceLevelId ; ElementData.ServiceLevelId = parameter.ServiceLevelId ; ElementData.ServiceLevel = null ; //Force the update to the Database | EF6 : Modifying an entity property with a foreign key relation - Do I need to change the Id or the related object or both ? |
C_sharp : I ca n't remember where but found an example how to exclude folder from being search . Our issue was search node_modules would cause long path exceptions.Any help to resolve this issue would be helpful . <code> Func < IFileSystemInfo , bool > exclude_node_modules = fileSystemInfo= > ! fileSystemInfo.Path.FullPath.Contains ( `` node_modules '' ) ; var solutions = GetFiles ( `` ./**/*.sln '' , exclude_node_modules ) ; | Breaking change in GetFiles with 0.15.2 ca n't exclude folders |
C_sharp : I wonder if that 's good pattern to use Discards in Linq queries according to https : //docs.microsoft.com/en-us/dotnet/csharp/discards , example : What 's pros / cons instead using <code> public bool HasRedProduct = > Products.Any ( _= > _.IsRed == true ) ; public bool HasRedProduct = > Products.Any ( x= > x.IsRed == true ) ; | Discards inside C # Linq queries |
C_sharp : Constrained Execution Regions are a feature of C # / .Net that allow the developer to attempt to hoist the 'big three ' exceptions out of critical regions of code - OutOfMemory , StackOverflow and ThreadAbort . CERs achieve this by postponing ThreadAborts , preparing all methods in the call graph ( so no JIT has to occur , which can cause allocations ) , and by ensuring enough stack space is available to fit the ensuing call stack.A typical uninterruptable region might look like : The above is mostly all well and good because none of the rules are broken inside the CER - all .Net allocations are outside the CER , Marshal.ReadInt32 ( ) has a compatible ReliabilityContract , and we 're presuming my NativeMethods are similarly tagged so that the VM can properly account for them when preparing the CER.So with all of that out of the way , how do you handle situations where an allocation has to happen inside of a CER ? Allocations break the rules , since it 's very possible to get an OutOfMemoryException.I 've run into this problem when querying a native API ( SSPI 's QuerySecurityPackageInfo ) that forces me to break these rules . The native API does perform its own ( native ) allocation , but if that fails I just get an empty result , so no big deal there . However , in the structure that it allocates , it stores a few C-strings of unknown size.When it gives me back a pointer to the structure it allocated , I have to copy the entire thing , and allocate room to store those c-strings as .Net string objects . After all of that , I 'm supposed to tell it to free the allocation.However , since I 'm performing .Net allocations in the CER , I 'm breaking the rules and possibly leaking a handle.What is the right way to deal with this ? For what it 's worth , this is my naive approach : EditI should mention that 'success ' for me in this case is that I never leak the handle ; its alright if I perform an allocation which fails , and release the handle , and then return an error to my caller indicating that an allocation failed . Just ca n't leak handles.Edit to respond to Frank Hileman We do n't have much control over the memory allocations required when we perform interop calls.Depends on what you mean - memory that might be allocated to perform the call invocation , or the memory created by the invoked call ? We have perfect control over the memory allocated to perform the invocation - that 's memory created by the JIT to compile the involved methods , and the memory needed by the stack to perform the invocation . The JIT compile memory is allocated during the preparation of the CER ; if that fails , the whole CER is never executed . The CER preparation also calculates how much stack space is needed in the static call graph performed by the CER , and aborts the CER preparation if there 's not enough stack.Coincidentally , this involves stack space preparation for any try-catch-finally frames , even nested try-catch-finally frames , that happen to define and partake in the CER . Nesting try-catch-finally 's inside a CER is perfectly reasonable , because the JIT can calculate the amount of stack memory needed to record the try-catch-finally context and abort the CER preparation all the same if too much is needed . The call itself may do some memory allocations outside the .net heap ; I am surprised native calls are allowed inside a CER at all.If you meant native memory allocations performed by the invoked call , then that 's also not a problem for CERs . Native memory allocations either succeed or return a status code . OOMs are not generated by native memory allocations . If a native allocation fails , presumably the native API I 'm invoking handles it by returning a status code , or a null pointer . The call is still deterministic . The only side effect is that it may cause subsequent managed allocations to fail due to increased memory pressure . However , if we either never perform allocations , or can deterministically handle failed managed allocations , then it 's still not a problem . So the only kind of allocation that is bad in a CER is a managed allocation , since it may cause the 'asynchronous ' OOM exception . So now the question is how do I deterministically handle a failed managed allocation inside of a CER..But that 's completely possible . A CER can have nested try-catch-finally blocks . All calls in a CER , and all stack space needed by a CER , even for recording the context of a nested try-finally inside a CER 's finally , can be deterministically calculated during the preparation of the entire CER , before any of my code actually executes . <code> public static void GetNativeFlag ( ) { IntPtr nativeResource = new IntPtr ( ) ; int flag ; // Remember , only the finally block is constrained ; try is normal . RuntimeHelpers.PrepareConstrainedRegions ( ) ; try { } finally { NativeMethods.GetPackageFlags ( ref nativeResource ) ; if ( nativeResource ! = IntPtr.Zero ) { flag = Marshal.ReadInt32 ( nativeResource ) ; NativeMethods.FreeBuffer ( nativeResource ) ; } } } internal static SecPkgInfo GetPackageCapabilities_Bad ( string packageName ) { SecPkgInfo info ; IntPtr rawInfoPtr ; rawInfoPtr = new IntPtr ( ) ; info = new SecPkgInfo ( ) ; RuntimeHelpers.PrepareConstrainedRegions ( ) ; try { } finally { NativeMethods.QuerySecurityPackageInfo ( packageName , ref rawInfoPtr ) ; if ( rawInfoPtr ! = IntPtr.Zero ) { // This performs allocations as it makes room for the strings contained in the result . Marshal.PtrToStructure ( rawInfoPtr , info ) ; NativeMethods.FreeContextBuffer ( rawInfoPtr ) ; } } return info ; } | How to deal with allocations in constrained execution regions ? |
C_sharp : I 'm trying to generate code that takes a StringBuilder , and writes the values of all the properties in a class to a string . I 've got the following , but I 'm currently getting a `` Invalid method token '' in the following code : Any ideas ? Thanks in advance : ) <code> public static DynamicAccessor < T > CreateWriter ( T target ) //Target class to *serialize* { DynamicAccessor < T > dynAccessor = new DynamicAccessor < T > ( ) ; MethodInfo AppendMethod = typeof ( StringBuilder ) .GetMethod ( `` Append '' , new [ ] { typeof ( Object ) } ) ; //Append method of Stringbuilder var method = new DynamicMethod ( `` ClassWriter '' , typeof ( StringBuilder ) , new [ ] { typeof ( T ) } , typeof ( T ) , true ) ; var generator = method.GetILGenerator ( ) ; LocalBuilder sb = generator.DeclareLocal ( typeof ( StringBuilder ) ) ; //sb pointer generator.Emit ( OpCodes.Newobj , typeof ( StringBuilder ) ) ; //make our string builder generator.Emit ( OpCodes.Stloc , sb ) ; //make a pointer to our new sb //iterate through all the instance of T 's props and sb.Append their values . PropertyInfo [ ] props = typeof ( T ) .GetProperties ( ) ; foreach ( var info in props ) { generator.Emit ( OpCodes.Callvirt , info.GetGetMethod ( ) ) ; //call the Getter generator.Emit ( OpCodes.Ldloc , sb ) ; //load the sb pointer generator.Emit ( OpCodes.Callvirt , AppendMethod ) ; //Call Append } generator.Emit ( OpCodes.Ldloc , sb ) ; generator.Emit ( OpCodes.Ret ) ; //return pointer to sb dynAccessor.WriteHandler = method.CreateDelegate ( typeof ( Write ) ) as Write ; return dynAccessor ; } | Stringbuilder in CIL ( MSIL ) |
C_sharp : I was in the process of moving repeated arithmetic code into reusable chunks using funcs but when I ran a simple test to benchmark if it will be any slower , I was surprised that it is twice as slow.Why is evaluating the expression twice as slowBelow is the benchmark : <code> using System ; using System.Runtime.CompilerServices ; using BenchmarkDotNet.Attributes ; using BenchmarkDotNet.Exporters ; using BenchmarkDotNet.Loggers ; using BenchmarkDotNet.Running ; namespace ConsoleApp1 { class Program { static void Main ( string [ ] args ) { var summary = BenchmarkRunner.Run < Calculations > ( ) ; var logger = ConsoleLogger.Default ; MarkdownExporter.Console.ExportToLog ( summary , logger ) ; Console.WriteLine ( summary ) ; } } public class Calculations { public Random RandomGeneration = new Random ( ) ; [ Benchmark ] public void CalculateNormal ( ) { var s = RandomGeneration.Next ( ) * RandomGeneration.Next ( ) ; } [ Benchmark ] public void CalculateUsingFunc ( ) { Calculate ( ( ) = > RandomGeneration.Next ( ) * RandomGeneration.Next ( ) ) ; } [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public int Calculate ( Func < int > expr ) { return expr ( ) ; } } } | Why are Func < > delegates so much slower |
C_sharp : As a followup question to this oneI undestand , that once the FeatureA is casted to IFeature the generic method will always get IFeature as type parameter.We have a service with provides us with a list features ( List < IFeature > ) . If we want to iterate over those features , passing each in the generic method , I guess there is no way to get the concrete type in the generic method other thanusing reflectionusing a dynamic variable to determine the type on runtime ( Calling a generic method with the correct derived type ) Since reflection is very costly , I would like to use the dynamic cast . Is there any downside to call the method that way ? Somehow I feel dirty when doing that : - ) <code> public interface IFeature { } public class FeatureA : IFeature { } IFeature a = new FeatureA ( ) ; Activate ( a ) ; private static void Activate < TFeature > ( TFeature featureDefinition ) where TFeature : IFeature { } | Calling a generic method with interface instances |
C_sharp : I am editing my question I think it is a little confusing and it does not explain what my intent is.Edit : My goal is that when my HelloWorld application references MyClassLibrary my code does not compile so that I ensure to initialize some code prior to running the main method . Kind of like a constructor of a class . When I reference MyClassLibrary I will like to run some code in there before running the main method of my HelloWorld application . NUnit has a similar functionality . When my HelloWorld application references NUnit I get the error : Error CS0017 Program has more than one entry point defined . Compile with /main to specify the type that contains the entry point . As @ Alex pointed out that Main method that NUnit creates is auto-generated . I will like to auto-generate a main method with some custom code . How can I do that from MyClassLibrary without doing anything on my HelloWorld application just like NUnit does it ? OLD Question : I want to perform the same behavior that NUnit tests perform that it prevents using a Main method . In this case the error that I need is a good thing . Let me explain what I mean.I create a hello world application targeting the .net coreProject file : Code file : ( default hello world c # code ) If I then run that application it runs fineAdd a reference to NUnit and my project file now contains..When I try to compile the project I get the error : Error CS0017 Program has more than one entry point defined . Compile with /main to specify the type that contains the entry point . That means that there is another Main method . That method is probably located on the NUnit nuget package I am referencing . This is the error I am trying to replicate ! .Now this is how I try to replicate the same error : I remove the NUnit nugget package having no references to NUnit on my hello world application.Create a Project ClassLibrary1 with the following code : .Have my hello world application reference that project : When I compile I get no errors even though there are 2 Main methods ! How does NUnit manages to prevent using a Main method ? How can I replicate the same behavior ? I want to create an assembly that when referenced it prevents executing the Main method . <code> < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > netcoreapp2.1 < /TargetFramework > < /PropertyGroup > < /Project > < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > netcoreapp2.1 < /TargetFramework > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' NUnit '' Version= '' 3.12.0 '' / > < PackageReference Include= '' NUnit3TestAdapter '' Version= '' 3.13.0 '' / > < PackageReference Include= '' Microsoft.NET.Test.Sdk '' Version= '' 16.2.0 '' / > < /ItemGroup > < /Project > public class MyLib { static void Main ( ) { Console.WriteLine ( `` fooooo '' ) ; // do something } } | Auto-generate main method from referenced assembly |
C_sharp : Some people in our team are using VisualStudio 2015 while the rest is still using 2013 ( both with ReSharper 9.1 ) .The Target Framework in the project properties is set to .NET Framework 4.5.1.My Problem : I can still use code likewhich is a .NET 4.6 feature . When I build the project , it also runs ( I guess because it 's more or less syntactical sugar , so the compiler makes code that does n't require .NET 4.6 ) .My colleagues however are not very amused , when they check out my changes in Visual Studio 2013 ; - ) Is it possible to get warnings / compile errors in Visual Studio 2015 for using .NET 4.6 features ? <code> public int X ( ) = > x ; | How to set the .NET Version for VisualStudio2015 ( Code ) |
C_sharp : I want to be able to get string and check if the Parentheses are valid.For example : This is what I have tried : So in both cases my code will return true . Do you have any suggestions about what I need to add in order for the program to work correctly ? <code> `` ( ew ) [ ] '' - this will be valid . `` ( ew [ ) ] '' - this will be not valid . public static bool CheckString ( string input ) { int braceSum = 0 , squareSum = 0 , parenSum = 0 ; foreach ( char c in input ) { if ( c == ' { ' ) braceSum++ ; if ( c == ' } ' ) braceSum -- ; if ( c == ' [ ' ) squareSum++ ; if ( c == ' ] ' ) squareSum -- ; if ( c == ' ( ' ) parenSum++ ; if ( c == ' ) ' ) parenSum -- ; //check for negatives ( pair closes before it opens ) if ( braceSum < 0 || squareSum < 0 || parenSum < 0 ) return false ; } return ( braceSum == 0 & & squareSum == 0 & & parenSum == 0 ) ; } | How to check parentheses validation |
C_sharp : I was playing with delegates and noticed that when I create a Func < int , int , int > like the example below : The signature of the compiler generated method is not what I expected : As you can see it takes an object for it 's first parameter . But when there is a closure : Everything works as expected : This is the IL code for the method with extra parameter : It seems that the parameter A_0 is not even used . So , what is the purpose of the object parameter in the first case ? Why is n't it added when there is a closure ? Note : If you have a better idea for the title please feel free to edit.Note 2 : I compiled the first code in both Debug and Release modes , there was no difference . But I compiled second in Debug mode to get a closure behaviour since it optimizes the local variable in Release mode.Note 3 : I 'm using Visual Studio 2014 CTP.Edit : This is the generated code for Main in the first case : <code> Func < int , int , int > func1 = ( x , y ) = > x * y ; int z = 10 ; Func < int , int , int > func1 = ( x , y ) = > x * y * z ; .method private hidebysig static int32 ' < Main > b__0 ' ( object A_0 , int32 x , int32 y ) cil managed { .custom instance void [ mscorlib ] System.Runtime.CompilerServices.CompilerGeneratedAttribute : :.ctor ( ) = ( 01 00 00 00 ) // Code size 8 ( 0x8 ) .maxstack 2 .locals init ( [ 0 ] int32 V_0 ) IL_0000 : ldarg.1 IL_0001 : ldarg.2 IL_0002 : mul IL_0003 : stloc.0 IL_0004 : br.s IL_0006 IL_0006 : ldloc.0 IL_0007 : ret } // end of method Program : : ' < Main > b__0 ' .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 30 ( 0x1e ) .maxstack 2 .locals init ( [ 0 ] class [ mscorlib ] System.Func ` 3 < int32 , int32 , int32 > func1 ) IL_0000 : nop IL_0001 : ldsfld class [ mscorlib ] System.Func ` 3 < int32 , int32 , int32 > ConsoleApplication9.Program : :'CS $ < > 9__CachedAnonymousMethodDelegate1 ' IL_0006 : dup IL_0007 : brtrue.s IL_001c IL_0009 : pop IL_000a : ldnull IL_000b : ldftn int32 ConsoleApplication9.Program : : ' < Main > b__0 ' ( object , int32 , int32 ) IL_0011 : newobj instance void class [ mscorlib ] System.Func ` 3 < int32 , int32 , int32 > : :.ctor ( object , native int ) IL_0016 : dup IL_0017 : stsfld class [ mscorlib ] System.Func ` 3 < int32 , int32 , int32 > ConsoleApplication9.Program : :'CS $ < > 9__CachedAnonymousMethodDelegate1 ' IL_001c : stloc.0 IL_001d : ret } // end of method Program : :Main | Why the compiler adds an extra parameter for delegates when there is no closure ? |
C_sharp : I am attempting to create a png capture of a StackPanel , however when I save , I am getting a distorted view where all the content is black rectangles , and the size is not correct . The width and height are correct in the image save , however all the content is forced to the top and squished togetherWhat it should render as ( with some info blacked out ) <code> < Windowxmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : Views= '' clr-namespace : POExpress.Views '' x : Class= '' POExpress.MainWindow '' Title= '' My Window '' Height= '' 500 '' MinWidth= '' 1000 '' Width= '' 1000 '' > < Grid > < TabControl > < TabItem Header= '' My Epics '' > < Grid Background= '' # FFE5E5E5 '' > < Border Margin= '' 0,52,0,0 '' BorderThickness= '' 1 '' BorderBrush= '' Black '' > < ScrollViewer HorizontalScrollBarVisibility= '' Disabled '' VerticalScrollBarVisibility= '' Auto '' > < StackPanel x : Name= '' sp_ports '' Orientation= '' Vertical '' / > < /ScrollViewer > < /Border > < Button x : Name= '' btn_capture '' Content= '' Save to png '' Margin= '' 0,10,114,0 '' VerticalAlignment= '' Top '' Height= '' 31 '' Background= '' White '' HorizontalAlignment= '' Right '' Width= '' 99 '' Click= '' Btn_capture_Click '' / > < /Grid > < /TabItem > < /TabControl > < /Grid > public RenderTargetBitmap GetImage ( ) { Size size = new Size ( sp_ports.ActualWidth , sp_ports.ActualHeight ) ; if ( size.IsEmpty ) return null ; RenderTargetBitmap result = new RenderTargetBitmap ( ( int ) size.Width , ( int ) size.Height , 96 , 96 , PixelFormats.Pbgra32 ) ; DrawingVisual drawingvisual = new DrawingVisual ( ) ; using ( DrawingContext context = drawingvisual.RenderOpen ( ) ) { context.DrawRectangle ( new VisualBrush ( sp_ports ) , null , new Rect ( new Point ( ) , size ) ) ; context.Close ( ) ; } result.Render ( drawingvisual ) ; return result ; } public static void SaveAsPng ( RenderTargetBitmap src ) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog ( ) ; dlg.Filter = `` PNG Files | *.png '' ; dlg.DefaultExt = `` png '' ; if ( dlg.ShowDialog ( ) == true ) { PngBitmapEncoder encoder = new PngBitmapEncoder ( ) ; encoder.Frames.Add ( BitmapFrame.Create ( src ) ) ; using ( var stream = dlg.OpenFile ( ) ) { encoder.Save ( stream ) ; } } } private void Btn_capture_Click ( object sender , RoutedEventArgs e ) { SaveAsPng ( GetImage ( ) ) ; } | WPF StackPanel PNG Capture not rendering correctly |
C_sharp : These days it is common for the data layer to interact asynchronously with the DB : With this technique , it is my understanding that all calling methods , all the way to the UI layer , then must also be defined with the async keyword . Thus you end up with an application where every method or function that eventually interacts with the DB be an async method.This seems terribly messy and `` pollutes '' all the application layers with knowledge of an implementation detail inside the data layer.Am I misunderstanding something or is this simply what one has to do ? <code> public async Task < Customer > GetCustomer ( int id ) { using ( db = new AppDbContext ( ) ) { return await db.Customers.FindAsync ( id ) ; } } | Does async in the data layer require the entire call stack to be async as well ? |
C_sharp : The first parameter to a C # extension method is the instance that the extension method was called on . I have adopted an idiom , without seeing it elsewhere , of calling that variable `` self '' . I would not be surprised at all if others are using that as well . Here 's an example : However , I 'm starting to see others name that parameter `` @ this '' , as follows : And as a 3rd option , some prefer no idiom at all , saying that `` self '' and `` @ this '' do n't give any information . I think we all agree that sometimes there is a clear , meaningful name for the parameter , specific to its purpose , which is better than `` self '' or `` @ this '' . Some go further and say you can always come up with a more valuable name . So this is another valid point of view.What other idioms have you seen ? What idiom do you prefer , and why ? <code> public static void Print ( this string self ) { if ( self ! = null ) Console.WriteLine ( self ) ; } public static void Print ( this string @ this ) { if ( @ this ! = null ) Console.WriteLine ( @ this ) ; } | What idiom ( if any ) do you prefer for naming the `` this '' parameter to extension methods in C # , and why ? |
C_sharp : I 've got two classes : ( So far ... .there will be more that implement different types ) And now lets say I want to write a function that will accept any uniform object ... but I ca n't do that because there is no class called Uniform , only the generic Uniform < T > . So what 's the best approach to solving this problem ? Make Uniform < T > implement IUniformMake Uniform < T > extend UniformMake all my functions that accept a Uniform to be generic too so that they can take a Uniform < T > directly ? <code> public abstract class Uniform < T > public class UniformMatrix4 : Uniform < Matrix4 > | Design pattern for allowing functions to accept generic types |
C_sharp : I would like to create some existing code-modules ( IMyDesiredType ) to load with MEF . The modules mostly have some constructor arguments which I want to provide with MEF ( ImportingConstructor ) . So far this works fine.The problem now arises because sometimes the dependencies are not available ( they are null ) in the host application . The modules will throw by convention an ArgumentNullException and I don ’ t want to change that . However I want MEF to overlook such objects ( not include them in the object-graph ) . To acquire this , I let MEF create Lazy < IMyDesiredType > instances and the initializing them one by one.The problem here is , that I have to catch CompositionException and not directly the Exception ( mostly ArgumentNullException ) from the module 's constructor . Therefore , Visual-Studio breaks on each module , because of the Exception is not catched from user-code . The obvious solution to this is , to tell visual studio not to break on ArgumentNullException-types , but this feels very “ hackish ” to me . And in any other place , I want VS to break on ArgumentNullExceptions.Is there another pattern with which I can make MEF not to add components to the graph , where the dependency is declared ( [ Export ] ) , but it ’ s value is null , or is there a method of a MEF-class I can override in a derived class and catch the constructor-exception on the fore-hand ? Please leave a comment , if the question is not clear , I 'm not a native english speaker and therefore maybe the quesion is verbalized a litte confusing . <code> [ Export ( typeof ( IMyDesiredType ) ) ] class MyModule : IMyDesiredType { [ ImportingConstructor ] public MyModule ( object aNecessaryDependency ) { if ( aNecessaryDependency==null ) throw new ArgumentNullException ( nameof ( aNecessaryDependency ) ) } } foreach ( var myLazy in collectionOfMefExports ) { try { myLazy.Value // do something with the value , so the object gets composed } catch ( CompositionException ) { // Here I get the ArgumentNullException wrapped in a CompositionException // and also can work around it . However because of the exception handling // is on the first hand in MEF , VS will break always in the throwing // constructor of the module continue ; // Go to the next module after logging etc . } } | Ignore constructor exceptions with MEF without Visual Studio breaking at the exception |
C_sharp : If I 've a method Multiply defined as : Then why does the compiler emit this IL : As you can see , it also contains some additional OpCodes which do n't make sense to me , when in fact I expect the following IL : which does the very same thing.So the question is , why does the compiler emit additional OpCodes in IL ? I 'm using Debug mode . <code> public static class Experiment { public static int Multiply ( int a , int b ) { return a * b ; } } .method public hidebysig static int32 Multiply ( int32 a , int32 b ) cil managed { .maxstack 2 //why is it not 16 ? .locals init ( [ 0 ] int32 CS $ 1 $ 0000 ) //what is this ? L_0000 : nop //why this ? L_0001 : ldarg.0 L_0002 : ldarg.1 L_0003 : mul L_0004 : stloc.0 //why this ? L_0005 : br.s L_0007 //why this ? L_0007 : ldloc.0 //why this ? L_0008 : ret } .method public hidebysig static int32 MyMethod ( int32 a , int32 b ) cil managed { .maxstack 16 L_0000 : ldarg.0 L_0001 : ldarg.1 L_0002 : mul L_0003 : ret } | Why does C # compiler emit additional OpCodes in IL ? |
C_sharp : Consider this code : This my Person Class : I call Get and pass student to the method.Like this : So i get this : Generic function.But when i call Get like this : I expect thisGet ( Person person ) to be called.but again call : Get < T > ( T person ) .Why Compiler has this behavior ? <code> static void Main ( string [ ] args ) { Get < Student > ( new Student ( ) ) ; System.Console.Read ( ) ; } public static void Get < T > ( T person ) { Console.WriteLine ( `` Generic function '' ) ; } public static void Get ( Person person ) { person.Show ( ) ; } class Person { public void Show ( ) { Console.WriteLine ( `` I am person '' ) ; } } class Student : Person { public new void Show ( ) { Console.WriteLine ( `` I am Student '' ) ; } } Get < Student > ( new Student ( ) ) ; Get ( new Student ( ) ) ; | Call generic method in c # |
C_sharp : I want to cache some expressions that are generated dynamically ( with LinqKit ) in order to pass them to a Where clause that is part of an Entity Framework query.So I have something likeIs it safe for multiple threads to call Apply and then execute those queries in parallel ? Is the Expression < TDelegate > class thread-safe ? Docs only give the standard `` Any public static ( Shared in Visual Basic ) members of this type are thread safe ... '' <code> private static Expression < Func < T , bool > > _expression ; // Gets a value at runtimepublic IQueryable < T > Apply ( IQueryable < T > query ) { return query.Where ( _expression ) ; // Here _expression already has a value } | Are expression trees thread-safe ? |
C_sharp : So that 's the question . I have the following variants of code in my test framework ( assuming appBarButton is ApplicationBarIconButton ) : orBoth pieces are not working . So I want to find some workarounds to programmatically click the ApplicationBarIconButton . Any help ? <code> var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic ; var method = typeof ( ApplicationBarIconButton ) .GetMethod ( `` ClickEvent '' , bindingFlags ) ; if ( method ! = null ) { method.Invoke ( appBarButton , null ) ; } IInvokeProvider invokableButton ; var isInvokable = ( invokableButton = appBarButton as IInvokeProvider ) ! = null ; if ( isInvokable ) { invokableButton.Invoke ( ) ; } | How to programmatically click an ApplicationBarIconButton ? |
C_sharp : When I open a tool like ILSpy or dotPeek , I have an option of viewing decompiled C # or the IL.When you view the decompiled source , does the decompiler reverse engineer the IL into the decompiled C # equivalent ? If so then how would a decompiler infer such a case as the IL below ? ( do note that this is a trivial example of the first language construct that came to mind which could n't easily be inferred from IL , as opposed to actual output from a decompiler ) : Translate to : <code> IL_0000 : nop // Do nothing ( No operation ) IL_0001 : ldstr `` C '' // Push a string object for the literal stringIL_0006 : stloc.0 // Pop a value from stack into local variable 0IL_0007 : ret public class C { public void M ( ) { string foo = nameof ( C ) ; } } | Does decompiled C # get reverse engineered from IL/MSIL ? |
C_sharp : Is there a way to emulate F # 's with keyword in C # ? I know it will likely not be as elegant , but I 'd like to know if there 's any way to handle creating new immutable copies of data structures.Records in F # are detailed here.Here 's an example of what I 'm trying to do . We 'll create `` immutable '' views of data via interfaces , while maintaining mutability in concrete classes . This lets us mutate locally ( while working ) and then return an immutable interface . This is what we 're handling immutability in C # .However , when it comes time to make a change to the data , it 's not very type ( or mutability ! ) safe to cast it back and forth , and it 's also a real pain to manually translate each property of the class into a new instance . What if we add a new one ? Do I have to go track down each manipulation ? I do n't want to create future headache when I really only need what I had before , but with [ some change ] .Example : What are sound strategies for accomplishing this ? What have you used in the past ? <code> public interface IThing { double A { get ; } double B { get ; } } public class Thing : IThing { double A { get ; set ; } double B { get ; set ; } } // ... IThing item = MethodThatDoesWork ( ) ; // Now I want to change it ... how ? This is ugly and error/change prone : IThing changed = new Thing { A = item.A , B = 1.5 } ; // ... | Emulating F # ` with ` keyword in C # |
C_sharp : I have a probleme with Postsharp.i have this : and i used like this . In assemblyInfo.cs : so , when an exception occurs in the assembly its executes OnException method . But , when i debug the method and i watch args ( type : MethodExecutionArgs ) every property has a null value . args.Exception is null . And i need the exception type..Anyone knows how can i fix this ? Thanks in advance <code> [ Serializable ] public class MethodConnectionTracking : OnExceptionAspect { public override void OnException ( MethodExecutionArgs args ) { base.OnException ( args ) ; } } [ assembly : MethodConnectionTracking ] | postsharp exception is null |
C_sharp : I 'm using the Youtube .Net libray I downloaded from Nuget . I created a windows service which is checking a folder to upload new videos to youtube . I did the tests using a console application and for this case the user had to do authorization manually on a web browser , after that I could upload videos to youtube without any problem . The issue is when I 'm trying to use the offline access . As I 'm running my code on a windows service I can not get a the manual authorization from the user so I created my access token following this answer : https : //stackoverflow.com/a/20689423/2277059The thing is that I did n't find any example of code using the standalone version so I 'm a bit lost . With my current code I 'm getting all the time Error : '' unauthorized_client '' when trying to upload the video . The JSON file you can see on my code `` client_secrets.json '' is the one you automatically generate when creating the credentials for the YouTube API V3.I tried this as well : https : //stackoverflow.com/a/43895931/2277059 , but got same error.Right now I 'm not refreshing the token from code , just doin it on the OAuth Playground and testing the service . Once it worked I 'll research about how refresh the token with every query.When creating the credentials I selected the type `` Other '' as this is a windows service.Is it something wrong with my code or am I missing something on the configuration ? This is my code : <code> var token = new TokenResponse ( ) { AccessToken = `` werwdsgfdg ... '' , ExpiresInSeconds = 3600 , RefreshToken = `` 3/dsdfsf ... '' , TokenType = `` Bearer '' } ; Log.Info ( `` Generating user credentials and secrets '' ) ; UserCredential credential ; string credentialsPath = System.AppDomain.CurrentDomain.BaseDirectory + `` client_secrets.json '' ; using ( var stream = new FileStream ( credentialsPath , FileMode.Open , FileAccess.Read ) ) { credential = new UserCredential ( new GoogleAuthorizationCodeFlow ( new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = GoogleClientSecrets.Load ( stream ) .Secrets , Scopes = new [ ] { YouTubeService.Scope.YoutubeUpload } } ) , EsSettings.YoutubeUser , token ) ; } Log.Info ( `` Generating youtube service '' ) ; //GoogleAuthorizationCodeFlowYouTubeService youtubeService = new YouTubeService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Name } ) ; Log.Info ( `` Uploading ... '' ) ; using ( var fileStream = new FileStream ( filePath , FileMode.Open ) ) { var videosInsertRequest = youtubeService.Videos.Insert ( video , `` snippet , status '' , fileStream , `` video/* '' ) ; videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged ; videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived ; await videosInsertRequest.UploadAsync ( ) ; } | .NET - How to upload videos to YouTube using OAuth2.0 and Offline Access from a Windows Service |
C_sharp : I am developing an intranet asp.net core web api application . The requirements for authentications are : REQ1 - when user which is trying to access the website is not in Active Directory 's special group ( let 's name it `` commonUsers '' ) it is simply not authorizedREQ2 - when user which is trying to access the website is in Active Directory 's group `` commonUsers '' is is authorized and a web resource is returnedREQ3 - when user which is trying to access the website is in Active Directory 's group `` superUser '' , it need to be prompted for his domain password once again ( because it tries to access some very restricted resources ) Now , what I have so far : My service is hosted using http.sys server in order to support windows authentication . I am using claims transformer middlewere in order to check the user 's Active Directory group , let 's say something like this : I have specified a special policies also in my service configuration , for instance something like that : I am using [ Authorize ] attribute with specific policy in order to restrict access to specific resources based on policiesNow the question is , how should I satisfy REQ3 ? <code> public class ClaimsTransformer : IClaimsTransformation { private readonly IAuthorizationService _authorizationService ; public ClaimsTransformer ( IAuthorizationService authorizationService ) { _authorizationService = authorizationService ; } public Task < ClaimsPrincipal > TransformAsync ( ClaimsPrincipal principal ) { _authorizationService.Authorize ( principal as IHmiClaimsPrincipal ) ; return Task.FromResult ( principal ) ; } } services.AddAuthorization ( options = > { options.AddPolicy ( `` TestPolicy '' , policy = > policy.RequireClaim ( ClaimTypes.Role , `` TestUser '' ) ) ; options.AddPolicy ( `` TestPolicy2 '' , policy = > policy.RequireClaim ( ClaimTypes.Role , `` SuperUser '' ) ) ; } ) ; | Windows Authentication - require additional password for special users |
C_sharp : I 'm playing with RavenDb and wondering if I 'm missing something obvious.Thing is , that if I 'm passing query like this : It works ok , if i 'm writing equivalent ( IMO ) using Func < T , bool > , it does not crash , but query is missing where condition : Profiler outputs it like : query= start=0 pageSize=5 aggregation=None sort=-CreatedAtUpdate : It works if I 'm using expression instead of Func , so I thought may be I remember something wrong about Func and Linq , so wrote a simple test : So now it is only question why Raven Db query builder acts different . <code> var name = `` test '' ; posts = RavenSession.Query < Post > ( ) .Where ( x = > x.Tags.Any ( y = > y == name ) ) .OrderByDescending ( x = > x.CreatedAt ) .Take ( 5 ) ; var name = `` test '' ; Func < Post , bool > selector = x = > x.Tags.Any ( y = > y == name ) ; posts = RavenSession.Query < Post > ( ) .Where ( x = > selector ( x ) ) .OrderByDescending ( x = > x.CreatedAt ) .Take ( 5 ) ; var range = Enumerable.Range ( 1 , 50 ) ; Func < int , bool > selector = x = > x == 42 ; var filtered = range.Where ( x = > selector ( x ) ) ; | Passing ravendb query as Func < T , bool > does not work |
C_sharp : For example , if you run the following code ... ... and you watch IListType variable , you 'll find that the whole Type instance has all properties available like FullName and others . But what happens when you run the code bellow ? Now IListType got from a generic type definition is n't the same as the first code sample : most Type properties will return null.The main issue with this is that IListType == IListType2 does n't equal while they 're the same type.What 's going on ? This is ugly ... Now see what happens if you call IListType2.GetGenericTypeDefinition ( ) ... It recovers the type information ! It would be great that a .NET Framework development team member could explain us why an already generic type definition which has strangely lost its metadata has IsGenericTypeDefinition property set to false while it 's still a generic type definition , and finally , if you call GetGenericTypeDefinition ( ) on it , you recover the type information.This is strange ... The following equality will be true : <code> Type IListType = new List < string > ( ) .GetType ( ) .GetInterface ( `` IList ` 1 '' ) .GetGenericTypeDefinition ( ) ; Type IListType2 = typeof ( List < > ) .GetInterface ( `` IList ` 1 '' ) Type IListType = new List < string > ( ) .GetType ( ) .GetInterface ( `` IList ` 1 '' ) .GetGenericTypeDefinition ( ) ; // Got interface is `` like a generic type definition '' since it has// no type for T generic parameter , and once you call // GetGenericTypeDefinition ( ) again , it recovers the lost metadata // and the resulting generic type definition equals the one got from// List < string > ! Type IListType2 = typeof ( List < > ) .GetInterface ( `` IList ` 1 '' ) .GetGenericTypeDefinition ( ) ; bool y = IListType == IListType2 ; | Why a generic type definition implemented interfaces lose type information ? |
C_sharp : I have a class that contains both primitive and custom properties : In the future i want to extend the class with a int property plus a customization of one of my custom objects , in this way : In Version_2 class the look of WeirdDad object has been replaced with its child WeirdChild so i want to substitute it.In this example , instead , i will have in the Version_2 class both WeirdDad and WeirdChild.How would you implement this example ? <code> public class Version_1 { public string Name { get ; set ; } public int Age { get ; set ; } public WeirdDad Weird { get ; set ; } public MysteriousDad Mysterious { get ; set ; } } public class Version_2 : Version_1 { public string IdentityCode { get ; set ; } public WeirdChild Weird { get ; set ; } } | Replace object in Inheritance |
C_sharp : I have a TcpClient class on a client and server setup on my local machine . I have been using the Network stream to facilitate communications back and forth between the 2 successfully.Moving forward I am trying to implement compression in the communications . I 've tried GZipStream and DeflateStream . I have decided to focus on DeflateStream . However , the connection is hanging without reading data now . I have tried 4 different implementations that have all failed due to the Server side not reading the incoming data and the connection timing out . I will focus on the two implementations I have tried most recently and to my knowledge should work.The client is broken down to this request : There are 2 separate implementations , one with streamwriter one without . The server receives the request and I do1 . ) a quick read of the first character then if it matches what I expect2 . ) I continue reading the rest . The first read works correctly and if I want to read the whole stream it is all there . However I only want to read the first character and evaluate it then continue in my LongReadStream method . When I try to continue reading the stream there is no data to be read . I am guessing that the data is being lost during the first read but I 'm not sure how to determine that . All this code works correctly when I use the normal NetworkStream . Here is the server side code.EDITNetworkStream has an underlying Socket property which has an Available property . MSDN says this about the available property . Gets the amount of data that has been received from the network and is available to be read.Before the call below Available is 77 . After reading 1 byte the value is 0.There does n't seem to be any documentation about DeflateStream consuming the whole underlying stream and I do n't know why it would do such a thing when there are explicit calls to be made to read specific numbers of bytes.Does anyone know why this happens or if there is a way to preserve the underlying data for a future read ? Based on this 'feature ' and a previous article that I read stating a DeflateStream must be closed to finish sending ( flush wo n't work ) it seems DeflateStreams may be limited in their use for networking especially if one wishes to counter DOS attacks by testing incoming data before accepting a full stream . <code> textToSend = ENQUIRY + START_OF_TEXT + textToSend + END_OF_TEXT ; // Send XML Requestbyte [ ] request = Encoding.UTF8.GetBytes ( textToSend ) ; using ( DeflateStream streamOut = new DeflateStream ( netStream , CompressionMode.Compress , true ) ) { //using ( StreamWriter sw = new StreamWriter ( streamOut ) ) // { // sw.Write ( textToSend ) ; // sw.Flush ( ) ; streamOut.Write ( request , 0 , request.Length ) ; streamOut.Flush ( ) ; // } } private void ProcessRequests ( ) { // This method reads the first byte of data correctly and if I want to // I can read the entire request here . However , I want to leave // all that data until I want it below in my LongReadStream method . if ( QuickReadStream ( _netStream , receiveBuffer , 1 ) ! = ENQUIRY ) { // Invalid Request , close connection clientIsFinished = true ; _client.Client.Disconnect ( true ) ; _client.Close ( ) ; return ; } while ( ! clientIsFinished ) // Keep reading text until client sends END_TRANSMISSION { // Inside this method there is no data and the connection times out waiting for data receiveText = LongReadStream ( _netStream , _client ) ; // Continue talking with Client ... } _client.Client.Shutdown ( SocketShutdown.Both ) ; _client.Client.Disconnect ( true ) ; _client.Close ( ) ; } private string LongReadStream ( NetworkStream stream , TcpClient c ) { bool foundEOT = false ; StringBuilder sbFullText = new StringBuilder ( ) ; int readLength , totalBytesRead = 0 ; string currentReadText ; c.ReceiveBufferSize = DEFAULT_BUFFERSIZE * 100 ; byte [ ] bigReadBuffer = new byte [ c.ReceiveBufferSize ] ; while ( ! foundEOT ) { using ( var decompressStream = new DeflateStream ( stream , CompressionMode.Decompress , true ) ) { //using ( StreamReader sr = new StreamReader ( decompressStream ) ) // { //currentReadText = sr.ReadToEnd ( ) ; // } readLength = decompressStream.Read ( bigReadBuffer , 0 , c.ReceiveBufferSize ) ; currentReadText = Encoding.UTF8.GetString ( bigReadBuffer , 0 , readLength ) ; totalBytesRead += readLength ; } sbFullText.Append ( currentReadText ) ; if ( currentReadText.EndsWith ( END_OF_TEXT ) ) { foundEOT = true ; sbFullText.Length = sbFullText.Length - 1 ; } else { sbFullText.Append ( currentReadText ) ; } // Validate data code removed for simplicity } c.ReceiveBufferSize = DEFAULT_BUFFERSIZE ; c.ReceiveTimeout = timeOutMilliseconds ; return sbFullText.ToString ( ) ; } private string QuickReadStream ( NetworkStream stream , byte [ ] receiveBuffer , int receiveBufferSize ) { using ( DeflateStream zippy = new DeflateStream ( stream , CompressionMode.Decompress , true ) ) { int bytesIn = zippy.Read ( receiveBuffer , 0 , receiveBufferSize ) ; var returnValue = Encoding.UTF8.GetString ( receiveBuffer , 0 , bytesIn ) ; return returnValue ; } } //receiveBufferSize = 1int bytesIn = zippy.Read ( receiveBuffer , 0 , receiveBufferSize ) ; | Why is my DeflateStream not receiving data correctly over TCP ? |
C_sharp : Research : Mocking IConfiguration from .NET CoreI need to integration test my data access layer to ensure that all the code is working properly.I know that it is n't going to work using the normal way : Normally the data access layer uses dependency injection and it retrieves the connection string with IConfiguration.My integration test : But I get an errorSystem.InvalidOperationException : The ConnectionString property has not been initialized.I 'm a bit lost here , I 'm not sure what happened . <code> //Will return a NotSupportedExceptionvar mock = new Mock < IConfiguration > ( ) ; mock.Setup ( arg = > arg.GetConnectionString ( It.IsAny < string > ( ) ) ) .Returns ( `` testDatabase '' ) ; [ Fact ] public async void GetOrderById_ScenarioReturnsCorrectData_ReturnsTrue ( ) { // Arrange OrderDTO order = new OrderDTO ( ) ; // Mocking the ASP.NET IConfiguration for getting the connection string from appsettings.json var mockConfSection = new Mock < IConfigurationSection > ( ) ; mockConfSection.SetupGet ( m = > m [ It.Is < string > ( s = > s == `` testDB '' ) ] ) .Returns ( `` mock value '' ) ; var mockConfiguration = new Mock < IConfiguration > ( ) ; mockConfiguration.Setup ( a = > a.GetSection ( It.Is < string > ( s = > s == `` ConnectionStrings : testDB '' ) ) ) .Returns ( mockConfSection.Object ) ; IDataAccess dataAccess = new SqlDatabase ( mockConfiguration.Object ) ; IRepository repository = new repository ( dataAccess , connectionStringData ) ; var connectionStringData = new ConnectionStringData { SqlConnectionLocation = `` testDatabase '' } ; // Act int id = await repository.CreateOrder ( order ) ; // Assert Assert.Equal ( 1 , id ) ; } | How to mock GetConnectionString ( ) from IConfiguration using moq ? |
C_sharp : My brain seems to be in masochistic mode , so after being drowned in this , this and this , it wanted to mess around with some DIY in C # .I came up with the following , which I do n't think is the Y-combinator , but it does seem to manage to make a non-recursive function recursive , without referring to itself : So given these : We can generate these : <code> Func < Func < dynamic , dynamic > , Func < dynamic , dynamic > > Y = x = > x ( x ) ; Func < dynamic , Func < dynamic , dynamic > > fact = self = > n = > n == 0 ? 1 : n * self ( self ) ( n - 1 ) ; Func < dynamic , Func < dynamic , dynamic > > fib = self = > n = > n < 2 ? n : self ( self ) ( n-1 ) + self ( self ) ( n-2 ) ; Func < dynamic , dynamic > Fact = Y ( fact ) ; Func < dynamic , dynamic > Fib = Y ( fib ) ; Enumerable.Range ( 0 , 10 ) .ToList ( ) .ForEach ( i = > Console.WriteLine ( `` Fact ( { 0 } ) = { 1 } '' , i , Fact ( i ) ) ) ; Enumerable.Range ( 0 , 10 ) .ToList ( ) .ForEach ( i = > Console.WriteLine ( `` Fib ( { 0 } ) = { 1 } '' , i , Fib ( i ) ) ) ; | Have I implemented Y-combinator using C # dynamic , and if I have n't , what is it ? |
C_sharp : UPDATE : Sept 2019.This API call now works as intended.Issues on the Tableau end appear to have been resolved and the call now returns the correct data.===============================================================I 'm using the Tableau REST API via C # to try and get a list of users favorites.I know the user has some , because its me.I have tried using API Version 2.8,3.0 , 3.1 and 3.2 with little to no joy.2.8 and 3.0 respond with:3.1 and 3.2 give me a ( 404 ) Not found.The code i have in c # is : I know the method works , as it is used for multiple other API calls using a different URL for each ( depending on the call ) .Does anyone know if its an issue on the tableau end or on my end ? Apparently it should work with Tableau server 2.8 or above , which we have . ( i think we 're running 2018.1 ) Is anyone able to get a list of favorites for a user using tableau REST API ? Where am i going wrong ? ( I have also posted the question on Tableau Forum . ) UPDATE : I have included the CURL and Headers of the request , as well as the results , in the screenshots below . ( I use 'Restlet Client ' more than 'Postman ' so screenshots are from the former . ) ID 's and authentication tokens have been removed as they are sensitive information , and i do n't think my company would be happy with me putting them on the public facing internet.All ID 's and auth keys are in the correct case and presented correctly . They are used in several other API calls with success and are pulled direct from Tableau via the API.The exceptions , i have found out are the inability to find the version of the API that i am calling . so v2.6 - v2.8 and v3.0 all `` work '' . Other versions return a 404001 VERSION_NOT_FOUND error . <code> < ? xml version= ' 1.0 ' encoding='UTF-8 ' ? > < tsResponse xmlns= '' http : //tableau.com/api '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //tableau.com/api http : //tableau.com/api/ts-api-2.8.xsd '' > //3.0.xsd when using API Version 3.0 < favorites/ > //There should be a plethora of favorites of all varieties in here. < /tsResponse > public static string QueryFavourites ( string APIVersion , string AuthToken , string SiteID , string UserID ) { string result = `` '' ; try { string url = $ @ '' { Server } /api/ { APIVersion } /sites/ { SiteID } /favorites/ { UserID } '' ; // Create the web request WebRequest request = WebRequest.Create ( url ) as WebRequest ; request.PreAuthenticate = true ; request.Headers.Add ( $ '' x-tableau-auth : { AuthToken } '' ) ; // Get response using ( WebResponse response = request.GetResponse ( ) ) { // Get the response stream StreamReader reader = new StreamReader ( response.GetResponseStream ( ) ) ; // Read the whole contents and return as a string result = reader.ReadToEnd ( ) ; } return result ; } catch ( Exception E ) { logger.Error ( `` Error ! System Says : `` + E.Message ) ; return result ; } } | Unable to return user favorites via Tableau REST API |
C_sharp : I 'm trying to make vector with 4 doubles with System.Numerics library because of SIMD . So I made this struct : In this phase I code it for 128bit SIMD register.It works fine , but when I want something like this : I get this : Can not take the address of , get the size of , or declare a pointer to a managed type ( 'Vector4D ' ) Any idea how to use stackalloc with System.Numerics.Vector ? With System.Numerics.Vector4 ( which is float-precision ) there is no problem with pointers , but I need double-precision . <code> public struct Vector4D { System.Numerics.Vector < double > vecXY , vecZW ; ... } Vector4D* pntr = stackalloc Vector4D [ 8 ] ; | Pointer to struct containing System.Numerics.Vector < double > in C # |
C_sharp : I 've this piece of code : And it should save all those variables into the textfile I say but it only writes the first variable ( numcont ) . What I need to do so it writes all the variables I need on that textfile ? Feel free to ask for more code . <code> using ( StreamWriter writer = new StreamWriter ( `` C : \\Users\\HP8200\\Desktop\\teste.txt '' ) ) { string numcont = _transaction.PartyFederalTaxID ; double numenc = _transaction.BillToPartyID ; double numfatura = _transaction.BillToPartyID ; string zona = _transaction.BillToPartyCountryID ; DateTime data = _transaction.CreateDate ; string ean = _transaction.ATDocCodeId ; double iva = _transaction.TotalTaxAmount ; double precoantesdisc = _transaction.TotalLineItemDiscountAmount ; double preconet = _transaction.TotalNetAmount ; writer.WriteLine ( numcont , '' ; '' , numenc , '' ; '' , numfatura , '' ; '' , data , '' ; '' , zona , Environment.NewLine , ean , '' ; '' , iva , '' ; '' , precoantesdisc , '' ; '' , preconet ) ; } MessageBox.Show ( `` gravou '' ) ; | Writing many variables into textfile |
C_sharp : To add foreach support to a custom collection , you need to implement IEnumerable . Arrays , however , are special in that they essentially compile into a range-based for loop , which is much faster than using an IEnumerable . A simple benchmark confirms that : The benchmark : And the implementation : Because arrays get special treatment from the compiler , they leave IEnumerable collections in the dust . Since C # focuses heavily on type safety , I can understand why this is the case , but it still incurs an absurd amount of overhead , especially for my custom collection , which enumerates in the exact same way as an array would . In fact , my custom collection is faster than a byte array in a range based for loop , as it uses pointer arithmetic to skip the CLR 's array range checks.So my question is : Is there a way to customize the behavior of a foreach loop such that I can achieve performance comparable to an array ? Maybe through compiler intrinsics or manually compiling a delegate with IL ? Of course , I can always just use a range based for loop instead . I am just curious as to if there is any possible way to customize the low-level behavior of a foreach loop in a similar manner to how the compiler handles arrays . <code> number of elements : 20,000,000 byte [ ] : 6.860ms byte [ ] as IEnumerable < byte > : 89.444msCustomCollection.IEnumerator < byte > : 89.667ms private byte [ ] byteArray = new byte [ 20000000 ] ; private CustomCollection < byte > collection = new CustomCollection < T > ( 20000000 ) ; [ Benchmark ] public void enumerateByteArray ( ) { var counter = 0 ; foreach ( var item in byteArray ) counter += item ; } [ Benchmark ] public void enumerateByteArrayAsIEnumerable ( ) { var counter = 0 ; var casted = ( IEnumerable < byte > ) byteArray ; foreach ( var item in casted ) counter += item ; } [ Benchmark ] public void enumerateCollection ( ) { var counter = 0 ; foreach ( var item in collection ) counter += item ; } public class CustomCollectionEnumerator : IEnumerable < T > where T : unmanaged { private CustomCollection < T > _collection ; private int _index ; private int _endIndex ; public CustomCollectionEnumerator ( CustomCollection < T > collection ) { _collection = collection ; _index = -1 ; _endIndex = collection.Length ; } public bool MoveNext ( ) { if ( _index < _endIndex ) { _index++ ; return ( _index < _endIndex ) ; } return false ; } public T Current = > _collection [ _index ] ; object IEnumerator.Current = > _collection [ _index ] ; public void Reset ( ) { _index = -1 ; } public void Dispose ( ) { } } public class CustomCollection < T > : IEnumerable < T > where T : unmanaged { private T* _ptr ; public int Length { get ; private set ; } public T this [ int index ] { [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] get = > *_ptr [ index ] ; [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] set = > *_ptr [ index ] = value ; } public IEnumerator < T > GetEnumerator ( ) { return new CustomCollectionEnumerator < T > ( this ) ; } } | Writing an IEnumerator with performance comparable to array foreach |
C_sharp : The multiple answers to question `` Multi value Dictionary '' propose to use an immutable class as TValue in Dictionary < TKey , TValue > Class . The accepted Jon Skeet 's answer proposes a class Pair with readonly properties and @ teedyay 's answer to use the immutable Tuple . What is the rationale ( or the possible benefits ) of such approaches ? And collateral question : Why to make TFirst and TSecond readonly if the respective properties First and Second do not have setters anyway : Update : I am using dictionaries with custom classes for values in them.And the va lues are being updated.What are the possible reasons ( benefits ) for me to make them immutable ? I see that Lookup < TKey , TElement > Class is also immutable and thought that I miss some benefits of using LINQ queries ( ? ) If so , can you give me examples what do I miss ? <code> private readonly TFirst first ; private readonly TSecond second ; public TFirst First { get { return first ; } } public TSecond Second { get { return second ; } } | Why would you use an immutable value in a dictionary ? |
C_sharp : using ILspy the code is : why is it checking if the num is greater than 2146435071 specifically should n't it just check for underflow & set num=Int.Max or anyother value greater than min ? <code> private void EnsureCapacity ( int min ) { if ( this._items.Length < min ) { int num = ( this._items.Length == 0 ) ? 4 : ( this._items.Length * 2 ) ; if ( num > 2146435071 ) { num = 2146435071 ; } if ( num < min ) { num = min ; } this.Capacity = num ; } } | why does c # List implementation specify this exact value in the ensure capacity method ? |
C_sharp : Inlining functions is a compiler optimization that replaces the function call site with the body of the callee . This optimization is supported for regular C # functions.Async functions that support the async-await pattern in C # 5.0 have a special declaration that involves the async modifier and wrapping return values with Task < > .Can async functions be inlined as well ? Example : Suppose I have these functions : Could they be optimized to : Extra Credit : If it is supported , who can decide what 's inlined ? The compiler ? The JIT ? me ? If it 's not supported , should I worry about this and avoid excessive wrappers I sometimes add for readability ? <code> private async Task < int > CalleeAsync ( ) { return await SomeOperationAsync ( ) ; } private async Task < int > CallerAsync ( ) { return await CalleeAsync ( ) ; } private async Task < int > CallerAsync ( ) { return await SomeOperationAsync ( ) ; } | Can async functions be inlined ? |
C_sharp : As far as I know , generic type A < T1 , T2 > is not an actual type , but rather a blueprint/template for an actual type , so why does typeof accept it as a parameter ( since as far as I know , typeof accepts as parameter actual types ) ? Thank you <code> class Program { static void Main ( string [ ] args ) { Type t = typeof ( A < , > ) ; Console.WriteLine ( typeof ( A < , > ) ) ; // prints A ' 2 [ T1 , T2 ] } } class A < T1 , T2 > { } | If A < T1 , T2 > is a template for actual type , then why is typeof ( A < , > ) allowed ? |
C_sharp : I have some code that currently looks somewhat like this : As you can see , I 'm currently wrapping the call to SomeProblemFunction around a try statement because that function could fail ( it relies on an outside web service call ) .My question is this : should the try statement be a ) outside the problem function ( like I have it now ) or b ) inside the problem function ? Thanks . <code> public void MainFunction ( ) { try { SomeProblemFunction ( ) ; } catch { AllFineFunction ( ) ; } } private void SomeProblemFunction ( ) { ... } private void AllFineFunction ( ) { ... } | position of the try catch statement |
C_sharp : I 'm trying to solve a dilemna that has been nagging me for the last few months.My colleagues and I completely disagree on a technical problem , and I would like our beloved community 's opinion on the matter.In a nutshell : Is it preferable to use enumerations ( with potentially attributes on them such as `` Description '' ) , or use entities ( with Name and Description properties ) ? In details : In our domain model , we 've got a lot of mini-entities which only contain an Id , a Name , and a Description.95 % of the time , the Description is equal to the Name.For the sake of the explanation I 'm going to take one of the many example : in our Security entity , we have an AssetClass property.An AssetClass has a static list of values ( `` Equity '' , `` Bond '' , etc . ) and does not change from the interface or anything else.The problem with that , is when you want to get all securities with an asset class of `` Bond '' say , NHibernate will have to join on the AssetClass table ... and considering AssetClass is not the only property like that , you can imagine the performance impact of all those joins.Our current solution : ( which I disagree with ) : We have in our code some hard-coded instances of AssetClass with all their respective values and Ids ( i.e . Equity with Id of 1 , Bond with Id of 2 etc . ) , which match what 's in the database : We also made a special NHibernate type ( code below if you are interested ) that allow us to avoid NHibernate doing a join by loading that hard-coded instance instead of going to the database to get it : My solution : ( which I agree with : - ) ) Replacing those entities by enums , and if we ever need a Description field , use an attribute.We could also have a constraint on the database to make sure you ca n't store random values that do n't match an enum.Their rational against using enumerations : This is not an object , so you ca n't extend it , it 's not object oriented , etc.You ca n't get the description easily , or have `` proper english '' names ( with spaces or symbols ) such as `` My Value '' ( which on an enum would be `` MyValue '' ) Enums sucksAttribute sucksMy rational against our current solution : We can have a mismatch between the ids in the code and what 's in the databaseIt 's a lot harder to maintain ( we need to make absolutely sure that every hard-coded values we have are also there in the database ) Attributes and enums do n't suck if used properly and for static values like theseFor `` proper english '' names , we can also use an attribute , with some extension method to consume it.Now , what do YOU think ? <code> public partial class AssetClass { static public AssetClass Equity = new AssetClass ( 1 , `` Equity '' , `` Equity '' ) ; static public AssetClass Bond = new AssetClass ( 2 , `` Bond '' , `` Bond '' ) ; static public AssetClass Future = new AssetClass ( 3 , `` Future '' , `` Future '' ) ; static public AssetClass SomethingElse = new AssetClass ( 4 , `` Something else '' , `` This is something else '' ) ; } using System ; using System.Data ; using System.Data.Common ; using NHibernate.Dialect ; using NHibernate.SqlTypes ; using NHibernate.Type ; namespace MyCompany.Utilities.DomainObjects { public abstract class PrimitiveTypeBase < T > : PrimitiveType where T : class , IUniquelyNamed , IIdentifiable { private readonly PrimitiveTypeFactory < T > _factory ; public PrimitiveTypeBase ( ) : base ( SqlTypeFactory.Int32 ) { _factory = new PrimitiveTypeFactory < T > ( ) ; } public override string Name { get { return typeof ( T ) .Name ; } } public override Type ReturnedClass { get { return typeof ( T ) ; } } public override Type PrimitiveClass { get { return typeof ( int ) ; } } public override object DefaultValue { get { return null ; } } public override void Set ( IDbCommand cmd , object value , int index ) { var type = value as T ; var param = cmd.Parameters [ index ] as DbParameter ; param.Value = type.Id ; } public override object Get ( IDataReader rs , int index ) { return GetStaticValue ( rs [ index ] ) ; } public override object Get ( IDataReader rs , string name ) { return GetStaticValue ( rs [ name ] ) ; } private T GetStaticValue ( object val ) { if ( val == null ) { return ( T ) DefaultValue ; } int id = int.Parse ( val.ToString ( ) ) ; T entity = _factory.GetById ( id ) ; // that returns , by reflection and based on the type T , the static value with the given Id if ( entity == null ) { throw new InvalidOperationException ( string.Format ( `` Could not determine { 0 } for id { 1 } '' , typeof ( T ) .Name , id ) ) ; } return entity ; } public override object FromStringValue ( string xml ) { return GetStaticValue ( xml ) ; } public override string ObjectToSQLString ( object value , Dialect dialect ) { var type = value as T ; return type.Id.ToString ( ) ; } } } | Opinion requested : for static values , is it better to use Enums or Entities ? |
C_sharp : When compiling code which uses code contracts , I have a very strange error I do n't understand.fails with the following error : Malformed contract . Found Invariant after assignment in method ' < ProjectName > .ObjectInvariant'.If the code is modified like this : it compiles well.What 's wrong with my default ( Guid ) ? <code> [ ContractInvariantMethod ] private void ObjectInvariant ( ) { Contract.Invariant ( this.isSubsidiary || this.parentCompanyId == default ( Guid ) ) ; } [ ContractInvariantMethod ] private void ObjectInvariant ( ) { Contract.Invariant ( this.isSubsidiary || this.parentCompanyId == Guid.Empty ) ; // Noticed the Guid.Empty instead of default ( Guid ) ? } | Why contract is malformed when using default ( Type ) ? |
C_sharp : I have an IEnumerable < IEnumerable < T > > collection that I want to convert to a single dimension collection . Is it possible to achieve this with a generic extension method ? Right now I 'm doing this to achieve it.If it 's not possible to get a generic solution , how can I optimize this in an elegant fashioned way . <code> List < string > filteredCombinations = new List < string > ( ) ; //For each collection in the combinated results collectionforeach ( var combinatedValues in combinatedResults ) { List < string > subCombinations = new List < string > ( ) ; //For each value in the combination collection foreach ( var value in combinatedValues ) { if ( value > 0 ) { subCombinations.Add ( value.ToString ( ) ) ; } } if ( subCombinations.Count > 0 ) { filteredCombinations.Add ( String.Join ( `` , '' , subCombinations.ToArray ( ) ) ) ; } } | How to convert an IEnumerable < IEnumerable < T > > to a IEnumerable < T > |
C_sharp : I was doing other experiments until this strange behaviour caught my eye.code is compiled in x64 release.if key in 1 , the 3rd run of List method cost 40 % more time than the first 2. output is if key in 2 , the 3rd run of Array method cost 30 % more time than the first 2. output is You can see the pattern , the complete code is attached following ( just compile and run ) : { the code presented is minimal to run the test . The actually code used to get reliable result is more complicated , I wrapped the method and tested it 100+ times after proper warmed up } <code> List costs 9312List costs 9289Array costs 12730List costs 11950 Array costs 8082Array costs 8086List costs 11937Array costs 12698 class ListArrayLoop { readonly int [ ] myArray ; readonly List < int > myList ; readonly int totalSessions ; public ListArrayLoop ( int loopRange , int totalSessions ) { myArray = new int [ loopRange ] ; for ( int i = 0 ; i < myArray.Length ; i++ ) { myArray [ i ] = i ; } myList = myArray.ToList ( ) ; this.totalSessions = totalSessions ; } public void ArraySum ( ) { var pool = myArray ; long sum = 0 ; for ( int j = 0 ; j < totalSessions ; j++ ) { sum += pool.Sum ( ) ; } } public void ListSum ( ) { var pool = myList ; long sum = 0 ; for ( int j = 0 ; j < totalSessions ; j++ ) { sum += pool.Sum ( ) ; } } } class Program { static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; ListArrayLoop test = new ListArrayLoop ( 10000 , 100000 ) ; string input = Console.ReadLine ( ) ; if ( input == `` 1 '' ) { sw.Start ( ) ; test.ListSum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` List costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ListSum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` List costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ArraySum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Array costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ListSum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` List costs { 0 } '' , sw.ElapsedMilliseconds ) ; } else { sw.Start ( ) ; test.ArraySum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Array costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ArraySum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Array costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ListSum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` List costs { 0 } '' , sw.ElapsedMilliseconds ) ; sw.Reset ( ) ; sw.Start ( ) ; test.ArraySum ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Array costs { 0 } '' , sw.ElapsedMilliseconds ) ; } Console.ReadKey ( ) ; } } | why in this simple test the speed of method relates to the order of triggering ? |
C_sharp : According to the documentation a ValueTask < TResult > ... Provides a value type that wraps a Task < TResult > and a TResult , only one of which is used . My question is about the state machine that the C # compiler generates when the async keyword is encountered . Is it smart enough to generate a ValueTask < TResult > that wraps a TResult , when the result is available immediately , or one that wraps a Task < TResult > , when the result comes after an await ? Here is an example : Calling GetNowAsync ( false ) should return a TResult wrapper , because nothing is awaited , and calling GetNowAsync ( true ) should return a Task < TResult > wrapper , because a Task.Delay is awaited before the result becomes available . I am worried about the possibility that the state machine always returns Task wrappers , nullifying all the advantages of the ValueTask type over the Task ( and keeping all the disadvantages ) . As far as I can tell the properties of the type ValueTask < TResult > offer no indication about what it wraps internally . I pasted the code above to sharplab.io , but the output did n't help me to answer this question either . <code> static async ValueTask < DateTime > GetNowAsync ( bool withDelay ) { if ( withDelay ) await Task.Delay ( 1000 ) ; return DateTime.Now ; } static void Test ( ) { var t1 = GetNowAsync ( false ) ; var t2 = GetNowAsync ( true ) ; } | The ValueTask < TResult > and the async state machine |
C_sharp : After refactoring some code recently , which involved some class renames , some of my code broke in a surprising way . The cause was a failing `` is '' operator test , that I was very surprised was n't a compiler error or warning.This complete program shows the situation : I would have expected `` obj is ExtensionMethods '' to raise a warning of some sort , given that ExtensionMethods is a static class . The compiler will issue a warning for the `` is '' operator when object under test can never be of the provided type , ( ( string ) obj ) is System.Uri for example . Am I forgetting a scenario in which this would actually be a meaningful test ? <code> static class ExtensionMethods { } class Program { static void Main ( ) { Test ( `` Test '' ) ; } public static bool Test ( object obj ) { return obj is ExtensionMethods ; } } | C # static classes and the is operator |
C_sharp : There are times when it 's helpful to check a non-repeatable IEnumerable to see whether or not it 's empty . LINQ 's Any does n't work well for this , since it consumes the first element of the sequence , e.g . ( Note : I 'm aware that there 's no need to do the check in this case - it 's just an example ! The real-world example is performing a Zip against a right-hand IEnumerable that can potentially be empty . If it 's empty , I want the result to be the left-hand IEnumerable as-is . ) I 've come up with a potential solution that looks like this : This can then be used as follows : I have two questions about this:1 ) Is this a reasonable thing to do ? Is it likely to be problematic from a performance point of view ? ( I 'd guess not , but worth asking . ) 2 ) Is there a better way of achieving the same end goal ? EDIT # 1 : Here 's an example of a non-repeatable IEnumerable , to clarify : Basically , things which come from user input or a stream , etc.EDIT # 2 : I need to clarify that I 'm looking for a solution that preserves the lazy nature of the IEnumerable - converting it to a list or an array can be an answer in certain circumstances , but is n't what I 'm after here . ( The real-world reason is that the number of items in the IEnumerable may be huge in my case , and it 's important not to store them all in memory at once . ) <code> if ( input.Any ( ) ) { foreach ( int i in input ) { // Will miss the first element for non-repeatable sequences ! } } private static IEnumerable < T > NullifyIfEmptyHelper < T > ( IEnumerator < T > e ) { using ( e ) { do { yield return e.Current ; } while ( e.MoveNext ( ) ) ; } } public static IEnumerable < T > NullifyIfEmpty < T > ( this IEnumerable < T > source ) { IEnumerator < T > e = source.GetEnumerator ( ) ; if ( e.MoveNext ( ) ) { return NullifyIfEmptyHelper ( e ) ; } else { e.Dispose ( ) ; return null ; } } input = input.NullifyIfEmpty ( ) ; if ( input ! = null ) { foreach ( int i in input ) { // Will include the first element . } } private static IEnumerable < int > ReadNumbers ( ) { for ( ; ; ) { int i ; if ( int.TryParse ( Console.ReadLine ( ) , out i ) & & i ! = -1 ) { yield return i ; } else { yield break ; } } } | Safely checking non-repeatable IEnumerables for emptiness |
C_sharp : I store my application settings the C # way ( Properties.Settings.Default.Save ( ) ; ) . The settings are then stored by the C # runtime in the folder : The strange thing is that I entered `` My Company Name '' as the Company-property in Visual Studio ( [ assembly : AssemblyCompany ( `` My Company Name '' ) ] ) .So , where do the underscores come from ? I 've seen other apps creating folders with blanks ... <code> C : \Users\UserName\AppData\Local\My_Company_Name | Why does the .NET runtime add underscores to my string ? |
C_sharp : I need to figure out how to get an element on an enum in an array.Basically , I have a grid of 9x9 buttons . I have two multi-dimensional arrays that houses these values . One houses their names ( if the name is 43 ) it means 5 down , 4 across ( because they start at 0 ) . The name is also the same as the ELEMENT of itself in the array.the names of the buttons are held in playingField.the status of each cell is held in cells ( if it is empty , has a bomb , etc . ) Credit to AbdElRaheim for giving the above . The reason I 'm doing this is so I can get a button name ( exactly the same as the element name ) which will be the same in both arrays.For example : I can do this : ( please excuse my terrible converting . i 'll fix that up later ; ) ) and what the above does is it allows me to see if a cell that you click has a bomb under it.However , what I need to do now , is essentially reverse of this . In the above I know the element name that I want to compare it to , because the element name is the same as the button name . However , now what I need to do is FIND the element name ( button name ) by getting the element of all elements that are Bomb in cells.I 'm not sure how to do this , I tried : but it does n't do anything . I need to find all 'bomb ' in 'cells ' and return the element name . That way I can use that element name , convert it to string , and use my StringToButton method to create a reference to the button.This is the way I 'm currently doing it , for reference , and to help you understand a little better , but take note this is NOT the way I want to continue doing it . I want to do it the way I asked about above : ) Thanks ! <code> string [ , ] playingField = new string [ 9 , 9 ] ; enum CellType { Empty , Flag , Hidden , Bomb } CellType [ , ] cells = new CellType [ 9 , 9 ] ; string dim1 = Convert.ToString ( btn.Name [ 0 ] ) ; string dim2 = Convert.ToString ( btn.Name [ 1 ] ) ; if ( cells [ Convert.ToInt32 ( dim1 ) , Convert.ToInt32 ( dim2 ) ] == CellType.Bomb ) foreach ( CellType Bomb in cells ) { foreach ( string i in minedNodes ) { Button buttonName = StringToButton ( Convert.ToString ( i ) ) ; buttonName.Image = new Bitmap ( dir + `` mine.png '' ) ; } | Getting element of enum in array |
C_sharp : When I run the following code , I get 0 printed on both lines : I would expect to get Double.NaN if an operation result gets out of range . Instead I get 0 . It looks that to be able to detect when this happens I have to check : Before the operation check if any of the operands is zeroAfter the operation , if neither of operands were zero , check if the result is zero . If not let it run . If it is zero , assign Double.NaN to it instead to indicate that it 's not really a zero , it 's just a result that ca n't be represented within this variable.That 's rather unwieldy . Is there a better way ? What Double.NaN is designed for ? I 'm assuming some operations must have return it , surely designers did not put it there just in case ? Is it possible that this is a bug in BCL ? ( I know unlikely , but , that 's why I 'd like to understand how that Double.NaN is supposed to work ) UpdateBy the way , this problem is not specific for double . decimal exposes it all the same : That also gives zero.In my case I need double , because I need the range they provide ( I 'm working on probabilistic calculations ) and I 'm not that worried about precision.What I need though is to be able to detect when my results stop mean anything , that is when calculations drop the value so low , that it can no longer be presented by double.Is there a practical way of detecting this ? <code> Double a = 9.88131291682493E-324 ; Double b = a*0.1D ; Console.WriteLine ( b ) ; Console.WriteLine ( BitConverter.DoubleToInt64Bits ( b ) ) ; Decimal a = 0.0000000000000000000000000001m ; Decimal b = a* 0.1m ; Console.WriteLine ( b ) ; | How do I detect total loss of precision with Doubles ? |
C_sharp : Simple question . What would an equally functioning conversion look like in C # ? VB6 : This was my attempt in C # ( does n't return similar results ) : <code> Dim rec As String * 200If rs ! cJobNum < > `` '' Then Open PathFintest & Mid ( rs ! cJobNum , 2 , 5 ) & `` .dat '' For Random As # 1 Len = 200 s = Val ( Mid ( rs ! cJobNum , 7 , 4 ) ) Get # 1 , Val ( Mid ( rs ! cJobNum , 7 , 4 ) ) + 1 , rec Close # 1 TestRec = rec Fail = FindFailure ( TestRec ) End If FileStream tempFile = File.OpenRead ( tempPath ) ; var tempBuf = new byte [ 200 ] ; var tempOffset = Int32.Parse ( StringHelper.Mid ( rs.Fields [ `` cJobnum '' ] .Value , 7 , 4 ) ) + 1 ; tempFile.Seek ( tempOffset , SeekOrigin.Begin ) ; tempFile.Read ( tempBuf , 0 , 200 ) ; rec.Value = new string ( System.Text.Encoding.Default.GetChars ( tempBuf ) ) ; tempFile.Close ( ) ; TestRec = rec.Value ; Fail = ( string ) FindFailure ( ref TestRec ) ; | What is the C # equivalent of a get statement in VB6 ? |
C_sharp : In Python one can iterate over multiple variables simultaneously like this : Is there a C # analog closer than this ? Edit - Just to clarify , the exact code in question was having to assign a name to each index in the C # example . <code> my_list = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] for a , b , c in my_list : pass List < List < int > > myList = new List < List < int > > { new List < int > { 1 , 2 , 3 } , new List < int > { 4 , 5 , 6 } } ; foreach ( List < int > subitem in myList ) { int a = subitem [ 0 ] ; int b = subitem [ 1 ] ; int c = subitem [ 2 ] ; continue ; } | C # analog of multi-variable iteration in Python ? |
C_sharp : I have a WCF service running under .NET Framework 4.6.2 . I have used the web.config before to configure the service with my custom IAuthorizationPolicy like this : Now I need to swtich to do this in code and this is what that looks like : In the IAuthorizationPolicy i set the principla like this just as before and it does break here : The problem is that when I try to run this : ( UserContextOnService ) Thread.CurrentPrincipal ; In the service method I get exception , the CurrentPrincipal is a WindowPrincipal ? I can get the correct Principal by using this code : But that would mean to change in MANY places where the context is fetched with just Thread.CurrentPrincipal.I suspect that I have lost something in the configuration ? Edit : Have tried to set the Thread.CurrentPrincipal = userContext ; in the Evaluate method but this does not help , the Thread.CurrentPrincipal if still a WindowsPrinciple ? I suspect that the servicemethod is ending up on another thread then the one that executes the Evaluate . <code> < services > behaviorConfiguration= '' MyClientService.CustomValidator_Behavior '' name= '' My.Service.Implementation.Services.MyClientService '' > < endpoint binding= '' netHttpBinding '' behaviorConfiguration= '' protoEndpointBehavior '' address= '' BinaryHttpProto '' bindingNamespace= '' http : //My.ServiceContracts/2007/11 '' contract= '' My.ServiceContracts.IMyClientService '' / > < endpoint binding= '' netHttpsBinding '' behaviorConfiguration= '' protoEndpointBehavior '' address= '' BinaryHttpsProto '' bindingNamespace= '' http : //My.ServiceContracts/2007/11 '' contract= '' My.ServiceContracts.IMyClientService '' / > bindingConfiguration= '' netTcpCertificate '' behaviorConfiguration= '' protoEndpointBehavior '' bindingNamespace= '' http : //My.ServiceContracts/2007/11 '' contract= '' My.ServiceContracts.IMyClientService '' address= '' Sll '' / > < host > < /host > < /service > < /services > < behavior name= '' MyClientService.CustomValidator_Behavior '' > < dataContractSerializer maxItemsInObjectGraph= '' 2147483647 '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < serviceMetadata httpGetEnabled= '' true '' / > < customBehaviorExtension_ClientService / > < serviceThrottling maxConcurrentCalls= '' 2000 '' maxConcurrentSessions= '' 2147483647 '' maxConcurrentInstances= '' 2000 '' / > < serviceCredentials > < clientCertificate > < authentication certificateValidationMode= '' PeerOrChainTrust '' / > < /clientCertificate > < userNameAuthentication userNamePasswordValidationMode= '' Custom '' customUserNamePasswordValidatorType= '' My.Service.Implementation.Security.CustomUsernamePasswordValidator , My.Service.Implementation '' / > < /serviceCredentials > < serviceAuthorization principalPermissionMode= '' Custom '' serviceAuthorizationManagerType= '' My.Service.Implementation.Security.CustomServiceAuthorizationManager , My.Service.Implementation '' > < authorizationPolicies > < add policyType= '' My.Service.Implementation.Security.CustomAuthorizationPolicy_ClientService , My.Service.Implementation '' / > < /authorizationPolicies > < /serviceAuthorization > < /behavior > var endpoint = new System.ServiceModel.Description.ServiceEndpoint ( System.ServiceModel.Description.ContractDescription.GetContract ( typeof ( IMyClientService ) ) , binding , new EndpointAddress ( endPointAddress ) ) ; endpoint.EndpointBehaviors.Add ( new ProtoBuf.ServiceModel.ProtoEndpointBehavior ( ) ) ; serviceHost.AddServiceEndpoint ( endpoint ) ; ServiceAuthorizationBehavior serviceAuthorizationBehavior = serviceHost.Description.Behaviors.Find < ServiceAuthorizationBehavior > ( ) ; if ( serviceAuthorizationBehavior == null ) { serviceAuthorizationBehavior = new ServiceAuthorizationBehavior ( ) ; serviceHost.Description.Behaviors.Add ( serviceAuthorizationBehavior ) ; } serviceAuthorizationBehavior.ExternalAuthorizationPolicies = new ReadOnlyCollection < IAuthorizationPolicy > ( new IAuthorizationPolicy [ ] { new CustomAuthorizationPolicy_ClientService ( ) } ) ; ( ( ServiceBehaviorAttribute ) serviceHost.Description.Behaviors [ typeof ( ServiceBehaviorAttribute ) ] ) .MaxItemsInObjectGraph = 2147483647 ; ( ( ServiceBehaviorAttribute ) serviceHost.Description.Behaviors [ typeof ( ServiceBehaviorAttribute ) ] ) .IncludeExceptionDetailInFaults = true ; ServiceThrottlingBehavior throttleBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = 200 , MaxConcurrentInstances = 2147483647 , MaxConcurrentSessions = 2000 , } ; serviceHost.Description.Behaviors.Add ( throttleBehavior ) ; Console.WriteLine ( `` Starting service ... '' ) ; serviceHost.Open ( ) ; Console.WriteLine ( `` Service started successfully ( `` + uri + `` ) '' ) ; return serviceHost ; } catch ( Exception ex ) var userContext = new UserContextOnService ( new ClientIdentity { AuthenticationType = `` regular '' , IsAuthenticated = true , Name = `` username '' } , currentAnvandare , LoginType.UsernamePassword ) ; userContext.OrbitToken = orbitToken ; evaluationContext.Properties [ `` Principal '' ] = userContext ; SharedContext.Instance.AddUserContext ( person.PersonId.ToString ( ) , userContext ) ; OperationContext.Current.ServiceSecurityContext.AuthorizationContext.Properties [ `` Principal '' ] | Set the Thread.CurrentPrincipal from IAuthorizationPolicy ? |
C_sharp : Just to be clear , a class that inherits DynamicObject ( in C # of course ) is not the same concept as JavaScript 's variables being dynamic . DynamicObject allows the implementer to programmatically determine what members an object has , including methods.Edit : I understand that JavaScript objects can have any members added to them at run time . That 's not at all what I 'm talking about . Here 's a C # example showing what DynamicObject does : When a member of obj is accessed , it uses the TryGetMember to programmatically determine whether the member exists and what its value is . In short , the existence of a member is determined when it 's requested , not by adding it before hand . I hope this clarifies the question a little . In case you 're wondering , I 'm trying to determine if it 's possible to make an object in JavaScript , that when the function call syntax is used on it like so : The uploadSomeData call goes to a `` TryGetMember '' like function , which performs an $ .ajax call using the name `` uploadSomeData '' to generate the URL , and the return value is the result . <code> public class SampleObject : DynamicObject { public override bool TryGetMember ( GetMemberBinder binder , out object result ) { result = binder.Name ; return true ; } } dynamic obj = new SampleObject ( ) ; Console.WriteLine ( obj.SampleProperty ) ; //Prints `` SampleProperty '' . myAPI.uploadSomeData ( data1 , data2 ) | JavaScript equivalent of C # 's DynamicObject ? |
C_sharp : I 'm using Dapper to read data from SQL Server . I have a SQL statement that returns a long Json result but the issue is this result being split into 3 rows with 2033 characters max per row , then Dapper ca n't parse the returned result because it 's invalid Json . How to prevent this splitting or how to make Dapper deal with it ? This is my code : And the code of TypeHandler : And here is how I run this SQL in DataGripEdit : Here is the error message : Newtonsoft.Json.JsonSerializationException : Unexpected end when deserializing object . Path ' [ 0 ] .Balances [ 4 ] .WarehouseId ' , line 1 , position 2033 . <code> SqlMapper.ResetTypeHandlers ( ) ; SqlMapper.AddTypeHandler ( new JsonTypeHandler < List < Product > > ( ) ) ; const string sql = @ '' SELECT * , ( SELECT * FROM Balance b WHERE p.SKU = b.SKU FOR JSON PATH ) AS [ Balances ] FROM Product p WHERE SKU IN @ SKUs FOR JSON PATH '' ; var connection = new SqlConnection ( `` myconnection '' ) ; return connection.QuerySingleAsync < List < Product > > ( sql , new { SKUs = new [ ] { `` foo '' , `` bar '' } } } ) ; public class JsonTypeHandler < T > : SqlMapper.TypeHandler < T > { public override T Parse ( object value ) { return JsonConvert.DeserializeObject < T > ( value.ToString ( ) ) ; } public override void SetValue ( IDbDataParameter parameter , T value ) { parameter.Value = JsonConvert.SerializeObject ( value ) ; } } | How to prevent returned Json being split ? |
C_sharp : I wanted to know what the euqivalent of the Newtonsoft.Json 's / Json.Net 's JsonProperty field in System.Text.Json is.Example : References : Newtonsoft.Json JsonPropertyUsing Newtonsoft.Json attributes <code> using Newtonsoft.Json ; public class Example { [ JsonProperty ( `` test2 '' ) ] public string Test { get ; set ; } } | What is the equivalent of Newtonsoft.Json 's / Json.Net 's JsonProperty field in System.Text.Json ? |
C_sharp : Validating Primitive Arguments and `` Complex Data '' Validating ArgumentsWhen writing a method , arguments should be validated first before any operations are performed . For example , let 's say we 've got a class representing people : What 's wrong with this Person class ? name and age are n't validated before their values are set as fields of Person . What do I mean by `` validated ? '' Both argument should be checked that their values are acceptable . For example , what if name 's value is an empty string ? Or age 's value is -10 ? Validating the arguments is performed by throwing ArgumentExceptions or derived exceptions when the values are unacceptable . For example : This properly validates the arguments Person 's constructor receives . Tedium ad NauseumBecause you 've been validating arguments for a long time ( right ? ) , you 're probably tired of writing these if ( ... . ) throw Argument ... statements in all of your methods . What can we do to avoid writing String.IsNullOrEmpty a bazillion times throughout your code ? <code> public class Person { public readonly string Name ; public readonly int Age ; public class Person ( string name , int age ) { this.Name = name ; this.Age = age ; } } public class Person ( string name , int age ) { if ( String.IsNullOrEmpty ( name ) ) { throw new ArgumentNullException ( `` name '' , `` Can not be null or empty . `` ) ; } if ( age < = 0 || age > 120 ) { throw new ArgumentOutOfRangeException ( `` age '' , `` Must be greater than 0 and less than 120 . `` ) ; } this.Name = name ; this.Age = age ; } | How to avoid argument validation |
C_sharp : I have a C library . It has many function calls like the following : The library itself is dynamically loaded at runtime ( rather like a plugin ) . The headers are consistent across all platforms . My problem is that on windows and 32bit linux , unsigned long is 32bits , yet on 64bit linux this is 64bits.The various implementations of this library all accept this , you need to build your C program for the right target platform ( as expected ) .My interop method will need to be one of these depending on the architecture.The C # types I can use are fixed size on all platforms ( as they should be ) . So my managed long passed from .Net/Mono will always be an unmanaged uint64_t.How can I cope with this variable integer size yet have a single assembly that will run on .Net or mono in either 32bit or 64bit mode ? <code> void init_foo ( unsigned long x , unsigned long y ) ; # if lin64 [ DllImport ( `` libfoo '' ) ] public static void init_foo ( Uint64 x , Uint64 y ) ; # else [ DllImport ( `` libfoo '' ) ] public static void init_foo ( Uint32 x , Uint32 y ) ; # endif | Handling different unmanaged integer sizes |
C_sharp : I just noticed that bitwise operations are n't as `` smart '' as logical `` and\or '' operations and I wonder why ? Here 's an example : However the bitwise operators `` |= '' and `` & = '' are n't as smart : I wondered why they do n't work in the same logical way . <code> // For the recordprivate bool getTrue ( ) { return true ; } private bool getFalse ( ) { return false ; } // Since a is true it wont enter getFalse.bool a = getTrue ( ) || getFalse ( ) ; // Since a is false it wont enter getTrue.bool b = getFalse ( ) & & getTrue ( ) ; // Since b is false it wont enter getTrue.b = b & & getTrue ( ) ; bool a = getTrue ( ) ; a |= getFalse ( ) ; // a has no chance to get false but it still enters the function.a = getFalse ( ) ; a & = getTrue ( ) ; // a has no chance to get true but still performs this operation . | Why are n't bitwise operators as smart as logical `` and\or '' operators |
C_sharp : This is Visual Studio 2008 . Obviously has to do with the static class for an extensions . <code> public class Dummy { public readonly int x ; public Dummy ( int x ) { this.x = x ; } public override string ToString ( ) { return x.ToString ( ) ; } } [ Obsolete ( `` Do Not Use '' , true ) ] public static class Extensions { public static int Squared ( this Dummy Dummy ) { return Dummy.x * Dummy.x ; } } class Program { static void Main ( string [ ] args ) { var d = new Dummy ( 42 ) ; Console.WriteLine ( String.Format ( `` { 0 } ^2= { 1 } '' , d , d.Squared ( ) ) ) ; } } | Why does this code compile without error even though the class is marked Obsoleted ? |
C_sharp : I 'm working in C # with a Borland C API that uses a lot of byte pointers for strings . I 've been faced with the need to pass some C # strings as ( short lived ) byte*.It would be my natural assumption that a const object would not be allocated on the heap , but would be stored directly in program memory , but I 've been unable to verify this in any documentation.Here 's an example of what I 've done in order to generate a pointer to a constant string . This does work as intended in testing , I 'm just not sure if it 's really safe , or it 's only working via luck.Is this const really pinned , or is there a chance it could be moved ? @ Kragen : Here is the import : This is the actual function . Yes , it actually requires a static function pointer : Following is another method that I used when mocking my API , using a static struct , which I also hoped was pinned . I was hoping to find a way to simplify this . <code> private const string pinnedStringGetWeight = `` getWeight '' ; unsafe public static byte* ExampleReturnWeightPtr ( int serial ) { fixed ( byte* pGetWeight = ASCIIEncoding.ASCII.GetBytes ( pinnedStringGetWeight ) ) return pGetWeight ; } [ DllImport ( `` sidekick.dll '' , CallingConvention = CallingConvention.Winapi ) ] public static extern int getValueByFunctionFromObject ( int serial , int function , byte* debugCallString ) ; private const int FUNC_GetWeight = 0x004243D0 ; private const string pinnedStringGetWeight = `` getWeight '' ; unsafe public static int getWeight ( int serial ) { fixed ( byte* pGetWeight = ASCIIEncoding.ASCII.GetBytes ( pinnedStringGetWeight ) ) return Core.getValueByFunctionFromObject ( serial , FUNC_GetWeight , pGetWeight ) ; } public byte* getObjVarString ( int serial , byte* varName ) { string varname = StringPointerUtils.GetAsciiString ( varName ) ; string value = MockObjVarAttachments.GetString ( serial , varname ) ; if ( value == null ) return null ; return bytePtrFactory.MakePointerToTempString ( value ) ; } static UnsafeBytePointerFactoryStruct bytePtrFactory = new UnsafeBytePointerFactoryStruct ( ) ; private unsafe struct UnsafeBytePointerFactoryStruct { fixed byte _InvalidScriptClass [ 255 ] ; fixed byte _ItemNotFound [ 255 ] ; fixed byte _MiscBuffer [ 255 ] ; public byte* InvalidScriptClass { get { fixed ( byte* p = _InvalidScriptClass ) { CopyNullString ( p , `` Failed to get script class '' ) ; return p ; } } } public byte* ItemNotFound { get { fixed ( byte* p = _ItemNotFound ) { CopyNullString ( p , `` Item not found '' ) ; return p ; } } } public byte* MakePointerToTempString ( string text ) { fixed ( byte* p = _ItemNotFound ) { CopyNullString ( p , text ) ; return p ; } } private static void CopyNullString ( byte* ptrDest , string text ) { byte [ ] textBytes = ASCIIEncoding.ASCII.GetBytes ( text ) ; fixed ( byte* p = textBytes ) { int i = 0 ; while ( * ( p + i ) ! = 0 & & i < 254 & & i < textBytes.Length ) { * ( ptrDest + i ) = * ( p + i ) ; i++ ; } * ( ptrDest + i ) = 0 ; } } } | Are constants pinned in C # ? |
C_sharp : C # 6.0 adds this new ? . operator which now allows to invoke events like so : Now , from what I read , this operator guarantees that someEvent is evaluated once.Is it correct to use this kind of invocation instead of the classic pattern : I 'm aware of certain scenarios where above version of pattern would require additional locks , but let 's assume the simplest case . <code> someEvent ? .Invoke ( sender , args ) ; var copy = someEventif ( copy ! = null ) copy ( sender , args ) | Can I use null conditional operator instead of classic event raising pattern ? |
C_sharp : I have a form that prints correctly on my machine but when I deploy the application on another machine , the form does not fit on the page and the desktop background appears on the printed document . The primary differences between the two machines is that one has the DPI setting at 150 % . I have changed auto scaling many times but nothing changes . The form looks ok on screen but just does not print correctly . Below is the code I am using . <code> private void btnPrint_Click ( object sender , EventArgs e ) { CaptureScreen ( ) ; printPreviewDialog1.Document = printDocument1 ; printPreviewDialog1.ShowDialog ( ) ; } Bitmap memoryImage ; private void CaptureScreen ( ) { Graphics myGraphics = this.CreateGraphics ( ) ; Size s = this.Size ; memoryImage = new Bitmap ( s.Width , s.Height , myGraphics ) ; Graphics memoryGraphics = Graphics.FromImage ( memoryImage ) ; memoryGraphics.CopyFromScreen ( this.Location.X , this.Location.Y , 0 , 0 , s ) ; } private void printDocument1_PrintPage ( System.Object sender , System.Drawing.Printing.PrintPageEventArgs e ) { e.Graphics.DrawImage ( memoryImage , 0 , 0 ) ; } | My form is not printing correctly when DPI is 150 % |
C_sharp : I 've a very simple app which contains only UITableView and its UITableViewSource..When using UITableView without linking to UITableViewSource ( the app works in simulator & device ) But when I link the UITableView to the UITableViewSource ( the app works in simulator but crashes on device ) ( The device is iPad running IOS 9.2.1 ) it gives me this long error : All my project contain just 2 views : ) ViewController.cs : and myTableSource.cs : Hope there is a simple solution for this error , because I still in the first step in learning XamarinThanks in advance .. <code> 2016-02-08 05:16:02.913 secondApp [ 4487:1711787 ] critical : Stacktrace:2016-02-08 05:16:02.913 secondApp [ 4487:1711787 ] critical : at < unknown > < 0xffffffff > 2016-02-08 05:16:02.915 secondApp [ 4487:1711787 ] critical : at ( wrapper managed-to-native ) UIKit.UIApplication.UIApplicationMain ( int , string [ ] , intptr , intptr ) < 0xffffffff > 2016-02-08 05:16:02.915 secondApp [ 4487:1711787 ] critical : at UIKit.UIApplication.Main ( string [ ] , intptr , intptr ) [ 0x00005 ] in /Users/builder/data/lanes/2689/962a0506/source/maccore/src/UIKit/UIApplication.cs:772016-02-08 05:16:02.916 secondApp [ 4487:1711787 ] critical : at UIKit.UIApplication.Main ( string [ ] , string , string ) [ 0x0001c ] in /Users/builder/data/lanes/2689/962a0506/source/maccore/src/UIKit/UIApplication.cs:602016-02-08 05:16:02.916 secondApp [ 4487:1711787 ] critical : at secondApp.Application.Main ( string [ ] ) [ 0x00008 ] in /Users/Mujtaba/Desktop/XamarinProjects/secondApp/secondApp/Main.cs:122016-02-08 05:16:02.917 secondApp [ 4487:1711787 ] critical : at ( wrapper runtime-invoke ) object.runtime_invoke_dynamic ( intptr , intptr , intptr , intptr ) < 0xffffffff > 2016-02-08 05:16:02.917 secondApp [ 4487:1711787 ] critical : Native stacktrace:2016-02-08 05:16:02.982 secondApp [ 4487:1711787 ] critical : 0 secondApp 0x0027ffb5 mono_handle_native_sigsegv + 2402016-02-08 05:16:02.982 secondApp [ 4487:1711787 ] critical : 1 secondApp 0x00286243 mono_sigsegv_signal_handler + 2262016-02-08 05:16:02.983 secondApp [ 4487:1711787 ] critical : 2 libsystem_platform.dylib 0x20f3385f _sigtramp + 422016-02-08 05:16:02.983 secondApp [ 4487:1711787 ] critical : 3 secondApp 0x00323310 xamarin_stret_trampoline + 962016-02-08 05:16:02.984 secondApp [ 4487:1711787 ] critical : 4 UIKit 0x25479d29 < redacted > + 29762016-02-08 05:16:02.984 secondApp [ 4487:1711787 ] critical : 5 UIKit 0x2547907b < redacted > + 3782016-02-08 05:16:02.984 secondApp [ 4487:1711787 ] critical : 6 UIKit 0x25478e2d < redacted > + 562016-02-08 05:16:02.985 secondApp [ 4487:1711787 ] critical : 7 UIKit 0x25478c33 < redacted > + 3142016-02-08 05:16:02.985 secondApp [ 4487:1711787 ] critical : 8 UIKit 0x256d4293 < redacted > + 422016-02-08 05:16:02.985 secondApp [ 4487:1711787 ] critical : 9 UIKit 0x2547f295 < redacted > + 1282016-02-08 05:16:02.986 secondApp [ 4487:1711787 ] critical : 10 UIKit 0x25391369 < redacted > + 14802016-02-08 05:16:02.986 secondApp [ 4487:1711787 ] critical : 11 UIKit 0x253b5fd5 < redacted > + 682016-02-08 05:16:02.986 secondApp [ 4487:1711787 ] critical : 12 UIKit 0x253910ab < redacted > + 7782016-02-08 05:16:02.987 secondApp [ 4487:1711787 ] critical : 13 UIKit 0x253907ed < redacted > + 1242016-02-08 05:16:02.987 secondApp [ 4487:1711787 ] critical : 14 UIKit 0x2539069b < redacted > + 4262016-02-08 05:16:02.987 secondApp [ 4487:1711787 ] critical : 15 UIKit 0x2539d713 < redacted > + 16582016-02-08 05:16:02.987 secondApp [ 4487:1711787 ] critical : 16 UIKit 0x2539d08f < redacted > + 302016-02-08 05:16:02.988 secondApp [ 4487:1711787 ] critical : 17 UIKit 0x2539c87d < redacted > + 4962016-02-08 05:16:02.988 secondApp [ 4487:1711787 ] critical : 18 UIKit 0x25399bf3 < redacted > + 2782016-02-08 05:16:02.988 secondApp [ 4487:1711787 ] critical : 19 UIKit 0x2540e915 < redacted > + 482016-02-08 05:16:02.989 secondApp [ 4487:1711787 ] critical : 20 UIKit 0x2563311d < redacted > + 33202016-02-08 05:16:02.989 secondApp [ 4487:1711787 ] critical : 21 UIKit 0x25636f0f < redacted > + 15702016-02-08 05:16:02.989 secondApp [ 4487:1711787 ] critical : 22 UIKit 0x2564ac15 < redacted > + 362016-02-08 05:16:02.989 secondApp [ 4487:1711787 ] critical : 23 UIKit 0x256343f7 < redacted > + 1342016-02-08 05:16:02.990 secondApp [ 4487:1711787 ] critical : 24 FrontBoardServices 0x2250fc75 < redacted > + 2322016-02-08 05:16:02.990 secondApp [ 4487:1711787 ] critical : 25 FrontBoardServices 0x2250ff61 < redacted > + 442016-02-08 05:16:02.990 secondApp [ 4487:1711787 ] critical : 26 CoreFoundation 0x211c1257 < redacted > + 142016-02-08 05:16:02.990 secondApp [ 4487:1711787 ] critical : 27 CoreFoundation 0x211c0e47 < redacted > + 4542016-02-08 05:16:02.990 secondApp [ 4487:1711787 ] critical : 28 CoreFoundation 0x211bf1af < redacted > + 8062016-02-08 05:16:02.991 secondApp [ 4487:1711787 ] critical : 29 CoreFoundation 0x21111bb9 CFRunLoopRunSpecific + 5162016-02-08 05:16:02.991 secondApp [ 4487:1711787 ] critical : 30 CoreFoundation 0x211119ad CFRunLoopRunInMode + 1082016-02-08 05:16:02.991 secondApp [ 4487:1711787 ] critical : 31 UIKit 0x25403a17 < redacted > + 5262016-02-08 05:16:02.991 secondApp [ 4487:1711787 ] critical : 32 UIKit 0x253fdfb5 UIApplicationMain + 1442016-02-08 05:16:02.992 secondApp [ 4487:1711787 ] critical : 33 secondApp 0x000f4044 wrapper_managed_to_native_UIKit_UIApplication_UIApplicationMain_int_string___intptr_intptr + 2722016-02-08 05:16:02.992 secondApp [ 4487:1711787 ] critical : 34 secondApp 0x000bd130 UIKit_UIApplication_Main_string___intptr_intptr + 522016-02-08 05:16:02.992 secondApp [ 4487:1711787 ] critical : 35 secondApp 0x000bd0f0 UIKit_UIApplication_Main_string___string_string + 2042016-02-08 05:16:02.992 secondApp [ 4487:1711787 ] critical : 36 secondApp 0x000b714c secondApp_Application_Main_string__ + 1882016-02-08 05:16:02.992 secondApp [ 4487:1711787 ] critical : 37 secondApp 0x002101b4 wrapper_runtime_invoke_object_runtime_invoke_dynamic_intptr_intptr_intptr_intptr + 2562016-02-08 05:16:02.993 secondApp [ 4487:1711787 ] critical : 38 secondApp 0x0028888f mono_jit_runtime_invoke + 11502016-02-08 05:16:02.993 secondApp [ 4487:1711787 ] critical : 39 secondApp 0x002c71f5 mono_runtime_invoke + 882016-02-08 05:16:02.993 secondApp [ 4487:1711787 ] critical : 40 secondApp 0x002ca64b mono_runtime_exec_main + 2822016-02-08 05:16:02.993 secondApp [ 4487:1711787 ] critical : 41 secondApp 0x00332fa4 xamarin_main + 20722016-02-08 05:16:02.994 secondApp [ 4487:1711787 ] critical : 42 secondApp 0x0025aac5 main + 1122016-02-08 05:16:02.994 secondApp [ 4487:1711787 ] critical : 43 libdyld.dylib 0x20dc4873 < redacted > + 22016-02-08 05:16:02.994 secondApp [ 4487:1711787 ] critical : =================================================================Got a SIGSEGV while executing native code . This usually indicatesa fatal error in the mono runtime or one of the native libraries used by your application.================================================================= using System ; using UIKit ; namespace secondApp { public partial class ViewController : UIViewController { public ViewController ( IntPtr handle ) : base ( handle ) { } public override void ViewDidLoad ( ) { base.ViewDidLoad ( ) ; string [ ] list = new string [ ] { `` Red '' , `` Blue '' , `` Brown '' , `` Green '' } ; UITableView table = new UITableView { Frame = new CoreGraphics.CGRect ( 0 , 0 , View.Bounds.Width , View.Bounds.Height ) , Source = new myTableSource ( list ) // the problem happens when I add this line } ; View.AddSubview ( table ) ; } public override void DidReceiveMemoryWarning ( ) { base.DidReceiveMemoryWarning ( ) ; } } } using System ; using UIKit ; namespace secondApp { public class myTableSource : UITableViewSource { string [ ] TableItems ; string CellIdentifier = `` TableCell '' ; public myTableSource ( string [ ] items ) { TableItems = items ; } public override nint RowsInSection ( UITableView tableview , nint section ) { return TableItems.Length ; } public override UITableViewCell GetCell ( UITableView tableView , Foundation.NSIndexPath indexPath ) { UITableViewCell cell = tableView.DequeueReusableCell ( CellIdentifier ) ; string item = TableItems [ indexPath.Row ] ; if ( cell == null ) { cell = new UITableViewCell ( UITableViewCellStyle.Default , CellIdentifier ) ; } cell.TextLabel.Text = item ; return cell ; } } } | Xamarin.IOS : UITableViewSource crashes on device |
C_sharp : This is my first application that will deal with exceptions properly . It 's a WCF service . All the other before were simple apps just for myself . I have very small knowledge about exception handling in C # .I have a code like this : In this code a few exceptions can happen . Like NullReferenceException for example . How do I know which object caused the exception so I can know what to do in the catch and what to return to the client ? <code> MembershipUser memUser = Membership.GetUser ( username ) ; DatabaseDataContext context = new DatabaseDataContext ( ) ; UserMembership user = UserMembership.getUserMembership ( memUser ) ; ItemsForUser itemUser = Helper.createItemForUser ( ref item , memUser ) ; Helper.setItemCreationInfo ( ref item , user ) ; context.Items.InsertOnSubmit ( item ) ; context.SubmitChanges ( ) ; | How to catch exceptions |
C_sharp : I have no idea what the problem is here . I have a ton of p/invoke calls that are working without incident ... except this one.I 've managed to reduce my problem to the following sample code.If I remove either struct member ( either the double or the int ) it works fine . I 'm assuming the problem is somehow related to the layout of the struct - but when I do a sizeof ( ) in C and a Marshal.SizeOf ( ) in C # , they both return the same value ... so if the struct size is the same in C # and C , what could the problem be ? I 'm obviously missing something basic here.SampleDLLCode.cBuild ScriptC # Code <code> # pragma pack ( 1 ) typedef struct SampleStruct { double structValueOne ; int structValueTwo ; } SampleStruct ; __declspec ( dllexport ) SampleStruct __cdecl SampleMethod ( void ) ; SampleStruct SampleMethod ( void ) { return ( SampleStruct ) { 1 , 2 } ; } gcc -std=c99 -pedantic -O0 -c -o SampleDLLCode.o SampleDLLCode.cgcc -shared -- out-implib -o SampleDLL.dll SampleDLLCode.o using System ; using System.Runtime.InteropServices ; namespace SampleApplication { [ StructLayout ( LayoutKind.Sequential , Pack=1 ) ] public struct SampleStruct { public double structValueOne ; public int structValueTwo ; } class Program { [ DllImport ( `` SampleDLL.dll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern SampleStruct SampleMethod ( ) ; static void Main ( string [ ] args ) { SampleStruct sample = SampleMethod ( ) ; } } } | PInvokeStackImbalance Not Caused By CallingConvention |
C_sharp : Imagine that we have the following methods ( pseudo C # ) : Which one will consume less memory ( and less GC cycles ) if we have many calls to similar like this methods ? Does it make sense to write your own Enumerable/Enumerator in order to implement this kind of Enumerable.Once ( ) scenario ? <code> static IEnumerable < T > Iterator < T > ( ) { switch ( SomeCondition ) { case CaseA : yield return default ( T ) ; case CaseB : yield return default ( T ) ; yield return default ( T ) ; case CaseC : yield return default ( T ) ; default : break ; } } static IEnumerable < T > Array < T > ( ) { switch ( SomeCondition ) { case CaseA : return new [ ] { default ( T ) } ; case CaseB : return new [ ] { default ( T ) , default ( T ) } ; case CaseC : return new [ ] { default ( T ) } ; default : break ; } } | Arrays or Iterators - which has a better performance characteristics ( memory wise ) for calls that return one/two elements |
C_sharp : I had a situation recently where I had an ASP.NET WebAPI controller that needed to perform two web requests to another REST service inside its action method . I had written my code to have functionality separated cleanly into separate methods , which looked a little like this example : Because I was using HttpClient all web requests had to be async . I 've never used async/await before so I started naively adding in the keywords . First I added the async keyword to the PerformWebRequest ( string api ) method but then the caller complained that the PerformWebRequests ( ) method has to be async too in order to use await . So I made that async but now the caller of that method must be async too , and so on.What I want to know is how far down the rabbit hole must everything be marked async to just work ? Surely there would come a point where something has to run synchronously , in which case how is that handled safely ? I 've already read that calling Task.Result is a bad idea because it could cause deadlocks . <code> public class FooController : ApiController { public IHttpActionResult Post ( string value ) { var results = PerformWebRequests ( ) ; // Do something else here ... } private IEnumerable < string > PerformWebRequests ( ) { var result1 = PerformWebRequest ( `` service1/api/foo '' ) ; var result = PerformWebRequest ( `` service2/api/foo '' ) ; return new string [ ] { result1 , result2 } ; } private string PerformWebRequest ( string api ) { using ( HttpClient client = new HttpClient ( ) ) { // Call other web API and return value here ... } } } | How does the async/await return callchain work ? |
C_sharp : Good afternoon , I have a c # jagged array with true and false values ( or 0 's and 1 's ) and I want to reverse the values like : to became : Is there an easy way to do it not looping it ? something like ! myJaggedArray ? ? <code> 1 1 1 10 1 1 01 1 1 11 0 0 1 0 0 0 01 0 0 10 0 0 00 1 1 0 | How to invert the values of a logical jagged array in c # ? |
C_sharp : In my ASP.NET Core 3.1 application , I want to do some settings AT THE END since they are dependent on some other services being registered in the Startup.cs only . Can someone help me to understand why my class implementing the IPostConfigureOptions < T > is never invoked by .NET Core ? I have an Options class like this : This is used in the Startup.cs 's ConfigureServices method as usual.I need to change some settings `` at the end '' . So , I implement IPostConfigureOptions < T > interface . The implementation class looks like this . ( PostConfigure method not shown in the snippet below ) .This is then registered in the Startup.cs 's ConfigureServices method as shown below.I tried to register PostConfig class in different way too.However , in any case the PostConfigure is not called.Am I missing something ? **Why the PostConfigure is never executed ? Is n't it true that all IPostConfigureOptions get executed automatically during startup ? Or is there any case when .NET Core chooses not to run it until it 's actually required ? ** <code> public class MyTestOptions { public string TestTest { get ; set ; } } services.Configure < MyTestOptions > ( o = > { o.TestTest = `` Test Test Test '' ; } ) ; public class MyTestPostConfigure : IPostConfigureOptions < MyTestOptions > services.ConfigureOptions < MyTestPostConfigure > ( ) ; services.AddSingleton < IPostConfigureOptions < MyTestOptions > , MyTestPostConfigure > ( ) ; | ASP.NET Core 3.1 does not call PostConfigure on the class implementing IPostConfigureOptions < T > |
C_sharp : As per the C # specs , is there any guarantee that foo.Bar would have the same effect of being atomic ( i.e . reading foo.Bar from different threads would never see a partially updated struct when written to by different threads ) ? I 've always assumed that it does . If indeed , I would like to know if the specification guarantees it.EDIT : @ vesan This is not the duplicate of Atomic Assignment of Reference Sized Structs . This question asks for the effect of boxing and unboxing whereas the other is about a single reference type in a struct ( no boxing / unboxing involved ) . The only similarities between the two questions are the words struct and atomic ( did you actually read the question at all ? ) .EDIT2 : Here 's the atomic version based on Raymond Chen 's answer : EDIT3 : Revisiting this after 4 years . Turns out that the memory model of CLR2.0+ states that All writes have the effect of volatile write : https : //blogs.msdn.microsoft.com/pedram/2007/12/28/clr-2-0-memory-model/ Thus the answer to this question should have been `` It is atomic if hardware does not reorder writes '' , as opposed to Raymond 's answer . The JIT and the compiler can not reorder writes so the `` atomic version '' based on Raymond 's answer is redundant . On weak memory model architectures , the hardware may reorder writes , so you 'll need to appropriate acquire/release semantics.EDIT4 : Again , this issue comes down to CLR vs CLI ( ECMA ) where the latter defines a very weak memory model while the former implements a strong memory model . There 's no guarantee that a runtime will do this though , so the answer still stands . However , since the vast majority of code was and still is written for CLR , I suspect anyone trying to create a new runtime will take the easier path and implement strong memory model at the detriment of performance ( just my own opinion ) . <code> public class Foo < T > where T : struct { private object bar ; public T Bar { get { return ( T ) bar ; } set { bar = value ; } } } // var foo = new Foo < Baz > ( ) ; public class Atomic < T > where T : struct { private object m_Value = default ( T ) ; public T Value { get { return ( T ) m_Value ; } set { Thread.VolatileWrite ( ref m_Value , value ) ; } } } | Can boxing/unboxing a struct in C # give the same effect of it being atomic ? |
C_sharp : When assigning a default value to a uint parameter in a C # method argument , as shown in the first code block below , I am presented with the message `` A value of type 'int ' can not be used as a default parameter because there are no standard conversions to type 'uint ' '' , whereas when assigning an int to a uint variable in the method body it is fine.The code does compile ; the warning is provided by means of the red , squiggly underlining in Visual Studio 2010 . This is easily resolved by by using 365U in place of 365 , thus : I am finding it really difficult to find a good explanation of why it is invalid to assign an int to the uint in the parameter when it is valid to do so elsewhere . Can anyone help me with the 'light-bulb ' moment I am trying to find ? <code> void GetHistoricData ( uint historyLength = 365 ) { uint i = 365 ; // this is valid } void GetHistoricData ( uint historyLength = 365U ) { // method body } | Why is it invalid to assign an integer value to a uint parameter in a C # method argument ? |
C_sharp : I 'm using Watin library in a windows forms app . In order to hide the browser I use this instruction : However , it does n't hide the popups ( when simulating a click on an element that opens a popup ) .Is there a way to hide them ? <code> Settings.Instance.MakeNewIeInstanceVisible = false ; | Hiding browser popups - Watin |
C_sharp : As you aware , in .NET code-behind style , we already use a lot of function to accommodate those _Click function , _SelectedIndexChanged function etc etc . In our team there are some developer that make a function in the middle of .NET function , for example : and the function listed above is only used once in that function and not used anywhere else in the page , or called from other part of the solution.They said it make the code more tidier by grouping them and extract them into additional sub-function.I can understand if the sub-function is use over and over again in the code , but if it is only use once , then I think it is not really a good idea to extract them into sub-function , as the code getting bigger and bigger , when you look into the page and trying to understand the logic or to debug by skimming through line by line , it will make you confused by jumping from main function to the sub-function then to main function and to sub-function again.I know this kind of grouping by method is better when you writing old ASP or ColdFusion style , but I am not sure if this kind of style is better for .NET or not.Question is : which is better when you developing .NET , is grouping similar logic into a sub-method better ( although they only use once ) , or just put them together inside main function and add //explanation here on the start of the logic is better ? Hope my question is clear enough.Thanks.UPDATE : Thanks all for the answer and input so far.Its just that we have been putting all logic and stuff into 1 function ( we only have 2-3 developers before ) , and suddenly we growing into the team with 7-8 developers , and everyone have their own style.I thinks its better to start building a guidelines , thats why I feel the need to ask the question . <code> public void Button_Click ( object sender , EventArgs e ) { some logic here.. some logic there.. DoSomething ( ) ; DoSomethingThere ( ) ; another logic here.. DoOtherSomething ( ) ; } private void DoSomething ( ) { } private void DoSomethingThere ( ) { } private void DoOtherSomething ( ) { } public void DropDown_SelectedIndexChanged ( ) { } public void OtherButton_Click ( ) { } | Coding style in .NET : whether to refactor into new method or not ? |
C_sharp : Note : The following code actually works okay , but shows the scenario that is failing in my own solution . See the bottom of this post for more information.With these classes : Get fields One and Two : Finally , get their values : In LinqPad or in a simple unit test class with the above code , everything works okay . But in my solution , where I have some unit tests that want to work with all instances of these fields , GetValue works fine to return fields of the parent type , but where the parent fields are supposed have instances of the subtype , they always instead give null ! ( If that happened here , the final list would be { One , null } instead of { One , Two } . ) The test class is in a different project from the two types ( each in their own file ) , but I 've temporarily made everything public . I 've dropped a breakpoint in and have examined all I can examine , and have done the equivalent of fieldInfos [ 1 ] .GetValue ( null ) in a Watch expression and it does in fact return null , despite the fact that there is a line in my main class exactly like the second one from MainType above.What is wrong ? How do I get all the values of the subtype fields ? How is it even possible for them to return null without an error ? On the theory that perhaps for some reason the subtype 's class was not being statically constructed due to the access through reflection , I triedat the top before starting , but it did n't help ( where SubType is the actual subtype class in my project ) .I 'll keep plugging away at trying to reproduce this in a simple case , but I 'm out of ideas for the moment.Additional InformationAfter a bunch of fiddling , the code started working . Now it is not working again . I am working on reproducing what triggered the code to start working.Note : Targeting .Net 4.6.1 using C # 6.0 in Visual Studio 2015.Problem Reproduction AvailableYou can play with a working ( failing ) trimmed-down version of my scenario by downloading this somewhat minimal working example of the problem at github.Debug the unit tests . When the exception occurs , step until you get to line 20 of GlossaryHelper.cs , and can see the return value of GetGlossaryMembers in the Locals tab . You can see that indexes 3 through 12 are null . <code> public class MainType { public static readonly MainType One = new MainType ( ) ; public static readonly MainType Two = SubType.Two ; } public sealed class SubType : MainType { public new static readonly SubType Two = new SubType ( ) ; } List < FieldInfo > fieldInfos = typeof ( MainType ) .GetFields ( BindingFlags.Static | BindingFlags.Public ) .Where ( f = > typeof ( MainType ) .IsAssignableFrom ( f.FieldType ) ) .ToList ( ) ; List < MainType > publicMainTypes = fieldInfos .Select ( f = > ( MainType ) f.GetValue ( null ) ) .ToList ( ) ; System.Runtime.CompilerServices.RuntimeHelpers .RunClassConstructor ( typeof ( SubType ) .TypeHandle ) ; | Reflection GetValue of static field with circular dependency returns null |
C_sharp : Consider the situation in which you want to subscribe to an event for one and only one notification . Once the first notification lands , you unsubscribe from all future events . Would the following pattern present any memory issues ? It works , but I was n't sure if the self-referencing closure could keeps things around in memory longer than desired.Note that you have to declare 'listener ' and assign a value ( null ) . Otherwise the compiler complains about 'Use of unassigned local variable listener ' <code> public class Entity { public event EventHandler NotifyEvent ; } // And then , elsewhere , for a listen-once handler , we might do this : Entity entity = new Entity ( ) ; Action < object , EventArgs > listener = null ; listener = ( sender , args ) = > { // do something interesting // unsubscribe , so we only get 1 event notification entity.NotifyEvent -= new EventHandler ( listener ) ; } ; entity.NotifyEvent += new EventHandler ( listener ) ; | Would the following pattern of unsubscribing your self from an event via closure cause any problems ? |
C_sharp : What determines which name is selected when calling ToString ( ) on an enum value which has multiple corresponding names ? Long explanation of question follows below.I have determined that this not determined uniquely by any of : alphabetical order ; declaration order ; nor , name length.For example , consider that I want to have an enum where the numeric values correspond directly to a practical use , ( e.g . rgb values for color ) . Now , with this enum , calling default ( RgbColor ) will return the rgb value for black . Let 's say I do n't want the default value to be black , because I want UI designers to be able to use a call to `` Default '' when they do n't have specific instructions about what color to use . For now , the Default value for UI designers to use is actually `` Blue '' , but that could change . So , I add an additional TextDefault definition on the enum , and now it looks like : Now , I have tested this and I find that calling RgbColorWithTextDefaultFirst.TextDefault.ToString ( ) and RgbColorWithTextDefaultFirst.Blue.ToString ( ) both yield `` Blue '' . So , I figured that the name that is declared last will overwrite the name of the previous declarations . To test my assumption , I wrote : However , to my surprise , RgbColorWithTextDefaultLast.Blue.ToString ( ) and RgbColorWithTextDefaultLast.TextDefault.ToString ( ) . My next guess is that it sorts the names by alphabetical order and returns the first one . To test this I try : Now , for all four of RgbColorWithATextDefaultFirst.ATextDefault.ToString ( ) , RgbColorWithATextDefaultFirst.Blue.ToString ( ) , RgbColorWithATextDefaultLast.ATextDefault.ToString ( ) , RgbColorWithATextDefaultLast.Blue.ToString ( ) , I end up with `` Blue '' . I realize that there is another distinguishing factor , which is length of the string . My guess is now that the selected name is determined by the length of the name string . So , my test is to use these declarations : Now , guess what value I got for all of : RgbColorWithAFirst.A.ToString ( ) ; RgbColorWithAFirst.Blue.ToString ( ) ; RgbColorWithALast.A.ToString ( ) , RgbColorWithALast.Blue.ToString ( ) . That 's right , `` Blue '' . At this point , I 've given up on trying to figure out what determines this by guessing . I opened up reflector , and I 'm going to take a look and try to figure this out , but I figured I would ask a question here to see if anyone here already knows the answer , which is , again : What determines which name is selected when calling ToString ( ) on an enum value which has multiple corresponding names ? <code> public enum RgbColor { Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff } public enum RgbColorWithTextDefaultFirst { TextDefault = 0x0000ff , Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff } public enum RgbColorWithTextDefaultLast { Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff , TextDefault = 0x0000ff } public enum RgbColorWithATextDefaultFirst { ATextDefault = 0x0000ff , Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff } public enum RgbColorWithATextDefaultLast { Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff , ATextDefault = 0x0000ff } public enum RgbColorWithALast { Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff , A = 0x0000ff } public enum RgbColorWithAFirst { A = 0x0000ff , Black = 0x000000 , Red = 0xff0000 , Green = 0x00ff00 , Blue = 0x0000ff , White = 0xffffff } | What determines which name is selected when calling ToString ( ) on an enum value which has multiple corresponding names ? |
C_sharp : Can Castle Windsor resolve a collection filtered by a string parameter ? My application defines regions as groups of IView-derived types . When I display a particular region at runtime , I want to resolve an instance of every IView type within it ( a la Prism ) .I 've tried doing it with the Castle 's Typed Factory Facility , ComponentModel Construction Contributors , and Handler Selectors , but I ca n't figure out how to map multiple types to a string in a way that Castle can access , nor how to extend Castle to check the string when it decides which types to try to resolve and return in the container . <code> interface IViewFactory { IView [ ] GetAllViewsInRegion ( string regionName ) ; } | How to resolve collection with filtering parameter ? |
C_sharp : I 'm trying to send/receive a string through C # , in C # i just do : but in CCS , if i try sending a string char after char it does not work at all , neither with ReadLine nor with ReadExisting ! This is what i have tried creating an array , so that everytime we enter the RXBUFF pragma , we add the received char to the array , until the array is full ( i randomly defined the array size to be 2 , which means we deal with 2-char-length strings ) , and eventually send the string by sending char after char : in C # : i get non-sense text , like : ? ? A ? ? ? sometimes : ? ? ? ? A ? etc.. , but with : in the first time i press the Send button which sends the `` A6 '' , i get nothing , the second time i get non-sense aswell , just like the ReadExisting behavior.by the way , even if i try to send the string in the easiest way ( without array and conditions ) , i mean like this : i also get inconsistent items in the listbox.However , if i do this : i do get `` A6 '' in the listbox and everything just work fine ( with ReadLine and ReadExisting ) ! could anyone just tell me why this is happening ? <code> SerialPort.WriteLine ( `` A6 '' ) ; # pragma vector = USCI_A1_VECTOR__interrupt void USCI_A1_ISR ( void ) if ( __even_in_range ( UCA1IV,18 ) == 0x02 ) { // Vector 2 - RXIFG if ( counter==0 ) { Data [ 0 ] =UCA1RXBUF ; counter++ ; } else { Data [ 1 ] =UCA1RXBUF ; counter=0 ; UCA1TXBUF=Data [ 0 ] ; while ( ! ( UCA1IFG & UCTXIFG ) ) ; // until UCTXBUF1 is empty UCA1TXBUF=Data [ 1 ] ; } } listBox2.Items.Add ( SerialPort.ReadExisting ( ) ) ; listBox2.Items.Add ( SerialPort.ReadLine ( ) ) ; # pragma vector = USCI_A1_VECTOR__interrupt void USCI_A1_ISR ( void ) UCA1TXBUF= ' A ' ; while ( ! ( UCA1IFG & UCTXIFG ) ) ; // until UCTXBUF1 is empty UCA1TXBUF= ' 6 ' ; # pragma vector = USCI_A1_VECTOR__interrupt void USCI_A1_ISR ( void ) UCA1TXBUF=UCA1RXBUF ; | SerialPort & CCS String Communication |
C_sharp : I am trying to mimic an old vb6 dll with a new .net one . The mimicry has to be perfect so that that callers do n't know they are using a new .dll.I have a curiousness though . In VB6 it has the following in the object library : But AFAIK property this ca n't be done in .net ? The closest I can get is creating a function that exhibits that behaviour but then the COM type goes from Property to Method.Can anyone suggest how I would create that signature with a property ? <code> Property BankList ( Index As Long ) As String | Creating a COM indexed property from C # ? |
C_sharp : A very short C # function.What does `` this '' keyword mean in this function ? What 's the equivalent of this keyword in C++ ? Besides , what is this function trying to calculate exactly ? <code> public static int SizeInBytes ( this byte [ ] a ) { return sizeof ( int ) + a.Length*sizeof ( byte ) ; } | What 's the meaning of `` this '' keyword here ? |
C_sharp : I 'm writing a simple wrapper to `` duck '' a dynamic object against a known interface : This works fine if the dynamic object can respond to the Bar signature . But if it can not this fails only when I call Bar . I would prefer if it could fail faster , i.e. , with argument validation upon construction of the DuckFoo wrapper . Something like this : In Ruby there is a respond_to ? method that can be used to test if an object `` has '' a certain method . Is there a way to test that with dynamic objects in C # 4 ? ( I am aware that even with this check the Bar call could fail later on because the dynamic nature of the duck lets it stop responding to methods later on . ) <code> interface IFoo { string Bar ( int fred ) ; } class DuckFoo : IFoo { private readonly dynamic duck ; public DuckFoo ( dynamic duck ) { this.duck = duck ; } public string Bar ( int fred ) { return duck.Bar ( fred ) ; } } public DuckFoo ( dynamic duck ) { if ( /* duck has no matching Bar method */ ) throw new ArgumentException ( `` duck '' , `` Bad dynamic object '' ) ; this.duck = duck ; } | Is there a C # equivalent to Ruby 's ` respond_to ? ` ? |
C_sharp : I have a console application . I have to remove all the unwanted escape characters from an HTML query string . Here is my query stringI tried the following : None will give me the best results . <code> string query= '' http : //10.1.1.186:8085/PublicEye_common/Jurisdiction/Login.aspx ? ReturnUrl= % 2fPublicEye_common % 2fJurisdiction % 2fprint.html % 3f % 257B % 2522__type % 2522 % 253A % 2522xPad.Reports.ReportDetail % 2522 % 252C % 2522ReportTitle % 2522 % 253A % 25221 % 2522 % 252C % 2522ReportFooter % 2522 % 253A % 25221 % 2522 % 252C % 2522ReportHeader % 2522 % 253A % 25221 % 2522 % 252C % 2522CommonFields % 2522 % 253A % 255B % 255D % 252C % 2522Sections % 2522 % 253A % 255B % 257B % 2522SectionTitle % 2522 % 253A % 2522Sections % 2522 % 252C % 2522ShowTitleSection % 2522 % 253Atrue % 252C % 2522SubSections % 2522 % 253A % 255B % 257B % 2522SubSectionTitle % 2522 % 253A % 2522Sub % 2520Section % 2522 % 252C % 2522ShowTitleSubSection % 2522 % 253Atrue % 252C % 2522FormGroups % 2522 % 253A % 255B % 257B % 2522FormGroupTitle % 2522 % 253A % 2522Form % 2520Groups % 2522 % 252C % 2522ShowTitleFormGroup % 2522 % 253Atrue % 252C % 2522FormFields % 2522 % 253A % 255B % 257B % 2522FormFieldTitle % 2522 % 253A % 2522Form % 2520Fields % 2522 % 252C % 2522FormFieldValue % 2522 % 253A % 252212 % 2522 % 257D % 255D % 257D % 255D % 257D % 255D % 257D % 255D % 257D & % 7B % 22__type % 22 % 3A % 22xPad.Reports.ReportDetail % 22 % 2C % 22ReportTitle % 22 % 3A % 221 % 22 % 2C % 22ReportFooter % 22 % 3A % 221 % 22 % 2C % 22ReportHeader % 22 % 3A % 221 % 22 % 2C % 22CommonFields % 22 % 3A % 5B % 5D % 2C % 22Sections % 22 % 3A % 5B % 7B % 22SectionTitle % 22 % 3A % 22Sections % 22 % 2C % 22ShowTitleSection % 22 % 3Atrue % 2C % 22SubSections % 22 % 3A % 5B % 7B % 22SubSectionTitle % 22 % 3A % 22Sub % 20Section % 22 % 2C % 22ShowTitleSubSection % 22 % 3Atrue % 2C % 22FormGroups % 22 % 3A % 5B % 7B % 22FormGroupTitle % 22 % 3A % 22Form % 20Groups % 22 % 2C % 22ShowTitleFormGroup % 22 % 3Atrue % 2C % 22FormFields % 22 % 3A % 5B % 7B % 22FormFieldTitle % 22 % 3A % 22Form % 20Fields % 22 % 2C % 22FormFieldValue % 22 % 3A % 2212 % 22 % 7D % 5D % 7D % 5D % 7D % 5D % 7D % 5D % 7D '' ; string decode = System.Net.WebUtility.HtmlDecode ( query ) ; string decode2 =System.Net.WebUtility.UrlDecode ( query ) ; string decode3=System.Web.HttpServerUtility.UrlTokenDecode ( query ) .ToString ( ) ; | Html query string removal of unwanted characters |
C_sharp : Is the following use of 'dynamic ' , in the method IsUnixNewline , good or bad ? <code> using System ; class Program { static void Main ( ) { byte [ ] bytes = { 32 , 32 , 32 , 10 } ; string text = `` hello\n '' ; for ( int i = 0 ; i < bytes.Length ; ++i ) { if ( IsUnixNewline ( bytes , i ) ) { Console.WriteLine ( `` Found Unix newline in 'bytes ' . `` ) ; break ; } } for ( int i = 0 ; i < text.Length ; ++i ) { if ( IsUnixNewline ( text , i ) ) { Console.WriteLine ( `` Found Unix newline in 'text ' . `` ) ; break ; } } } static bool IsUnixNewline ( dynamic array , int index ) { return array [ index ] == '\n ' & & ( index == 0 || array [ index - 1 ] ! = '\r ' ) ; } } | Is this an abuse of 'dynamic ' ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.