text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I 'm a student and i 'm new around here . I have a course project to make a Paint-like program . I have a base class Shape with DrawSelf , Contains ect . methods and classes for Rectangle , Ellipse and Triangle for now . Also i have two other classed DisplayProccesor which is class for drawing , and DialogProcessor , which controls the dialog with the user . Theese are requirements for the project . And here ` s the other one : So , i want to rotate one shape , which is selected by the user.I try like this . It rotates it , but i get this : http : //www.freeimagehosting.net/qj3zp <code> public class DisplayProcessor { public DisplayProcessor ( ) { } /// < summary > /// List of shapes /// < /summary > private List < Shape > shapeList = new List < Shape > ( ) ; public List < Shape > ShapeList { get { return shapeList ; } set { shapeList = value ; } } /// < summary > /// Redraws all shapes in shapeList /// < /summary > public void ReDraw ( object sender , PaintEventArgs e ) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias ; Draw ( e.Graphics ) ; } public virtual void Draw ( Graphics grfx ) { int n = shapeList.Count ; Shape shape ; for ( int i = 0 ; i < = n - 1 ; i++ ) { shape = shapeList [ i ] ; DrawShape ( grfx , shape ) ; } } public virtual void DrawShape ( Graphics grfx , Shape item ) { item.DrawSelf ( grfx ) ; } } public class DialogProcessor : DisplayProcessor { public DialogProcessor ( ) { } private Shape selection ; public Shape Selection { get { return selection ; } set { selection = value ; } } private bool isDragging ; public bool IsDragging { get { return isDragging ; } set { isDragging = value ; } } private PointF lastLocation ; public PointF LastLocation { get { return lastLocation ; } set { lastLocation = value ; } } public void AddRandomRectangle ( ) { Random rnd = new Random ( ) ; int x = rnd.Next ( 100 , 1000 ) ; int y = rnd.Next ( 100 , 600 ) ; RectangleShape rect = new RectangleShape ( new Rectangle ( x , y , 100 , 200 ) ) ; rect.FillColor = Color.White ; ShapeList.Add ( rect ) ; } } public class RectangleShape : Shape { public override void DrawSelf ( Graphics grfx ) { grfx.TranslateTransform ( Rectangle.X + Rectangle.Width / 2 , Rectangle.Y + Rectangle.Height / 2 ) ; grfx.RotateTransform ( base.RotationAngle ) ; grfx.TranslateTransform ( - ( Rectangle.X + Rectangle.Width / 2 ) , - ( Rectangle.Y + Rectangle.Height / 2 ) ) ; grfx.FillRectangle ( new SolidBrush ( FillColor ) , Rectangle.X , Rectangle.Y , Rectangle.Width , Rectangle.Height ) ; grfx.DrawRectangle ( Pens.Black , Rectangle.X , Rectangle.Y , Rectangle.Width , Rectangle.Height ) ; grfx.ResetTransform ( ) ; } } | When rotating shape , it stays together with the rotated one |
C_sharp : On my production server I have set environment variable by adding the following to /etc/environment : I checked it has recorded with printenv ASPNETCORE_ENVIRONMENT after a reboot.My server is Ubuntu 14.04 and I am using asp.net core 1.1.It is loading my appsettings.Development.json instead of appsettings.Production.json.This is my startup.cs contructorInside my log file I can correctly see it says Hosting environment : Production but if I output values from configuration file to view then it is values from contents of appsettings.Development.json.I even tried deleting appsettings.Development.json from server and rebooting entire server but it still pulls the same values I guess it must be compiled somewhere . I have also tried adding this to .csproj : My settings files appear nested inside VS2017 like this : The default appsettings.json just has a defualt value for logging , it does n't contain the values I am pulling.I ca n't figure out what the issue is . <code> ASPNETCORE_ENVIRONMENT=Production public Startup ( IHostingEnvironment env ) { var builder = new ConfigurationBuilder ( ) .SetBasePath ( env.ContentRootPath ) .AddJsonFile ( `` appsettings.json '' , optional : false , reloadOnChange : true ) .AddJsonFile ( $ '' appsettings . { env.EnvironmentName } .json '' , optional : true ) .AddEnvironmentVariables ( ) ; Configuration = builder.Build ( ) ; } < ItemGroup > < None Include= '' appsettings . *.json '' CopyToPublishDirectory= '' Always '' / > < /ItemGroup > | Ca n't set production server to production |
C_sharp : Is it true that if i use the following , it will take less resources and the cleanup will be faster ? as compared to : <code> using ( TextReader readLogs = File.OpenText ( `` C : \\FlashAuto\\Temp\\log.txt '' ) ) { //my stuff } TextReader readLogs = new StreamReader ( `` C : \\FlashAuto\\Temp\\log.txt '' ) ; //my stuffreadLogs.Close ( ) ; readLogs.Dispose ( ) ; | using keyword takes less space ? |
C_sharp : There are several options when one class must have a container ( collection ) of some sort of objects and I was wondering what implementation I shall prefer.Here follow the options I found : Pros : AClass is not dependent on a concrete implementation of a collection ( in this case List ) .Cons : AClass does n't have interface for Adding and removing elementsPros : Same as IEnumerable plus it have interface for adding and removing elementsCons : The ICollection interface define other methods that one rarely uses and it get 's boring to implement those just for the sake of the interface . Also IEnumerable LINQ extensions takes care of some of those.Pros : No need of implementing any method . Caller may call any method implemented by ListCons : AClass is dependent on collection List and if it changes some of the caller code may need to be changed . Also AClass ca n't inherit any other class.The question is : Which one shall I prefer to state that my class contains a collection supporting both Add and Remove operations ? Or other suggestions ... <code> public class AClass : IEnumerable < string > { private List < string > values = new List < string > ( ) IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } public IEnumerator < T > GetEnumerator ( ) { return values.GetEnumerator ( ) ; } } public class AClass : ICollection < string > { private List < string > values = new List < string > ( ) IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } public IEnumerator < T > GetEnumerator ( ) { return values.GetEnumerator ( ) ; } //other ICollectionMembers } public class AClass : List < string > { } | Having a collection in class |
C_sharp : We have a problem with AppFabric that is causing the below error to occur : This error happens infrequently in our test environment ( we have not found a scenario to reproduce the issue on demand ) , but seems to always happen in our production environment just after each deployment . Our deployments are automated and we have verified that the steps to deploy to our various environments are the same.Our server setup for a given environment is as follows : Server1 - Hosts our .net website , and is our AppFabric 1.1 serverServer2 - Hosts our .net websiteThese servers are load balanced . AppFabric local caching has been enabled on both applications . Our test and production servers are setup the same . We are aware that it would be better to have AppFabric on a dedicated server , but do n't think that would cause/resolve this issue.We are stumped by this issue as we have not found any mention of it elsewhere online and because the stack trace seems to indicate that it is a problem with AppFabric itself . The exception mentions inserting something , but all we are doing when this happens is trying to get the default cache from the DataCacheFactory so that we can retrieve an item from it . So , what does this error mean and how might we resolve it ? UpdateHere is the code I am using to create the DataCacheFactory and pull data from the cache : <code> Exception type : ArgumentException Exception message : An item with the same key has already been added . at System.Collections.Generic.Dictionary ` 2.Insert ( TKey key , TValue value , Boolean add ) at Microsoft.ApplicationServer.Caching.DataCacheFactory.CreateRoutingClient ( String cacheName , NamedCacheConfiguration config ) at Microsoft.ApplicationServer.Caching.DataCacheFactory.CreateNewCacheClient ( DataCacheDeploymentMode mode , String cacheName , NamedCacheConfiguration config , IClientChannel channel ) at Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache ( String cacheName ) at Microsoft.ApplicationServer.Caching.DataCacheFactory.GetDefaultCache ( ) ... our code where we are attempting to retrieve a cache item from the default cache by its key private static readonly Lazy < DataCacheFactory > _DATA_CACHE_FACTORY = new Lazy < DataCacheFactory > ( ( ) = > new DataCacheFactory ( ) ) ; private static readonly Lazy < DataCache > _CACHE = new Lazy < DataCache > ( ( ) = > _DATA_CACHE_FACTORY.Value.GetDefaultCache ( ) ) ; public object Get ( string key ) { return _CACHE.Value.Get ( key ) ; } | AppFabric CreateRoutingClient Error |
C_sharp : I have IdentityServer4 with Angular . Every 5 minutes the token is silent refreshed . But after 30minutes the user is automatically logged out . I was trying to set lifetime cookies somehow , without any success . This is my current configuration : @ EDITIf I will addThen it working fine , but I bet this is not correct solution for my issue . @ EDIT2I found thishttps : //github.com/IdentityModel/oidc-client-js/issues/911 # issuecomment-617724445and this helped me , but still not sure whether is proper way to solve it or it just next hack . <code> public void ConfigureServices ( IServiceCollection services ) { services.AddDbContext < AppIdentityDbContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` Identity '' ) ) ) ; services.AddIdentity < AppUser , IdentityRole > ( options = > { options.Password.RequiredLength = 6 ; options.Password.RequireLowercase = false ; options.Password.RequireUppercase = false ; options.Password.RequireNonAlphanumeric = false ; options.Password.RequireDigit = false ; options.SignIn.RequireConfirmedEmail = true ; options.User.RequireUniqueEmail = true ; options.User.AllowedUserNameCharacters = null ; } ) .AddEntityFrameworkStores < AppIdentityDbContext > ( ) .AddDefaultTokenProviders ( ) ; services.AddIdentityServer ( options = > options.Authentication.CookieLifetime = TimeSpan.FromHours ( 10 ) ) .AddDeveloperSigningCredential ( ) .AddInMemoryPersistedGrants ( ) .AddInMemoryIdentityResources ( Config.GetIdentityResources ( ) ) .AddInMemoryApiResources ( Config.GetApiResources ( ) ) .AddInMemoryClients ( Config.GetClients ( Configuration [ `` AppUrls : ClientUrl '' ] ) ) .AddAspNetIdentity < AppUser > ( ) ; services.AddTransient < IProfileService , IdentityClaimsProfileService > ( ) ; services.AddCors ( options = > options.AddPolicy ( `` AllowAll '' , p = > p.AllowAnyOrigin ( ) .AllowAnyMethod ( ) .AllowAnyHeader ( ) ) ) ; services.AddRazorPages ( ) .AddRazorRuntimeCompilation ( ) ; } services.Configure < SecurityStampValidatorOptions > ( options = > { options.ValidationInterval = TimeSpan.FromHours ( 24 ) ; } ) ; | IdentityServer4 automatically logout after 30 minutes |
C_sharp : Hey , I 'm self-learning about bitwise , and I saw somewhere in the internet that arithmetic shift ( > > ) by one halfs a number . I wanted to test it : Another Example : Thanks . <code> 44 > > 1 returns 22 , ok22 > > 1 returns 11 , ok11 > > 1 returns 5 , and not 5.5 , why ? 255 > > 1 returns 127127 > > 1 returns 63 and not 63.5 , why ? | Why arithmetic shift halfs a number only in SOME incidents ? |
C_sharp : I have a .NET Core worker project and want to add a library providing several HTTP endpoints . I have to stay with the worker project , I ca n't change it to a Web API project . What I have done so far : I created a worker projectI created a library projectI added a reference to the library in the worker projectIn the Worker.csproj and Lib.csproj I added < FrameworkReference Include= '' Microsoft.AspNetCore.App '' / > to the item group to gain access to the webbuilder stuffI installed the package Microsoft.AspNetCore.Mvc.Core in the library projectIn the library project I add several extensions classes and a web API controller for testing purposes.In the worker project I created a Startup class.In the worker project I modified the Program class to.I run the project and call GET http : //localhost:5000/usersI would expect a 200 but get a 404 and the debugger does not hit the controller endpoint in the library projectDoes someone know what I 'm missing ? It is possible for me to Add Web API controller endpoint to Kestrel worker project but it is not possible for me to add web controllers to a library project and call them from the library . <code> public static class IApplicationBuilderExtensions { public static IApplicationBuilder AddLibrary ( this IApplicationBuilder applicationBuilder ) { applicationBuilder.UseRouting ( ) ; applicationBuilder.UseEndpoints ( endpoints = > { endpoints.MapControllers ( ) ; } ) ; return applicationBuilder ; } } public static class IServiceCollectionExtensions { public static IServiceCollection AddLibrary ( this IServiceCollection services ) { services.AddMvc ( ) ; // this might be not needed services.AddControllers ( ) ; return services ; } } public static class KestrelServerOptionsExtensions { public static void AddLibrary ( this KestrelServerOptions kestrelServerOptions ) { kestrelServerOptions.ListenLocalhost ( 5000 ) ; // value from config } } [ ApiController ] [ Route ( `` [ controller ] '' ) ] public class UsersController : ControllerBase { [ HttpGet ] public async Task < ActionResult > Test ( ) { return Ok ( ) ; } } internal class Startup { public void ConfigureServices ( IServiceCollection services ) { services.AddLibrary ( ) ; } public void Configure ( IApplicationBuilder applicationBuilder ) { applicationBuilder.AddLibrary ( ) ; } } public class Program { public static void Main ( string [ ] args ) { CreateHostBuilder ( args ) .Build ( ) .Run ( ) ; } public static IHostBuilder CreateHostBuilder ( string [ ] args ) = > Host.CreateDefaultBuilder ( args ) .ConfigureWebHostDefaults ( webHostBuilder = > { webHostBuilder.UseKestrel ( kestrelServerOptions = > { kestrelServerOptions.AddLibrary ( ) ; } ) .UseStartup < Startup > ( ) ; } ) .ConfigureServices ( ( hostContext , services ) = > { services.AddHostedService < Worker > ( ) ; } ) ; } | register Web API controller from class library |
C_sharp : I am trying to convert the ffg : ,This Worksinto this , which does not work , It gives me an error that it can not find `` COLUMNS '' .While debugging , it seems that rs is picking up all the return methods and private variables in the SELECT class it just is not picking up the method like COLUMNS in the SELECT class at runtime . This is very odd , I expected it to also pick up the methods , I am doing something wrong ? ? ? UPDATEThe definition for db in db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) ; isThe definition for SELECT in db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) ; which is an interface to my SELECT class ; This is where the problem lies , the dynamic object is not picking up the methods in the interface , it picks up all private variables and the only method it picks up is `` DISTINCT '' .Below is part of the definition of the SELECT class , there is alot of code in it so I will just put a little ; etc . <code> IResultSEt rs = db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) .FROM ( data.ToString ( ) ) .Execute ( ) ; dynamic rs = db.SELECT.COLUMNS ( db.GetTable ( data.ToString ( ) ) .ColumnNames ) ; rs = rs.FROM ( data.ToString ( ) ) ; rs = rs.Execute ( ) ; public class Database { private Dictionary < string , ITable > _tables = new Dictionary < string , ITable > ( ) ; public ITable AddTable ( string tableName , string [ ] columnNames , Type [ ] columnTypes ) { ITable tbl = new Table ( tableName ) ; tbl.SetColumns ( columnNames , columnTypes ) ; _tables.Add ( tableName.ToUpper ( ) , tbl ) ; return tbl ; } public ITable GetTable ( string tableName ) { return _tables [ tableName.ToUpper ( ) ] ; } public ISELECT SELECT { get { ISELECT select = new SELECT ( this ) ; return select ; } } public Dictionary < string , ITable > getTables ( ) { return _tables ; } } public interface ISELECT { ISELECT TOP ( Int32 N ) ; ISELECT DISTINCT { get ; } ISELECTCOLUMN COLUMN ( string columnName ) ; ISELECTTABLECOLUMN COLUMN ( string tableName , string columnName ) ; ISELECTCOLUMNS COLUMNS ( params string [ ] columnNames ) ; ISELECTSUMCOLUMN SUM ( string columnName ) ; ISELECTSUMCOLUMN SUM ( string tableName , string columnName ) ; } internal class SELECT : ISELECT , ISELECTInternals { private Database _dw ; private bool _DISTINCT ; private Int32 _TOPN = -1 ; private List < Int32 > _JOINNumbers = new List < Int32 > ( ) ; private string [ ] _selectJOINLHScolumnTableNames ; private string [ ] _selectJOINLHScolumnNames ; private string [ ] _selectJOINRHScolumnTableNames ; private string [ ] _selectJOINRHScolumnNames ; private string [ ] _selectcolumnTableNames ; private string [ ] _selectcolumnNames ; private string [ ] _selectcolumnAliases ; private object [ ] _selectcolumnLiterals ; private string [ ] _selectcolumnStringTemplates ; private AggregateTypes [ ] _selectcolumnAggregates ; private string [ ] _queryTableNames ; private string _SUMcolumnName ; private string _FROMTableName ; private List < string > _INNERJOINTableNames = new List < string > ( ) ; private List < string > _JOINTableNames = new List < string > ( ) ; private List < JoinTypes > _TableJoinTypes = new List < JoinTypes > ( ) ; private bool _takeANDFlag = true ; private List < string > _filterColumnTableNames = new List < string > ( ) ; private List < string > _filterColumnNames = new List < string > ( ) ; private List < object [ ] > _filterColumnValues = new List < object [ ] > ( ) ; private List < string > _GROUPBYcolumnTableNames = new List < string > ( ) ; private List < string > _GROUPBYcolumnNames = new List < string > ( ) ; | Dynamic object not showing its methods |
C_sharp : I work in C # , so I 've posted this under C # although this may be a question that can be answered in any programming language.Sometimes I will create a method that will do something such as log a user into a website . Often times I return a boolean from the method , but this often causes problems because a boolean return value does n't convey any context . If an error occurs whilst logging the user in I have no way of knowing what caused the error . Here is an example of a method that I currently use , but would like to change so that it returns more than just 0 or 1.The above method can only return True or False . This works well because I can just call the following : But the problem is I have no way of knowing why the user was n't logged in . A number of reasons could exist such as : wrong username/password combination , suspended account , account requires users attention etc . But using the following method , and logic , it is n't possible to know this.What alternative approaches do I have ? <code> public bool LoginToTwitter ( String username , String password ) { // Some code to log the user in } if ( http.LoginToTwitter ( username , password ) ) { // Logged in } else { // Not Logged in } | Methods that return meaningful return values |
C_sharp : Consider the following code : I 'm trying to keep an instance of a generic class in a property for later usage , but as you know : Properties , events , constructors etc ca n't be generic - only methods and types can be generic . Most of the time that 's not a problem , but I agree that sometimes it 's a pain ( Jon Skeet ) I want to know is this a good way to round this situation ? <code> public dynamic DataGrid { get ; private set ; } public DataGridForm < TData , TGrid > GridConfig < TData , TGrid > ( ) where TData : class { return DataGrid = new DataGridForm < TData , TGrid > ( ) ; } | Using dynamic type instead of none-possible generic properties |
C_sharp : How does the compiler handle interpolated strings without an expressions ? Will it still try to format the string ? How does the compiled code differ from that of one with an expression ? <code> string output = $ '' Hello World '' ; | How does C # string interpolation without an expression compile ? |
C_sharp : Anyone have any ideas why this does n't work ( C # or VB.NET or other .NET language does n't matter ) . This is a very simplified example of my problem ( sorry for VB.NET ) : If you do : You will be surprised at the result . It will print `` Nothing '' . Anyone have any idea why it does n't print `` Something '' Here 's a Unit Test per suggestion : This returns : <code> Private itsCustomTextFormatter As String Public Property CustomTextFormatter As String Get If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not ' Return itsCustomTextFormatter End Get Set ( ByVal value As String ) If value Is Nothing Then value = `` Something '' End If itsCustomTextFormatter = value End Set End Property Dim myObj as new MyClassConsole.WriteLine ( myObj.CustomTextFormatter ) Imports NUnit.Framework < TestFixture ( ) > _Public Class Test Private itsCustomTextFormatter As String Public Property CustomTextFormatter As String Get If itsCustomTextFormatter Is Nothing Then CustomTextFormatter = Nothing 'thinking this should go into the setter - strangely it does not ' Return itsCustomTextFormatter End Get Set ( ByVal value As String ) If value Is Nothing Then value = `` Something '' End If itsCustomTextFormatter = value End Set End Property < Test ( ) > Public Sub Test2 ( ) Assert.AreEqual ( `` Something '' , CustomTextFormatter ) End SubEnd Class Test2 : Failed Expected : `` Something '' But was : nullat NUnit.Framework.Assert.That ( Object actual , IResolveConstraint expression , String message , Object [ ] args ) at NUnit.Framework.Assert.AreEqual ( Object expected , Object actual ) | Interesting Property Behavior |
C_sharp : Say I have a rather expensive assertion : If I test this assertion with : Will IsCompatible be executed in release builds ? My understanding is that Debug.Assert being marked as [ Conditional ( `` DEBUG '' ) ] , calls to it will only be emitted in debug builds . I 'm thinking that this wo n't prevent the expression from being evaluated in release mode though , since the method call may have side effects , only the passing of the result to Debug.Assert would n't be emitted . Is that correct ? Should I be doing : To ensure that I do n't pay the cost of IsCompatible in release mode ? <code> bool IsCompatible ( Object x , Object y ) { // do expensive stuff here } Debug.Assert ( IsCompatible ( x , y ) ) ; # if DEBUGDebug.Assert ( IsCompatible ( x , y ) ) ; # endif | Will the expression provided to Debug.Assert be evaluated in a release build ? |
C_sharp : This code fails only in Release mode at Assert.Fail ( ) line despite the fact relay variable is still in scope and thus we still have strong reference to the instance , so WeakReference must not be dead yet.UPD : To clarify a bit : I realize that it can be 'optimized away ' . But depending on this optimization indicator variable would have 0 or 1 value , i.e . we have actual visible change of behavior.UPD2 : From C # language specification , section 3.9 If the object , or any part of it , can not be accessed by any possible continuation of execution , other than the running of destructors , the object is considered no longer in use , and it becomes eligible for destruction . The C # compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future . For instance , if a local variable that is in scope is the only existing reference to an object , but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure , the garbage collector may ( but is not required to ) treat the object as no longer in use.Technically speaking , this object can and will be accessed by continuation of execution and thus ca n't be treated as 'no longer in use ' ( actually C # spec says nothing about weak references because it is aspect of CLR and not the compiler - compiler output is fine ) . Will try to search for memory management info about CLR/JIT.UPD3 : Here is some info on CLR 's memory management - section 'Releasing memory ' : ... Every application has a set of roots . Each root either refers to an object on the managed heap or is set to null . An application 's roots include global and static object pointers , local variables and reference object parameters on a thread 's stack , and CPU registers . The garbage collector has access to the list of active roots that the just-in-time ( JIT ) compiler and the runtime maintain . Using this list , it examines an application 's roots , and in the process creates a graph that contains all the objects that are reachable from the roots.Variable in question is definitely local variable , hence it is reachable . Thus said , this mention is very quick/vague , so I would be really glad to see more concrete info.UPD4 : From sources of .NET Framework : See here for my investigation in more details , if you 're interested . <code> [ TestFixture ] public class Tests { private class Relay { public Action Do { get ; set ; } } [ Test ] public void OptimizerStrangeness ( ) { var relay = new Relay ( ) ; var indicator = 0 ; relay.Do = ( ) = > indicator++ ; var weak = new WeakReference ( relay ) ; GC.Collect ( ) ; var relayNew = weak.Target as Relay ; if ( relayNew == null ) Assert.Fail ( ) ; relayNew.Do ( ) ; Assert.AreEqual ( 1 , indicator ) ; } } // This method DOES NOT DO ANYTHING in and of itself . It 's used to // prevent a finalizable object from losing any outstanding references // a touch too early . The JIT is very aggressive about keeping an // object 's lifetime to as small a window as possible , to the point // where a 'this ' pointer is n't considered live in an instance method // unless you read a value from the instance . So for finalizable // objects that store a handle or pointer and provide a finalizer that // cleans them up , this can cause subtle -- -- s with the finalizer // thread . This is n't just about handles - it can happen with just // about any finalizable resource . // // Users should insert a call to this method near the end of a // method where they must keep an object alive for the duration of that // method , up until this method is called . Here is an example : // // `` ... all you really need is one object with a Finalize method , and a // second object with a Close/Dispose/Done method . Such as the following // contrived example : // // class Foo { // Stream stream = ... ; // protected void Finalize ( ) { stream.Close ( ) ; } // void Problem ( ) { stream.MethodThatSpansGCs ( ) ; } // static void Main ( ) { new Foo ( ) .Problem ( ) ; } // } // // // In this code , Foo will be finalized in the middle of // stream.MethodThatSpansGCs , thus closing a stream still in use . '' // // If we insert a call to GC.KeepAlive ( this ) at the end of Problem ( ) , then // Foo does n't get finalized and the stream says open . [ System.Security.SecuritySafeCritical ] // auto-generated [ ResourceExposure ( ResourceScope.None ) ] [ MethodImplAttribute ( MethodImplOptions.InternalCall ) ] [ ReliabilityContract ( Consistency.WillNotCorruptState , Cer.Success ) ] public static extern void KeepAlive ( Object obj ) ; | Is it really a bug in JIT optimization or am I missing something ? |
C_sharp : There are multiple questions ( 1,2,3,4 etc . etc . ) called `` Why is n't this exception caught '' . Sadly , none of these solutions work for me ... So I am stuck with a truly uncatchable exception.I have a piece of code ( .NET 4.0 ) that checks a large textfile for digits and numbers . Whilst testing I got a runtime exception : What you see here is a try-catch pattern with a catchblock for an ArgumentOutOfRangeException . But during runtime , the try block throws an ArgumentOutOfRangeException that is not being caught.I read the C # language specification section about the try-catch structure , and it says : A catch block of a try statement is reachable if the try statement is reachable.So in theory the above code should catch the exception.Then I thought it might had something to do with the fact that this code is running in a task ( during the processing of the textfile I also want to update the UI so I do it asynchronous ) . I searched around and then I found this answer by Jon Skeet . Basically suggesting I use Task.Wait in a try-catch block to catch any exceptions.The problem I am facing now is that I ca n't really call Task.Wait because that would block the calling thread which is my UI thread ! Then I figured that I could create an extra tasklayer to wait for that task : But this still gives the same result ... Then I thought that it could be because of the fact I am not specific enough with my Exceptiontype . But the C # Language Specification states : Some programming languages may support exceptions that are not representable as an object derived from System.Exception , although such exceptions could never be generated by C # code . So unless you use some sketchy third party API you 're always good when you use Exception . So I found myself with an suggested answer by Jon Skeet that did n't quite work for me . That 's when I knew I should just stop trying ... So does anyone know what is going on ? And how can I fix this ? I know I could just check if i is equal or bigger than text.Length but understanding what 's happening is more important than working code . <code> //Code called from the UISystem.Threading.Tasks.Task.Factory.StartNew ( ( ) = > { //Create a new task and use this task to catch any exceptions System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew ( MethodWithException ) ; try { task.Wait ( ) ; } catch ( Exception ) { MessageBox.Show ( `` Caught it ! `` ) ; } } ) ; | Moby Dick of exceptions |
C_sharp : I 'm new to C # and working on a snake project . I 'm trying to make it rainbow coloured , is there a better way to switch between six colours and then repeat ? Any suggestions ? <code> public Brush Colour ( int i ) { Brush snakeColour ; switch ( i ) { case 0 : case 6 : case 12 : case 18 : case 24 : snakeColour = Brushes.HotPink ; break ; case 1 : case 7 : case 13 : case 19 : case 25 : snakeColour = Brushes.Orange ; break ; case 2 : case 8 : case 14 : case 20 : case 26 : snakeColour = Brushes.PeachPuff ; break ; etc . default : snakeColour = Brushes.White ; break ; } return snakeColour ; } | Better way to switch Brush colours ? |
C_sharp : When using extremely short-lived objects that I only need to call one method on , I 'm inclined to chain the method call directly to new . A very common example of this is something like the following : The point here is that I have no need for the Regex object after I 've done the one replacement , and I like to be able to express this as a one-liner . Is there any non-obvious problem with this idiom ? Some of my coworkers have expressed discomfort with it , but without anything that seemed to be like a good reason . ( I 've marked this as both C # and Java , since the above idiom is common and usable in both languages . ) <code> string noNewlines = new Regex ( `` \\n+ '' ) .Replace ( `` `` , oldString ) ; | Any reason not to use ` new object ( ) .foo ( ) ` ? |
C_sharp : Compiler warning CS4014 ( calling async method without awaiting result ) is not emitted as a warning during build when the called method is in a referenced assembly.When the called method is in the same assembly the warning is correctly emitted.The compiler warning is signaled in Visual Studio when both projects are contained in the same solution.The difference seems to be caused by the compiler having only the compiled referenced assembly and Visual Studio having the source code to both assemblies.The question is : why have these two different behaviors ? And is there any way to have the CS4014 warning emitted during compilation ? To replicate this behavior setup two class libraries , both having one code file : TestClassLibrary1TestClassLibrary2 ( referencing TestClassLibrary1 ) Compiling these projects will complete without warnings . Opening them in the same solution in Visual Studio will result in 1 error being shown in the Error List and a red squiggly line under Class1.DoSomething ( ) . <code> public class Class1 { public static async Task < string > DoSomething ( ) { return await Task.FromResult ( `` test '' ) ; } } public class Class2 { public void CallingDoSomething ( ) { Class1.DoSomething ( ) ; } } | Compiler warning CS4014 not emitted during build |
C_sharp : Most of the Q & A I found on StackOverflow is how Binding work but x : Bind does n't which usually solved by Bindings.Update ( ) . However , my issue is , inside a GridView , ItemSource= '' { x : Bind _myList } '' works but ItemSource= '' { Binding _myList } '' does n't . Why ? And how do I make Binding work ? ( instead of x : Bind ) Here 's a few code thingies : Class : Code BehindXAML ( does n't work here but works if ItemSource : changed into x : Bind _myList ) <code> public class MyClass { public string prop1 { get ; set ; } public string prop2 { get ; set ; } } public class MyList : List < MyClass > { public void Populate ( ) // Add items } public MyList _myList = new MyList ( ) ; _myList.Populate ( ) ; DataContext = this ; Bindings.Update ( ) ; < GridView ItemSource= '' { Binding _myList } '' > < GridView.ItemTemplate > < DataTemplate > < StackPanel > < TextBlock Text= '' { Binding prop1 } '' / > < TextBlock Text= '' { Binding prop2 } / > < /StackPanel > < /DataTemplate > < /GridView.ItemTemplate > < /GridView > | x : Bind works but Binding does n't ( opposite to most Q & A found ) |
C_sharp : If you compile the following code : And then decompile it ( I used dotPeek ) and examine the all-important MoveNext method , you will see a bool variable declared near the beginning ; dotPeek chose `` flag '' for me.In this case , you will see one subsequent consumer of that variable , in the default case statement after initiating the first async call : I 've tried half a dozen more complicated examples than my initial one , and they are consistent in only assigning to this variable before exiting the method . So in other words , in all the cases I 've tried so far , this variable is not only never consumed , but is only given a non-initial value immediately before returning from the method -- a point in time where the assignment is definitionally useless . As background , I am enjoying the process of trying to implement async/await in Javascript via a C # - > JS cross-compiler . I 'm trying to understand in what situation I need to consider the utility of this flag . At face , it seems spurious and therefore I should ignore it . However , I 'd like to understand why the C # compiler introduces this variable -- I suspect there are more complicated expressions that consume this variable in a useful way . To put is succinctly : Why does the C # compiler generate this flag variable ? <code> private async Task < int > M ( ) { return await Task.FromResult ( 0 ) ; } bool flag = true ; if ( ! awaiter.IsCompleted ) { this.\u003C\u003E1__state = 0 ; this.\u003C\u003Eu__\u0024awaiter11 = awaiter ; this.\u003C\u003Et__builder.AwaitUnsafeOnCompleted < TaskAwaiter < int > , Program.\u003CP\u003Ed__10 > ( ref awaiter , ref this ) ; flag = false ; return ; } | Why does a bool `` flag '' get generated for the async/await state machine ? |
C_sharp : First , I apologize if this is not an appropriate venue to ask this question , but I was n't really sure where else to get input from.I have created an early version of a .NET object persistence library . Its features are : A very simple interface for persistence of POCOs.The main thing : support for just about every conceivable storage medium . This would be everything from plain text files on the local filesystem , to embedded systems like SQLite , any standard SQL server ( MySQL , postgres , Oracle , SQL Server , whatever ) , to various NoSQL databases ( Mongo , Couch , Redis , whatever ) . Drivers could be written for nearly anything , so for instance you could fairly easily write a driver where the actual backing store could be a web-service.When I first had this idea I was convinced it was totally awesome . I quickly created an initial prototype . Now , I 'm at the 'hard part ' where I am debating issues like connection pooling , thread safety , and debating whether to try to support IQueryable for LINQ , etc . And I 'm taking a harder look at whether it is worthwhile to develop this library beyond my own requirements for it.Here is a basic example of usage : The querying interface that works right now looks like : I am also working on an alternative query interface that lets you just pass in something very like a SQL WHERE clause . And obviously , in the NET world it would be great to support IQueryable / expression trees.Because the library supports many storage mediums with disparate capabilities , it uses attributes to help the system make the best use of each driver.All of the attributes are optional , and are basically all about performance . In a simple case you do n't need any of them.In a SQL environment , the system will by default take care of creating tables and indexes for you , though there is a DbaSafe option that will prevent the system from executing DDLs.It is also fun to be able to migrate your data from , say , a SQL engine to MongoDB in one line of code . Or to a zip file . And back again.OK , The Question : The root question is `` Is this useful ? '' Is it worth taking the time to really polish , make thread-safe or connection pooled , write a better query interface , and upload somewhere ? Is there another library already out there that already does something like this , NAMELY , providing a single interface that works across multiple data sources ( beyond just different varieties of SQL ) ? Is it solving a problem that needs to be solved , or has someone else already solved it better ? If I proceed , how do you go about trying to make your project visible ? Obviously this is n't a replacement for ORMs ( and it can co-exist with ORMs , and coexist with your traditional SQL server ) . I guess its main use cases are for simple persistence where an ORM is overkill , or for NoSQL type scenarios and where a document-store type interface is preferable . <code> var to1 = new TestObject { id = `` fignewton '' , number = 100 , FruitType = FruitType.Apple } ; ObjectStore db = new SQLiteObjectStore ( `` d : /objstore.sqlite '' ) ; db.Write ( to1 ) ; var readback = db.Read < TestObject > ( `` fignewton '' ) ; var readmultiple = db.ReadObjects < TestObject > ( collectionOfKeys ) ; var appleQuery = new Query < TestObject > ( ) .Eq ( `` FruitType '' , FruitType.Apple ) .Gt ( `` number '' ,50 ) ; var results = db.Find < TestObject > ( appleQuery ) ; [ TableName ( `` AttributeTest '' ) ] [ CompositeIndex ( `` AutoProperty '' , '' CreatedOn '' ) ] public class ComplexTypesObject { [ Id ] public string id ; [ QueryableIndexed ] public FruitType FruitType ; public SimpleTypesObject EmbeddedObject ; public string [ ] Array ; public int AutoProperty { get ; set ; } public DateTime CreatedOn = DateTime.Now ; } | Is my idea for an object persistence library useful ? |
C_sharp : I am trying to write a code generator using a c # console application . Now when I type this , I receive an error : It says `` input in wrong format '' I have checked that all the variables were strings , and they are . When I tried It worked perfectly fine . Is there a way to fix this ? <code> Console.WriteLine ( `` sphere { { 0 } { 1 } { 2 } texture { Gold_Metal } } '' , pre , i.ToString ( ) , sprad.ToString ( ) ) ; Console.WriteLine ( `` sphere { 0 } { 1 } { 2 } textureGold_Metal '' , pre , i.ToString ( ) , sprad.ToString ( ) ) ; | Writing scope ( { ) into string in console app |
C_sharp : Today , I was doing some tests in .NET Core , and I have come across some interesting thing.Before ( ~ .NET Framework 4 ) , Random used Environment.TickCount , but now I believe this has changed.Consider the following code : In older .NET Framework versions , the new Random ( ) empty constructor would use Environment.TickCount , which would lead to repetition of pseudo-random values.So you could expect results like : so on and so fourth.On the latest .NET Core version using the latest compiler , I have received the following result : Which is definitely improved.Other S.O questions demonstrating this behaviour in older versions : How do I generate a random int number ? generate random numbers with no repeat in c # Non-repetitive random numberIs C # Random Number Generator thread safe ? My setup : .NET Core 2.2 / latest C # compiler.The actual questionSo my question is , has the PRNG really improved or they just changed constructor to use another default seeds , and , if so , what they 're using as a seed ? Is it safer now for cryptography ( if they actually changed the implementation ) ? <code> while ( true ) { Random random = new Random ( ) ; Console.WriteLine ( random.Next ( 0 , 10000 ) ) ; } 542421152445244524495019501 5332220392852429732840496556676576434317030467044 | Did Microsoft change Random default seed ? |
C_sharp : I was playing around with the C # compiler on TryRoslyn recently , and I came across a strange problem where an inequality check was getting converted into a greater-than one . Here is the repro code : and here is the code that gets generated by the decompiler : Here 's the link to the repro . Why does Roslyn do this ; is it a bug ? Some observations I 've made after playing around with the code for a while : This only happens with the last boolean expression in the condition . For example if you add another || statement , it will only happen with the last call to Foo ( ) .It also only happens with 0 , specifically ; if you substitute it for 1 , or some other number , it wo n't happen . <code> using System ; public class C { public void M ( ) { if ( Foo ( ) ! = 0 || Foo ( ) ! = 0 ) { Console.WriteLine ( `` Hi ! `` ) ; } } private int Foo ( ) = > 0 ; } using System ; using System.Diagnostics ; using System.Reflection ; using System.Runtime.CompilerServices ; using System.Security ; using System.Security.Permissions ; [ assembly : AssemblyVersion ( `` 0.0.0.0 '' ) ] [ assembly : Debuggable ( DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue ) ] [ assembly : CompilationRelaxations ( 8 ) ] [ assembly : RuntimeCompatibility ( WrapNonExceptionThrows = true ) ] [ assembly : SecurityPermission ( SecurityAction.RequestMinimum , SkipVerification = true ) ] [ module : UnverifiableCode ] public class C { public void M ( ) { bool flag = this.Foo ( ) ! = 0 || this.Foo ( ) > 0 ; // this should be an ! = check if ( flag ) { Console.WriteLine ( `` Hi ! `` ) ; } } private int Foo ( ) { return 0 ; } } | Why is Roslyn generating a > comparison instead of a ! = one here ? |
C_sharp : I just wrote an if statement in the lines ofand it annoys me that I always have to repeat the 'value == ' part . In my opinion this is serving no purpose other than making it difficult to read.I wrote the following ExtensionMethod that should make above scenario more readable : Now I can simply writeIs this a good usage of an ExtensionMethod ? EDIT : Thanks for all the great answers . For the record : I have kept the method . While the suggestion that you could simply use new [ ] { value1 , value2 , value3 , value4 } .Contains ( value ) is true , I simply prefer reading this kind of if statement from left to right ( if this value is equal to any of these instead of if these values contain this value ) . Having one more method show up in intellisense on each object is not an issue for me . <code> if ( value == value1 || value == value2 || value == value3 || value == value4 ) //do something public static bool IsEqualToAny < T > ( this T value , params T [ ] objects ) { return objects.Contains ( value ) ; } if ( value.IsEqualToAny ( value1 , value2 , value3 , value4 ) ) //do something | Is this a good use of an ExtensionMethod ? |
C_sharp : Let 's assume that I have a controller 's action which does the following : checks if there is a calendar slot at a particular timechecks if there are no appointments already booked that overlap with that slotif both conditions are satisfied it creates a new appointment at the given timeThe trivial implementation presents multiple problems : what if the calendar slot fetched in 1 is removed before step 3 ? what if another appointment is booked after step 2 but before step 3 ? The solution to these problems seems to be using the SERIALIZABLE transaction isolation level . The problem is that everybody seems to consider this transaction isolation level to be extremely dangerous as it may lead to deadlocks.Given the following trivial solution : what would be the best way to always prevent concurrency problems and how should I handle eventual deadlocks ? <code> public class AController { // ... public async Task Fn ( ... , CancellationToken cancellationToken ) { var calendarSlotExists = dbContext.Slots.Where ( ... ) .AnyAsync ( cancellationToken ) ; var appointmentsAreOverlapping = dbContext.Appointments.Where ( ... ) .AnyAsync ( cancellationToken ) ; if ( calendarSlotExists & & ! appointmentsAreOverlapping ) dbContext.Appointments.Add ( ... ) ; dbContext.SaveChangesAsync ( cancellationToken ) ; } } | Enforcing business rules in entity framework core |
C_sharp : I 've got some inheritance going , requiring a custom JsonConverter for deserialization . I 'm using a very straightforward approach for now where I determine the type based on the existence of certain properties.Important note : in my actual code I can not touch the DeserializeObject calls , i.e . I can not add custom convertors there . I know this is therefor to some degree an XY-problem , and realize as such my answer might be that what I want is not possible . As far as I can tell this makes my question slightly different from this question.Here 's a repro of my situation : And this is the custom converter : This works fine for the FavoritePet , but not so much for the OtherPets because it 's a list . Here 's a way to reproduce my problem with NUnit tests : The latter test is red because : Newtonsoft.Json.JsonReaderException : Error reading JObject from JsonReader . Current JsonReader item is not an object : StartArray . Path 'OtherPets ' , line 1 , position 33.I 've also tried without the custom converter on OtherPets , which results in : Newtonsoft.Json.JsonSerializationException : Could not create an instance of type JsonConverterLists.Mammal . Type is an interface or abstract class and can not be instantiated . Path 'OtherPets [ 0 ] .Lives ' , line 1 , position 42.I understand what 's going on , I even know that I could fix it with : But repeating the note from above : I ca n't change the DeserializeObject call as it 's wrapped inside a function in a library I can not currently change.Is there a way to do the same with a attribute-based approach , e.g . is there a built-in converter for lists where each entry takes in a custom converter ? Or do I have to roll my own , seperate converter for this too ? Footnote , how to reproduce : Visual Studio 2013 = > Fresh new .NET 4.5.1 Class LibraryInstall-Package Newtonsoft.Json -Version 7.0.1Install-Package nunit -Version 2.6.4You can just drop the above three code blocks in your fresh namespace and run the NUnit tests , seeing the second one fail . <code> abstract class Mammal { } class Cat : Mammal { public int Lives { get ; set ; } } class Dog : Mammal { public bool Drools { get ; set ; } } class Person { [ JsonConverter ( typeof ( PetConverter ) ) ] public Mammal FavoritePet { get ; set ; } [ JsonConverter ( typeof ( PetConverter ) ) ] public List < Mammal > OtherPets { get ; set ; } } public class PetConverter : JsonConverter { public override bool CanConvert ( Type objectType ) { return objectType == typeof ( Mammal ) ; } public override bool CanWrite { get { return false ; } } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { throw new NotImplementedException ( ) ; } public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { if ( reader.TokenType == JsonToken.Null ) return null ; JObject jsonObject = JObject.Load ( reader ) ; if ( jsonObject [ `` Lives '' ] ! = null ) return jsonObject.ToObject < Cat > ( serializer ) ; if ( jsonObject [ `` Drools '' ] ! = null ) return jsonObject.ToObject < Dog > ( serializer ) ; return null ; } } [ TestFixture ] class MyTests { [ Test ] public void CanSerializeAndDeserializeSingleItem ( ) { var person = new Person { FavoritePet = new Cat { Lives = 9 } } ; var json = JsonConvert.SerializeObject ( person ) ; var actual = JsonConvert.DeserializeObject < Person > ( json ) ; Assert.That ( actual.FavoritePet , Is.InstanceOf < Cat > ( ) ) ; } [ Test ] public void CanSerializeAndDeserializeList ( ) { var person = new Person { OtherPets = new List < Mammal > { new Cat { Lives = 9 } } } ; var json = JsonConvert.SerializeObject ( person ) ; var actual = JsonConvert.DeserializeObject < Person > ( json ) ; Assert.That ( actual.OtherPets.Single ( ) , Is.InstanceOf < Cat > ( ) ) ; } } var actual = JsonConvert.DeserializeObject < Person > ( json , new PetConverter ( ) ) ; | How to deserialize a list of abstract items without passing converters to DeserializeObject ? |
C_sharp : I have a list of ranges . Each range has a from and to value , meaning the value can be between that range . For eample if range is ( 1,4 ) . , the values can be 1,2,3 and 4 . Now , I need to find the distinct values in a given list of range . Below is the sample code.I can loop through every range and find the distinct values . but if some one can give an effieient approach , it would be helpful . <code> class Program { static void Main ( string [ ] args ) { List < Range > values = new List < Range > ( ) ; values.Add ( new Range ( 1 , 2 ) ) ; values.Add ( new Range ( 1 , 3 ) ) ; values.Add ( new Range ( 1 , 4 ) ) ; values.Add ( new Range ( 3 , 5 ) ) ; values.Add ( new Range ( 7 , 10 ) ) ; values.Add ( new Range ( 7 , 8 ) ) ; // Expected Output from the range of values //1,2,3,4,5,7,8,9,10 } } class Range { public Range ( int _form , int _to ) { from = _from ; to = _to ; } private int from ; public int From { get { return from ; } set { from = value ; } } private int to ; public int To { get { return to ; } set { to = value ; } } } | Efficient Logic to get distinct values from a range of values in c # 2.0 |
C_sharp : I 'd like to reinterpret a string in a array of int where every int take charge of 4 or 8 chars based on processor architecture.Is there a way to achieve this in a relatively inexpensive way ? I tried out this but does n't seem to reinterpret 4 chars in one intSOLUTION : ( change Int64 or Int32 based on your needs ) <code> string text = `` abcdabcdefghefgh '' ; unsafe { fixed ( char* charPointer = text ) { Int32* intPointer = ( Int32* ) charPointer ; for ( int index = 0 ; index < text.Length / 4 ; index++ ) { Console.WriteLine ( intPointer [ index ] ) ; } } } string text = `` abcdabcdefghefgh '' ; unsafe { fixed ( char* charPointer = text ) { Int64* intPointer = ( Int64* ) charPointer ; int conversionFactor = sizeof ( Int64 ) / sizeof ( char ) ; int index = 0 ; for ( index = 0 ; index < text.Length / conversionFactor ; index++ ) { Console.WriteLine ( intPointer [ index ] ) ; } if ( text.Length % conversionFactor ! = 0 ) { intPointer [ index ] < < = sizeof ( Int64 ) ; intPointer [ index ] > > = sizeof ( Int64 ) ; Console.WriteLine ( intPointer [ index ] ) ; } } } | reinterpret cast an array from string to int |
C_sharp : I 'm trying to detect when mouse enters VS 2017 title bar , but I 've noticed that MouseEnter and MouseLeave events do n't work correctly . Event fires only when mouse enters child controls outlined by green rectangle on the screenshot below.The title bar is a DockPanel with some elements in it . I 've set its background to SolidColorBrush ( Colors.Red ) to make sure hit test runs correctly . When mouse is over elements in green rectangle IsMouseOver correctly returns true , but everywhere else it is false . For menu bar , IsMouseOver and MouseEnter and MouseLeave events work correctly . What could be wrong there ? Update 2 : It is likely that title bar is marked as non-client area and this is what causes this problemUpdate : Here is Visual Tree of main VS window : Decompiled MainWindowTitleBar class : Extracted XAML for MainWindowTitleBar : <code> using Microsoft.VisualStudio.PlatformUI.Shell.Controls ; using Microsoft.VisualStudio.Shell ; using System ; using System.Windows ; using System.Windows.Automation.Peers ; using System.Windows.Controls ; using System.Windows.Input ; using System.Windows.Interop ; using System.Windows.Media ; namespace Microsoft.VisualStudio.PlatformUI { public sealed class MainWindowTitleBar : Border , INonClientArea { protected override HitTestResult HitTestCore ( PointHitTestParameters hitTestParameters ) { return new PointHitTestResult ( this , hitTestParameters.HitPoint ) ; } int INonClientArea.HitTest ( Point point ) { return 2 ; } protected override AutomationPeer OnCreateAutomationPeer ( ) { return new MainWindowTitleBarAutomationPeer ( this ) ; } protected override void OnContextMenuOpening ( ContextMenuEventArgs e ) { if ( ! e.Handled ) { HwndSource hwndSource = PresentationSource.FromVisual ( this ) as HwndSource ; if ( hwndSource ! = null ) { CustomChromeWindow.ShowWindowMenu ( hwndSource , this , Mouse.GetPosition ( this ) , base.RenderSize ) ; } e.Handled = true ; } } } } < mwtb : MainWindowTitleBar Name= '' MainWindowTitleBar '' x : Uid= '' vs : MainWindowTitleBar_1 '' Grid.Row= '' 0 '' Grid.Column= '' 0 '' Background= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowActiveCaptionBrushKey } } '' TextElement.Foreground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowActiveCaptionTextBrushKey } } '' > < DockPanel x : Uid= '' DockPanel_2 '' > < wcp : SystemMenu Name= '' SystemMenu '' x : Uid= '' Image_1 '' Source= '' { TemplateBinding Window.Icon } '' VectorFill= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowActiveIconDefaultBrushKey } } '' Width= '' 32 '' Height= '' 27 '' Margin= '' 0,0,12,4 '' Padding= '' 12,7,0,0 '' DockPanel.Dock= '' Left '' VectorIcon= '' { Binding Source= { x : Static Application.Current } , Path=VectorIcon } '' / > < StackPanel Name= '' WindowTitleBarButtons '' x : Uid= '' WindowTitleBarButtons '' Orientation= '' Horizontal '' DockPanel.Dock= '' Right '' > < wcp : WindowTitleBarButton Name= '' MinimizeButton '' x : Uid= '' MinimizeButton '' VerticalAlignment= '' Top '' Command= '' { x : Static vsc : ViewCommands.MinimizeWindow } '' BorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveBorderBrushKey } } '' BorderThickness= '' 1,0,1,1 '' GlyphForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveGlyphBrushKey } } '' HoverBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBrushKey } } '' HoverBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBorderBrushKey } } '' HoverForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveGlyphBrushKey } } '' HoverBorderThickness= '' 1,0,1,1 '' PressedBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBrushKey } } '' PressedBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBorderBrushKey } } '' PressedForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownGlyphBrushKey } } '' PressedBorderThickness= '' 1,0,1,1 '' Padding= '' 0,3,0,0 '' Width= '' 34 '' Height= '' 26 '' AutomationProperties.Name= '' Minimize '' AutomationProperties.AutomationId= '' Minimize '' ToolTip= '' { x : Static vs : MainWindowResources.WindowMinimizeToolTip } '' CommandParameter= '' { Binding RelativeSource= { RelativeSource TemplatedParent } } '' > < Path Name= '' MinimizeButtonPath '' x : Uid= '' MinimizeButtonPath '' Width= '' 9 '' Height= '' 9 '' Stretch= '' None '' Data= '' F1M0,6L0,9 9,9 9,6 0,6z '' Fill= '' { Binding Path= ( TextElement.Foreground ) , RelativeSource= { RelativeSource Self } } '' / > < /wcp : WindowTitleBarButton > < wcp : WindowTitleBarButton Name= '' MaximizeRestoreButton '' x : Uid= '' MaximizeRestoreButton '' VerticalAlignment= '' Top '' Command= '' { x : Static vsc : ViewCommands.ToggleMaximizeRestoreWindow } '' BorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveBorderBrushKey } } '' BorderThickness= '' 1,0,1,1 '' GlyphForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveGlyphBrushKey } } '' HoverBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBrushKey } } '' HoverBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBorderBrushKey } } '' HoverForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveGlyphBrushKey } } '' HoverBorderThickness= '' 1,0,1,1 '' PressedBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBrushKey } } '' PressedBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBorderBrushKey } } '' PressedForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownGlyphBrushKey } } '' PressedBorderThickness= '' 1,0,1,1 '' Padding= '' 0,3,0,0 '' Width= '' 34 '' Height= '' 26 '' AutomationProperties.Name= '' Maximize '' AutomationProperties.AutomationId= '' Maximize '' ToolTip= '' { x : Static vs : MainWindowResources.WindowMaximizeToolTip } '' CommandParameter= '' { Binding RelativeSource= { RelativeSource TemplatedParent } } '' > < Path Name= '' MaximizeRestoreButtonPath '' x : Uid= '' MaximizeRestoreButtonPath '' Width= '' 9 '' Height= '' 9 '' Stretch= '' Uniform '' Data= '' F1M0,0L0,9 9,9 9,0 0,0 0,3 8,3 8,8 1,8 1,3z '' Fill= '' { Binding Path= ( TextElement.Foreground ) , RelativeSource= { RelativeSource Self } } '' / > < /wcp : WindowTitleBarButton > < wcp : WindowTitleBarButton Name= '' HideButton '' x : Uid= '' HideButton '' VerticalAlignment= '' Top '' Command= '' { x : Static vsc : ViewCommands.CloseWindow } '' BorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveBorderBrushKey } } '' BorderThickness= '' 1,0,1,1 '' GlyphForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonActiveGlyphBrushKey } } '' HoverBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBrushKey } } '' HoverBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveBorderBrushKey } } '' HoverForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonHoverActiveGlyphBrushKey } } '' HoverBorderThickness= '' 1,0,1,1 '' PressedBackground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBrushKey } } '' PressedBorderBrush= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownBorderBrushKey } } '' PressedForeground= '' { DynamicResource { x : Static ui : EnvironmentColors.MainWindowButtonDownGlyphBrushKey } } '' PressedBorderThickness= '' 1,0,1,1 '' Padding= '' 0,3,0,0 '' Width= '' 34 '' Height= '' 26 '' AutomationProperties.Name= '' Close '' AutomationProperties.AutomationId= '' Close '' ToolTip= '' { x : Static vs : MainWindowResources.WindowCloseToolTip } '' CommandParameter= '' { Binding RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type Window } } } '' > < Path Name= '' HideButtonPath '' x : Uid= '' HideButtonPath '' Width= '' 10 '' Height= '' 8 '' Stretch= '' Uniform '' Data= '' F1M0,0L2,0 5,3 8,0 10,0 6,4 10,8 8,8 5,5 2,8 0,8 4,4 0,0z '' Fill= '' { Binding Path= ( TextElement.Foreground ) , RelativeSource= { RelativeSource Self } } '' / > < /wcp : WindowTitleBarButton > < /StackPanel > < mwtb : FrameControlContainer Name= '' PART_TitleBarFrameControlContainer '' x : Uid= '' PART_TitleBarFrameControlContainer '' DockPanel.Dock= '' Right '' TextElement.FontSize= '' { DynamicResource VsFont.EnvironmentFontSize } '' TextElement.FontFamily= '' { DynamicResource VsFont.EnvironmentFontFamily } '' Margin= '' 0,0,2,0 '' DataContext= '' { Binding FrameControls } '' / > < TextBlock x : Uid= '' TextBlock_1 '' Text= '' { TemplateBinding Window.Title } '' TextBlock.FontFamily= '' { DynamicResource VsFont.CaptionFontFamily } '' TextBlock.FontSize= '' { DynamicResource VsFont.CaptionFontSize } '' TextBlock.FontWeight= '' { DynamicResource VsFont.CaptionFontWeight } '' TextTrimming= '' CharacterEllipsis '' VerticalAlignment= '' Center '' Margin= '' 0,7,0,4 '' / > < /DockPanel > < /mwtb : MainWindowTitleBar > | IsMouseOver returns false over some elements in a DockPanel |
C_sharp : I have read that a 'BackgroundWorker ' is designed to be replaced by Ansyc/Await . Because I like the condensed look of Async/Await , I am starting to convert some of my BackgroundWorkers into Async/Await calls.This is an example of the code I have ( called from the UI ) : When I call RunFromTheUI it will return almost immediately ( as per the Async and Await design ) .But when it resumes after services.SomeRemoteAction ( ) finishes it has a foreach loop and another method call to run through.My question is : If that loop is a performance hog will it freeze the UI ? ( Before I had it all in a Background worker thread , so it did not slow the UI down ) .Note : I am targeting .Net 4.0 and using the Async Nuget Package . <code> public async void RunFromTheUI ( ) { await OtherAction ( ) ; } public async void OtherAction ( ) { var results = await services.SomeRemoteAction ( ) ; foreach ( var result in results ) { result.SemiIntenseCalculation ( ) ; Several ( ) ; Other ( ) ; NonAsync ( ) ; Calls ( ) ; } SomeFileIO ( ) ; } | Does an await make the rest of the method asynchronous ? |
C_sharp : I am trying to define code contracts for an interface using ContractClass and ContractClassFor . It works fine when everything is in the same assembly , but if I put the interface definition and its respective contract class in a different assembly then the concrete class implementation , it does n't work anymore.For example , this code works : Now , if I have a separate project with the following : and then in the main project ( different assembly from the above ) if I write : Then the Contract.Requires is no longer checked in the Deposit method.Any ideas on this , please ? Thanks a lot ! <code> namespace DummyProject { [ ContractClass ( typeof ( AccountContracts ) ) ] public interface IAccount { void Deposit ( double amount ) ; } [ ContractClassFor ( typeof ( IAccount ) ) ] internal abstract class AccountContracts : IAccount { void IAccount.Deposit ( double amount ) { Contract.Requires ( amount > = 0 ) ; } } internal class Account : IAccount { public void Deposit ( double amount ) { Console.WriteLine ( amount ) ; } } class Program { static void Main ( string [ ] args ) { Account account = new Account ( ) ; // Contract.Requires will be checked below account.Deposit ( -1 ) ; } } } namespace SeparateAssembly { [ ContractClass ( typeof ( SeparateAssemblyAccountContracts ) ) ] public interface ISeparateAssemblyAccount { void Deposit ( double amount ) ; } [ ContractClassFor ( typeof ( ISeparateAssemblyAccount ) ) ] internal abstract class SeparateAssemblyAccountContracts : ISeparateAssemblyAccount { void ISeparateAssemblyAccount.Deposit ( double amount ) { Contract.Requires ( amount > = 0 ) ; } } } namespace DummyProject { internal class AccountFromSeparateAssembly : ISeparateAssemblyAccount { public void Deposit ( double amount ) { Console.WriteLine ( amount ) ; } } class Program { static void Main ( string [ ] args ) { ISeparateAssemblyAccount accountFromSeparateAssembly = new AccountFromSeparateAssembly ( ) ; // Neither of the two statements below will work // Contract.Requires will be ignored accountFromSeparateAssembly.Deposit ( -1 ) ; ( ( AccountFromSeparateAssembly ) accountFromSeparateAssembly ) .Deposit ( -1 ) ; } } } | Code Contracts for C # does not work when ContractFor is on a different assembly |
C_sharp : IntroductionAs a developer , I 'm involved in writing a lot of mathematical code everyday and I 'd like to add very few syntactic sugar to the C # language to ease code writing and reviewing.I 've already read about this thread and this other one for possible solutions and would simply like to know which best direction to go and how much effort it may represent to solve only for the three following syntactical issues* . * : I can survive without described syntactic sugars , but if it ai n't too much work and Rube-Goldberg design for simple compilation process , it may be interesting to investigate further . 1 . Multiple output argumentsI 'd like to write : Instead of : NB : out parameters being placed first and foo being declared as usual ( or using same kind of syntax ) .2 . Additional operatorsI 'd like to have a few new unary/binary operators . Do n't know much how to define for these ( and it seems quite complex for not introducing ambiguity when parsing sources ) , anyway would like to have something like : Instead of:3 . Automatic name insertion for static classesIt 's extremely unappealing to endlessly repeating Math.BlaBlaBla ( ) everywhere in a computation code instead of writing directly and simply BlaBlaBla . For sure this can be solved by adding local methods to wrap Math.BlaBlaBla inside computation class . Anyway would be better when there 's no ambiguity at all , or when ambiguity would be solved with some sort of implicit keyword , to automatically insert class names when required.For instance : Would become : * The compiler may simply generate a warning to indicate that it solved the ambiguity because an implicit solution has been defined.NB : 3 ) is satisfying enough for solving 2 ) . <code> [ double x , int i ] = foo ( z ) ; double x ; int i ; foo ( out x , out i , z ) ; namespace Foo { using binary operator `` \ '' as `` MyMath.LeftDivide '' ; using unary operator `` ' '' as `` MyMath.ConjugateTranspose '' ; public class Test { public void Example ( ) { var y = x ' ; var z = x \ y ; } } } namespace Foo { public class Test { public void Example ( ) { var y = MyMath.ConjugateTranspose ( x ) ; var z = MyMath.LeftDivide ( x , y ) ; } } } using System ; using implicit MySystem ; // Definying for 'MyMaths.Math.Bessel'public class Example { public Foo ( ) { var y = 3.0 * Cos ( 12.0 ) ; var z = 3.0 * Bessel ( 42 ) ; } // Local definition of 'Bessel ' function again public static double Bessel ( double x ) { ... } } using System ; using MySystem ; // Definying for 'Math.Bessel'public class Example { public Foo ( ) { var y = 3.0 * System.Math.Cos ( 12.0 ) ; // No ambiguity at all var z = 3.0 * MySystem.Math.Bessel ( 42 ) ; // Solved from ` implicit ` keyword } // Local definition of 'Bessel ' function again public static double Bessel ( double x ) { ... } } | Extending C # language , how much effort/gain ? |
C_sharp : As in : And how do I search for it in the documentation ? <code> public string [ , ] GetHelp ( ) { return new string [ , ] { ... things ... } } | What does [ , ] mean in c # ? |
C_sharp : I 'm working on my solution to the Cult of the Bound Variable problem.Part of the problem has you implement an interpreter for the `` ancient '' Universal Machine . I 've implemented an intepreter for the machine they describe and now I 'm running a benchmark program that the university provided to test it.My C # implementation of this interpreter is slow ! I fired up my program in the ANTS profiler to see where the slowdown is and I can see that over 96 % of my time is taken up by the `` Load Program '' operation.The specification of this operator is as follows : Here is my code for this operator : The source code to my whole `` Universal Machine '' interpreter is here.What can I do to make this faster ? There are other implementations of this interpreter written in C which complete the entire benchmark significantly faster . <code> # 12 . Load Program . The array identified by the B register is duplicated and the duplicate shall replace the ' 0 ' array , regardless of size . The execution finger is placed to indicate the platter of this array that is described by the offset given in C , where the value 0 denotes the first platter , 1 the second , et cetera . The ' 0 ' array shall be the most sublime choice for loading , and shall be handled with the utmost velocity . case 12 : // Load Program _platters [ 0 ] = ( UInt32 [ ] ) _platters [ ( int ) _registers [ B ] ] .Clone ( ) ; _finger = _registers [ C ] ; break ; | How can I speed up array cloning in C # ? |
C_sharp : I 'm using Visual Studio 2015 on Windows 10 , I 'm still a new coder , I 've just started to learn C # , and while I was in the process , I discovered the Math class and was just having fun with it , till the console outputted : `` ∞ `` It 's a Console ApplicationHere 's the code : Why is this happening ? using normal calculator the result is : 96985953901866.7 <code> var k = Math.Sqrt ( ( Math.Pow ( Math.Exp ( 5 ) , Math.E ) ) ) ; var l = Math.Sqrt ( ( Math.Pow ( Math.PI , Math.E ) ) ) ; Console.WriteLine ( `` number 1 : `` + k ) ; Console.WriteLine ( `` number 2 : `` + l ) ; Console.ReadKey ( ) ; var subject = Math.Pow ( Math.Sqrt ( ( Math.Pow ( Math.PI , Math.E ) ) ) , Math.Sqrt ( ( Math.Pow ( Math.Exp ( 5 ) , Math.E ) ) ) ) ; Console.WriteLine ( k + `` ^ `` + l + `` = `` + subject ) ; Console.ReadKey ( ) ; //output : /*number 1 : 893.998923601492 number 2 : 4.73910938029088 893.998923601492 ^ 4.73910938029088 = ∞*/ | C # : The console is outputting infinite ( ∞ ) |
C_sharp : I bet that 's an easy question for you , but searching SO or Google with { or } in the search string does n't work very well.So , let 's say i wan na output { Hello World } , how do i do this using string.format ( ... ) ? Edit : looks like this : would do the job , but that does n't look very elegant to me . Is there a way to escape these characters inside the format string ? <code> string hello = `` Hello World '' ; string.format ( `` { 0 } '' , ' { ' + hello + ' } ' ) ; | Output ' { ' or ' } ' with string.format ( ... ) |
C_sharp : I have an ID with me and I have name with me . So in essence , my method just has these parameters : and I have this piece of logic inside method : That 's it . Nothing fancy . I get this error : `` An object with the same key already exists in the ObjectStateManager . The ObjectStateManager can not track multiple objects with the same key '' and this answer by Ladislav Mrnka : An object with the same key already exists in the ObjectStateManager . The ObjectStateManager can not track multiple objects with the same keysuggests to use context.Entry ( oldEntity ) .CurrentValues.SetValues ( newEntity ) ; but I do n't really have oldEntity with me . Can anybody just please tell me how do I update just 1 property of User ? I am getting nuts . <code> public void Foo ( int id , string name ) { } User user = new User ( ) { Id = id , Name = name } ; Db.Entry ( user ) .State = System.Data.EntityState.Modified ; Db.SaveChanges ( ) ; | Why I do I fall into all of the hurdles for a simple update in EF ? |
C_sharp : When we have two structs , and one is implicitly convertible to the other , then it seems like the System.Nullable < > versions of the two are also implicitly convertible . Like , if struct A has an implicit conversion to struct B , then A ? converts to B ? as well.Here is an example : Inside some method : In the C # Language Specification Version 4.0 we read that a conversion like this shall exist for `` the predefined implicit identity and numeric conversions '' .But is it safe to assume that it will also work for user-defined implicit conversions ? ( This question might be related to this bug : http : //connect.microsoft.com/VisualStudio/feedback/details/642227/ ) <code> struct MyNumber { public readonly int Inner ; public MyNumber ( int i ) { Inner = i ; } public static implicit operator int ( MyNumber n ) { return n.Inner ; } } MyNumber ? nmn = new MyNumber ( 42 ) ; int ? covariantMagic = nmn ; // works ! | `` Covariance '' of the System.Nullable < > struct |
C_sharp : I 'm trying to match strings that look like this : But not if it occurs in larger context like this : The regex I 've got that does the job in a couple different RegEx engines I 've tested ( PHP , ActionScript ) looks like this : You can see it working here : http : //regexr.com ? 36g0eThe problem is that that particular RegEx does n't seem to work correctly under .NET . Specifically , .NET does n't seem to be paying attention to the first \b* . In other words , it correctly fails to match this string : But it incorrectly matches this string ( note the extra spaces ) : Any ideas as to what I 'm doing wrong or how to work around it ? <code> http : //www.google.com < a href= '' http : //www.google.com '' > http : //www.google.com < /a > ( ? < ! [ `` ' > ] \b* ) ( ( https ? : // ) ( [ A-Za-z0-9_= % & @ ? ./- ] + ) ) \b private static readonly Regex fixHttp = new Regex ( @ '' ( ? < ! [ `` '' ' > ] \b* ) ( ( https ? : // ) ( [ A-Za-z0-9_= % & @ ? ./- ] + ) ) \b '' , RegexOptions.IgnoreCase ) ; private static readonly Regex fixWww = new Regex ( @ '' ( ? < = [ \s ] ) \b ( ( www\ . ) ( [ A-Za-z0-9_= % & @ ? ./- ] + ) ) \b '' , RegexOptions.IgnoreCase ) ; public static string FixUrls ( this string s ) { s = fixHttp.Replace ( s , `` < a href=\ '' $ 1\ '' > $ 1 < /a > '' ) ; s = fixWww.Replace ( s , `` < a href=\ '' http : // $ 1\ '' > $ 1 < /a > '' ) ; return s ; } < a href= '' http : //www.google.com '' > http : //www.google.com < /a > < a href= '' http : //www.google.com '' > http : //www.google.com < /a > | RegEx does n't work with .NET , but does with other RegEx implementations |
C_sharp : As you can see in the following image , I have a model with a base class `` Person '' and both entities `` Kunde '' and `` Techniker '' inherit the base class.Now I 've got following problem . When I try to use the method Find to get an object of the derived class Kunde with given ID , it tells me that OfType < TResult > is a method and is n't valid in this context . I 've also tried to drop the OfType but it obviously tells me that the object Person can not be implicitly converted to Kunde.Is there anything I 'm missing here ? <code> public Kunde GetById ( int id ) { return dbModel.PersonMenge.OfType < Kunde > .Find ( id ) ; } | Finding inherited object by ID - Entity Framework |
C_sharp : I 'm trying to learn how to use WPF binding and the MVVM architecture . I 'm running into some trouble with Dependency Properties . I 've tried to control the visibility of an item on the view by binding it to a DependencyProperty in the DataContext , but it does n't work . No matter what I set the GridVisible value to in the constructor of the view model below , it is always displayed as visible when I run the code.Can anyone see where I 'm going wrong ? C # code ( ViewModel ) : XAML code ( View ) : I 've looked at several tutorials online , and it seems like I 'm correctly following what I 've found there . Any ideas ? Thanks ! <code> public class MyViewModel : DependencyObject { public MyViewModel ( ) { GridVisible = false ; } public static readonly DependencyProperty GridVisibleProperty = DependencyProperty.Register ( `` GridVisible '' , typeof ( bool ) , typeof ( MyViewModel ) , new PropertyMetadata ( false , new PropertyChangedCallback ( GridVisibleChangedCallback ) ) ) ; public bool GridVisible { get { return ( bool ) GetValue ( GridVisibleProperty ) ; } set { SetValue ( GridVisibleProperty , value ) ; } } protected static void GridVisibleChangedCallback ( DependencyObject source , DependencyPropertyChangedEventArgs e ) { // Do other stuff in response to the data change . } } < UserControl ... > < UserControl.Resources > < BooleanToVisibilityConverter x : Key= '' BoolToVisConverter '' / > < /UserControl.Resources > < UserControl.DataContext > < local : MyViewModel x : Name= '' myViewModel '' / > < /UserControl.DataContext > < Grid x : Name= '' _myGrid '' Visibility= '' { Binding Path=GridVisible , ElementName=myViewModel , Converter= { StaticResource BoolToVisConverter } } '' > < ! -- Other elements in here -- > < /Grid > < /UserControl > | WPF Data Binding Architecture Question |
C_sharp : I 'm trying to create an instance of a generic class , without knowing what type to cast it to it until runtime . I 've written the following codeHopefully that gives you an idea what I 'm trying to do , however it wont compile it just says `` the type or namespace pType could not be found '' . Is there any easy way of doing this ? ThanksGavin <code> Type pType = propertyInfo.GetType ( ) ; ObjectComparer < pType > oc = new ObjectComparer < pType > ( ) ; | C # Generics |
C_sharp : I have a very basic video recording project that was working perfectly in Swift , but the same code ported into a blank project in Xamarin is producing a video that is constantly skipping frames every few seconds . The code starts in ViewDidLoad and is stopped via a UIButton Here is the recording code below : And here is what the VideoSettings file looks like : <code> RPScreenRecorder rp = RPScreenRecorder.SharedRecorder ; AVAssetWriter assetWriter ; AVAssetWriterInput videoInput ; public override void ViewDidLoad ( ) { base.ViewDidLoad ( ) ; StartScreenRecording ( ) ; } public void StartScreenRecording ( ) { VideoSettings videoSettings = new VideoSettings ( ) ; NSError wError ; assetWriter = new AVAssetWriter ( videoSettings.OutputUrl , AVFileType.AppleM4A , out wError ) ; videoInput = new AVAssetWriterInput ( AVMediaType.Video , videoSettings.OutputSettings ) ; videoInput.ExpectsMediaDataInRealTime = true ; assetWriter.AddInput ( videoInput ) ; if ( rp.Available ) { rp.StartCaptureAsync ( ( buffer , sampleType , error ) = > { if ( buffer.DataIsReady ) { if ( assetWriter.Status == AVAssetWriterStatus.Unknown ) { assetWriter.StartWriting ( ) ; assetWriter.StartSessionAtSourceTime ( buffer.PresentationTimeStamp ) ; } if ( assetWriter.Status == AVAssetWriterStatus.Failed ) { return ; } if ( sampleType == RPSampleBufferType.Video ) { if ( videoInput.ReadyForMoreMediaData ) { videoInput.AppendSampleBuffer ( buffer ) ; } } } } ) ; } } public void StopRecording ( ) { rp.StopCapture ( ( error ) = > { if ( error == null ) { assetWriter.FinishWriting ( ( ) = > { } ) ; } } ) ; } public class VideoSettings { public string VideoFilename = > `` render '' ; public string VideoFilenameExt = `` mp4 '' ; public nfloat Width { get ; set ; } public nfloat Height { get ; set ; } public AVVideoCodec AvCodecKey = > AVVideoCodec.H264 ; public NSUrl OutputUrl { get { return GetFilename ( VideoFilename , VideoFilenameExt ) ; } } private NSUrl GetFilename ( string filename , string extension ) { NSError error ; var docs = new NSFileManager ( ) .GetUrl ( NSSearchPathDirectory.DocumentDirectory , NSSearchPathDomain.User , null , true , out error ) .ToString ( ) + filename + 1 + `` . '' + extension ; if ( error == null ) { return new NSUrl ( docs ) ; } return null ; } public AVVideoSettingsCompressed OutputSettings { get { return new AVVideoSettingsCompressed { Codec = AvCodecKey , Width = Convert.ToInt32 ( UIScreen.MainScreen.Bounds.Size.Width ) , Height = Convert.ToInt32 ( UIScreen.MainScreen.Bounds.Size.Height ) } ; } } } | Video produced by ReplayKit is constantly skipping frames in Xamarin |
C_sharp : I 'm trying to use reflection to retrieve a list of all methods of an interface + its base interfaces.So far I have this : I 'd like to be able to filter out methods that shadow methods declared in base interfaces , i.e. , `` new '' methods : With my current code , the result includes both methods - I 'd like to retrieve IInterfaceWithMethod.Method only and filter out IBaseInterface.Method.Fiddle : https : //dotnetfiddle.net/fwVeLSPS : If it helps , you can assume I have access to a concrete instance of the derived interface . The type of that instance will only be known at runtime ( it 's a dynamic proxy ) . <code> var methods = type.GetMethods ( ) .Concat ( type.GetInterfaces ( ) .SelectMany ( @ interface = > @ interface.GetMethods ( ) ) ) ; public interface IBaseInterface { string Method ( ) ; } public interface IInterfaceWithNewMethod : IBaseInterface { new string Method ( ) ; } | How to check whether an interface 's MethodInfo is a `` new '' method |
C_sharp : I have this BdlTabItem which receives a parameter of type DockableUserControl and would like to know if is it a bad practice to create a circular reference between the two by using uc.TabItem = this and new BdlDockableWindow ( this ) before the constructor finishes.I know this behavior can be considered really bad with unmanaged native code ( C++ ) . So , even though I did n't have any warnings or errors , I ask here if I should do this or not . <code> public BdlTabItem ( BdlTabControl parent , DockableUserControl uc , string title ) { TabControlParent = parent ; UserControl = uc ; WindowParent = new BdlDockableWindow ( this ) ; this.Content = UserControl ; UserControl.TabItem = this ; } | Is it a bad practice to pass `` this '' as parameter inside its own constructor ? |
C_sharp : I have some objects that read a file , save the data in arrays and make some operations . The sequence is Create object A , operate with object A . Create object B , operate with object B ... The data read by each object may be around 10 MB . So the best option would be to delete each object after operate with each one . Let say I want my program to allocate around 10 MB in memory , not 10MB * 1000 objects = 1GBThe objects are something like : My question is : should I implement dispose ? And do something like : I´ve read that implementing Disposable is recommended when you use unmmanaged resources ( sockets , streams , ... ) , but in my class I have only big data arrays.Another way would be to create functions for each objects ( I suppose GC will delete a object created in a function automatically ) : <code> class MyClass { List < string [ ] > data ; public MyClass ( string datafile ) { using ( CsvReader csv = new CsvReader ( new StreamReader ( datafile ) , true ) ) { data = csv.ToList < string [ ] > ( ) ; } } public List < string > Operate ( ) { ... } } List < string > results = new List < results > ( ) ; using ( MyClass m = new MyClass ( `` fileM.txt '' ) ) { results.AddRange ( m.Operate ( ) ) ; } using ( MyClass d = new MyClass ( `` fileD.txt '' ) ) { results.AddRange ( d.Operate ( ) ) ; } ... List < string > results = new List < results > ( ) ; results.AddRange ( myFunction ( `` fileM.txt '' ) ) ; results.AddRange ( myFunction ( `` fileD.txt '' ) ) ; public List < string > myFunction ( string file ) { MyClass c = new MyClass ( file ) ; return results.AddRange ( c.Operate ( ) ) ; } | Need to delete objects : implement Dispose or create objects in a function ? |
C_sharp : I have the following block of linq queries to calculate some values for a report.I 've stepped through the code in a debugger and I 've noticed some oddities . After assigning into test its value is 0 . After assigning into test2 test2 == 0 and test == 11.31 after assigning into test3 test == 11.31 test2 == 11.28 and test3 == 22.59 after assigning into ExtraSales ExtraSales == 11.31 . The value in ExtraSales when this is all complete should be 22.59 . What 's going on here ? EDIT : I 've added additional lines after the assignment into ExtraSales but the value does not change . <code> var items = ( from trans in calclabordb.Sales_Transactions select trans ) .SelectMany ( st = > st.Sales_TransactionLineItems ) .Where ( stli = > stli.TypeID == typeID ) ; decimal test = items.Where ( stli = > stli.Inventory_Item is Base ) .Sum ( stli = > ( decimal ? ) stli.Inventory_Item.IntExtraServiceAmount ) ? ? 0 ; decimal test2 = items.Where ( stli = > stli.Inventory_Item is Extra ) .Sum ( stli = > ( decimal ? ) stli.ItemPrice ) ? ? 0 ; decimal test3 = test + test2 ; current.ExtraSales = items.Where ( stli = > stli.Inventory_Item is Base ) .Sum ( stli = > ( decimal ? ) stli.Inventory_Item.IntExtraServiceAmount ) ? ? 0 + items.Where ( stli = > stli.Inventory_Item is Extra ) .Sum ( stli = > ( decimal ? ) stli.ItemPrice ) ? ? 0 ; | Why do n't the values from my linq queries appear immediately ? |
C_sharp : EDITIf I use Stopwatch correctly and up the number of iterations by two orders of magnitude I getTernary took 22404msNormal took 21403msThese results are closer to what I was expecting and make me feel all is right with the world ( if not with my code . ) The Ternary/Conditional operator is in fact marginally slower.Following on from this question , which I have partially answered.I compile this console app in x64 Release Mode , with optimizations on , and run it from the command line without a debugger attached.I do n't get any exceptions and the output to the console is somthing close to , Ternary took 107msNormal took 230msWhen I break down the CIL for the two logical functions I get this , Whilst the Ternary CIL is a little shorter , it seems to me that the execution path through the CIL for either function takes 3 loads and 1 or 2 jumps and a return . Why does the Ternary function appear to be twice as fast.I underdtand that , in practice , they are both very quick and indeed , quich enough but , I would like to understand the discrepancy . <code> using System ; using System.Diagnostics ; class Program { static void Main ( ) { var stopwatch = new Stopwatch ( ) ; var ternary = Looper ( 10 , Ternary ) ; var normal = Looper ( 10 , Normal ) ; if ( ternary ! = normal ) { throw new Exception ( ) ; } stopwatch.Start ( ) ; ternary = Looper ( 10000000 , Ternary ) ; stopWatch.Stop ( ) ; Console.WriteLine ( `` Ternary took { 0 } ms '' , stopwatch.ElapsedMilliseconds ) ; stopwatch.Start ( ) ; normal = Looper ( 10000000 , Normal ) ; stopWatch.Stop ( ) ; Console.WriteLine ( `` Normal took { 0 } ms '' , stopwatch.ElapsedMilliseconds ) ; if ( ternary ! = normal ) { throw new Exception ( ) ; } Console.ReadKey ( ) ; } static int Looper ( int iterations , Func < bool , int , int > operation ) { var result = 0 ; for ( int i = 0 ; i < iterations ; i++ ) { var condition = result % 11 == 4 ; var value = ( ( i * 11 ) / 3 ) % 5 ; result = operation ( condition , value ) ; } return result ; } static int Ternary ( bool condition , in value ) { return value + ( condition ? 2 : 1 ) ; } static int Normal ( int iterations ) { if ( condition ) { return = 2 + value ; } return = 1 + value ; } } ... Ternary ... { : ldarg.1 // push second arg : ldarg.0 // push first arg : brtrue.s T // if first arg is true jump to T : ldc.i4.1 // push int32 ( 1 ) : br.s F // jump to F T : ldc.i4.2 // push int32 ( 2 ) F : add // add either 1 or 2 to second arg : ret // return result } ... Normal ... { : ldarg.0 // push first arg : brfalse.s F // if first arg is false jump to F : ldc.i4.2 // push int32 ( 2 ) : ldarg.1 // push second arg : add // add second arg to 2 : ret // return result F : ldc.i4.1 // push int32 ( 1 ) : ldarg.1 // push second arg : add // add second arg to 1 : ret // return result } | Why does the conditional ( ternary ) operator seem significantly faster ? |
C_sharp : I have ICollectionView looks like I want to use drag & drop to change the item Series Name , and location on the list view any idea how to do that for example if Idraged and droped book3 in ScienceFiction the output should be I use xaml code like this : <code> public ICollectionView UsersCollectionView { get { var view = CollectionViewSource.GetDefaultView ( this ) ; view.GroupDescriptions.Add ( new PropertyGroupDescription ( `` SeriesName '' ) ) ; view.SortDescriptions.Add ( new SortDescription ( `` CreationDate '' , ListSortDirection.Ascending ) ) ; view.SortDescriptions.Add ( new SortDescription ( `` DocumentTypeId '' , ListSortDirection.Ascending ) ) ; return view ; } } -- - ScienceFiction -- -- -- -- -- -- > Book1 -- -- -- -- -- -- > Book2 -- - History -- -- -- -- -- -- > Book3 -- -- -- -- -- -- > Book4 -- - ScienceFiction -- -- -- -- -- -- > Book1 -- -- -- -- -- -- > Book2 -- -- -- -- -- -- > Book3 -- - History -- -- -- -- -- -- > Book4 < UserControl.Resources > < Style x : Key= '' ContainerStyle '' TargetType= '' { x : Type GroupItem } '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate > < Expander Header= '' { Binding Name } '' IsExpanded= '' True '' > < ItemsPresenter / > < /Expander > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /UserControl.Resources > < Grid > < ListBox x : Name= '' lbPersonList '' Margin= '' 19,17,162,25 '' AlternationCount= '' 2 '' ItemsSource= '' { Binding } '' > < ListBox.GroupStyle > < GroupStyle ContainerStyle= '' { StaticResource ContainerStyle } '' / > < /ListBox.GroupStyle > < ListBox.ItemTemplate > < DataTemplate > < TextBlock Text= '' { Binding Name } '' / > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > < /Grid > | change the group of item in ICollectionView |
C_sharp : Is there a performance difference between the following two pieces of code ? andMy gut feeling is that the compiler should optimize for this and there should n't be a difference , but I frequently see it done both ways throughout our code . I 'd like to know if it comes down to a matter of preference and readability . <code> if ( myCondition ) { return `` returnVal1 '' ; } return `` returnVal2 '' if ( myCondition ) { return `` returnVal1 '' ; } else { return `` returnVal2 '' ; } | Is there a performance difference by excluding an 'Else ' clause ? |
C_sharp : Situation : Assembly 1 is a application that other developers can use.We will give them only the .dll so we can publish updates from the application if we do n't change the api . The developers ca n't change the framework in assembly 1Methods are virtual so developers can override methods to implement there own logic if needed.The problem is that a developer ca n't override otherMethod from class B , he can override it but Class A will always call the method from Class B and not the overridden method.Assembly 2 haves a reference to assembly 1 Partial class does n't work because it must be the same assembly and will not work over 2Are there design patterns for this problem ? Or is there a other solution with reflection or something ? EDIT Added a code example : <code> Assembly 1________________________ ________________________| Class A | | Class B || -- -- -- -- -- -- -- -- -- -- -- -| | -- -- -- -- -- -- -- -- -- -- -- -|| Method someMethod | -- -- -- -- -- > | Method otherMethod || | | ||_______________________| |_______________________| Assembly 1________________________ ________________________| Class A | | Class B || -- -- -- -- -- -- -- -- -- -- -- -| | -- -- -- -- -- -- -- -- -- -- -- -|| Method someMethod | -- -- XX -- -- > | Method otherMethod || | | ||_______________________| |_______________________| \ | \ | \ |Assembly 2 \ | \ ________________|_______ \ | Class ExtendedB | \ | -- -- -- -- -- -- -- -- -- -- -- -| \____________ > | Method otherMethod | | | |_______________________| /* ASSEMBLY 1 */namespace Assembly1 { public interface IAService { void TestMethod3 ( ) ; void TestMethod4 ( ) ; } public interface IBService { void TestMethod1 ( ) ; void TestMethod2 ( ) ; } public class AService : IAService { // Base implementation of AService public virtual void TestMethod3 ( ) { //do something } public virtual void TestMethod4 ( ) { //do something } } public class BService : IBService { // Base implementation of BService public virtual void TestMethod1 ( ) { //do something } public virtual void TestMethod2 ( ) { //need to call AService implementation from assembly 2 } } } /* ASSEMBLY 2 */namespace Assembly2 { public class NewAService : AService { public override void TestMethod3 ( ) { //default implementation which could be overridden base.TestMethod3 ( ) ; } public override void TestMethod4 ( ) { //default implementation which could be overridden //An implementation of IBService Should be called base.TestMethod4 ( ) ; } } } | C # OO design problem with override from methods |
C_sharp : I 'm trying to write a complement function , such that when provided with a function f , it returns a function which , when provided with the same input as f , returns it 's logical opposite.Having put similar code into VS2017 , I get no errors , however I 'm not yet able to run the code to see if it 'll work as expected . My intention was to try this in a repl first , to see if it would do as expected . The code I used there was this : Here is a link to the same.Within the repl , I get the error : main.cs ( 17,42 ) : error CS0411 : The type arguments for method ` MainClass.Complement ( System.Func ) ' can not be inferred from the usage . Try specifying the type arguments explicitly Compilation failed : 1 error ( s ) , 0 warnings compiler exit status 1I have looked at a few questions on stack overflow which cover the same error message , for instance this and this , but I 'm not able to see how they relate to this issue I 'm having . <code> public static Func < T , bool > Complement < T > ( Func < T , bool > f ) { return ( T x ) = > ! f ( x ) ; } public static bool GreaterThanTwo ( int x ) { return x > 2 ; } static public void Main ( string [ ] args ) { Func < int , bool > NotGreaterThanTwo = Complement ( GreaterThanTwo ) ; Console.WriteLine ( NotGreaterThanTwo ( 1 ) ) ; } | Complement higher order function |
C_sharp : I would like to write a method that gives me the 3 letters - representing the day , month , year - from a datetimeformat.So in en-US culture my desired return values would be ( plus the separator ) dMy/in de-DE the same method should returnT ( Tag = day ) M ( Monat = month ) J ( Jahr = year ) . ( Separator ) I had a look into the DateTimeFormatInfo class form CurrentCulture but could only find the separator do you have any idea how I can get the rest ? I need this because the TEXT function inside Excel does n't accept the format from the InvariantCulture and only handles it from the currentculture.So something like this is n't valid in german Excel version : this needs to be set with ( it does n't matter if its done with VBA , it does n't get translated ) You can have a look at the following http : //www.rondebruin.nl/win/s9/win013.htmThe string format can be anything since the user can input it as he likes and I need to translate it to the current culture . <code> var culture = Thread.CurrentThread.CurrentCulture ; Console.WriteLine ( culture.DateTimeFormat.DateSeparator ) ; =TEXT ( NOW ( ) ; '' dd.MM.yyyy '' ) =TEXT ( NOW ( ) ; '' TT.MM.JJJJ '' ) | DateTime get the letters representing day , month , year from the currentculture |
C_sharp : I found interesting behavior of LinkedList < T > . I ca n't call Add method for an instance of LinkedList < > . However LinkedList < T > implements ICollection < T > ( link ) which actually has the Add method . Here are examples . When I do like this , it works perfect : But this code even will not compile : Compiler says : `` Can not access explicit implementation of 'ICollection.Add ' '' Error CS1061 'LinkedList ' does not contain a definition for 'Add ' and no extension method 'Add ' accepting a first argument of type 'LinkedList ' could be found ( are you missing a using directive or an assembly reference ? ) '' Moreover if to look at the sources of LinkedList , it implements the method.So my question is , how can it be ? <code> ICollection < string > collection = new LinkedList < string > ( ) ; collection.Add ( `` yet another string '' ) ; LinkedList < string > linkedList = new LinkedList < string > ( ) ; linkedList.Add ( `` yet another string '' ) ; | LinkedList does not contain explicit Add method |
C_sharp : I know I can create expression trees using : Factory methods.Compiler conversion of a lambda expression to an Expression.For complicated expression trees I would prefer 2 because it is more concise.Is it possible to refer to already constructed Expressions using this way ? <code> using System ; using System.Linq.Expressions ; public class Test { public static Expression < Func < int , int > > Add ( Expression expr ) { # if false // works ParameterExpression i = Expression.Parameter ( typeof ( int ) ) ; return Expression.Lambda < Func < int , int > > ( Expression.Add ( i , expr ) , i ) ; # else // compiler error , can I pass expr here somehow ? return i = > i + expr ; # endif } public static void Main ( ) { Func < int , int > f = Add ( Expression.Constant ( 42 ) ) .Compile ( ) ; Console.WriteLine ( f ( 1 ) ) ; } } | Using an Expression in a compiler-generated expression tree |
C_sharp : In one class , ClassA , I have a timer object . In this class I register the event handlers for the timer elapsed event . In another class , ClassB , I have a public event-handler for the timer elapsed event . So I register the event-handler from ClassB in ClassA as follows : What happens if I were to create a new instance of ClassBInstance and the timer elapsed event fires when the previous instance of ClassB 's event-handler is still tied to the Elapsed event of the timer ? For example : <code> myTimer.Elapsed += ClassBInstance.TimerElapsed ClassB classBInstance = new ClassB ( ) ; myTimer.Elapsed += classBInstance.TimerElapsedclassBInstance = new ClassB ( ) ; myTimer.Elapsed += classBInstance.TimerElapsed | What happens when an event fires and tries to execute an event-handler in an object that no longer exists ? |
C_sharp : Sorry about the vocabulary question but I ca n't find this anywhere : how do you call this below ? Is it a statement , a directive , ... ? I want to indicate that you have to insert that line in order to give MyAssembly access to your assembly 's internal members , but I 'd like to use a more specific term than `` line '' .Thanks ! <code> [ assembly : System.Runtime.CompilerServices.InternalsVisibleTo ( `` MyAssembly '' ) ] | What is [ assembly : InternalsVisibleTo ( `` MyAssembly '' ) ] ? A statement , directive , ... ? |
C_sharp : I wonder what the difference is between the following methods with regards to how the object parameter is referenced : andShould I use ref object parameter in cases where I want to change the reference to the object not override the object in the same reference ? <code> public void DoSomething ( object parameter ) { } public void DoSomething ( ref object parameter ) { } | What is the difference between 2 methods with ref object par and without ? |
C_sharp : While analyzing the .NET memory allocation of my code with the Visual Studio 2013 performance wizard I noticed a certain function allocating a lot of bytes ( since it is called in a large loop ) . But looking at the function highlighted in the profiling report I did n't understand why it was allocating any memory at all.To better understand what happened I isolated the code causing the allocations . This was similar to the LinqAllocationTester class below.Once I commented out the LINQ code in that function , which was never executed anyway in the tested code path , no memory was allocated anymore.The NonLinqAllocationTester class imitates this behavior . Replacing the LINQ code with a normal loop also let to no memory allocations.If I run the .NET memory allocation test on the test code below it shows that the LinqAllocationTester causes 100.000 allocations ( 1 per call ) , while the NonLinqAllocationTester has none . Note that useLinq is always false , so the LINQ code itself is never actually being executed.So why does the non executing LINQ code cause memory allocations ? And is there a way to prevent this besides avoiding LINQ functions ? <code> Function Name | Inclusive | Exclusive | Inclusive | Exclusive | Allocations | Allocations | Bytes | Bytes -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -LinqAllocationTester.Test ( int32 ) | 100.000 | 100.000 | 1.200.000 | 1.200.000Program.Main ( string [ ] ) | 100.000 | 0 | 1.200.000 | 0 class Program { static void Main ( string [ ] args ) { List < int > values = new List < int > ( ) { 1 , 2 , 3 , 4 } ; LinqAllocationTester linqTester = new LinqAllocationTester ( false , values ) ; NonLinqAllocationTester nonLinqTester = new NonLinqAllocationTester ( false , values ) ; for ( int i = 0 ; i < 100000 ; i++ ) { linqTester.MaxDifference ( i ) ; } for ( int i = 0 ; i < 100000 ; i++ ) { nonLinqTester.MaxDifference ( i ) ; } } } internal class LinqAllocationTester { private bool useLinq ; private List < int > values ; public LinqAllocationTester ( bool useLinq , List < int > values ) { this.useLinq = useLinq ; this.values = values ; } public int MaxDifference ( int value ) { if ( useLinq ) { return values.Max ( x = > Math.Abs ( value - x ) ) ; } else { int maxDifference = int.MinValue ; foreach ( int value2 in values ) { maxDifference = Math.Max ( maxDifference , Math.Abs ( value - value2 ) ) ; } return maxDifference ; } } } internal class NonLinqAllocationTester { private bool useLinq ; private List < int > values ; public NonLinqAllocationTester ( bool useLinq , List < int > values ) { this.useLinq = useLinq ; this.values = values ; } public int MaxDifference ( int value ) { if ( useLinq ) { return 0 ; } else { int maxDifference = int.MinValue ; foreach ( int value2 in values ) { maxDifference = Math.Max ( maxDifference , Math.Abs ( value - value2 ) ) ; } return maxDifference ; } } } | non executing linq causing memory allocation C # |
C_sharp : I 'm trying to refactor some code to use .NET Core dependency injection via mapping services in startup.cs . I would like to inject an IRequestDatabaseLogger here instead of newing it up . However it requires the context in the constructor . How can I achieve this ? Is it even possible without an DI framework or even then ? <code> public class ActionFilter : ActionFilterAttribute { public override void OnActionExecuting ( ActionExecutingContext context ) { var requestDatabaseLogger = new RequestDatabaseLogger ( context ) ; long logId = requestDatabaseLogger.Log ( ) ; context.HttpContext.AddCurrentLogId ( logId ) ; base.OnActionExecuting ( context ) ; } } | Injecting a logger with constructor dependencies |
C_sharp : I 'm trying to create a generic method that will return a predicate to find elements in an XML document . Basically something like this : Only thing is that this does n't compile . The problem is on the ( T ) x.Attribute ( criterion.PropertyName ) part where the compiler indicates : Can not cast expression of type 'System.Xml.Linq.XAttribute ' to type 'T'Currently I have two methods that are identical except that one casts to double and the other one to decimal . I would really like not to have that kind of duplication . <code> private static Func < XElement , bool > GetPredicate < T > ( Criterion criterion ) { switch ( criterion.CriteriaOperator ) { case CriteriaOperator.Equal : return x = > ( T ) x.Attribute ( criterion.PropertyName ) == ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.GreaterThan : return x = > ( T ) x.Attribute ( criterion.PropertyName ) > ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.GreaterThanOrEqual : return x = > ( T ) x.Attribute ( criterion.PropertyName ) > = ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.LessThan : return x = > ( T ) x.Attribute ( criterion.PropertyName ) < ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.LessThanOrEqual : return x = > ( T ) x.Attribute ( criterion.PropertyName ) < = ( T ) ( criterion.PropertyValue ) ; case CriteriaOperator.NotEqual : return x = > ( T ) x.Attribute ( criterion.PropertyName ) ! = ( T ) ( criterion.PropertyValue ) ; default : throw new ArgumentException ( `` Criteria Operator not supported . `` ) ; } } | Is there a way to do this kind of casting in a c # predicate |
C_sharp : I 've been working , giving up and then reworking on this problem for a couple days . I 've looked at a lot of different ways to go about however I either ca n't implement it correctly or it does n't suit what I need it to do.Basically : I have two arrays , prefix and suffix I need to : Have a minimum of 3 used combined ( 2+1 or 1+2 ) and a max of 6 used ( 3+3 ) .Not use an affix more than once ( except when it 's repeated ( ie there 's two 8 's in prefix ) ) The end goal is to see what combinations can equal X.eg I 've tried looking into Permutations , IEnumerables , Concat 's etc . but can not find something that 'll do this successfully.These are the 'full ' arrays I 'm needing to work with.Any help is appreciated , if I 'm unclear about anything I 'll clarify as best as possible , Thanks ! Edit : I was also suggested to run it to equate all possible outcomes and store it in a hash table to be used when the correct values are used ? Not sure which would work best . <code> prefix = { 0 , 0 , 3 , 8 , 8 , 15 } suffix = { 0 , 3 , 2 , 7 , 7 , 9 , 12 , 15 } X = 423 + 8 + 8 + 2 + 9 + 12 = 420 + 8 + 8 + 7 + 7 + 12 = 42| Prefix | | Suffix |15 + 12 + 15 = 420 + 15 + 0 + 12 + 15 = 42 public int [ ] Prefix = { 0 , 6 , 6 , 8 , 8 , 8 , 8 , 8 , 8 , 11 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 12 , 16 , 15 , 15 , 18 , 18 , 18 , 18 , 18 , 18 , 23 } ; public int [ ] Suffix = { 0 , 3 , 3 , 9 , 11 , 11 , 11 , 17 , 18 , 18 , 20 , 25 , 25 , 27 , 30 , 30 } ; | C # OR Javascript Permutations of two arrays multiple times |
C_sharp : I have been struggling with these elements for about 2 months . The first problem arise when my MVC4 application was recycled . The current logged-in user suddenly can not access any controller actions which are marked [ Authorize ] . Also , any successful access to the controller action which requires database connection produces this error : Can not open user default database . Login failed . Login failed for user 'IIS APPPOOL\DefaultAppPool'.This is weird because if I clear my authentication cookies , it works fine . So there is a problem with the ASPXAUTH and .ASPNET_SessionId cookies.Later I figure out that those errors are caused by session invalidation after server restart or recycle . My session setting was in InProc mode . This means the session is lost every time the server is restarted or recycled . Then I change my session config into Custom Session SQLStore which described inhttps : //msdn.microsoft.com/en-us/library/ms178588.aspx andhttps : //msdn.microsoft.com/en-us/library/ms178589.aspxThe purpose is to store the session data in SQLServer , but the problem seems to not go away . After the server is restarted or recycled , the currently logged-in user still having the problem accessing the controller action.My thought is that the SimpleMembership is not storing the login session in the database . This is how I do login : If I am correct , the system will try to match authentication cookies with login session data and determine if the authentication is still valid . This is why my user is kept having the problem because the matching between session and cookies produce some weird things.I did a lot of research for the past 2 months , I found many similar problems with mine , but I did not find a proper solution.The temporary solution that I am using is to logged-out the user if the server is getting recycled or restarted . This is not a good solution because if the user is in the middle of important transaction or submission , the data can be lost , and the user is redirected to login page again.UpdateI have my machine key set : I try to debug my custom SQL session store , I found out that there is no authentication session is stored in the database . I can only find `` __ControllerTempData '' retrieved from my SQL session , and nothing else.Please correct me if I am wrong , the way the website reuse the authentication cookies and validates it is by comparing authentication cookie and the authentication session , am I right ? Apparently , SimpleMembership Login ( ) does not store the authentication session into the SQL state server.Then which session key is used for the comparing ? <code> WebSecurity.Login ( userName , model.Password , persistCookie : true ) < machineKey validationKey= '' 685DD0E54A38F97FACF4CA27F54D3DA491AB40FE6941110A5A2BA2BC7DDE7411965D45A1E571B7B9283A0D0B382D35A0840B46EDBCE8E05DCE74DE5A37D7A5B3 '' decryptionKey= '' 15653D093ED55032EA6EDDBFD63E4AAA479E79038C0F800561DD2CC4597FBC9E '' validation= '' SHA1 '' decryption= '' AES '' / > | ASP.NET MVC : How do SimpleMembership , SQLSession store , Authentication , and Authorization work ? |
C_sharp : I 'd like to arrange some TextBlocks horizontally without any margins . I can see that my TextBlock is as small as it should be , but for some reason a lot of space is added around it . I think it has something to do with the ListView or its styling , but I do n't know what.I have a following layout : <code> < ListView Width= '' Auto '' SelectionMode= '' None '' Background= '' # 654321 '' ItemsSource= '' { Binding } '' > < ListView.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' / > < /ItemsPanelTemplate > < /ListView.ItemsPanel > < ListView.ItemTemplate > < DataTemplate > < Border Background= '' Black '' > < TextBlock Text= '' { Binding } '' Margin= '' 0,0,0,0 '' / > < /Border > < /DataTemplate > < /ListView.ItemTemplate > < x : String > A < /x : String > < x : String > B < /x : String > < x : String > C < /x : String > < x : String > D < /x : String > < x : String > E < /x : String > < /ListView > | Too much spacing between StackPanel items in Windows Store app |
C_sharp : it 's possible write something like : C # there a equivalent to .apply of javascript ? <code> function foo ( a , b , c ) { return a + b + c ; } var args = [ 2,4,6 ] ; var output = foo.apply ( this , args ) ; // 12 | dynamic arguments definition in C # |
C_sharp : I 've been reading Jon Skeet 's C # In Depth : Second Edition and I noticed something slightly different in one of his examples from something I do myself.He has something similar to the following : Whereas I 've been doing the following : Is there any real difference between the two ? I know Jon Skeet is pretty much the c # god so I tend to think his knowledge in this area is better than mine so I might be misunderstanding something here . Hope someone can help . <code> var item = someObject.Where ( user = > user.Id == Id ) .Single ( ) ; var item = someObject.Single ( user = > user.Id == Id ) ; | Linq with dot notation - which is better form or what 's the difference between these two ? |
C_sharp : I need a data structure with both named column and row . For example : I need to be able to access elements like magic_data_table [ `` row_foo '' , `` col_bar '' ] ( which will give me 3 ) I also need to be able to add new columns like : AFAIK , DataTable only has named column ... EDIT : I do n't need to change the name of a column or a row . However , I may need to insert new rows into the middle of the table . <code> magic_data_table : col_foo col_barrow_foo 1 3 row_bar 2 4 magic_data_table.Columns.Add ( `` col_new '' ) ; magic_data_table [ `` row_foo '' , `` col_new '' ] = 5 ; | Is there a `` DataTable '' with `` named row '' in C # ? |
C_sharp : Robert C. Martin in one of his talks about clean architecture openly criticizes fairly standard way of doing things nowadays.Robert C. Martin - Clean Architecture and DesignWhat I understand as standard way is something like this : Martin here says , that the application should reveal its purpose immediately when you look at its top level directory structure ... I wonder , can anyone provide an example of such directory structure , for instance while using MVVM pattern as a delivery mechanism ? How can one structure his application the way Martin is describing ? <code> solution - UI project - Models - Views - Controllers - Assets - Logic project - Data project | How can a top level directory structure reveal the purpose of the application ? |
C_sharp : I 'm trying to replace CompilationUnitSyntax of a class using Roslyn.However , ReplaceNode that I 'm using has a different signature than ReplaceNode in Roslyn FAQ and any StackOverflow question that I 've looked at . Can anyone point out why is that , and how can I use ReplaceNode that takes old ClassDeclarationSyntax and new ClassDeclarationSyntax as parameters ? I 'm looking at September CTP FAQ¹ , method : particularly the following line : When I 'm attempting to build this code , I 'm getting an error because ReplaceNode expects different arguments : ¹ I 'm fairly sure I 'm using the September CTP : I 'm using the FAQ from % userprofile % \Documents\Microsoft Roslyn CTP - September 2012\CSharp\APISampleUnitTestsCS\FAQ.csNuGet says that my Roslyn package has version 1.2.20906.2 <code> [ FAQ ( 26 ) ] public void AddMethodToClass ( ) CompilationUnitSyntax newCompilationUnit = compilationUnit.ReplaceNode ( classDeclaration , newClassDeclaration ) ; 'Roslyn.Compilers.CSharp.CompilationUnitSyntax ' does not contain a definition for 'ReplaceNode ' and the best extension method overload 'Roslyn.Compilers.CSharp.SyntaxExtensions.ReplaceNode < TRoot > ( TRoot , Roslyn.Compilers.CSharp.SyntaxNode , Roslyn.Compilers.SyntaxRemoveOptions , System.Func < Roslyn.Compilers.CSharp.SyntaxNode , Roslyn.Compilers.CSharp.SyntaxTriviaList > , System.Func < Roslyn.Compilers.CSharp.SyntaxNode , Roslyn.Compilers.CSharp.SyntaxTriviaList > ) ' | Ambiguity in Roslyn 's CompilationUnitSyntax.ReplaceNode |
C_sharp : I have a list like so : and each element of the string array is another array with 3 elements.So countryList [ 0 ] might contain the array : How can I search countryList for a specific array e.g . how to search countryList for <code> List < string [ ] > countryList new string [ 3 ] { `` GB '' , `` United Kingdom '' , `` United Kingdom '' } ; new string [ 3 ] { `` GB '' , `` United Kingdom '' , `` United Kingdom '' } ? | How to search a list in C # |
C_sharp : I would like to implement my generic IQueue < T > interface in an efficient way by doing one implementation if T is struct and another if T is a class.The , I 'd like to have a factory method which based on T 's kind returns an instance of one or the other : Of course , the compiler indicates that T should be non-nullable/nullable type argument respectively.Is there a way to cast T into a struct kind ( and into a class kind ) to make the method compile ? Is this kind of runtime dispatching even possible with C # ? <code> interface IQueue < T > { ... } class StructQueue < T > : IQueue < T > where T : struct { ... } class RefQueue < T > : IQueue < T > where T : class { ... } static IQueue < T > CreateQueue < T > ( ) { if ( typeof ( T ) .IsValueType ) { return new StructQueue < T > ( ) ; } return new RefQueue < T > ( ) ; } | Chose generic implementation if the type parameter is struct or class |
C_sharp : I have a form that i dynamicly compiled and i have a style class . When i copy this style class to my form source and compile it all works fine . But how can i use this style class without copy it to my form source . My main program that compile this form has this class , how can i use it ? Maybe i can pass style class to this for with i compile it , like a var ? Program source : Style folder : Form source : Style source : http : //pastebin.com/CjmQQ9NDProject source - https : //yadi.sk/d/ChtMacrsraD4gIf you compile this source , all will work fine . That because i use style at form.txt file . I separated form from style at form.txt file . I have this style at my main program ( you can see that at screenshot ) . How can i send this style class to my dynamicly compiled form , so form can use it . <code> using System ; using System.CodeDom.Compiler ; using System.Collections.Generic ; using System.IO ; using System.Threading ; using System.Windows.Forms ; using Microsoft.CSharp ; namespace dynamic { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; new Thread ( newForm ) .Start ( ) ; } public void newForm ( ) { using ( CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < string , string > { { `` CompilerVersion '' , `` v4.0 '' } } ) ) { var parameters = new CompilerParameters { GenerateExecutable = false , // Create a dll GenerateInMemory = true , // Create it in memory WarningLevel = 3 , // Default warning level CompilerOptions = `` /optimize '' , // Optimize code TreatWarningsAsErrors = false // Better be false to avoid break in warnings } ; parameters.ReferencedAssemblies.Add ( `` mscorlib.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.Core.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.Data.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.Drawing.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.Xml.dll '' ) ; parameters.ReferencedAssemblies.Add ( `` System.Windows.Forms.dll '' ) ; var source = File.ReadAllText ( `` form.txt '' ) ; CompilerResults results = provider.CompileAssemblyFromSource ( parameters , source ) ; Type type = results.CompiledAssembly.GetType ( `` myForm.Form1 '' ) ; object compiledObject = Activator.CreateInstance ( type ) ; type.GetMethod ( `` ShowDialog '' , new Type [ 0 ] ) .Invoke ( compiledObject , new object [ ] { } ) ; MessageBox.Show ( `` formClosed '' ) ; } } } } using System ; using System.Windows.Forms ; namespace myForm { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; var newTmr = new Timer { Interval = 1000 } ; newTmr.Tick += count ; newTmr.Enabled = true ; } private void count ( Object myObject , EventArgs myEventArgs ) { timer.Value2 = ( Int32.Parse ( timer.Value2 ) + 1 ) .ToString ( ) ; } private void button1_Click ( object sender , System.EventArgs e ) { MessageBox.Show ( `` clicked '' ) ; } private void nsButton1_Click ( object sender , EventArgs e ) { MessageBox.Show ( `` button '' ) ; } } } namespace myForm { partial class Form1 { /// < summary > /// Required designer variable . /// < /summary > private System.ComponentModel.IContainer components = null ; /// < summary > /// Clean up any resources being used . /// < /summary > /// < param name= '' disposing '' > true if managed resources should be disposed ; otherwise , false. < /param > protected override void Dispose ( bool disposing ) { if ( disposing & & ( components ! = null ) ) { components.Dispose ( ) ; } base.Dispose ( disposing ) ; } # region Windows Form Designer generated code /// < summary > /// Required method for Designer support - do not modify /// the contents of this method with the code editor . /// < /summary > private void InitializeComponent ( ) { this.nsTheme1 = new myForm.NSTheme ( ) ; this.nsButton1 = new myForm.NSButton ( ) ; this.timer = new myForm.NSLabel ( ) ; this.nsControlButton1 = new myForm.NSControlButton ( ) ; this.nsTheme1.SuspendLayout ( ) ; this.SuspendLayout ( ) ; // // nsTheme1 // this.nsTheme1.AccentOffset = 0 ; this.nsTheme1.BackColor = System.Drawing.Color.FromArgb ( ( ( int ) ( ( ( byte ) ( 50 ) ) ) ) , ( ( int ) ( ( ( byte ) ( 50 ) ) ) ) , ( ( int ) ( ( ( byte ) ( 50 ) ) ) ) ) ; this.nsTheme1.BorderStyle = System.Windows.Forms.FormBorderStyle.None ; this.nsTheme1.Colors = new myForm.Bloom [ 0 ] ; this.nsTheme1.Controls.Add ( this.nsControlButton1 ) ; this.nsTheme1.Controls.Add ( this.timer ) ; this.nsTheme1.Controls.Add ( this.nsButton1 ) ; this.nsTheme1.Customization = `` '' ; this.nsTheme1.Dock = System.Windows.Forms.DockStyle.Fill ; this.nsTheme1.Font = new System.Drawing.Font ( `` Verdana '' , 8F ) ; this.nsTheme1.Image = null ; this.nsTheme1.Location = new System.Drawing.Point ( 0 , 0 ) ; this.nsTheme1.Movable = true ; this.nsTheme1.Name = `` nsTheme1 '' ; this.nsTheme1.NoRounding = false ; this.nsTheme1.Sizable = true ; this.nsTheme1.Size = new System.Drawing.Size ( 284 , 274 ) ; this.nsTheme1.SmartBounds = true ; this.nsTheme1.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultLocation ; this.nsTheme1.TabIndex = 0 ; this.nsTheme1.Text = `` nsTheme1 '' ; this.nsTheme1.TransparencyKey = System.Drawing.Color.Empty ; this.nsTheme1.Transparent = false ; // // nsButton1 // this.nsButton1.Location = new System.Drawing.Point ( 100 , 166 ) ; this.nsButton1.Name = `` nsButton1 '' ; this.nsButton1.Size = new System.Drawing.Size ( 75 , 23 ) ; this.nsButton1.TabIndex = 0 ; this.nsButton1.Text = `` nsButton1 '' ; this.nsButton1.Click += new System.EventHandler ( this.nsButton1_Click ) ; // // timer // this.timer.Font = new System.Drawing.Font ( `` Segoe UI '' , 11.25F , System.Drawing.FontStyle.Bold ) ; this.timer.Location = new System.Drawing.Point ( 91 , 82 ) ; this.timer.Name = `` timer '' ; this.timer.Size = new System.Drawing.Size ( 101 , 23 ) ; this.timer.TabIndex = 1 ; this.timer.Text = `` nsLabel1 '' ; this.timer.Value1 = `` Timer : `` ; this.timer.Value2 = `` 0 '' ; // // nsControlButton1 // this.nsControlButton1.Anchor = ( ( System.Windows.Forms.AnchorStyles ) ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right ) ) ) ; this.nsControlButton1.ControlButton = myForm.NSControlButton.Button.Close ; this.nsControlButton1.Location = new System.Drawing.Point ( 262 , 4 ) ; this.nsControlButton1.Margin = new System.Windows.Forms.Padding ( 0 ) ; this.nsControlButton1.MaximumSize = new System.Drawing.Size ( 18 , 20 ) ; this.nsControlButton1.MinimumSize = new System.Drawing.Size ( 18 , 20 ) ; this.nsControlButton1.Name = `` nsControlButton1 '' ; this.nsControlButton1.Size = new System.Drawing.Size ( 18 , 20 ) ; this.nsControlButton1.TabIndex = 2 ; this.nsControlButton1.Text = `` nsControlButton1 '' ; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF ( 6F , 13F ) ; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font ; this.ClientSize = new System.Drawing.Size ( 284 , 274 ) ; this.Controls.Add ( this.nsTheme1 ) ; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None ; this.Name = `` Form1 '' ; this.Text = `` Form1 '' ; this.nsTheme1.ResumeLayout ( false ) ; this.ResumeLayout ( false ) ; } # endregion private NSTheme nsTheme1 ; private NSButton nsButton1 ; private NSControlButton nsControlButton1 ; private NSLabel timer ; } } | How to use custom class with dynamic compilation |
C_sharp : I have a function which among other things does a conversion from Utc to Local and vice-versa.The problem is that when I run it on a PC with Win 7 it works OK , but when I run it on a PC with Vista the conversion goes wrong.ex : My current time zone is +2 UTCMyCurrentTime is set to 27.09.2012 , 19:00 and the DateTimeKind is Unspecified.The output on Win 7 is 27.09.2012 , 17:00The output on Vista is 27.09.2012 , 04:00Any ideas why this happens ? Thanks . <code> DateTime utcTime = DateTime.SpecifyKind ( MyCurrentTime , DateTimeKind.Utc ) ; DateTime localTime = new DateTime ( ) ; localTime = utcTime.Date.ToLocalTime ( ) ; | DateTime conversion from Utc to Local in .NET 4.0 |
C_sharp : I have a vector class with two deconstruction methods as follows : Somewhere else I have : This gives me : How is this ambiguous ? Edit : Calling Deconstruct manually works fine : <code> public readonly struct Vector2 { public readonly double X , Y ; ... public void Deconstruct ( out double x , out double y ) { x = this.X ; y = this.Y ; } public void Deconstruct ( out Vector2 unitVector , out double length ) { length = this.Length ; unitVector = this / length ; } } Vector2 foo = ... ( Vector2 dir , double len ) = foo ; CS0121 : The call is ambiguous between the following methods or properties : 'Vector2.Deconstruct ( out double , out double ) ' and 'Vector2.Deconstruct ( out Vector2 , out double ) ' foo.Deconstruct ( out Vector2 dir , out double len ) ; | Deconstruction is ambiguous |
C_sharp : I have some user admin functionality in a WPF app that I 'm currently writing and would like to make it a bit more intuitive for the end userI 'd like to be able to provide some kind of means of easily editing the list of roles a given user belongs to . At the moment the grid is filled as a result of binding to a List < ApplicationUser > ApplicationUser is my own class defined as : As can be seen the roles that the user is in are held in a List < Role > . Role is my own class defined as : The below mockup represents the current state where I just get the roles as a List and through the use of a converter just display the roles as new-line separated strings in the gridviewHowever this is what I 'd like to achieve to make toggling off and on membership of various groups easier . Now that I think about it I 'll probably have to change the definition of Role to include an IsMember property to facilitate binding on the checkbox but if anybody has a better way I 'll welcome that as well . I can change the JOIN type in the sproc so I get back all roles with a query about a particular user and fill the IsMember property accordingly.Thanks for your time ! <code> public class ApplicationUser { public Guid ? UserId { get ; set ; } public string GivenName { get ; set ; } public string Surname { get ; set ; } public string EmailAddress { get ; set ; } public string UserPhone { get ; set ; } public string NtLoginName { get ; set ; } public List < Role > ApplicationRoles { get ; set ; } } public class Role { public Guid RoleId ; public string RoleName ; public string RoleDescription ; } | Enhancing the display of a particular column in a WPF grid view |
C_sharp : I have two arrays , one with values an one with indicesnow I want a result array from the items selected by the indices of indices arrayQuestion : Is there a more generic approach for this ? <code> int [ ] items = { 1 , 2 , 3 , 7 , 8 , 9 , 13 , 16 , 19 , 23 , 25 , 26 , 29 , 31 , 35 , 36 , 39 , 45 } ; int [ ] indices = { 1 , 3 , 5 , 6 , 7 , 9 } ; // 2 , 7 , 9 , 13 , 19int [ ] result = new [ ] { items [ 1 ] , items [ 3 ] , items [ 5 ] , items [ 6 ] , items [ 7 ] , items [ 9 ] } ; | Get array items by index |
C_sharp : Let 's say I have a service interface that looks like this : I would like to fulfill some cross-cutting concerns when calling methods on services like these ; for example , I want unified request logging , performance logging , and error handling . My approach is to have a common base `` Repository ' class with an Invoke method that takes care of invoking the method and doing other things around it . My base class looks something like this : This works fine . However , my whole goal of making the code cleaner is thwarted by the fact that type inference is n't working as expected . For example , if I write a method like this : I get this compilation error : The type arguments for method ... can not be inferred from the usage . Try specifying the type arguments explicitly.Obviously , I can fix it by changing my call to : But I 'd like to avoid this . Is there a way to rework the code so that I can take advantage of type inference ? Edit : I should also mention that an earlier approach was to use an extension method ; type inference for this worked : <code> public interface IFooService { FooResponse Foo ( FooRequest request ) ; } public class RepositoryBase < TService > { private Func < TService > serviceFactory ; public RepositoryBase ( Func < TService > serviceFactory ) { this.serviceFactory = serviceFactory ; } public TResponse Invoke < TRequest , TResponse > ( Func < TService , Func < TRequest , TResponse > > methodExpr , TRequest request ) { // Do cross-cutting code var service = this.serviceFactory ( ) ; var method = methodExpr ( service ) ; return method ( request ) ; } } public class FooRepository : BaseRepository < IFooService > { // ... public BarResponse CallFoo ( ... ) { FooRequest request = ... ; var response = this.Invoke ( svc = > svc.Foo , request ) ; return response ; } } var response = this.Invoke < FooRequest , FooResponse > ( svc = > svc.Foo , request ) ; public static class ServiceExtensions { public static TResponse Invoke < TRequest , TResponse > ( this IService service , Func < TRequest , TResponse > method , TRequest request ) { // Do other stuff return method ( request ) ; } } public class Foo { public void SomeMethod ( ) { IService svc = ... ; FooRequest request = ... ; svc.Invoke ( svc.Foo , request ) ; } } | Why is n't type inference working in this code ? |
C_sharp : How can we access the complete visual studio solution from code analyzer in Roslyn ? I have been trying semantic analysis without much help.This is what I came up with using intellisense but this always gives a null value . <code> var sol = ( ( Microsoft.CodeAnalysis.Diagnostics.WorkspaceAnalyzerOptions ) context.Options ) .Workspace.CurrentSolution ; | Accessing VS complete solution in roslyn |
C_sharp : I 'm generating a file on the fly on the event of a button . I have to following code : I would like the Save As Dialog to appear after the first flush , because the operation can take a while . How would I go about ? After some playing around I discovered that it will buffer 256 characters ( reproducible by sending new string ( ' x ' , 256 ) to the client ) . <code> Response.ClearHeaders ( ) ; Response.ClearContent ( ) ; Response.Buffer = false ; Response.ContentType = `` application/octet-stream '' ; Response.AppendHeader ( `` Content-Disposition '' , `` attachment ; filename=Duck.xml '' ) ; Response.Write ( `` First part '' ) ; Response.Flush ( ) ; //simulate long operation System.Threading.Thread.Sleep ( 10000 ) ; //DoneResponse.Write ( `` Done '' ) ; Response.Flush ( ) ; Response.End ( ) ; | How to make a save as dialog appear `` early '' ? Or : How to make Flush ( ) behave correctly ? |
C_sharp : I have a checkbox substituting a switch-like control.It works great . The only problem is that this checkbox initial mode can be either true or false . For false - no problem , but if it 's true , then when the view is loaded , you immediately see the animation of the switch moving . I want to prevent that . Is there anyway to do so ? Here 's the relevant XAML : This is the way I initialize the view + viewmodel : <code> < CheckBox Style= '' { StaticResource MySwitch } '' IsChecked= '' { Binding ExplicitIncludeMode } '' > < /CheckBox > < Style x : Key= '' MySwitch '' TargetType= '' { x : Type CheckBox } '' > < Setter Property= '' Foreground '' Value= '' { DynamicResource { x : Static SystemColors.WindowTextBrushKey } } '' / > < Setter Property= '' Background '' Value= '' { DynamicResource { x : Static SystemColors.WindowBrushKey } } '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type CheckBox } '' > < ControlTemplate.Resources > < Storyboard x : Key= '' OnChecking '' > < DoubleAnimationUsingKeyFrames BeginTime= '' 00:00:00 '' Storyboard.TargetName= '' slider '' Storyboard.TargetProperty= '' ( UIElement.RenderTransform ) . ( TransformGroup.Children ) [ 3 ] . ( TranslateTransform.X ) '' > < SplineDoubleKeyFrame KeyTime= '' 00:00:00.3000000 '' Value= '' 55 '' / > < /DoubleAnimationUsingKeyFrames > < /Storyboard > < Storyboard x : Key= '' OnUnchecking '' > < DoubleAnimationUsingKeyFrames BeginTime= '' 00:00:00 '' Storyboard.TargetName= '' slider '' Storyboard.TargetProperty= '' ( UIElement.RenderTransform ) . ( TransformGroup.Children ) [ 3 ] . ( TranslateTransform.X ) '' > < SplineDoubleKeyFrame KeyTime= '' 00:00:00.3000000 '' Value= '' 0 '' / > < /DoubleAnimationUsingKeyFrames > < ThicknessAnimationUsingKeyFrames BeginTime= '' 00:00:00 '' Storyboard.TargetName= '' slider '' Storyboard.TargetProperty= '' ( FrameworkElement.Margin ) '' > < SplineThicknessKeyFrame KeyTime= '' 00:00:00.3000000 '' Value= '' 1,1,1,1 '' / > < /ThicknessAnimationUsingKeyFrames > < /Storyboard > < /ControlTemplate.Resources > < DockPanel x : Name= '' dockPanel '' > < ContentPresenter SnapsToDevicePixels= '' { TemplateBinding SnapsToDevicePixels } '' Content= '' { TemplateBinding Content } '' ContentStringFormat= '' { TemplateBinding ContentStringFormat } '' ContentTemplate= '' { TemplateBinding ContentTemplate } '' RecognizesAccessKey= '' True '' VerticalAlignment= '' Center '' / > < Border BorderBrush= '' LightGray '' BorderThickness= '' 1 '' Margin= '' 5,5,0,5 '' > < Grid Width= '' 110 '' Background= '' GhostWhite '' > < TextBlock Text= '' Included '' TextWrapping= '' Wrap '' FontWeight= '' Medium '' FontSize= '' 12 '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Right '' Margin= '' 0,0,3,0 '' Foreground= '' # FF00AFC4 '' / > < TextBlock HorizontalAlignment= '' Left '' Margin= '' 2,0,0,0 '' FontSize= '' 12 '' FontWeight= '' Bold '' Text= '' Excluded '' VerticalAlignment= '' Center '' TextWrapping= '' Wrap '' Foreground= '' # FFE4424D '' / > < Border HorizontalAlignment= '' Left '' x : Name= '' slider '' Width= '' 55 '' BorderThickness= '' 1,1,1,1 '' CornerRadius= '' 3,3,3,3 '' RenderTransformOrigin= '' 0.5,0.5 '' Margin= '' 1,1,1,1 '' > < Border.RenderTransform > < TransformGroup > < ScaleTransform ScaleX= '' 1 '' ScaleY= '' 1 '' / > < SkewTransform AngleX= '' 0 '' AngleY= '' 0 '' / > < RotateTransform Angle= '' 0 '' / > < TranslateTransform X= '' 0 '' Y= '' 0 '' / > < /TransformGroup > < /Border.RenderTransform > < Border.BorderBrush > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' WhiteSmoke '' Offset= '' 0 '' / > < GradientStop Color= '' # FFFFFFFF '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Border.BorderBrush > < Border.Background > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop x : Name= '' grdColor '' Color= '' # FF00AFC4 '' Offset= '' 1 '' / > < GradientStop Color= '' # 092E3E '' Offset= '' 0 '' / > < /LinearGradientBrush > < /Border.Background > < /Border > < /Grid > < /Border > < /DockPanel > < ControlTemplate.Triggers > < MultiTrigger > < MultiTrigger.Conditions > < Condition Property= '' IsChecked '' Value= '' True '' / > < Condition Property= '' IsPressed '' Value= '' True '' / > < /MultiTrigger.Conditions > < MultiTrigger.ExitActions > < BeginStoryboard Storyboard= '' { StaticResource OnUnchecking } '' x : Name= '' OnUnchecking_BeginStoryboard '' / > < /MultiTrigger.ExitActions > < MultiTrigger.EnterActions > < BeginStoryboard Storyboard= '' { StaticResource OnChecking } '' x : Name= '' OnChecking_BeginStoryboard '' / > < /MultiTrigger.EnterActions > < /MultiTrigger > < Trigger Property= '' IsEnabled '' Value= '' False '' > < Setter Property= '' Foreground '' Value= '' { DynamicResource { x : Static SystemColors.GrayTextBrushKey } } '' / > < /Trigger > < /ControlTemplate.Triggers > < /ControlTemplate > < /Setter.Value > < /Setter > < Setter Property= '' Width '' Value= '' 118 '' > < /Setter > < Setter Property= '' Height '' Value= '' 39 '' > < /Setter > < /Style > // ctor of view ( tab ) public MonitoredExtensions ( ) { InitializeComponent ( ) ; DataContext = new MonitoredExtensionsViewModel ( ) ; } // ctor of viewmodelpublic MonitoredExtensionsViewModel ( ) { ... ExplicitIncludeMode = true/false ; ... } | Pause/prevent animation for a checkbox control |
C_sharp : Consider the following code that I 'm using when displaying a Customer 's mailing address inside a table in a view : I find myself using a fair amount of these ternary conditional statements and I am wondering if there is a way to refer back to the object being evaluated in the condition so that I can use it in the expression . Something like this , perhaps : Does something like this exist ? I know I can create a variable to hold the value but it would be nice to keep everything inside one tight little statement in the view pages.Thanks ! <code> < % : Customer.MailingAddress == null ? `` '' : Customer.MailingAddress.City % > < % : Customer.MailingAddress == null ? `` '' : { 0 } .City % > | ASP.NET MVC/C # : Can I avoid repeating myself in a one-line C # conditional statement ? |
C_sharp : If I compile the following code snippet with Visual C # 2010 I ALWAYS get false : Does anybody know why ? ? ? <code> object o = null ; Console.WriteLine ( `` Is null : `` + o == null ) ; // returns false | Testing for null reference always returns false ... even when null |
C_sharp : In ASP.NET Core you can validate all non-GET requests by including this line in Startup.cs ( docs ) : However , if you add the filter by type ( using typeof or the generic Add < T > method ) , the validation does n't seem to work : See https : //github.com/davidgruar/GlobalFilterDemo for a minimal repro.What is going on here ? <code> services.AddMvc ( options = > options.Filters.Add ( new AutoValidateAntiforgeryTokenAttribute ( ) ) ) ; // Does n't workservices.AddMvc ( options = > options.Filters.Add ( typeof ( AutoValidateAntiforgeryTokenAttribute ) ) ; // Does n't work eitherservices.AddMvc ( options = > options.Filters.Add < AutoValidateAntiforgeryTokenAttribute > ( ) ) ; | Why does adding AutoValidateAntiForgeryTokenAttribute by type not work ? |
C_sharp : The following Rx.NET code will use up about 500 MB of memory after about 10 seconds on my machine.If I use the Observable.Generate overload without a Func < int , TimeSpan > parameter my memory usage plateaus at 35 MB.It seems to only be a problem when using SelectMany ( ) or Merge ( ) extension methods . <code> var stream = Observable.Range ( 0 , 10000 ) .SelectMany ( i = > Observable.Generate ( 0 , j = > true , j = > j + 1 , j = > new { N = j } , j = > TimeSpan.FromMilliseconds ( 1 ) ) ) ; stream.Subscribe ( ) ; var stream = Observable.Range ( 0 , 10000 ) .SelectMany ( i = > Observable.Generate ( 0 , j = > true , j = > j + 1 , j = > new { N = j } ) ) ; // j = > TimeSpan.FromMilliseconds ( 1 ) ) ) ; ** Removed ! **stream.Subscribe ( ) ; | Why does this Observable.Generate overload cause a memory leak ? [ Using Timespan < 15ms ] |
C_sharp : I 'm trying to get the positions of controls ( buttons ) but it keeps returning { 0 ; 0 } . I 'm sure there 's an explanation for this , but I ca n't figure out why this happens.I want the position of the control , relative to the window or a certain container . My buttons are arranged in another grid . Taking the margins of these buttons would just give 0,0 since they 're all inside grid cells.What I tried : I tried this with a grid as a parent and with a canvas . Everything I try gives me { 0,0 } . When I change the new Point parameters , the position does change . It stays the same as the parameters.Small part of my XAML : <code> - var point = btnTest.TransformToAncestor ( mainGrid ) .Transform ( new Point ( ) ) ; - UIElement container = VisualTreeHelper.GetParent ( btnTest ) as UIElement ; Point relativeLocation = btnTest.TranslatePoint ( new Point ( 0 , 0 ) , mainGrid ) ; < Grid x : Name= '' mainGrid '' > < Grid Name= '' buttonGrid '' Margin= '' 105,64,98.4,97.8 '' > < Grid.RowDefinitions > < RowDefinition Height= '' 25 '' / > < RowDefinition Height= '' 25 '' / > < RowDefinition Height= '' 25 '' / > < /Grid.RowDefinitions > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 50 '' / > < ColumnDefinition Width= '' 50 '' / > < ColumnDefinition Width= '' 50 '' / > < /Grid.ColumnDefinitions > < Button x : Name= '' btnTest '' Grid.Row= '' 0 '' Grid.Column= '' 0 '' Content= '' Button '' HorizontalAlignment= '' Left '' Margin= '' 0,0,0,0 '' VerticalAlignment= '' Top '' Width= '' 26 '' Height= '' 29 '' / > < Button x : Name= '' btnTest2 '' Grid.Row= '' 1 '' Grid.Column= '' 1 '' Content= '' Button '' HorizontalAlignment= '' Left '' Margin= '' 0,0,0,0 '' VerticalAlignment= '' Top '' Width= '' 26 '' Height= '' 29 '' / > < /Grid > < /Grid > | WPF - Getting position of a control keeps returning { 0 ; 0 } |
C_sharp : ReSharper has features that look for inconsistencies in the use of keywords aliasing a type name . For example , it would see these two declarations and urge you to change one to be like the other ( depending on which is set as your preference ) : This is handy , because I always prefer using the keyword alias for the CLR types when declaring variables , and thus in the above example , I would want to correct the second line . However , this is also problematic because when using static members of the CLR types , I always prefer to use the type names and NOT the keywords . Consider the below example : If the option is set to prefer using the keyword , then ReSharper does not complain about the declarations , but it DOES complain about using the type name to access the static String.Format ( ) method.So , my question is ... Is there any way to configure ReSharper such that it will prefer keywords for declarations but type names for static member access ? In other words , can I configure it to not complain about any of the code in my second example above . <code> string myString1 = `` String 1 '' ; String myString2 = `` String 2 '' ; string myString1 = `` String 1 '' ; string myString2 = String.Format ( `` { 0 } is String 1 . `` , myString1 ) ; | Can ReSharper use keyword for declarations but type name for member access ? |
C_sharp : I know and I think I understand about the ( co/conta ) variance issue with IEnumerables . However I thought the following code would not be affected by it.This class is to mimic BackgroundWorker 's RunWorkerCompletedEventArgs so I can return errors from my WCF service without faulting the connection.Most of my code is working fine so I can do things like thisand it works fine , however the folowing code gives a errorWhere the error is What is going wrong that is causing this error to happen ? <code> [ DataContract ] public class WcfResult < T > { public WcfResult ( T result ) { Result = result ; } public WcfResult ( Exception error ) { Error = error ; } public static implicit operator WcfResult < T > ( T rhs ) { return new WcfResult < T > ( rhs ) ; } [ DataMember ] public T Result { get ; set ; } [ DataMember ] public Exception Error { get ; set ; } } public WcfResult < Client > AddOrUpdateClient ( Client client ) { try { //AddOrUpdateClient returns `` Client '' return client.AddOrUpdateClient ( LdapHelper ) ; } catch ( Exception e ) { return new WcfResult < Client > ( e ) ; } } public WcfResult < IEnumerable < Client > > GetClients ( ClientSearcher clientSearcher ) { try { //GetClients returns `` IEnumerable < Client > '' return Client.GetClients ( clientSearcher , LdapHelper , 100 ) ; } catch ( Exception e ) { return new WcfResult < IEnumerable < Client > > ( e ) ; } } Can not implicitly convert type 'System.Collections.Generic.IEnumerable < myNs.Client > 'to 'myNs.WcfResult < System.Collections.Generic.IEnumerable < myNs.Client > > ' . An explicitconversion exists ( are you missing a cast ? ) | Implicit cast fails for myClass < T > when T is IEnumerable < U > |
C_sharp : Is there a way of calling a method/lines of code multiple times not using a for/foreach/while loop ? For example , if I were to use to for loop : The lines of code I 'm calling do n't use ' i ' and in my opinion the whole loop declaration hides what I 'm trying to do . This is the same for a foreach.I was wondering if there 's a looping statement I can use that looks something like : It 's really clear that I just want to execute that code 6 times and there 's no noise involving index instantiating and adding 1 to some arbitrary variable.As a learning exercise I have written a static class and method : Which works but scores very highly on the pretentious scale and I 'm sure my peers would n't approve.I 'm probably just being picky and a for loop is certainly the most recognisable , but as a learning point I was just wondering if there ( cleaner ) alternatives . Thanks . ( I 've had a look at this thread , but it 's not quite the same ) Using IEnumerable without foreach loop <code> int numberOfIterations = 6 ; for ( int i = 0 ; i < numberOfIterations ; i++ ) { DoSomething ( ) ; SomeProperty = true ; } do ( 6 ) { DoSomething ( ) ; SomeProperty = true ; } Do.Multiple ( int iterations , Action action ) | Looping through a method without for/foreach/while |
C_sharp : We have a lot of code that passes about “ Ids ” of data rows ; these are mostly ints or guids . I could make this code safer by creating a different struct for the id of each database table . Then the type checker will help to find cases when the wrong ID is passed.E.g the Person table has a column calls PersonId and we have code like : Would it be better to have : Has anyone got real life experienceof dong this ? Is it worth the overhead ? Or more pain then it is worth ? ( It would also make it easier to change the data type in the database of the primary key , that is way I thought of this ideal in the first place ) Please don ’ t say use an ORM some other big change to the system design as I know an ORM would be a better option , but that is not under my power at present . However I can make minor changes like the above to the module I am working on at present.Update : Note this is not a web application and the Ids are kept in memory and passed about with WCF , so there is no conversion to/from strings at the edge . There is no reason that the WCF interface can ’ t use the PersonId type etc . The PersonsId type etc could even be used in the WPF/Winforms UI code . The only inherently `` untyped '' bit of the system is the database . This seems to be down to the cost/benefit of spending time writing code that the compiler can check better , or spending the time writing more unit tests . I am coming down more on the side of spending the time on testing , as I would like to see at least some unit tests in the code base . <code> DeletePerson ( int personId ) DeleteCar ( int carId ) struct PersonId { private int id ; // GetHashCode etc ... . } DeletePerson ( PersionId persionId ) DeleteCar ( CarId carId ) | Is it a good idea to create a custom type for the primary key of each data table ? |
C_sharp : I have a float4x4 struct which simply containts 16 floats : I want to copy an array of these structs into a big array of floats . This is as far as I know a 1:1 copy of a chunk of memoryWhat I do know is rather ugly , and not that fast : If I was using a lower level language , I would simply use memcpy , what can I use as an equivilant in C # ? <code> struct float4x4 { public float M11 ; public float M12 ; public float M13 ; public float M14 ; public float M21 ; public float M22 ; public float M23 ; public float M24 ; public float M31 ; public float M32 ; public float M33 ; public float M34 ; public float M41 ; public float M42 ; public float M43 ; public float M44 ; } int n = 0 ; for ( int i = 0 ; i < Length ; i++ ) { array [ n++ ] = value [ i ] .M11 ; array [ n++ ] = value [ i ] .M12 ; array [ n++ ] = value [ i ] .M13 ; array [ n++ ] = value [ i ] .M14 ; array [ n++ ] = value [ i ] .M21 ; array [ n++ ] = value [ i ] .M22 ; array [ n++ ] = value [ i ] .M23 ; array [ n++ ] = value [ i ] .M24 ; array [ n++ ] = value [ i ] .M31 ; array [ n++ ] = value [ i ] .M32 ; array [ n++ ] = value [ i ] .M33 ; array [ n++ ] = value [ i ] .M34 ; array [ n++ ] = value [ i ] .M41 ; array [ n++ ] = value [ i ] .M42 ; array [ n++ ] = value [ i ] .M43 ; array [ n++ ] = value [ i ] .M44 ; } | Is there a faster/cleaner way to copy structs to an array in C # ? |
C_sharp : Im trying to make a universal parser using generic type parameters , but i ca n't grasp the concept 100 % As you might guess , the code does n't compile , since i ca n't convert int|bool|string to T ( eg . value = valueInt ) . Thankful for feedback , it might not even be possible to way i 'm doing it . Using .NET 3.5 <code> private bool TryParse < T > ( XElement element , string attributeName , out T value ) where T : struct { if ( element.Attribute ( attributeName ) ! = null & & ! string.IsNullOrEmpty ( element.Attribute ( attributeName ) .Value ) ) { string valueString = element.Attribute ( attributeName ) .Value ; if ( typeof ( T ) == typeof ( int ) ) { int valueInt ; if ( int.TryParse ( valueString , out valueInt ) ) { value = valueInt ; return true ; } } else if ( typeof ( T ) == typeof ( bool ) ) { bool valueBool ; if ( bool.TryParse ( valueString , out valueBool ) ) { value = valueBool ; return true ; } } else { value = valueString ; return true ; } } return false ; } | Generic type parameters using out |
C_sharp : I have a ( C # ) function that checks four sets of conditions and returns a bool . If any of them are true , it returns true . I 'm sure I could simplify the logic but I want it to be fairly readable.The CodeMaid extension in Visual Studios and tells me the cylomatic complexity of the function is 12 . I looked it up and the cylomatic complexity is the number of independent paths through the source codeI do n't understand why it 's 12 . I can think of it two ways , either the cyclomatic complexity should be 2 , because it always goes through the same path but could return either a true or a false . Or could understand if it was 16 , because the four booleans or 'd together at the end could each be true or false , 2*2*2*2 = 16.Can someone tell me why its 12 ? Maybe even show a diagram so I can visualize the different paths ? Thanks in advance.Edit : I changed it to this . assigning local variables for the checkbox conditions did n't have any effect , but creating booleans out of the `` YES '' / '' NO '' cranked up the complexity to 14 , which I think I understand . <code> public bool FitsCheckBoxCriteria ( TaskClass tasks ) { // note : bool == true/false comparisons mean you do n't have to cast 'bool ? ' as bool // if neither checkboxes are checked , show everything bool showEverything = NoShutDownRequiredCheckBox.IsChecked == false & & ActiveRequiredCheckBox.IsChecked == false ; // if both are checked , only show active non-shutdown tasks bool showActiveNonShutdown = ActiveRequiredCheckBox.IsChecked == true & & tasks.Active == `` YES '' & & NoShutDownRequiredCheckBox.IsChecked == true & & tasks.ShutdownRequired == `` NO '' ; // if active is checked but shudown is n't , display all active bool showActive = ActiveRequiredCheckBox.IsChecked == true & & tasks.Active == `` YES '' & & NoShutDownRequiredCheckBox.IsChecked == false ; // if non-shutdown is checked but active is n't , display all non-shutdown tasks bool showNonShutdown = NoShutDownRequiredCheckBox.IsChecked == true & & tasks.ShutdownRequired == `` NO '' & & ActiveRequiredCheckBox.IsChecked == false ; return showEverything || showActiveNonShutdown || showActive || showNonShutdown ; } public bool FitsCheckBoxCriteria ( LubeTask tasks ) { bool noShutdownReqChecked = ( bool ) NoShutDownRequiredCheckBox.IsChecked ; bool activeChecked = ( bool ) ActiveRequiredCheckBox.IsChecked ; bool active = tasks.Active == `` YES '' ? true : false ; bool shutdownReq = tasks.ShutdownRequired == `` YES '' ? true : false ; // if neither checkboxes are checked , show everything bool showEverything = ! noShutdownReqChecked & & ! activeChecked ; // if both are checked , only show activeChecked non-shutdown tasks bool showActiveNonShutdown = activeChecked & & noShutdownReqChecked & & active & & ! shutdownReq ; // if activeChecked is checked but shudown is n't , display all activeChecked bool showActive = activeChecked & & ! noShutdownReqChecked & & active ; // if non-shutdown is chceked but activeChecked is n't , display all non-shutdown tasks bool showNonShutdown = noShutdownReqChecked & & ! activeChecked & & ! shutdownReq ; return showEverything || showActiveNonShutdown || showActive || showNonShutdown ; } | Why is the cylcomatic complexity of this function 12 ? |
C_sharp : Why does the following compile ? It sure seems like the compiler has enough info to know that the attempted assignment is invalid , since the return type of the Func < > is not dynamic . <code> Func < dynamic , int > parseLength = whatever = > whatever.Length ; dynamic dynamicString = `` String with a length '' ; DateTime wrongType = parseLength ( dynamicString ) ; | Why does the compiler treat the return type of Func < dynamic , int > as strongly typed ? |
C_sharp : I 'm trying to make a dynamic array in C # but I get an annoying error message . Here 's my code : And the error : This is just baffling my mind . I came from VB , so please me gentle , lol.Cheers . <code> private void Form1_Load ( object sender , EventArgs e ) { int [ ] dataArray ; Random random = new Random ( ) ; for ( int i = 0 ; i < random.Next ( 1 , 10 ) ; i++ ) { dataArray [ i ] = random.Next ( 1 , 1000 ) ; } } Use of unassigned local variable 'dataArray ' | Ca n't make an array in C # |
C_sharp : want to know why String behaves like value type while using ==.StringBuilder and String behaves differently with == operator . Thanks . <code> String s1 = `` Hello '' ; String s2 = `` Hello '' ; Console.WriteLine ( s1 == s2 ) ; // True ( why ? s1 and s2 are different ) Console.WriteLine ( s1.Equals ( s2 ) ) ; //True StringBuilder a1 = new StringBuilder ( `` Hi '' ) ; StringBuilder a2 = new StringBuilder ( `` Hi '' ) ; Console.WriteLine ( a1 == a2 ) ; //false Console.WriteLine ( a1.Equals ( a2 ) ) ; //true | Why String behaves like value type while using == |
C_sharp : Currently working on a 2-way lookup association generic , sorted by TKey . At some point I hope to have access like the following : But obviously when TKey == TValue this will fail . Out of curiosity , is there a conditional compile syntax to do this : <code> public class Assoc < TKey , TValue > { public TKey this [ TValue value ] { get ; } public TValue this [ TKey value ] { get ; } } public class Assoc < TKey , TValue > { [ Condition ( ! ( TKey is TValue ) ) ] public TKey this [ TValue value ] { get ; } [ Condition ( ! ( TKey is TValue ) ) ] public TValue this [ TKey value ] { get ; } public TKey Key ( TValue value ) { get ; } public TValue Value ( TKey value ) { get ; } } | Conditional Compile of Generic Methods |
C_sharp : Programmers on my team sometimes open a transaction and forget to include the scope.Complete ( ) statement ( see code block below ) . Any ideas on ways to either ( 1 ) search our solution for missing scope.Complete ( ) statements , or ( 2 ) have Visual Studio automatically highlight or raise a warning for missing scope.Complete ( ) statements ? Here 's the line we miss : What I have tried I have tried using a ReSharper Custom Pattern for this purpose , with no luck . Ideally I would search for something like : However , ReSharper only accepts regular expressions for identifiers , not for statements , so this does not appear to work ( http : //www.jetbrains.com/resharper/webhelp/Reference__Search_with_Pattern.html ) .Any ideas ? I 'm open to using other plugins or tools as well.Thanks , Ben <code> using ( TransactionScope scope = new TransactionScope ( ) ) { /* Perform transactional work here */ scope.Complete ( ) ; < -- we forget this line /* Optionally , include a return statement */ } using ( TransactionScope scope = new TransactionScope ( ) ) { $ statements1 $ [ ^ ( scope.Complete ( ) ; ) ] $ statements2 $ } | C # - How do I check for missing scope.Complete ( ) statements ? |
C_sharp : How would I know what `` it '' means here ? Whole example from MSDN docs <code> productQuery1.SelectValue < Int32 > ( `` it.ProductID '' ) ; using ( AdventureWorksEntities context = new AdventureWorksEntities ( ) ) { string queryString = @ '' SELECT VALUE product FROM AdventureWorksEntities.Products AS product '' ; ObjectQuery < Product > productQuery1 = new ObjectQuery < Product > ( queryString , context , MergeOption.NoTracking ) ; ObjectQuery < Int32 > productQuery2 = productQuery1.SelectValue < Int32 > ( `` it.ProductID '' ) ; foreach ( Int32 result in productQuery2 ) { Console.WriteLine ( `` { 0 } '' , result ) ; } } | Where does `` it '' come from in this example of ObjectSet < T > .SelectValue ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.