lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
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 .
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 = int...
Which numeric type conversion is better for simple math operation ?
C#
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 t...
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 priva...
How do you refactor two classes with the same , duplicated events ?
C#
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 g...
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 C...
Regex replacing inside of
C#
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 ...
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#
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 an...
void Method < T > ( T data ) { } void Method < T > ( IEnumerable < T > data ) { }
Generic overloaded method resolution problems
C#
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 o...
var temp = File.ReadAllText ( @ '' C : \\Users\\text.txt '' ) .ToString ( ) ; // no error
Why does a path work even if it contains an @ before `` \\ ''
C#
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...
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 ( ) .MakeArray...
Array types with same element type & rank not equal
C#
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...
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.ThrowExceptio...
Render 3D scene on locked system
C#
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 typ...
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 > ( ) ; ( ( INotif...
How can you explicitly cast a variable of type 'object ' to satisfy a multi-typed generic constraint ?
C#
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 th...
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 ( ) ;...
How to preserve/rebind event listeners on MapFragment after rotating the device ( portrait / landscape ) ?
C#
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 .
Texture2D t1 ; t1 = content.Load < Texture2D > ( `` some texture '' ) ; Texture2D t2 ; t2 = t1 ;
( Texture2D ) t1 = t2 ; Does it creates reference or a copy ?
C#
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 u...
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 her...
Why did my async with ContinueWith deadlock ?
C#
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
[ 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#
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 , bec...
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...
c # enum covariance does n't work
C#
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...
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#
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 ...
< 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 ; } ...
Get DataTemplate from data object in ListBox
C#
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.Th...
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#
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 .
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#
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
public bool HasRedProduct = > Products.Any ( _= > _.IsRed == true ) ; public bool HasRedProduct = > Products.Any ( x= > x.IsRed == true ) ;
Discards inside C # Linq queries
C#
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 occ...
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 ) {...
How to deal with allocations in constrained execution regions ?
C#
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 : )
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 =...
Stringbuilder in CIL ( MSIL )
C#
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 :
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 > ( ...
Why are Func < > delegates so much slower
C#
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 gu...
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#
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 ....
< 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 < /TargetFr...
Auto-generate main method from referenced assembly
C#
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 ...
public int X ( ) = > x ;
How to set the .NET Version for VisualStudio2015 ( Code )
C#
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 ?
`` ( 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 == '...
How to check parentheses validation
C#
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 I...
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.CompilerGeneratedAtt...
Why the compiler adds an extra parameter for delegates when there is no closure ?
C#
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 re...
< 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 '' > < ...
WPF StackPanel PNG Capture not rendering correctly
C#
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 ...
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#
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 oth...
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#
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 prob...
public abstract class Uniform < T > public class UniformMatrix4 : Uniform < Matrix4 >
Design pattern for allowing functions to accept generic types
C#
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 t...
[ 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....
Ignore constructor exceptions with MEF without Visual Studio breaking at the exception
C#
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...
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_...
Why does C # compiler emit additional OpCodes in IL ?
C#
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 ?
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 ( `...
Call generic method in c #
C#
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 thre...
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#
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 ?
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...
How to programmatically click an ApplicationBarIconButton ?
C#
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 ex...
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#
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 dat...
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#
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 t...
[ Serializable ] public class MethodConnectionTracking : OnExceptionAspect { public override void OnException ( MethodExecutionArgs args ) { base.OnException ( args ) ; } } [ assembly : MethodConnectionTracking ]
postsharp exception is null
C#
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 wit...
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.BaseDirecto...
.NET - How to upload videos to YouTube using OAuth2.0 and Offline Access from a Windows Service
C#
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 webs...
public class ClaimsTransformer : IClaimsTransformation { private readonly IAuthorizationService _authorizationService ; public ClaimsTransformer ( IAuthorizationService authorizationService ) { _authorizationService = authorizationService ; } public Task < ClaimsPrincipal > TransformAsync ( ClaimsPrincipal principal ) ...
Windows Authentication - require additional password for special users
C#
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 aggregati...
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 = > sel...
Passing ravendb query as Func < T , bool > does not work
C#
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 samp...
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 i...
Why a generic type definition implemented interfaces lose type information ?
C#
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 ...
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#
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...
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....
Why is my DeflateStream not receiving data correctly over TCP ?
C#
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.M...
//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 ( )...
How to mock GetConnectionString ( ) from IConfiguration using moq ?
C#
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 gi...
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 )...
Have I implemented Y-combinator using C # dynamic , and if I have n't , what is it ?
C#
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...
< ? 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 shou...
Unable to return user favorites via Tableau REST API
C#
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 ( 'V...
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#
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 .
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 = _transacti...
Writing many variables into textfile
C#
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 ge...
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 enumerate...
Writing an IEnumerator with performance comparable to array foreach
C#
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 b...
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#
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 ?
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#
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...
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#
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
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#
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 ( l...
public void MainFunction ( ) { try { SomeProblemFunction ( ) ; } catch { AllFineFunction ( ) ; } } private void SomeProblemFunction ( ) { ... } private void AllFineFunction ( ) { ... }
position of the try catch statement
C#
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 `` Descripti...
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 Someth...
Opinion requested : for static values , is it better to use Enums or Entities ?
C#
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 )...
[ 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.Empt...
Why contract is malformed when using default ( Type ) ?
C#
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 ...
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 combinatedV...
How to convert an IEnumerable < IEnumerable < T > > to a IEnumerable < T >
C#
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 comple...
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 [ ...
why in this simple test the speed of method relates to the order of triggering ?
C#
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 >...
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#
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 ExtensionMetho...
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#
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-wor...
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 > Nullify...
Safely checking non-repeatable IEnumerables for emptiness
C#
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 , w...
C : \Users\UserName\AppData\Local\My_Company_Name
Why does the .NET runtime add underscores to my string ?
C#
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 it...
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 ) ] == ...
Getting element of enum in array
C#
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 o...
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#
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 ) :
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 tempFi...
What is the C # equivalent of a get statement in VB6 ?
C#
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 .
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 ] ; ...
C # analog of multi-variable iteration in Python ?
C#
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 ...
< services > behaviorConfiguration= '' MyClientService.CustomValidator_Behavior '' name= '' My.Service.Implementation.Services.MyClientService '' > < endpoint binding= '' netHttpBinding '' behaviorConfiguration= '' protoEndpointBehavior '' address= '' BinaryHttpProto '' bindingNamespace= '' http : //My.ServiceContracts...
Set the Thread.CurrentPrincipal from IAuthorizationPolicy ?
C#
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 member...
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#
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 de...
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 ( `` myc...
How to prevent returned Json being split ?
C#
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
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#
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...
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 o...
How to avoid argument validation
C#
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 im...
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#
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 .
// 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 & & ...
Why are n't bitwise operators as smart as logical `` and\or '' operators
C#
This is Visual Studio 2008 . Obviously has to do with the static class for an extensions .
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 {...
Why does this code compile without error even though the class is marked Obsoleted ?
C#
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 b...
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 ) ] ...
Are constants pinned in C # ?
C#
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 add...
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#
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 ...
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...
My form is not printing correctly when DPI is 150 %
C#
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 runnin...
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 [ ] , i...
Xamarin.IOS : UITableViewSource crashes on device
C#
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 ....
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.I...
How to catch exceptions
C#
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...
# 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....
PInvokeStackImbalance Not Caused By CallingConvention
C#
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 ?
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 ) { ...
Arrays or Iterators - which has a better performance characteristics ( memory wise ) for calls that return one/two elements
C#
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 al...
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 ( `` se...
How does the async/await return callchain work ?
C#
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 ? ?
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#
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 th...
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 < IPostC...
ASP.NET Core 3.1 does not call PostConfigure on the class implementing IPostConfigureOptions < T >
C#
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 specificati...
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.Volatil...
Can boxing/unboxing a struct in C # give the same effect of it being atomic ?
C#
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 v...
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#
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 ?
Settings.Instance.MakeNewIeInstanceVisible = false ;
Hiding browser popups - Watin
C#
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 fun...
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_Selecte...
Coding style in .NET : whether to refactor into new method or not ?
C#
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 . ...
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.Stati...
Reflection GetValue of static field with circular dependency returns null
C#
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 arou...
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...
Would the following pattern of unsubscribing your self from an event via closure cause any problems ?
C#
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 w...
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 { Bla...
What determines which name is selected when calling ToString ( ) on an enum value which has multiple corresponding names ?
C#
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 Fac...
interface IViewFactory { IView [ ] GetAllViewsInRegion ( string regionName ) ; }
How to resolve collection with filtering parameter ?
C#
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 th...
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 & U...
SerialPort & CCS String Communication
C#
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 functi...
Property BankList ( Index As Long ) As String
Creating a COM indexed property from C # ?
C#
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 ?
public static int SizeInBytes ( this byte [ ] a ) { return sizeof ( int ) + a.Length*sizeof ( byte ) ; }
What 's the meaning of `` this '' keyword here ?
C#
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 ...
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 ArgumentExce...
Is there a C # equivalent to Ruby 's ` respond_to ? ` ?
C#
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 .
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...
Html query string removal of unwanted characters
C#
Is the following use of 'dynamic ' , in the method IsUnixNewline , good or bad ?
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 ; ++...
Is this an abuse of 'dynamic ' ?