lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
My ultimate aim is to convert the below code in python to C # , but I 'd like to do it my self by learning the python syntax . I understand that the code is recursive.The code produces polynomials of degree n with k variables . More specifically the list of exponents for each variable.Here is the conversion I have so f...
def multichoose ( n , k ) : if k < 0 or n < 0 : return `` Error '' if not k : return [ [ 0 ] *n ] if not n : return [ ] if n == 1 : return [ [ k ] ] return [ [ 0 ] +val for val in multichoose ( n-1 , k ) ] + \ [ [ val [ 0 ] +1 ] +val [ 1 : ] for val in multichoose ( n , k-1 ) ] public double [ ] MultiChoose ( int n , i...
Python to C # Code Explanation
C#
I 'm developing a WPF C # application and I have a strange behaviour in modification of objects . I try to explain it in general way.Suppose that you have an object of a class described as follows : where B is : I pass an instance of A class and an instance of B class from a window to another , only defining two variab...
public class A { int one ; bool two ; List < B > listofBObjects ; } public class B { int three ; int four ; } SecondWindow newWindow = new SecondWindow ( ) ; newWindow.instanceOfA = this.instanceOfA ; //instanceOfA is of type AnewWindow.instanceOfB = this.instanceOfA.listOfBObjects [ 0 ] ; //instanceOfB is of type Bnew...
c # objects modification : a strange behaviour
C#
For instance , something like : At this point , I do n't know enough about C # lambdas and multi-type generic containers to be able to put this together correctly . Is this even possible ?
Dictionary < string , Func < T1 , T2 , bool > > comparisons ; comparisons.add ( `` < `` , ( x , y ) = > x < y ) ; comparisons.add ( `` == '' , ( x , y ) = > x == y ) ; comparisons.add ( `` > '' , ( x , y ) = > x > y ) ;
Possible to create a single multi-type collection of multi-type lambda functions in C # 4.0 ?
C#
This is a followup question to this : List < T > .Contains and T [ ] .Contains behaving differentlyT [ ] .Contains is behaving differently when T is class and struct . Suppose I have this struct : Here , generic Equals is rightly called as I expected . But in case of a class : The non generic Equals is called , taking ...
public struct Animal : IEquatable < Animal > { public string Name { get ; set ; } public bool Equals ( Animal other ) // < - he is the man { return Name == other.Name ; } public override bool Equals ( object obj ) { return Equals ( ( Animal ) obj ) ; } public override int GetHashCode ( ) { return Name == null ? 0 : Nam...
T [ ] .Contains for struct and class behaving differently
C#
Let 's assume I want to deserialize this ( I 've removed the namespaces to make things simpler ) : TextField inherits from FormField , so in my class definition of FormField looks something like this : TextField class looks like this : I tried deserializing using this : I get a SerializationException : `` Expecting ele...
< TextField > < Caption > Location < /Caption > < Name > Location < /Name > < /TextField > [ KnownType ( typeof ( TextField ) ) ] [ DataContract ( Name = `` FormField '' ] public abstract class FormField { [ DataMember ] public string Name { get ; set ; } } [ DataContract ( Name = `` TextField '' ) ] public class TextF...
How can I deserialize an XML , when I only know the type of an ancestor class ?
C#
I recently upgraded one of my projects from .NET Core 2.0 to .NET Core 2.1 . After doing so several of my tests started to fail.After narrowing this down I 've found that in .NET Core 2.1 it is not possible to compute the hash code of a string using a culture aware comparer with the string sort compare option.I 've cre...
[ TestMethod ] public void Can_compute_hash_code_using_invariant_string_sort_comparer ( ) { var compareInfo = CultureInfo.InvariantCulture.CompareInfo ; var stringComparer = compareInfo.GetStringComparer ( CompareOptions.StringSort ) ; stringComparer.GetHashCode ( `` test '' ) ; // should not throw ! }
Hash code of string is broken in .NET Core 2.1 , but works in 2.0
C#
I 'm specifically calling attention to null-propagation as it pertains to bool ? and the use of a bool returning method . For example , consider the following : This does n't compile , and the following error exists : Can not implicitly convert bool ? to bool . An explicit conversion exists ( are you missing a cast ) ?...
public static bool IsAttributedWith < TAttribute > ( this JsonProperty property ) where TAttribute : Attribute { return property ? .AttributeProvider .GetAttributes ( typeof ( TAttribute ) , false ) .Any ( ) ; } public static bool IsAttributedWith < TAttribute > ( this JsonProperty property ) where TAttribute : Attribu...
Why is null propagation inconsistently propagating Nullable < T > ?
C#
I 've been experimenting with queries in LinqPad . We have a table Lot with a column Side char ( 1 ) . When I write a linq to sql query Lots.Where ( l = > l.Side == ' A ' ) , it produces the following SQLHowever , using Lots.Where ( l = > l.Side.Equals ( ' A ' ) ) , it producesIt would appear upon ( albeit naïve ) insp...
-- Region ParametersDECLARE @ p0 Int = 65 -- EndRegionSELECT ... , [ t0 ] . [ Side ] , ... FROM [ Lot ] AS [ t0 ] WHERE UNICODE ( [ t0 ] . [ Side ] ) = @ p0 -- Region ParametersDECLARE @ p0 Char ( 1 ) = ' A ' -- EndRegionSELECT ... , [ t0 ] . [ Side ] , ... FROM [ Lot ] AS [ t0 ] WHERE [ t0 ] . [ Side ] = @ p0 static v...
Different SQL produced from Where ( l = > l.Side == ' A ' ) vs Where ( l = > l.Side.Equals ( ' A ' )
C#
The output I got for this is `` In derived OBJECT '' . What is the reason for this strange behaviour ? After some research , I found out the reason is the signatures declared in the base class are ignored . Why are they ignored ?
class Base { public virtual void MethodA ( int x ) { Console.WriteLine ( `` In Base Class '' ) ; } } class Derived : Base { public override void MethodA ( int x ) { Console.WriteLine ( `` In derived INT ) '' ) ; } public void MethodA ( object o ) { Console.WriteLine ( `` In derived OBJECT '' ) ; } } class Test { static...
Why are signatures declared in the base class ignored ?
C#
fMethod is an Action < Fruit > . But when fMethod is called , the parameter is always the last entry of _Fruits.How to solve this ?
foreach ( Fruit f in _Fruits ) { field.Add ( new Element ( f.ToString ( ) , delegate { fMethod ( f ) ; } ) ) ; }
C # Action in Foreach
C#
I 'm trying to create a very simple page for my slackbot so that users can login and register . However , even when using their generated `` Login with Slack '' button I receive an error `` The oauth state was missing or invalid. '' . The same error happens with `` Add to Slack '' .I based my code off of https : //dotn...
services.AddAuthentication ( options = > options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme ) .AddCookie ( options = > { options.Cookie.Name = `` MyAuthCookieName '' ; options.Cookie.HttpOnly = true ; options.Cookie.SecurePolicy = CookieSecurePolicy.Always ; options.Cookie.MaxAge = TimeSpan...
Add to Slack in dotnetcore without having Identity Framework error : The oauth state was missing or invalid
C#
Most of the time when we use MVVM we use the INotifyPropertyChanged interface to provide the notification to the bindings , and the general implementation looks like this : This works fine for me whenever I read the code from the experts - they wrote similar code : I would like to know what is the exact reason behind c...
public class MyClass : INotifyPropertyChanged { // properties implementation with RaisePropertyChanged public event PropertyChangedEventHandler PropertyChanged ; protected void RaisePropertyChanged ( string propertyName ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( proper...
Why we should use temprary object to raise event ?
C#
i got this SQL -query that i want converted to Linq.this is the contect : im making a asp.net api that needs to return values from 3 different tablesI left out all the foreignkeys and primary . This is just for the clarification of what i want . My problem is now that i have a function that needs to return information ...
CREATE TABLE Locatie ( locatieId INT IDENTITY ( 1,1 ) not null , postcode VARCHAR ( 10 ) not null , huisnummer INT not null , adres VARCHAR ( 50 ) not null , plaats VARCHAR ( 50 ) not null , CREATE TABLE Vereniging ( verenigingId INT IDENTITY ( 1,1 ) not null , locatieId INT not null , naam VARCHAR ( 50 ) not null , fa...
double inner join in linq/ lambda query ?
C#
Given the following class : From the implicit cast of Func < MyType > to MyType , I assumed the following would be possible : However I 'm getting : Can not convert method group 'MyTypeWrapper ' to non-delegate type 'Test.MyType ' . Did you intend to invoke the method ? Which , unfortunately for me , when searched for ...
public class MyType { public static implicit operator MyType ( Func < MyType > wrapper ) { return wrapper ( ) ; } } public MyType MyTypeWrapper ( ) { return new MyType ( ) ; } public void MyTestMethod ( ) { MyType m = MyTypeWrapper ; // not a call ! } MyType m = ( MyType ) MyTypeWrapper ;
Implicit cast of Func < MyType > to MyType
C#
I am required to create separate windows service accounts for eachenvironment ( dev , acceptance , and production ) that my desktopapplication uses to connect to one of our internal databases.A global group has been added to these accounts to provide access thereby requiring access by windows authentication using imper...
Console.WriteLine ( Environment.UserName ) ; //This shows me ! So no impersonation yet ! using ( new Impersonator ( `` AppUser '' , `` mydomain '' , `` notapassword '' ) ) { Console.WriteLine ( Environment.UserName ) ; //This shows as AppUSER ! So it works ! using ( BillMarkContext dbContext = new BillMarkContext ( ) )...
EF Code First Connection String during Runtime with Impersonated Windows Service Account
C#
Is the following request automatically `` optimized '' ? This is equivalent toWhich one of these statements is the more optimized of the two ? Or are they identical ?
var result = initial .Where ( Predicate1 ) .Where ( Predicate2 ) .Where ( Predicate3 ) ; var result = initial .Where ( e = > Predicate1 ( e ) & & Predicate2 ( e ) & & Predicate3 ( e ) ) ;
Most optimized use of multiple Where statements
C#
I stumbled across this odd case yesterday , where t as D returns a non-null value , but ( D ) t causes a compiler error.Since I was in a hurry I just used t as D and carried on , but I am curious about why the cast is invalid , as t really is a D. Can anyone shed some light on why the compiler does n't like the cast ? ...
class Program { public class B < T > where T : B < T > { } public class D : B < D > { public void M ( ) { Console.Out.WriteLine ( `` D.M called . `` ) ; } } static void Main ( ) { M ( new D ( ) ) ; } public static void M < T > ( T t ) where T : B < T > { // Works as expected : prints `` D.M called . '' var d = t as D ;...
Why is this cast invalid when ` x as Y ` works fine ?
C#
If a class implements a method defined in an interface you can choose whether you duplicate the documentation or reference it with < see cref= '' ... '' / > .Is it possible to let the API documentation tool ( Sandcastle ) copy the documentation automatically ( what would make reading the API documentation more comforta...
public interface IPerformer { /// < summary > /// Do something useful . /// < /summary > /// < param name= '' something '' > Object to do something with < /param > void Do ( Something something ) ; } public class Implementation : IPerformer { /// < copy from= '' IPerformer '' / > # that is what I want ! public void Do ...
How to copy .NET API documentation ?
C#
I thought I understood the async-wait pattern and the Task.Run operation.But I am wondering why in the following code example the await does not sync back to the UI thread after returning from the finished task.This code runs within a .NET Framework WPF application on a Windows 10 system with attached Visual Studio 201...
public async Task InitializeAsync ( ) { Console.WriteLine ( $ '' Thread : { Thread.CurrentThread.ManagedThreadId } '' ) ; // `` Thread : 1 '' double value = await Task.Run ( ( ) = > { Console.WriteLine ( $ '' Thread : { Thread.CurrentThread.ManagedThreadId } '' ) ; // Thread : 6 // Do some CPU expensive stuff double x ...
Why does n't await Task.Run ( ) sync back to UI Thread / origin context ?
C#
Let 's say I need an extension method which selects only required properties from different sources . The source could be the database or in-memory collection . So I have defined such extension method : This works fine for IQueryables . But , I have to call this function also for IEnumerables.And in that case , I can c...
public IQueryable < TResult > SelectDynamic < TResult > ( this IQueryable < T > source , ... ) myEnumerable.AsQueryable ( ) .SelectDynamic ( ... ) .ToList ( ) ;
In which cases do I need to create two different extension methods for IEnumerable and IQueryable ?
C#
I am developing a drawing application in which one can draw various types of lines . On the line corner points I have placed a thumb using an itemsControl . The thumbs should move that corner point when the user left mouse clicks on it and drags the mouse . What 's happening now is that when I do this the point and thu...
< ItemsControl x : Name= '' PART_LineRelocate '' ItemsSource= '' { Binding pointsObservableCollection } '' Visibility= '' Collapsed '' > < ItemsControl.ItemTemplate > < DataTemplate DataType= '' { x : Type s : LineCornerPoint } '' > < Grid > < c : PointRelocateThumb VerticalAlignment= '' Center '' HorizontalAlignment= ...
Thumbs on line corner points do not relocate points
C#
In a Visual Studio extension I 've built I need to highlight method invocations within the Visual Studio editor . For example : I would like to use HSV colors to divide up the color spectrum according to to the number of unique invocations.I can achieve the highlighting if I export each color as its own EditorFormatDef...
[ Export ( typeof ( EditorFormatDefinition ) ) ] [ ClassificationType ( ClassificationTypeNames = `` red-background '' ) ] [ Name ( `` red-background '' ) ] [ UserVisible ( true ) ] [ Order ( After = Priority.High ) ] public sealed class RedBackground : ClassificationFormatDefinition { public RedBackground ( ) { Displa...
Export custom EditorFormatDefinition at runtime
C#
Im preparing for a very tricky c # exam and this question popped up while doing so.I have the following code : -12u is recognized as System.Uint32 literal but it can only be stored in variable of type long . Why is that ?
uint zzz = -12u ;
C # int32 literal can only be stored in long data type
C#
I have the following interface declarations : I have two concrete classes , like so : Lastly , I have a static service method for saving to the database : My problem is , how do I pass a distro of either concrete type to my static method ? The following does n't compile : The error is : The best overloaded method match...
interface IOrder < T > where T : IOrderItem { IList < T > Items { get ; set ; } } interface IDistro < T > : IOrder < T > where T : IOrderItem { } // DistroItem implements IOrderItempublic class Distro : IDistro < DistroItem > { public IList < DistroItem > Items { get ; set ; } } // PerishableOrderItem implements IOrder...
How do I pass two similar concrete objects to a method with interface parameters that implement generics in C # ?
C#
I 'm looking over Joe Albahari 's C # 5.0 in A Nutshell and in Chapter 26 regarding regular expressions , he states : In some of the proceeding examples , we called a static RegEx method repeatedly with the same pattern . An alternative approach in these cases is to instantiate a Regex object with the pattern and then ...
// Code example from the bookRegex r = new Regex ( @ '' sausages ? `` ) ; Console.WriteLine ( r.Match ( `` sausage '' ) ) ; // sausageConsole.WriteLine ( r.Match ( `` sausages '' ) ) ; // sausages class Program { static void Main ( string [ ] args ) { var str = `` 01/02/03/04/05/06/07/08/09/10 '' ; var regex = new Rege...
Compiled regex performance not as expected ?
C#
I made a Bot using Microsoft bot framework and made use of Luis for matching intents . Some of the intents directs it to QNA and and some other intents directs it to graph api . My Question is what is the best approach for identifying whether it should go to qna for searching the related intents in qna or whether it sh...
[ Serializable ] public class RootDialog : DispatchDialog { //this intent directs to graph api dialog [ LuisIntent ( DialogMatches.GraphApiIntent ) ] public async Task RunGraphapiIntent ( IDialogContext context , IActivity activity ) { UserMessage = ( activity as IMessageActivity ) .Text ; await context.Forward ( new G...
C # Microsoft Bot Framework with luis result directing to QNA Maker and graph api
C#
I have a ListView in virtual mode , and the underlying data is being stored in a List < MyRowObject > . Each column of the ListView corresponds to a public string property of MyRowObject . The columns of my ListView are configurable during runtime , such that any of them can be disabled and they can be reordered . To r...
class MyRowObject { public string [ ] GetItems ( List < PropertyInfo > properties ) { string [ ] arr = new string [ properties.Count ] ; foreach ( PropertyInfo property in properties ) { arr [ i ] = ( string ) property.GetValue ( this , null ) ; } return arr ; } } private void listView_RetrieveVirtualItem ( object send...
Is there a nice way to avoid using reflection to populate my virtual ListView ?
C#
After reading a blog post mentioning how it seems wrong to expose a public getter just to facilitate testing , I could n't find any concrete examples of better practices.Suppose we have this simple example : Let 's say for object-oriented design reasons , I have no need to publicly expose the list of products . How the...
public class ProductNameList { private IList < string > _products ; public void AddProductName ( string productName ) { _products.Add ( productName ) ; } }
How can I avoid adding getters to facilitate unit testing ?
C#
I have a Project table with two columns -- ProjectId and ProjectName -- and am writing a function that constructs and executes a SqlCommand to query the database for the ids of a Project with a given name . This command works , but is vulnerable to SQL Injection : attributeParam , tableParam , idParam , and idValue are...
string sqlCommand = String.Format ( `` SELECT { 0 } FROM { 1 } WHERE { 2 } = { 3 } '' , attributeParam , tableParam , idParam , surroundWithSingleQuotes ( idValue ) ) ; SqlCommand command = new SqlCommand ( sqlCommand , sqlDbConnection ) ; using ( SqlDataAdapter adapter = new SqlDataAdapter ( command ) ) { DataTable at...
Why does String.Format work but SqlCommand.Parameters.Add not ?
C#
I write WCF code and hosted in my WPF app.I write class to switch my MainWindow to show other page in my projectand I write my wcf service like this : I want change page remotely from another computer with WCF but it not work and I trace code the wcf is run and response but do not do anything how can access to main thr...
public static class Switcher { public static MainWindow pageSwitcher ; public static void Switch ( Page newPage ) { pageSwitcher.Navigate ( newPage ) ; } } [ ServiceContract ] public interface IAppManager { [ OperationContract ] void DoWork ( ) ; [ OperationContract ] void Page1 ( ) ; [ OperationContract ] void Page2 (...
WCF hosted in WPF and how can i change control in MainWindow UI from wcf ?
C#
This is the code example in my C # project.I have a python script which imports the .dll with this code example and I want to create this settings.SpecificValue variable within the python script.Is it somehow possible without making a function in C # which I can call within python code.In python I want to call it like ...
var settings = new SettingsClass ( ) ; settings.SpecificValue = new List < SpecificValueClass > ( ) ; public class SettingsClass { public bool Timesync { get ; set ; } public string SystemName { get ; set ; } public string Timezone { get ; set ; } public List < SpecificValueClass > SpecificValue { get ; set ; } } publi...
Create a generic List from C # dll in python script
C#
if I want to get executable locationwhat is the different between this command : is there any different ? is its pointed to different location ?
Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ) .Location ) ; Directory.GetCurrentDirectory ( ) ; System.Environment.CurrentDirectory ;
different between executable location
C#
I have a question regarding the following method calls : Here 's IL for these two calls : I 've always thought in this situation , the generic version of this method was more `` syntactic sugar '' vs. true improvement . Is the IL telling a different story ?
var ctl1 = this.FindControlRecursively ( `` SomeField '' ) as HiddenField ; var ctl = this.FindControlRecursively < HiddenField > ( `` SomeField '' ) ; IL_0010 : ldstr `` AsyncReset '' IL_0015 : call class [ System.Web ] System.Web.UI.Control [ Amc.WebG081.MethodExtensions ] Amc.WebG081.ControlExtensions : :FindControl...
Generic syntactic sugar or true improvement
C#
I have an IObservable < IObservable < T > > where each inner IObservable < T > is a stream of values followed by an eventual OnCompleted event.I would like to transform this into an IObservable < IEnumerable < T > > , a stream consisting of the latest value from any inner stream that is not completed . It should produc...
input -- -. -- -- . -- -. -- -- -- -- -- -- -- -- | | '-f -- -- -g-| | 'd -- -- -- e -- -- -- -- -| ' a -- b -- -- c -- -- -| result -- -a -- b-b -- c-c-c-e-e-e -- - [ ] - d d d e f g f f
`` Merging '' a stream of streams to produce a stream of the latest values of each
C#
I 'm not intrigued by the BadImageFormatException that is thrown when I declare a variable of a Visual C++ type that is defined inside a referenced Visual C++ assembly as much as I am intrigued by the fact that the exception is not caught by the catch clause of the try-catch statement immediately surrounding the variab...
public static void method ( ) { try { Some_Visual_Cpp_Type o ; } catch ( Exception ) { Console.WriteLine ( `` caught inside the method '' ) ; //apparently not called } } public static void Main ( ) { try { method ( ) ; } catch ( BadImageFormatException ) { Console.WriteLine ( `` caught outside the method '' ) ; //print...
In .NET , why ca n't a BadImageFormatException be caught inside the method that throws it ?
C#
I found this code below in a file called Filter.cs in a project created with Microsoft App Studio . Although I am a veteran C # programmer , I 'm short on experience with LINQ predicate expression builders . I can tell that the code below it is `` meta-logic '' for flexibly building a query given a list of filter predi...
query = query.Where ( expression ) .AsQueryable ( ) '' public class Filter < T > { public static ObservableCollection < T > FilterCollection ( FilterSpecification filter , IEnumerable < T > data ) { IQueryable < T > query = data.AsQueryable ( ) ; foreach ( var predicate in filter.Predicates ) { Func < T , bool > expres...
Why multiple filters are applied even if query recreated on each iteration
C#
I Think I am currently experiencing a bug in Entity Framework 6 and possibly ADO.NET . Since there is a deadline I am not sure I can wait for this bug to be fixed and hopefully someone can help me with a clean work around.The problem is that the query uses the values 1 and 5 in places where it should be 0.01 and 0.05 ....
declare @ p3 dbo.someUDTinsert into @ p3 values ( NULL,5 ) insert into @ p3 values ( 5,0.10 ) insert into @ p3 values ( NULL,1 ) insert into @ p3 values ( 1,2 ) exec sp_executesql N'Select * from @ AName ' , N ' @ AName [ dbo ] . [ someUDT ] READONLY ' , @ AName= @ p3 declare @ p3 dbo.someUDTinsert into @ p3 values ( N...
User defined table in Entity Framework generating incorrect query
C#
Besides it 's not BP ( catching-routing ) - but this is the best isolation I can get.But I get nice waves telling me `` danger , danger - might be uninitialized '' .How comes ? Edit : Please do not suggest `` Simply put a string foo = string.Empty ; at the 'declaration ' '' . I 'd like to declare it , but just do the a...
string foo ; try { foo = `` test '' ; // yeah , i know ... } catch // yeah , i know this one too : ) { foo = null ; } finally { Console.WriteLine ( foo ) ; // argh ... @ # ! } Console.WriteLine ( foo ) ; // but nothing to complain about here
Why is my variable still `` uninitialized '' ?
C#
I 'm trying to port the C++ code to C # and for the most part it is working , however only for the first 3 round of the loop . On the fourth round , the bytes for the input block begin to differ and I do n't understand why . If we assume the C++ version is the correct implementation , why is the C # code giving a diffe...
BigInteger AESResult = new BigInteger ( t ) ; // ConsoleApplication2.cpp : main project file. # include `` stdafx.h '' using namespace System ; using namespace System : :Security : :Cryptography ; void unpack ( unsigned int a , unsigned char *b ) { /* unpack bytes from a word */ b [ 0 ] = unsigned char ( a ) ; b [ 1 ] ...
Why are my bytes different on the fourth round of this C # port of an encryption algorithm ?
C#
I am creating a new namespace and the most apt name for one of the class seems to be the same name as the namespace . Is this a good practice ? If not , what is the alternative ? For example : Related questions discussing the same issue : Should a class have the same name as the namespace ? How to avoid having the same...
com.person| -- - Person . ( java/cs ) | -- - PersonDetailChecker . ( java/cs ) | -- - PersonNameGenerator . ( java/cs )
Is it a good practice to have a package/namespace and class within with the same name ?
C#
After scratching my head for the better part of the day , I stumbled upon a very weird issue with .NET code that is compiled using .NET Native ( used for Windows UWP apps ) .The following code works fine in any .NET runtime environment , including Mono , Xamarin , etc . : On Windows UWP with .NET Native compilation , t...
public class ABC { } // ... var constr = typeof ( ABC ) .GetTypeInfo ( ) .DeclaredConstructors.First ( ) ; var abc = ( ABC ) constr ? .Invoke ( new object [ 0 ] ) ; // abc now contains an instance of ABC public class ABC { } // ... var constr = typeof ( ABC ) .GetTypeInfo ( ) .DeclaredConstructors.First ( ) ; var abc1 ...
.NET Native code crashes on constructor ? .Invoke ( ) ( null-propagation )
C#
I 'm reading .NET4 sources ( they can be downloaded for research freely ) and I found something strange in the implementation of System.Web.Security.FormsAuthenticationModule.The class is declared like this : where IHttpModule has two methods - Init ( ) and Dispose ( ) .Inside OnEnter ( ) there 're these lines : where ...
public sealed class FormsAuthenticationModule : IHttpModule // Step 2 : Call OnAuthenticate virtual method to create // an IPrincipal for this requestOnAuthenticate ( new FormsAuthenticationEventArgs ( context ) ) ; // OnAuthenticate : Forms Authentication modules can override // this method to create a Forms IPrincipa...
How is this code in FormsAuthenticationModule supposed to work ?
C#
Using protobuf-net v2 build 668 , I ’ m trying to serialize/deserialize a class which contains a member defined as an interface while doing on-the-fly conversions at the same time.Normally , the surrogate approach would work just fine but since C # doesn ’ t allow user-defined conversions for interfaces , I can ’ t def...
namespace ProtoBufNetTest { using System.Diagnostics ; using System.IO ; using ProtoBuf ; using ProtoBuf.Meta ; class Program { static void Main ( ) { RuntimeTypeModel.Default.Add ( typeof ( IDummy ) , false ) .SetSurrogate ( typeof ( DummySurrogate ) ) ; var container = new Container { Data = new Dummy { Positive = 3 ...
Is there a way to define alternative conversion functions ( from/to interfaces ) in a protobuf-net surrogate class
C#
I have one doubt concerning c # method overloading and call resolution.Let 's suppose I have the following C # code : Note that I know how to make it work but I would like to know why for one value of int ( 0 ) it calls one method and for another ( 1 ) it calls another . It sounds awkward since both values have the sam...
enum MyEnum { Value1 , Value2 } public void test ( ) { method ( 0 ) ; // this calls method ( MyEnum ) method ( 1 ) ; // this calls method ( object ) } public void method ( object o ) { } public void method ( MyEnum e ) { }
Why are C # calls different for overloaded methods for different values of the same type ?
C#
Greetings everybody . I am sorry , if this was already asked before ( searched in vain ) or is really very simple , but i just ca n't get it . The MSDN definition of a Nullable type , states , that it is defined in a following manner : So the question is quite straightforward : How is this definition possible ? Or this...
[ SerializableAttribute ] public struct Nullable < T > where T : struct , new ( )
Confusion about Nullable < T > constraints
C#
I have a problem with an anonymous method within a loop . The following code is just to illustrate my problem : And when I click into the button , the output is : Victor Wooten Victor Wooten Victor Wooten Victor Wooteninstead of : Jaco Pastorius Marcus Miller Flea Vicor WootenThe main point of my problem is the differe...
private void Form1_Load ( object sender , EventArgs e ) { List < string > bassists = new List < string > ( ) { `` Jaco Pastorius '' , `` Marcus Miller '' , `` Flea '' , `` Vicor Wooten '' } ; foreach ( string item in bassists ) { this.button1.Click += ( s , ea ) = > Output ( s , ea , item ) ; } } private void Output ( ...
Problem with different `` execution context '' of an anonymous method within a loop
C#
Do simple lambda expressions get inlined ? I have a tendency ( thanks to F # and other functional forays ) to encapsulate repeated code present within a single function into a lambda , and call it instead . I 'm curious if I 'm incurring a run-time overhead as a result : vsWhich one costs more to run ?
var foo = a + b ; var bar = a + b ; Func < T1 , T2 > op = ( ) = > a + b ; var foo = op ( ) ; var bar = op ( ) ;
Do lambdas get inlined ?
C#
I 'm reading a C # book for beginners , and in every end of the chapter , there are exercises to be answered based on the lessons tackled.One of those exercises goes this way : ( not the exact wordings ) Write a program that will accept an int as the array length , and the values for the array.Then will print : '' 0 ''...
// SortedInput : 1 , 2 , 3 , 5Print : 1// Not sortedInput : 2 , 1 , 3 , 6Print : 0// Sorted , but with duplicatesInput : 2 , 2 , 3 , 7Print : 2 int arrayLength = 0 ; int prev , next ; int sortStatus = 1 ; Console.Write ( `` Input array Length : `` ) ; arrayLength = Convert.ToInt32 ( Console.ReadLine ( ) ) ; int [ ] ar ...
Is it possible to express this code in LINQ ?
C#
When deleting records that are in a many to many relationship , the relationship table has orphan records . I have the following many to many relationship set up in my DbContext.My Owner model has virtual property Cars : My Car model has virtual property Owners : I delete a Car as follows ( db is my DbContext , car is ...
protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < Car > ( ) .HasMany ( u = > u.Owners ) .WithMany ( l = > l.Cars ) .Map ( ul = > { ul.MapLeftKey ( `` CarId '' ) ; ul.MapRightKey ( `` OwnerId '' ) ; ul.ToTable ( `` CarOwners '' ) ; } ) ; } public virtual ICollection < Car > ...
Deleting Entity in Many to Many Relationship Leaves Orphans in Relationship Table
C#
When querying an XmlDocument I need to pass a namespace manager over with each call . Annoying really but it 's just something we live with . The really annoying bit is creating the namespace manager in the first place.To create it I need to not only seed the instance with the nametable but then specify every single na...
XmlNamespaceManager nsMan = new XmlNamespaceManager ( invoiceTextReader.NameTable ) ; nsMan.AddNamespace ( `` '' , `` urn : oasis : names : specification : ubl : schema : xsd : Invoice-2 '' ) ; nsMan.AddNamespace ( `` pb '' , `` urn : pierbridge : names : specification : pbl : schema : xsd : tpn-1 '' ) ; ...
Why do I need to specify a Namespace manager for Xpath querys
C#
I am looking into using post sharp and I am trying to put together a few demos . One of them was an aspect that will log exceptions , and another was to check for null arguments and throw an exception when one is encountered . The problem I am having is that I want my exception logging aspect to log the exceptions thro...
[ Serializable ] public class NullCheckAttribute : OnMethodBoundaryAspect { [ ExceptionLogger ] public override void OnEntry ( MethodExecutionArgs args ) { foreach ( var argument in args.Arguments ) { if ( argument == null ) throw new InvalidOperationException ( `` Null argument in `` + args.Method.Name ) ; } } } [ Ser...
Applying aspects to aspects with postsharp
C#
I 'm learning how Dapper is working behind the scenes.However I saw this pattern of disposing which is not understood to me.Roughly in general — this is how QueryAsync is implemented : I can understand why he did n't use using over the connection , that 's because he wanted to conditionally close the connection via the...
/*1*/ public async Task < IEnumerable < T > > QueryAsync < T > ( string sql , Func < IDataRecord , T > projector , DbConnection _conn , dynamic param = null ) /*2*/ { /*3*/ /*4*/ DbDataReader reader = null ; /*5*/ bool wasClosed = _conn.State == ConnectionState.Closed ; /*6*/ try/*7*/ { /*8*/ /*9*/ using ( var cmd = _c...
Dapper 's nested ` using ` clause - Clarification ?
C#
I 've been asked to maintain some not-as-legacy-as-I-would-like code , and it is riddled with compiler directives , making it pretty much unreadable and almost as maintainable . Case in point : using directives are even prettier : I thought I 'd give the ConditionalAttribute a go but that wo n't quite work in this situ...
# if CONDITION_1 protected override void BeforeAdd ( LogEntity entity ) # else protected override void BeforeAdd ( AbstractBusinessEntity entity ) # endif { # if CONDITON_1 entity.DateTimeInsert = DateTime.Now ; # else ( ( LogEntity ) entity ) .DateTimeInsert = DateTime.Now ; # endif base.BeforeAdd ( entity ) ; } # if ...
Getting rid of precompiler directives in C #
C#
I seem to be having a very weird problem and I really have no idea what 's going on . This is the source code I 'm trying to debug The weird thing is that the list is shown only if I put Output.ItemsSource = showslist ; inside of the foreach loop but not when it 's outside and I really do n't understand why it 's not ....
StorageFile file = await roamingFolder.GetFileAsync ( filename ) ; string text = await FileIO.ReadTextAsync ( file ) ; string [ ] shows = text.Split ( new [ ] { `` : ? ; '' } , StringSplitOptions.None ) ; List < show > showslist = new List < show > ( ) ; foreach ( string splitshow in shows ) { string [ ] show1 = splits...
List and foreach
C#
I 'm writing some F # code and I 'd like to use an enum value defined in a c # assembly.For instance , in the c # assembly I 've got this codeHow do I call MyEnum.valueA in F # ? When I just write that , the compiler shouts : Invalid use of a type name and/or object constructor . If necessary use 'new ' and apply the c...
public enum MyEnum { valueA , valueB , valueC }
How to call the values of a C # enum in F #
C#
From many examples of compiling a Roslyn SyntaxTree , I have seen code such as : But when I try to do this in the current Roslyn released with Visual Studio 2015 RC , I see no Emit ( ) which takes a module . I need to write to a stream and load it into a regular AppDomain-locked Assembly.I then see this answer from Tom...
[ ... create tree and compilation ... ] var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly ( new AssemblyName ( `` foo '' ) , AssemblyBuilderAccess.RunAndCollect ) ; var module = assembly.DefineDynamicModule ( `` foo '' ) ; var result = compilation.Emit ( module ) ;
Emit to DynamicAssembly with Roslyn RC
C#
I have a simple service manager called ServiceManager that has two methods . Create ( ) creates an instance of a service . Provide ( ) returns a service that has previously been created.I have a basic implementation that works but am wondering if there 's a cleaner way . This is my basic implementation of the ServiceMa...
public class ServiceManager : MonoBehaviour { private Dictionary < Type , MonoBehaviour > services = new Dictionary < Type , MonoBehaviour > ( ) ; public void Create < T > ( ) where T : MonoBehaviour { // Create service GameObject serviceObject = new GameObject ( typeof ( T ) .Name ) ; serviceObject.transform.SetParent...
Get instance from a dictionary of types and instances
C#
Where Sessions is a Dictionary < Guid , WebSession > , and NewSession is new WebSession ( ) I have this line : Now at this point you 're probably rolling your eyeballs and thinking `` well either Sessions is null , or NewSession.SessionID is null . '' However : It 's pretty intermittent . Happens maybe one time in 50 ....
Sessions.Add ( NewSession.SessionID , NewSession ) ; Sessions == nullfalseNewSession.SessionID == nullfalseNewSession == nullfalse
NullReferenceException adding to a dictionary - very certain that nothing is null
C#
I have often the case where I want to return an Enumerable < T > from a method or a property . To build the returning Enumerable < T > , I use a List < T > -instance . After filling the list , I return the list.I always thought that this is enough . But it exists the possibility that the caller casts the resulting Enum...
IEnumerable < string > GetAList ( ) { List < string > aList = new List < string > ( ) ; aList.Add ( `` a '' ) ; aList.Add ( `` b '' ) ; return aList ; } IEnumerable < string > GetAList ( ) { List < string > aList = new List < string > ( ) ; aList.Add ( `` a '' ) ; aList.Add ( `` b '' ) ; return aList.ToArray < string >...
Is it a mistake to return a list if the return type is an enumerable
C#
There is my model classI want to test MyCollection getter returns an actual read-only collection . That is clients of the class can neither add nor remove elements to/from it at all . What 's the correct way to write such test ? Option 1It 's returns true e.g when field of the MyCollection property is an instance of Li...
public class Model { public ICollection < string > MyCollection { get ; } } Assert.That ( modelInstance.MyCollection is IReadonlyCollection < string > ) ; var testDelegate = ( ) = > modelInstance.MyCollection.Add ( `` QWERTY '' ) ; Assert.That ( testDelegate , Throws.TypeOf < NotSupportedException > ( ) ) ;
Correct way of checking if a ICollection is actually read-only
C#
I 'm using dependency injection pattern for my application without any IoC Container . Now I decided to use some IoC Container because my Composition Root consists of thousands lines of code , but I failed to make it work with my classes , which actively use variance . For example the following interfaceand servicePure...
public interface IQuery < in TIn , out TOut > { IReadOnlyCollection < TOut > Get ( TIn key ) ; } public class FakeRepository : IQuery < object , string > { public IReadOnlyCollection < string > Get ( object key ) { return new [ ] { key.ToString ( ) } ; } } IQuery < string , object > service = new FakeRepository ( ) ; s...
Covariant service resolution by IoC container
C#
In this section of a function ( .NET 2.0 ) : The compiler shows the error `` Can not convert type 'T ' to 'int'.So , I used Convert.ToInt32 ( ) which worked - but does it box input to an object ? Is there a better solution ? ThanksEdit1 : Taken off unnecessary stuff related to the question Edit2 : Taking a deeper look ...
public void AttachInput < T > ( T input ) where T : struct { if ( input is int ) { Inputs.Add ( ( int ) input ) ; } }
Casting between value types on a class using generics
C#
I 'm looking to implement a few nicer ways to use List in a couple of apps I 'm working on . My current implementation looks like this . MyPage.aspx.csBLL Class ( s ) Now while this is working all well and good , I 'm just wondering if there is any way to improve it , and just make it cleaner that having to use the two...
protected void Page_Load ( object sender , EventArgs e ) { BLL.PostCollection oPost = new BLL.PostCollection ( ) ; oPost.OpenRecent ( ) ; rptPosts.DataSource = oArt ; rptPosts.DataBind ( ) ; } public class Post { public int PostId { get ; set ; } public string PostTitle { get ; set ; } public string PostContent { get ;...
What is a better , cleaner way of using List < T >
C#
I have an abstract `` Action '' class , which has derived types of ActionAppointment , ActionCall , ActionEmail , and ActionLetter . I 'm trying to write a function that will DRY up our service layer , so we 're not writing CRUD calls 5 times anymore.I have in our service layer some update logic ( lots of other code re...
private IServiceResponse UpdateAction < T > ( T action , string originalActionStatus ) where T : Action { if ( action.GetType ( ) == typeof ( Action ) ) { _actionRepository.Update ( action ) ; } else if ( action.GetType ( ) == typeof ( ActionAppointment ) ) { _actionAppointmentRepository.Update ( action as ActionAppoin...
C # Pattern for abstract class specific code
C#
I 've uploaded a log of a WinDBG session that I 'll refer to : https : //pastebin.com/TvYD9500So , I 'm debugging a hang that has been reported by a customer . The reproducer is a small C # program : We sell a framework to build ODBC drivers with , and the customer is testing an ODBC driver built with the framework . O...
using System ; using System.Data.Odbc ; using System.Threading ; namespace ConnectionPoolingTest { class Program { static void Main ( string [ ] args ) { String connString = `` DSN=DotNetUltraLightDSII '' ; using ( OdbcConnection connnection = new OdbcConnection ( connString ) ) { connnection.Open ( ) ; connnection.Clo...
Debugging a CLR hang
C#
I am reviewing an example code in a book and came across the following code ( simplified ) .In the code , when Subscribe ( T subscriber ) is called , the thread enters into a lock section.and then , when code inside the lock calls AddToSubscribers ( T subscriber ) method , the method has another lock . why is this seco...
public abstract class SubscriptionManager < T > where T : class { private static List < T > subscribers ; private static void AddToSubscribers ( T subscriber ) { lock ( typeof ( SubscriptionManager < T > ) ) { if ( subscribers.Contains ( subscriber ) ) return ; subscribers.Add ( subscriber ) ; } } public void Subscribe...
rationale behind lock inside lock ?
C#
I often end up writing classes like this : When you have lots of properties and types then you quickly end up with a lot of boiler plate code . Ideally in this situation I would just create an IAnimal interface and reference that . I 'm currently in a situation where the Dog and Cat classes exist in a third party assem...
public class Animal { public string Colour { get ; set ; } public int Weight { get ; set ; } public Animal ( Dog data ) { this.Colour = data.Colour ; this.Weight = data.Weight ; } public Animal ( Cat data ) { this.Colour = data.Colour ; this.Weight = data.Weight ; } } public class Animal { public string Colour { get ; ...
Reducing constructor boiler plate code
C#
My Question is about a Fluent , which i merged with my program.exe in one merged.exe with this code : My problem is that the Fluent Ribbon Control cant find any style , but i settled it with them code in my app.xamlThe second problem that i have with this solution is that i cant connect to my database ( SQL Express ) w...
public class Program { [ STAThreadAttribute ] public static void Main ( ) { AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly ; App.Main ( ) ; } private static Assembly OnResolveAssembly ( object sender , ResolveEventArgs args ) { //We dont ' care about System Assemblies and so on ... //if ( ! args.Name.ToLo...
Problems after merging Fluent into main.exe
C#
How to apply multiple operands to a single operator ? An example : instead ofI can have the following or similar :
if ( foo == `` dog '' || foo == `` cat '' || foo == `` human '' ) if ( foo == ( `` dog '' || `` cat '' || `` human '' ) ) ;
How to apply multiple operands to a single operator ?
C#
Like most software , users are able to specify how they 'd like to handle certain things . In my case , users can specify what kind of formatting they would prefer . There are 3 options , leave unformatted , camel case or proper case . I currently have it working but it feels very clunky and repetitive . Here is a jist...
public static class Extensions { public static string GetPreferenceFormattedText ( this string text , ApplicationPreferences applicationPreferences , bool pluralize ) { if ( applicationPreferences.FieldNamingConvention.Equals ( FieldNamingConvention.SameAsDatabase ) ) return text ; string formattedText = text.Replace (...
How do you handle user preferences ?
C#
I was looking at this question : How to implement multiplication without using multiplication operator in .NET and actually had a lot of fun trying to think of ways to multiply without using *.But I was left scratching my head at this answer . I have no idea what is going on in this code . Can someone explain it to me ...
using System ; using System.Runtime.InteropServices ; delegate uint BinaryOp ( uint a , uint b ) ; static class Program { [ DllImport ( `` kernel32.dll '' , SetLastError = true ) ] static extern bool VirtualProtect ( IntPtr address , IntPtr size , uint protect , out uint oldProtect ) ; static void Main ( ) { var bytes ...
Can Someone Explain This Code To Me ?
C#
I have this line of code that I 'm using to prepare some CSS file : The problem is that in CSS , I have this declaration : How do I change the .Replace statement to replace white with # FFF but to leave white-space alone ? Thanks.Note , I know I can add TheMinifiedCSS = TheMinifiedCSS.Replace ( `` # FFF-space '' , `` w...
TheMinifiedCSS = TheMinifiedCSS.Replace ( `` white '' , `` # FFF '' ) ; .SomeClass { white-space : pre-wrap ; }
string replace with exception on certain strings
C#
I have the following codeThe first Messagebox shows nothing The Second Messagebox shows something If the counter value is 0 then both messagebox shows same result but if counter is greater than 0 then the problem occurs . I think the problem is with new string ( ptr , counter ) initilization . But I want to know the in...
char ptr=new char ( ) ; int counter = 1 ; string s = new System.String ( ptr , counter ) ; // does not show something MessageBox.Show ( s+ '' Something '' ) ; //shows something MessageBox.Show ( `` Something '' + s ) ;
Why string is functioning differently
C#
I am writing a program about job interview . Everything is working properly , except one thing . When I use an outside method TotalLines ( where I have seperate StreamReader ) , it is working properly , but when I am calculating a number of totalLines in the program , I am receiving one question mark on the beginning o...
PotentialEmployee potentialEmployee = new PotentialEmployee ( ) ; using ( StreamReader InterviewQuestions = new StreamReader ( text , Encoding.Unicode ) ) { int totalLines = 0 ; while ( InterviewQuestions.ReadLine ( ) ! = null ) { totalLines++ ; } InterviewQuestions.DiscardBufferedData ( ) ; InterviewQuestions.BaseStre...
Strange question mark , when setting StreamReader to beginning
C#
In C # I have following methods defined in given class ( non static ) : I want to create wrapping lambda / Action / Delegate / MethodInfo ( all are accepted by script engine ) that automatically passes ScriptEngine and this from given , predefined variables.So far I 've experimenting with : But when called on MyMethod2...
int MyMethod ( ScriptEngine script , int a , int b ) { return a + b ; } void MyMethod2 ( ScriptEngine script , string c ) { // do something with c } // With overloads up to 16 template parametersAction < T1 > Wrap < T1 > ( Action < ScriptEngine , T1 > func , ScriptEngine script ) { return ( Action < T1 > ) ( ( t1 ) = >...
C # Create lambda over given method that injects first paramater
C#
Background : I am still a C # novice and this is my first big project with inheritance . The following story is a simplified example of my current situation : Suppose I have a class called LivingOrganism . Every living creature can use this class as base and inherit the functionality that is common to all living organi...
//Valid and makes sense.foreach ( LivingOrganism foo in cityOfNeyYork ) { /*embedded statement*/ }
Making abstract classes invisible ; or : hiding my BananaHuman
C#
The above code would make the compiler crash on build.I would expect the compiler to stop with a meaningful error-message , instead of trying to compile the code.Could it be a bug in the compiler ? If not , how can I solve this error ?
var xrr = __arglist ( Convert.ToUInt32 ( 1 ) , Convert.ToUInt32 ( 2 ) , Convert.ToUInt32 ( 3 ) ) ;
C # compiler crashes without an error-message
C#
I have a launch dialog button which creates a view model of a window and bind it to the the window ( it is having UI virutalization enabled ) . It takes only 1 second to launch the dialog at first click . But if I open the same dialog very frequently or back to back , it starts taking more time in populating the grid d...
for first time populating the item source it take only 1 second : next time populating the item source it takes 2 secondnext time populating the item source it takes 3 secondnext time populating the item source it takes 6 secondnext time populating the item source it takes 8 second Gc.Collect ( ) Gc.WaitForPendingFinal...
Performance concern while opening a dialog repetitively in wpf
C#
I 'm having trouble understanding why the C # compiler can infer types forbut not forwhen it would seem that the former would be a more complicated deduction than the latter.Could someone please explain why this happens ?
Array.ConvertAll ( new int [ 1 ] , i = > Convert.ToDouble ( i ) ) ; Array.ConvertAll ( new int [ 1 ] , Convert.ToDouble ) ;
C # generics -- why do lambdas work , when simple methods do n't ?
C#
I was attempting to compare three different ways of passing a delegate to a function in C # -- by lambda , by delegate , and by direct reference . What really surprised me was the direct reference method ( i.e . ComputeStringFunctionViaFunc ( object [ i ] .ToString ) ) was six times slower than the other methods . Does...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Runtime.CompilerServices ; namespace FunctionInvocationTest { class Program { static void Main ( string [ ] args ) { object [ ] objectArray = new object [ 10000000 ] ; for ( int i = 0 ; i < objectArray.Length ; ++i ) ...
Why is there such a large difference in the performance of different ways to pass delegates ?
C#
If I have this : the clr throws an IOException because I have n't close the cout.In fact If I do this : I have no exception.But If I do this and then exit from the application : without closing cin the file can from the OS opened and written . However reading the source code of StreamReader.cs I did n't ' find a destru...
StreamWriter cout = new StreamWriter ( `` test.txt '' ) ; cout.WriteLine ( `` XXX '' ) ; // here IOException ... StreamReader cin = new StreamReader ( `` test.txt '' ) ; string text = cin.ReadLine ( ) ; StreamWriter cout = new StreamWriter ( `` test.txt '' ) ; cout.WriteLine ( `` XXX '' ) ; cout.Close ( ) ; StreamReade...
Finalization on StreamWriter and StreamReader
C#
( Slightly simplified scenario to highlight the specific issue ) .I 'm trying to use Castle Windsor to resolve a component , which has a constructor with a single parameter which is an array of a service interface : The Windsor container is configured to use the ArrayResolver : This all works fine , and one or more ser...
public class TestClass < T > { public TestClass ( IService < T > [ ] services ) { ... } } container.Kernel.Resolver.AddSubResolver ( new ArrayResolver ( container.Kernel ) ) ; container.Register ( Classes.FromAssembly ( Assembly.GetExecutingAssembly ( ) ) .BasedOn < IService < > > ( ) .WithService.FirstInterface ( ) ) ...
Castle Windsor resolve zero or more implementations
C#
This is something that I 've always wrestled with in my code . Suppose we have the following code : Which way is more correct - method A or B ? I am always torn about this . Method A seems like it would be minutely faster , due to the fact that it does n't have to go access a property before getting the real variable ....
public class MyClass { private string _myVariable ; public string MyVariable { get { return _myVariable ; } set { _myVariable = value ; } } public void MyMethod ( ) { string usingPrivateMember = _myVariable ; // method A string usingPublicProperty = MyVariable ; // method B } }
When inside a class , is it better to call its private members or its public properties ?
C#
Trying to manage access to a web site I created some necessary entities The goal is use a custom permission attribute for some controller 's action method of my MVC application . For this operation I have two enumsNow I want the method below to check permissionsIt works good but is it safe to use reflection here ? Is i...
[ Permissions ( PermissionType.SomePermissionName , CrudType.CanDelete ) ] public ActionResult SomeAction ( ) { } [ Flags ] public enum CrudType { CanCreate = 0x1 , CanRead = 0x2 , CanUpdate = 0x4 , CanDelete = 0x8 , } [ Flags ] public enum PermissionType { SomePermissionName = 0x1 , // ... } public static bool CanAcce...
Is it safe to use reflection and enums for logic control of MVC application access ?
C#
I usually program in C++ , but for school i have to do a project in C # .So i went ahead and coded like i was used to in C++ , but was surprised when the compiler complained about code like the following : Ok they expect int as argument type , but why ? I would feel much more comfortable with uint as argument type , be...
const uint size = 10 ; ArrayList myarray = new ArrayList ( size ) ; //Arg 1 : can not convert from 'uint ' to 'int
Why do C # containers and GUI classes use int and not uint for size related members ?
C#
Consider the following typical scenario : I 'm wondering what is thought of the following replacement using the ? ? operator : I 'm not sure whether I should be using the second form . It seems like a nice shorthand , but the anObject = anObject construct at the beginning seems like it could be a bit of a code-smell.Is...
if ( anObject == null ) { anObject = new AClass ( ) ; } anObject = anObject ? ? new AClass ( ) ;
Instantiating Null Objects with ? ? Operator
C#
I have 2 concerns about my unit test method : Do I test too much in one test method ? How can my test method name reflect all test expectations ? I asked myself when my method name says : ReturnInvalidModelState , then my 2 other Asserts are not correct . At least concerning the method name ...
[ Test ] public void Create_TemplateAlreadyExists_ReturnInvalidModelState ( ) { // ARRANGE TemplateViewModel templateViewModel = new TemplateViewModel { Name = `` MyTest '' } ; Mock < ITemplateDataProvider > mock1 = new Mock < ITemplateDataProvider > ( ) ; Mock < IMappingEngine > mock2 = new Mock < IMappingEngine > ( )...
Does my unit test care about too much
C#
I 've got some code that looks like this : If I return from inside a `` using '' , will the using still clean up ?
using ( DBDataContext dc = new DBDataContext ( ConnectionString ) ) { Main main = new Main { ClientTime = clientTime } ; dc.Mains.InsertOnSubmit ( main ) ; dc.SubmitChanges ( ) ; return main.ID ; }
Returning from inside the scope of a 'using ' statement ?
C#
I am trying to get Razor runtime compilation working in an MVC Core 3.1 web application for Razor pages , but it 's not working for me . It 's frustrating as I have several previous MVC Core web applications across several releases ( 2.0 , 2.1 , 3.1 ) using controllers and views that work as expected.What is n't workin...
< Project Sdk= '' Microsoft.NET.Sdk.Web '' > < PropertyGroup > < TargetFramework > netcoreapp3.1 < /TargetFramework > < RootNamespace > WebApplication3._1 < /RootNamespace > < CopyRefAssembliesToPublishDirectory > false < /CopyRefAssembliesToPublishDirectory > < /PropertyGroup > < ItemGroup > < PackageReference Include...
Razor Page Runtime Compilation not working
C#
The only thing I can think of is to mark the class as [ CLSCompliant ( false ) ] , but I was wondering if there is a better way to get around this ?
[ assembly : CLSCompliant ( true ) ] //CS3016 : Arrays as attribute arguments is not CLS-compliant . [ ModuleExport ( typeof ( ModuleA ) , DependsOnModuleNames = new [ ] { `` ModuleB '' } ) ] public class ModuleA : IModule { }
CS3016 - How do we get around this when working with Prism + MEF ExportModule ?
C#
I am new to C # and SyncFusion and would really appreciate your help.I need to have the correct records shown in TreeViewPresenter ( TreeViewAdv ) after filtering gridGroupingControl . First I thought about to get the filters with : and to set these filters in the TreeViewPresenter but it seems that it does n't work li...
detailGroupingControl.TableDescriptor.RecordFilters
How to filter TreeViewAdv with RecordFilters
C#
I am having the following problem : How can I solve this problem ? Is there a way ?
public class A { public A ( X , Y , Z ) { ... } } public class B : A { public B ( X , Y ) : base ( X , Y ) { //i want to instantiate Z here and only then pass it to the base class ! } }
Problem with constructors and inheritance in C #
C#
I 'm trying to parse the values given from a device with a LSM6DSL chip ( gyroscopic and acc . ) and I 'm having a hard time parsing the data properly for positioning and angle.From the vendor I 've received the information that the unit is running on a resolution of 2000 for the gyro , 8g for the acc.I receive the dat...
public int [ ] BufferToMotionData ( byte [ ] buffer , int segments = 2 ) { int [ ] motionDataArray = new int [ segments * 3 ] ; int offset = Constants.BufferSizeImage + Constants.CommandLength ; for ( int i = 0 ; i < 6 ; i++ ) { motionDataArray [ i ] = BitConverter.ToInt16 ( buffer , offset + ( i * 2 ) ) ; if ( motionD...
Parsing LSM6DSL raw values
C#
I 'm sending messages to individual users depending on their roles , to accomplish that I have the following piece of code : I 'm not sure why do I have to invoke .ToList ( ) each time I need to send something , my backing store is HashSet < String > and I want SignalR to work with that type of store instead of convert...
public static void Add ( Guid userId , IEnumerable < SnapshotItem > snapshot ) { var hub = GlobalHost.ConnectionManager.GetHubContext < FeedbackHub > ( ) ; var items = ApplicationDbContext.Instance.InsertSnapshot ( userId , Guid.NewGuid ( ) , snapshot ) ; foreach ( var sendOperation in ConnectedUsers.Instance.Enumerate...
Why does SignalR use IList in its contracts and everywhere in its internals instead of IEnumerable ?
C#
I was looking at the metadata for Type , and noticed a member was protected , which made me wonder what might derive from it , which made me realize I could write a class that derives from it , and all that makes me wonder what I can do with that ( if anything ) .No compiler error from following :
class MyType : Type { // Implemented abstract members here . }
Why is n't the class Type sealed , and what can I do with that ?
C#
I am new to .net core and attempting a web app with a login page that uses the provided authentication features in asp .net-core . When I created the web app and built it up , I used IISExpress to run it and the authentication features worked correctly and allowed me to login and use various operations on the web app ....
info : RestartTool.Controllers.AccountController [ 0 ] User logged in.info : Microsoft.AspNetCore.Mvc.RedirectToActionResult [ 1 ] Executing RedirectResult , redirecting to /.info : Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [ 2 ] Executed action RestartTool.Controllers.AccountController.Login ( RestartT...
Authentication failing on Kestrel but not on IIS Express
C#
i created a db-model with the entity framework wizzard in Visual Studio . There are 2 tables ( job , stocktype ) which are related to each other with the table stocktype2job.With a Job Object , i could do something like this ... That should work just fine . But is there a way to create a navigation property in the job ...
Job < -- -- -- - no direct relation / navigation property -- -- -- -- > StockType | | | | -- -- -- -- -- -- -- -- -- -- - > StockType2Job -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > EntitiesObject db = new EntitiesObject ( ) ; Job job = db.Jobs.SingleOrDefault ( j = > j.IdJob == 40 ) ; List < StockType > stockTypes =...
Entity Framework - Create navigation property
C#
I have implementated the Factory Pattern as below . However , since the individual classes are public , nothing prevents someone from instantiating them directly . Is this correct ? How do I ensure that the concrete classes are only created via the Factory ? Factory implementationMain
namespace MRS.Framework { public abstract class DataSource { public override string ToString ( ) { return `` DataSource '' ; } } public class XMLDataSource : DataSource { } public class SqlDataSource : DataSource { } public class CSVDataSource : DataSource { public int MyProperty { get ; set ; } public override string ...
Factory Pattern Understanding
C#
About : My mathematical program will have a giant collection of items to iterate through . It will mainly consist of an item and a pointer to an other item ( ( int ) item , ( int ) pointer ) , resembling a key value pair.However , each item on his own will have several other attributes like this : ( item , pointer ) , ...
Dictionary < Dictionary < int , int > , Dictionary < int , int > nestedDictionary = new Dictionary < Dictionary < int , int > , Dictionary < int , int > nestedDictionary ( ) ; Dictionary < Dictionary < item , pointer > , Dictionary < attribute , attribute , ... > nestedDictionary = Dictionary < Dictionary < item , poin...
hashset , dictionary , arraylist : can ` t see the forest for the trees
C#
I 'm pretty new to the memory problem . Hope you do n't think this is a stupid question to ask.I know that memory larger than 85,000 Bytes would be put into LOH in C # i.e . I 'm wondering if a collection with size 10000 - 20000 with an object that contains 10 member variables ( byte type ) will be put into LOH or SOH ...
Byte [ ] hugeByteCollection = new Byte [ 85000 ] ;
C # Large object in medium size collection