lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a table in my SQL Server database with a column ReviewText of datatype NVARCHAR ( MAX ) .If I insert or update rows via a SQL query with N '' prefix , for example : it works great and it will write smiley into the table.But if I insert it from code : the code will store It 's OK . ? ? without smiley into the col...
UPDATE [ dbo ] . [ Reviews ] SET ReviewText = N'It 's OK. ' WHERE Id = [ id ] var review = _context.UserReview.FirstOrDefault ( x = > x.Id == [ id ] ) ; review.ReviewText = `` It 's OK. `` ;
Can not write unicode ( emoji ) into SQL Server table via context ( Entity Framework Core )
C#
I currently haveandThe idea is that when the mouse enters the yellow highlighted control on the left the yellow highlighted control on the right will shake . The control on the right has the x : Name=StatorMinorRadiusEdit So far so good the above works.Now I want to add another complication . I only want the animation ...
< ContentControl Grid.Column= '' 2 '' Grid.Row= '' 3 '' > < ContentControl.Triggers > < EventTrigger RoutedEvent= '' UIElement.MouseEnter '' > < BeginStoryboard Storyboard= '' { StaticResource ShakeStatorMinorRadiusEdit } '' / > < /EventTrigger > < /ContentControl.Triggers > ... < snip > ... < /ContentControl > < Grid....
Putting a guard on a WPF event trigger . Is this possible ?
C#
While reading Jeffrey Richter 's CLR via C # 4th edition ( Microsoft Press ) , the author at one point states that while Object.Equals currently checks for identity equality , Microsoft should have implemented the method like this : This strikes me as very odd : every non-null object of the same type would be equal by ...
public class Object { public virtual Boolean Equals ( Object obj ) { // The given object to compare to ca n't be null if ( obj == null ) return false ; // If objects are different types , they ca n't be equal . if ( this.GetType ( ) ! = obj.GetType ( ) ) return false ; // If objects are same type , return true if all o...
Object.Equals : everything is equal by default
C#
I have to following ProgressIndicator and in the ViewModel ascociated with this View I implement The problem is this binding is failing and I do n't know why . Using Snoop I have the following System.Windows.Data Error : 40 : BindingExpression path error : 'ProgressVisibility ' property not found on 'object ' `` Progre...
< MahAppsControls : ProgressIndicator Width= '' 100 '' Height= '' 10 '' VerticalAlignment= '' Center '' ProgressColour= '' White '' Visibility= '' { Binding ProgressVisibility } '' / > private Visibility progressVisibility = Visibility.Collapsed ; public Visibility ProgressVisibility { get { return progressVisibility ;...
Binding Failure with MahAppsMetro ProgressIndicator
C#
i was wondering , because i have a method with multiple default parameters and when i call the method it i have to do it in order so my question is , is there any way to skip the first few default parameters ? Let 's say i want to input only the colour , and the font-family like this :
private string reqLabel ( string label , byte fontSize = 10 , string fontColour = `` # 000000 '' , string fontFamily = `` Verdana '' ) { return `` < br / > < strong > < span style=\ '' font-family : `` + fontFamily + `` , sans-serif ; font-size : '' +fontSize.ToString ( ) + `` px ; color : '' + fontColour + `` ; \ '' >...
calling a method with multiple default values
C#
I need to draw primitives with graphics object with different transformation matrix . I wonder should I dispose the matrix or graphics will do it for me : http : //msdn.microsoft.com/en-us/library/system.drawing.graphics.transform.aspx Says : Because the matrix returned and by the Transform property is a copy of the ge...
using ( var g = Graphics.FromImage ( ... ) ) { ... some code ... var tmp = g.Transform ; g.TranslateTransform ( ... ) ; ... some code ... g.Transform = tmp ; // should I call tmp.Dispose ( ) here ? tmp.Dispose ( ) ; ... some code that use g ... . }
Should I dispose ( ) the Matrix returned by Graphics.Transform ?
C#
If the title did n't make sense , here 's an example : I 'd like to create an extension method like this : So I can do this : Is this possible ? Where did I go wrong ? The real-world application here is that `` Dog '' is a major base class in my application , and there are many subclasses , each of which may have IList...
interface IEat { void Eat ; } class Cat : IEat { void Eat { nom ( ) ; } } class Dog : IEat { void Eat { nom ( ) ; nom ( ) ; nom ( ) ; } } class Labrador : Dog { } public static void FeedAll ( this IEnumerable < out IEat > hungryAnimals ) { foreach ( var animal in hungryAnimals ) animal.Eat ( ) ; } listOfCats.FeedAll ( ...
How can I create a covariant extension method on a generic interface in C # ?
C#
So these two methods have the same signature but different constraintsBut they can not be defined in a single class because they have the same signatures . But in this particular case they 're mutually exclusive . ( Unless I 'm wrong about that ) I understand you can put additional constraints besides class and struct ...
public static void Method < T > ( ref T variable ) where T : struct { } public static void Method < T > ( ref T variable ) where T : class { }
Mutally exclusive constraints on two methods with the same signature
C#
If I have a LINQ to SQL statement for exampleWhen I want to see what SQL is being generated by LINQ , what I do is that I comment out the ToList ( ) and put a breakpoint on the command after this LINQ statement and then I can hover it and read the SQL.My question : Is that a correct way of getting the generated SQL ?
var query = ( from a in this.Context.Apples select a.Name ) .ToList ( ) ;
Seeing the SQL that LINQ generates
C#
I have this sample code : It obviously return the Result from the t1 task . ( which is 1 ) But how can I get the Result from the last continued task ( it should be 3 { 1+1+1 } )
Task < int > t1= new Task < int > ( ( ) = > 1 ) ; t1.ContinueWith ( r= > 1+r.Result ) .ContinueWith ( r= > 1+r.Result ) ; t1.Start ( ) ; Console.Write ( t1.Result ) ; //1
Get the result for the last Task < > ( continuation ) ?
C#
Following this prototype for unit testing I 've ran into a problem when using JS interop.Just adding a component that uses IJSRuntime will cause the following exception System.InvalidOperationException : Can not provide a value for property 'JsRuntime ' on type 'Application.Components.MyComponent ' . There is no regist...
[ Test ] public void ExampleTest ( ) { var component = host.AddComponent < MyComponent > ( ) ; } [ Test ] public void ExampleTest ( ) { var jsRuntimeMock = new Mock < IJSRuntime > ( ) ; host.AddService ( jsRuntimeMock ) ; var component = host.AddComponent < MyComponent > ( ) ; }
Mocking IJSRuntime for Blazor Component unit tests
C#
When i initialize an object using the new object initializers in C # I can not use one of the properties within the class to perform a further action and I do not know why.My example code : Within the Person Class , x will equal 0 ( default ) : However person.Age does equal 29 . I am sure this is normal , but I would l...
Person person = new Person { Name = `` David '' , Age = `` 29 '' } ; public Person ( ) { int x = Age ; // x remains 0 - edit age should be Age . This was a typo }
What am I doing wrong with C # object initializers ?
C#
I 'm struggling to implement a custom auth flow with OAuth and JWT.Basically it should go as follows : User clicks in loginUser is redirect to 3rd party OAuth login pageUser logins into the pageI get the access_token and request for User InfoI get the user info and create my own JWT Token to be sent back and forthI hav...
services.AddAuthentication ( options = > { options.DefaultChallengeScheme = `` 3rdPartyOAuth '' ; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme ; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme ; } ) .AddCookie ( ) // Added only because of the DefaultSignInSc...
OAuth with custom JWT authentication
C#
I have always wondered what the best practice for using a Stream class in C # .Net is . Is it better to provide a stream that has been written to , or be provided one ? i.e : as opposed to ; I have always used the former example for sake of lifecycle control , but I have this feeling that it a poor way of `` streaming ...
public Stream DoStuff ( ... ) { var retStream = new MemoryStream ( ) ; //Write to retStream return retStream ; } public void DoStuff ( Stream myStream , ... ) { //write to myStream directly }
.Net streams : Returning vs Providing
C#
I want to get full url , in ASp.NET MVC 4 , for example user entered url : And when I try to get this url in Global.asax , I get only http : //localhost:5555/Thanks
http : //localhost:5555/ # globalName=MainLines & ItemId=5 protected void Application_BeginRequest ( object sender , EventArgs e ) { var url = HttpContext.Current.Request.Url ; }
How to get full url address
C#
The screenshot says it pretty much.I have the overloads as seen in the screenshot . When using a string as second parameter the compiler should figure out that the first argument can only be a Func and not an expression.But the compiler throws an error saying ' A lamda expression with a statement body can not be conver...
public static void Main ( string [ ] args ) { //compiler error A.CallTo ( ( ) = > Main ( A < string [ ] > .That.Matches ( strings = > { return true ; } , `` description '' ) ) ) ; //compiles Func < string [ ] , bool > predicate = strings = > { return true ; } ; A.CallTo ( ( ) = > Main ( A < string [ ] > .That.Matches (...
Compiler Error for Expression/Func overloads
C#
Here is my class and I do n't want this method to be overridden in child classes , how can I accomplish this behaviour ?
class A { public virtual void demo ( ) { } } class B : A { public override void demo ( ) { } } // when Class B be inherited in C , methods can be overridden further , // but I do n't want the method to be overridden further.class C : B { }
Forbid overriding of a method in a derived class
C#
You can find the source code demonstrating this issue @ http : //code.google.com/p/contactsctp5/I have three model objects . Contact , ContactInfo , ContactInfoType . Where a contact has many contactinfo 's and each contactinfo is a contactinfotype . Fairly simple I guess . The problem I 'm running into is when I go to...
public partial class Contact { public Contact ( ) { this.ContactInformation = new HashSet < ContactInformation > ( ) ; } public int ContactId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public virtual ICollection < ContactInformation > ContactInformation { get ; set ; ...
CTP5 EF Code First Question
C#
I have a function as below : I need this function to return either string or int . My return value is set as belowHow to have either one data type as return value in dynamic environment .
public var UpdateMapFetcher ( int stationID , int typeID ) if ( finaloutput == `` System.String '' ) { // param1 [ i ] = Convert.ChangeType ( typeID_New.ToString ( ) , typeof ( string ) ) ; returnvalue = returnvalue.ToString ( ) ; return returnvalue ; } else if ( finaloutput == `` System.Int32 '' ) { int a=0 ; a = Conv...
set multiple return value for method declaration
C#
Feel like asking a stupid question but I want to know answer . I don ’ t need any code to update UI from worker thread I know how to update UI from worker/thread pool.I want to know that why we get this error “ Cross-thread operation not valid : Control `` accessed from a thread other than the thread it was created on....
public partial class Form1 : Form { private void Form1_Load ( object sender , EventArgs e ) { } TextBox textbox2 = null ; List < int > collection = new List < int > ( ) ; public Form1 ( ) { InitializeComponent ( ) ; textbox2 = new TextBox ( ) ; } public void UpdateTextBox ( ) { collection.Add ( Thread.CurrentThread.Man...
Why we cant update UI from worker thread ? same as other variables/object
C#
I have 2 classes declared in a css file ( StyleSheet1.css ) , .Class1 and .Class2 . How do I choose between those two classes after CLICKING A BUTTON for my table tag ? CSS File : As much as possible I want to change classes using C # if possible , but if not , javascript maybe ? I 'm very new to ASP and C # , with a l...
< link href= '' Styles/StyleSheet1.css '' rel= '' stylesheet '' type= '' text/css '' / > < table class= '' Class1 '' > < tr > < td > Hello World ! < /td > < /tr > < /table > .Class1 { background-color : Blue ; } .Class2 { background-color : Red ; }
Choose a class for my table after button click ? ( HTML table )
C#
I 've run across .NET 4 's ThreadLocal < T > and was wondering if there 's a way to accumulate the .Value values from all threads . In Microsoft 's ppl C++ library they have Concurrency : :combinable : :combine_each , is there an equivalent method for .NET 's ThreadLocal ?
ThreadLocal < long > ticks = new ThreadLocal < long > ( ) ; void AddTicks ( StopWatch sw ) { ticks.Value += sw.ElapsedTicks ; } void ReportTimes ( ) { long totalTicks = /* How do I accumulate all the different values ? */ ; Console.WriteLine ( TimeSpan.FromTicks ( totalTicks ) ) ; }
How to combine all values from a ThreadLocal < T > ?
C#
Below is the code I 'm using but it replies with Method 'Boolean isUser ( System.String ) ' has no supported translation to SQL.Any help ? Btw I 'm using linq to SQL data sourceI found a solution to query the result of the first query as objects but is that good cause I will passing through my data twice.the updated co...
public void dataBind ( ) { using ( var gp = new GreatPlainsDataContext ( ) ) { var emp = from x in gp.Employees let k = isUser ( x.ID ) where x.ActivtyStatus == 0 & & isUser ( x.ID ) ! = false orderby x.ID select new { ID = x.ID , Name = x.FirstName + `` `` + x.MiddleName } ; ListView1.DataSource = emp ; ListView1.Data...
trying to call a method in the where of a linq statment
C#
I updated my VS Community Edition to 15.8.1 and after that I got this error when I tried to edit my sql inside strongly typed dataset .
Configure TableAdapter failedUnable to find connection 'my_connection ' for object 'Web.config'.The connection string could not be found in application settings , or the data provider associated with the connection string could not be loaded . ''
Strongly typed dataset ( .xsd ) error VS Community Edition 15.8.1
C#
I noticed the today that my one application im developing is seriously growing in memory.So I did a Visual Studio Memory Profile and I found the following results : This was on top of the memory Usage with ~600Meg This doesnt seem correct to me and im Not sure why it is so ? Here is my send function : The application b...
Function Name Inclusive Allocations Exclusive Allocations Inclusive Bytes Exclusive Bytes System.Net.Sockets.Socket.BeginSend ( uint8 [ ] , int32 , int32 , valuetype System.Net.Sockets.SocketFlags , valuetype System.Net.Sockets.SocketError & , class System.AsyncCallback , object ) 3 192 569 3 192 561 635 307 885 635 30...
Memory Issue with async socket and begin Send
C#
I was handling yet another KeyDown event in a user control when I wondered if it existed a library for typing fluent code for handling event likeDoes that exist ?
editor.When ( Keys.F ) .IsDown ( ) .With ( Keys.Control ) .Do ( ( sender , e ) = > ShowFindWindow ( ) ) ;
Is there is a fluent approach to handling WinForm event ?
C#
I want to search the name of the students which contains the keywords , at first I pass the keywords separated by commas , but I find the search time is too long.But when I convert these keywords into an array , it is real fast.Why do linq search has a huge difference in efficiency ? Is that because of the array or lin...
var keyWord= '' Lyly , Tom , Jack , Rose '' ; //and so on , more than 500 namesvar student= Context.Students.Where ( i = > keyWord.Contains ( i.Name ) ) ; //very slow var keyWord= '' Lyly , Tom , Jack , Rose '' ; //and so on , more than 500 names var keyWordArray=keyWord.split ( ' , ' ) ; var student= Context.Students....
Why do linq search has a huge difference in efficiency when I use string and array especially for large data ?
C#
I am working on a Visual Studio 2010 extension and I want to add an attribute to an MSBuild Item , as follows : So , far the only way I found is using the method IVsBuildPropertyStorage.SetItemAttribute . This works fine for simple strings , but when i try to use characters that are special to MSBuild , I get this resu...
< EmbeddedResource Include= '' SomeFile.xml '' > < FooAttribute > % ( Filename ) % ( Extension ) < /FooAttribute > < /EmbeddedResource > < EmbeddedResource Include= '' SomeFile.xml '' > < FooAttribute > % 29 % 25 % 28Filename % 29 % 25 % 28Extension % 29 < /FooAttribute > < /EmbeddedResource >
How do I prevent IVsBuildPropertyStorage.SetItemAttribute from escaping special characters ?
C#
The code found in the PresentationCore.dll ( .NET4 WPF ) by ILSpy : The return type of uri.GetComponents is string , why did n't the method just return the string value instead of wrapping it in a StringBuilder ( string ) .ToString ( ) ; Is this by design ? What would be the reason for doing this in a general sense ? W...
// MS.Internal.PresentationCore.BindUriHelperinternal static string UriToString ( Uri uri ) { if ( uri == null ) { throw new ArgumentNullException ( `` uri '' ) ; } return new StringBuilder ( uri.GetComponents ( uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString , UriFormat.SafeUnesca...
Why does the WPF Presentation library wrap strings in StringBuilder.ToString ( ) ?
C#
In the following code , I create a DispatcherTimer in the class 's constructor . No one keeps reference on it.In my understanding , the timer should be reclaimed by the garbage collector some time after leaving the constructor 's scope . But that does n't happen ! Even after forcing a garbage collection with GC.Collect...
public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; new DispatcherTimer { Interval = TimeSpan.FromMilliseconds ( 100 ) , IsEnabled = true } .Tick += ( s , e ) = > { textBlock1.Text = DateTime.Now.ToString ( ) ; } ; } }
Garbage collection of C # object declared in constructor
C#
Assuming I have an attached property defined like that : I can write the documentation for the property identifier ( MyPropertyProperty ) and for the accessors ( GetMyProperty and SetMyProperty ) , but I have no idea where to put the documentation for MyClass.MyProperty attached property , since it is not an actual cod...
public static string GetMyProperty ( DependencyObject obj ) { return ( string ) obj.GetValue ( MyPropertyProperty ) ; } public static void SetMyProperty ( DependencyObject obj , string value ) { obj.SetValue ( MyPropertyProperty , value ) ; } // Using a DependencyProperty as the backing store for MyProperty . This enab...
Where to put the XML documentation comments for an attached property ?
C#
My Goal : I have a system where I would like others to be able to add a C # script that contains a specific method that I can lookup and execute from within another class at runtime.My Approach : I created an interface with a method so I can loop through any class that implements the interface using reflection and list...
//Possible solution 1 : Type selectedType = typeSelectedByEnum ; MethodInfo genericMethod = selectedType.GetMethod ( `` TheInterfaceMethod '' ) .MakeGenericMethod ( selectedType ) ; genericMethod.Invoke ( selectedType , new object [ 0 ] ) ; //Possible solution 2 : ( however I would much prefer to use something avaliabl...
Dynamically invoke a method given a Type variable
C#
I am trying to develop a mechanism using which I can execute any method with 1 retry attempt . The retry will be triggered if an exception is encountered in the 1st run.The basic Idea is , I will have a generic class for the retry logic , and I want to pass any method in it via delegates . And that method will be execu...
public class RetryHandler { Delegate _methodToRetry ; // default constructor with delegate to function name . public RetryHandler ( Delegate MethodToExecuteWithRetry ) { _methodToRetry = MethodToExecuteWithRetry ; } public void ExecuteWithRetry ( bool IsRetryEnabled ) { try { _methodToRetry.DynamicInvoke ( ) ; } catch ...
Generic method to execute any method with 1 time retry using Delegates
C#
I Have a DbContext where i need a CompanyId to make a global query , like multi tenant.The CompanyId is added to a token claim , how i 'm can get the claim value and inject on the DbContext ?
public void SetGlobalQuery < T > ( ModelBuilder builder ) where T : BaseEntity { builder.Entity < T > ( ) .HasQueryFilter ( e = > e.CompanyId == _companyId ) ; } services.AddScoped ( provider = > { var optionsBuilder = new DbContextOptionsBuilder < MyDbContext > ( ) ; var options = optionsBuilder.UseSqlServer ( Configu...
How to get a token claim value and inject on a dbcontext service
C#
I do have an MVC website , which is running locally just fine.When I 'm debugging the application , off course , it 's running under the HTTP protocol then everything works fine.I do have a controller : Note : I 've removed the code from this method here because it 's irrelivant.This method is called through AngularJS ...
[ Route ( `` messages/new/form/invoice '' ) , HttpPost ] public ActionResult Invoice ( object model ) { var result = JsonConvert.DeserializeObject < dynamic > ( model.ToString ( ) ) ; // Further processing goes here ... } this.saveInvoice = function ( ) { // Post the form . $ http ( { method : `` POST '' , url : `` /me...
StackOverflowException when posting JSon data to server ( HTTP / HTTPS )
C#
I am currently writing a helper library that connects to shop floor PLCs via Software Toolbox 's TopServer . The TopServer library has separate versions for x86 and x64 architectures and I want to load the appropriate version at runtime using late binding based on the CPU architecture of the calling code . The methods ...
public class LateBinding { public static T GetInstance < T > ( string dllPath , string fullyQualifiedClassName ) where T : class { Assembly assembly = System.Reflection.Assembly.LoadFile ( dllPath ) ; Type t = assembly.GetType ( fullyQualifiedClassName ) ; return ( T ) Activator.CreateInstance ( t ) ; } }
Late Binding to dll based on CPU architecture
C#
I have a system which uses AOP with ContextBoundObject.This is used to intercept a method call and perform certain operations before and after the function . It all works fine until I make the 'function to be intercepted ' async.I understand that the C # compiler rewrites async methods into a state machine , which retu...
[ AuditBoundary ] public class AuditFacade : ContextBoundObject { [ Audit ] public ResponseObject DoSomthing ( ) { //Do something return new ResponseObject ( ) ; } /// < summary > /// Async Method to be intercepted /// < /summary > /// < returns > < /returns > [ Audit ] public async Task < ResponseObject > DoSomthingAy...
ContextBoundObject with Async/Await
C#
I just download the Iron JS and after doing some 2/3 simple programs using the Execute method , I am looking into the ExecuteFile method.I have a Test.js file whose content is as underI want to invoke the same from C # using Iron JS . How can I do so ? My code so farBut loadfile variable is null ( path is correct ) ..H...
function Add ( a , b ) { var result = a+b ; return result ; } var o = new IronJS.Hosting.CSharp.Context ( ) ; dynamic loadFile = o.ExecuteFile ( @ '' d : \test.js '' ) ; var result = loadFile.Add ( 10 , 20 ) ;
How to invoke a function written in a javascript file from C # using IronJS
C#
While giving answer to an SO question , I was told that my solution will introduce a closure over variable so it will have slightly worse performance . So my question is : How will there be a closure ? How will it affect performance ? Here is the questionHere is my solution . I introduced the variable yr to store year....
List.Where ( s = > s.ValidDate.Date == DateTime.Today.Year ) .ToList ( ) ; int yr = DateTime.Now.Year ; List.Where ( s = > s.ValidDate.Year == yr ) .ToList ( ) ;
`` Closure over variable gives slightly worse performance '' . How ?
C#
I am working on a project in which I am binding Cart : As shown in image I am populating my cart . Using User Control . And in User control I have populated that using One simple aspx form that is minicart . So now as you can see there is one button Checkout in That page . Which is populated through User Control but ac...
< a id= '' lnkcheckout '' runat= '' server '' href= '' javascript : return false ; '' onclick= '' checkout_onclick '' > Checkout < /a >
Calling Page Click event via User Control
C#
I 'm using protobuf-net for serializing a number of types , some of which are inherited from a base type . I know that the Protocol Buffers spec does not support inheritance , and that the support in protobuf-net is basically a workaround because of that.Rather than using the protobuf-net attributes I am configuring a ...
using System ; using System.Collections.Generic ; using ProtoBuf.Meta ; namespace Test { public sealed class History { public History ( ) { Events = new List < Event > ( ) ; } public ICollection < Event > Events { get ; private set ; } } public enum EventType { ConcertStarted , ConcertFinished , SongPlayed } public cla...
How to choose a field number when using protobuf-net inheritance ?
C#
IntroductionWhile testing performance differences with certain LinQ functions today , I noticed , that LastOrDefault ( predicate ) was almost always faster than FirstOrDefault ( predicate ) , which got me a little interested , so i wrote some test cases , to test both functions against each other.I created a list of in...
List < int > l = new List < int > ( ) ; for ( int i = 1 ; i < = 1000000 ; i++ ) { l.Add ( i ) ; } static void first ( List < int > l ) { int e = l.FirstOrDefault ( x = > x == 500000 ) ; int z = l.FirstOrDefault ( x = > x == 500000 ) ; int d = l.FirstOrDefault ( x = > x == 500000 ) ; int v = l.FirstOrDefault ( x = > x =...
Why is LastOrDefault ( predicate ) in LINQ faster than FirstOrDefault ( predicate )
C#
A colleague pointed me to a strange case in C # ( not so sure if this actually strange though ) . Suppose you have a class Employee . If you want to create a Generic List < > of type Employee , you can simply do : I understand that I need to pass the Employee type to the Generic list so that it knows the required type ...
List < Employee > x = new List < Employee > ; Employee x = new Employee ( ) ; List < typeof ( x ) > list = new List < typeof ( x ) > ( ) ;
Why this is not possible in C # Generics ?
C#
Why is it that when run I website using Azure SDK 1.3 it opens two browser windows ( or tabs ) despite the fact that I have only defined one end point : What do I have to do to get just one browser window appearing when I run ( using F5 ) my Azure application from Visual Studio ?
< Sites > < Site name= '' Web '' > < Bindings > < Binding name= '' Endpoint1 '' endpointName= '' Endpoint1 '' / > < /Bindings > < /Site > < /Sites >
Azure SDK 1.3 opens two browser windows ( or tabs )
C#
In a WinForms application , a Panel is used as a placeholder to display a single User Control as a navigation strategy : whenever the user wishes to navigate to a given area , the respective User Control is added to the Panel . Simplified : As a result of a requirement that is out of my control , the Form must support ...
contentPanel.Controls.Clear ( ) ; userControl.Dock = DockStyle.Fill ; contentPanel.Controls.Add ( userControl ) ; protected virtual void OnChangeCulture ( CultureInfo newCulture ) { System.Threading.Thread.CurrentThread.CurrentCulture = newCulture ; System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture ; ...
Re-apply layout of a dynamically added UserControl after calling ApplyResources
C#
I trying to convert from WPF combobox selected value to enumurator it return not valid cast in the runtime otherwise the string and the enum name is matched my code is
Siren.PfundMemberWebServices.Emirates EM = ( Siren.PfundMemberWebServices.Emirates ) cmbemirate.SelectedValue
Convert from String to Enum return not valid cast in WPF
C#
I 'm wondering if there is any shortcut in visual studio to generate automatic documentation for a method or class.For example when I write a method : I want generate the following structure :
public void MyFunction ( int d ) { } /// < summary > /// /// < /summary > /// < param name= '' d '' > < /param >
how to simplify code documentation process - visual studio C #
C#
I 'm trying to write a small little scripting engine for a bullet hell game and I would like to do it in F # . I wrote some C # code to conceptualize it , but I 'm having trouble porting it to F # . The C # code is posted below , and I would like some help porting it to F # . I have a feeling the matching F # code will...
interface IRunner { Result Run ( int data ) ; } struct Result { public Result ( int data , IRunner next ) { Data = data ; Next = next ; } public int Data ; public IRunner Next ; } class AddOne : IRunner { public Result Run ( int data ) { return new Result ( data + 1 , null ) ; } } class Idle : IRunner { public Result R...
F # : Need help converting C # to F #
C#
Why is x dynamic , compiler not smart enough or I miss something important ?
public string Foo ( object obj ) { return null ; } public string Foo ( string str ) { return null ; } var x = Foo ( ( dynamic ) `` abc '' ) ;
Why dynamic call return dynamic result ?
C#
Lets say I have a library , version 1.0.0 , with the following contents : and I reference this library in a console application with the following contents : Running the program will output the following : If I build a new version of the library , version 2.0.0 , looking like this : and copy this version to the bin fol...
public class Class1 { public virtual void Test ( ) { Console.WriteLine ( `` Library : Class1 - Test '' ) ; Console.WriteLine ( `` '' ) ; } } public class Class2 : Class1 { } class Program { static void Main ( string [ ] args ) { var c3 = new Class3 ( ) ; c3.Test ( ) ; Console.ReadKey ( ) ; } } public class Class3 : Cla...
Method binding to base method in external library ca n't handle new virtual methods `` between ''
C#
For a network protocol implementation I want to make use of the new Memory and Span classes to achieve zero-copy of the buffer while accessing the data through a struct.I have the following contrived example : The result is that buffer is filled with 7 , 6 , 5 , 4 , 3 , 2 , 1 , which is as desired , but I can hardly im...
[ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct Data { public int IntValue ; public short ShortValue ; public byte ByteValue ; } static void Prepare ( ) { var buffer = new byte [ 1024 ] ; var dSpan = MemoryMarshal.Cast < byte , Data > ( buffer ) ; ref var d = ref dSpan [ 0 ] ; d.ByteValue = 1 ; d.Sh...
Proper way to get a mutable struct for Memory < byte > / Span < byte > ?
C#
This is a spin-off question based on Eric Lippert 's answer on this question.I would like to know why the C # language is designed not being able to detect the correct interface member in the following specific case . I am not looking on feedback whether designing a class this way is considered best practice . In the c...
class Turtle { } class Giraffe { } class Ark : IEnumerable < Turtle > , IEnumerable < Giraffe > { public IEnumerator < Turtle > GetEnumerator ( ) { yield break ; } // explicit interface member 'IEnumerable.GetEnumerator ' IEnumerator IEnumerable.GetEnumerator ( ) { yield break ; } // explicit interface member 'IEnumera...
Interface conflict resolution in C #
C#
I have a `` Status '' class in C # , used like this : You get the idea.All callers of MyFunction should check the returned Status : Lazy callers however can ignore the Status.or Is it possible to make this impossible ? e.g . an throw exceptionIn general : is it possible to write a C # class on which you have to call a ...
Status MyFunction ( ) { if ( ... ) // something bad return new Status ( false , `` Something went wrong '' ) else return new Status ( true , `` OK '' ) ; } Status myStatus = MyFunction ( ) ; if ( ! myStatus.IsOK ( ) ) // handle it , show a message , ... MyFunction ( ) ; // call function and ignore returned Status { Sta...
Enforcing required function call
C#
The IndexOf function called on a string returns -1 , while there definitely is a match.Do you have any idea , why it is that it finds `` NY '' but not `` N '' by itself ? If I search for every other letter in the string , it is able to find it , but not the `` N '' .The same issue appears as well with lower case.If I t...
string sUpperName = `` PROGRAMOZÁSI NYELVEK II . ADA EA+GY . ( BSC 08 A ) '' ; string sUpperSearchValue = `` N '' ; sUpperName.IndexOf ( sUpperSearchValue ) ; // Returns -1sUpperSearchValue = `` NY '' ; sUpperName.IndexOf ( sUpperSearchValue ) ; // Returns 13sUpperName [ 13 ] ; // 78 ' N'sUpperSearchValue [ 0 ] ; // 78...
Why ca n't IndexOf find the character N in combination with Y in hungarian culture ?
C#
I work on a fairly large product . It 's been in development since .Net 1.0 was still a work-in-progress and so it has a lot of bad quality code and was not written with unit tests in mind . Now we 're trying to improve the quality and implement tests for each feature and bug fix . One of the biggest problems we 're ha...
interface IBar { string Baz { get ; set ; } } interface IFoo { string Biz { get ; set ; } } interface ISession : IFoo , IBar { }
Interface inheritance to breakup god objects ?
C#
I read alot about async/await , but I still have some lack in understanding the following situation.My question is , should I implement my `` wrapper '' methods as in DoSomething ( ) or like in DoSomethingAsync ( ) .So what 's better ( and why ) : Do I use await in wrapper methods or return the Task directly ?
public static async void Main ( ) { await DoSomething ( ) ; await DoSomethingAsync ( ) ; } private static Task DoSomething ( ) { return MyLibrary.DoSomethingAsync ( ) ; } private static async Task DoSomethingAsync ( ) { await MyLibrary.DoSomethingAsync ( ) .ConfigureAwait ( false ) ; } public class MyLibrary { public s...
Struggling with async/await C #
C#
I am a bit new to c # so please overlook if you find it trivial . I saw the following `` weird '' code.Can anybody shed a bit of light on it.Specially the _action -= c ; part .
public event Action _action ; if ( _action ! = null ) { foreach ( Action c in _action.GetInvocationList ( ) ) { _action -= c ; } }
Correct usage of Action and Events
C#
I have the following dependencyProject A ( owned by me ) uses project_b.dllNewtonsoft.Json.dll ( version 8 ) Project B usesproject_c.dllNewtonsoft.Json.dll ( version 9 ) Project C usesNewtonsoft.Json.dll ( version 4.5 ) Project A calls a method of Project B which will call a method of Project C , then return values bac...
< dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-655535.0.0.0 '' newVersion= '' XX '' / > < /dependentAssembly >
C # Assembly Binding Redirects - Newtonsoft.Json
C#
In C # 6.0 you can write this : They have the same result of : But you ca n't write this : It generates the following error : Invalid expression term 'object'.But you can still write this : Why nameof ( object ) does not compile ?
var instance = default ( object ) ; var type = typeof ( object ) ; var instance = default ( System.Object ) ; var type = typeof ( System.Object ) ; var name = nameof ( object ) ; var name = nameof ( System.Object ) ;
Why is nameof ( object ) not allowed ?
C#
I 'm developing a C # application that supports Windows Aero in the main form.Some applications that do not support Visual Styles , for example GoToMeeting , disable visual styles and my form is wrongly drawn while GoToMeeting is running ( the Aero client area is drawn black ) .How could I subscribe to a OS event that ...
private const int WM_DWMCOMPOSITIONCHANGED = 0x31e ; [ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmIsCompositionEnabled ( ref bool pfEnabled ) ; protected override void WndProc ( ref Message m ) { if ( m.Msg == WM_DWMCOMPOSITIONCHANGED ) { bool compositionEnabled = false ; DwmIsCompositionEnabled ( r...
How do I subscribe to an OS-level event raised when DWM composition/Aero Glass is disabled ?
C#
Take the following simple code . The DoMyCode method has two attributes applied to it , with a space between the entries.This was made in VS 2015 targeting .Net 4.6.If you run this code in Visual Studio 2015 ( update 3 ) it will compile and run with no errors or warnings.However , running the exact same code in Visual ...
using System ; namespace AttributeSpaceTesting { class Program { static void Main ( string [ ] args ) { } [ Horse Cow ] static void DoMyCode ( ) { } } [ AttributeUsage ( AttributeTargets.Method ) ] class HorseAttribute : Attribute { } [ AttributeUsage ( AttributeTargets.Method ) ] class CowAttribute : Attribute { } } S...
Why does VS 2015 allow attributes separated by spaces while VS 2017 does not ?
C#
Excuse me if I am asking silly question , but can anybody explain the difference between following two calls ( ToArray ) . In the intellisense it does not show them as overloaded methods & of course the output of both the calls are same .
List < int > i = new List < int > { 1 , 2 , 5 , 64 } ; int [ ] input = i.Where ( j = > j % 2 == 1 ) .ToArray ( ) ; input = i.Where ( j = > j % 2 == 1 ) .ToArray < int > ( ) ;
Difference between ToArray ( ) & ToArray < int > ( ) ;
C#
I have a method like : Here I am trying to get text from a string until & character is found . My senior modified this method to So instead of storing the index , it will calculate it twice , and his reasoning was that since that method would be called in multiple threads , there could be invalid value stored in index ...
private static string AmpRemove ( string str ) { int index = str.IndexOf ( ' & ' ) ; if ( index > 0 ) str = str.Substring ( 0 , index ) ; return str ; } private static string AmpRemove ( string str ) { if ( str.IndexOf ( ' & ' ) > 0 ) str = str.Substring ( 0 , str.IndexOf ( ' & ' ) ) ; return str ; }
Reentrant code and local variables
C#
I have an array Vector2f structs that each contain two floats , and I want to pass it to a function that takes an array of floats . These structs represent 2d coordinates , and I want the end result to be [ x0 , y0 , x1 , y1 , ... xn , yn ] . Some code to demonstrate : This is easy by copying the contents into a new ar...
using System ; using System.Runtime.InteropServices ; public class Test { [ StructLayout ( LayoutKind.Sequential ) ] public struct Vector2f { float x ; float y ; public Vector2f ( float x , float y ) { this.x = x ; this.y = y ; } } public static void Main ( ) { Vector2f [ ] structs = new Vector2f [ ] { new Vector2f ( 1...
Use an array of Vector2f structs as an array of floats in-place
C#
I started to use Ninject , on this relatively small project and i have run into a problem : i have this classthat depends on that in turn depends on the DataRepository has a ctor that looks like : Now , i need to be able to use a single instance of BizEntityModel across more than one IDataRepository instance . I also n...
class SomeService : ISomeService class BizLogicModule : IBizLogicModule class DataRepository : IDataRepository DataRepository ( BizEntityModel context ) Bind < SomeService > ( ) .To < ISomeService > ( ) ; Bind < BizLogicModule > ( ) .To < IBizLogicModule > ( ) ; Bind < DataRepository > ( ) .To < IDataRepository > ( ) ;...
How to keep IoC container in one place , while inner classes need to create dependencies after beeing constructed
C#
I am trying to build a query like thisBut when I run this I get Is Math.Abs not supported or do I have to do it differently ? Here is the sql statement ( a couple more fields then what was in my example ) big this is that it is translating it toso has an extra `` as '' in it.Pick class
var d = dbContext.Picks .Where ( /* some conditions */ ) .GroupBy ( x = > new { gameDiff = x.Schedule.GameTotal.Value - x.TieBreakerScore.Value } ) .Select ( g = > new { name = g.Key.firstname , count = g.Count ( ) , gameDiff = Math.Abs ( g.Key.gameDiff ) } ) .OrderByDescending ( x = > x.count ) .ThenBy ( x = > x.gameD...
Math Absolute In Ef Core ?
C#
I am trying to print a WPF visual ( a Canvas to be exact ) containing multiple images . The image sources are loaded from base64 strings that are converted to BitmapSources . When the canvas is shown in a Window the 2 images are displayed correctly , however when its printed using PrintVisual method of PrintDialog , th...
< Window x : Class= '' ImagePrintTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-com...
Printing a WPF Visual Containing Images
C#
First , this is not a duplicate of IEnumerable < T > as return type for WCF methods , I think I understand that the WCF architecture only allows concrete types to be transferred that can be stuffed into a message.Second , our setup however is not a general service but connecting up a bundle of proprietary apps via C # ...
interface IStuffProvider { IEnumerable < Stuff > GetItems ( ) ; // may open large file or access database } [ ServiceContract ( SessionMode = SessionMode.Required ) ] interface IStuffService { [ OperationContract ] void Reset ( ) ; // may open large file or access database [ OperationContract ] List < Stuff > GetNext (...
Getting IEnumerable < T > semantics with a NetTcpBinding WCF service ?
C#
So , I have a datagrid that has different colour cells depending on the cell 's value.I also have a tooltip that displays some further information . This all works fine.I , however , would like to alter the tooltip to show further information and also to be the same colour as the cell . So , I thought it would be wise ...
< Style TargetType= '' ToolTip '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' ToolTip '' > < Border CornerRadius= '' 15,15,15,15 '' BorderThickness= '' 3,3,3,3 '' Background= '' # AA000000 '' BorderBrush= '' # 99FFFFFF '' RenderTransformOrigin= '' 0.5,0.5 '' > < Grid > < Grid...
Control template : how to create bindings
C#
I being following the Unity Interception link , to implement Unity in my project.By , following a link I have made a class as shown below : Till now I have done nothing special , just followed the example as explained in the upper link . But , when I have to implement the Unity Interception class , I came up with lots ...
[ AttributeUsage ( AttributeTargets.Method ) ] public class MyInterceptionAttribute : Attribute { } public class MyLoggingCallHandler : ICallHandler { IMethodReturn ICallHandler.Invoke ( IMethodInvocation input , GetNextHandlerDelegate getNext ) { IMethodReturn result = getNext ( ) ( input , getNext ) ; return result ;...
Unity Interception Concept Clarity
C#
If you are parsing , lets just say HTML , once you read the element name , will it be beneficial to intern it ? The logic here is that this parser will parse the same strings ( element names ) over and over again ? And several documents will be parsed.Theory : This question was motivated by the question string-internin...
// elemName is checked for null.MarkupNode node = new MarkupNode ( ) { Name = String.IsInterned ( elemName ) ? elemName : String.Intern ( elemName ) , ... } ;
Will Interning strings help performance in a parser ?
C#
If anyone cares , I 'm using WPF ... .Beginning of story : I got a series of gray-scale images ( slices of a model ) . The user inputs a `` range '' of gray-scale values to build a 3D model upon . Thus I created a 3D bool array to make it easier to build the 3D model . This array represents a box of pixels , indicating...
cubeindex = 0 ; if ( grid.val [ 0 ] < isolevel ) cubeindex |= 1 ; if ( grid.val [ 1 ] < isolevel ) cubeindex |= 2 ; if ( grid.val [ 2 ] < isolevel ) cubeindex |= 4 ; if ( grid.val [ 3 ] < isolevel ) cubeindex |= 8 ; if ( grid.val [ 4 ] < isolevel ) cubeindex |= 16 ; if ( grid.val [ 5 ] < isolevel ) cubeindex |= 32 ; if...
How could I polygonise a bool [ , , ]
C#
How do you concatenate huge lists without doubling memory ? Consider the following snippet : The output is : I would like to keep memory usage to 2014 MB after concatenation , without modifying a and b .
Console.WriteLine ( $ '' Initial memory size : { Process.GetCurrentProcess ( ) .WorkingSet64 /1024 /1024 } MB '' ) ; int [ ] a = Enumerable.Range ( 0 , 1000 * 1024 * 1024 / 4 ) .ToArray ( ) ; int [ ] b = Enumerable.Range ( 0 , 1000 * 1024 * 1024 / 4 ) .ToArray ( ) ; Console.WriteLine ( $ '' Memory size after lists init...
How to concatenate lists without using extra memory ?
C#
I am having a huge problem in all browsers.I have a site where clients can download a csv file that contains detail they need.The problem I am having is that the csv file either downloads with no extension or as a htm file.In the code I am specifying the file name with .csv , the file on the server is also a .csv.The c...
context.Response.Buffer = true ; context.Response.Clear ( ) ; context.Response.ClearHeaders ( ) ; context.Response.ContentType = `` text/csv '' ; context.Response.AppendHeader ( `` Content-Disposition '' , @ '' attachment , filename= '' + ( ( string ) Path.GetFileName ( downloadFilePath ) ) ) ; context.Response.WriteFi...
CSV downloads as HTM
C#
Why is it not possible to have implicitly-typed variables at a class level within C # for when these variables are immediately assigned ? ie : Is it just something that has n't been implemented or is there a conceptual/technical reason for why it has n't been done ?
public class TheClass { private var aList = new List < string > ( ) ; }
var in C # - Why ca n't it be used as a member variable ?
C#
I 'm trying to save any logs I received from the application into a log table in my db and so far , nothing gets saved . I 'm using Log4net and AdoNetAppender for saving the logs into my table inside SQL Server . This code sits inside a Web API project on the server side of my app . I set up the logs as follows : 1 ) S...
< log4net > < appender name= '' AdoNetAppender '' type= '' log4net.Appender.AdoNetAppender '' > < bufferSize value= '' 1 '' / > < connectionType value= '' System.Data.SqlClient.SqlConnection , System.Data , Version=1.0.3300.0 , Culture=neutral , PublicKeyToken=token '' / > < connectionString value= '' data source=db ; ...
Logs do not get saved into Logs table
C#
I want to increase values on timer tick event but it is not increasing do n't know what I am forgetting it is showing only 1 .
< asp : Timer ID= '' Timer1 '' runat= '' server '' OnTick= '' Timer1_Tick '' Interval= '' 1000 '' > < /asp : Timer > private int i = 0 ; protected void Timer1_Tick ( object sender , EventArgs e ) { i++ ; Label3.Text = i.ToString ( ) ; }
Timer Tick not increasing values on time interval
C#
I have always included the at sign in the parameter name when using AddWithValue , but I just noticed some code written by someone else that does n't use it . Is one way more correct than the other ? or
cmd.Parameters.AddWithValue ( `` ixCustomer '' , ixCustomer ) ; cmd.Parameters.AddWithValue ( `` @ ixCustomer '' , ixCustomer ) ;
should I include the @ when using SqlCommand.Parameters.AddWithValue ?
C#
I 'm trying to record audio and immediately send it to IBM Watson Speech-To-Text for transcription . I 've tested Watson with a WAV file loaded from disk , and that worked . On the other end , I 've also tested with recording from microphone and storing it to disk , works good too . But when I try to record the audio w...
private async void StartHere ( ) { var ws = new ClientWebSocket ( ) ; ws.Options.Credentials = new NetworkCredential ( `` ***** '' , `` ***** '' ) ; await ws.ConnectAsync ( new Uri ( `` wss : //stream.watsonplatform.net/speech-to-text/api/v1/recognize ? model=en-US_NarrowbandModel '' ) , CancellationToken.None ) ; Task...
Recording WAV to IBM Watson Speech-To-Text
C#
I 'm using Entity Framework 6.1.1 and I have a Users table and a User_Documents table ( 1 : many ) . I already had a navigation property from User_Documents to User were things were working fine.I added a navigation property from Users to User_Documentsand now I 'm getting an error when I try to run the application : S...
public partial class User_Document { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public long User_Document_ID { get ; set ; } public long User_ID { get ; set ; } [ ForeignKey ( `` User_ID '' ) ] public virtual User User { get ; set ; } } public partial class User { [ Key ] [ DatabaseGenerated ( Datab...
Entity Framework getting confused about navigation property
C#
In other words , is functionally identical to Stated another way , isfunctionally identical toAccording to Task.Wait and Inlining , if the Task being Wait ’ d on has already started execution , Wait has to block . However , if it hasn ’ t started executing , Wait may be able to pull the target task out of the scheduler...
var task = SomeLongRunningOperationAsync ( ) ; task.Wait ( ) ; SomeLongRunningOperation ( ) ; var task = SomeOtherLongRunningOperationAsync ( ) ; var result = task.Result ; var result = SomeOtherLongRunningOperation ( ) ;
Is calling Task.Wait ( ) immediately after an asynchronous operation equivalent to running the same operation synchronously ?
C#
I 've been playing with a c # app that hosts IronPython , IronRuby , and ( hopefully ) PowerShell . Since IronPython and IronRuby were completely built on the DLR , the API for using them is pretty much identical . andboth create instances of a Microsoft.Scripting.Hosting.ScriptEngine . Is there any hope of coercing Po...
IronPython.Hosting.Python.CreateEngine ( ) IronRuby.Ruby.CreateEngine ( ) System.Management.Automation.PowerShell.Create ( )
How can I host PowerShell 3.0 in a c # app using a similar API to other DLR languages
C#
While reflecting with ILSpy i found this line of code in the Queue < T > .Enqueue ( T item ) -method : I 'm just wondering why somebody would do this ? I think it 's some kind of a integer overflow check , but why multiply first with 200L and then divide by 100L ? Might this have been a issue with earlier compilers ?
if ( this._size == this._array.Length ) { int num = ( int ) ( ( long ) this._array.Length * 200L / 100L ) ; if ( num < this._array.Length + 4 ) { num = this._array.Length + 4 ; } this.SetCapacity ( num ) ; }
Strange Queue < T > .Enqueue ( T item ) code
C#
I want to start the new On-Screen-Keyboard ( OSK ) using code . You can find this one in the taskbar : ( if not there you find it by right clicking the taskbar ) .I have already tried the regular : But I want to start the other one ( not in window mode ) . Here you see which OSK I want and which one not : How can I sta...
System.Diagnostics.Process.Start ( `` osk.exe '' ) ;
How to open the tablet-mode on-screen-keyboard in C # ?
C#
For some time I have had a custom Visual Studio code snippet to assist in injecting a copyright header in my C # source files . It looks something like this : The important thing to note for this question is the two trailing endlines at the end of the CDATA block . In editions of Visual Studio prior to 2015 , I could p...
< CodeSnippet Format= '' 1.0.0 '' xmlns= '' http : //schemas.microsoft.com/VisualStudio/2005/CodeSnippet '' > < Header > < Title > File Header < /Title > < Author > Me < /Author > < Shortcut > header < /Shortcut > < Description > Inserts a standard copyright header. < /Description > < SnippetTypes > < SnippetType > Exp...
Visual Studio 2015 Code Snippet with significant trailing whitespace
C#
Can I reduce this razor code ? I was trying this but it does n't work :
< li > @ { if ( @ Model.PublicationDate.HasValue ) { @ Model.PublicationDate.Value.ToString ( `` D '' , new System.Globalization.CultureInfo ( `` fr-FR '' ) ) } else { @ : '' pas disponible '' } } < /li > @ { ( @ Model.PublicationDate.HasValue ) ? ( @ Model.PublicationDate.Value.ToString ( `` D '' ) ) : ( @ : '' pas di...
Can I reduce razor code to just few lines ?
C#
So I 'm writing a `` dynamic '' Linq query . I 've created an `` options '' class that holds all of the dynamic options that can be a part of the query . Some of these option properties are List objects , which hold IDs of entities that I want to return that are part of many-to-many relationships in SQL Server . A quic...
public IEnumerable < Car > Search ( SearchOptions options ) { var query = from car in ctx.Cars select car ; // This works just fine if ( options.MaxMileage.HasValue ) query = query.Where ( x = > x.Mileage < = options.Mileage.Value ) ; // How do I implement this pseudo code . options.Colors is a List < int > if ( option...
LINQ & Many to Many Relationships
C#
We are using Machine.Specification as our test framework on my current project . This works well for most of what we are testing . However , we have a number of view models where we have 'formatted ' properties that take some raw data , apply some logic , and return a formatted version of that data . Since there is log...
public class DwellingInformation { public DateTime ? PurchaseDate { get ; set ; } public string PurchaseDateFormatted { if ( PurchaseDate == null ) return `` N/A '' ; return PurchaseDate.Value.ToShortDateString ( ) ; } public int ? ReplacementCost { get ; set ; } public string ReplacementCostFormatted { if ( Replacemen...
Does MSpec support `` row tests '' or data-driven tests , like NUnit TestCase ?
C#
Say I have the followingIs there any way to specify that my Func < T > parameters must obey some contracts ?
public T Example ( Func < T > f ) { Contract.Requires ( f ! = null ) ; Contract.Requires ( f ( ) ! = null ) ; // no surprise , this is an error ... }
Specify code contract on Func < T > parameters ?
C#
In a C # controller , I have a function defined with an optional parameter which is set to default to null ( see code example below ) . The first time the page loads , the function is called and the filter is passed in as an initialized object , despite the default value being null . I would like it to be null the firs...
public ActionResult MyControllerFunction ( CustomFilterModel filter = null ) { if ( filter == null ) doSomething ( ) ; // We never make it inside this `` if '' statement . // Do other things ... } routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // URL with parameters new { c...
Optional Parameters in C # - Defaulting a user-defined Class to null
C#
Given a CancellationToken , I want to call a 'cancel ' method on an object that represents an asynchronous operation when the CancellationToken is cancelled . Is this possible ? Background : I 'm interfacing with an API that represents an async op the following way ( more or less ) : I can wrap this in a method Task Do...
class AsyncOp { void Start ( Action callback ) ; //returns 'immediately ' , while beginning an async op . Callback is called when the operation completes . void Cancel ( ) ; //aborts async operation and calls callback }
How to run code when a CancellationToken is cancelled ?
C#
In C # it 's conventional to write in a fairly objective manner , like so : I could just write the above like this : However , how does the stackframe work when you have a bunch of function calls in a sequence like this ? The example is fairly straightforward but imagine if I 've got 50+ function calls chained ( this c...
MyObj obj = new MyObj ( ) ; MyReturn ret = obj.DoSomething ( ) ; AnotherReturn rett = ret.DoSomethingElse ( ) ; AnotherReturn rett = new MyObj ( ) .DoSomething ( ) .DoSomethingElse ( ) ;
C # : How do sequential function calls work ? ( efficiency-wise )
C#
An application I 'm working on processes Work Items . Depending on the state of a work item there are a number of actions available . `` Complete '' `` Cancel '' `` Reassign '' etc ... To provide the functionality for the actions I currently have an interface that looks something like this ... Then based on other detai...
public interface IActionProvider { public void Complete ( WorkItem workItem ) ; public void Cancel ( WorkItem workItem ) ; public void Reassign ( WorkItem workItem ) ; } public class NormalActionProvider : IActionProvider { ... } public class UrgentActionProvider : IActionProvider { ... . }
Recommend a design pattern
C#
Following is a complete console program that reproduces a strange error I have been experiencing . The program reads a file that contains urls of remote files , one per line . It fires up 50 threads to download them all.On my local computer it works fine . On the server , after downloading a few hundred images , it sho...
static void Main ( string [ ] args ) { try { string filePath = ConfigurationManager.AppSettings [ `` filePath '' ] , folder = ConfigurationManager.AppSettings [ `` folder '' ] ; Directory.CreateDirectory ( folder ) ; List < string > urls = File.ReadAllLines ( filePath ) .Take ( 10000 ) .ToList ( ) ; int urlIX = -1 ; Ta...
Multithread error not caught by catch
C#
Im trying to see some queries that my application using EntityFramework does.In my method wich is not async i can see the queries normally : But if its like : Is it possible to get the queries of a async method in IntelliTrace Events ? Thanks .
public List < Tool > GetTools ( ) { return EntityContext.ToList ( ) ; } public Task < List < Tool > > GetTools ( int quantity ) { return EntityContext.Take ( quantity ) .ToListAsync ( ) ; }
How to trace async database operations in Intellitrace Events ?
C#
Back when I was learning about foreach , I read somewhere that this : is basically equivalent to this : Why does this code even compile if neither IEnumerator nor IEnumerator < T > implement IDisposable ? C # language specification only seems to mention the using statement in the context of IDisposable.What does such a...
foreach ( var element in enumerable ) { // do something with element } using ( var enumerator = enumerable.GetEnumerator ( ) ) { while ( enumerator.MoveNext ( ) ) { var element = enumerator.Current ; // do something with element } }
Why does the using statement work on IEnumerator and what does it do ?
C#
We have a REST API method similar to : This is a fairly costly method with some complicated DB calls , and we have a common situation where hundreds of users with the same AccountId will make the call almost simultaneously ( they are all being notified with a broadcast ) .In the method , we cache the result set for 10 ...
List < item > GetItems ( int AccountID ) { var x = getFromCache ( AccountID ) ; if ( x==null ) { x = getFromDatabase ( AccountID ) ; addToCache ( AccountID , x ) ; } return x ; }
Pause simultaneous REST calls until first one completes
C#
Upon successful login I want to save a cookie which contains username.The cookie saves correctly and loads username correctly but loses session ! The code to retreive username is : The code to save username is : Any help will be greatly appreciated , Thank you
if ( Request.Cookies [ `` userName '' ] ! = null ) { txtEmail.Text = Request.Cookies [ `` username '' ] .Value ; chkRemember.Checked = true ; } HttpCookie aCookie = new HttpCookie ( `` username '' ) ; aCookie.Value = txtEmail.Text ; aCookie.Expires = DateTime.Now.AddYears ( 5 ) ; Response.Cookies.Add ( aCookie ) ;
Session lost when saving cookie
C#
Reading a Previous SO Question I was confused to find Eric Lippert saying that an interface can not be defined in C # for all Monads , using an implementation as below : My problem is all the problems listed in the question seem to have easy solutions : no `` higher kinded types '' = > use parent interfacesno static me...
typeInterface Monad < MonadType < A > > { static MonadType < A > Return ( A a ) ; static MonadType < B > Bind < B > ( MonadType < A > x , Func < A , MonadType < B > > f ) ; } using System ; using System.Linq ; public class Program { public static void Main ( ) { //it works , where 's the problem ? new SequenceMonad < i...
Here is the C # Monad , where is the problem ?
C#
Note : For Assert , using XunitAnonymous objects use value equality : Anonymous arrays with anonymous objects use value equality : Anonymous objects with nested arrays seem to use reference equality ( this fails ) : But this works ( presumably because there 's now reference equality ) : And this works ( so it appears I...
Assert.Equal ( new { foo = `` bar '' } , new { foo = `` bar '' } ) ; Assert.Equal ( new [ ] { new { foo = `` bar '' } } , new [ ] { new { foo = `` bar '' } } ) ; Assert.Equal ( new { baz = new [ ] { new { foo = `` bar '' } } , new { baz = new [ ] { new { foo = `` bar '' } } ) ; var baz = new [ ] { new { foo = `` bar ''...
In C # , how do you get recursive value equality for nested anonymous arrays and objects ?