text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have a table in my SQL Server database with a column ReviewText of datatype NVARCHAR ( MAX ) .If I insert or update rows via a SQL query with N '' prefix , for example : it works great and it will write smiley into the table.But if I insert it from code : the code will store It 's OK . ? ? without smiley into the column.How to fix this in code ? <code> UPDATE [ dbo ] . [ Reviews ] SET ReviewText = N'It 's OK. ' WHERE Id = [ id ] var review = _context.UserReview.FirstOrDefault ( x = > x.Id == [ id ] ) ; review.ReviewText = `` It 's OK. `` ;
Can not write unicode ( emoji ) into SQL Server table via context ( Entity Framework Core )
C_sharp : I currently haveandThe idea is that when the mouse enters the yellow highlighted control on the left the yellow highlighted control on the right will shake . The control on the right has the x : Name=StatorMinorRadiusEdit So far so good the above works.Now I want to add another complication . I only want the animation to trigger if a value on my view model RotorLobes == 1 . In an imaginary world I would do.In the real world I have no idea how to achieve this . <code> < ContentControl Grid.Column= '' 2 '' Grid.Row= '' 3 '' > < ContentControl.Triggers > < EventTrigger RoutedEvent= '' UIElement.MouseEnter '' > < BeginStoryboard Storyboard= '' { StaticResource ShakeStatorMinorRadiusEdit } '' / > < /EventTrigger > < /ContentControl.Triggers > ... < snip > ... < /ContentControl > < Grid.Resources > < Storyboard x : Key= '' ShakeStatorMinorRadiusEdit '' > < DoubleAnimationUsingKeyFrames Storyboard.TargetName= '' StatorMinorRadiusEdit '' Storyboard.TargetProperty= '' RenderTransform.X '' RepeatBehavior= '' 5x '' > < EasingDoubleKeyFrame KeyTime= '' 0:0:0.05 '' Value= '' 0 '' / > < EasingDoubleKeyFrame KeyTime= '' 0:0:0.1 '' Value= '' 3 '' / > < EasingDoubleKeyFrame KeyTime= '' 0:0:0.15 '' Value= '' 0 '' / > < EasingDoubleKeyFrame KeyTime= '' 0:0:0.20 '' Value= '' -3 '' / > < EasingDoubleKeyFrame KeyTime= '' 0:0:0.25 '' Value= '' 0 '' / > < /DoubleAnimationUsingKeyFrames > < /Storyboard > < /Grid.Resources > < ContentControl Grid.Column= '' 2 '' Grid.Row= '' 3 '' > < ContentControl.Triggers > < EventTrigger RoutedEvent= '' UIElement.MouseEnter '' > < If Property= '' { Binding RotorLobes } '' Value= '' 1 '' / > < BeginStoryboard Storyboard= '' { StaticResource ShakeStatorMinorRadiusEdit } '' / > < /EventTrigger > < /ContentControl.Triggers > ... < snip > ... < /ContentControl >
Putting a guard on a WPF event trigger . Is this possible ?
C_sharp : While reading Jeffrey Richter 's CLR via C # 4th edition ( Microsoft Press ) , the author at one point states that while Object.Equals currently checks for identity equality , Microsoft should have implemented the method like this : This strikes me as very odd : every non-null object of the same type would be equal by default ? So unless overridden : all instances of a type are equal ( e.g . all your locking objects are equal ) , and return the same hash code . And assuming that the == on Object still checks reference equality , this would mean that ( a == b ) ! = a.Equals ( b ) which would also be strange.I think the idea of things being equal if it is the exact same thing ( identity ) is a better idea than just making everything equal unless overridden . But this is a well known book 's 4th edition published by Microsoft , so there must be some merit to this idea . I read the rest of the text but could not help but wonder : Why would the author suggest this ? What am I missing here ? What is the great advantage of Richter 's implementation over the current Object.Equals implementation ? <code> public class Object { public virtual Boolean Equals ( Object obj ) { // The given object to compare to ca n't be null if ( obj == null ) return false ; // If objects are different types , they ca n't be equal . if ( this.GetType ( ) ! = obj.GetType ( ) ) return false ; // If objects are same type , return true if all of their fields match // Because System.Object defines no fields , the fields match return true ; } }
Object.Equals : everything is equal by default
C_sharp : I have to following ProgressIndicator and in the ViewModel ascociated with this View I implement The problem is this binding is failing and I do n't know why . Using Snoop I have the following System.Windows.Data Error : 40 : BindingExpression path error : 'ProgressVisibility ' property not found on 'object ' `` ProgressIndicator ' ( Name='progressIndicator ' ) ' . BindingExpression : Path=ProgressVisibility ; DataItem='ProgressIndicator ' ( Name='progressIndicator ' ) ; target element is 'ProgressIndicator ' ( Name='progressIndicator ' ) ; target property is 'Visibility ' ( type 'Visibility ' ) System.Windows.Data Error : 40 : BindingExpression path error : 'ProgressVisibility ' property not found on 'object ' `` ProgressIndicator ' ( Name='progressIndicator ' ) ' . BindingExpression : Path=ProgressVisibility ; DataItem='ProgressIndicator ' ( Name='progressIndicator ' ) ; target element is 'ProgressIndicator ' ( Name='progressIndicator ' ) ; target property is 'Visibility ' ( type 'Visibility ' ) System.Windows.Data Error : 40 : BindingExpression path error : 'ProgressVisibility ' property not found on 'object ' `` ProgressIndicator ' ( Name='progressIndicator ' ) ' . BindingExpression : Path=ProgressVisibility ; DataItem='ProgressIndicator ' ( Name='progressIndicator ' ) ; target element is 'ProgressIndicator ' ( Name='progressIndicator ' ) ; target property is 'Visibility ' ( type 'Visibility ' ) I appreciate that there is a binding error , but I am setting the main window 's DataContext in the App.xaml.cs via So , Why is the binding failing ? Thanks for your time . <code> < MahAppsControls : ProgressIndicator Width= '' 100 '' Height= '' 10 '' VerticalAlignment= '' Center '' ProgressColour= '' White '' Visibility= '' { Binding ProgressVisibility } '' / > private Visibility progressVisibility = Visibility.Collapsed ; public Visibility ProgressVisibility { get { return progressVisibility ; } set { if ( value == progressVisibility ) return ; progressVisibility = value ; this.OnPropertyChanged ( `` ProgressVisibility '' ) ; } } MainWindow window = new MainWindow ( ) ; MainWindowViewModel mainWindowViewModel = new MainWindowViewModel ( ) ; // When the ViewModel asks to be closed , close the window.EventHandler handler = null ; handler = delegate { mainWindowViewModel.RequestClose -= handler ; window.Close ( ) ; } ; mainWindowViewModel.RequestClose += handler ; // Allow all controls in the window to bind to the ViewModel by setting the // DataContext , which propagates down the element tree.window.DataContext = mainWindowViewModel ; window.Show ( ) ;
Binding Failure with MahAppsMetro ProgressIndicator
C_sharp : i was wondering , because i have a method with multiple default parameters and when i call the method it i have to do it in order so my question is , is there any way to skip the first few default parameters ? Let 's say i want to input only the colour , and the font-family like this : <code> private string reqLabel ( string label , byte fontSize = 10 , string fontColour = `` # 000000 '' , string fontFamily = `` Verdana '' ) { return `` < br / > < strong > < span style=\ '' font-family : `` + fontFamily + `` , sans-serif ; font-size : '' +fontSize.ToString ( ) + `` px ; color : '' + fontColour + `` ; \ '' > '' + label + '' : < /span > < /strong > '' ; } reqLabel ( `` prerequitie ( s ) '' ) reqLabel ( `` prerequitie ( s ) '' , 12 ) reqLabel ( `` prerequitie ( s ) '' , 12 , `` blue '' ) reqLabel ( `` prerequitie ( s ) '' , 12 , `` blue '' , `` Tahoma '' ) reqLabel ( `` Prerequisite ( s ) '' , `` blue '' , `` Tahoma '' ) /* or the same with 2 comma 's where the size param is supposed to be . */reqLabel ( `` Prerequisite ( s ) '' , , `` blue '' , `` Tahoma '' )
calling a method with multiple default values
C_sharp : I need to draw primitives with graphics object with different transformation matrix . I wonder should I dispose the matrix or graphics will do it for me : http : //msdn.microsoft.com/en-us/library/system.drawing.graphics.transform.aspx Says : Because the matrix returned and by the Transform property is a copy of the geometric transform , you should dispose of the matrix when you no longer need it.I do not need it after g.Transform = tmp ; , should I dispose it ? <code> using ( var g = Graphics.FromImage ( ... ) ) { ... some code ... var tmp = g.Transform ; g.TranslateTransform ( ... ) ; ... some code ... g.Transform = tmp ; // should I call tmp.Dispose ( ) here ? tmp.Dispose ( ) ; ... some code that use g ... . }
Should I dispose ( ) the Matrix returned by Graphics.Transform ?
C_sharp : If the title did n't make sense , here 's an example : I 'd like to create an extension method like this : So I can do this : Is this possible ? Where did I go wrong ? The real-world application here is that `` Dog '' is a major base class in my application , and there are many subclasses , each of which may have ILists of things from time to time that need to have group operations performed on them . Having to cast them just to call an extension method on a List of an interface they all implement would be suboptimal.Edit : I goofed up the example a little . My actual code is using IList , I was hoping to have Count and index-based operations available . Based on the answers below , I guess I 'll have to go another direction for the methods that require IList semantics . <code> interface IEat { void Eat ; } class Cat : IEat { void Eat { nom ( ) ; } } class Dog : IEat { void Eat { nom ( ) ; nom ( ) ; nom ( ) ; } } class Labrador : Dog { } public static void FeedAll ( this IEnumerable < out IEat > hungryAnimals ) { foreach ( var animal in hungryAnimals ) animal.Eat ( ) ; } listOfCats.FeedAll ( ) ; listOfLabs.FeedAll ( ) ; listOfMixedHungryAnimals.FeedAll ( ) ;
How can I create a covariant extension method on a generic interface in C # ?
C_sharp : So these two methods have the same signature but different constraintsBut they can not be defined in a single class because they have the same signatures . But in this particular case they 're mutually exclusive . ( Unless I 'm wrong about that ) I understand you can put additional constraints besides class and struct but you ca n't specify both struct and class on the same method . So why would this fail to compile ? <code> public static void Method < T > ( ref T variable ) where T : struct { } public static void Method < T > ( ref T variable ) where T : class { }
Mutally exclusive constraints on two methods with the same signature
C_sharp : If I have a LINQ to SQL statement for exampleWhen I want to see what SQL is being generated by LINQ , what I do is that I comment out the ToList ( ) and put a breakpoint on the command after this LINQ statement and then I can hover it and read the SQL.My question : Is that a correct way of getting the generated SQL ? <code> var query = ( from a in this.Context.Apples select a.Name ) .ToList ( ) ;
Seeing the SQL that LINQ generates
C_sharp : I have this sample code : It obviously return the Result from the t1 task . ( which is 1 ) But how can I get the Result from the last continued task ( it should be 3 { 1+1+1 } ) <code> Task < int > t1= new Task < int > ( ( ) = > 1 ) ; t1.ContinueWith ( r= > 1+r.Result ) .ContinueWith ( r= > 1+r.Result ) ; t1.Start ( ) ; Console.Write ( t1.Result ) ; //1
Get the result for the last Task < > ( continuation ) ?
C_sharp : Following this prototype for unit testing I 've ran into a problem when using JS interop.Just adding a component that uses IJSRuntime will cause the following exception System.InvalidOperationException : Can not provide a value for property 'JsRuntime ' on type 'Application.Components.MyComponent ' . There is no registered service of type 'Microsoft.JSInterop.IJSRuntime'.The JS interop is n't doing anything of interest , it 's just a void function that focuses an element - I do n't care about testing it , I just want to be able to proceed with writing tests for the component itself.How can I use Moq to mock IJSRuntime ? When I try something likeI still get the exception <code> [ Test ] public void ExampleTest ( ) { var component = host.AddComponent < MyComponent > ( ) ; } [ Test ] public void ExampleTest ( ) { var jsRuntimeMock = new Mock < IJSRuntime > ( ) ; host.AddService ( jsRuntimeMock ) ; var component = host.AddComponent < MyComponent > ( ) ; }
Mocking IJSRuntime for Blazor Component unit tests
C_sharp : When i initialize an object using the new object initializers in C # I can not use one of the properties within the class to perform a further action and I do not know why.My example code : Within the Person Class , x will equal 0 ( default ) : However person.Age does equal 29 . I am sure this is normal , but I would like to understand why . <code> Person person = new Person { Name = `` David '' , Age = `` 29 '' } ; public Person ( ) { int x = Age ; // x remains 0 - edit age should be Age . This was a typo }
What am I doing wrong with C # object initializers ?
C_sharp : I 'm struggling to implement a custom auth flow with OAuth and JWT.Basically it should go as follows : User clicks in loginUser is redirect to 3rd party OAuth login pageUser logins into the pageI get the access_token and request for User InfoI get the user info and create my own JWT Token to be sent back and forthI have been following this great tutorial on how to build an OAuth authentication , the only part that differs is that Jerrie is using Cookies.What I Have done so far : Configured the AuthenticationServiceAuth ControllerDisclaimer : This OAuth flow is being incorporated now . I have a flow for creating and using my own JWT working and everything . I will not post here because my problem is before that.What I wantIn Jerrie 's post you can see that he sets DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme ; . With that , when the /auth/loginCallback is reached I have the user claims in the HttpContext.The problem is my DefaultAuthenticateScheme is set to JwtBearersDefault and when the loginCallback is called I ca n't see the user claims nowhere in the Request.How can I have access to the information gained on the OnCreatingTicketEvent in my callback in this scenario ? Bonus question : I do n't know much about OAuth ( sure that is clear now ) . You may have noted that my options.CallbackPath differs from the RedirectUri passed in the Challenge at the login endpoint . I expected the option.CallbackPath to be called by the 3rd Part OAuth provider but this is not what happens ( apparently ) . I did have to set the CallbackPath to the same value I have set in the OAuth provider configuration ( like Jerries tutorial with GitHub ) for it to work . Is that right ? The Callback is used for nothing but a match configuration ? I can even comment the endpoint CallbackPath points to and it keep working the same way ... Thanks ! <code> services.AddAuthentication ( options = > { options.DefaultChallengeScheme = `` 3rdPartyOAuth '' ; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme ; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme ; } ) .AddCookie ( ) // Added only because of the DefaultSignInScheme.AddJwtBearer ( options = > { options.TokenValidationParameters = // Ommited for brevity } ) .AddOAuth ( `` 3rdPartyOAuth '' , options = > { options.ClientId = securityConfig.ClientId ; options.ClientSecret = securityConfig.ClientSecret ; options.CallbackPath = new PathString ( `` /auth/oauthCallback '' ) ; options.AuthorizationEndpoint = securityConfig.AuthorizationEndpoint ; options.TokenEndpoint = securityConfig.TokenEndpoint ; options.UserInformationEndpoint = securityConfig.UserInfoEndpoint ; // Only this for testing for now options.ClaimActions.MapJsonKey ( `` sub '' , `` sub '' ) ; options.Events = new OAuthEvents { OnCreatingTicket = async context = > { // Request for user information var request = new HttpRequestMessage ( HttpMethod.Get , context.Options.UserInformationEndpoint ) ; request.Headers.Accept.Add ( new MediaTypeWithQualityHeaderValue ( `` application/json '' ) ) ; request.Headers.Authorization = new AuthenticationHeaderValue ( `` Bearer '' , context.AccessToken ) ; var response = await context.Backchannel.SendAsync ( request , HttpCompletionOption.ResponseHeadersRead , context.HttpContext.RequestAborted ) ; response.EnsureSuccessStatusCode ( ) ; var user = JObject.Parse ( await response.Content.ReadAsStringAsync ( ) ) ; context.RunClaimActions ( user ) ; } } ; } ) ; [ AllowAnonymous ] [ HttpGet ( `` login '' ) ] public IActionResult LoginIam ( string returnUrl = `` /auth/loginCallback '' ) { return Challenge ( new AuthenticationProperties ( ) { RedirectUri = returnUrl } ) ; } [ AllowAnonymous ] [ DisableRequestSizeLimit ] [ HttpGet ( `` loginCallback '' ) ] public IActionResult IamCallback ( ) { // Here is where I expect to get the user info , create my JWT and send it back to the client return Ok ( ) ; }
OAuth with custom JWT authentication
C_sharp : I have always wondered what the best practice for using a Stream class in C # .Net is . Is it better to provide a stream that has been written to , or be provided one ? i.e : as opposed to ; I have always used the former example for sake of lifecycle control , but I have this feeling that it a poor way of `` streaming '' with Stream 's for lack of a better word . <code> public Stream DoStuff ( ... ) { var retStream = new MemoryStream ( ) ; //Write to retStream return retStream ; } public void DoStuff ( Stream myStream , ... ) { //write to myStream directly }
.Net streams : Returning vs Providing
C_sharp : I want to get full url , in ASp.NET MVC 4 , for example user entered url : And when I try to get this url in Global.asax , I get only http : //localhost:5555/Thanks <code> http : //localhost:5555/ # globalName=MainLines & ItemId=5 protected void Application_BeginRequest ( object sender , EventArgs e ) { var url = HttpContext.Current.Request.Url ; }
How to get full url address
C_sharp : The screenshot says it pretty much.I have the overloads as seen in the screenshot . When using a string as second parameter the compiler should figure out that the first argument can only be a Func and not an expression.But the compiler throws an error saying ' A lamda expression with a statement body can not be converted to an expression tree ' . Why ca n't the compiler figure out the correct overload ? Explicit cast does not help . What works is when i make a local variable of type Func and then use this instead.The framework used is FakeItEasy 1.24.0EDIT : Here is the code that shows the behavior : <code> public static void Main ( string [ ] args ) { //compiler error A.CallTo ( ( ) = > Main ( A < string [ ] > .That.Matches ( strings = > { return true ; } , `` description '' ) ) ) ; //compiles Func < string [ ] , bool > predicate = strings = > { return true ; } ; A.CallTo ( ( ) = > Main ( A < string [ ] > .That.Matches ( predicate , `` description '' ) ) ) ; Console.ReadLine ( ) ; }
Compiler Error for Expression/Func overloads
C_sharp : Here is my class and I do n't want this method to be overridden in child classes , how can I accomplish this behaviour ? <code> class A { public virtual void demo ( ) { } } class B : A { public override void demo ( ) { } } // when Class B be inherited in C , methods can be overridden further , // but I do n't want the method to be overridden further.class C : B { }
Forbid overriding of a method in a derived class
C_sharp : You can find the source code demonstrating this issue @ http : //code.google.com/p/contactsctp5/I have three model objects . Contact , ContactInfo , ContactInfoType . Where a contact has many contactinfo 's and each contactinfo is a contactinfotype . Fairly simple I guess . The problem I 'm running into is when I go to edit the contact object . I pulled it from my contact repository . Then I run `` UpdateModel ( contact ) ; '' and it updates the object with all the values from my form . ( monitoring with debug ) When I save the changes though , I get the following error : The operation failed : The relationship could not be changed because one or more of the foreign-key properties is non-nullable . When a change is made to a relationship , the related foreign-key property is set to a null value . If the foreign-key does not support null values , a new relationship must be defined , the foreign-key property must be assigned another non-null value , or the unrelated object must be deleted.It seems like after I call update model it nulls out my references and this seems to break everything ? Any thoughts on how to remedy would be greatly appreciated . Thanks.Here are my models : My Controller Action : Context Code : <code> public partial class Contact { public Contact ( ) { this.ContactInformation = new HashSet < ContactInformation > ( ) ; } public int ContactId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public virtual ICollection < ContactInformation > ContactInformation { get ; set ; } } public partial class ContactInformation { public int ContactInformationId { get ; set ; } public int ContactId { get ; set ; } public int ContactInfoTypeId { get ; set ; } public string Information { get ; set ; } public virtual Contact Contact { get ; set ; } public virtual ContactInfoType ContactInfoType { get ; set ; } } public partial class ContactInfoType { public ContactInfoType ( ) { this.ContactInformation = new HashSet < ContactInformation > ( ) ; } public int ContactInfoTypeId { get ; set ; } public string Type { get ; set ; } public virtual ICollection < ContactInformation > ContactInformation { get ; set ; } } [ AcceptVerbs ( HttpVerbs.Post ) ] public ActionResult Edit ( Contact person ) { if ( this.ModelState.IsValid ) { var contact = this.contactRepository.GetById ( person.ContactId ) ; UpdateModel ( contact ) ; this.contactRepository.Save ( ) ; TempData [ `` message '' ] = `` Contact Saved . `` ; return PartialView ( `` Details '' , contact ) ; } else { return PartialView ( person ) ; } } protected override void OnModelCreating ( System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder ) { modelBuilder.Entity < Contact > ( ) .HasMany ( c = > c.ContactInformation ) .WithRequired ( ) .HasForeignKey ( c = > c.ContactId ) ; modelBuilder.Entity < ContactInfoType > ( ) .HasMany ( c = > c.ContactInformation ) .WithRequired ( ) .HasForeignKey ( c = > c.ContactInfoTypeId ) ; }
CTP5 EF Code First Question
C_sharp : I have a function as below : I need this function to return either string or int . My return value is set as belowHow to have either one data type as return value in dynamic environment . <code> public var UpdateMapFetcher ( int stationID , int typeID ) if ( finaloutput == `` System.String '' ) { // param1 [ i ] = Convert.ChangeType ( typeID_New.ToString ( ) , typeof ( string ) ) ; returnvalue = returnvalue.ToString ( ) ; return returnvalue ; } else if ( finaloutput == `` System.Int32 '' ) { int a=0 ; a = Convert.ToInt32 ( returnvalue ) ; return a ; }
set multiple return value for method declaration
C_sharp : Feel like asking a stupid question but I want to know answer . I don ’ t need any code to update UI from worker thread I know how to update UI from worker/thread pool.I want to know that why we get this error “ Cross-thread operation not valid : Control `` accessed from a thread other than the thread it was created on. ” whenever any worker thread try to update UI controls ? and Why not this error come when worker thread access object created by Main thread and there is no UI interaction ? See below exampleHow we can apply same kind of restruction for my `` collection '' variable . ? <code> public partial class Form1 : Form { private void Form1_Load ( object sender , EventArgs e ) { } TextBox textbox2 = null ; List < int > collection = new List < int > ( ) ; public Form1 ( ) { InitializeComponent ( ) ; textbox2 = new TextBox ( ) ; } public void UpdateTextBox ( ) { collection.Add ( Thread.CurrentThread.ManagedThreadId ) ; textbox2.Text = `` hi , ThreadId : `` + Thread.CurrentThread.ManagedThreadId.ToString ( ) ; panel1.Controls.Add ( textbox2 ) ; //If remove this line ... will work with worker thread . } private void btnMainThread_Click ( object sender , EventArgs e ) { UpdateTextBox ( ) ; } private void btnWorkerThread_Click ( object sender , EventArgs e ) { Thread t1 = new Thread ( UpdateTextBox ) ; t1.Start ( ) ; //Will get error . why ? } }
Why we cant update UI from worker thread ? same as other variables/object
C_sharp : I have 2 classes declared in a css file ( StyleSheet1.css ) , .Class1 and .Class2 . How do I choose between those two classes after CLICKING A BUTTON for my table tag ? CSS File : As much as possible I want to change classes using C # if possible , but if not , javascript maybe ? I 'm very new to ASP and C # , with a little experience in HTML . Regards <code> < link href= '' Styles/StyleSheet1.css '' rel= '' stylesheet '' type= '' text/css '' / > < table class= '' Class1 '' > < tr > < td > Hello World ! < /td > < /tr > < /table > .Class1 { background-color : Blue ; } .Class2 { background-color : Red ; }
Choose a class for my table after button click ? ( HTML table )
C_sharp : I 've run across .NET 4 's ThreadLocal < T > and was wondering if there 's a way to accumulate the .Value values from all threads . In Microsoft 's ppl C++ library they have Concurrency : :combinable : :combine_each , is there an equivalent method for .NET 's ThreadLocal ? <code> ThreadLocal < long > ticks = new ThreadLocal < long > ( ) ; void AddTicks ( StopWatch sw ) { ticks.Value += sw.ElapsedTicks ; } void ReportTimes ( ) { long totalTicks = /* How do I accumulate all the different values ? */ ; Console.WriteLine ( TimeSpan.FromTicks ( totalTicks ) ) ; }
How to combine all values from a ThreadLocal < T > ?
C_sharp : Below is the code I 'm using but it replies with Method 'Boolean isUser ( System.String ) ' has no supported translation to SQL.Any help ? Btw I 'm using linq to SQL data sourceI found a solution to query the result of the first query as objects but is that good cause I will passing through my data twice.the updated code that worked in the end after using the like as advised by Anders Abel <code> public void dataBind ( ) { using ( var gp = new GreatPlainsDataContext ( ) ) { var emp = from x in gp.Employees let k = isUser ( x.ID ) where x.ActivtyStatus == 0 & & isUser ( x.ID ) ! = false orderby x.ID select new { ID = x.ID , Name = x.FirstName + `` `` + x.MiddleName } ; ListView1.DataSource = emp ; ListView1.DataBind ( ) ; } } public static bool isUser ( string ID ) { int temp ; bool x = int.TryParse ( ID , out temp ) ; return x ; } public void dataBind ( ) { using ( var gp = new GreatPlainsDataContext ( ) ) { var emp = from x in gp.Employees where x.ActivtyStatus == 0 & & SqlMethods.Like ( x.ID , `` [ 0-9 ] % '' ) orderby x.ID select new { ID = x.ID , Name = x.FirstName + `` `` + x.MiddleName } ; ListView1.DataSource = emp ; ListView1.DataBind ( ) ; } }
trying to call a method in the where of a linq statment
C_sharp : I updated my VS Community Edition to 15.8.1 and after that I got this error when I tried to edit my sql inside strongly typed dataset . <code> Configure TableAdapter failedUnable to find connection 'my_connection ' for object 'Web.config'.The connection string could not be found in application settings , or the data provider associated with the connection string could not be loaded . ''
Strongly typed dataset ( .xsd ) error VS Community Edition 15.8.1
C_sharp : I noticed the today that my one application im developing is seriously growing in memory.So I did a Visual Studio Memory Profile and I found the following results : This was on top of the memory Usage with ~600Meg This doesnt seem correct to me and im Not sure why it is so ? Here is my send function : The application blocks on a concurrent QUEUE with messages to send , And when it successfully dequeues a message it loops through all the registered ( Clients ) and sends this message to them.Am I using the begin-send Incorrectly ? One thing I though of , is the fact that its being async , might my program loop through the entire queue and offload it all into the async system buffer ? { EDIT } Way I drain the queue <code> Function Name Inclusive Allocations Exclusive Allocations Inclusive Bytes Exclusive Bytes System.Net.Sockets.Socket.BeginSend ( uint8 [ ] , int32 , int32 , valuetype System.Net.Sockets.SocketFlags , valuetype System.Net.Sockets.SocketError & , class System.AsyncCallback , object ) 3 192 569 3 192 561 635 307 885 635 307 621 private void SendSignal ( Byte [ ] signal ) { if ( state.WorkSocket.Connected ) { try { state.WorkSocket.BeginSend ( signal , 0 , signal.Length , 0 , new AsyncCallback ( SendCallback ) , state.WorkSocket ) ; } catch ( Exception e ) { log.Error ( `` Transmission Failier for ip : `` + state.WorkSocket.AddressFamily , e ) ; } } else { CloseConnection ( ) ; } } private void SendCallback ( IAsyncResult asyncResult ) { try { Socket handler = ( Socket ) asyncResult.AsyncState ; int bytesSent = handler.EndSend ( asyncResult ) ; if ( bytesSent == 0 ) { CloseConnection ( ) ; return ; } } catch { CloseConnection ( ) ; } } ExponentialBackoff eb = new ExponentialBackoff ( ) ; while ( run ) { //Fetch Latest Item ILogItem logItem ; if ( incomingQueue.TryDequeue ( out logItem ) ) { //Handle the logItem SendEventToObservers ( logItem ) ; //Reset the exponetial backoff counter eb.reset ( ) ; } else { //Exponential backoff thread sleep eb.sleep ( ) ; } } private void SendEventToObservers ( ILogItem item ) { foreach ( var observer in registeredObservers.ToList ( ) ) { if ( observer ! = null ) { observer.OnMessageRecieveEvent ( new ObserverEvent ( item ) ) ; // This just calls private void SendSignal ( Byte [ ] signal ) } } }
Memory Issue with async socket and begin Send
C_sharp : I was handling yet another KeyDown event in a user control when I wondered if it existed a library for typing fluent code for handling event likeDoes that exist ? <code> editor.When ( Keys.F ) .IsDown ( ) .With ( Keys.Control ) .Do ( ( sender , e ) = > ShowFindWindow ( ) ) ;
Is there is a fluent approach to handling WinForm event ?
C_sharp : I want to search the name of the students which contains the keywords , at first I pass the keywords separated by commas , but I find the search time is too long.But when I convert these keywords into an array , it is real fast.Why do linq search has a huge difference in efficiency ? Is that because of the array or linq ? Using string to searchUsing array to search <code> var keyWord= '' Lyly , Tom , Jack , Rose '' ; //and so on , more than 500 namesvar student= Context.Students.Where ( i = > keyWord.Contains ( i.Name ) ) ; //very slow var keyWord= '' Lyly , Tom , Jack , Rose '' ; //and so on , more than 500 names var keyWordArray=keyWord.split ( ' , ' ) ; var student= Context.Students.Where ( i = > keyWordArray.Contains ( i.Name ) ) ; //fast
Why do linq search has a huge difference in efficiency when I use string and array especially for large data ?
C_sharp : I am working on a Visual Studio 2010 extension and I want to add an attribute to an MSBuild Item , as follows : So , far the only way I found is using the method IVsBuildPropertyStorage.SetItemAttribute . This works fine for simple strings , but when i try to use characters that are special to MSBuild , I get this result : This means that SetItemAttribute automatically escapes from MsBuild characters and I do n't want that . <code> < EmbeddedResource Include= '' SomeFile.xml '' > < FooAttribute > % ( Filename ) % ( Extension ) < /FooAttribute > < /EmbeddedResource > < EmbeddedResource Include= '' SomeFile.xml '' > < FooAttribute > % 29 % 25 % 28Filename % 29 % 25 % 28Extension % 29 < /FooAttribute > < /EmbeddedResource >
How do I prevent IVsBuildPropertyStorage.SetItemAttribute from escaping special characters ?
C_sharp : The code found in the PresentationCore.dll ( .NET4 WPF ) by ILSpy : The return type of uri.GetComponents is string , why did n't the method just return the string value instead of wrapping it in a StringBuilder ( string ) .ToString ( ) ; Is this by design ? What would be the reason for doing this in a general sense ? Would it reduce allocations or improve Garbage Collection or used for thread safety ? <code> // MS.Internal.PresentationCore.BindUriHelperinternal static string UriToString ( Uri uri ) { if ( uri == null ) { throw new ArgumentNullException ( `` uri '' ) ; } return new StringBuilder ( uri.GetComponents ( uri.IsAbsoluteUri ? UriComponents.AbsoluteUri : UriComponents.SerializationInfoString , UriFormat.SafeUnescaped ) , 2083 ) .ToString ( ) ; }
Why does the WPF Presentation library wrap strings in StringBuilder.ToString ( ) ?
C_sharp : In the following code , I create a DispatcherTimer in the class 's constructor . No one keeps reference on it.In my understanding , the timer should be reclaimed by the garbage collector some time after leaving the constructor 's scope . But that does n't happen ! Even after forcing a garbage collection with GC.Collect ( ) What is going on under the hood ? <code> public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; new DispatcherTimer { Interval = TimeSpan.FromMilliseconds ( 100 ) , IsEnabled = true } .Tick += ( s , e ) = > { textBlock1.Text = DateTime.Now.ToString ( ) ; } ; } }
Garbage collection of C # object declared in constructor
C_sharp : Assuming I have an attached property defined like that : I can write the documentation for the property identifier ( MyPropertyProperty ) and for the accessors ( GetMyProperty and SetMyProperty ) , but I have no idea where to put the documentation for MyClass.MyProperty attached property , since it is not an actual code element.The MSDN library contains such documentation ( see for instance Grid.Row ) , so it must be possible ... Where should I put the XML documentation comments for an attached property ? <code> public static string GetMyProperty ( DependencyObject obj ) { return ( string ) obj.GetValue ( MyPropertyProperty ) ; } public static void SetMyProperty ( DependencyObject obj , string value ) { obj.SetValue ( MyPropertyProperty , value ) ; } // Using a DependencyProperty as the backing store for MyProperty . This enables animation , styling , binding , etc ... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached ( `` MyProperty '' , typeof ( string ) , typeof ( MyClass ) , new UIPropertyMetadata ( 0 ) ) ;
Where to put the XML documentation comments for an attached property ?
C_sharp : My Goal : I have a system where I would like others to be able to add a C # script that contains a specific method that I can lookup and execute from within another class at runtime.My Approach : I created an interface with a method so I can loop through any class that implements the interface using reflection and list them then have the method name be the same between all those classes.I have class that has an enum of all the classes found during the lookup and the user can select between them at runtime.I now need to be able to get the method of the selected class type and invoke it 's method , the problem is I know the name of the method for certain but the type of the class is stored as a variable.The Code : //Pseudo code from memory : Any help appreciated , at this point I have tried many things and am open to just about any possible runtime alternative . I can provide more code if necessary . <code> //Possible solution 1 : Type selectedType = typeSelectedByEnum ; MethodInfo genericMethod = selectedType.GetMethod ( `` TheInterfaceMethod '' ) .MakeGenericMethod ( selectedType ) ; genericMethod.Invoke ( selectedType , new object [ 0 ] ) ; //Possible solution 2 : ( however I would much prefer to use something avaliable prior to .NET 4.6 ) Type selectedType = typeSelectedByEnum ; dynamic changedObj = Convert.ChangeType ( selectedType , selectedType ) ; //-Something here needs to implement IConvertable , how would I set this up ? changedObj.TheInterfaceMethod ( ) ; //Possible solution 3 : //Your solution ? ? !
Dynamically invoke a method given a Type variable
C_sharp : I am trying to develop a mechanism using which I can execute any method with 1 retry attempt . The retry will be triggered if an exception is encountered in the 1st run.The basic Idea is , I will have a generic class for the retry logic , and I want to pass any method in it via delegates . And that method will be executed with 1 retry.So far I have developed this.Now I have a problem : The methods which I want to pass have different Input parameters ( both by number of parameters and object types ) and different output parameters . Is there any way by which I can achieve this ? Basically I want to call the methods like this : Any help would be much appreciated . Thank you . <code> public class RetryHandler { Delegate _methodToRetry ; // default constructor with delegate to function name . public RetryHandler ( Delegate MethodToExecuteWithRetry ) { _methodToRetry = MethodToExecuteWithRetry ; } public void ExecuteWithRetry ( bool IsRetryEnabled ) { try { _methodToRetry.DynamicInvoke ( ) ; } catch ( Exception ex ) { if ( IsRetryEnabled ) { // re execute method . ExecuteWithRetry ( false ) ; } else { // throw exception throw ; } } } } RetryHandler rh = new RetryHandler ( MyMethod1 ( int a , int b ) ) ; int output = ( int ) rh.ExecuteWithRetry ( true ) ; RetryHandler rh2 = new RetryHandler ( MyMethod2 ( string a ) ) ; string output2 = ( string ) rh2.ExecuteWithRetry ( true ) ;
Generic method to execute any method with 1 time retry using Delegates
C_sharp : I Have a DbContext where i need a CompanyId to make a global query , like multi tenant.The CompanyId is added to a token claim , how i 'm can get the claim value and inject on the DbContext ? <code> public void SetGlobalQuery < T > ( ModelBuilder builder ) where T : BaseEntity { builder.Entity < T > ( ) .HasQueryFilter ( e = > e.CompanyId == _companyId ) ; } services.AddScoped ( provider = > { var optionsBuilder = new DbContextOptionsBuilder < MyDbContext > ( ) ; var options = optionsBuilder.UseSqlServer ( Configuration.GetConnectionString ( `` MyDbDatabase '' ) ) .Options ; var companyId = 1 ; return new DocContext ( options , companyId ) ; } ) ;
How to get a token claim value and inject on a dbcontext service
C_sharp : I do have an MVC website , which is running locally just fine.When I 'm debugging the application , off course , it 's running under the HTTP protocol then everything works fine.I do have a controller : Note : I 've removed the code from this method here because it 's irrelivant.This method is called through AngularJS $ http post service . This is done in the following way : This function is called through my view : But , as said previously , when running on my local computer , the code is working fine.But now , I 'm deploying it to a server where the website is running under the HTTPS protocol , which is off course different than HTTP on my local machine.When I 'm executing the code and I click the button to submit the form on the webserver , a new window open and that 's the `` Visual Studio Just In Time Debugger '' asking me for an instance of Visual Studio to debug it , but Visual Studio is not installed on that server , which means I need to not select a debugger.This window is showed to me 3 times . After cancelling all these debugger questions , in my webbrowser I do see the following in the console : This does mean that the application pool has crashed.So what I 've tried right now is the following : Deploying a DEBUG build to the server.In the web.config changed the compilation debug to false.Installed the Visual Studio remote debugger and remote debugged the application.When I 'm remote debugging the application , ( meaning that I 'm attaching to the remote IIS process ) I 'm setting my breakpoint on the very first line of the method in the post action ( see my controller above ) .But , this method is n't hit at all , instead the remote debugging does throw a StackOverflowException as soon as I 've hit the button to submit the form.I 'm hoping someone could point me in the right direction because I 'm lost and it 's driving me nuts for serveral hours.Edit : Added web.configEdit : Added some information about loggingThanks to the comments on this post , I 've double checked in IIS , where the logs are being saved.The screenshot below shows where the logs are being saved : According to another post here on SO , I know that the logs could also be found in the following location : So , I 've executed a new request , and on the server , again the Just-In-Time Debugger Windows opens for a few times ( 5 I guess ) , but in both directories , ( the one defined in the screenshot , and the one listed above ) there are no files created , nor modified with the same timestamp as the request , so I could n't find any more information there.Edit : Added some more information on further investigationAfter some further investigation , I 've found out that the problem is not related to HTTPS , since running the website in IIS on the HTTP protocol gives me the same error.However , the Windows Event Log shows me the following entries : Kind regards , <code> [ Route ( `` messages/new/form/invoice '' ) , HttpPost ] public ActionResult Invoice ( object model ) { var result = JsonConvert.DeserializeObject < dynamic > ( model.ToString ( ) ) ; // Further processing goes here ... } this.saveInvoice = function ( ) { // Post the form . $ http ( { method : `` POST '' , url : `` /messages/new/form/invoice '' , data : { model : JSON.stringify ( this.invoice ) } , headers : { 'Content-Type ' : 'application/json ' } } ) .success ( function ( data ) { $ ( ' # content ' ) .html ( data ) ; } ) .error ( function ( error ) { console.log ( 'An error occured while saving the form : ' + error ) ; } ) ; } < form id= '' invoiceForm '' name= '' invoiceForm '' ng-submit= '' invoiceForm. $ valid & & invoiceCtrl.saveInvoice ( ) ; '' novalidate ng-init= '' invoiceCtrl.Init ( @ Model.FlowId ) '' > An error occured while saving the form : < ! DOCTYPE HTML PUBLIC `` -//W3C//DTD HTML 4.01//EN '' '' http : //www.w3.org/TR/html4/strict.dtd '' > < HTML > < HEAD > < TITLE > Service Unavailable < /TITLE > < META HTTP-EQUIV= '' Content-Type '' Content= '' text/html ; charset=us-ascii '' > < /HEAD > < BODY > < h2 > Service Unavailable < /h2 > < hr > < p > HTTP Error 503 . The service is unavailable. < /p > < /BODY > < /HTML > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < section name= '' entityFramework '' type= '' System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection , EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < section name= '' loggingConfiguration '' type= '' Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings , Microsoft.Practices.EnterpriseLibrary.Logging '' / > < sectionGroup name= '' elmah '' > < section name= '' security '' requirePermission= '' false '' type= '' Elmah.SecuritySectionHandler , Elmah '' / > < section name= '' errorLog '' requirePermission= '' false '' type= '' Elmah.ErrorLogSectionHandler , Elmah '' / > < section name= '' errorMail '' requirePermission= '' false '' type= '' Elmah.ErrorMailSectionHandler , Elmah '' / > < section name= '' errorFilter '' requirePermission= '' false '' type= '' Elmah.ErrorFilterSectionHandler , Elmah '' / > < /sectionGroup > < ! -- For more information on Entity Framework configuration , visit http : //go.microsoft.com/fwlink/ ? LinkID=237468 -- > < /configSections > < connectionStrings > < ! -- Removed for security reasons . -- > < /connectionStrings > < appSettings > < add key= '' webpages : Version '' value= '' 3.0.0.0 '' / > < add key= '' webpages : Enabled '' value= '' false '' / > < add key= '' owin : AutomaticAppStartup '' value= '' false '' / > < add key= '' ClientValidationEnabled '' value= '' true '' / > < add key= '' UnobtrusiveJavaScriptEnabled '' value= '' true '' / > < add key= '' elmah.mvc.disableHandler '' value= '' false '' / > < add key= '' elmah.mvc.disableHandleErrorFilter '' value= '' true '' / > < add key= '' elmah.mvc.requiresAuthentication '' value= '' false '' / > < add key= '' elmah.mvc.IgnoreDefaultRoute '' value= '' false '' / > < add key= '' elmah.mvc.allowedRoles '' value= '' * '' / > < add key= '' elmah.mvc.allowedUsers '' value= '' * '' / > < add key= '' elmah.mvc.route '' value= '' elmah '' / > < /appSettings > < location inheritInChildApplications= '' false '' > < system.web > < globalization uiCulture= '' auto '' culture= '' auto '' / > < authentication mode= '' Forms '' > < forms loginUrl= '' ~/login '' timeout= '' 2880 '' / > < /authentication > < pages > < namespaces > < add namespace= '' System.Web.Helpers '' / > < add namespace= '' System.Web.Mvc '' / > < add namespace= '' System.Web.Mvc.Ajax '' / > < add namespace= '' System.Web.Mvc.Html '' / > < add namespace= '' System.Web.Optimization '' / > < add namespace= '' System.Web.Routing '' / > < add namespace= '' System.Web.WebPages '' / > < add namespace= '' DocTrails3.Net.ViewModels '' / > < /namespaces > < /pages > < compilation debug= '' true '' targetFramework= '' 4.5.1 '' / > < httpRuntime targetFramework= '' 4.5.1 '' requestPathInvalidCharacters= '' & lt ; , & gt ; , % , & amp ; , : , \ , ? '' relaxedUrlToFileSystemMapping= '' true '' maxRequestLength= '' 1048576 '' / > < httpModules > < add name= '' ErrorLog '' type= '' Elmah.ErrorLogModule , Elmah '' / > < add name= '' ErrorMail '' type= '' Elmah.ErrorMailModule , Elmah '' / > < add name= '' ErrorFilter '' type= '' Elmah.ErrorFilterModule , Elmah '' / > < /httpModules > < /system.web > < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < security > < requestFiltering > < requestLimits maxAllowedContentLength= '' 1073741824 '' / > < /requestFiltering > < /security > < httpProtocol > < customHeaders > < remove name= '' X-Powered-By '' / > < /customHeaders > < redirectHeaders > < clear / > < /redirectHeaders > < /httpProtocol > < modules > < add name= '' ErrorLog '' type= '' Elmah.ErrorLogModule , Elmah '' preCondition= '' managedHandler '' / > < add name= '' ErrorMail '' type= '' Elmah.ErrorMailModule , Elmah '' preCondition= '' managedHandler '' / > < add name= '' ErrorFilter '' type= '' Elmah.ErrorFilterModule , Elmah '' preCondition= '' managedHandler '' / > < /modules > < /system.webServer > < /location > < runtime > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' WebGrease '' publicKeyToken= '' 31bf3856ad364e35 '' / > < bindingRedirect oldVersion= '' 0.0.0.0-1.5.2.14234 '' newVersion= '' 1.5.2.14234 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.Helpers '' publicKeyToken= '' 31bf3856ad364e35 '' / > < bindingRedirect oldVersion= '' 1.0.0.0-3.0.0.0 '' newVersion= '' 3.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.WebPages '' publicKeyToken= '' 31bf3856ad364e35 '' / > < bindingRedirect oldVersion= '' 0.0.0.0-3.0.0.0 '' newVersion= '' 3.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.Mvc '' publicKeyToken= '' 31bf3856ad364e35 '' / > < bindingRedirect oldVersion= '' 0.0.0.0-5.1.0.0 '' newVersion= '' 5.1.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.Razor '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-2.0.0.0 '' newVersion= '' 2.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.WebPages.Razor '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-2.0.0.0 '' newVersion= '' 2.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' System.Web.WebPages.Deployment '' publicKeyToken= '' 31bf3856ad364e35 '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-3.0.0.0 '' newVersion= '' 3.0.0.0 '' / > < /dependentAssembly > < dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' publicKeyToken= '' 30ad4fe6b2a6aeed '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-6.0.0.0 '' newVersion= '' 6.0.0.0 '' / > < /dependentAssembly > < /assemblyBinding > < /runtime > < ! -- Entity Framework Configuration . -- > < entityFramework > < defaultConnectionFactory type= '' System.Data.Entity.Infrastructure.SqlConnectionFactory , EntityFramework '' / > < providers > < provider invariantName= '' System.Data.SqlClient '' type= '' System.Data.Entity.SqlServer.SqlProviderServices , EntityFramework.SqlServer '' / > < /providers > < /entityFramework > < elmah > < security allowRemoteAccess= '' yes '' / > < errorLog type= '' Elmah.SqlErrorLog , Elmah '' connectionStringName= '' elmah-sql '' applicationName= '' DocTrails '' / > < /elmah > < /configuration > C : \Windows\System32\LogFiles\HTTPERR Faulting application name : w3wp.exe , version : 8.5.9600.16384 , time stamp : 0x52157ba0Faulting module name : clr.dll , version : 4.0.30319.34014 , time stamp : 0x52e0b784Exception code : 0xc00000fdFault offset : 0x00003022Faulting process id : 0xd00Faulting application start time : 0x01d0452cb0b43b02Faulting application path : C : \Windows\SysWOW64\inetsrv\w3wp.exeFaulting module path : C : \Windows\Microsoft.NET\Framework\v4.0.30319\clr.dllReport Id : f1876b51-b11f-11e4-8149-005056a1b9d2Faulting package full name : Faulting package-relative application ID :
StackOverflowException when posting JSon data to server ( HTTP / HTTPS )
C_sharp : I am currently writing a helper library that connects to shop floor PLCs via Software Toolbox 's TopServer . The TopServer library has separate versions for x86 and x64 architectures and I want to load the appropriate version at runtime using late binding based on the CPU architecture of the calling code . The methods in the two libraries have the same signatures.I can use reflection to load the relevant object using the below code but I am wondering what is the best method of using this instance in the calling code.As I 'm late binding I do n't get the types pre-runtime so was thinking that creating an interface based on the libraries method signatures would be a good way to implement both version.Does anyone have a view on this method or recommendations on other methods ? <code> public class LateBinding { public static T GetInstance < T > ( string dllPath , string fullyQualifiedClassName ) where T : class { Assembly assembly = System.Reflection.Assembly.LoadFile ( dllPath ) ; Type t = assembly.GetType ( fullyQualifiedClassName ) ; return ( T ) Activator.CreateInstance ( t ) ; } }
Late Binding to dll based on CPU architecture
C_sharp : I have a system which uses AOP with ContextBoundObject.This is used to intercept a method call and perform certain operations before and after the function . It all works fine until I make the 'function to be intercepted ' async.I understand that the C # compiler rewrites async methods into a state machine , which returns control to the sink as soon as 'await ' is reachedSo it continues into the interception and executes the code which is meant to be executed only after the Method.I can see there is an `` AsyncProcessMessage '' in IMessageSink , but I ca n't find a way to invoke it , and I am not sure if it will work in the async/await scenario.Is there a way to make Async/Await work with the ContextBoundObject ? Is using another Aspect Oriented Programming approach the only option here ? The code sample below has the method to be intercepted decorated with the 'Audit ' attribute and placed in the AuditFacade which is a ContextBoundObject . The SyncProcessMessage method in the AuditSink has the logic to be executed before and after the method . <code> [ AuditBoundary ] public class AuditFacade : ContextBoundObject { [ Audit ] public ResponseObject DoSomthing ( ) { //Do something return new ResponseObject ( ) ; } /// < summary > /// Async Method to be intercepted /// < /summary > /// < returns > < /returns > [ Audit ] public async Task < ResponseObject > DoSomthingAysnc ( ) { //Do something Async await Task.Delay ( 10000 ) ; return new ResponseObject ( ) ; } } [ AttributeUsage ( AttributeTargets.Method ) ] public class AuditAttribute : Attribute { } [ AttributeUsage ( AttributeTargets.Class ) ] public class AuditBoundaryAttribute : ContextAttribute { public AuditBoundaryAttribute ( ) : base ( `` AuditBoundary '' + Guid.NewGuid ( ) .ToString ( ) ) { } public override void GetPropertiesForNewContext ( IConstructionCallMessage ctorMsg ) { ctorMsg.ContextProperties.Add ( new AuditProperty ( ) ) ; } } public class AuditProperty : IContextProperty , IContributeObjectSink { public string Name { get { return `` AuditProperty '' ; } } public bool IsNewContextOK ( Context newCtx ) { var p = newCtx.GetProperty ( `` AuditProperty '' ) as AuditProperty ; if ( p == null ) return false ; return true ; } public void Freeze ( Context newContext ) { } public IMessageSink GetObjectSink ( MarshalByRefObject obj , IMessageSink nextSink ) { return new AuditSink ( nextSink ) ; } } public class AuditSink : IMessageSink { private IMessageSink nextSink ; public AuditSink ( IMessageSink nextSink ) { this.nextSink = nextSink ; } public IMessage SyncProcessMessage ( IMessage msg ) { var message = msg as IMethodCallMessage ; IMethodReturnMessage returnMessage = null ; ResponseObject response ; //Some Pre Processing happens here var newMessage = new MethodCallMessageWrapper ( message ) ; //Invoke the Method to be Audited returnMessage = nextSink.SyncProcessMessage ( newMessage ) as IMethodReturnMessage ; response = returnMessage.ReturnValue as ResponseObject ; //Some Post Processing happens here with the `` response '' return returnMessage ; } public IMessageSink NextSink { get { return this.nextSink ; } } public IMessageCtrl AsyncProcessMessage ( IMessage msg , IMessageSink replySink ) { return nextSink.AsyncProcessMessage ( msg , replySink ) ; } }
ContextBoundObject with Async/Await
C_sharp : I just download the Iron JS and after doing some 2/3 simple programs using the Execute method , I am looking into the ExecuteFile method.I have a Test.js file whose content is as underI want to invoke the same from C # using Iron JS . How can I do so ? My code so farBut loadfile variable is null ( path is correct ) ..How to invoke JS function , please help ... Also searching in google yielded no help.Thanks <code> function Add ( a , b ) { var result = a+b ; return result ; } var o = new IronJS.Hosting.CSharp.Context ( ) ; dynamic loadFile = o.ExecuteFile ( @ '' d : \test.js '' ) ; var result = loadFile.Add ( 10 , 20 ) ;
How to invoke a function written in a javascript file from C # using IronJS
C_sharp : While giving answer to an SO question , I was told that my solution will introduce a closure over variable so it will have slightly worse performance . So my question is : How will there be a closure ? How will it affect performance ? Here is the questionHere is my solution . I introduced the variable yr to store year.Here it is in the answer 's comments <code> List.Where ( s = > s.ValidDate.Date == DateTime.Today.Year ) .ToList ( ) ; int yr = DateTime.Now.Year ; List.Where ( s = > s.ValidDate.Year == yr ) .ToList ( ) ;
`` Closure over variable gives slightly worse performance '' . How ?
C_sharp : I am working on a project in which I am binding Cart : As shown in image I am populating my cart . Using User Control . And in User control I have populated that using One simple aspx form that is minicart . So now as you can see there is one button Checkout in That page . Which is populated through User Control but actaully its inside my minicart form . So now if I am trying to redirect using that Checkout link button . But that is not calling my click event rather its just postback the page . Basically I want to call aspx page 's click event through user control in my another aspx page.I have tried to call that click event through many ways . But still page is only doing postback . I just want respose.redirect to my checkout page . Even I have tried by using < a > also : But not succeed.. <code> < a id= '' lnkcheckout '' runat= '' server '' href= '' javascript : return false ; '' onclick= '' checkout_onclick '' > Checkout < /a >
Calling Page Click event via User Control
C_sharp : I 'm using protobuf-net for serializing a number of types , some of which are inherited from a base type . I know that the Protocol Buffers spec does not support inheritance , and that the support in protobuf-net is basically a workaround because of that.Rather than using the protobuf-net attributes I am configuring a custom RuntimeTypeModel , and using the Add and AddSubType methods . What I 'm not quite grasping is how I should determine which numbers to use for the field numbers passed to the AddSubType method ( aka the number that would be used in a ProtoInclude attribute ) .This SO question and several others like it do not really describe how the field numbers are chosen , and indeed I 've seen many different variations : 4 & 5 ; 7 & 8 ; 101 & 102 & 103 ; 20 ; 500 ; etc . Obviously they 're chosen so as not to clash with one another , but how are they chosen ? What determines which number to start at ? The following code is a contrived example but it does match my heirarchy ( a base Event type that has two derived subtypes ) . <code> using System ; using System.Collections.Generic ; using ProtoBuf.Meta ; namespace Test { public sealed class History { public History ( ) { Events = new List < Event > ( ) ; } public ICollection < Event > Events { get ; private set ; } } public enum EventType { ConcertStarted , ConcertFinished , SongPlayed } public class Event { public EventType Type { get ; set ; } public DateTimeOffset Timestamp { get ; set ; } } public sealed class Concert : Event { public string Location { get ; set ; } } public sealed class Song : Event { public string Name { get ; set ; } } public static class ModelFactory { public static RuntimeTypeModel CreateModel ( ) { RuntimeTypeModel model = TypeModel.Create ( ) ; model.Add ( typeof ( DateTimeOffset ) , applyDefaultBehaviour : false ) .SetSurrogate ( typeof ( DateTimeOffsetSurrogate ) ) ; model.Add ( typeof ( History ) , applyDefaultBehaviour : false ) .Add ( `` Events '' ) ; model.Add ( typeof ( Concert ) , applyDefaultBehaviour : false ) .Add ( `` Location '' ) ; model.Add ( typeof ( Song ) , applyDefaultBehaviour : false ) .Add ( `` Name '' ) ; model.Add ( typeof ( Event ) , applyDefaultBehaviour : false ) .Add ( `` Type '' , `` Timestamp '' ) .AddSubType ( ? ? ? , typeof ( Concert ) ) .AddSubType ( ? ? ? , typeof ( Song ) ) ; return model ; } } }
How to choose a field number when using protobuf-net inheritance ?
C_sharp : IntroductionWhile testing performance differences with certain LinQ functions today , I noticed , that LastOrDefault ( predicate ) was almost always faster than FirstOrDefault ( predicate ) , which got me a little interested , so i wrote some test cases , to test both functions against each other.I created a list of integer values from 1 to 1 mil like this : and then wrote 2 methods first ( ) and last ( ) which i put in a for loop to run 1000 times , wile setting a breakpoint with a condition to halt after the last iteration , but in every singe case I tested , LastOrDefault was faster . Test casesBoth set to an element the middle of the list ( LastOrDefault is nearly double as fast ) Both set to an element with the same distance within the list ( like 250k and 750k ) - again LastOrDefault was fasterSwitch order of my my method calls ( call Last ( ) before First ( ) ) - no differencerun both with their own lists instead of running both on the same list ( again no difference ) run one , close the app , reopen , run the other ( still LastOrDefault is faster ) set the predicate to an element , thats not in the list ( still same ) Change the predicate to multipe eligable objects ( still same ) create a descending list instead of an ascending one ( no difference ) .Net Core version : 3.0Since the debugger can be inaccurate , I tried again with this code : which also returned 34 sec for FirstOrDefault and 23 sec for LastOrDefaultQuestionHow come LastOrDefault is so significantly faster than FirstOrDefaultin all my test cases ? <code> List < int > l = new List < int > ( ) ; for ( int i = 1 ; i < = 1000000 ; i++ ) { l.Add ( i ) ; } static void first ( List < int > l ) { int e = l.FirstOrDefault ( x = > x == 500000 ) ; int z = l.FirstOrDefault ( x = > x == 500000 ) ; int d = l.FirstOrDefault ( x = > x == 500000 ) ; int v = l.FirstOrDefault ( x = > x == 500000 ) ; int f = l.FirstOrDefault ( x = > x == 500000 ) ; } Console.WriteLine ( DateTime.Now + `` : '' + DateTime.Now.Millisecond ) ; for ( int i = 0 ; i < 1000 ; i++ ) { first ( l ) ; } Console.WriteLine ( DateTime.Now + `` : '' + DateTime.Now.Millisecond ) ; for ( int i = 0 ; i < 1000 ; i++ ) { last ( l ) ; } Console.WriteLine ( DateTime.Now + `` : '' + DateTime.Now.Millisecond ) ;
Why is LastOrDefault ( predicate ) in LINQ faster than FirstOrDefault ( predicate )
C_sharp : A colleague pointed me to a strange case in C # ( not so sure if this actually strange though ) . Suppose you have a class Employee . If you want to create a Generic List < > of type Employee , you can simply do : I understand that I need to pass the Employee type to the Generic list so that it knows the required type information about Employee and generates methods that return and accept parameters that are compatible with Employee . Now my question is , why is n't it possible to do the following ? Should n't this suffice the information required for List < > to know , in order to create a list ? In other words , the type of x which is the type of Employee is now passed as a generic type parameter to List < > , which ( as I used to believe ) is the same as passing list the type name ( in this case Employee ) . I know that something like this is available in Java ( using the .class ) keyword on a variable . I 'm sure I AM missing something , so please , enlight me guys ! <code> List < Employee > x = new List < Employee > ; Employee x = new Employee ( ) ; List < typeof ( x ) > list = new List < typeof ( x ) > ( ) ;
Why this is not possible in C # Generics ?
C_sharp : Why is it that when run I website using Azure SDK 1.3 it opens two browser windows ( or tabs ) despite the fact that I have only defined one end point : What do I have to do to get just one browser window appearing when I run ( using F5 ) my Azure application from Visual Studio ? <code> < Sites > < Site name= '' Web '' > < Bindings > < Binding name= '' Endpoint1 '' endpointName= '' Endpoint1 '' / > < /Bindings > < /Site > < /Sites >
Azure SDK 1.3 opens two browser windows ( or tabs )
C_sharp : In a WinForms application , a Panel is used as a placeholder to display a single User Control as a navigation strategy : whenever the user wishes to navigate to a given area , the respective User Control is added to the Panel . Simplified : As a result of a requirement that is out of my control , the Form must support switching the language dynamically . This is implemented and working fine using Hans Passant 's answer , with a modification to use the User Control 's Resource Manager , which correctly gets and applies the localized text to controls.After applying the resources from the User Control 's respective resource file , however , the layout resulting from DockStyle.Fill is lost for the User Control 's constituent controls that are not themselves set to have a DockStyle.Fill . This has the effect that controls no longer stretch to fill the available area , and are limited to the original size defined in the designer/resource file . Note that the Dock property of the User Control is still set correctly to DockStyle.Fill after applying the resources.I created an example application which illustrates/reproduces the problem : the form below has a panel to which a user control is added dynamically and set to DockStyle.Fill . The user control has a label which is anchored top left on the Default locale and top right in the German locale . I would expect the form to snap the label which is anchored to the right against the right margin of the form , but the size of the user control is reset to the value at design time . View source code.If I start the form on the German locale , the label is correctly laid out against the right edge of the form : What I 'd like to happen is that the layout is retained after calling ApplyResources . Of course I could simply make a copy of the controls ' Location and Size properties ( as suggested in another answer to the same question mentioned above ) but unfortunately values of these properties differ between locales . So , after the localized string and positioning are applied , how can the User Control be directed to layout all its controls anew ? What I 've triedBy looking into InitializeComponent ( ) , I 've tried calling PerformLayout ( ) to the Panel container , the User Control , and the Form to no avail.Adding SuspendLayout ( ) and ResumeLayout ( true ) before and after the call to ApplyResources , also without success.Additional implementation detailsReferences to instantiated User Controls are kept in a private dictionary in the Main Form . When navigation for that control is raised , the previous user control is removed and the existing reference added with the snippet above.Reacting to the user event of changing the language : Applying the resources to all controls in the form : Many thanks in advance for any pointers ! <code> contentPanel.Controls.Clear ( ) ; userControl.Dock = DockStyle.Fill ; contentPanel.Controls.Add ( userControl ) ; protected virtual void OnChangeCulture ( CultureInfo newCulture ) { System.Threading.Thread.CurrentThread.CurrentCulture = newCulture ; System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture ; SuspendLayout ( ) ; ComponentResourceManager resources = new ComponentResourceManager ( this.GetType ( ) ) ; ApplyResources ( resources , this , newCulture ) ; ResumeLayout ( true ) ; } private void ApplyResources ( ComponentResourceManager resourceMgr , Component target , CultureInfo culture ) { //Since target can be a Control or a Component , get their name and children ( OMITTED ) in order to apply the resources and recurse string name ; IEnumerable < Component > children ; //Have the resource manager apply the resources to the given target resourceMgr.ApplyResources ( target , name , culture ) ; //iterate through the collection of children and recursively apply resources foreach ( Component c in children ) { //In the case of user controls , they have their own ResourceManager with the translated strings , so get it and use it instead if ( c is UserControl ) resourceMgr = new ComponentResourceManager ( c.GetType ( ) ) ; //recursively apply resources to the child this.ApplyResources ( resourceMgr , c , culture ) ; } }
Re-apply layout of a dynamically added UserControl after calling ApplyResources
C_sharp : I trying to convert from WPF combobox selected value to enumurator it return not valid cast in the runtime otherwise the string and the enum name is matched my code is <code> Siren.PfundMemberWebServices.Emirates EM = ( Siren.PfundMemberWebServices.Emirates ) cmbemirate.SelectedValue
Convert from String to Enum return not valid cast in WPF
C_sharp : I 'm wondering if there is any shortcut in visual studio to generate automatic documentation for a method or class.For example when I write a method : I want generate the following structure : <code> public void MyFunction ( int d ) { } /// < summary > /// /// < /summary > /// < param name= '' d '' > < /param >
how to simplify code documentation process - visual studio C #
C_sharp : I 'm trying to write a small little scripting engine for a bullet hell game and I would like to do it in F # . I wrote some C # code to conceptualize it , but I 'm having trouble porting it to F # . The C # code is posted below , and I would like some help porting it to F # . I have a feeling the matching F # code will be significantly smaller . I 'm open to any sort of creative solutions : ) <code> interface IRunner { Result Run ( int data ) ; } struct Result { public Result ( int data , IRunner next ) { Data = data ; Next = next ; } public int Data ; public IRunner Next ; } class AddOne : IRunner { public Result Run ( int data ) { return new Result ( data + 1 , null ) ; } } class Idle : IRunner { public Result Run ( int data ) { return new Result ( data , null ) ; } } class Pair : IRunner { IRunner _one ; IRunner _two ; public Pair ( IRunner one , IRunner two ) { _one = one ; _two = two ; } public Result Run ( int data ) { var res = _one.Run ( data ) ; if ( res.Next ! = null ) return new Result ( res.Data , new Pair ( res.Next , _two ) ) ; return new Result ( res.Data , _two ) ; } } class Repeat : IRunner { int _counter ; IRunner _toRun ; public Repeat ( IRunner toRun , int counter ) { _toRun = toRun ; _counter = counter ; } public Result Run ( int data ) { var res = _toRun.Run ( data ) ; if ( _counter > 1 ) { if ( res.Next ! = null ) return new Result ( res.Data , new Pair ( res.Next , new Repeat ( _toRun , _counter - 1 ) ) ) ; return new Result ( res.Data , new Repeat ( _toRun , _counter - 1 ) ) ; } return res ; } } class Sequence : IRunner { IEnumerator < IRunner > _runner ; public Sequence ( IEnumerator < IRunner > runner ) { _runner = runner ; } public Result Run ( int data ) { var res = _runner.Current.Run ( data ) ; bool next = _runner.MoveNext ( ) ; if ( res.Next ! = null ) { return new Result ( res.Data , new Pair ( res.Next , new Sequence ( _runner ) ) ) ; } return new Result ( res.Data , new Sequence ( _runner ) ) ; } }
F # : Need help converting C # to F #
C_sharp : Why is x dynamic , compiler not smart enough or I miss something important ? <code> public string Foo ( object obj ) { return null ; } public string Foo ( string str ) { return null ; } var x = Foo ( ( dynamic ) `` abc '' ) ;
Why dynamic call return dynamic result ?
C_sharp : Lets say I have a library , version 1.0.0 , with the following contents : and I reference this library in a console application with the following contents : Running the program will output the following : If I build a new version of the library , version 2.0.0 , looking like this : and copy this version to the bin folder containing my console program and run it , the results are : I.e , the Class2.Test method is never executed , the base.Test call in Class3.Test seems to be bound to Class1.Test since Class2.Test did n't exist when the console program was compiled.This was very surprising to me and could be a big problem in situations where you deploy new versions of a library without recompiling applications . Does anyone else have experience with this ? Are there any good solutions ? This makes it tempting to add empty overrides that just calls base in case I need to add some code at that level in the future ... Edit : It seems to be established that the call is bound to the first existing base method at compile time . I wonder why . If I build my console program with a reference to version 2 of my library ( which should mean that the call is compiled to invoke Class2.Test ) and then replace the dll in the bin folder with version 1 the result is , as expected : So there is no runtime error when Class2.Test does n't exist . Why could n't the base call have been compiled to invoke Class2.Test in the first place ? It would be interesting to get a comment from Eric Lippert or someone else who works with the compiler ... <code> public class Class1 { public virtual void Test ( ) { Console.WriteLine ( `` Library : Class1 - Test '' ) ; Console.WriteLine ( `` '' ) ; } } public class Class2 : Class1 { } class Program { static void Main ( string [ ] args ) { var c3 = new Class3 ( ) ; c3.Test ( ) ; Console.ReadKey ( ) ; } } public class Class3 : ClassLibrary1.Class2 { public override void Test ( ) { Console.WriteLine ( `` Console : Class3 - Test '' ) ; base.Test ( ) ; } } Console : Class3 - TestLibrary : Class1 - Test public class Class1 { public virtual void Test ( ) { Console.WriteLine ( `` Library : Class1 - Test V2 '' ) ; Console.WriteLine ( `` '' ) ; } } public class Class2 : Class1 { public override void Test ( ) { Console.WriteLine ( `` Library : Class2 - Test V2 '' ) ; base.Test ( ) ; } } Console : Class3 - TestLibrary : Class1 - Test V2 Console : Class3 - TestLibrary : Class1 - Test
Method binding to base method in external library ca n't handle new virtual methods `` between ''
C_sharp : For a network protocol implementation I want to make use of the new Memory and Span classes to achieve zero-copy of the buffer while accessing the data through a struct.I have the following contrived example : The result is that buffer is filled with 7 , 6 , 5 , 4 , 3 , 2 , 1 , which is as desired , but I can hardly imagine that MemoryMarshal.Cast is the only way ( bar anything requiring the unsafe keyword ) to do this . I tried some other methods , but I ca n't figure out how to use them with either a ref struct ( which ca n't be used as generic type argument ) or how to get a struct that 's in the actual buffer and not a copy ( on which any mutations made are not reflected in the buffer ) .Is there a some easier way to get this mutable struct from the buffer ? <code> [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct Data { public int IntValue ; public short ShortValue ; public byte ByteValue ; } static void Prepare ( ) { var buffer = new byte [ 1024 ] ; var dSpan = MemoryMarshal.Cast < byte , Data > ( buffer ) ; ref var d = ref dSpan [ 0 ] ; d.ByteValue = 1 ; d.ShortValue = ( 2 < < 8 ) + 3 ; d.IntValue = ( 4 < < 24 ) + ( 5 < < 16 ) + ( 6 < < 8 ) + 7 ; }
Proper way to get a mutable struct for Memory < byte > / Span < byte > ?
C_sharp : This is a spin-off question based on Eric Lippert 's answer on this question.I would like to know why the C # language is designed not being able to detect the correct interface member in the following specific case . I am not looking on feedback whether designing a class this way is considered best practice . In the code above , Ark has 3 conflicting implementation of GetEnumerator ( ) . This conflict is resolved by treating IEnumerator < Turtle > 's implementation as default , and requiring specific casts for both others.Retrieving the enumerators works like a charm : Why is n't there a similar resolution for LINQ 's Select extension method ? Is there a proper design decision to allow the inconsistency between resolving the former , but not the latter ? <code> class Turtle { } class Giraffe { } class Ark : IEnumerable < Turtle > , IEnumerable < Giraffe > { public IEnumerator < Turtle > GetEnumerator ( ) { yield break ; } // explicit interface member 'IEnumerable.GetEnumerator ' IEnumerator IEnumerable.GetEnumerator ( ) { yield break ; } // explicit interface member 'IEnumerable < Giraffe > .GetEnumerator ' IEnumerator < Giraffe > IEnumerable < Giraffe > .GetEnumerator ( ) { yield break ; } } var ark = new Ark ( ) ; var e1 = ( ( IEnumerable < Turtle > ) ark ) .GetEnumerator ( ) ; // turtlevar e2 = ( ( IEnumerable < Giraffe > ) ark ) .GetEnumerator ( ) ; // giraffevar e3 = ( ( IEnumerable ) ark ) .GetEnumerator ( ) ; // object// since IEnumerable < Turtle > is the default implementation , we do n't need// a specific cast to be able to get its enumeratorvar e4 = ark.GetEnumerator ( ) ; // turtle // This is not allowed , but I do n't see any reason why .. // ark.Select ( x = > x ) ; // turtle expected // these are allowed ark.Select < Turtle , Turtle > ( x = > x ) ; ark.Select < Giraffe , Giraffe > ( x = > x ) ;
Interface conflict resolution in C #
C_sharp : I have a `` Status '' class in C # , used like this : You get the idea.All callers of MyFunction should check the returned Status : Lazy callers however can ignore the Status.or Is it possible to make this impossible ? e.g . an throw exceptionIn general : is it possible to write a C # class on which you have to call a certain function ? In the C++ version of the Status class , I can write a test on some private bool bIsChecked in the destructor and ring some bells when someone does n't check this instance.What is the equivalent option in C # ? I read somewhere that `` You do n't want a destructor in your C # class '' Is the Dispose method of the IDisposable interface an option ? In this case there are no unmanaged resources to free.Additionally , it is not determined when the GC will dispose the object.When it eventually gets disposed , is it still possible to know where and when you ignored that specific Status instance ? The `` using '' keyword does help , but again , it is not required for lazy callers . <code> Status MyFunction ( ) { if ( ... ) // something bad return new Status ( false , `` Something went wrong '' ) else return new Status ( true , `` OK '' ) ; } Status myStatus = MyFunction ( ) ; if ( ! myStatus.IsOK ( ) ) // handle it , show a message , ... MyFunction ( ) ; // call function and ignore returned Status { Status myStatus = MyFunction ( ) ; } // lose all references to myStatus , without calling IsOK ( ) on it
Enforcing required function call
C_sharp : The IndexOf function called on a string returns -1 , while there definitely is a match.Do you have any idea , why it is that it finds `` NY '' but not `` N '' by itself ? If I search for every other letter in the string , it is able to find it , but not the `` N '' .The same issue appears as well with lower case.If I type `` N '' no match either , at `` NY '' it does.Picture of this in console <code> string sUpperName = `` PROGRAMOZÁSI NYELVEK II . ADA EA+GY . ( BSC 08 A ) '' ; string sUpperSearchValue = `` N '' ; sUpperName.IndexOf ( sUpperSearchValue ) ; // Returns -1sUpperSearchValue = `` NY '' ; sUpperName.IndexOf ( sUpperSearchValue ) ; // Returns 13sUpperName [ 13 ] ; // 78 ' N'sUpperSearchValue [ 0 ] ; // 78 ' N'sUpperName [ 13 ] == sUpperSearchValue [ 0 ] ; // true
Why ca n't IndexOf find the character N in combination with Y in hungarian culture ?
C_sharp : I work on a fairly large product . It 's been in development since .Net 1.0 was still a work-in-progress and so it has a lot of bad quality code and was not written with unit tests in mind . Now we 're trying to improve the quality and implement tests for each feature and bug fix . One of the biggest problems we 're having now is dependency hell and god objects . There is one god object in particular that 's bad : Session . Basically , anything related to the current session of the program is in this object . There are also a few other god objects . Anyway , we 've made this god object `` mockable '' by using Resharper to extract an interface out of them . However , this still makes it hard to test because most of the time you have to look at the code that you write to figure out what really needs mocked out of the 100 different methods and properites.Just splitting this class is out of the question right now because there are literally hundreds if not thousands of references to this class . Because I have an interface ( and nearly all code has been refactored to use the interface ) though , I had an interesting idea . What if I made the ISession interface inherit from other interfaces . For instance , if we had something like this : In this way , existing code using ISession would n't have to be updated , nor does the actual implementation have to be updated . But , in new code we write and refactor we can use the more granular IFoo or IBar interfaces , but pass in an ISession . And eventually , I see this as probably making it easier to eventually break up the actual ISession and Session god interface/objectNow to you . Is this a good way of testing against these god objects and eventually breaking them up ? Is this a documented approach and/or design pattern ? Have you ever done anything like this ? <code> interface IBar { string Baz { get ; set ; } } interface IFoo { string Biz { get ; set ; } } interface ISession : IFoo , IBar { }
Interface inheritance to breakup god objects ?
C_sharp : I read alot about async/await , but I still have some lack in understanding the following situation.My question is , should I implement my `` wrapper '' methods as in DoSomething ( ) or like in DoSomethingAsync ( ) .So what 's better ( and why ) : Do I use await in wrapper methods or return the Task directly ? <code> public static async void Main ( ) { await DoSomething ( ) ; await DoSomethingAsync ( ) ; } private static Task DoSomething ( ) { return MyLibrary.DoSomethingAsync ( ) ; } private static async Task DoSomethingAsync ( ) { await MyLibrary.DoSomethingAsync ( ) .ConfigureAwait ( false ) ; } public class MyLibrary { public static async Task DoSomethingAsync ( ) { // Here is some I/O } }
Struggling with async/await C #
C_sharp : I am a bit new to c # so please overlook if you find it trivial . I saw the following `` weird '' code.Can anybody shed a bit of light on it.Specially the _action -= c ; part . <code> public event Action _action ; if ( _action ! = null ) { foreach ( Action c in _action.GetInvocationList ( ) ) { _action -= c ; } }
Correct usage of Action and Events
C_sharp : I have the following dependencyProject A ( owned by me ) uses project_b.dllNewtonsoft.Json.dll ( version 8 ) Project B usesproject_c.dllNewtonsoft.Json.dll ( version 9 ) Project C usesNewtonsoft.Json.dll ( version 4.5 ) Project A calls a method of Project B which will call a method of Project C , then return values back to B , then AI am trying to use assembly binding redirect on Project A . If I set 'newVersion ' as 9.0 , then the code complains ( missing Newtonsoft.jSon.dll 4.5 library ) . Same thing if I set 'newVersion ' as 4.5 , then missing Newtonsoft.Json.dll 9.0 library error happens . I tried 'newVersion ' value of 8.0 as well . It looks simple , and I thought redirecting should solve the issue . What will be the good solution ? Should Project A , B , and C have the same version of Newtonsoft.Json.dll ? Thanks in advance.. <code> < dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-655535.0.0.0 '' newVersion= '' XX '' / > < /dependentAssembly >
C # Assembly Binding Redirects - Newtonsoft.Json
C_sharp : In C # 6.0 you can write this : They have the same result of : But you ca n't write this : It generates the following error : Invalid expression term 'object'.But you can still write this : Why nameof ( object ) does not compile ? <code> var instance = default ( object ) ; var type = typeof ( object ) ; var instance = default ( System.Object ) ; var type = typeof ( System.Object ) ; var name = nameof ( object ) ; var name = nameof ( System.Object ) ;
Why is nameof ( object ) not allowed ?
C_sharp : I 'm developing a C # application that supports Windows Aero in the main form.Some applications that do not support Visual Styles , for example GoToMeeting , disable visual styles and my form is wrongly drawn while GoToMeeting is running ( the Aero client area is drawn black ) .How could I subscribe to a OS event that is fired when visual styles are disabled ? Then I could adjust the client area in my window to be correctly drawn.Managed and unmanaged solutions are valid for me.Thanks in advance.EDIT : According to Hans 's answer , here is the code to manage this event : <code> private const int WM_DWMCOMPOSITIONCHANGED = 0x31e ; [ DllImport ( `` dwmapi.dll '' ) ] private static extern void DwmIsCompositionEnabled ( ref bool pfEnabled ) ; protected override void WndProc ( ref Message m ) { if ( m.Msg == WM_DWMCOMPOSITIONCHANGED ) { bool compositionEnabled = false ; DwmIsCompositionEnabled ( ref compositionEnabled ) ; if ( compositionEnabled ) { // composition has been enabled } else { // composition has been disabled } } base.WndProc ( ref m ) ; }
How do I subscribe to an OS-level event raised when DWM composition/Aero Glass is disabled ?
C_sharp : Take the following simple code . The DoMyCode method has two attributes applied to it , with a space between the entries.This was made in VS 2015 targeting .Net 4.6.If you run this code in Visual Studio 2015 ( update 3 ) it will compile and run with no errors or warnings.However , running the exact same code in Visual Studio 2017 will produce the following exception : I understand why this error happens . I expect that you would need commas between attribute items . In section 17.2 of the C # 5 specifications : An attribute section consists of a pair of square brackets , which surround a comma-separated list of one or more attributes.So why is this syntax legal in VS 2015 ? For full context , I am experimenting with using VS 2017 on my team 's unit test projects . I 've noticed lines like this : which cause syntax errors when compiled in the new Visual Studio system . <code> using System ; namespace AttributeSpaceTesting { class Program { static void Main ( string [ ] args ) { } [ Horse Cow ] static void DoMyCode ( ) { } } [ AttributeUsage ( AttributeTargets.Method ) ] class HorseAttribute : Attribute { } [ AttributeUsage ( AttributeTargets.Method ) ] class CowAttribute : Attribute { } } Syntax error , ' , ' expected [ Description ( @ '' The Test Description '' ) ] [ TestCategory ( `` Regression '' ) , TestCategory ( `` Module '' ) , TestCategory ( `` ModuleRegression '' ) TestMethod ] public void TC_12345_VerifyTheThingWorks ( )
Why does VS 2015 allow attributes separated by spaces while VS 2017 does not ?
C_sharp : Excuse me if I am asking silly question , but can anybody explain the difference between following two calls ( ToArray ) . In the intellisense it does not show them as overloaded methods & of course the output of both the calls are same . <code> List < int > i = new List < int > { 1 , 2 , 5 , 64 } ; int [ ] input = i.Where ( j = > j % 2 == 1 ) .ToArray ( ) ; input = i.Where ( j = > j % 2 == 1 ) .ToArray < int > ( ) ;
Difference between ToArray ( ) & ToArray < int > ( ) ;
C_sharp : I have a method like : Here I am trying to get text from a string until & character is found . My senior modified this method to So instead of storing the index , it will calculate it twice , and his reasoning was that since that method would be called in multiple threads , there could be invalid value stored in index . My understanding of thread is limited , but I believe each thread would have its own stack , where the parameter str and index would be pushed . I have tried reasoning with him , that this is a reentrant code and there is no way that multiple threads could modify a local variable in this method . So , my question is , Am I right in assuming that caching storing index is a better solution , since it will not involve calculating index twice and since it is local variable and str is a parameter local to method , there is no way that multiple threads could modify/change str and index ? Is that correct ? <code> private static string AmpRemove ( string str ) { int index = str.IndexOf ( ' & ' ) ; if ( index > 0 ) str = str.Substring ( 0 , index ) ; return str ; } private static string AmpRemove ( string str ) { if ( str.IndexOf ( ' & ' ) > 0 ) str = str.Substring ( 0 , str.IndexOf ( ' & ' ) ) ; return str ; }
Reentrant code and local variables
C_sharp : I have an array Vector2f structs that each contain two floats , and I want to pass it to a function that takes an array of floats . These structs represent 2d coordinates , and I want the end result to be [ x0 , y0 , x1 , y1 , ... xn , yn ] . Some code to demonstrate : This is easy by copying the contents into a new array of floats , but the data gets large and it would be nice not to duplicate it.This may not be possible due to memory layout . <code> using System ; using System.Runtime.InteropServices ; public class Test { [ StructLayout ( LayoutKind.Sequential ) ] public struct Vector2f { float x ; float y ; public Vector2f ( float x , float y ) { this.x = x ; this.y = y ; } } public static void Main ( ) { Vector2f [ ] structs = new Vector2f [ ] { new Vector2f ( 1f , 2f ) , new Vector2f ( 3f , 4f ) } ; // I want this to contain 1f , 2f , 3f , 4f // But Syntax error , can not convert type ! float [ ] floats = ( float [ ] ) structs ; } }
Use an array of Vector2f structs as an array of floats in-place
C_sharp : I started to use Ninject , on this relatively small project and i have run into a problem : i have this classthat depends on that in turn depends on the DataRepository has a ctor that looks like : Now , i need to be able to use a single instance of BizEntityModel across more than one IDataRepository instance . I also need to create IDataRepository 's along the life of a IBizLogicModule . The IBizLogicModule does not know about Ninject and i want to keep it that way.so my problem is : how to wire all that up , using the Ninject kernel , while : not having to pass the kernel instance around the layers.leaving the code readable close to what it was prior Ninject ( i was just new'ing using a factory method ) .The simple part of the wiring i got so far is : Your guidance is very much appreciatedEDIT : Thanks for your answers ! here 's some more data that was requested : BizEntityModel is registered with Ninject ( code updated ) .if i understand correctly : i can create instances of IDataRepository in IBizLogicModule using a 'factory method ' . but that leaves me with : 1 ) i need to pass a BizEntityModel to the factory method , some times its bran new and sometimes its an existing instance . using the factory method , it will create anew one every time . 2 ) is this a problem that SomeService is in another assembly , and only it has a ref to Ninject.dll ? <code> class SomeService : ISomeService class BizLogicModule : IBizLogicModule class DataRepository : IDataRepository DataRepository ( BizEntityModel context ) Bind < SomeService > ( ) .To < ISomeService > ( ) ; Bind < BizLogicModule > ( ) .To < IBizLogicModule > ( ) ; Bind < DataRepository > ( ) .To < IDataRepository > ( ) ; Bind < BizEntityModel > ( ) .To < BizEntityModel > ( ) ; //ToSelf ( ) // .WithConstructorArgument ( context = > Kernel.Get < BizEntityModel > )
How to keep IoC container in one place , while inner classes need to create dependencies after beeing constructed
C_sharp : I am trying to build a query like thisBut when I run this I get Is Math.Abs not supported or do I have to do it differently ? Here is the sql statement ( a couple more fields then what was in my example ) big this is that it is translating it toso has an extra `` as '' in it.Pick class <code> var d = dbContext.Picks .Where ( /* some conditions */ ) .GroupBy ( x = > new { gameDiff = x.Schedule.GameTotal.Value - x.TieBreakerScore.Value } ) .Select ( g = > new { name = g.Key.firstname , count = g.Count ( ) , gameDiff = Math.Abs ( g.Key.gameDiff ) } ) .OrderByDescending ( x = > x.count ) .ThenBy ( x = > x.gameDiff ) .Take ( top ) .ToList ( ) ; System.Data.SqlClient.SqlException : 'Incorrect syntax near the keyword 'AS ' . 'System.Data.SqlClient.SqlException HResult=0x80131904 Message=Incorrect syntax near the keyword 'AS ' . Source=Core .Net SqlClient Data Provider StackTrace : at System.Data.SqlClient.SqlConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) at System.Data.SqlClient.TdsParser.TryRun ( RunBehavior runBehavior , SqlCommand cmdHandler , SqlDataReader dataStream , BulkCopySimpleResultSet bulkCopyHandler , TdsParserStateObject stateObj , Boolean & dataReady ) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData ( ) at System.Data.SqlClient.SqlDataReader.get_MetaData ( ) at System.Data.SqlClient.SqlCommand.FinishExecuteReader ( SqlDataReader ds , RunBehavior runBehavior , String resetOptionsString ) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , Boolean async , Int32 timeout , Task & task , Boolean asyncWrite , SqlDataReader ds ) at System.Data.SqlClient.SqlCommand.RunExecuteReader ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , TaskCompletionSource ` 1 completion , Int32 timeout , Task & task , Boolean asyncWrite , String method ) at System.Data.SqlClient.SqlCommand.ExecuteReader ( CommandBehavior behavior ) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader ( CommandBehavior behavior ) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute ( IRelationalConnection connection , DbCommandMethod executeMethod , IReadOnlyDictionary ` 2 parameterValues ) at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader ( IRelationalConnection connection , IReadOnlyDictionary ` 2 parameterValues ) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable ` 1.Enumerator.BufferlessMoveNext ( DbContext _ , Boolean buffer ) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute [ TState , TResult ] ( TState state , Func ` 3 operation , Func ` 3 verifySucceeded ) at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable ` 1.Enumerator.MoveNext ( ) at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor ` 1.EnumeratorExceptionInterceptor.MoveNext ( ) at System.Collections.Generic.List ` 1.AddEnumerable ( IEnumerable ` 1 enumerable ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at GetWeeklyWinners ( Int32 week , Int32 season , Int32 top ) in line 23 at ValuesController.test ( ) in line 54 at Microsoft.Extensions.Internal.ObjectMethodExecutor. < > c__DisplayClass33_0. < WrapVoidMethod > b__0 ( Object target , Object [ ] parameters ) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute ( Object target , Object [ ] parameters ) at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.VoidResultExecutor.Execute ( IActionResultTypeMapper mapper , ObjectMethodExecutor executor , Object controller , Object [ ] arguments ) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker. < InvokeActionMethodAsync > d__12.MoveNext ( ) exec sp_executesql N'SELECT TOP ( @ __p_0 ) COUNT ( * ) AS [ count ] , ABS ( [ x.Schedule ] . [ GameTotal ] - [ x ] . [ TieBreakerScore ] AS [ gameDiff ] ) AS [ gameDiff ] FROM [ Picks ] AS [ x ] INNER JOIN [ Schedules ] AS [ x.Schedule ] ON [ x ] . [ ScheduleId ] = [ x.Schedule ] . [ Id ] GROUP BY [ x.Schedule ] . [ GameTotal ] - [ x ] . [ TieBreakerScore ] ORDER BY [ count ] DESC , [ gameDiff ] ' , N ' @ __p_0 int ' , @ __p_0=5 ABS ( [ x.Schedule ] . [ GameTotal ] - [ x ] . [ TieBreakerScore ] AS [ gameDiff ] ) AS [ gameDiff ] public class Pick { public int Id { get ; set ; } public virtual Schedule Schedule { get ; set ; } public int ScheduleId { get ; set ; } public virtual Team TeamChoice { get ; set ; } public int TeamChoiceId { get ; set ; } public int ? TieBreakerScore { get ; set ; } public virtual Employee Employee { get ; set ; } public virtual string EmployeeId { get ; set ; } public DateTime LastUpdated { get ; set ; } }
Math Absolute In Ef Core ?
C_sharp : I am trying to print a WPF visual ( a Canvas to be exact ) containing multiple images . The image sources are loaded from base64 strings that are converted to BitmapSources . When the canvas is shown in a Window the 2 images are displayed correctly , however when its printed using PrintVisual method of PrintDialog , the images both appear the same . I have created a scaled down example that exhibits the behavior that I am seeing.Here is the XAML I 'm using : And this is the code behind : I am assuming that the image sources are being cached somehow somewhere but I really cant explain this behavior . Can anyone explain what is happening here ? <code> < Window x : Class= '' ImagePrintTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : ImagePrintTest '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 800 '' Width= '' 600 '' > < StackPanel > < Button Content= '' Print '' Click= '' Button_Click '' / > < Canvas x : Name= '' ImageCanvas '' > < Image x : Name= '' ImageA '' Canvas.Left= '' 50 '' Canvas.Top= '' 50 '' Width= '' 380 '' Height= '' 56 '' / > < Image x : Name= '' ImageB '' Canvas.Left= '' 50 '' Canvas.Top= '' 150 '' Width= '' 380 '' Height= '' 56 '' / > < /Canvas > < /StackPanel > public partial class MainWindow : Window { string ABC_DATA = @ '' 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 '' ; string DEF_DATA = @ '' iVBORw0KGgoAAAANSUhEUgAAAXwAAAA4CAYAAAD+WUMEAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAkXSURBVHhe7d1bbBxXHQbw78xt77v2ri9rO87FuTVO2qRJSkkTCakNSlWUoNIHglBRK3F5RUJUFa9IATUCIQSRkCpe4IUnHpBAUAnxhNqqVZOqMYWW4CR1mviW+La7s7szh/+s7SrYG3t3jaV15vspo43PjHf3SONv/ntm5qzSWoOIiB5+xtIjERE95Bj4REQhwcAnIgoJBj4RUUgw8ImIQoKBT0QUEgx8IqKQYOATEYUEA5+IKCQY+EREIcHAJyIKCQY+EVFIcPK0sPF9lCsao/O+niprFKSpmT0gYhvojJvodRS6Lail5uZ4PubKPkbnfD3rAcWl5qaZBlIRA3uS8mhCOUvNn/E1ylUf1+V1Jlvo67JU1ERW+txnQ8lLEW1ZDPywcSuYmC3rSyNl/G3Kw6g0+YtrGpLP2HhyKIWzXQa+mGox8EtlXB0v61+OuLhc0Bhbam5azMGhbgevHHDwaMJAVvbnpTWLyhVMzSz29a/S1+vSJMeXph0ciOPkjji+0gEciLbYZ6I2wMAPmwUXY5OufuVqGX+WEJyWpmb2gHTMxI5cFIcSCvvjkn0xCwcyJs5mTRVrtPotuHjvtqt/fNnFWwtSgS81Ny0ewdF8FBcOOzgmpXfXysCXg9v4XXmdKyX8cdzDv6WpurimKY9vT+CZPUm8KEeUx2IMfNq6GPhhM1PS1++U8K1/VfDG3cXaPmIZiFoKcQlseXggr6pR8jRmZJF/gCkbd0bxbH8Erw3ZGJTET1lQQe6vmYorAv+GNFnyXDF58ZQ8Go1GqlT4j65V4dcJfLPBvt7vYP9ihf9CJyt82toY+GFTJ/CHJdCO5yM4nQLydq1pFe1r3Jss4Z3JCn4t4TkVlMpB9NkmepI2hjsdfH2njXP9Fjpkzarx9PutCPxPJOT7u2P4fLeN81218fjGGAbSwRh+6gFj+HUCf29fDMf7onhG+tr/gL6uFIzh5ziGTw8BBn7Y1An8E7tTOLMrjm9IibwrUr+CDQJ/ZtrVV6Yr+N2Uj5uzVUzNV/FPF5hWktCOhXM7Inh+u4NTHQa2OUpFl353lRWBf0tK7d2DSZwdjODVARPZVk8Gr1Qn8I8PSV+H4rXhmd0P6CvRw4r1CjVEGQqZXESd2p1UP3kirX60L4JvBgeIoKyuBpfauPjTjRJe+0cZ7837mJVjBEsJovbCwKeGKaVgLo21D3ZF8ORQEud7LZxJAhFZX3E9TM+X8faMxtWF1i6BJKLNw8CnlmRSttrbH1PP5S083aHQKXuSLZX+QqGCt6c8vD+rUZLEb+UySCLaHAx8apkt1f7OLgfDOQd7DQl9aStWNa6MV3B5uoI7UuS3fFMVEf3fMfCpZUoB8YSttmdsnEwDg45U9MFlm/NVjM17tRO693yO7BC1CwY+tS5IfMdCb9LC6azCrpi0BfHuerhX9HG1AEihT0RtgoFPGxYxFbpjBhK1O5mCxPdRqPr4tAQscBCfqG0w8GnDoqZSPTETCXt5d5LA93yMFTUWWpnLgIg2BQOfNixiAl1RA/H75iooeBq3ip4EfjNTsxHRZuKdtmHT4p22a3KljJ8r6QsflvGL/1RqE7JlspHa3bPf32bg+eyK2XFW3Gl7U1ZnMw72py2cSiusOwmbY0LFLZzLGTiSWGPmnTp32uaD99Vh43AcyK47hUPw1AYO9lg4lrfQIw2JxRVEWxIDP2w2I/ArEvjFMi5ddfXrH5drwRptIvCbni0z5cDIxfD6Phsv95pNBX5zI0zBkcfGVw9F8e3HozgkPwWhX1tFtAVxSIeIKCRY4YfNZlT45WBIx9UXP3Rx6VrthiukmhnSUQrJhIX+uIHhmIKz3juIWlBS5X+nz8QXMs0N6WSSFvKyBHMArT/zZfDUJk4MOnh6p43t0pBeXEG0JTHww2YzAr9YAaaL+tWPK7h4o1r7Bq2eJgJ/LJgtc1sCzw1E8L1+E53rzZYZrJWDRHBguO888Wp1Av/oriRO74zja9LXIaexvppyYLCkC8HxoaFfIGpTHNKhDXM9YLLoY6GiP/u6xJipkI8ZiK8xxL4s2CKYmG35S1CCq33WXGS7Zr7A5H6GvE4wJUTw/uo+d50lImEfnN9l2NNWx8CnDXM9rYPAL1SXPy0aSNoGhpIG0jZjkqhdMPBpw1wJ+olahR/U90HAm8g5Bo50Btfn1zYhojbAwKfWBed/qlVMFat4a8bHmCttwXB9wkSnLI85Evjcw4jaBv8cqXWS936piltzVbwxBVwrSn1vSn2fNpFNmjigoKTI55gOUZtg4FPLKp7G6GRZj0xV8JGvcVfagpOhRzIWHpHAZ9ITtRcGPrWkWPJw+15Z/328ijfvyv+l2i/aBpJxC091mDiSNGqjO0TUPhj41JLxKVe/89E8fvNpFX+YA0rB+dq4jXQuimezJk4moLhzEbUX/k1SY4IrLgsVXLtT0j8bWdA/vebitxMePihqzMpupCMOTvY6eGmHjf1JFZy3JaI2w8AnlD0fMyUPtwoebi54uv5S1TenXf3mzQIufrCAn4+W8Xup7Ce0QjpqYaDTwZfyNl7qMzEQCb4Kq3HBxT7B+YA518fYwlrvYcVS8PUdV+vgy9KXb/giogfj1AphU2dqhUzcRC5qot/G2lMTVzxMlXyMFHRtCMeyFPq7Y3iqx8H5HgvDaQODcaUc2XTNSmLF1Ao35PAQl9fvjhrYGVFo+F4t+VSxN2vj5SEb+2Jq9Tw3daZWOD6UwpmhOF7MArtbmUaCaAtj4IfNnItPJkv6uyNl/GXax7w0Nb4HKKQiJnZ0muiTVO51ZMlFcTxn4ctZQ607j/2yjU6PvCwewdF8FBcOOziWNNC18hJQBj7R/+CQTthIUFtSTQ+YCnn5sbkdwEA+5eDccAo/eCKNX30upX64x1Ev5AwlxTkRtTlW+GHjeVJge3h3wtPXixr3pKmZCr8zZmJft43tETlgtHqpfdXDRMHT8h5wu6Ixt9TcNMtET8LEiS55tJVaNYuD56PoVvHupKdHCxoz0tSTkfeetvGIbJzhrQIUMgx8IqKQ4AdxIqKQYOATEYUEA5+IKCQY+EREIcHAJyIKCQY+EVFIMPCJiEKCgU9EFArAfwE2JuRnUGyVRgAAAABJRU5ErkJggg== '' ; public MainWindow ( ) { InitializeComponent ( ) ; ImageA.Source = Convert ( ABC_DATA ) ; ImageB.Source = Convert ( DEF_DATA ) ; } private void Button_Click ( object sender , RoutedEventArgs e ) { PrintDialog printDialog = new PrintDialog ( ) ; if ( printDialog.ShowDialog ( ) == true ) { printDialog.PrintVisual ( ImageCanvas , `` image print test '' ) ; } } public static BitmapSource Convert ( string s ) { byte [ ] bytes ; bytes = System.Convert.FromBase64String ( s ) ; BitmapSource source ; using ( System.IO.MemoryStream ms = new System.IO.MemoryStream ( bytes ) ) { source = PngBitmapDecoder.Create ( ms , BitmapCreateOptions.None , BitmapCacheOption.OnLoad ) .Frames [ 0 ] ; } return source ; } }
Printing a WPF Visual Containing Images
C_sharp : First , this is not a duplicate of IEnumerable < T > as return type for WCF methods , I think I understand that the WCF architecture only allows concrete types to be transferred that can be stuffed into a message.Second , our setup however is not a general service but connecting up a bundle of proprietary apps via C # + WCF + NetTcpBinding + Protobuf ( only ) so we may have more room for some tricks that something that needs to be more binding neutral.Third , it is neither my place nor this question 's to propose a different RPC or messaging framework . `` IEnumerable semantics '' , for the purpose of this question , are : The returned sequence can be arbitrarily large -- it is therefore not possible to convert the sequence to a List or similar.It is not known in advance how many items will be returnedCaller can just use foreach and be done with it.In a local assembly , a C # interface my look like this : You ca n't map that directly to a WCF service . Something that might achieve the same could look like : Of course , using IStuffService will be more error prone than a IStuffProvider and add in to the mix than many usage scenarios would involve using both service and client on the same machine , so for `` user code '' it would n't be super important to be aware that `` the network '' is involved , the user code is just interested in a simple interface.One option would be of course to have a client side interface wrapper implementation , that exposes IStuffProvider and internally forwards to and uses IStuffService . However , it seems it would really be desirable to not have to maintain two interfaces , one for user code , one solely for the WCF communication , especially as these applications are all tightly coupled anyway , so the additional abstraction just seems overhead.What are the options we have here with WCF ? Note that after reading up on it , the Streamed Binding seems a poor solution , as I would still need a wrapper on the client side and the service interface would get more complex for no real gain in my case : I do n't need maximum binary transfer efficiency , I would like good implementation + maintenance efficiency . <code> interface IStuffProvider { IEnumerable < Stuff > GetItems ( ) ; // may open large file or access database } [ ServiceContract ( SessionMode = SessionMode.Required ) ] interface IStuffService { [ OperationContract ] void Reset ( ) ; // may open large file or access database [ OperationContract ] List < Stuff > GetNext ( ) ; // return next batch of items ( empty list if no more available ) }
Getting IEnumerable < T > semantics with a NetTcpBinding WCF service ?
C_sharp : So , I have a datagrid that has different colour cells depending on the cell 's value.I also have a tooltip that displays some further information . This all works fine.I , however , would like to alter the tooltip to show further information and also to be the same colour as the cell . So , I thought it would be wise to create a custom style for my tool tips . So , I have the below code.I have an object shown below that is bound to my datagrid . I want to bind the three properties to the three textboxes in my tooltip.In my DataGrid I do the following to bind my data to my datagridThen in the DataGridTextColumn I bind to a property like belowThis makes sense to me . I am however at a loss to see how I use binding when creating my custom tooltip . I read that I can use templatebinding . I still do n't understand how my tooltip will bind to my object of type MyTask in my xaml above ? Update - hopefully make my question clearerI want to know how to create the bindings in my control template ( for the 3 textboxes ) and then in the main part of my code how I bind to these text boxes . I then would like to know how to create a binding for the background colour of my control template , I believe this is something to do with relativesource ? When I 'm reading other examples ( changing the Template Property ) I see lines like below . I do n't really understand why you have to do it ? Is it a case of if you did n't right the line below you would n't be able to create a binding on the Padding property ? <code> < Style TargetType= '' ToolTip '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' ToolTip '' > < Border CornerRadius= '' 15,15,15,15 '' BorderThickness= '' 3,3,3,3 '' Background= '' # AA000000 '' BorderBrush= '' # 99FFFFFF '' RenderTransformOrigin= '' 0.5,0.5 '' > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' 2* '' / > < RowDefinition/ > < RowDefinition/ > < /Grid.RowDefinitions > < TextBlock Grid.Row= '' 0 '' / > < TextBlock Grid.Row= '' 1 '' / > < TextBlock Grid.Row= '' 2 '' / > < /Grid > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > class MyTask { public string Name ; public int Code ; public string Description ; } ItemsSource= '' { Binding TaskList } '' DataGridTextColumn Header= '' Code '' Binding= '' { Binding Code } '' < Border Padding= '' { Binding Padding } '' ... >
Control template : how to create bindings
C_sharp : I being following the Unity Interception link , to implement Unity in my project.By , following a link I have made a class as shown below : Till now I have done nothing special , just followed the example as explained in the upper link . But , when I have to implement the Unity Interception class , I came up with lots of confusion.Suppose , I have to implement on one of the methods in my class like : This is the main thing where I have being stuck , I dnt know how I have to use the Intercept class over the GetModelByID ( ) method and how to get the unity . Please help me , and please also explain the concept of Unity Interception . <code> [ AttributeUsage ( AttributeTargets.Method ) ] public class MyInterceptionAttribute : Attribute { } public class MyLoggingCallHandler : ICallHandler { IMethodReturn ICallHandler.Invoke ( IMethodInvocation input , GetNextHandlerDelegate getNext ) { IMethodReturn result = getNext ( ) ( input , getNext ) ; return result ; } int ICallHandler.Order { get ; set ; } } public class AssemblyQualifiedTypeNameConverter : ConfigurationConverterBase { public override object ConvertTo ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , object value , Type destinationType ) { if ( value ! = null ) { Type typeValue = value as Type ; if ( typeValue == null ) { throw new ArgumentException ( `` Can not convert type '' , typeof ( Type ) .Name ) ; } if ( typeValue ! = null ) return ( typeValue ) .AssemblyQualifiedName ; } return null ; } public override object ConvertFrom ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , object value ) { string stringValue = ( string ) value ; if ( ! string.IsNullOrEmpty ( stringValue ) ) { Type result = Type.GetType ( stringValue , false ) ; if ( result == null ) { throw new ArgumentException ( `` Invalid type '' , `` value '' ) ; } return result ; } return null ; } } [ MyInterception ] public Model GetModelByID ( Int32 ModelID ) { return _business.GetModelByID ( ModelID ) ; }
Unity Interception Concept Clarity
C_sharp : If you are parsing , lets just say HTML , once you read the element name , will it be beneficial to intern it ? The logic here is that this parser will parse the same strings ( element names ) over and over again ? And several documents will be parsed.Theory : This question was motivated by the question string-interning-memory . <code> // elemName is checked for null.MarkupNode node = new MarkupNode ( ) { Name = String.IsInterned ( elemName ) ? elemName : String.Intern ( elemName ) , ... } ;
Will Interning strings help performance in a parser ?
C_sharp : If anyone cares , I 'm using WPF ... .Beginning of story : I got a series of gray-scale images ( slices of a model ) . The user inputs a `` range '' of gray-scale values to build a 3D model upon . Thus I created a 3D bool array to make it easier to build the 3D model . This array represents a box of pixels , indicating whether each pixel should be built/generated/filled or not.The tie : Using a bool [ , , ] , I want to retrieve a List < Point3D [ ] > where each Point3D [ ] has a length of 3 and represents a triangle in 3D space.Additional info : The generated model is going to be 3D printed . In the bool [ , , ] , true indicates the presence of matter , while false indicates the absence of matter . I need to avoid cubic models , where each pixel is replaced with a cube ( That would be useless according to my purpose ) . The model should be as smooth as possible and as accurate as possible.What I tried to do:1- I implemented the marching cubes algorithm , but it simply does n't seem to be created to accept a `` range '' of values.2- I kept struggling for a couple of days trying to make my own algorithm , but I partially failed . ( It 's real complicated . If you want to know more about it , please inform ) Some expected solutions that I have no idea how to implement:1- Modify the Marching cubes algorithm in order to make it work using a bool [ , , ] 2- Modify the Marching cubes algorithm in order to make it work using a work using a `` range '' of isolevel values3- Showing how to implement another algorithm that is suitable for my purpose ( Maybe the Ray-Casting algorithm ) in WPF.4- Requesting the source of the algorithm I tried to implement then showing me how to solve it . ( It was made to polygonise a bool [ , , ] in the first place ) 5- Some other magical solution.Thanks in advance.EDIT : By saying Using a bool [ , , ] , I want to retrieve a List < Point3D [ ] > where each Point3D [ ] has a length of 3 and represents a triangle in 3D space.I mean that I want to retrieve a group of Triangles . Each triangle should be represented as 3 Point3Ds . If you do n't know what a Point3Dis , it is a struct containing 3 doubles ( X , Y and Z ) that 's used to represent a position in 3D space.The problem with the marching cubes algorithm is that it 's kinda vague . I mean , what do you understand by doing that ? ? Thus , I simply have no idea where to start modifying it.Another EDIT : After some experimenting with the marching cubes algorithm , I noticed that polygonising a bool [ , , ] is not going to result in the smooth 3D model I 'm looking forward to , so my first expected solution and my fourth expected solution are both out of the play . After a lot of research , I knew about the Ray-Casting method of volume rendering . It seems really cool , but I 'm not really sure if it fits to my needs . I ca n't really understand how it is implemented although I know how it works.One more EDIT : TriTable.LookupTable and EdgeTable.LookupTable are the tables present hereHere 's the MarchingCubes class : Here 's the GridCell class : Ok , that 's what I 'm doing : I made that right from Stack-Overflow , so please point out any typos . That is working , This results in a shell of a model . I want to do is replace the isolevel variable in the Polygonise function with 2 integers : isolevelMin and isolevelMax . Not only 1 int , but a range.EDIT : Guys , please help . 50 rep is almost 1/2 my reputation . I hope I can change my expectations . Now I just want any idea how I can implement what I want , any snippet on how to do it or if anyone gives out some keywords that I can google which I used to solve my problem he 'll get the rep . I just need some light - it 's all dark in here.EDITs are awesome : After even more , more and much more research , I found out that the volumetric ray-marching algorithm does not actually generate surfaces . Since I need to print the generated 3D model , I only have one way out now . I got ta make the marching cubes algorithm generate a hollow model from the maximum and minimum isolevel values . <code> cubeindex = 0 ; if ( grid.val [ 0 ] < isolevel ) cubeindex |= 1 ; if ( grid.val [ 1 ] < isolevel ) cubeindex |= 2 ; if ( grid.val [ 2 ] < isolevel ) cubeindex |= 4 ; if ( grid.val [ 3 ] < isolevel ) cubeindex |= 8 ; if ( grid.val [ 4 ] < isolevel ) cubeindex |= 16 ; if ( grid.val [ 5 ] < isolevel ) cubeindex |= 32 ; if ( grid.val [ 6 ] < isolevel ) cubeindex |= 64 ; if ( grid.val [ 7 ] < isolevel ) cubeindex |= 128 ; public class MarchingCubes { public static Point3D VertexInterp ( double isolevel , Point3D p1 , Point3D p2 , double valp1 , double valp2 ) { double mu ; Point3D p = new Point3D ( ) ; if ( Math.Abs ( isolevel - valp1 ) < 0.00001 ) return ( p1 ) ; if ( Math.Abs ( isolevel - valp2 ) < 0.00001 ) return ( p2 ) ; if ( Math.Abs ( valp1 - valp2 ) < 0.00001 ) return ( p1 ) ; mu = ( isolevel - valp1 ) / ( valp2 - valp1 ) ; p.X = p1.X + mu * ( p2.X - p1.X ) ; p.Y = p1.Y + mu * ( p2.Y - p1.Y ) ; p.Z = p1.Z + mu * ( p2.Z - p1.Z ) ; return ( p ) ; } public static void Polygonise ( ref List < Point3D [ ] > Triangles , int isolevel , GridCell gridcell ) { int cubeindex = 0 ; if ( grid.val [ 0 ] < isolevel ) cubeindex |= 1 ; if ( grid.val [ 1 ] < isolevel ) cubeindex |= 2 ; if ( grid.val [ 2 ] < isolevel ) cubeindex |= 4 ; if ( grid.val [ 3 ] < isolevel ) cubeindex |= 8 ; if ( grid.val [ 4 ] < isolevel ) cubeindex |= 16 ; if ( grid.val [ 5 ] < isolevel ) cubeindex |= 32 ; if ( grid.val [ 6 ] < isolevel ) cubeindex |= 64 ; if ( grid.val [ 7 ] < isolevel ) cubeindex |= 128 ; // Cube is entirely in/out of the surface if ( EdgeTable.LookupTable [ cubeindex ] == 0 ) return ; Point3D [ ] vertlist = new Point3D [ 12 ] ; // Find the vertices where the surface intersects the cube if ( ( EdgeTable.LookupTable [ cubeindex ] & 1 ) > 0 ) vertlist [ 0 ] = VertexInterp ( isolevel , grid.p [ 0 ] , grid.p [ 1 ] , grid.val [ 0 ] , grid.val [ 1 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 2 ) > 0 ) vertlist [ 1 ] = VertexInterp ( isolevel , grid.p [ 1 ] , grid.p [ 2 ] , grid.val [ 1 ] , grid.val [ 2 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 4 ) > 0 ) vertlist [ 2 ] = VertexInterp ( isolevel , grid.p [ 2 ] , grid.p [ 3 ] , grid.val [ 2 ] , grid.val [ 3 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 8 ) > 0 ) vertlist [ 3 ] = VertexInterp ( isolevel , grid.p [ 3 ] , grid.p [ 0 ] , grid.val [ 3 ] , grid.val [ 0 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 16 ) > 0 ) vertlist [ 4 ] = VertexInterp ( isolevel , grid.p [ 4 ] , grid.p [ 5 ] , grid.val [ 4 ] , grid.val [ 5 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 32 ) > 0 ) vertlist [ 5 ] = VertexInterp ( isolevel , grid.p [ 5 ] , grid.p [ 6 ] , grid.val [ 5 ] , grid.val [ 6 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 64 ) > 0 ) vertlist [ 6 ] = VertexInterp ( isolevel , grid.p [ 6 ] , grid.p [ 7 ] , grid.val [ 6 ] , grid.val [ 7 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 128 ) > 0 ) vertlist [ 7 ] = VertexInterp ( isolevel , grid.p [ 7 ] , grid.p [ 4 ] , grid.val [ 7 ] , grid.val [ 4 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 256 ) > 0 ) vertlist [ 8 ] = VertexInterp ( isolevel , grid.p [ 0 ] , grid.p [ 4 ] , grid.val [ 0 ] , grid.val [ 4 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 512 ) > 0 ) vertlist [ 9 ] = VertexInterp ( isolevel , grid.p [ 1 ] , grid.p [ 5 ] , grid.val [ 1 ] , grid.val [ 5 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 1024 ) > 0 ) vertlist [ 10 ] = VertexInterp ( isolevel , grid.p [ 2 ] , grid.p [ 6 ] , grid.val [ 2 ] , grid.val [ 6 ] ) ; if ( ( EdgeTable.LookupTable [ cubeindex ] & 2048 ) > 0 ) vertlist [ 11 ] = VertexInterp ( isolevel , grid.p [ 3 ] , grid.p [ 7 ] , grid.val [ 3 ] , grid.val [ 7 ] ) ; // Create the triangle for ( int i = 0 ; TriTable.LookupTable [ cubeindex , i ] ! = -1 ; i += 3 ) { Point3D [ ] aTriangle = new Point3D [ 3 ] ; aTriangle [ 0 ] = vertlist [ TriTable.LookupTable [ cubeindex , i ] ] ; aTriangle [ 1 ] = vertlist [ TriTable.LookupTable [ cubeindex , i + 1 ] ] ; aTriangle [ 2 ] = vertlist [ TriTable.LookupTable [ cubeindex , i + 2 ] ] ; theTriangleList.Add ( aTriangle ) ; } } } public class GridCell { public Point3D [ ] p = new Point3D [ 8 ] ; public Int32 [ ] val = new Int32 [ 8 ] ; } List < int [ ] [ ] > Slices = new List < int [ ] [ ] > ( ) ; //Each slice is a 2D jagged array . This is a list of slices , each slice is a value between about -1000 to 2300public static void Main ( ) { List < Point3D [ ] > Triangles = new List < Point3D [ ] > ( ) ; int RowCount ; //That is my row count int ColumnCount ; //That is my column count //Here I fill the List with my values //Now I 'll polygonise each GridCell for ( int i = 0 ; i < Slices.Count - 1 ; i++ ) { int [ ] [ ] Slice1 = Slices [ i ] ; int [ ] [ ] Slice2 = Slices [ i + 1 ] ; for ( int j = 0 ; j < RowCount - 1 ; j++ ) { for ( int k = 0 ; k < ColumnCount - 1 ; k++ ) { GridCell currentCell = GetCurrentCell ( Slice1 , Slice2 , j , k ) ; Polygonise ( ref Triangles , int isoLevel , GridCell currentCell ) ; } } } //I got the `` Triangles '' : D } //What this simply does is that it returns in 3D space from RI and CIpublic static GridCell GetCurrentCell ( int [ ] [ ] CTSliceFront , int [ ] [ ] CTSliceBack , int RI , int CI ) //RI is RowIndex and CI is ColumnIndex { //Those are preset indicating X , Y or Z coordinates of points/edges double X_Left_Front ; double X_Right_Front ; double X_Left_Back ; double X_Right_Back ; double Y_Top_Front ; double Y_Botton_Front ; double Y_Top_Back ; double Y_Botton_Back ; double Z_Front ; double Z_Back ; GridCell currentCell = new GridCell ( ) ; currentCell.p [ 0 ] = new Point3D ( X_Left_Back , Y_Botton_Back , Z_Back ) ; currentCell.p [ 1 ] = new Point3D ( X_Right_Back , Y_Botton_Back , Z_Back ) ; currentCell.p [ 2 ] = new Point3D ( X_Right_Front , Y_Botton_Front , Z_Front ) ; currentCell.p [ 3 ] = new Point3D ( X_Left_Front , Y_Botton_Front , Z_Front ) ; currentCell.p [ 4 ] = new Point3D ( X_Left_Back , Y_Top_Back , Z_Back ) ; currentCell.p [ 5 ] = new Point3D ( X_Right_Back , Y_Top_Back , Z_Back ) ; currentCell.p [ 6 ] = new Point3D ( X_Right_Front , Y_Top_Front , Z_Front ) ; currentCell.p [ 7 ] = new Point3D ( X_Left_Front , Y_Top_Front , Z_Front ) ; currentCell.val [ ] = CTSliceBack [ theRowIndex + 1 ] [ theColumnIndex ] ; currentCell.val [ ] = CTSliceBack [ theRowIndex + 1 ] [ theColumnIndex + 1 ] ; currentCell.val [ ] = CTSliceFront [ theRowIndex + 1 ] [ theColumnIndex + 1 ] ; currentCell.val [ ] = CTSliceFront [ theRowIndex ] [ theColumnIndex ] ; currentCell.val [ ] = CTSliceBack [ theRowIndex ] [ theColumnIndex + 1 ] ; currentCell.val [ ] = CTSliceFront [ theRowIndex ] [ theColumnIndex + 1 ] ; currentCell.val [ ] = CTSliceFront [ theRowIndex ] [ theColumnIndex ] ; return currentCell ; }
How could I polygonise a bool [ , , ]
C_sharp : How do you concatenate huge lists without doubling memory ? Consider the following snippet : The output is : I would like to keep memory usage to 2014 MB after concatenation , without modifying a and b . <code> Console.WriteLine ( $ '' Initial memory size : { Process.GetCurrentProcess ( ) .WorkingSet64 /1024 /1024 } MB '' ) ; int [ ] a = Enumerable.Range ( 0 , 1000 * 1024 * 1024 / 4 ) .ToArray ( ) ; int [ ] b = Enumerable.Range ( 0 , 1000 * 1024 * 1024 / 4 ) .ToArray ( ) ; Console.WriteLine ( $ '' Memory size after lists initialization : { Process.GetCurrentProcess ( ) .WorkingSet64 / 1024 / 1024 } MB '' ) ; List < int > concat = new List < int > ( ) ; concat.AddRange ( a.Skip ( 500 * 1024 * 1024 / 4 ) ) ; concat.AddRange ( b.Skip ( 500 * 1024 * 1024 / 4 ) ) ; Console.WriteLine ( $ '' Memory size after lists concatenation : { Process.GetCurrentProcess ( ) .WorkingSet64 / 1024 / 1024 } MB '' ) ; Initial memory size : 12 MBMemory size after lists initialization : 2014 MBMemory size after lists concatenation : 4039 MB
How to concatenate lists without using extra memory ?
C_sharp : I am having a huge problem in all browsers.I have a site where clients can download a csv file that contains detail they need.The problem I am having is that the csv file either downloads with no extension or as a htm file.In the code I am specifying the file name with .csv , the file on the server is also a .csv.The code is as followsI have tried context.Response.ContentType = `` text/html '' ; and context.Response.ContentType = `` application/octet-stream '' ; .It is running on IIS6.Does anybody know what could be causing this ? <code> context.Response.Buffer = true ; context.Response.Clear ( ) ; context.Response.ClearHeaders ( ) ; context.Response.ContentType = `` text/csv '' ; context.Response.AppendHeader ( `` Content-Disposition '' , @ '' attachment , filename= '' + ( ( string ) Path.GetFileName ( downloadFilePath ) ) ) ; context.Response.WriteFile ( downloadFilePath ) ; context.Response.Flush ( ) ; context.Response.Close ( ) ;
CSV downloads as HTM
C_sharp : Why is it not possible to have implicitly-typed variables at a class level within C # for when these variables are immediately assigned ? ie : Is it just something that has n't been implemented or is there a conceptual/technical reason for why it has n't been done ? <code> public class TheClass { private var aList = new List < string > ( ) ; }
var in C # - Why ca n't it be used as a member variable ?
C_sharp : I 'm trying to save any logs I received from the application into a log table in my db and so far , nothing gets saved . I 'm using Log4net and AdoNetAppender for saving the logs into my table inside SQL Server . This code sits inside a Web API project on the server side of my app . I set up the logs as follows : 1 ) Setup the XML in my Web.Config : 2 ) Here 's the code inside my Global.asax.cs : 3 ) Added the Stored Procedure to the db : Question : Where should this stored procedure be saved in SSMS ? When I save the stored procedure , it automatically defaults it to Documents\SSMS but I want to save it under DB/Programmability/StoredProcedures folder but I do n't see it there . However , I did execute the stored procedure successfully without any errors.4 ) added logs to other files inside my app project outside of the global.asax.cs file . Does Log4Net know to log those as well ? So yeah I 'm not sure what I did wrong and nothing gets logged to my table in SQL Server . Did I miss a step in the process of setting up Log4Net ? EDIT : Internal debugger says : What key ? <code> < log4net > < appender name= '' AdoNetAppender '' type= '' log4net.Appender.AdoNetAppender '' > < bufferSize value= '' 1 '' / > < connectionType value= '' System.Data.SqlClient.SqlConnection , System.Data , Version=1.0.3300.0 , Culture=neutral , PublicKeyToken=token '' / > < connectionString value= '' data source=db ; Initial Catalog=dbname ; Trusted_Connection=True ; '' providerName= '' System.Data.SqlClient '' / > < commandText value= '' dbo.procLogs_Insert '' / > < commandType value= '' StoredProcedure '' / > < parameter > < parameterName value= '' @ log_timestamp '' / > < dbType value= '' DateTime '' / > < layout type= '' log4net.Layout.RawTimeStampLayout '' / > < /parameter > < parameter > < parameterName value= '' @ log_recordNum '' / > < dbType value= '' Int32 '' / > < size value= '' 32 '' / > < layout type= '' log4net.Layout.RawPropertyLayout '' / > < /parameter > < parameter > < parameterName value= '' @ log_computerName '' / > < dbType value= '' String '' / > < size value= '' 128 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % X { machine } '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_processTimeStamp '' / > < dbType value= '' DateTime '' / > < layout type= '' log4net.Layout.RawTimeStampLayout '' / > < /parameter > < parameter > < parameterName value= '' @ log_group '' / > < dbType value= '' StringFixedLength '' / > < size value= '' 1 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % message '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_type '' / > < dbType value= '' StringFixedLength '' / > < size value= '' 1 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % message '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_eventId '' / > < dbType value= '' Int32 '' / > < size value= '' 32 '' / > < layout type= '' log4net.Layout.RawPropertyLayout '' / > < /parameter > < parameter > < parameterName value= '' @ log_userId '' / > < dbType value= '' Int32 '' / > < size value= '' 32 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % identity '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_line '' / > < dbType value= '' Int32 '' / > < size value= '' 32 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % line '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_description '' / > < dbType value= '' AnsiString '' / > < size value= '' 4000 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % message % newline % exception '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_source '' / > < dbType value= '' AnsiString '' / > < size value= '' 4000 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % file '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_data '' / > < dbType value= '' AnsiString '' / > < size value= '' 4000 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % logger '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ log_addTimeStamp '' / > < dbType value= '' DateTime '' / > < layout type= '' log4net.Layout.RawTimeStampLayout '' / > < /parameter > < parameter > < parameterName value= '' @ log_deviceId '' / > < dbType value= '' StringFixedLength '' / > < size value= '' 10 '' / > < layout type= '' log4net.Layout.PatternLayout '' / > < /parameter > < /appender > < appender name= '' asyncForwarder '' type= '' Log4Net.Async.AsyncForwardingAppender , Log4Net.Async '' > < appender-ref ref= '' AdoNetAppender '' / > < /appender > < root > < level value= '' ALL '' / > < appender-ref ref= '' asyncForwarder '' / > < /root > < /log4net > public class WebApiApplication : System.Web.HttpApplication { private static readonly ILog _log = LogManager.GetLogger ( MethodBase.GetCurrentMethod ( ) .DeclaringType ) ; protected void Application_Start ( ) { XmlConfigurator.Configure ( ) ; _log.Info ( `` Service Started '' ) ; GlobalConfiguration.Configure ( WebApiConfig.Register ) ; } public static void Register ( HttpConfiguration config ) { // Web API routes config.MapHttpAttributeRoutes ( ) ; } } SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE dbo.procLogs_Insert @ log_timestamp datetime , @ log_recordNum int , @ log_computerName varchar ( 128 ) , @ log_processTimeStamp datetime , @ log_group char ( 1 ) , @ log_type char ( 1 ) , @ log_eventId int , @ log_userId varchar ( 128 ) , @ log_line int , @ log_description text , @ log_source text , @ log_data text , @ log_addTimeStamp datetime , @ log_deviceId char ( 10 ) ASBEGIN SET NOCOUNT ON ; insert into dbo.BS_ApplicationLogs ( LogTimestamp , RecordNum , ComputerName , ProcessTimestamp , LogGroup , [ Type ] , EventId , UserId , Line , [ Description ] , [ Source ] , [ Data ] , AddTimestamp , DeviceID ) values ( @ log_timestamp , @ log_recordNum , @ log_computerName , @ log_processTimeStamp , @ log_group , @ log_type , @ log_eventId , @ log_userId , @ log_line , @ log_description , @ log_source , @ log_data , @ log_addTimeStamp , @ log_deviceId ) ENDGO log4net : Created Appender [ AdoNetAppender ] log4net : Created Appender [ asyncForwarder ] log4net : Adding appender named [ asyncForwarder ] to logger [ root ] .log4net : Hierarchy Threshold [ ] log4net : ERROR [ AdoNetAppender ] ErrorCode : GenericFailure . Exception while writing to databaseSystem.ArgumentNullException : Key can not be null.Parameter name : key at System.Collections.Hashtable.get_Item ( Object key ) at log4net.Util.PropertiesDictionary.get_Item ( String key ) at log4net.Core.LoggingEvent.LookupProperty ( String key ) at log4net.Layout.RawPropertyLayout.Format ( LoggingEvent loggingEvent ) at log4net.Appender.AdoNetAppenderParameter.FormatValue ( IDbCommand command , LoggingEvent loggingEvent ) at log4net.Appender.AdoNetAppender.SendBuffer ( IDbTransaction dbTran , LoggingEvent [ ] events ) at log4net.Appender.AdoNetAppender.SendBuffer ( LoggingEvent [ ] events )
Logs do not get saved into Logs table
C_sharp : I want to increase values on timer tick event but it is not increasing do n't know what I am forgetting it is showing only 1 . <code> < asp : Timer ID= '' Timer1 '' runat= '' server '' OnTick= '' Timer1_Tick '' Interval= '' 1000 '' > < /asp : Timer > private int i = 0 ; protected void Timer1_Tick ( object sender , EventArgs e ) { i++ ; Label3.Text = i.ToString ( ) ; }
Timer Tick not increasing values on time interval
C_sharp : I have always included the at sign in the parameter name when using AddWithValue , but I just noticed some code written by someone else that does n't use it . Is one way more correct than the other ? or <code> cmd.Parameters.AddWithValue ( `` ixCustomer '' , ixCustomer ) ; cmd.Parameters.AddWithValue ( `` @ ixCustomer '' , ixCustomer ) ;
should I include the @ when using SqlCommand.Parameters.AddWithValue ?
C_sharp : I 'm trying to record audio and immediately send it to IBM Watson Speech-To-Text for transcription . I 've tested Watson with a WAV file loaded from disk , and that worked . On the other end , I 've also tested with recording from microphone and storing it to disk , works good too . But when I try to record the audio with NAudio WaveIn , the result from Watson is empty , as if there 's no audio . Anyone who can shine a light on this , or someone has some ideas ? Edit : I 've also tried to send the WAV `` header '' prior to StartRecording , like this <code> private async void StartHere ( ) { var ws = new ClientWebSocket ( ) ; ws.Options.Credentials = new NetworkCredential ( `` ***** '' , `` ***** '' ) ; await ws.ConnectAsync ( new Uri ( `` wss : //stream.watsonplatform.net/speech-to-text/api/v1/recognize ? model=en-US_NarrowbandModel '' ) , CancellationToken.None ) ; Task.WaitAll ( ws.SendAsync ( openingMessage , WebSocketMessageType.Text , true , CancellationToken.None ) , HandleResults ( ws ) ) ; Record ( ) ; } public void Record ( ) { var waveIn = new WaveInEvent { BufferMilliseconds = 50 , DeviceNumber = 0 , WaveFormat = format } ; waveIn.DataAvailable += new EventHandler ( WaveIn_DataAvailable ) ; waveIn.RecordingStopped += new EventHandler ( WaveIn_RecordingStopped ) ; waveIn.StartRecording ( ) ; } public void Stop ( ) { await ws.SendAsync ( closingMessage , WebSocketMessageType.Text , true , CancellationToken.None ) ; } public void Close ( ) { ws.CloseAsync ( WebSocketCloseStatus.NormalClosure , `` Close '' , CancellationToken.None ) .Wait ( ) ; } private void WaveIn_DataAvailable ( object sender , WaveInEventArgs e ) { await ws.SendAsync ( new ArraySegment ( e.Buffer ) , WebSocketMessageType.Binary , true , CancellationToken.None ) ; } private async Task HandleResults ( ClientWebSocket ws ) { var buffer = new byte [ 1024 ] ; while ( true ) { var segment = new ArraySegment ( buffer ) ; var result = await ws.ReceiveAsync ( segment , CancellationToken.None ) ; if ( result.MessageType == WebSocketMessageType.Close ) { return ; } int count = result.Count ; while ( ! result.EndOfMessage ) { if ( count > = buffer.Length ) { await ws.CloseAsync ( WebSocketCloseStatus.InvalidPayloadData , `` That 's too long '' , CancellationToken.None ) ; return ; } segment = new ArraySegment ( buffer , count , buffer.Length - count ) ; result = await ws.ReceiveAsync ( segment , CancellationToken.None ) ; count += result.Count ; } var message = Encoding.UTF8.GetString ( buffer , 0 , count ) ; // you 'll probably want to parse the JSON into a useful object here , // see ServiceState and IsDelimeter for a light-weight example of that . Console.WriteLine ( message ) ; if ( IsDelimeter ( message ) ) { return ; } } } private bool IsDelimeter ( String json ) { MemoryStream stream = new MemoryStream ( Encoding.UTF8.GetBytes ( json ) ) ; DataContractJsonSerializer ser = new DataContractJsonSerializer ( typeof ( ServiceState ) ) ; ServiceState obj = ( ServiceState ) ser.ReadObject ( stream ) ; return obj.state == `` listening '' ; } [ DataContract ] internal class ServiceState { [ DataMember ] public string state = `` '' ; } waveIn.DataAvailable += new EventHandler ( WaveIn_DataAvailable ) ; waveIn.RecordingStopped += new EventHandler ( WaveIn_RecordingStopped ) ; /* Send WAV `` header '' first */ using ( var stream = new MemoryStream ( ) ) { using ( var writer = new BinaryWriter ( stream , Encoding.UTF8 ) ) { writer.Write ( Encoding.UTF8.GetBytes ( `` RIFF '' ) ) ; writer.Write ( 0 ) ; // placeholder writer.Write ( Encoding.UTF8.GetBytes ( `` WAVE '' ) ) ; writer.Write ( Encoding.UTF8.GetBytes ( `` fmt `` ) ) ; format.Serialize ( writer ) ; if ( format.Encoding ! = WaveFormatEncoding.Pcm & & format.BitsPerSample ! = 0 ) { writer.Write ( Encoding.UTF8.GetBytes ( `` fact '' ) ) ; writer.Write ( 4 ) ; writer.Write ( 0 ) ; } writer.Write ( Encoding.UTF8.GetBytes ( `` data '' ) ) ; writer.Write ( 0 ) ; writer.Flush ( ) ; } byte [ ] header = stream.ToArray ( ) ; await ws.SendAsync ( new ArraySegment ( header ) , WebSocketMessageType.Binary , true , CancellationToken.None ) ; } /* End WAV header */ waveIn.StartRecording ( ) ;
Recording WAV to IBM Watson Speech-To-Text
C_sharp : I 'm using Entity Framework 6.1.1 and I have a Users table and a User_Documents table ( 1 : many ) . I already had a navigation property from User_Documents to User were things were working fine.I added a navigation property from Users to User_Documentsand now I 'm getting an error when I try to run the application : System.Data.Entity.ModelConfiguration.ModelValidationException : One or more validation errors were detected during model generation : User_Documents : Name : Each member name in an EntityContainer must be unique . A member with name 'User_Documents ' is already defined.Of course there is a table called User_Documents but no other property with that name . I 'm not sure what 's it getting confused by . Maybe it 's taking the table name `` User '' and the property name `` Documents '' and trying to create something called `` User_Documents '' out of it ? If I rename it to from Documents to Some_Documents like thisthen I get a different error stating System.InvalidOperationException : The model backing the 'PipeTrackerContext ' context has changed since the database was created . Consider using Code First Migrations to update the databaseSo I run Add-Migration and I get this : Why is it trying to add a new column called User_User_ID ? Why ca n't I just add the Document navigation property like I want ? <code> public partial class User_Document { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public long User_Document_ID { get ; set ; } public long User_ID { get ; set ; } [ ForeignKey ( `` User_ID '' ) ] public virtual User User { get ; set ; } } public partial class User { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public long User_ID { get ; set ; } [ StringLength ( 50 ) ] public string Username { get ; set ; } public virtual List < User_Document > Documents { get ; set ; } } public virtual List < User_Document > Some_Documents { get ; set ; } public override void Up ( ) { AddColumn ( `` dbo.User_Documents '' , `` User_User_ID '' , c = > c.Long ( ) ) ; CreateIndex ( `` dbo.User_Documents '' , `` User_User_ID '' ) ; AddForeignKey ( `` dbo.User_Documents '' , `` User_User_ID '' , `` dbo.Users '' , `` User_ID '' ) ; }
Entity Framework getting confused about navigation property
C_sharp : In other words , is functionally identical to Stated another way , isfunctionally identical toAccording to Task.Wait and Inlining , if the Task being Wait ’ d on has already started execution , Wait has to block . However , if it hasn ’ t started executing , Wait may be able to pull the target task out of the scheduler to which it was queued and execute it inline on the current thread.Are those two cases merely a matter of deciding which thread the Task is going to run on , and if you 're waiting on the result anyway , does it matter ? Is there any benefit to using the asynchronous form over the synchronous form , if nothing executes between the asynchronous call and the Wait ( ) ? <code> var task = SomeLongRunningOperationAsync ( ) ; task.Wait ( ) ; SomeLongRunningOperation ( ) ; var task = SomeOtherLongRunningOperationAsync ( ) ; var result = task.Result ; var result = SomeOtherLongRunningOperation ( ) ;
Is calling Task.Wait ( ) immediately after an asynchronous operation equivalent to running the same operation synchronously ?
C_sharp : I 've been playing with a c # app that hosts IronPython , IronRuby , and ( hopefully ) PowerShell . Since IronPython and IronRuby were completely built on the DLR , the API for using them is pretty much identical . andboth create instances of a Microsoft.Scripting.Hosting.ScriptEngine . Is there any hope of coercing PowerShell 3.0 to create a ScriptEngine ? I have not been able to find much on the subject , other than PowerShell 3.0 seem be built on the DLR more than the previous version was ( see http : //huddledmasses.org/powershell-3-finally-on-the-dlr.It does n't appear that you can cast a PowerShell engine created with the following to a ScriptEngine.I suspect that if I really want to handle PowerShell through the same API I need to create my own ScriptEngine that wraps the PowerShell host . <code> IronPython.Hosting.Python.CreateEngine ( ) IronRuby.Ruby.CreateEngine ( ) System.Management.Automation.PowerShell.Create ( )
How can I host PowerShell 3.0 in a c # app using a similar API to other DLR languages
C_sharp : While reflecting with ILSpy i found this line of code in the Queue < T > .Enqueue ( T item ) -method : I 'm just wondering why somebody would do this ? I think it 's some kind of a integer overflow check , but why multiply first with 200L and then divide by 100L ? Might this have been a issue with earlier compilers ? <code> if ( this._size == this._array.Length ) { int num = ( int ) ( ( long ) this._array.Length * 200L / 100L ) ; if ( num < this._array.Length + 4 ) { num = this._array.Length + 4 ; } this.SetCapacity ( num ) ; }
Strange Queue < T > .Enqueue ( T item ) code
C_sharp : I want to start the new On-Screen-Keyboard ( OSK ) using code . You can find this one in the taskbar : ( if not there you find it by right clicking the taskbar ) .I have already tried the regular : But I want to start the other one ( not in window mode ) . Here you see which OSK I want and which one not : How can I start that version ? And how can I start it in a certain setting ( if possible ) ? <code> System.Diagnostics.Process.Start ( `` osk.exe '' ) ;
How to open the tablet-mode on-screen-keyboard in C # ?
C_sharp : For some time I have had a custom Visual Studio code snippet to assist in injecting a copyright header in my C # source files . It looks something like this : The important thing to note for this question is the two trailing endlines at the end of the CDATA block . In editions of Visual Studio prior to 2015 , I could place my cursor at the beginning of a file , right before the first using declaration , type header+TAB , and my header would appear with an extra empty line in between the last comment and the first using declaration.Visual Studio 2015 appears to not honor the trailing whitespace . When I type header+TAB , the first using declaration appears on the same line as the last comment.Am I looking at a bug , or is there a way to configure my code snippet so that Visual Studio 2015 will honor the trailing whitespace ? <code> < CodeSnippet Format= '' 1.0.0 '' xmlns= '' http : //schemas.microsoft.com/VisualStudio/2005/CodeSnippet '' > < Header > < Title > File Header < /Title > < Author > Me < /Author > < Shortcut > header < /Shortcut > < Description > Inserts a standard copyright header. < /Description > < SnippetTypes > < SnippetType > Expansion < /SnippetType > < /SnippetTypes > < /Header > < Snippet > < Declarations > < Literal > < ID > FileName < /ID > < ToolTip > The name of the C # code file. < /ToolTip > < Default > FileName < /Default > < /Literal > < /Declarations > < Code Language= '' CSharp '' > < ! [ CDATA [ // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -// < copyright file= '' $ FileName $ .cs '' company= '' Company Name '' > // Copyright © 2011-2016 by Company Name . All rights reserved.// < /copyright > // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ] ] > < /Code > < /Snippet > < /CodeSnippet >
Visual Studio 2015 Code Snippet with significant trailing whitespace
C_sharp : Can I reduce this razor code ? I was trying this but it does n't work : <code> < li > @ { if ( @ Model.PublicationDate.HasValue ) { @ Model.PublicationDate.Value.ToString ( `` D '' , new System.Globalization.CultureInfo ( `` fr-FR '' ) ) } else { @ : '' pas disponible '' } } < /li > @ { ( @ Model.PublicationDate.HasValue ) ? ( @ Model.PublicationDate.Value.ToString ( `` D '' ) ) : ( @ : '' pas disponible '' ) }
Can I reduce razor code to just few lines ?
C_sharp : So I 'm writing a `` dynamic '' Linq query . I 've created an `` options '' class that holds all of the dynamic options that can be a part of the query . Some of these option properties are List objects , which hold IDs of entities that I want to return that are part of many-to-many relationships in SQL Server . A quick code example and descriptions of the tables might help ( seriously pared down for brevity ) .Table Cars : Id int PK , Model varchar ( 50 ) , Year intTable Colors : Id int PK , Name varchar ( 50 ) Table CarsXColors : CarId int PK , ColorId int PK <code> public IEnumerable < Car > Search ( SearchOptions options ) { var query = from car in ctx.Cars select car ; // This works just fine if ( options.MaxMileage.HasValue ) query = query.Where ( x = > x.Mileage < = options.Mileage.Value ) ; // How do I implement this pseudo code . options.Colors is a List < int > if ( options.Colors.Count > 0 ) { query = query.Where ( -- select cars that are in the List < int > of colors -- ) ; } return query ; }
LINQ & Many to Many Relationships
C_sharp : We are using Machine.Specification as our test framework on my current project . This works well for most of what we are testing . However , we have a number of view models where we have 'formatted ' properties that take some raw data , apply some logic , and return a formatted version of that data . Since there is logic involved in the formatting ( null checks , special cases for zero , etc . ) I want test a number of possible data values including boundary conditions . To me , this does n't feel like the right use case for MSpec and that we should drop down into something like NUnit where I can write a data-driven test using something like the [ TestCase ] attribute . Is there a clean , simple way to write this kind of test in MSpec , or am I right in my feeling that we should be using a different tool for this kind of test ? View ModelMSpec TestsNUnit w/TestCaseIs there a better way to write the MSpec tests that I 'm missing because I 'm just not familiar enough with MSpec yet , or is MSpec really just the wrong tool for the job in this case ? NOTE : Another Dev on the team feels we should write all of our tests in MSpec because he does n't want to introduce multiple testing frameworks into the project . While I understand his point , I want to make sure we are using the right tool for the right job , so if MSpec is not the right tool , I 'm looking for points I can use to argue the case for introducing another framework . <code> public class DwellingInformation { public DateTime ? PurchaseDate { get ; set ; } public string PurchaseDateFormatted { if ( PurchaseDate == null ) return `` N/A '' ; return PurchaseDate.Value.ToShortDateString ( ) ; } public int ? ReplacementCost { get ; set ; } public string ReplacementCostFormatted { if ( ReplacementCost == null ) return `` N/A '' ; if ( ReplacementCost == 0 ) return `` Not Set '' ; return ReplacementCost.ToString ( `` C0 '' ) ; } // ... and so on ... } public class When_ReplacementCost_is_null { private static DwellingInformation information ; Establish context = ( ) = > { information = new DwellingInformation { ReplacementCost = null } ; } ; It ReplacementCostFormatted_should_be_Not_Available = ( ) = > information.ReplacementCostFormatted.ShouldEqual ( `` N/A '' ) ; } public class When_ReplacementCost_is_zero { private static DwellingInformation information ; Establish context = ( ) = > { information = new DwellingInformation { ReplacementCost = `` 0 '' } ; } ; It ReplacementCostFormatted_should_be_Not_Set = ( ) = > information.ReplacementCostFormatted.ShouldEqual ( `` Not Set '' ) ; } public class When_ReplacementCost_is_a_non_zero_value { private static DwellingInformation information ; Establish context = ( ) = > { information = new DwellingInformation { ReplacementCost = 200000 } ; } ; It ReplacementCostFormatted_should_be_formatted_as_currency = ( ) = > information.ReplacementCostFormatted.ShouldEqual ( `` $ 200,000 '' ) ; } [ TestCase ( null , `` N/A '' ) ] [ TestCase ( 0 , `` Not Set '' ) ] [ TestCase ( 200000 , `` $ 200,000 '' ) ] public void ReplacementCostFormatted_Correctly_Formats_Values ( int ? inputVal , string expectedVal ) { var information = new DwellingInformation { ReplacementCost = inputVal } ; information.ReplacementCostFormatted.ShouldEqual ( expectedVal ) ; }
Does MSpec support `` row tests '' or data-driven tests , like NUnit TestCase ?
C_sharp : Say I have the followingIs there any way to specify that my Func < T > parameters must obey some contracts ? <code> public T Example ( Func < T > f ) { Contract.Requires ( f ! = null ) ; Contract.Requires ( f ( ) ! = null ) ; // no surprise , this is an error ... }
Specify code contract on Func < T > parameters ?
C_sharp : In a C # controller , I have a function defined with an optional parameter which is set to default to null ( see code example below ) . The first time the page loads , the function is called and the filter is passed in as an initialized object , despite the default value being null . I would like it to be null the first time the page loads . Is there a way to do this ? This action is resolved by the following route definition : <code> public ActionResult MyControllerFunction ( CustomFilterModel filter = null ) { if ( filter == null ) doSomething ( ) ; // We never make it inside this `` if '' statement . // Do other things ... } routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // URL with parameters new { controller = `` Project '' , action = `` Index '' , id = UrlParameter.Optional } // Parameter defaults ) ;
Optional Parameters in C # - Defaulting a user-defined Class to null
C_sharp : Given a CancellationToken , I want to call a 'cancel ' method on an object that represents an asynchronous operation when the CancellationToken is cancelled . Is this possible ? Background : I 'm interfacing with an API that represents an async op the following way ( more or less ) : I can wrap this in a method Task DoAsyncOp ( ) easily enough , but I want to support cancellation , eg Task DoAsyncOp ( CancellationToken cancellationToken ) . In my case , when the CancellationToken is cancelled , call Cancel on the AsyncOp object . <code> class AsyncOp { void Start ( Action callback ) ; //returns 'immediately ' , while beginning an async op . Callback is called when the operation completes . void Cancel ( ) ; //aborts async operation and calls callback }
How to run code when a CancellationToken is cancelled ?
C_sharp : In C # it 's conventional to write in a fairly objective manner , like so : I could just write the above like this : However , how does the stackframe work when you have a bunch of function calls in a sequence like this ? The example is fairly straightforward but imagine if I 've got 50+ function calls chained ( this can possibly happen in the likes of JavaScript ( /w jQuery ) ) .My assumption was that , for each function call , a return address is made ( to the `` dot '' ? ) and the return value ( a new object with other methods ) is then immediately pumped into the next function call at that return address . How does this work w.r.t . getting to the overall return value ( in this example the return address will assign the final function value to rett ) ? If I kept chaining calls would I eventually overflow ? In that case , is it considered wiser to take the objective route ( at the cost of `` needless '' memory assignment ? ) . <code> MyObj obj = new MyObj ( ) ; MyReturn ret = obj.DoSomething ( ) ; AnotherReturn rett = ret.DoSomethingElse ( ) ; AnotherReturn rett = new MyObj ( ) .DoSomething ( ) .DoSomethingElse ( ) ;
C # : How do sequential function calls work ? ( efficiency-wise )
C_sharp : An application I 'm working on processes Work Items . Depending on the state of a work item there are a number of actions available . `` Complete '' `` Cancel '' `` Reassign '' etc ... To provide the functionality for the actions I currently have an interface that looks something like this ... Then based on other details of the work item I have concrete implementations of the interface . Just for example ... and The problem is , if I want to add a new action , say ... `` Delegate '' I have to update the interface which of course has effects on all of the implementations . Does this violate the Open/Close Principle ? Can you recommend a design pattern or refactor that may help me here ? <code> public interface IActionProvider { public void Complete ( WorkItem workItem ) ; public void Cancel ( WorkItem workItem ) ; public void Reassign ( WorkItem workItem ) ; } public class NormalActionProvider : IActionProvider { ... } public class UrgentActionProvider : IActionProvider { ... . }
Recommend a design pattern
C_sharp : Following is a complete console program that reproduces a strange error I have been experiencing . The program reads a file that contains urls of remote files , one per line . It fires up 50 threads to download them all.On my local computer it works fine . On the server , after downloading a few hundred images , it shows an error of either Attempted to read or write protected memory or Unable to read data from the transport connection : A blocking operation was interrupted by a call to WSACancelBlockingCall..It seems to be a native error , because neither the inner nor the outer catch catches it . I never see Something bad happened..I ran it in WinDbg , and it showed the following : I just turned off Lavasoft , and now WinDbg shows this : <code> static void Main ( string [ ] args ) { try { string filePath = ConfigurationManager.AppSettings [ `` filePath '' ] , folder = ConfigurationManager.AppSettings [ `` folder '' ] ; Directory.CreateDirectory ( folder ) ; List < string > urls = File.ReadAllLines ( filePath ) .Take ( 10000 ) .ToList ( ) ; int urlIX = -1 ; Task.WaitAll ( Enumerable.Range ( 0 , 50 ) .Select ( x = > Task.Factory.StartNew ( ( ) = > { while ( true ) { int curUrlIX = Interlocked.Increment ( ref urlIX ) ; if ( curUrlIX > = urls.Count ) break ; string url = urls [ curUrlIX ] ; try { var req = ( HttpWebRequest ) WebRequest.Create ( url ) ; using ( var res = ( HttpWebResponse ) req.GetResponse ( ) ) using ( var resStream = res.GetResponseStream ( ) ) using ( var fileStream = File.Create ( Path.Combine ( folder , Guid.NewGuid ( ) + url.Substring ( url.LastIndexOf ( ' . ' ) ) ) ) ) resStream.CopyTo ( fileStream ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Error downloading img : `` + url + `` \n '' + ex ) ; continue ; } } } ) ) .ToArray ( ) ) ; } catch { Console.WriteLine ( `` Something bad happened . `` ) ; } } ( 3200.1790 ) : Access violation - code c0000005 ( first chance ) First chance exceptions are reported before any exception handling.This exception may be expected and handled.LavasoftTcpService64+0x765f:00000001 ` 8000765f 807a1900 cmp byte ptr [ rdx+19h ] ,0 ds : baadf00d ` 0000001a= ? ? 0:006 > g ( 3200.326c ) : CLR exception - code e0434352 ( first chance ) ( 3200.326c ) : CLR exception - code e0434352 ( first chance ) ( 3200.2b9c ) : Access violation - code c0000005 ( ! ! ! second chance ! ! ! ) LavasoftTcpService64 ! WSPStartup+0x9749:00000001 ` 8002c8b9 f3a4 rep movs byte ptr [ rdi ] , byte ptr [ rsi ] Critical error detected c0000374 ( 3c4.3494 ) : Break instruction exception - code 80000003 ( first chance ) ntdll ! RtlReportCriticalFailure+0x4b:00007fff ` 4acf1b2f cc int 30:006 > g ( 3c4.3494 ) : Unknown exception - code c0000374 ( first chance ) ( 3c4.3494 ) : Unknown exception - code c0000374 ( ! ! ! second chance ! ! ! ) ntdll ! RtlReportCriticalFailure+0x8c:00007fff ` 4acf1b70 eb00 jmp ntdll ! RtlReportCriticalFailure+0x8e ( 00007fff ` 4acf1b72 ) 0:006 > gWARNING : Continuing a non-continuable exception ( 3c4.3494 ) : C++ EH exception - code e06d7363 ( first chance ) HEAP [ VIPJobsTest.exe ] : HEAP : Free Heap block 0000007AB96CC5D0 modified at 0000007AB96CC748 after it was freed ( 3c4.3494 ) : Break instruction exception - code 80000003 ( first chance ) ntdll ! RtlpBreakPointHeap+0x1d:00007fff ` 4acf3991 cc int 3
Multithread error not caught by catch
C_sharp : Im trying to see some queries that my application using EntityFramework does.In my method wich is not async i can see the queries normally : But if its like : Is it possible to get the queries of a async method in IntelliTrace Events ? Thanks . <code> public List < Tool > GetTools ( ) { return EntityContext.ToList ( ) ; } public Task < List < Tool > > GetTools ( int quantity ) { return EntityContext.Take ( quantity ) .ToListAsync ( ) ; }
How to trace async database operations in Intellitrace Events ?
C_sharp : Back when I was learning about foreach , I read somewhere that this : is basically equivalent to this : Why does this code even compile if neither IEnumerator nor IEnumerator < T > implement IDisposable ? C # language specification only seems to mention the using statement in the context of IDisposable.What does such an using statement do ? <code> foreach ( var element in enumerable ) { // do something with element } using ( var enumerator = enumerable.GetEnumerator ( ) ) { while ( enumerator.MoveNext ( ) ) { var element = enumerator.Current ; // do something with element } }
Why does the using statement work on IEnumerator and what does it do ?
C_sharp : We have a REST API method similar to : This is a fairly costly method with some complicated DB calls , and we have a common situation where hundreds of users with the same AccountId will make the call almost simultaneously ( they are all being notified with a broadcast ) .In the method , we cache the result set for 10 seconds since a near-time result is fine for everyone making the request within that window . However , since they all make the call at the same time ( again , for a specific AccountID ) the cache is never populated up front , so everyone ends up making the database call.So my question is , within the method , how can I pause all incoming requests for a specific accountId and make them all wait for the first result set to complete , so that the rest of the calls can use the cached result set ? I 've read a little about Monitor.Pulse and Monitor.Lock but the implementation for a per-accountId lock kind of escapes me . Any help would be tremendously appreciated . <code> List < item > GetItems ( int AccountID ) { var x = getFromCache ( AccountID ) ; if ( x==null ) { x = getFromDatabase ( AccountID ) ; addToCache ( AccountID , x ) ; } return x ; }
Pause simultaneous REST calls until first one completes
C_sharp : Upon successful login I want to save a cookie which contains username.The cookie saves correctly and loads username correctly but loses session ! The code to retreive username is : The code to save username is : Any help will be greatly appreciated , Thank you <code> if ( Request.Cookies [ `` userName '' ] ! = null ) { txtEmail.Text = Request.Cookies [ `` username '' ] .Value ; chkRemember.Checked = true ; } HttpCookie aCookie = new HttpCookie ( `` username '' ) ; aCookie.Value = txtEmail.Text ; aCookie.Expires = DateTime.Now.AddYears ( 5 ) ; Response.Cookies.Add ( aCookie ) ;
Session lost when saving cookie
C_sharp : Reading a Previous SO Question I was confused to find Eric Lippert saying that an interface can not be defined in C # for all Monads , using an implementation as below : My problem is all the problems listed in the question seem to have easy solutions : no `` higher kinded types '' = > use parent interfacesno static method in interface . = > why use static ? ! just use instance methodsMonad is a pattern allowing chaining of operations on wrapped typesit seems easy to define a C # interface for all Monads allowing us to write a generic class for all monadsWhere 's the problem ? <code> typeInterface Monad < MonadType < A > > { static MonadType < A > Return ( A a ) ; static MonadType < B > Bind < B > ( MonadType < A > x , Func < A , MonadType < B > > f ) ; } using System ; using System.Linq ; public class Program { public static void Main ( ) { //it works , where 's the problem ? new SequenceMonad < int > ( 5 ) .Bind ( x = > new SequenceMonad < float > ( x + 7F ) ) .Bind ( x = > new SequenceMonad < double > ( x + 5D ) ) ; } interface IMonad < T > { IMonad < T > Wrap ( T a ) ; IMonad < U > Bind < U > ( Func < T , IMonad < U > > map ) ; T UnWrap ( ) ; //if we can wrap we should be able to unwrap } class GenericClassForAllMonads < T > { //example writing logic for all monads IMonad < U > DoStuff < U > ( IMonad < T > input , Func < T , IMonad < U > > map ) { return map ( input.UnWrap ( ) ) ; } } class SequenceMonad < T > : IMonad < T > where T : new ( ) { //specific monad implementation readonly T [ ] items ; //immutable public SequenceMonad ( T a ) { Console.WriteLine ( `` wrapped : '' +a ) ; items = new [ ] { a } ; } public IMonad < B > Bind < B > ( Func < T , IMonad < B > > map ) { return map ( UnWrap ( ) ) ; } public T UnWrap ( ) { return items == null ? default ( T ) : items.FirstOrDefault ( ) ; } public IMonad < T > Wrap ( T a ) { Console.WriteLine ( `` wrapped : '' +a ) ; return new SequenceMonad < T > ( a ) ; } } }
Here is the C # Monad , where is the problem ?
C_sharp : Note : For Assert , using XunitAnonymous objects use value equality : Anonymous arrays with anonymous objects use value equality : Anonymous objects with nested arrays seem to use reference equality ( this fails ) : But this works ( presumably because there 's now reference equality ) : And this works ( so it appears I can recursively nest anonymous objects with value equality preserved ) : I 'm not sure how equality is being conducted here , but I 'd like to be able to nest objects and arrays and have infinite-depth value equality . How might I go about doing that ? UpdateLooks like Fluent Assertions solved my problem ( this test passes ) : <code> Assert.Equal ( new { foo = `` bar '' } , new { foo = `` bar '' } ) ; Assert.Equal ( new [ ] { new { foo = `` bar '' } } , new [ ] { new { foo = `` bar '' } } ) ; Assert.Equal ( new { baz = new [ ] { new { foo = `` bar '' } } , new { baz = new [ ] { new { foo = `` bar '' } } ) ; var baz = new [ ] { new { foo = `` bar '' } } ; Assert.Equal ( new { baz } , new { baz } ) ; Assert.Equal ( new { baz = new { qux = new { foo = `` bar '' } } } , new { baz = new { qux = new { foo = `` bar '' } } } ) ; ( new { baz = new [ ] { new { foo = `` bar '' } } } ) .Should ( ) .BeEquivalentTo ( new { baz = new [ ] { new { foo = `` bar '' } } } ) ;
In C # , how do you get recursive value equality for nested anonymous arrays and objects ?