text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : In the sample code below I get the following exception when doing db.Entry ( a ) .Collection ( x = > x.S ) .IsModified = true : System.InvalidOperationException : 'The instance of entity type ' B ' can not be tracked because another instance with the key value ' { Id : 0 } ' is already being tracked . When attaching existing entities , ensure that only one entity instance with a given key value is attached.Why does n't it add instead of attach the instances of B ? Strangely the documentation for IsModified does n't specify InvalidOperationException as a possible exception . Invalid documentation or a bug ? I know this code is strange , but I wrote it only to understand how ef core works in some weird egde cases . What I want is an explanation , not a work around . <code> using Microsoft.EntityFrameworkCore ; using Microsoft.Extensions.Logging ; using System ; using System.Collections.Generic ; using System.Linq ; class Program { public class A { public int Id { get ; set ; } public ICollection < B > S { get ; set ; } = new List < B > ( ) { new B { } , new B { } } ; } public class B { public int Id { get ; set ; } } public class Db : DbContext { private const string connectionString = @ '' Server= ( localdb ) \mssqllocaldb ; Database=Apa ; Trusted_Connection=True '' ; protected override void OnConfiguring ( DbContextOptionsBuilder o ) { o.UseSqlServer ( connectionString ) ; o.EnableSensitiveDataLogging ( ) ; } protected override void OnModelCreating ( ModelBuilder m ) { m.Entity < A > ( ) ; m.Entity < B > ( ) ; } } static void Main ( string [ ] args ) { using ( var db = new Db ( ) ) { db.Database.EnsureDeleted ( ) ; db.Database.EnsureCreated ( ) ; db.Add ( new A { } ) ; db.SaveChanges ( ) ; } using ( var db = new Db ( ) ) { var a = db.Set < A > ( ) .Single ( ) ; db.Entry ( a ) .Collection ( x = > x.S ) .IsModified = true ; db.SaveChanges ( ) ; } } } | Unexpected InvalidOperationException when trying to change relationship via property default value |
C_sharp : I found in legacy code following line : What does [ , ] mean here ? <code> protected bool [ , ] PixelsChecked ; | bool [ , ] - What does this syntax mean in c # ? |
C_sharp : Is there a generally-accepted best practice for creating an event handler that unsubscribes itself ? E.g. , the first thing I came up with is something like : To say that this feels hackish/bad is an understatement . It 's tightly coupled with a temporal dependency ( HandlerToUnsubscribe must be assigned the exact value at the exact right time ) . I feel like I must be playing the part of a complicator in this case -- - is there something stupid or simple that I 'm missing ? Context : I 'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms ( using the useful ICommand in System.Windows.Input ) . One aspect of the binding infrastructure is that users who create a binding between a UI command component ( like a toolbar button or menu item ) have the option to listen to the command 's CanExecuteChanged event and then update the UI 's state based on that -- typically setting the Enabled property to true or false.The technique generally works quite well , but there are ways for the event to be fired prior to a ui component 's handle having been created . I 'm trying to guarantee that the provided handler is n't run unless the handle has been created . Resultantly , I 'm considering providing a general helper class ( `` Bar '' ) that will aid implementation . The goal of Bar is to check to see if the appropriate handle exists . If so , great ! If not , it will subscribe to appropriate IsHandleCreated event so that the supplied handlers get run when the handle eventually is created . ( This is important b/c the client may set their bindings in the UI 's .ctor , before a handle exists . ) I want this subscription to be completely transparent , however , and so I also want each event handler to automatically unsubscribe itself from IsHandleCreated once it 's finished running.I 'm still at a point where I 'm trying to figure out if this is a good idea , so I have n't generalized the concept yet -- I 've only implemented it directly against ToolStripItems in this case to verify that the idea is sound . I 'm not sold on it yet , though.I understand that I also have the option of simply mandating that bindings can only be created once the UI 's handle has been created , in the OnLoad event of a form ( e.g. ) . I know that can work , I 've done it in the past . I 'd like to see if I can ease that particular requirement in this case though . If it 's even practical . <code> // Foo.cs// ... Bar bar = new Bar ( /* add ' l req 'd state */ ) ; EventHandler handler = new EventHandler ( bar.HandlerMethod ) ; bar.HandlerToUnsubscribe = handler ; eventSource.EventName += handler ; // ... // Bar.csclass Bar { /* add ' l req 'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get ; set ; } public void HandlerMethod ( object sender , EventArgs args ) { // Do what must be done w/ add ' l req 'd state ( ( EventSourceType ) sender ) .EventName -= this.HandlerToUnsubscribe ; } } | Am I using the right approach to monitor the tasks I want to perform when a handle is created ? |
C_sharp : The `` using '' construct looks incredibly handy for situations that require both beginning and separated end parts . Quick example to illustrate : The beginning part is defined as the constructor , the end part is the Dispose method.However despite of being attractive this construct has a serious caveat that comes from the fact that the Dispose method is called from within a finally block . So there are 2 problems : You should avoid throwing exceptions from the finally block because they will override the original exception that was supposed to be caught.There is no way of knowing inside of the Dispose method if an exception was thrown earlier between `` beginning '' and `` end '' and thus there is no way of handling the `` end '' part accordingly.These 2 things make using of this construct impractical which is a very sad fact.Now , my questions are : Is my understanding of the problems right ? Is this how `` using '' actually works ? If so , is there any way to overcome these problems and make practical use of the `` using '' construct other than what it was originally designed for ( releasing resources and cleaning up ) In case there is no practical way for `` using '' to be used this way . What are the alternative approaches ( to enforce the context over some code with the beginning and end parts ) ? <code> using ( new Tag ( `` body '' ) ) { Trace.WriteLine ( `` hello ! `` ) ; } // ... class Tag : IDisposable { String name ; public Tag ( String name ) { this.name = name ; Trace.WriteLine ( `` < `` + this.name + `` > '' ) ; Trace.Indent ( ) ; } public void Dispose ( ) { Trace.Unindent ( ) ; Trace.WriteLine ( `` < / '' + this.name + `` > '' ) } } | `` using '' construct and exception handling |
C_sharp : In .net fx i can doBut when looking at .net core or .net standard there is no more a culture parameter that can be passed . There is only string.ToLower ( ) and string.ToLowerInvariant ( ) Should the culture just be ommitted ? But should n't then there be issues when the culture of the string is not the current culture ? Any hints what the reason behind this is ? When I have the idea of a invariant culture I can use ToLowerInvariant ( ) .But what about use cases where i have to use string.ToLower ( ) in a culture that is not the current culture ? <code> myString.ToLower ( frenchCulture ) ; | .net core / standard string.ToLower ( ) has no culture parameter |
C_sharp : I 'm trying to generate a bit pattern ( repetitive strings ) and export into a text file , Here 's my code : Result : Now if I change the loop value to `` 20 '' , Result : I get this funny little rectangle boxes , could somebody please suggest me , what am I doing wrong here ? ? Many thanks for your time.. : ) <code> string pattern_01010101 = `` '' ; for ( int i = 0 ; i < 10 ; i++ ) { pattern_01010101 += `` 0,1,0,1,0,1,0,1 , '' ; } System.IO.File.WriteAllText ( @ '' C : \BField_pattern_01010101.txt '' , pattern_01010101 ) ; string pattern_01010101 = `` '' ; for ( int i = 0 ; i < 20 ; i++ ) { pattern_01010101 += `` 0,1,0,1,0,1,0,1 , '' ; } System.IO.File.WriteAllText ( @ '' C : \BField_pattern_01010101.txt '' , pattern_01010101 ) ; | How to generate repetitive bit pattern ( strings ) & export into text file ? |
C_sharp : Trying with a Diagnostic and a CodeFix to make a code who transform that : Into : Already done the diagnostic ( it works ) : Edit : I 've made some change.Now the incrementating is always recognized . The program go in the CodeFix , but my ReplaceToken with a SyntaxFactory do n't work . ( It 's now only for `` ++ '' and not `` -- '' ) : <code> variable = variable + 1 ; otherVariable = otherVariable -1 ; variable++ ; otherVariable -- ; var incrementing = node as BinaryExpressionSyntax ; if ( incrementing ! = null ) { string right = incrementing .Right.ToString ( ) ; string left = incrementing .Left.ToString ( ) ; if ( right == left + `` - 1 '' || right == left + `` + 1 '' ) { addDiagnostic ( Diagnostic.Create ( Rule , incrementation.GetLocation ( ) , `` Use the shorter way '' ) ) ; } } if ( node.IsKind ( SyntaxKind.SimpleAssignmentExpression ) ) //I use a node instead of a token { var IncrementationClause = ( BinaryExpressionSyntax ) node ; string left = IncrementationClause.Left.ToString ( ) ; left = left + `` ++ '' ; string rigt = IncrementationClause.Right.ToString ( ) ; var newIncrementationClause = IncrementationClause.ReplaceToken ( SyntaxFactory.Identifier ( IncrementationClause.Left.ToString ( ) ) , SyntaxFactory.Identifier ( left ) ) ; newIncrementationClause = IncrementationClause.ReplaceToken ( SyntaxFactory.Identifier ( IncrementationClause.Right.ToString ( ) ) , SyntaxFactory.Identifier ( String.Empty ) ) ; newIncrementationClause = IncrementationClause.ReplaceToken ( SyntaxFactory.Identifier ( IncrementationClause.OperatorToken.ToString ( ) ) , SyntaxFactory.Identifier ( String.Empty ) ) ; var newRoot = root.ReplaceNode ( IncrementationClause , newIncrementationClause ) ; return new [ ] { CodeAction.Create ( `` Changer la mise en forme '' , document.WithSyntaxRoot ( newRoot ) ) } ; } | Roslyn C # incrementing change |
C_sharp : Given a collection of Tasks : I would like to process the results of GetPricesAsync ( ) in whatever order they arrive . Currently , I 'm using a while loop to achieve this : Is this a problem that can be solved more elegantly using Rx ? I tried to use something like the code below but got stuck because somewhere I 'd have to await each getFlightPriceTask which would block and only then execute the next one instead of taking the first that 's done and then wait for the next : <code> var americanAirlines = new FlightPriceChecker ( `` AA '' ) ; ... var runningTasks = new List < Task < IList < FlightPrice > > > { americanAirlines.GetPricesAsync ( from , to ) , delta.GetPricesAsync ( from , to ) , united.GetPricesAsync ( from , to ) } ; while ( runningTasks.Any ( ) ) { // Wait for any task to finish var completed = await Task.WhenAny ( runningTasks ) ; // Remove from running list runningTasks.Remove ( completed ) ; // Process the completed task ( updates a property we may be binding to ) UpdateCheapestFlight ( completed.Result ) ; } runningTasks .ToObservable ( ) .Select ( getFlightPriceTask = > . ? ? ? . ) | How to turn a list of Tasks into an Observable and process elements as they are completed ? |
C_sharp : Im not sure because in Java getter/setter are looking a little bit different but whats the `` c # way '' to code this stuff ? Option a. ) b. ) c . ) Ok there are some examples . What would look better ? Should I write all the private variable declarations first then the properties or should I group my variable and property declaration next to each other . <code> private string name ; public string Name { get { return name ; } set { name = value ; } } private int time ; public int Time { get { return time ; } set { time = value ; } } private string _name ; private int _time ; public string name { get { return _name ; } set { _name = value ; } } public int time { get { return _time ; } set { _time = value ; } } public string name { get ; set ; } public int time { get ; set ; } | How should I use Properties in C # ? |
C_sharp : In our ASP.Net MVC 3 application we 're getting truncated strings on our forms when the string value contains a double-quote.For example , given a textbox : If the user enters the string : 'Hampshire '' County ' , when rendering the value back out to the form , only the string 'Hampsire ' is displayed . If I inspect the value in the model , the double-quote is escaped as 'Hampshire\ '' County ' . In Fiddler , the posted value is correct and the value is stored in the database correctly , so it would appear to be related to the Html helper that renders the textbox out to the client.Can anyone shed some light on this ? <code> @ Html.TextBoxFor ( m = > m.County ) | Truncated strings with TextBoxFor |
C_sharp : I was just reading an SO question on Python , and noticed the lack of parentheses in a for-loop . Looked nice to me , then I wondered : why does C # require them ? For example , I currently need to write : andSo I am wondering why I ca n't write : Is there a syntactic ambiguity in that statement that I am unaware of ? PS , funnily , braces can be optional for one-liners : <code> if ( thing == stuff ) { } foreach ( var beyonce in allthesingleladies ) { } if thing == stuff { } if ( thing == stuff ) dostuff ( ) ; | Why does C # require parens around conditionals ? |
C_sharp : I have an array consisting of following elements : The real object that i try to flatten is from importing data into array of arrays from CSV and then joining it on values of fields : I want to flatten that array of strings to get : I already have an solution that does that in loop , its not so performance-wise , but it seems to work ok . I 've tried to use SelectMany but can not make up a solution.Thank you very much for feedback ; ) I 've tried answer from npo : But CSVwriter class method accepts only explicitly typed : So how to do it in linq , I 've tried to : But no go , InvalidCastException arrises , unfortunately . <code> var schools = new [ ] { new object [ ] { new [ ] { `` 1 '' , '' 2 '' } , `` 3 '' , '' 4 '' } , new object [ ] { new [ ] { `` 5 '' , '' 6 '' } , `` 7 '' , '' 8 '' } , new object [ ] { new [ ] { `` 9 '' , '' 10 '' , '' 11 '' } , `` 12 '' , '' 13 '' } } ; var q = from c in list join p in vocatives on c.Line [ name1 ] .ToUpper ( ) equals p.first_name.ToUpper ( ) into ps from p in ps.DefaultIfEmpty ( ) select new object [ ] { c.Line , p == null ? `` ( No vocative ) '' : p.vocative , p == null ? `` ( No sex ) '' : p.sex } ; string [ ] { new string [ ] { `` 1 '' , '' 2 '' , '' 3 '' , '' 4 '' } , new string [ ] { `` 5 '' , '' 6 '' , '' 7 '' , '' 8 '' } , new string [ ] { `` 9 '' , '' 10 '' , '' 11 '' , '' 12 '' , '' 13 '' } } var result = schools.Select ( z = > z.SelectMany ( y= > y.GetType ( ) .IsArray ? ( object [ ] ) y : new object [ ] { y } ) ) ; IEnumerable < string [ ] > List < string [ ] > listOflists = ( List < string [ ] > ) result ; | How do I flatten an array of arrays ? |
C_sharp : I am writing code that interfaces with an external API that I can not change : It 's important that I call the correct overloaded method when reading data into buffer , but once the data is read in , I will process it generically . My first pass at code that does that was : C # , though , wo n't convert from T [ ] to byte [ ] . Is there a way to enumerate the types that T can represent explicitly ? I 've tried using a where T : clause , but there does n't appear to be a way to say where T : { byte , int , float , double and nothing else ever } ? Following the advice here : Generic constraint to match numeric types , I added constraints to the generic , and also added a generic method to my simulated API that takes an object as its parameterThis will compile and run happily , but the only method that is ever called is Foo ( object buffer ) , even when T is byte . Is there a way to force methods of non-generic classes to use the most specific overload when the calling class is generic ? <code> public class ExternalAPI { public static void Read ( byte [ ] buffer ) ; public static void Read ( int [ ] buffer ) ; public static void Read ( float [ ] buffer ) ; public static void Read ( double [ ] buffer ) ; } public class Foo < T > { T [ ] buffer ; public void Stuff ( ) { ExternalAPI.Foo ( buffer ) ; } } public class ExternalAPI { public static void Read ( object buffer ) ; public static void Read ( byte [ ] buffer ) ; public static void Read ( int [ ] buffer ) ; public static void Read ( double [ ] buffer ) ; } public class Foo < T > where T : struct , IComparable , IComparable < T > , IConvertible , IEquatable < T > , IFormattable { T [ ] buffer ; public void Stuff ( ) { ExternalAPI.Read ( buffer ) ; } } | Is it possible to force an external class to call a specialized overload when the calling class is , itself , generic ? |
C_sharp : The code below produces this error in Visual Studio 2012 ; `` A local variable named ' x ' can not be declared in this scope because it would give a different meaning to ' x ' , which is already used in a 'child ' scope to denote something else '' However . When modified as below I get this error ; `` The name ' x ' does not exist in the current context '' Is this a huge contradiction or am I missing something ? <code> for ( int x = 0 ; x < 9 ; x++ ) { //something } int x = 0 ; for ( int x = 0 ; x < 9 ; x++ ) { //something } x = 0 ; | For loop counter variable scope seems to have a dual personality ? |
C_sharp : Im working on an existing Windows Service project in VS 2013.I 've added a web API Controller class I cant remember now if its a ( v2.1 ) or ( v1 ) controller class ... .Anyway I 've called it SyncPersonnelViaAwsApiControllerIm trying to call it from a AWS lambda ... so If I call the GETwith const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/Get/4 ' , ( res ) = > { I get returned body : undefined '' value '' which is correct . However if I try and call I get returned body : undefined { `` Message '' : '' The requested resource does not support http method 'GET ' . `` } Does anyone have any idea why it works for GET and not POST ? As we can hit the get im confident its not the lambda but I have included it just incaseUPDATEThanks to @ Thangadurai post with AWS Lambda - NodeJS POST request and asynch write/read fileI was able to include a post_options ... please see updated lambdaIt is now flagging as error : I had this getaggrinfo ENOTFOUND error before , it means it cant find the address ... .but arnt the hostname and api path correct ? I am trying to reachand yes the port is 80any help would be appreciatedTaM <code> public string Get ( int id ) { return `` value '' ; } const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/SapCall ' , ( res ) = > { //// POST api/ < controller > public string SapCall ( [ FromBody ] string xmlFile ) { string responseMsg = `` Failed Import User '' ; if ( ! IsNewestVersionOfXMLFile ( xmlFile ) ) { responseMsg = `` Not latest version of file , update not performed '' ; } else { Business.PersonnelReplicate personnelReplicate = BusinessLogic.SynchronisePersonnel.BuildFromDataContractXml < Business.PersonnelReplicate > ( xmlFile ) ; bool result = Service.Personnel.SynchroniseCache ( personnelReplicate ) ; if ( result ) { responseMsg = `` Success Import Sap Cache User '' ; } } return `` { \ '' response\ '' : \ '' `` + responseMsg + `` \ '' , \ '' isNewActiveDirectoryUser\ '' : \ '' false \ '' } '' ; } const AWS = require ( 'aws-sdk ' ) ; const https = require ( 'https ' ) ; var s3 = new AWS.S3 ( ) ; var un ; var pw ; var seralizedXmlFile ; let index = function index ( event , context , callback ) { // For the purpose of testing I have populated the bucket and key params with objects that already exist in the S3 bucket var params = { Bucket : `` testbucketthur7thdec '' , Key : `` personnelData_50312474_636403151354943757.xml '' } ; // Get Object from S3 bucket and add to 'seralizedXmlFile's3.getObject ( params , function ( data , err ) { console.log ( `` get object from S3 bucket '' ) ; if ( err ) { // an error occurred } else { console.log ( `` data `` + data ) ; // populate seralizedXmlFile with data from S3 bucket let seralizedXmlFile = err.Body.toString ( 'utf-8 ' ) ; // Use the encoding necessary console.log ( `` objectData `` + seralizedXmlFile ) ; } } ) ; // set params var ssm = new AWS.SSM ( { region : 'Usa2 ' } ) ; console.log ( 'Instatiated SSM ' ) ; var paramsx = { 'Names ' : [ '/Sap/ServiceUsername ' , '/Sap/ServicePassword ' ] , 'WithDecryption ' : true } ; // password and username ssm.getParameters ( paramsx , function ( err , data ) { console.log ( 'Getting parameter ' ) ; if ( err ) console.log ( err , err.stack ) ; // an error occurred else { console.log ( 'data : ' + JSON.stringify ( data ) ) ; // successful response console.log ( 'password : ' + data.Parameters [ 0 ] .Value ) ; console.log ( 'username : ' + data.Parameters [ 1 ] .Value ) ; pw = data.Parameters [ 0 ] .Value ; un = data.Parameters [ 1 ] .Value ; } // request to external api application & remove dependency on ssl process.env.NODE_TLS_REJECT_UNAUTHORIZED = `` 0 '' ; //POST DOES NOT WORK const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/SapEaiCall ' , ( res ) = > { //GET WORKS // const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/Get/4 ' , ( res ) = > { res.headers + 'Authorization : Basic ' + un + ' : ' + pw ; let body = seralizedXmlFile ; console.log ( 'seralizedXmlFile : ' + seralizedXmlFile ) ; console.log ( 'Status : ' , res.statusCode ) ; console.log ( 'Headers : ' , JSON.stringify ( res.headers ) ) ; res.setEncoding ( 'utf8 ' ) ; res.on ( 'data ' , ( chunk ) = > body += chunk ) ; res.on ( 'end ' , ( ) = > { console.log ( 'Successfully processed HTTPS response ' ) ; callback ( null , body ) ; console.log ( 'returned body : ' , body ) ; } ) ; } ) ; req.end ( ) ; } ) ; } ; exports.handler = index ; // An object of options to indicate where to post to var post_options = { host : 'https : //actualUrlAddress ' , port : '80 ' , path : '/api/SyncPersonnelViaAwsApi/SapEaiCall ' , method : 'POST ' , headers : { 'Content-Type ' : 'application/json ' , 'Content-Length ' : post_data.length } } ; const req = https.request ( post_options , ( res ) = > { res.headers + 'Authorization : Basic ' + un + ' : ' + pw ; let body = seralizedXmlFile ; console.log ( 'seralizedXmlFile : ' + seralizedXmlFile ) ; console.log ( 'Status : ' , res.statusCode ) ; console.log ( 'Headers : ' , JSON.stringify ( res.headers ) ) ; res.setEncoding ( 'utf8 ' ) ; res.on ( 'data ' , ( chunk ) = > body += chunk ) ; res.on ( 'end ' , ( ) = > { console.log ( 'Successfully processed HTTPS response ' ) ; callback ( null , body ) ; console.log ( 'returned body : ' , body ) ; } ) ; } ) ; req.end ( ) ; Error : getaddrinfo ENOTFOUND http : //actualUrlAddress http : //actualUrlAddress.private:80 const req = https.request ( 'https : //actualUrlAddress/api/SyncPersonnelViaAwsApi/SapCall | can use API GET but not API POST |
C_sharp : Given that I have three tables , Vehicles , Cars , Bikes . Both Cars and Bikes have a VehicleID FK that links back to Vehicles.I want to count all vehicles that are cars like this.However , this will give me ALL the rows of vehicles and put null in the rows where the vehicle type is Bikes.I 'm using linqpad to do this and seeing the sql statment I realised the reason why it does this is because on the x.Car join it performs a LEFT OUTER JOIN between vehicle and car which means it will return all vehicles.If I change the query to just use JOIN , then it works as expected.Is there a way to tell linq to do a join using this type of syntax ? Ultimately I want to do something like : But because of this error : I end up doing this : <code> Vehicles.Select ( x= > x.Car ) .Count ( ) ; Vehicles.Select ( x= > x.Car.CountryID ) .Distinct ( ) .Dump ( ) ; InvalidOperationException : The null value can not be assigned to a member with type System.Int32 which is a non-nullable value type . Vehicles.Where ( x= > x.Car ! =null ) .Select ( x= > x.Car.CountryID ) .Distinct ( ) .Dump ( ) ; | linq to sql : specifying JOIN instead of LEFT OUTER JOIN |
C_sharp : I 've created a user control in a Windows Application C # 3.5 and it has a number of properties ( string , int , color etc ) . These can be modified in the properties window and the values are persisted without problem.However I 've created a property likeThe properties dialog allows me to add and remove these items , but as soon as I close the dialog the values I entered are lost . What am I missing ? Many thanks ! <code> public class MyItem { public string Text { get ; set ; } public string Value { get ; set ; } } public class MyControl : UserControl { public List < MyItem > Items { get ; set ; } } | .Net WinForm application not persisting a property of type List < MyClass > |
C_sharp : During a demo I saw a piece of test code where the developer had pasted an url in the code . And when the developer build the application everything worked , but we where all very curious why the compiler accepted the url as a line.Why does the code above build ? Does the compiler treat the line as a comment ? <code> public class Foo { // Why does n't 'http : //www.foo.org ' break the build ? public void Bar ( ) { http : //www.foo.org Console.WriteLine ( `` Do stuff '' ) ; } } | Url in code not breaking build |
C_sharp : In my Word add-in , I have a Word Document object which contains a particular Section . In this Section , I append a Shape : My issue is that some Word document templates have images or other things that appear over top of my shape . Originally , I thought that setting the Z order would be enough to fix this : It did not . So my question is , how can I absolutely set the Z order of my Shape , or in other words , what else would I have to do to set in order to make my Shape such that it becomes the top-most thing you see in the document ( meaning , that it appears above all of the other things ) ? <code> var shape = section.Headers [ WdHeaderFooterIndex.wdHeaderFooterFirstPage ] .Shapes.AddTextEffect ( MsoPresetTextEffect.msoTextEffect1 , `` Example text ... '' , `` Calibri '' , 72 , MsoTriState.msoFalse , MsoTriState.msoFalse , 0 , 0 , section.Headers [ WdHeaderFooterIndex.wdHeaderFooterFirstPage ] .Range ) as Shape ; shape.ZOrder ( MsoZOrderCmd.msoBringToFront ) ; | Making a Shape top-most |
C_sharp : I would like to be able to write the following in a LINQ query : to use this code , I have the following method : How do I write this method so that the query stated above would work ? <code> from item in listcollate by item.Propertyselect item ; public static IEnumerable < T > CollateBy < T , TKey > ( this IEnumerable < T > arr , Func < T , TKey > keySelector ) { foreach ( var group in arr.GroupBy ( keySelector ) ) { foreach ( var item in group ) yield return item ; } } | Extend the options of LINQ |
C_sharp : I am drawing a rectangle in the paint method of a control . There is a zoom factor to consider , e.g . each positive MouseWheel event causes the control to repaint and then the rectangle gets bigger . Now I am drawing a string inside this rectangle , but I could n't figure out how to relate the font size of the text to the growth or shrinkage of the rectangle that the text is supposed to be inside it.Here is some relevant part of my code : A hardcoded simple multiplication by the zoom factor seems to some how work but this is not the smartest way I assume . int size = 8 + _zoomFactor * 6 ; <code> public GateShape ( Gate gate , int x , int y , int zoomFactor , PaintEventArgs p ) { _gate = gate ; P = p ; StartPoint = new Point ( x , y ) ; ShapeSize = new Size ( 20 + zoomFactor * 10 , 20 + zoomFactor * 10 ) ; Draw ( ) ; } public Bitmap Draw ( ) { # if DEBUG Debug.WriteLine ( `` Drawing gate ' '' + _gate.GetGateType ( ) + `` ' with symbol ' '' + _gate.GetSymbol ( ) + `` ' '' ) ; # endif Pen pen = new Pen ( Color.Red ) ; DrawingRect = new Rectangle ( StartPoint.X , StartPoint.Y , ShapeSize.Width , ShapeSize.Height ) ; P.Graphics.DrawRectangle ( pen , DrawingRect ) ; StringFormat sf = new StringFormat { Alignment = StringAlignment.Center , LineAlignment = StringAlignment.Center } ; using ( Font font = new Font ( FontFamily.GenericMonospace , 8 ) ) //what to do here ? P.Graphics.DrawString ( _gate.GetSymbol ( ) , font , Brushes.Black , DrawingRect , sf ) ; return null ; } | Dynamic font size to draw string inside a rectangle |
C_sharp : I have a system that displays entries ordered by one of three fields , the most popular Today , This Week and This Month . Each time an entry is viewed the score is incremented by 1 thus changing the order.So if entry 1 is new and viewed 10 times today its scores will be : The Current SolutionAt the moment I simply have 3 fields associated with each entry , one for today another for this week and another for this month . Each time an entry is viewed all three scores are incremented by 1.At the end of the day , the day score is reset to 0 . At the end of the current week the week score is set to 0 and at the end of the current calender month , the month score is set to 0.The ProblemAlthough this works and uses little space it is not ideal for two reasons:1 ) At the end of the current period ( day , week , month ) that value is reset to 0 all at once meaning that at 00:00:00 every day the ranking is all reset and all daily scores are set to 0 , the same is true for end of the week and end of the month . At 00:00:00 on the 1st of each month all scores are set to 0 loosing all existing ranking data.2 ) Because the end of the month usually falls inside a week ( Mon-Sun ) , the monthly scores are reset during the week leading to weekly scores being higher than monthly scores.Possible SolutionI could use a rolling hourly counter for every hour of the month which is used to calculate the scores for the current day , week , month based on the current hour index.So on the 1st at 4am a view would be placed in hours [ 4 ] The stats calculator would then then use today as the sum of the last 24 values and the This Week score would be the sum of the last ( 24*7 ) values . Finally the This Month would be the sum of the last ( 24*31 ) values.Solution problemsThe major issue with solution 1 is the disk/memory requirements . I 've gone from using 3 32 bit values in my current solution to using 744 32 bit values . Even if I change them to in16 I 'm still going to be using a lot more memory per entryWith this solution my memory usage per entry has jumped 12400 % ! ! Can anyone suggest another solution that would meet resolve the issues in my current solution but without using 1.5k per entry ? Many thanks ! <code> Today : 10Week : 10Month : 10 Array size = 31 * 24 = 744 int16 values hours [ 4 ] ++ Memory per Entry = 3 * 4 bytes = 12 bytes ( Existing ) Memory per Entry = 744 * 2 = 1,488 bytes ( possible solution ) | Popular Today , This Week , This Month - Design Pattern |
C_sharp : I have a Visual Studio 2008 C # .NET 3.5 project where a class listens for an event invocation from another class that is multithreaded . I need to ensure that my event only allows simultaneous access to a maximum of 10 threads . The 11th thread should block until one of the 10 finishes.I do not have control over the other MyObj class , so I can not implement a threadpool there.What is the best way to implement this ? Thanks , PaulH <code> myobj.SomeEvent += OnSomeEvent ; private void OnSomeEvent ( object sender , MyEventArgs args ) { // allow up to 10 threads simultaneous access . Block the 11th thread . using ( SomeThreadLock lock = new SomeThreadLock ( 10 ) ) { DoUsefulThings ( args.foo ) ; } } | A function that only permits N concurrent threads |
C_sharp : People here are using visual studio for performance testing . Now there are some small issues with some javascript parts : they are not able to check the performance of the javascript part with visual studio web-performance testing.I never used visual studio performance test , so I really have no idea how to bench stuff there , but I saw there are a lot of solutions for web + js performance check . I thought we could use other tools and frameworks , but its not allowed . People here want to use visual studio for everything . So this is making stuff more tricky.If I would have to check the javascript performance , I would easily do something like this : At the end I can see in the variable bench my result . Now I just have to pass this variable `` somehow '' to the visual studio performance test ? Via C # ? Or how is this stuff working ? Could this be a good solution ? Any other ideas ? <code> var begin = new Date ( ) ; functionA ( ) ; functionB ( ) ; functionX ( ) ; var end = new Date ( ) ; var bench = end - begin ; | Read JS variable in C # / Forwarding JS variable to visual studio performance test ? |
C_sharp : I have come across some unit tests written by another developer that regularly use an overloaded version of Assert.AreEqual like so : stringParamX is set within the unit test and stringparamY will be the result from the system under test.It is possible hat this code may be ported to other countries and these tests may be executed . However , on having a look at the MSDN docs for Culture , I ca n't help thinking that passing in CultureInfo.InvariantCulture is adding some unnecessary complexity here . I 'm not sure what kind of impact removing it would have on the tests if executed in other cultures.In the context of unit testing in my situation , why should I ( or not ) write asserts like this ? <code> Assert.AreEqual ( stringparamX , stringParamY , true , CultureInfo.InvariantCulture ) ; | When to pass Culture when comparing strings using Assert.AreEqual ( ) in C # |
C_sharp : I use LINQ-SQL as my DAL , I then have a project called DB which acts as my BLL . Various applications then access the BLL to read / write data from the SQL Database.I have these methods in my BLL for one particular table : All pretty straight forward I thought.Get_SystemSalesTaxListByZipCode is always returning a null value though , even when it has a ZIP Code that exists in that table.If I write the method like this , it returns the row I want : Why does the other method not return the same , as the query should be identical ? Note that , the overloaded Get_SystemSalesTaxList ( string strSalesTaxID ) returns a record just fine when I give it a valid SalesTaxID.Is there a more efficient way to write these `` helper '' type classes ? Thanks ! <code> public IEnumerable < SystemSalesTaxList > Get_SystemSalesTaxList ( ) { return from s in db.SystemSalesTaxLists select s ; } public SystemSalesTaxList Get_SystemSalesTaxList ( string strSalesTaxID ) { return Get_SystemSalesTaxList ( ) .Where ( s = > s.SalesTaxID == strSalesTaxID ) .FirstOrDefault ( ) ; } public SystemSalesTaxList Get_SystemSalesTaxListByZipCode ( string strZipCode ) { return Get_SystemSalesTaxList ( ) .Where ( s = > s.ZipCode == strZipCode ) .FirstOrDefault ( ) ; } public SystemSalesTaxList Get_SystemSalesTaxListByZipCode ( string strZipCode ) { var salesTax = from s in db.SystemSalesTaxLists where s.ZipCode == strZipCode select s ; return salesTax.FirstOrDefault ( ) ; } | What 's the difference between these LINQ queries ? |
C_sharp : Problem : Displaying large amounts of data in a scrollable area has horrible performance and/or User eXperience.Tried : Basically set a DataTemplate in a ListBox to show a grid of populated data with the VirtualizationMode set to Recycle and a fixed height set on the ListBox iteself . Something like the example below.The ContentControl would be bringing in a standard < Grid > from another view that formats the overall layout of the populated items consisting of around 20 static , and 20 data bound TextBlocks.This works alright , and cut the initial loads in half . HOWEVER , now the problem is I need the ability for the height to NOT be a fixed size so it takes up the space available in its parent and can even be resized . Thanks to @ DanFox I found out you have to fix the height in one form or another to invoke the virtualizing or the RenderEngine just thinks it has infinite room anyway.The Question is : Is there a better way to do this , or how can I at least fix the current technique to allow for better UX ? I 'm generating potentially hundreds of these items so I need the performance enhancement of virtualization . However I also need to allow the user to resize the window and retain the ability to scroll effectively.Any insight is greatly appreciated , thanks and Happy Holidays ! <code> < ListBox x : Name= '' Items '' TabNavigation= '' Once '' VirtualizingStackPanel.VirtualizationMode= '' Recycling '' Height= '' 500 '' > < ListBox.ItemTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' Margin= '' 0,5 '' > < HyperlinkButton Content= '' Action '' Margin= '' 5 '' / > < ContentControl cal : View.Model= '' { Binding } '' VerticalContentAlignment= '' Stretch '' HorizontalContentAlignment= '' Stretch '' / > < /StackPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > | Virtualization Performance Issue with Large Scrollable Data SL4 |
C_sharp : I have a C # web api which I use to access an F # library . I have created a DU of the types I want to return and use pattern matching to choose which is return back to the c # controller . In the C # controller how do I access the data of the type which is return from the function call to the F # library ? C # ControllerF # TypesF # function <code> public HttpResponseMessage Post ( ) { var _result = Authentication.GetAuthBehaviour ( ) ; //Access item1 of my tuple var _HTTPStatusCode = ( HttpStatusCode ) _result.item1 ; //Access item2 of my tuple var _body = ( HttpStatusCode ) _result.item2 ; return base.Request.CreateResponse ( _HTTPStatusCode , _body ) ; } module Types = [ < JsonObject ( MemberSerialization=MemberSerialization.OptOut ) > ] [ < CLIMutable > ] type ValidResponse = { odata : string ; token : string ; } [ < JsonObject ( MemberSerialization=MemberSerialization.OptOut ) > ] [ < CLIMutable > ] type ErrorResponse = { code : string ; message : string ; url : string ; } type AuthenticationResponse = | Valid of int * ValidResponse | Error of int * ErrorResponse module Authentication = open Newtonsoft.Json let GetAuthBehaviour ( ) = let behaviour = GetBehaviour.Value.authentication match behaviour.statusCode with | 200 - > let deserializedAuthenticationResponse = JsonConvert.DeserializeObject < Types.ValidResponse > ( behaviour.body ) Types.Valid ( behaviour.statusCode , deserializedAuthenticationResponse ) | _ - > let deserializedAuthenticationResponse = JsonConvert.DeserializeObject < Types.ErrorResponse > ( behaviour.body ) Types.Error ( behaviour.statusCode , deserializedAuthenticationResponse ) | Working with F # types in C # |
C_sharp : I 'm working on a neural networks project and I have 2 classes like this : When I try to create network and display it 's `` contents '' : When I run that code - I 'm getting something like this ( all weights are identical ) : When I saw it - I tried to debug and find my mistake . However , when I put breakpoint in the neuron constructor - my network initializes as I want ( weights are different ) : I tried to use Debug and Release configurations - same results.Can someone explain what is going on here ? Magic ? <code> public class Net { // Net object is made of neurons public List < Neuron > Neurons = new List < Neuron > ( ) ; // neurons are created in Net class constructor public Net ( int neuronCount , int neuronInputs ) { for ( int n = 0 ; n < neuronCount ; n++ ) { Neurons.Add ( new Neuron ( n , neuronInputs ) ) ; } } } public class Neuron { public int index ; // neuron has index public List < double > weights = new List < double > ( ) ; // and list of weights // Neuron constructor is supposed to add random weights to new neuron public Neuron ( int neuronIndex , int neuronInputs ) { Random rnd = new Random ( ) ; for ( int i = 0 ; i < neuronInputs ; i++ ) { this.index = neuronIndex ; this.weights.Add ( rnd.NextDouble ( ) ) ; } } Neuro.Net Network = new Neuro.Net ( 4 , 4 ) ; // creating network with 4 neurons with 4 weights each// dgv is a DataGridView for weights previewdgv.Rows.Clear ( ) ; dgv.Columns.Clear ( ) ; // creating columnsforeach ( Neuro.Neuron neuron in Network.Neurons ) { dgv.Columns.Add ( `` colN '' + neuron.index , `` N '' + neuron.index ) ; } dgv.Rows.Add ( Network.Neurons [ 0 ] .weights.Count ( ) ) ; for ( int n = 0 ; n < Network.Neurons.Count ( ) ; n++ ) { for ( int w = 0 ; w < Network.Neurons [ n ] .weights.Count ( ) ; w++ ) { dgv.Rows [ w ] .Cells [ n ] .Value = Network.Neurons [ n ] .weights [ w ] ; } } | Very weird - code ( with Random ) works different when I use breakpoint |
C_sharp : When we connect to a database in ASP.NET you must specify the appropriate connection string . However most other instances where data is to be specified is done within an object.For example why could n't we have connection objects such as : which is far better than some key/value string : Data Source=myServerAddress ; Initial Catalog=myDataBase ; UserId=myUsername ; Password=myPassword ; The only reason I can think of is to allow storage in web.config , but there would be nothing stopping us storing the individual values in there anyway.I 'm sure there are good reasons , but what are they ? <code> var connection = new connectionObject ( ) { DataSource = `` myServerAddress '' , IntialCatalog = `` myDataBase '' , UserId = `` myUsername '' , Password = `` myPassword '' } | Why do we need connection strings ? |
C_sharp : I 'm wondering if someone else can come up with a better way of simplifying relative URLs on either the basis of System.Uri or other means that are available in the standard .NET framework . My attempt works , but is pretty horrendous : This gives , for example : The problem that makes this so awkward is that Uri itself does n't seem to simplify URLs that are relative and MakeRelativeUri also only works on absolute URLs . So to trick the Uri class into doing what I want , I construct a base URL that has the appropriate amount of nesting.I could also use System.IO.Path , but then I 'd have to search-and-replace backlashes to slashes ... There has to be a better way , right ? <code> public static String SimplifyUrl ( String url ) { var baseDummyUri = new Uri ( `` http : //example.com '' , UriKind.Absolute ) ; var dummyUri = new Uri ( baseDummyUri , String.Join ( `` / '' , Enumerable.Range ( 0 , url.Split ( new [ ] { `` .. '' } , StringSplitOptions.None ) .Length ) .Select ( i = > `` x '' ) ) ) ; var absoluteResultUri = new Uri ( dummyUri , url ) ; var resultUri = dummyUri.MakeRelativeUri ( absoluteResultUri ) ; return resultUri.ToString ( ) ; } ./foo - > foofoo/./bar - > foo/barfoo/../bar - > bar | Simplify a relative URL |
C_sharp : I have some code in a WPF application that looks like this : The dispose method is never getting explicitly called so the destructor calls it . It seems like in this case the object would be destroyed before the delegate in the BeginInvoke fires on the UI thread . It appears to be working though . What is happening here ? Is this safe ? <code> public class MyTextBox : System.Windows.Controls.TextBox , IDisposable { public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { Dispatcher.BeginInvoke ( ( Action ) delegate { // do work on member variables on the UI thread . } ) ; } ~MyTextBox ( ) { Dispose ( false ) ; } } | Calling BeginInvoke from a destructor |
C_sharp : Is there a performance/memory usage difference between the two following property declarations , and should one be preferred ? Also , does the situation change if the Boolean is replaced with a different immutable value ( e.g . string ) ? <code> public bool Foo = > true ; public bool Foo { get ; } = true ; | Get-only property with constant value , auto-property or not ? |
C_sharp : So I 've been going through various problems to review for upcoming interviews and one I encountered is determining whether two strings are rotations of each other . Obviously , I 'm hardly the first person to solve this problem . In fact , I did discover that my idea for solving this seems similar to the approach taken in this question.Full disclosure : I do have a related question on Math SE that 's focused on the properties from a more mathematical perspective ( although it 's worth noting that the way that I tried to formulate the ideas behind this there end up being incorrect for reasons that are explained there ) .Here 's the idea ( and this is similar to the approach taken in the linked question ) : suppose you have a string abcd and the rotation cdab . Clearly , both cd and ab are substrings of cdab , but if you concatenate them together you get abcd.So basically , a rotation simply entails moving a substring from the end of the string to the beginning ( e.g . we constructed cdab from abcd by moving cd from the end of the string to the beginning of the string ) .I came up with an approach that works in a very restricted case ( if both of the substrings consist of consecutive letters , like they do in the example there ) , but it fails otherwise ( and I give an example of passing and failing cases and inputs/outputs below the code ) . I 'm trying to figure out if it 's possible ( or even worthwhile ) to try to fix it to work in the general case.And now for the sample inputs/outputs : Is it possible/worthwhile to salvage this approach and have it still be O ( n ) , or should I just go with one of the approaches described in the post I linked to ? ( Note that this is n't actually production code or homework , it 's purely for my own learning ) .Edit : For further clarification based on the comments , there are actually two questions here - first , is this algorithm fixable ? Secondly , is it even worth fixing it ( or should I just try another approach like one described in the answers or the other question I linked to ) ? I thought of a few potential fixes but they all involved either inelegant special-case reasoning or making this algorithm O ( n^2 ) , both of which would kill the point of the algorithm in the first place . <code> public bool AreRotations ( string a , string b ) { if ( a == null ) throw new ArgumentNullException ( `` a '' ) ; else if ( b == null ) throw new ArgumentNullException ( `` b '' ) ; else if ( a.Trim ( ) .Length == 0 ) throw new ArgumentException ( `` a is empty or consists only of whitespace '' ) ; else if ( b.Trim ( ) .Length == 0 ) throw new ArgumentException ( `` b is empty or consists only of whitespace '' ) ; // Obviously , if the strings are of different lengths , they ca n't possibly be rotations of each other if ( a.Length ! = b.Length ) return false ; int [ ] rotationLengths = new int [ a.Length ] ; /* For rotations of length -2 , -2 , -2 , 2 , 2 , 2 , the distinct rotation lengths are -2 , 2 * * In the example I give below of a non-working input , this contains -16 , -23 , 16 , 23 * * On the face of it , that would seem like a useful pattern , but it seems like this * could quickly get out of hand as I discover more edge cases */ List < int > distinctRotationLengths = new List < int > ( ) ; for ( int i = 0 ; i < a.Length ; i++ ) { rotationLengths [ i ] = a [ i ] - b [ i ] ; if ( i == 0 ) distinctRotationLengths.Add ( rotationLengths [ 0 ] ) ; else if ( rotationLengths [ i ] ! = rotationLengths [ i - 1 ] ) { distinctRotationLengths.Add ( rotationLengths [ i ] ) ; } } return distinctRotationLengths.Count == 2 ; } StringIsRotation rot = new StringIsRotation ( ) ; // This is the case that does n't work right - it gives `` false '' instead of `` true '' bool success = rot.AreRotations ( `` acqz '' , `` qzac '' ) ; // True success = rot.AreRotations ( `` abcdef '' , `` cdefab '' ) ; // True success = rot.AreRotations ( `` ablm '' , `` lmab '' ) ; // False , but should be true - this is another illustration of the bug success = rot.AreRotations ( `` baby '' , `` byba '' ) ; // True success = rot.AreRotations ( `` abcdef '' , `` defabc '' ) ; //True success = rot.AreRotations ( `` abcd '' , `` cdab '' ) ; // True success = rot.AreRotations ( `` abc '' , `` cab '' ) ; // False success = rot.AreRotations ( `` abcd '' , `` acbd '' ) ; // This is an odd situation - right now it returns `` false '' but you could // argue about whether that 's correct success = rot.AreRotations ( `` abcd '' , `` abcd '' ) ; | How to generalize my algorithm to detect if one string is a rotation of another |
C_sharp : The Code PartImage Unfortunately this menu does not appear after I transform html file to aspx , what am I missing ? Do I missing something to enable ? Since the order of index.html file is absolutely the same with index.aspx , just I want to see the js powered menu . please help ! I just released that when I remove from the file , the menu appears . You may check the content of the Currency.js below.. please check-it up and let me know how can I fix this problemPS : I tried to replace the place of the reference of Currency.js to header block . But it did not work either..Currency.jsmain.jsI got the answer actually . I overwrite the onload method . Now , I need to run the Currency 's necessary fetchService on load time of the method below . How can I call the window.onload = fetchService ; or all function ( ) in he main.js 's below.. please help ? <code> < script src= '' /c/Currency.js '' type= '' text/javascript '' > < /script > < form id= '' form1 '' runat= '' server '' > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' EnablePageMethods= '' true '' > < /asp : ScriptManager > < div id= '' Content '' > < div class= '' nobg '' > < div id= '' Top '' > < div class= '' left '' > < a href= '' index.html '' > < img src= '' /i/xyz.gif '' alt= '' Dexia '' / > < /a > < /div > < div class= '' right '' > < div id= '' tmenu '' > < ul > < li class= '' aboutus '' > < a href= '' /aboutus/ '' > < img src= '' /i/menu/about_us.gif '' alt= '' About Us '' > < /a > < /li > < li class= '' presscenter '' > < a href= '' /press_center/ '' > < img src= '' /i/menu/press_center.gif '' alt= '' Press Center '' > < /a > < /li > < li class= '' financials '' > < a href= '' /financials/ '' > < img src= '' /i/menu/financials.gif '' alt= '' Financials '' > < /a > < /li > < li class= '' xysza '' > < a href= '' /work_xyz/ '' > < img src= '' /i/menu/xyz.gif '' alt= '' Work & xyz '' > < /a > < /li > < li class= '' sitemap '' > < a href= '' /site_map/ '' > < img src= '' /i/menu/site_map.gif '' alt= '' Site Map '' > < /a > < /li > < li class= '' ruski '' > < a href= '' /russian/ '' > < img src= '' /i/menu/try.gif '' alt= '' rt '' > < /a > < /li > < li class= '' search '' > < a href= '' /search/ '' > < img src= '' /i/menu/search.gif '' alt= '' Search '' > < /a > < /li > < li class= '' mainpage '' > < a href= '' /index.html '' > < img src= '' /i/menu/main_page.gif '' alt= '' Main Page '' > < /a > < /li > < /ul > < /div > < div id= '' tm '' > < /div > < /div > < div id= '' tms '' > < /div > < script type= '' text/javascript '' > var activepage = 0 < /script > < script src= '' /c/inc/menu.js '' type= '' text/javascript '' > < /script > < span id= '' txt_submenu '' > < /span > < script src= '' /c/inc/submenu.js '' type= '' text/javascript '' > < /script > < /div > < div id= '' Middle '' > function CallMe ( ) { // call server side method PageMethods.GetData ( function ( result ) { DcSet ( `` lblUsdRub '' , result.UsdRub ) ; DcSet ( `` lblEurRub '' , result.EurRub ) ; DcSet ( `` lblMicex '' , result.Micex ) ; DcSet ( `` lblUrals '' , result.Urals ) ; DcSet ( `` lblUsdEur '' , result.UsdEur ) ; DcSet ( `` lblUsdTur '' , result.UsdTur ) ; DcSet ( `` lblNasdaq '' , result.Nasdaq ) ; DcSet ( `` lblImkb100 '' , result.Imkb100 ) ; } ) ; } function DcSet ( labelName , value ) { document.getElementById ( labelName ) .innerText = value.toFixed ( 3 ) ; } ( function ( ) { var status = true ; var fetchService = function ( ) { if ( status ) { CallMe ( ) ; status = false ; } setTimeout ( fetchService , 300000 ) ; //Every Five Minutes , Update Data status = true ; } window.onload = fetchService ; } ( ) ) ; window.onload = function ( ) { preload ( ) ; init ( ) ; externalLinks ( ) ; topmenu.Build ( ) ; if ( typeof sIFR == `` function '' ) { sIFR.replaceElement ( named ( { sSelector : `` h1 '' , sFlashSrc : `` /swf/Futura_Bk_BT.swf '' , sWmode : `` transparent '' , sColor : `` # 027DA2 '' , sLinkColor : `` # FFFFFF '' , sHoverColor : `` # FFFFFF '' , sFlashVars : `` '' } ) ) ; } initHDS ( ) ; SubMenuKaydir ( ) ; StartCurrencyOnLoad ( ) ; } | Covered from html to aspx page , but the menus disappeared , why ? |
C_sharp : C # does n't allow lambda functions to represent iterator blocks ( e.g. , no `` yield return '' allowed inside a lambda function ) . If I wanted to create a lazy enumerable that yielded all the drives at the time of enumeration for example , I 'd like to do something likeIt took a while , but I figured out this as a way to get that functionality : Is there a more idiomatic way ? <code> IEnumerable < DriveInfo > drives = { foreach ( var drive in DriveInfo.GetDrives ( ) ) yield return drive ; } ; var drives = Enumerable.Range ( 0 , 1 ) .SelectMany ( _ = > DriveInfo.GetDrives ( ) ) ; | How to create an IEnumerable to get all X lazily in a single statement |
C_sharp : In this piece of codeWhy does my Javascript recognize Model.IntegerParameter correctly but Model.StringParameter as null ? I am sure it has data on it as I check the response and it shows like thisMy View model is really simple and it looks like thisHow do I fix this ? Added InfoI tried changing the second parameter to int , now its not passing as null but 0 and still it shows in the response in FireBug.I added the Html.Raw , but it still gets a null value in Javascript.Here is a real world screenshot of what I get in the console response : -- -- -- -- -- -- -- -Another Update -- -- -- -- -- -- -- -- -- I tried all the suggestions , but it seems to be a BUG in MVC s # arp ? I tried in different projects and on different PC 's it still happens for me . I noticed this only happens if its coming from a Model it looks like what happens in between the response to Javascript the value of string gets lost regardless whether its the first , second or any position in the parameter but if I use a hard coded value , such as : I get a successful result , also if I use jQuery like such : This also works but if I do pass a Model that is a string like suchThis does not work.So is you want to see what really happens on real world where I taken account the suggestions of @ Darin and @ Shark . Here is a screenshot : As you see in the response , it is there but when passed to Javascript , it gets lost . Here is the real life Javascript as well <code> @ using ( Ajax.BeginForm ( `` MyAction '' , `` MyRouteValues '' , new AjaxOptions { OnSuccess = `` myJSFunction ( `` + Model.IntegerParameter + `` , ' '' + Model.StringParameter + `` ' ) '' } ) ) data-ajax-success= '' myJSFunction ( 111111 , & # 39 ; AAAAAA & # 39 ; ) '' public class MyViewModel { public int IntegerParameter { get ; set ; } public string StringParameter { get ; set ; } } myJSFunction ( `` + Model.IntegerParameter + `` , 'AAAAAAAA ' ) '' myJSFunction ( `` + Model.IntegerParameter + `` , $ ( ' # SearchString ' ) .val ( ) ) '' myJSFunction ( `` + Model.IntegerParameter + `` , ' '' + Model.StringParameter + `` ' ) '' displayResultsPopUpWindow : function ( model ) { var postData = { transactionId : model.transactionId , searchString : model.searchString } ; $ .post ( `` /Invoicing/GetSearchResults '' , postData , function ( data ) { WindowHelper.displayWindow ( `` Add Airline Transaction '' , `` < div id='matchBookingResults ' > '' + unescape ( data.viewHtml ) + `` < /div > '' , 640 , 500 ) ; } ) ; } , | String Parameter in AjaxOption null on Submit but showing in Response |
C_sharp : I am running a search algorithm which is fed at the start with a single seed . From this point on I expect the algorithm to behave in a deterministic fashion , which it largely does . I can largely verify this by looking at the 10,000th step , 20,000 step and seeing they are identical . What I am seeing different though is the length of thread processor time used to get to the same place ( having taken identical paths ) . I am measuring the thread time withProcessThread.TotalProcessorTime.To quantify this I have done some tests for you . I varied the run time and measured the number of solutions evaluated within this timeI repeated the test 8 times for each . The bottom two rows show the Average solutions evaluated over a 30 second period followed by the Standard Deviation . I repeated the 120s test as the standard deviation was so high the first time and much lower the second time.If my algorithm is doing the same work then what could cause the same work to take different amounts of time ? What random element is being introduced ? To clarify a few points : I am talking about Thread Processor time and not Clock timeThe algorithm runs on a single thread with no explicit interactions with other threadsThis environment is Windows XP .Net C # Dual processorIt is a console applicationThe algorithm uses the processor and memory , only after it has finished will it print the result to screen . Best Regards <code> 30s 60s 120s 120s473,962 948,800 1,890,668 1,961,532477,287 954,335 1,888,955 1,936,974473,441 953,049 1,895,727 1,960,875475,606 953,576 1,905,271 1,941,511473,283 951,390 1,946,729 1,949,231474,846 954,307 1,840,893 1,939,160475,052 952,949 1,848,938 1,934,243476,797 957,179 1,945,426 1,951,542475,034 476,599 473,831 486,721 1,478 2,426 23,922 11,108 | Why might my C # computation time be non-deterministic ? |
C_sharp : So the question is in the header.What NHibernate users can do : How to mimic such behavior in EF 4 ? <code> var q1 = Source.Companies.ToFuture ( ) ; var q2 = Source.Items.ToFuture ( ) ; var q3 = Source.Users.ToFuture ( ) ; var compoundModel = new CompoundModel ( q1 , q2 , q3 ) ; // All data obtained in single database roundtrip // When the first to future statement is touched | Does an analog of the NHibernate.ToFuture ( ) extension method exist in the Entity Framework ? |
C_sharp : I want to display the icons associated with files . This is n't a problem for file types associated with normal desktop applications but only for those associated with ( metro/modern ) apps.If a file type is associated with an app and I am using AsParallel ( ) , I get only the default unknown file type icon . To clarify , I do n't get null or an empty icon , but the default icon that shows an empty paper sheet . Without AsParallel ( ) I get the correct icon.I tried several other ways to get the icon , e.g. , SHGetFileInfo ( ) or calling ExtractAssociatedIcon ( ) directly via the dll . The behavior was always the same.Example : If 'Adobe Acrobat ' is the default application for PDF files , I get the correct Adobe PDF icon in both cases . If the built-in ( modern UI ) app 'Reader ' from Windows 8 or 10 is the default app , I get the unknown file type icon when AsParallel ( ) is applied.MCVEXAML : Corresponding code : Usage note : Use only one of the two variants . If both are executed , even with different variables , the problem may not be reproducible . <code> < Window x : Class= '' FileIconTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < StackPanel > < TextBox x : Name= '' TxtFilename '' Text= '' x : \somefile.pdf '' / > < Button Click= '' Button_Click '' > Go < /Button > < Image x : Name= '' TheIcon '' Stretch= '' None '' / > < /StackPanel > < /Window > private void Button_Click ( object sender , RoutedEventArgs e ) { var list = new List < string > ( ) ; list.Add ( TxtFilename.Text ) ; var icons = list.AsParallel ( ) .Select ( GetIcon ) ; // problem with apps// var icons = list.Select ( GetIcon ) ; // works always TheIcon.Source = icons.First ( ) ; } public static ImageSource GetIcon ( string filename ) { var icon = System.Drawing.Icon.ExtractAssociatedIcon ( filename ) ; var iSource = Imaging.CreateBitmapSourceFromHIcon ( icon.Handle , Int32Rect.Empty , BitmapSizeOptions.FromEmptyOptions ( ) ) ; iSource.Freeze ( ) ; return iSource ; } | Ca n't get file icon for files associated with Windows apps when using AsParallel ( ) |
C_sharp : Suppose we have created Entities model , what is preferred way to work with it ? I 'm personally could n't make up my mind..Using ModelAdapter : looks neat ; but , context is created/released a lot sometimes , objects lose contact with context ; Using context in place : effectivebut , code becomes messyMixed mode , compromise ? Extension methods : Actually now , I 'm trying approach # 4 , implementing utility methods as extensions to context . So I can use one context , and make many calls to this context . <code> public statiс Product [ ] GetProducts ( ) { using ( Entities ctx = new Entities ( ) ) { return ctx.Product.ToArray ( ) ; } } Product [ ] ps = ModelAdapter.GetProducts ( ) ; // ... ModelAdapter.UpdateProduct ( p ) ; using ( Entities ctx = new Entities ( ) ) { Product [ ] ps = ctx.Product.ToArray ( ) ; // ... ctx.SaveChanges ( ) ; } using ( Entities ctx = new Entities ( ) ) { Product [ ] ps = ctx.GetProducts ( ) ; // ... ctx.UpdateProduct ( p ) ; } | Working with entity framework , preferred way ? |
C_sharp : If I have a class SubOfParent which is a sub-class of Parent , and two methods : why does the first doStuff get called when I pass a SubOfParent type object ? Thanks for any insight on this ! <code> public static void doStuff ( Parent in ) { } public static void doStuff ( SubOfPArent in ) { } | basic question on method overloading |
C_sharp : I want to test GetParameters ( ) to assert the returned value includes `` test= '' within the value . Unfortunately the method responsible for this is private . Is there a way I can provide test coverage for this ? The problem I have is highlighted below : The problem is that info.TagGroups equals null in my testThanks , TestImplementation class to test <code> if ( info.TagGroups ! = null ) [ Test ] public void TestGetParameters ( ) { var sb = new StringBuilder ( ) ; _renderer.GetParameters ( sb ) ; var res = sb.ToString ( ) ; Assert.IsTrue ( res.IndexOf ( `` test= '' ) > -1 , `` blabla '' ) ; } internal void GetParameters ( StringBuilder sb ) { if ( _dPos.ArticleInfo ! = null ) { var info = _dPos.ArticleInfo ; AppendTag ( sb , info ) ; } } private static void AppendTag ( StringBuilder sb , ArticleInfo info ) { if ( info.TagGroups ! = null ) // PROBLEM - TagGroups in test equals null { foreach ( var tGroups in info.TagGroups ) { foreach ( var id in tGroups.ArticleTagIds ) { sb.AppendFormat ( `` test= { 0 } ; '' , id ) ; } } } } | unit testing c # and issue with testing a private method |
C_sharp : I wanted to make an array awaitable by implementing an extension methodbut even though IntelliSense says `` ( awaitable ) mytype [ ] '' , the compiler gives me an error when usingCalling await on a single object of mytype works fine . Why is that ? Am I doing something wrong ? Thanks for your help . <code> public static IAwaitable GetAwaiter ( this mytype [ ] t ) { return t.First ( ) .GetAwaiter ( ) ; } mytype [ ] t = new mytype [ ] { new mytype ( ) , new mytype ( ) } ; await t ; | await array ; by implementing extension method for array |
C_sharp : I 'm looking for the fastest way to find all strings in a collection starting from a set of characters . I can use sorted collection for this , however I ca n't find convenient way to do this in .net . Basically I need to find low and high indexes in a collection that meet the criteria.BinarySearch on List < T > does not guarantee the returned index is that of the 1st element , so one would need to iterate up and down to find all matching strings which is not fast if one has a large list.There are also Linq methods ( with parallel ) , but I 'm not sure which data structure will provide the best results.List example , ~10M of records : Search for strings starting from : skk ... Result : record indexes from x to y.UPDATE : strings can have different lengths and are unique . <code> aaaaaaaaaaaaaaabbaaaaaaaaaaaaaabaaaaaaaaaaaaaabc ... zzzzzzzzzzzzzxxzzzzzzzzzzzzzyzzzzzzzzzzzzzzzzzzzzza | Fastest way to select all strings from list starting from |
C_sharp : I 've got a ResourceDictionary in a xaml file that represents a skin in a folder on my hard drive in some random folder . Say D : \Temp2\BlackSkin.xaml.I 've set the permissions correctly to give full access so that 's not the issue.This ResourceDictionary BlackSkin.xaml references a BaseSkin.xaml like so : So I 'm loading this BlackSkin.xaml using XamlReader.Load ( ... ) It works fine if I put : Which is of course a hard-coded path . I would like to provide a relative path , not relative to the current application that is running , but a relative path to the current skin being loaded ( BlackSkin.xaml ) ... aka `` D : \Temp2\BaseSkin.xaml '' ... or ... if you will just `` BaseSkin.xaml '' since they are located in the same folder , which again is not the same folder as the application.Do I need to define a Custom Markup Extension to do this ? And if so , where would I put this in my project ? Just make a folder called `` Extensions '' and create some random .cs file and implement it there ? Would such a Custom Markup Extension get called when calling XamlReader.Load ( ... ) ? Then I would need to tie this Custom Markup Extension into the program to get a fully qualified path from some setting or config file in my application and return the path as part of the ProvideValue function ? Are there any other ways of doing this ? Such as where I call XamlReader.Load ( fileStream ) like so : And perhaps just remove the BaseSkin.xaml lookup in the BlackSkin.xaml ... that is to say remove this block of code from the BaseSkin.xaml ? But then the question becomes what if I have other resources that I want to load in the BlackSkin.xaml , like images or anything else ? So I guess the above really only works for a generic single-use situation like this , but what I 'm really after is a generic solution that can work for chaining all kinds of different resources into a ResourceDictionary that is an external file located at a random folder on the disk , and resources that may or may-not be co-located with the originating xaml resource Dictionary file.Which brings me back to the Custom Markup Extensions question.EDIT : Well I did try to create a custom markup extension , but it throws a XamlParseException , I think because it does n't know what the clr-namespace is , again because it 's not in any assembly or anything of that nature that can be related back to the running program.So here is the Xaml that I have now , maybe I got it completely wrong , or maybe I 'm going completely down the wrong path ... ? And this is what I have for the custom extension , just trying to see if I can make it work with a hard-coded path for now in the custom extension . Did I misunderstand something ? I 'm going off from this example : http : //tech.pro/tutorial/883/wpf-tutorial-fun-with-markup-extensions <code> < ResourceDictionary xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' { D : \Temp2\BaseSkin.xaml '' > < /ResourceDictionary.MergedDictionaries > Source= '' D : \Temp2\BaseSkin.xaml '' / > public void ApplySkin ( string fileName , string baseSkinFileName ) { if ( File.Exists ( baseSkinFileName ) ) { ResourceDictionary baseSkinDictionary = null ; using ( FileStream baseSkinStream = new FileStream ( baseSkinFileName , FileMode.Open ) ) { //Read in the BaseSkin ResourceDictionary File so we can merge them manually ! baseSkinDictionary = ( ResourceDictionary ) XamlReader.Load ( baseSkinStream ) ; baseSkinStream.Close ( ) ; } using ( FileStream fileStream = new FileStream ( fileName , FileMode.Open ) ) { // Read in ResourceDictionary File ResourceDictionary skinDictionary = ( ResourceDictionary ) XamlReader.Load ( fileStream ) ; skinDictionary.MergedDictionaries.Add ( baseSkinDictionary ) ; // Clear any previous dictionaries loaded Resources.MergedDictionaries.Clear ( ) ; // Add in newly loaded Resource Dictionary Resources.MergedDictionaries.Add ( skinDictionary ) ; fileStream.Close ( ) ; } < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' { StaticResource baseSkin } '' / > < ! -- D : \Temp2\BaseSkin.xaml '' / -- > < /ResourceDictionary.MergedDictionaries > < ResourceDictionaryxmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : base= '' clr-namespace : TimersXP.Extensions '' > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' { base : BaseSkinPath } '' / > < ! -- D : \Temp2\BaseSkin.xaml '' / -- > < /ResourceDictionary.MergedDictionaries > using System ; using System.Windows.Markup ; namespace TimersXP.Extensions { class BaseSkin : MarkupExtension { /// < summary > Gets the base skin file path. < /summary > /// < value > The base skin. < /value > public string BaseSkinPath { get { return `` D : \\Temp2\\BaseSkin.xaml '' ; } } public override object ProvideValue ( IServiceProvider serviceProvider ) { return `` D : \\Temp2\\BaseSkin.xaml '' ; } } } | How can I chain Resource Dictionaries that are externally loaded from disk , not included in project or assembly ? |
C_sharp : ( This used to be a 2-part question , but since the second part is literally the important one , I decided to split this into two separate posts . See Using Serialization to copy entities between two ObjectContexts in Entity Framework for the second part.I want to create a fairly generic `` cloner '' of databases for my entity model . Also , I might need to support different providers and such . I 'm using ObjectContext API.I am aware of this question already and the EntityConnectionStringBuilder MDSN documentation example , but I need to know if there is a programmatic way to obtain the values to initialize the Provider and Metadata properties of an EntityConnectionStringBuilder ? That is , is there a way to fetch the '' System.Data.SqlClient '' '' res : //*/EntityModel.csdl|res : //*/EntityModel.ssdl|res : //*/EntityModel.msl '' from somewhere and not use literal values ? <code> using ( var sourceContext = new EntityContext ( ) ) { var sourceConnection = ( EntityConnection ) sourceContext.Connection ; var targetConnectionBuilder = new EntityConnectionStringBuilder ( ) ; targetConnectionBuilder.ProviderConnectionString = GetTargetConnectionString ( ) ; targetConnectionBuilder.Provider = `` System.Data.SqlClient '' ; // want code targetConnectionBuilder.Metadata = `` res : //*/EntityModel.csdl|res : //*/EntityModel.ssdl|res : //*/EntityModel.msl '' ; // want code using ( var targetContext = new EntityContext ( targetConnectionBuilder.ConnectionString ) ) { if ( ! targetContext.DatabaseExists ( ) ) targetContext.CreateDatabase ( ) ; // how to copy all data from the source DB to the target DB ? ? ? } } | `` Cloning '' EntityConnections and ObjectContexts in Entity Framework |
C_sharp : Silly question , but why does the following line compile ? As you can see , I have n't entered in the second element and left a comma there . Still compiles even though you would expect it not to . <code> int [ ] i = new int [ ] { 1 , } ; | Why is this c # snippet legal ? |
C_sharp : In the following code , I would have expected calling a.Generate ( v ) would have resulted in calling V.Visit ( A a ) , since when Generate is called this is of type A. Hoewever , it appears that this is seen as being an Inter instead . Is it possible to have the intended behaviour without explicitly implementing the ( identical ) method in both A and B and only on the shared base class ? If so , how can it be acheived ? EditIt was suggested in the answers that the code above is not polymorphic . I would object to that . V.Visit is polymorphic . <code> using System ; using System.Diagnostics ; namespace Test { class Base { } class Inter : Base { public virtual void Generate ( V v ) { // ` Visit ( Base b ) ` and not ` Visit ( A a ) ` is called when calling // A.Generate ( v ) . Why ? v.Visit ( this ) ; } } class A : Inter { } class B : Inter { } class V { public void Visit ( Base b ) { throw new NotSupportedException ( ) ; } public void Visit ( A a ) { Trace.WriteLine ( `` a '' ) ; } public void Visit ( B b ) { Trace.WriteLine ( `` b '' ) ; } } class Program { static void Main ( ) { V v = new V ( ) ; A a = new A ( ) ; B b = new B ( ) ; a.Generate ( v ) ; b.Generate ( v ) ; } } } | How does polymorphism work with undefined intermediate types in C # ? |
C_sharp : I 've tried looking for an answer but could n't find it . The 'issue ' is simple : If I have a collection of items using linq as follows : And another collection of items using linq but without a ToList ( ) : If now I try to iterate each item with a foreach ( I did n't try while or other kind of iteration methods ) : If I stop the code at the breakpoint and I try to update the AnyTable on SQL Management Studio everything is OK . BUT IF ! : If now I try to update ( while on the breakpoint ) the AnyTable on SQL Management Studio I wo n't be able to do it ( TimeOut ) .Why is the ToList ( ) making such a difference ? From what I 've learnt a particular difference is WHEN the query is being executed ( on items it is executed at the declaration and on items2 it is executed on the foreach statement ) . Why is that preventing me to update the AnyTable ? <code> var items = db.AnyTable.Where ( x = > x.Condition == condition ) .ToList ( ) ; var items2 = db.AnyTable.Where ( x = > x.Condition == condition ) ; foreach ( var item in items ) { int i = 2 ; // Does n't matter , The important part is to put a breakpoint here . } foreach ( var item in items2 ) { int i = 2 ; // Does n't matter , The important part is to put a breakpoint here . } | Database is locked when inside a foreach with linq without ToList ( ) |
C_sharp : In a current benchmark about mongodb drivers , we have noticed a huge difference in performance between python and .Net ( core or framework ) .And the a part of the difference can be explained by this in my opinion.We obtained the following results : We took a look to the memory allocation in C # and we noticed a ping pong between download phases of a BsonChunck and deserialization . ( Normal as it 's by batch . ) But the download phases were very long . So we took a look to the network trace of the different queries as mongo use TCP/IP : For the config file , the result is stunning only with the following one : The latency for one object is impressive : 0.03 ms for python and 24.82 for csharp.Do you have some insights about this difference ? Do you know a way to reach the same performance in C # than in Python ? Thank you in advance : - ) To do the benchmark , we are using these two codes : Python ( pymongo driver ) : And for .Net ( MongoDB.Driver ) : OLD METRICS : Before removing the connection pull from the benchmark loop . <code> ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━━━┫┃ Ratio Duration/Document ┃ 24.82 ┃ 0.03 ┃ 0.001 ┃┃ Duration ( ms ) ┃ 49 638 ┃ 20 016 ┃ 0.40 ┃┃ Count ┃ 2000 ┃ 671 972 ┃ 336 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━━━┛ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━┫┃ Packets/sec to db ┃ 30 ┃ 160 ┃ 5.3 ┃┃ Packets/sec from DB ┃ 120 - 150 ┃ 750 - 1050 ┃ ~6.5 ┃┃ Packet count to db ┃ 1560 ┃ 2870 ┃ 1.84 ┃┃ Packet count from db ┃ 7935 ┃ 13663 ┃ 1.7 ┃┃ Packet average length to db ┃ 73.6 ┃ 57.6 ┃ 0.74 ┃┃ Packet average length from db ┃ 1494 ┃ 1513 ┃ 1.01 ┃┃ Max TCP Errors/sec ┃ 20 ┃ 170 ┃ 8.5 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━┛ { `` connectionString '' : `` mongodb : //ip.of.the.mongo:27018 '' , `` dbname '' : `` mydb '' , `` colname '' : `` mycollection '' , `` query '' : { } , `` projection '' : { } , `` limit '' : 2000 , `` batchsize '' : 10 } # ! /usr/bin/env python3import pymongoimport timeimport jsonimport osqueries_dir = `` ../queries '' results_dir = `` ../results '' for subdir , dirs , files in os.walk ( queries_dir ) : for f in files : filepath = subdir + os.sep + f print ( filepath ) conf = json.load ( open ( filepath ) ) conf [ `` language '' ] = `` python '' client = pymongo.MongoClient ( conf [ `` connectionString '' ] ) db = client [ conf [ `` dbname '' ] ] col = db [ conf [ `` colname '' ] ] initConnection = col.find ( { } , { } ) .limit ( 1 ) for element in initConnection : print ( element ) input ( `` Press enter to continue . '' ) res = col.find ( conf [ `` query '' ] , conf [ `` projection '' ] ) returned = 0 start = time.time ( ) for i in res : returned += 1 duration = ( time.time ( ) - start ) * 1000 conf [ `` duration '' ] = duration conf [ `` returned '' ] = returned conf [ `` duration_per_returned '' ] = float ( duration ) / float ( returned ) d = time.strftime ( `` % Y- % m- % d_ % H- % M- % S '' ) fr = open ( results_dir + os.sep + d + `` _ '' + conf [ `` language '' ] + `` _ '' + f , '' w '' ) json.dump ( conf , fr , indent=4 , sort_keys=True ) fr.close ( ) print ( json.dumps ( conf , indent=4 , sort_keys=True ) ) class Program { static void Main ( string [ ] args ) { var dir = Directory.GetCurrentDirectory ( ) ; var queryDirectory = dir.Replace ( @ '' csharp\benchmark\benchmark\bin\Debug\netcoreapp2.2 '' , string.Empty ) + `` queries '' ; var resultDirectory = dir.Replace ( @ '' csharp\benchmark\benchmark\bin\Debug\netcoreapp2.2 '' , string.Empty ) + `` results '' ; var configurationFiles = Directory.GetFiles ( queryDirectory ) ; foreach ( var file in configurationFiles ) { var configuration = JsonConvert.DeserializeObject < BenchmarkConfiguration > ( File.ReadAllText ( file ) ) ; var collection = new MongoClient ( configuration.ConnectionString ) .GetDatabase ( configuration.Database ) .GetCollection < BsonDocument > ( configuration.Collection ) ; var filters = BsonDocument.Parse ( ( string ) ( configuration.Query.ToString ( ) ) ) ; var projection = BsonDocument.Parse ( ( string ) ( configuration.Projection.ToString ( ) ) ) ; var query = collection.Find ( filters , new FindOptions { BatchSize = configuration.BatchSize } ) .Project ( projection ) .Limit ( configuration.Limit ) ; var initconnection = collection.Find ( new BsonDocument { } ) .Limit ( 1 ) .FirstOrDefault ( ) ; Console.WriteLine ( initconnection.ToString ( ) ) ; Console.WriteLine ( `` Press Enter to continue . `` ) ; Console.ReadLine ( ) ; var watch = new Stopwatch ( ) ; watch.Start ( ) ; var results = query.ToList ( ) ; watch.Stop ( ) ; var time = watch.ElapsedMilliseconds ; var now = DateTime.Now.ToString ( `` yyyy-MM-dd_hh-mm-ss '' ) ; var report = new BenchmarkResult ( configuration , time , results.Count ( ) ) ; File.WriteAllText ( $ '' { resultDirectory } / { now } _csharp_ { Path.GetFileName ( file ) } '' , JsonConvert.SerializeObject ( report , Formatting.Indented ) ) ; } } } ┏━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━━━┫┃ Ratio Duration/Document ┃ 26.07 ┃ 0.06 ┃ 0.002 ┃┃ Duration ( ms ) ┃ 52 145.0 ┃ 41 981 ┃ 0.80 ┃┃ Count ┃ 2000 ┃ 671 972 ┃ 336 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━━━┛┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━┓┃ Metric ┃ Csharp ┃ Python ┃ ratio p/c ┃┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━┫┃ Packets/sec to db ┃ 30 ┃ 150 ┃ 5 ┃┃ Packets/sec from DB ┃ 120 - 180 ┃ 750 - 1050 ┃ ~6 ┃┃ Packet count to db ┃ 1540 ┃ 2815 ┃ 1.8 ┃┃ Packet count from db ┃ 7946 ┃ 13700 ┃ 1.7 ┃┃ Packet average length to db ┃ 74 ┃ 59 ┃ 0.80 ┃┃ Packet average length from db ┃ 1493 ┃ 1512 ┃ 1 ┃┃ Max TCP Errors/sec ┃ 10 ┃ 320 ┃ 32 ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━┛ | How to reach the same performance with the C # mongo driver than PyMongo in python ? |
C_sharp : As I understand , generics is an elegant solution to resolve issues with extra boxing/unboxing procedures which occur within generic collections like List . But I can not understand how generics can fix problems with using interfaces within a generic function . In other words , if I want to pass a value instance which implements an interface of a generic method , will boxing be performed ? How does the compiler treat such cases ? As I understand , in order to use the interface method the value instance should be boxed , because a call of a `` virtual '' function requires `` private '' information contained within the reference object ( it 's contained within all reference objects ( it also has a synch block ) ) That 's why I decided to analyze the IL code of a simple program to see if any boxing operations are used within the generic function : I thought that add ( new MyInt ( 1 ) , new MyInt ( 2 ) ) will use boxing operations because the add generic method uses the INum < a > interface ( otherwise how can compiler emit virtual method call of value instance without boxing ? ? ) . But I was very surprised . Here is a piece of IL code of Main : Such listing does not have box instructions . It seems like newobj does not create a value instance on heap , for values it creates them on stack . Here is a description from documentation : ( ECMA-335 standard ( Common Language Infrastructure ) III.4.21 ) Value types are not usually created using newobj . They are usually allocated either as arguments or local variables , using newarr ( for zero-based , one-dimensional arrays ) , or as fields of objects . Once allocated , they are initialized using initobj . However , the newobj instruction can be used to create a new instance of a value type on the stack , that can then be passed as an argument , stored in a local , etc.So , I decided to check out the add function . It 's very interesting , because it does not containt box instructions either : What 's wrong with my assumptions ? Can generics invoke virtual methods of values without boxing ? <code> public class main_class { public interface INum < a > { a add ( a other ) ; } public struct MyInt : INum < MyInt > { public MyInt ( int _my_int ) { Num = _my_int ; } public MyInt add ( MyInt other ) = > new MyInt ( Num + other.Num ) ; public int Num { get ; } } public static a add < a > ( a lhs , a rhs ) where a : INum < a > = > lhs.add ( rhs ) ; public static void Main ( ) { Console.WriteLine ( add ( new MyInt ( 1 ) , new MyInt ( 2 ) ) .Num ) ; } } IL_0000 : ldc.i4.1IL_0001 : newobj instance void main_class/MyInt : :.ctor ( int32 ) IL_0006 : ldc.i4.2IL_0007 : newobj instance void main_class/MyInt : :.ctor ( int32 ) IL_000c : call ! ! 0 main_class : :'add ' < valuetype main_class/MyInt > ( ! ! 0 , ! ! 0 ) IL_0011 : stloc.0 .method public hidebysig static ! ! a 'add ' < ( class main_class/INum ` 1 < ! ! a > ) a > ( ! ! a lhs , ! ! a rhs ) cil managed { // Method begins at RVA 0x2050 // Code size 15 ( 0xf ) .maxstack 8 IL_0000 : ldarga.s lhs IL_0002 : ldarg.1 IL_0003 : constrained . ! ! a IL_0009 : callvirt instance ! 0 class main_class/INum ` 1 < ! ! a > : :'add ' ( ! 0 ) IL_000e : ret } // end of method main_class : :'add ' | Generics and usage of interfaces without boxing of value instances |
C_sharp : I 'm developing a wp7 game where the player draws lines in the program and a ball bounces off of them . I 'm using XNA and farseer physics . What is the best method for a user to draw a line , and then for the program to take it and turn it in to a physics object , or at least a list of vector2s ? I 've tried creating a list of TouchLocations , but it ends up spotty if the user does not draw very slow , like the picture I 've attached . Any suggestions ? Thankshttp : //img829.imageshack.us/img829/3985/capturehbn.pngHere 's some code : I 'm using the gamestatemanagement sample , and this is in the HandleInput methodThe pathManager class manages a collection of path classes , which are drawable physics objects . Here is pathManager.UpdateThis is just what I 'm doing now and I 'm willing to throw it out for anything . You 'd think that having a 5x5 rectangle for each touch location would kill the performance , but using farseer I did n't see any drops , even with a mostly full screen . However , this system does n't create a smooth line at all if the line is drawn fast.I doubt this helps any , but here is the Path constructor . <code> foreach ( TouchLocation t in input.TouchState ) { pathManager.Update ( gameTime , t.Position ) ; } public void Update ( GameTime gameTime , Vector2 touchPosition ) { paths.Add ( new Path ( world , texture , new Vector2 ( 5,5 ) ,0.1f ) ) ; paths [ paths.Count-1 ] .Position = touchPosition ; } public Path ( World world , Texture2D texture , Vector2 size , float mass ) { this.Size = size ; this.texture = texture ; body = BodyFactory.CreateRectangle ( world , size.X * pixelToUnit , size.Y * pixelToUnit , 1 ) ; body.BodyType = BodyType.Static ; body.Restitution = 1f ; body.Friction = 0 ; body.Friction = 10 ; } | What is the best method in XNA to have the player paint smoothly on the screen ? |
C_sharp : I have a factory class and CreateInstance methodThe factory can instantiate two differents subtypes depending on the value of tipoParametroEntita.TipoCampo.IdTipoCampo The point is the second argument of CreateInstance ( parametroEntitaMultiValoreDataSourceProvider ) is used only for creating instance of TipoEntitaTipoParametroEntitaMultiValorewhereas is not used in creating instance of TipoEntitaTipoParametroEntitaSingoloValoreI 'm doubtful about this adopted pattern as I always need to pass an instance of IParametroEntitaMultiValoreDataSourceProvider even when it is not necessary and moreover someone reading the signature of the method might be led to think that for creating any type of TipoEntitaTipoParametroEntita an instance of IParametroEntitaMultiValoreDataSourceProvider is required.What would be a better approach ? Two distinct factories ? Only one factory and two CreateInstance ( one returning TipoEntitaTipoParametroEntitaSingoloValore and the other TipoEntitaTipoParametroEntitaMultiValore ) ? I both of the cases I should already know which factory or which CreateInstance to call so I should check tipoParametroEntita.TipoCampo.IdTipoCampo every time in advance . But I 'd like to keep this logic only in one place . <code> CreateInstance ( EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita , IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider ) public class TipoEntitaTipoParametroEntitaFactory : ITipoEntitaTipoParametroEntitaFactory { /// < summary > /// Creates an instance of TipoEntitaTipoParametroEntitaSingoloValore or TipoEntitaTipoParametroEntitaMultiValore /// < /summary > public TipoEntitaTipoParametroEntita CreateInstance ( EntityModel.TipoEntitaTipoParametroEntita tipoParametroEntita , IParametroEntitaMultiValoreDataSourceProvider parametroEntitaMultiValoreDataSourceProvider ) { if ( tipoParametroEntita.TipoCampo.IdTipoCampo == ( int ) EntityModel.Enum.TipoCampo.CampoLibero || tipoParametroEntita.TipoCampo.IdTipoCampo == ( int ) EntityModel.Enum.TipoCampo.CampoLiberoMultiLinea ) { return new TipoEntitaTipoParametroEntitaSingoloValore ( tipoParametroEntita ) ; } if ( tipoParametroEntita.TipoCampo.IdTipoCampo == ( int ) EntityModel.Enum.TipoCampo.DropdownListQueryDataSource || tipoParametroEntita.TipoCampo.IdTipoCampo == ( int ) EntityModel.Enum.TipoCampo.DropdownListTableDataSource ) { return new TipoEntitaTipoParametroEntitaMultiValore ( tipoParametroEntita , parametroEntitaMultiValoreDataSourceProvider ) ; } return null ; } } | Factory CreateInstance argument method not necessary for a specific subtype |
C_sharp : I 'm trying to write a method for coverting a given object to an instance of a given type . I started with this : Going in , I know that is n't going to work , but it illustrates the concept . Now , I 'm going to start having problems when I have types that wo n't cast automatically , like string -- > DateTime . I was trying to use the Convert Class to deal with these cases , but I just get a compile time error instead of a runtime error . The following code gets the compile error `` Can not cast expression of type 'string ' to type 'T ' I 'm also aware of Convert.ChangeType ( ) , but I 'm wondering if it will handle edge cases that I would otherwise handle in the above switch , like the stated string -- > DateTime that I 'd normally just use Convert.ToDateTime for.So , what is my best option ? If somebody can give me a workable approach , I can take it from there . <code> private static T TryCast < T > ( object o ) { return ( T ) o ; } private static T TryCast < T > ( object o ) { var typeName = typeof ( T ) .FullName ; switch ( typeName ) { case `` System.String '' : return ( T ) Convert.ToString ( o ) ; default : return ( T ) o ; } } private static T TryCast < T > ( object o ) { return ( T ) Convert.ChangeType ( o , typeof ( T ) ) ; } | C # Help me with some Generic casting awesomeness |
C_sharp : After seeing how double.Nan == double.NaN is always false in C # , I became curious how the equality was implemented under the hood . So I used Resharper to decompile the Double struct , and here is what I found : This seems to indicate the the struct Double declares a constant that is defined in terms of this special lower case double , though I 'd always thought that the two were completely synonymous . What 's more , if I Go To Implementation on the lowercase double , Resharper simply scrolls me to the declaration at the top of the file . Similarly , jumping to implementation of the lowercase 's NaN just takes me to the constant declaration earlier in the line ! So I 'm trying to understand this seemingly recursive definition . Is this just an artefact of the decompiler ? Perhaps a limitation in Resharper ? Or is this lowercase double actually a different beast altogether - representing something at a lower level from the CLR/CTS ? Where does NaN really come from ? <code> public struct Double : IComparable , IFormattable , IConvertible , IComparable < double > , IEquatable < double > { // stuff removed ... public const double NaN = double.NaN ; // more stuff removed ... } | When is a System.Double not a double ? |
C_sharp : I was going through some old code that was written in years past by another developer at my organization . Whilst trying to improve this code , I discovered that the query it uses had a very bad problem . The problem is that the column a.RRRAREQ_TRST_DESC does not exist . A fact you learn very quickly when running it in Oracle SQL Developer . The strange thing ? This code works . The gridview binds successfully . ( It does n't try to bind to that field . ) And it 's been in production for years . So , my question is ... why ? I 've never seen a bad query work . I 've never seen Oracle allow it or a data provider hack around it . Does anyone have any idea what 's going on here ? <code> OdbcDataAdapter financialAidDocsQuery = new OdbcDataAdapter ( @ '' SELECT a.RRRAREQ_TREQ_CODE , b.RTVTREQ_SHORT_DESC , a.RRRAREQ_TRST_DESC , RRRAREQ_STAT_DATE , RRRAREQ_EST_DATE , a.RRRAREQ_SAT_IND , a.RRRAREQ_SBGI_CODE , b.RTVTREQ_PERK_MPN_FLAG , b.RTVTREQ_PCKG_IND , a.RRRAREQ_MEMO_IND , a.RRRAREQ_TRK_LTR_IND , a.RRRAREQ_DISB_IND , a.RRRAREQ_FUND_CODE , a.RRRAREQ_SYS_IND FROM FAISMGR.RRRAREQ a , FAISMGR.RTVTREQ b WHERE a.RRRAREQ_TREQ_CODE = b.RTVTREQ_CODE and a.RRRAREQ_PIDM = : PIDM AND a.RRRAREQ_AIDY_CODE = : AidYear `` , this.bannerOracle ) ; financialAidDocsQuery.SelectCommand.Parameters.Add ( `` : PIDM '' , OdbcType.Int , 32 ) .Value = this.pidm ; financialAidDocsQuery.SelectCommand.Parameters.Add ( `` : AidYear '' , OdbcType.Int , 32 ) .Value = this.aidYear ; DataTable financialAidDocsResults = new DataTable ( ) ; financialAidDocsQuery.Fill ( financialAidDocsResults ) ; FADocsGridView.DataSource = financialAidDocsResults ; FADocsGridView.DataBind ( ) ; | The riddle of the working broken query |
C_sharp : What 's the best way to fix the below synchronization issue by enhancing OrderManager ? OrderForm needs to get the latest list of orders and trades and subscribe to those events while OrderManager generates order and trade by another thread.Should I remove event pattern and implement like this ? Any other better way ? <code> public class OrderManager { public event EventHandler < OrderEventArgs > OrderAdded ; public event EventHandler < OrderEventArgs > OrderUpdated ; public event EventHandler < OrderEventArgs > OrderDeleted ; public event EventHandler < TradeEventArgs > TradeAdded ; public List < Order > Orders { get ; private set ; } public List < Trade > Trades { get ; private set ; } ... } public class OrderForm { public OrderForm ( OrderManager manager ) { manager.OrderAdded += manager_OrderAdded ; manager.OrderUpdated += manager_OrderUpdated ; manager.OrderDeleted += manager_OrderDeleted ; manager.TradeAdded += manager_TradeAdded ; Populate ( manager.Orders ) ; Populate ( manager.Trades ) ; } ... } public class OrderListener { public Action < Order > OrderAdded { get ; set ; } public Action < Order > OrderUpdated { get ; set ; } public Action < Order > OrderDeleted { get ; set ; } public Action < Trade > TradeAdded { get ; set ; } } public class OrderManager { ... List < Order > orders ; List < Trade > trades ; List < OrderListener > listeners ; public IDisposable Subscribe ( OrderListener listener ) { lock ( orderTradeLock ) { listeners.Add ( listener ) ; orders.ForEach ( listener.OrderAdded ) ; trades.ForEach ( listener.TradeAdded ) ; // Allow caller to dispose the return object to unsubscribe . return Disposable.Create ( ( ) = > { lock ( orderTradeLock ) { listeners.Remove ( listener ) ; } } ) ; } } void OnOrderAdded ( Order order ) { lock ( orderTradeLock ) { orders.Add ( order ) ; listeners.ForEach ( x = > x.OrderAdded ( order ) ) ; } } void OnTradeAdded ( Trade trade ) { lock ( orderTradeLock ) { trades.Add ( trade ) ; listeners.ForEach ( x = > x.TradeAdded ( trade ) ) ; } } ... } public class OrderForm { IDisposable subscriptionToken ; public OrderForm ( OrderManager manager ) { subscriptionToken = manager.Subscribe ( new OrderListener { OrderAdded = manager_OrderAdded ; OrderUpdated = manager_OrderUpdated ; OrderDeleted = manager_OrderDeleted ; TradeAdded = manager_TradeAdded ; } } ... } | Synchronization issue in multiple event subscriptions and getting latest snapshot |
C_sharp : I had C/C++ background . I came across a strange way of exchanging two values in C # . In C # , the above two lines do swap values between n1 and n2 . This is a surprise to me as in C/C++ , the result should be n1=n2=20 . So , how does C # evaluate an expression ? It looks like the + above is treated as a function calling to me . The following explainion seems reasoable . BUT seems way weired to me.First ( n1=n2 ) is executed . And thus n1=20 . Then n1 in n1+ ( n1=n2 ) *0 is not 20 yet . It is treated as a function parameter , thus pushed on the stack and is still 10 . Therefore , n2=10+0=10 . <code> int n1 = 10 , n2=20 ; n2 = n1 + ( n1=n2 ) *0 ; | How does C # evaluate expressions which contain assignments ? |
C_sharp : I 'm writing a generic code that should handle situations when data is loaded from multiple sources . I have a method with following signature : But it 's an overkill : when I pass TResult , I already know what TContract and TSection exactly are . In my example : But I have to write following : You can see that I have to specify pair < SourceObserverContract , SourceObserverSection > twice , it 's a violation of DRY principe . So I 'd like to write something like : and make SourceObserverContract and SourceObserverSection inferred from interface.Is it possible in C # or I should specify it everywhere manually ? IDatabaseConfigurable looks like : Then extension just calls these two methods based on some logic . I must specify types becuase I need to access properties of each specific realisation , so I need a covariance . <code> public static TResult LoadFromAnySource < TContract , TSection , TResult > ( this TSection section , string serviceBaseUri , string nodeName ) where TSection : ConfigurationSection where TResult : IDatabaseConfigurable < TContract , TSection > , new ( ) where TContract : new ( ) public interface ISourceObserverConfiguration : IDatabaseConfigurable < SourceObserverContract , SourceObserverSection > sourceObserverSection.LoadFromAnySource < SourceObserverContract , SourceObserverSection , SourceObserverConfiguration > ( _registrationServiceConfiguration.ServiceBaseUri , nodeName ) ; sourceObserverSection.LoadFromAnySource < SourceObserverConfiguration > ( _registrationServiceConfiguration.ServiceBaseUri , nodeName ) ; public interface IDatabaseConfigurable < in TContract , in TSection > where TContract : ConfigContract where TSection : ConfigurationSection { string RemoteName { get ; } void LoadFromContract ( TContract contract ) ; void LoadFromSection ( TSection section ) ; } | Simplify generic type inferring |
C_sharp : I am trying to find an alternative to the following so that I can take advantage of the is operator.Something similar to the following , which does not compile . <code> public bool IsOfType ( Type type ) { return this._item.GetType ( ) == type ; } public bool IsOfType ( Type type ) { return this._item is type ; } | Is there a way to pass an argument to the is operator ? |
C_sharp : Watching Advanced Memory Management by Mark Probst and Rodrigo Kumpera , I learned new techniques such as profiling Mono GC and using WeakReference.Yet I still do n't understand how to “ fix ” the Puzzle 2 from 28th minute : The controller holds a ref to button that holds a ref to event handler that holds a ref to the controller . One way to break the cycle would be to nullify the button.Another way is to detach the handler ( but we 'd have to forsake using lamdas ) . Are there other /more elegant/ ways to break the cycle ? Can we somehow stick WeakReference in here ? Thanks.Edit : In this case , the button is not even a field . But there is still a cycle , is n't there ? It 's in Controller 's View 's Subviews . Do we have to clear them ? I 'm confused . <code> public class CustomButton : UIButton { public CustomButton ( ) { } } public class Puzzle2Controller : UIViewController { public override void ViewDidLoad ( ) { var button = new CustomButton ( ) ; View.Add ( button ) ; button.TouchUpInside += ( sender , e ) = > this.RemoveFromParentViewController ( ) ; } } | How do I fix the GC cycle caused by a lambda event handler ? |
C_sharp : We use the .NET 2.0 framework with C # 3.0 ( I think it 's the last version of C # which can run on the 2.0 version of the framework , correct me if I am wrong ) .Is there something built into C # which can make this type of parameter validation more convenient ? That sort of parameter validation becomes a common pattern and results in a lot of `` almost boilerplate '' code to wade through in our public methods.If there is nothing built in . Are there any great free libraries which we could use ? <code> public ConnectionSettings ( string url , string username , string password , bool checkPermissions ) { if ( username == null ) { throw new ArgumentNullException ( `` username '' ) ; } if ( password == null ) { throw new ArgumentNullException ( `` password '' ) ; } if ( String.IsNullOrEmpty ( url ) ) { throw new ArgumentException ( `` Must not be null or empty , it was `` + ( url == null ? url : `` empty '' ) , `` url '' ) ; } this.url = url ; this.username = username ; this.password = password ; this.checkPermissions = checkPermissions ; } | Nicer way of parameter checking ? |
C_sharp : Let 's say I have a generic list of Fruit ( List < Fruit > fruits = new List < Fruit > ( ) ) . I then add a couple of objects ( all derived from Fruit ) - Banana , Apple , Orange but with different properties on the derived objects ( such as Banana.IsYellow ) .Then I can do this : But at execution time of course this is not valid because there is no IsYellow-property on the Apple and Orange objects.How do I get only the bananas , apples , oranges etc from the List < Fruit > ? <code> List < Fruit > fruits = new List < Fruit > ( ) ; Banana banana1 = new Banana ( ) ; Banana banana2 = new Banana ( ) ; Apple apple1 = new Apple ( ) ; Orange orange2 = new Orange ( ) ; fruits.Add ( banana1 ) ; fruits.Add ( banana2 ) ; fruits.Add ( apple1 ) ; fruits.Add ( orange1 ) ; foreach ( Banana banana in fruits ) Console.Write ( banana.IsYellow ) ; | How do I get a particular derived object in a List < T > ? |
C_sharp : Possible Duplicate : C # Captured Variable In Loop I 'm working on a few simple applications of threading , but I ca n't seem to get this to work : The goal basically is to add threads to a queue one by one , and then to go through the queue one by one and pop off a thread and execute it . Because I have `` x < 2 '' in my for loop , it should only make two threads - one where it runs WriteNumber ( 0 ) , and one where it runs WriteNumber ( 1 ) , which means that I should end up with 1000 0 's and 1000 1 's on my screen in varying order depending on how the threads are ultimately executed.What I end up with is 2000 2 's . The two possible solutions that I 've come up with are : I 've missed something glaringly obvious , or sending the variable x to the WriteNumber function is doing a pass-by-reference and not pass-by-value , so that when the threads execute they 're using the most recent version of x instead of what it was at the time that the function was set . However , it was my understanding that variables are passed by value by default in C # , and only passed by reference if you include 'ref ' in your parameter . <code> class ThreadTest { static Queue < Thread > threadQueue = new Queue < Thread > ( ) ; static void Main ( ) { //Create and enqueue threads for ( int x = 0 ; x < 2 ; x++ ) { threadQueue.Enqueue ( new Thread ( ( ) = > WriteNumber ( x ) ) ) ; } while ( threadQueue.Count ! = 0 ) { Thread temp = threadQueue.Dequeue ( ) ; temp.Start ( ) ; } Console.Read ( ) ; } static void WriteNumber ( int number ) { for ( int i = 0 ; i < 1000 ; i++ ) { Console.Write ( number ) ; } } } | Simple Threading in C # |
C_sharp : I 'm pretty sure this is related to implementing interfaces and inheritance.In c # how does the System.Type class have the property Name ? When I example the code of the Type class from metadata or using the Object Browser I see the Type class does n't have : defined anywhere . I also see that Type inherits from MemberInfo and implements _Type and IReflect ( like this ) : The base class MemberInfo has the property : From what I know , this has to be overridden in the derived class because of the abstract modifier . I do n't see it in Type ... Then in the _Type interface there is a property : and because that is in an interface it has no implementation of its own either.Where is Name getting defined and how do it have a value in the System.Type class ? Or am I not understanding how inheritance and implementing interfaces works for this class <code> string Name public abstract class Type : MemberInfo , _Type , IReflect public abstract string Name { get ; } string Name { get ; } | How does c # System.Type Type have a name property |
C_sharp : Why does expr1 compile but not expr2 ? <code> Func < object > func = ( ) = > new object ( ) ; Expression < Func < object > > expr1 = ( ) = > new object ( ) ; Expression < Func < object > > expr2 = func ; // Can not implicitly convert type 'System.Func < object > ' to 'System.Linq.Expressions.Expression < System.Func < object > > ' | Why does an Expression type in .NET allows construction from a function but not conversion from one ? |
C_sharp : I 've noticed some bizarre behavior in my code when accidentally commenting out a line in a function during code review . It was very hard to reproduce but I 'll depict a similar example here.I 've got this test class : there is No assignment to Email in the GetOut which normally would throw an error : The out parameter 'email ' must be assigned to before control leaves the current methodHowever if EmailAddress is in a struct in a seperate assembly there is no error created and everything compiles fine.Why does n't the compiler enforce that Email must be assign to ? Why does this code compile if the struct is created in a separate assembly , but it does n't compile if the struct is defined in the existing assembly ? <code> public class Test { public void GetOut ( out EmailAddress email ) { try { Foo ( email ) ; } catch { } } public void Foo ( EmailAddress email ) { } } public struct EmailAddress { # region Constructors public EmailAddress ( string email ) : this ( email , string.Empty ) { } public EmailAddress ( string email , string name ) { this.Email = email ; this.Name = name ; } # endregion # region Properties public string Email { get ; private set ; } public string Name { get ; private set ; } # endregion } | out parameters of struct type not required to be assigned |
C_sharp : Consider this code : in above code we do n't use method hiding.when create instance of student and call showinfo method my output is I am Student i do n't use new keyword.Why does not call parent method when we do n't use method hiding ? <code> internal class Program { private static void Main ( string [ ] args ) { var student = new Student ( ) ; student.ShowInfo ( ) ; //output -- > `` I am Student '' } } public class Person { public void ShowInfo ( ) { Console.WriteLine ( `` I am person '' ) ; } } public class Student : Person { public void ShowInfo ( ) { Console.WriteLine ( `` I am Student '' ) ; } } | Why does not call parent method when we do n't use method hiding ? |
C_sharp : I am using the default Sitemap provider with secutiry trimming . But , some how , I get : A network-related or instance-specific error occurred while establishing a connection to SQL Server . I 'm thinking the sitemap provider is looking for the roles in the wrong place . My configuration is like this : The Sitemap tag is defined like this : Why am I getting the sql error ? How does the trimming get the roles ? EDIT : <code> < connectionStrings > < add name= '' DB '' ... / > < /connectionStrings > < membership defaultProvider= '' SqlProvider '' userIsOnlineTimeWindow= '' 15 '' > < providers > < clear/ > < add name= '' SqlProvider '' ... / > < /providers > < /membership > < roleManager enabled= '' true '' > < providers > < add connectionStringName= '' DB '' type= '' System.Web.Security.SqlRoleProvider '' ... / > < /providers > < /roleManager > < siteMap defaultProvider= '' XmlSiteMapProvider '' enabled= '' true '' > < providers > < clear/ > < add name= '' XmlSiteMapProvider '' description= '' Default SiteMap provider . '' type= '' System.Web.XmlSiteMapProvider `` siteMapFile= '' Web.sitemap '' securityTrimmingEnabled= '' true '' / > < /providers > < /siteMap > | Sitemap Security Trimming throws SQL error |
C_sharp : When overriding the Equals ( ) method , the MSDN recommends this : But if we know that the subclass directly inherits from Object , then is the following equivalent ? Note the ! base.Equals ( ) call : <code> class Point : Object { protected int x , y ; public Point ( int X , int Y ) { this.x = X ; this.y = Y ; } public override bool Equals ( Object obj ) { //Check for null and compare run-time types . if ( obj == null || GetType ( ) ! = obj.GetType ( ) ) return false ; Point p = ( Point ) obj ; return ( x == p.x ) & & ( y == p.y ) ; } } class Point : Object { protected int x , y ; public Point ( int X , int Y ) { this.x = X ; this.y = Y ; } public override bool Equals ( Object obj ) { if ( ! base.Equals ( obj ) || GetType ( ) ! = obj.GetType ( ) ) return false ; Point p = ( Point ) obj ; return ( x == p.x ) & & ( y == p.y ) ; } } | Overriding Equals ( ) : is null comparison redundant when calling base.Equals ( ) ? |
C_sharp : I have a list of invoices that and I transferred them to an Excel spreadsheet . All the columns are created into the spreadsheet except for the Job Date column . That is blank in the spreadsheet . Here 's the code : The sql returns all the correct information and as you can see the job date is there : But when I open the Excel file after it is created , the job date column is blank : <code> string Directory = ConfigurationSettings.AppSettings [ `` DownloadDestination '' ] + Company.Current.CompCode + `` \\ '' ; string FileName = DataUtils.CreateDefaultExcelFile ( Company.Current.CompanyID , txtInvoiceID.Value , Directory ) ; FileInfo file = new FileInfo ( FileName ) ; Response.Clear ( ) ; Response.ContentType = `` application/x-download '' ; Response.AddHeader ( `` Content-Length '' , file.Length.ToString ( ) ) ; Response.AddHeader ( `` Content-Disposition '' , `` attachment ; filename= '' + file.Name ) ; Response.CacheControl = `` public '' ; Response.TransmitFile ( file.FullName ) ; Response.Flush ( ) ; Context.ApplicationInstance.CompleteRequest ( ) ; public static string CreateDefaultExcelFile ( int CompanyID , string InvoiceNo , string CreateDirectory ) { List < MySqlParameter > param = new List < MySqlParameter > { { new MySqlParameter ( `` CompanyID '' , CompanyID ) } , { new MySqlParameter ( `` InvoiceNo '' , InvoiceNo ) } } ; DataTable result = BaseDisplaySet.CustomFill ( BaseSQL , param ) ; string FileName = CreateDirectory + `` InvoiceFile_ '' + DateTime.Now.ToString ( `` yyyyMMddhhmmssff '' ) + `` . `` ; FileName += `` xlsx '' ; XLWorkbook workbook = new XLWorkbook ( ) ; workbook.Worksheets.Add ( result , `` Bulk Invoices '' ) ; workbook.SaveAs ( FileName ) ; return FileName ; } private const string BaseSQL = `` SELECT q.InvoiceNo AS InvoiceNumber , j.JobNo , j.JobDate AS JobDate , `` + `` ( SELECT Name FROM job_address WHERE AddressType = 6 AND JobID = j.ID LIMIT 0,1 ) AS DebtorName , `` + `` ( SELECT CONCAT ( Name , CONCAT ( ' , ' , Town ) ) FROM job_address WHERE AddressType = 3 AND JobID = j.ID LIMIT 0,1 ) AS CollectFrom , `` + `` ( SELECT CONCAT ( Name , CONCAT ( ' , ' , Town ) ) FROM job_address WHERE AddressType = 2 AND JobID = j.ID LIMIT 0,1 ) AS DeliverTo , `` + `` deladd.Town AS DeliverToTown , deladd.County AS DeliveryToCounty , `` + `` ( SELECT DocketNo FROM job_dockets WHERE JobID = j.ID LIMIT 0,1 ) AS DocketNo , `` + `` SUM ( j.DelAmt ) AS DelAmount , `` + `` ( SELECT CAST ( group_concat ( DISTINCT CONCAT ( AdvisedQty , ' ' , PieceType ) separator ' , ' ) AS CHAR ( 200 ) ) FROM job_pieces WHERE JobID = j.ID GROUP BY JobID ) AS PieceBreakDown `` + `` FROM Invoice q `` + `` LEFT JOIN customer c ON q.accountcode = c.ID `` + `` INNER JOIN job_new j ON q.JobID = j.ID `` + `` LEFT JOIN job_address coladd ON coladd.JobID = j.ID AND coladd.AddressType = 3 `` + `` LEFT JOIN job_address deladd ON deladd.JobID = j.ID AND deladd.AddressType = 2 `` + `` WHERE q.IsActive = 1 AND q.Company_ID = ? CompanyID AND q.InvoiceNo = ? InvoiceNo `` + `` group by j.id '' ; | Column missing from excel spreedshet |
C_sharp : Let 's say there is a class A with an parameterless instance methodIt 's easy to invoke the method using reflection : However , I want to invoke the method as if it is staticIs there any way I can get this staticmethod ? NOTE : I want Something to be universal , i.e . A can be any class , and foo can be any instance method.EDIT : To make things clear : There is no static method in class A.There is a parameterless instance method called foo.I want to invoke ( using MethodInfo.Invoke ) foo AS IF it is a static method , that takes class A as the parameter.EDIT2 : Why I want this : ( to help you understand better ) I have a list of static methods that does similar job for different types , and they are stored in a dictionary Dictionary < Type , MethodInfo > dict.Thus , whenever I have an object obj and want to do the job , I canNow I want to add instance methods into it as well , but it will require me to remember which methods are static and which methods are instance-bond , and invoke them in different ways : Which is inconvenient . So I want to get static MethodInfo from instance methods , before adding them into the dict.EDIT3 : I do n't understand why this question is marked duplicate . The linked page does NOT answer my question . If I 'm missing something , please tell me.The linked page has several answers , but they eitherrequires that I know how many arguments foo takes , orgives a method that takes object [ ] as the parameter , instead of a list of parameters.So none of them fit here.After some research I found that there 's something close to what I need : Here , it takes new object [ ] { a } as the argument . But the thing is , since I do n't know how foo looks like , how can I pass the first argument of Delegate.CreateDelegate ? Last EDIT : Found a solution myself . Thank you for your help guys ! <code> class A { public A ( int x ) { this.x = x ; } private int x ; public int foo ( ) { return x ; } } A a = new A ( 100 ) ; var method = typeof ( A ) .GetMethod ( `` foo '' ) ; var result = method.Invoke ( a , new object [ 0 ] ) ; // 100 var staticmethod = Something ( typeof ( A ) , `` foo '' ) ; var result = staticmethod.Invoke ( null , new object [ ] { a } ) ; dict [ obj.GetType ( ) ] .Invoke ( null , new object [ ] { obj , param1 , param2 , ... } ) ; dict [ obj.GetType ( ) ] .Invoke ( null , new object [ ] { obj , param1 , param2 , ... } ) ; // static methodsdict [ obj.GetType ( ) ] .Invoke ( obj , new object [ ] { param1 , param2 , ... } ) ; // instance methods A a = new A ( 100 ) ; var method = typeof ( A ) .GetMethod ( `` foo '' ) ; var deleg = Delegate.CreateDelegate ( typeof ( Func < A , int > ) , method ) var result = deleg.DynamicInvoke ( new object [ ] { a } ) ; // 100 | Invoke instance method statically |
C_sharp : I saw some code written by another developer that looks something like this : ( It is ALL over the place in the code ) Question 1 : Would that error logging code even get called ? If there was no memory , would n't an System.OutOfMemoryException be thrown on that first line ? Question 2 : Can a call to a constructor ever return null ? <code> var stringBuilder = new StringBuilder ( ) ; if ( stringBuilder == null ) { // Log memory allocation error // ... return ; } | Would simple class instantiation ever fail in C # ? |
C_sharp : I have system being developed for an HR system . There are Accountant employees and Programmer employees . For the first month of joining the company , the employee is not given any role . One employee can be an Accountant and a programmer at the same time . I have a design shown by the following code.Now , I need to enhance the system by implementing a new functionality : Terminate all Accountants . ( Terminate means set status of employee as IsActive = false ) . The issue is I can not set all accountants directly as inactive without checking . I need to check whether he has got any other role . How to remodel these classes in order to do the terminate function more natural OO ? UPDATEI am looking for an answer that has EF Database First solution model and database schema for @ AlexDev answer.C # Code @ AlexDev AnswerREFERENCEDDD Approach to Access External InformationPrefer composition over inheritance ? Inheritance vs enum properties in the domain modelEntity Framework : Get Subclass objects in Repository <code> List < Accountant > allAccountants = Get All accountants from databasepublic class Employee { public int EmpID { get ; set ; } public DateTime JoinedDate { get ; set ; } public int Salary { get ; set ; } public bool IsActive { get ; set ; } } public class Accountant : Employee { public Employee EmployeeData { get ; set ; } } public class Programmer : Employee { public Employee EmployeeData { get ; set ; } } public class Employee { ... IList < Role > Roles ; bool isActive ; public void TerminateRole ( Role role ) { Roles.Remove ( role ) ; if ( Roles.Count == 0 ) { isActive = false ; } } } public class Role { abstract string Name { get ; } } public class ProgrammerRole : Role { override string Name { get { return `` Programmer '' ; } } } | Issue in using Composition for “ is – a “ relationship |
C_sharp : I wrote a Thread helper class that can be used to execute a piece of code in Unity 's main Thread . This is the functions blue print : The complete script is really long and will make this post unnecessarily long . You can see the rest of the script helper class here.Then I can use unity 's API from another Thread like this : The problem is that when I use a variable declared outside of that delegate , it would allocate memory . The code above allocates 104 bytes each frame . That 's because of the transform variable that is used inside that closure.This may seem like nothing now but I do this 60 times per-sec and I have about 6 camera 's I need to connect to and display images on the screen . I do not like the amount of garbage that is generated.Below is an example of how I am downloading images from a camera and uploading it into Unity . I get about 60 frames per-sec . The receiveVideoFrame ( ) function runs on a separate Thread . It downloads the image , send 's it to Unity 's main Thread and Unity uploads the image bytes into Texture2D . The Texture2D is then displayed with RawImage . The allocation happens when closure is captured due to UnityThread.executeInUpdate.How can I use closure without causing memory allocation ? If that 's not possible , is there another way to do this ? I can just remove the class I use to execute code in the main Thread and re-write those logic in the main script but that would be messy and long . <code> public static void executeInUpdate ( System.Action action ) UnityThread.executeInUpdate ( ( ) = > { transform.Rotate ( new Vector3 ( 0f , 90f , 0f ) ) ; } ) ; bool doneUploading = false ; byte [ ] videoBytes = new byte [ 25000 ] ; public Texture2D videoDisplay ; void receiveVideoFrame ( ) { while ( true ) { //Download Video Frame downloadVideoFrameFromNetwork ( videoBytes ) ; //Display Video Frame UnityThread.executeInUpdate ( ( ) = > { //Upload the videobytes to Texture to display videoDisplay.LoadImage ( videoBytes ) ; doneUploading = true ; } ) ; //Wait until video is done uploading to Texture/Displayed while ( ! doneUploading ) { Thread.Sleep ( 1 ) ; } //Done uploading Texture . Now set to false for the next run doneUploading = false ; //Repeat again } } | Delegate Closure with no memory allocation |
C_sharp : I want to create a .Net Core console app that gets run by the Windows Task Scheduler . In this console app I want to find the path of the directory where the app 's .exe file is located.I publish the app to create the .exe file by running this line of code in a command prompt : dotnet publish -r win-x64 -c Release /p : PublishSingleFile=true I believe that this might have something to do with the strange behavior outlined below.The problem I encounter is that when I run the .exe file the path it gets is not the path to the folder where it is located.To demonstrate this I have written this console application : When I debug this program I get this output : debug imageWhen I run the .exe file I get this output : manual runWhen I use Windows Task Scheduler to run the .exe file I get this output : task scheduler imageWhat I would like to know is : What code should I use to get the path to the directory where the .exe file is located ? Why is the path to a temp folder is being returned ? <code> //program.csusing System ; using System.Diagnostics ; using System.IO ; using System.Reflection ; namespace PathTest { class Program { static void Main ( string [ ] args ) { Write ( Directory.GetCurrentDirectory ( ) ) ; Write ( Assembly.GetExecutingAssembly ( ) .Location ) ; Write ( Assembly.GetExecutingAssembly ( ) .CodeBase ) ; Write ( Path.GetDirectoryName ( Assembly.GetEntryAssembly ( ) .Location ) ) ; Write ( AppDomain.CurrentDomain.BaseDirectory ) ; Write ( Environment.GetCommandLineArgs ( ) [ 0 ] ) ; Write ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ) .GetName ( ) .CodeBase ) ) ; Write ( Process.GetCurrentProcess ( ) .MainModule.FileName ) ; Write ( new Uri ( Assembly.GetExecutingAssembly ( ) .CodeBase ) .LocalPath ) ; Console.ReadKey ( ) ; } readonly static Action < string > Write = ( str ) = > { Console.WriteLine ( str ) ; Console.WriteLine ( `` '' ) ; } ; } } | How to get the path of the directory where the .exe file for a .Net Core console application is located ? |
C_sharp : So in C # , you might have the following code : As soon as you enter DoSomething , the CLR sets up space for int x . Why does it not wait until it reaches the line with int x =5 on it ? Especially since even though x is bound , it does n't let you actually use it until that line is reached anyway ? <code> void DoSomething ( ) { //some code . int x = 5 ; //some more code . } | Why does C # bind the local variables up-front ? |
C_sharp : If you have a brush and pen as in : and dispose them like so : How would you dispose it if it was : Pen p = CreatePenFromColor ( color ) which would create the brush and pen for you ? I ca n't dispose the brush inside this method , right ? Is this a method not to be used with disposable objects ? EDIT : What I mean is , how do you dispose the BRUSH ? <code> Brush b = new SolidBrush ( color ) ; Pen p = new Pen ( b ) ; b.Dispose ( ) ; p.Dispose ( ) ; | How to handle disposable objects we do n't have a reference to ? |
C_sharp : BackgroundI have an application where 3 views utilize html5 offline app functionality . As such , I have an app manifest generated in a razor view . A cut-down version of this view may look like the following : In order for the offline app to function correctly , the cached files must exactly match those requested by offline pages within the app . However , I would like to apply a 'cache-busting ' version string to the js/css resources referenced in this manifest . For HTML tags , this is supported by the ScriptTagHelper but I have not found any helpers/extension methods which support this for plain URLs ( as required in the above manifest ) .With reference to this post , I have resolved this by injecting a FileVersionProvider into my manifest view and using the AddFileVersionToPath ( ) method as follows : However , the FileVersionProvider class is in the Microsoft.AspNetCore.Mvc.TagHelpers.Internal namespace which does not fill me with confidence form a maintenance perspective . Finally , my implementation of the DI setup for this is not exactly ideal ( see below ) . I do n't like the fact that I need to make calls to GetService ( ) and surely I should be specifying a specific MemoryCache ? QuestionHas anyone had a requirement to create a link to a js/css resource with a version string before ? If so , is there a more elegant solution ? <code> CACHE MANIFESTCACHE : /site.min.css/site.min.js @ inject FileVersionProvider versionProviderCACHE MANIFESTCACHE : @ versionProvider.AddFileVersionToPath ( `` /site.min.css '' ) @ versionProvider.AddFileVersionToPath ( `` /site.min.js '' ) services.AddSingleton < FileVersionProvider > ( s = > new FileVersionProvider ( s.GetService < IHostingEnvironment > ( ) ? .WebRootFileProvider , s.GetService < IMemoryCache > ( ) , new PathString ( `` '' ) ) ) ; | Service/extension for getting a cache-busting 'version string ' |
C_sharp : I have the following extension method to find an element within a sequence , and then return two IEnumerable < T > s : one containing all the elements before that element , and one containing the element and everything that follows . I would prefer if the method were lazy , but I have n't figured out a way to do that . Can anyone come up with a solution ? Doing sequence.ToArray ( ) immediately defeats the laziness requirement . However , without that line , an expensive-to-iterate sequence may be iterated over twice . And , depending on what the calling code does , many more times . <code> public static PartitionTuple < T > Partition < T > ( this IEnumerable < T > sequence , Func < T , bool > partition ) { var a = sequence.ToArray ( ) ; return new PartitionTuple < T > { Before = a.TakeWhile ( v = > ! partition ( v ) ) , After = a.SkipWhile ( v = > ! partition ( v ) ) } ; } | Lazily partition sequence with LINQ |
C_sharp : Here is the equality comparer I just wrote because I wanted a distinct set of items from a list containing entities.Why does Distinct require a comparer as opposed to a Func < T , T , bool > ? Are ( A ) and ( B ) anything other than optimizations , and are there scenarios when they would not act the expected way , due to subtleness in comparing references ? If I wanted to , could I replace ( C ) with return GetHashCode ( x ) == GetHashCode ( y ) <code> class InvoiceComparer : IEqualityComparer < Invoice > { public bool Equals ( Invoice x , Invoice y ) { // A if ( Object.ReferenceEquals ( x , y ) ) return true ; // B if ( Object.ReferenceEquals ( x , null ) || Object.ReferenceEquals ( y , null ) ) return false ; // C return x.TxnID == y.TxnID ; } public int GetHashCode ( Invoice obj ) { if ( Object.ReferenceEquals ( obj , null ) ) return 0 ; return obj.TxnID2.GetHashCode ( ) ; } } | Questions about IEqualityComparer < T > / List < T > .Distinct ( ) |
C_sharp : When implementing IEnumerable & IEnumerator on a class I was writing during training , I noticed that I was required to specify two implementations for the property `` Current '' .I roughly understand that I 'm implementing some non-generic version of IEnumerator and a `` Current '' property for it , however I do n't understand the following things : Why am I allowed to overload by return type here ? Presumably it has something to do with the explicit IEnumerator.Current ; however the reasons are opaque to me.Why can `` object IEnumerator.Current '' not be specified as `` public '' ? Thanks in advance ! <code> public class PeopleEnumerator : IEnumerator < Person > { People people ; // my collection I 'm enumerating ( just a wrapped array ) . int index ; // my index to keep track of where in the collection I am . ... //implementation for Person public Person Current { get { return people [ index ] ; } } //implementation for object object Enumerator.Current { get { return people [ index ] ; } } } | Why must I define IEnumerator < T > .Current & IEnumerator.Current , and what does that achieve ? |
C_sharp : Sorry for the long question but I 'm kinda new to C # ( I used to use VB.Net ) I fully understand the difference between Overriding and Overloading in both VB.Net and C # .. so there 's no problem with the overriding.Now , in VB.Net there 's a difference between Shadowing ( using the keyword Shadows ) and Overloading ( using the keyword Overloads 'with the same arguments ' ) as follows : When using Shadows , it shadows every method with the same name -regardless of the arguments- to become one method only ( the shadowed method ) .When using Overloads -with the same arguments- , it overloads ( shadows ) only the method with the same name and arguments.Consider this code : Then : While : So far so good..BUT , in C # I 'm not getting the same difference between Shadowing ( using the keyword New ) and Overloading ( Same name & arguments ) ! So , when trying the same code above in C # ( using C # syntax of course : D ) , the following line : will return > > ' A.MyMethod2 ( x ) 'Looks like no difference between Overloading and Shadowing in C # ! ! Anyone can explain why this discrepancy exists ? Thank you <code> Class A Sub MyMethod ( ) Console.WriteLine ( `` A.MyMethod '' ) End Sub Sub MyMethod ( ByVal x As Integer ) Console.WriteLine ( `` A.MyMethod ( x ) '' ) End Sub Sub MyMethod2 ( ) Console.WriteLine ( `` A.MyMethod2 '' ) End Sub Sub MyMethod2 ( ByVal x As Integer ) Console.WriteLine ( `` A.MyMethod2 ( x ) '' ) End SubEnd ClassClass B Inherits A Overloads Sub MyMethod ( ) Console.WriteLine ( `` B.MyMethod '' ) End Sub Shadows Sub MyMethod2 ( ) Console.WriteLine ( `` B.MyMethod2 '' ) End SubEnd Class Dim obj As New B ( ) obj.MyMethod ( ) ' B.MyMethodobj.MyMethod ( 10 ) ' A.MyMethod ( x ) obj.MyMethod2 ( ) ' B.MyMethod2 obj.MyMethod2 ( 10 ) 'Error , cuz there 's only one 'MyMethod2 ' ( and with zero arguments ) obj.MyMethod2 ( 10 ) ; | C # vs VB.Net , what 's the difference between Shadowing and [ Overloading ( without changing the arguments ) ] |
C_sharp : I using Unity 2019.2.14f1 to create a simple 3D game.In that game , I want to play a sound anytime my Player collides with a gameObject with a specific tag.The MainCamera has an Audio Listener and I am using Cinemachine Free Look , that is following my avatar , inside the ThridPersonController ( I am using the one that comes on Standard Assets - but I have hidden Ethan and added my own character/avatar ) .The gameObject with the tag that I want to destroy has an Audio Source : In order to make the sound playing on the collision , I started by creating an empty gameObject to serve as the AudioManager , and added a new component ( C # script ) to it : And created the script Sound.cs : After that , in the Unity UI , I went to the Inspector in the gameObject AudioManager , and added a new element in the script that I named : CatchingPresent.On the Third Person Character script , in order to destroy a gameObject ( with a specific tag ) when colliding with it , I have added the following : It is working properly as that specific object is disappearing on collision . Now , in order to play the sound `` CatchingPresent '' anytime the Player collides with the object with the tag , in this case , Present , I have tried adding the following to the if in the OnCollisionEnter : FindObjectOfType < AudioManager > ( ) .Play ( `` CatchingPresent '' ) ; But I get the error : The type or namespace name 'AudioManager ' could not be found ( are you missing a using directive or an assembly reference ? ) AudioManager.instance.Play ( `` CatchingPresent '' ) ; But I get the error : The name 'AudioManager ' does not exist in the current contextAs all the compiler errors need to be fixed before entering the Playmode , any guidance on how to make the sound playing after a collision between the player and the gameObject with the tag Present is appreciated.Edit 1 : Assuming that it is helpful , here it goes the full ThirdPersonUserControl.cs : Edit 2 : Hierarchy in Unity : <code> using UnityEngine.Audio ; using System ; using UnityEngine ; public class AudioManager : MonoBehaviour { public Sound [ ] sounds ; // Start is called before the first frame update void Awake ( ) { foreach ( Sound s in sounds ) { s.source = gameObject.AddComponent < AudioSource > ( ) ; s.source.clip = s.clip ; s.source.volume = s.volume ; s.source.pitch = s.pitch ; } } // Update is called once per frame public void Play ( string name ) { Sound s = Array.Find ( sounds , sound = > sound.name == name ) ; s.source.Play ( ) ; } } using UnityEngine.Audio ; using UnityEngine ; [ System.Serializable ] public class Sound { public string name ; public AudioClip clip ; [ Range ( 0f , 1f ) ] public float volume ; [ Range ( .1f , 3f ) ] public float pitch ; [ HideInInspector ] public AudioSource source ; } void OnCollisionEnter ( Collision other ) { if ( other.gameObject.CompareTag ( `` Present '' ) ) { Destroy ( other.gameObject ) ; count = count - 1 ; SetCountText ( ) ; } } using System ; using UnityEngine ; using UnityEngine.UI ; using UnityStandardAssets.CrossPlatformInput ; namespace UnityStandardAssets.Characters.ThirdPerson { [ RequireComponent ( typeof ( ThirdPersonCharacter ) ) ] public class ThirdPersonUserControl : MonoBehaviour { public Text countText ; public Text winText ; private int count ; private ThirdPersonCharacter m_Character ; // A reference to the ThirdPersonCharacter on the object private Transform m_Cam ; // A reference to the main camera in the scenes transform private Vector3 m_CamForward ; // The current forward direction of the camera private Vector3 m_Move ; private bool m_Jump ; // the world-relative desired move direction , calculated from the camForward and user input . private void Start ( ) { count = 20 ; SetCountText ( ) ; winText.text = `` '' ; // get the transform of the main camera if ( Camera.main ! = null ) { m_Cam = Camera.main.transform ; } else { Debug.LogWarning ( `` Warning : no main camera found . Third person character needs a Camera tagged \ '' MainCamera\ '' , for camera-relative controls . `` , gameObject ) ; // we use self-relative controls in this case , which probably is n't what the user wants , but hey , we warned them ! } // get the third person character ( this should never be null due to require component ) m_Character = GetComponent < ThirdPersonCharacter > ( ) ; } private void Update ( ) { if ( ! m_Jump ) { m_Jump = CrossPlatformInputManager.GetButtonDown ( `` Jump '' ) ; } } // Fixed update is called in sync with physics private void FixedUpdate ( ) { // read inputs float h = CrossPlatformInputManager.GetAxis ( `` Horizontal '' ) ; float v = CrossPlatformInputManager.GetAxis ( `` Vertical '' ) ; bool crouch = Input.GetKey ( KeyCode.C ) ; // calculate move direction to pass to character if ( m_Cam ! = null ) { // calculate camera relative direction to move : m_CamForward = Vector3.Scale ( m_Cam.forward , new Vector3 ( 1 , 0 , 1 ) ) .normalized ; m_Move = v*m_CamForward + h*m_Cam.right ; } else { // we use world-relative directions in the case of no main camera m_Move = v*Vector3.forward + h*Vector3.right ; } # if ! MOBILE_INPUT // walk speed multiplier if ( Input.GetKey ( KeyCode.LeftShift ) ) m_Move *= 0.5f ; # endif // pass all parameters to the character control script m_Character.Move ( m_Move , crouch , m_Jump ) ; m_Jump = false ; } void OnCollisionEnter ( Collision other ) { if ( other.gameObject.CompareTag ( `` Present '' ) ) { Destroy ( other.gameObject ) ; count = count - 1 ; SetCountText ( ) ; //FindObjectOfType < AudioManager > ( ) .Play ( `` CatchingPresent '' ) ; AudioManager.instance.Play ( `` CatchingPresent '' ) ; } } void SetCountText ( ) { countText.text = `` Missing : `` + count.ToString ( ) ; if ( count == 0 ) { winText.text = `` You saved Christmas ! `` ; } } } } | Unity3D playing sound when Player collides with an object with a specific tag |
C_sharp : It is my understanding that C # is a safe language and does n't allow one to access unallocated memory , other than through the unsafe keyword . However , its memory model allows reordering when there is unsynchronized access between threads . This leads to race hazards where references to new instances appear to be available to racing threads before the instances have been fully initialized , and is a widely known problem for double-checked locking . Chris Brumme ( from the CLR team ) explains this in their Memory Model article : Consider the standard double-locking protocol : This is a common technique for avoiding a lock on the read of ‘ a ’ in the typical case . It works just fine on X86 . But it would be broken by a legal but weak implementation of the ECMA CLI spec . It ’ s true that , according to the ECMA spec , acquiring a lock has acquire semantics and releasing a lock has release semantics . However , we have to assume that a series of stores have taken place during construction of ‘ a ’ . Those stores can be arbitrarily reordered , including the possibility of delaying them until after the publishing store which assigns the new object to ‘ a ’ . At that point , there is a small window before the store.release implied by leaving the lock . Inside that window , other CPUs can navigate through the reference ‘ a ’ and see a partially constructed instance.I 've always been confused by what `` partially constructed instance '' means . Assuming that the .NET runtime clears out memory on allocation rather than garbage collection ( discussion ) , does this mean that the other thread might read memory that still contains data from garbage-collected objects ( like what happens in unsafe languages ) ? Consider the following concrete example : The above has a race condition ; the output would be either 00-00 or 00-00-00-00 . However , is it possible that the second thread reads the new reference to buffer before the array 's memory has been initialized to 0 , and outputs some other arbitrary string instead ? <code> if ( a == null ) { lock ( obj ) { if ( a == null ) a = new A ( ) ; } } byte [ ] buffer = new byte [ 2 ] ; Parallel.Invoke ( ( ) = > buffer = new byte [ 4 ] , ( ) = > Console.WriteLine ( BitConverter.ToString ( buffer ) ) ) ; | Can memory reordering cause C # to access unallocated memory ? |
C_sharp : I am trying to use the SMO for Sql Server 2008 R2 Standard , but I am running into an issue whenever I try to Dump an object.The relevant code : Edit : A work around that I found is to use the Dump method with a fixed recursion depth e.g . Dump ( 1 ) , but the exception is at a different level for each object . <code> void Main ( ) { var connectionString = @ '' Server= ( local ) ; Trusted_Connection=True ; '' ; Server server = new Server ( new ServerConnection ( new SqlConnection ( connectionString ) ) ) ; server.ConnectionContext.Connect ( ) ; server.Dump ( ) ; //Error Database database = new Database ( server , `` master '' ) ; database.Refresh ( ) ; database.Dump ( ) ; // Error IEnumerable < Table > tables = database.Tables.Cast < Table > ( ) ; tables.Dump ( ) ; //Error } | Using LinqPad with SMO |
C_sharp : Something I do often if I 'm storing a bunch of string values and I want to be able to find them in O ( 1 ) time later is : This way , I can comfortably perform constant-time lookups on these string values later on , such as : However , I feel like I 'm cheating by making the value String.Empty . Is there a more appropriate .NET Collection I should be using ? <code> foreach ( String value in someStringCollection ) { someDictionary.Add ( value , String.Empty ) ; } if ( someDictionary.containsKey ( someKey ) ) { // etc } | 'Proper ' collection to use to obtain items in O ( 1 ) time in C # .NET ? |
C_sharp : I would like to enumerate the strings that are in the string intern pool.That is to say , I want to get the list of all the instances s of string such that : Does anyone know if it 's possible ? <code> string.IsInterned ( s ) ! = null | Read the content of the string intern pool |
C_sharp : I have encryption method that runs incredible slowly . It takes around 20 minutes to encrypt several hundred MB of data . I 'm not sure if I 'm taking the right approach . Any help , thoughts , advice would be greatly appreciated.Thanks for your help ! <code> private void AES_Encrypt ( string inputFile , string outputFile , byte [ ] passwordBytes , byte [ ] saltBytes ) { FileStream fsCrypt = new FileStream ( outputFile , FileMode.Create ) ; RijndaelManaged AES = new RijndaelManaged ( ) ; AES.KeySize = 256 ; AES.BlockSize = 128 ; var key = new Rfc2898DeriveBytes ( passwordBytes , saltBytes , 1000 ) ; AES.Key = key.GetBytes ( AES.KeySize / 8 ) ; AES.IV = key.GetBytes ( AES.BlockSize / 8 ) ; AES.Padding = PaddingMode.Zeros ; AES.Mode = CipherMode.CBC ; CryptoStream cs = new CryptoStream ( fsCrypt , AES.CreateEncryptor ( ) , CryptoStreamMode.Write ) ; FileStream fsIn = new FileStream ( inputFile , FileMode.Open ) ; int data ; while ( ( data = fsIn.ReadByte ( ) ) ! = -1 ) cs.WriteByte ( ( byte ) data ) ; fsCrypt.Flush ( ) ; cs.Flush ( ) ; fsIn.Flush ( ) ; fsIn.Close ( ) ; cs.Close ( ) ; fsCrypt.Close ( ) ; } | How to Speed Up this Encryption Method C # Filestream |
C_sharp : I have the following code : This code results in a compiler error : can not implicity convert type 'int ' to 'short'If I write the condition in the expanded format there is no compiler error : Why do I get a compiler error ? <code> Int16 myShortInt ; myShortInt = Condition ? 1 :2 ; if ( Condition ) { myShortInt = 1 ; } else { myShortInt = 2 ; } | cast short to int in if block |
C_sharp : I made an extension method to find the number of consecutive values in a collection . Because it is generic , I allow the caller to define the `` incrementor '' which is a Func < > that is supposed to increment the value in order to check for the existence of a `` next '' value.However , if the caller passes an improper incrementor ( i.e . x = > x ) , it will cause an infinite recursive loop . Any suggestions on a clean way to prevent this ? <code> public static int CountConsecutive < T > ( this IEnumerable < T > values , T startValue , Func < T , T > incrementor ) { if ( values == null ) { throw new ArgumentNullException ( `` values '' ) ; } if ( incrementor == null ) { throw new ArgumentNullException ( `` incrementor '' ) ; } var nextValue = incrementor ( startValue ) ; return values.Contains ( nextValue ) ? values.CountConsecutive ( nextValue , incrementor ) + 1 : 1 ; } | How do I avoid infinite recursion with a custom enumerator ? |
C_sharp : I have a list of properties and their values and they are formatted in a Dictionary < string , object > like this : There are two classes . Person is composed of the string Name and primitive Age as well as the complex Address class which has House , Street , City , and State string properties.Basically what I want to do is look up the class Person in the current assembly and create an instance of it and assign all of the values , no matter how complicated the classes get , as long as at the deepest level they are composed of primitives , strings , and a few common structures such as DateTime.I have a solution which allows me to assign the top level properties and down into one of the complex properties . I am assuming I must use recursion to solve this , but I would prefer not to . Though , even with recursion , I am at a loss as to a nice way to get down into each of the properties and assign their values.In this example below I am trying to translate the dotted representation to classes based on a method 's parameters . I look up the appropriate dotted representation based on the parameter 's type , trying to find a match . DotField is basically a KeyValuePair < string , object > where the key is the Name property . The code below may not work correctly but it should express the idea well enough . <code> Person.Name = `` John Doe '' Person.Age = 27Person.Address.House = `` 123 '' Person.Address.Street = `` Fake Street '' Person.Address.City = `` Nowhere '' Person.Address.State = `` NH '' foreach ( ParameterInfo parameter in this.method.Parameters ) { Type parameterType = parameter.ParameterType ; object parameterInstance = Activator.CreateInstance ( parameterType ) ; PropertyInfo [ ] properties = parameterType.GetProperties ( ) ; foreach ( PropertyInfo property in properties ) { Type propertyType = property.PropertyType ; if ( propertyType.IsPrimitive || propertyType == typeof ( string ) ) { string propertyPath = String.Format ( `` { 0 } . { 1 } '' , parameterType.Name , propertyType.Name ) ; foreach ( DotField df in this.DotFields ) { if ( df.Name == propertyPath ) { property.SetValue ( parameterInstance , df.Value , null ) ; break ; } } } else { // Somehow dive into the class , since it 's a non-primitive } } } | How can you translate a flat dotted list of properties to a constructed object ? |
C_sharp : a ) Do s and s1 reference variables point to same string object ( I ’ m assuming this due to the fact that strings are immutable ) ? b ) I realize equality operators ( == , > etc ) have been redefined to compare the values of string objects , but is the same true when comparing two strings using static methods Object.Equals ( ) and Object.ReferenceEquals ( ) ? thanx <code> string s = `` value '' ; string s1 = `` value '' ; | Since strings are immutable , do variables with identical string values point to the same string object ? |
C_sharp : I ca n't figure out the use for this code . Of what use is this pattern ? [ code repeated here for posterity ] <code> public class Turtle < T > where T : Turtle < T > { } | What use is this code ? |
C_sharp : I 'm designing a linguistic analyzer for French text . I have a dictionary in XML format , that looks like this : Sorry it 's so long , but it 's necessary to show exactly how the data is modeled ( tree-node structure ) .Currently I am using structs to model the conjugation tables , nested structs to be more specific . Here is the class I created to model what is a single entry in the XML file : I 'm new to C # , and I 'm not too familiar with the data structures . Based on my limited knowledge of C++ , I know that structs are useful when you are modeling small , highly-related pieces of data , which is why I am currently using them in this fashion.All of these structs could realistically be made into a ConjugationTables class , and would have , to a high degree , the same structure . I 'm unsure of whether to make these into a class , or use a different data structure that would be better suited to the problem . In order to give some more information about the problem specifications , I 'll say the following : Once these values have been loaded from the XML file , they will not be changed.These values will be read/fetched very often.The table-like structure must be maintained - that is to say that IndicativePresent must be nested under VerbForms ; the same applies to all other structs that are members of the VerbForms struct . These are conjugation tables after all ! Perhaps the most important : I need the organization of the data to be set up in a way that , if for example a Word in the XML file does not have a GrammaticalForm of verb , that no VerbForms struct will actually be created for that entry . This is in an effort to improve efficiency - why instantiate VerbForms if the word is not actually a verb ? This idea of avoiding unnecessary creation of these `` forms '' tables ( which are currently represented as struct XXXXXForms ) is absolutely imperative.In accordance with ( primarily ) point # 4 above , what kinds of data structures would be best used in modeling conjugation tables ( not database tables ) ? Do I need to change the format of my data in order to be compliant with # 4 ? If I instantiate a new Word , will the structs , in their current state , be instantiated as well and take up a lot of space ? Here 's some math ... after Googling around and eventually finding this question ... In all the conjugation tables ( nouns , adjectives , verbs ) , there are a total of ( coincidence ? ) 100 strings allocated , and that are empty . So 100 x 18 bytes = 1800 bytes for each Word , at minimum , if these data structures are created and remain empty ( there will always be at least some overhead for the values that would actually be filled in ) . So assuming ( just randomly , could be more or less ) 50,000 Words that would need to be in memory , that 's 90 million bytes , or approximately 85.8307 megabytes.That 's a lot of overhead just to have empty tables . So what is a way that I can put this data together to allow me to instantiate only certain tables ( noun , adjective , verb ) depending on what GrammaticalForms the Word actually has ( in the XML file ) .I want these tables to be a member of the Word class , but only instantiate the tables that I need . I ca n't think of a way around it , and now that I did the math on the structs I know that it 's not a good solution . My first thought is to make a class for each type of NounForms , AdjectiveForms , and VerbForms , and instantiate the class if the form appears in the XML file . I 'm not sure if that is correct though ... Any suggestions ? <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Dictionary > < ! -- This is the base structure for every entry in the dictionary . Values on attributes are given as explanations for the attributes . Though this is the structure of the finished product for each word , definition , context and context examples will be ommitted as they do n't have a real effect on the application at this moment . Defini -- > < Word word= '' The word in the dictionary ( any word that would be defined ) . '' aspirate= '' Whether or not the word starts with an aspirate h. Some adjectives that come before words that start with a non-aspirate h have an extra form ( AdjectiveForms - & gt ; na [ non-aspirate ] ) . `` > < GrammaticalForm form= '' The grammatical form of the word is the grammatical context in which it is used . Forms may consist of a word in noun , adjective , adverb , exclamatory or other form . Each form ( generally ) has its own definition , as the meaning of the word changes in the way it is used . `` > < Definition definition= '' '' > < /Definition > < /GrammaticalForm > < ConjugationTables > < NounForms ms= '' The masculin singular form of the noun . '' fs= '' The feminin singular form of the noun . '' mpl= '' The masculin plural form of the noun . '' fpl= '' The feminin plural form of the noun . '' gender= '' The gender of the noun . Determines '' > < /NounForms > < AdjectiveForms ms= '' The masculin singular form of the adjective . '' fs= '' The feminin singular form of the adjective . '' mpl= '' The masculin plural form of the adjective . '' fpl= '' The feminin plural form of the adjective . '' na= '' The non-aspirate form of the adjective , in the case where the adjective is followed by a non-aspirate word . '' location= '' Where the adjective is placed around the noun ( before , after , or both ) . `` > < /AdjectiveForms > < VerbForms group= '' What group the verb belongs to ( 1st , 2nd , 3rd or exception ) . '' auxillary= '' The auxillary verb taken by the verb . '' prepositions= '' A CSV list of valid prepositions this verb uses ; for grammatical analysis . '' transitive= '' Whether or not the verb is transitive . '' pronominal= '' The pronominal infinitive form of the verb , if the verb allows pronominal construction . `` > < Indicative > < Present fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Present > < SimplePast fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /SimplePast > < PresentPerfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /PresentPerfect > < PastPerfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /PastPerfect > < Imperfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Imperfect > < Pluperfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Pluperfect > < Future fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Future > < PastFuture fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /PastFuture > < /Indicative > < Subjunctive > < Present fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Present > < Past fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Past > < Imperfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Imperfect > < Pluperfect fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Pluperfect > < /Subjunctive > < Conditional > < Present fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /Present > < FirstPast fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /FirstPast > < SecondPast fps= '' ( Je ) first person singular . '' sps= '' ( Tu ) second person singular . '' tps= '' ( Il ) third person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . '' tpp= '' ( Ils ) third person plural . `` > < /SecondPast > < /Conditional > < Imperative > < Present sps= '' ( Tu ) second person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . `` > < /Present > < Past sps= '' ( Tu ) second person singular . '' fpp= '' ( Nous ) first person plural . '' spp= '' ( Vous ) second person plural . `` > < /Past > < /Imperative > < Infinitive present= '' The present infinitive form of the verb . '' past= '' The past infinitive form of the verb . `` > < /Infinitive > < Participle present= '' The present participle of the verb . '' past= '' The past partciple of the verb . `` > < /Participle > < /VerbForms > < /ConjugationTables > < /Word > < /Dictionary > class Word { public string word { get ; set ; } public bool aspirate { get ; set ; } public List < GrammaticalForms > forms { get ; set ; } struct GrammaticalForms { public string form { get ; set ; } public string definition { get ; set ; } } struct NounForms { public string gender { get ; set ; } public string masculinSingular { get ; set ; } public string femininSingular { get ; set ; } public string masculinPlural { get ; set ; } public string femininPlural { get ; set ; } } struct AdjectiveForms { public string masculinSingular { get ; set ; } public string femininSingular { get ; set ; } public string masculinPlural { get ; set ; } public string femininPlural { get ; set ; } public string nonAspirate { get ; set ; } public string location { get ; set ; } } struct VerbForms { public string group { get ; set ; } public string auxillary { get ; set ; } public string [ ] prepositions { get ; set ; } public bool transitive { get ; set ; } public string pronominalForm { get ; set ; } struct IndicativePresent { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativeSimplePast { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativePresentPerfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativePastPerfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativeImperfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativePluperfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativeFuture { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct IndicativePastFuture { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct SubjunctivePresent { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct SubjunctivePast { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct SubjunctiveImperfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct SubjunctivePluperfect { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct ConditionalPresent { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct ConditionalFirstPast { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct ConditionalSecondPast { public string firstPersonSingular { get ; set ; } public string secondPersonSingular { get ; set ; } public string thirdPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } public string thirdPersonPlural { get ; set ; } } struct ImperativePresent { public string secondPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } } struct ImperativePast { public string secondPersonSingular { get ; set ; } public string firstPersonPlural { get ; set ; } public string secondPersonPlural { get ; set ; } } struct Infinitive { public string present { get ; set ; } public string past { get ; set ; } } struct Participle { public string present { get ; set ; } public string past { get ; set ; } } } } | How to Represent Conjugation Tables in C # |
C_sharp : I was wondering , An Instance of class is on the Heap . ( value types inside it are also in the heap ) .But what about the opposite case ? There is one question here but it did n't mention any GC related info.So - How does GC handle this situation ? <code> public struct Point { object o ; public int x , y ; public Point ( int p1 , int p2 ) { o = new Object ( ) ; x = p1 ; y = p2 ; } } | Struct with reference types and GC ? |
C_sharp : I am trying to solve this business issue : A user gets 10 attempts to login every 5 minutesIf a user exceeds 10 attempts , I display a `` You need to wait tologin '' messageOnce 5 minutes have elapsed , I need to reset the number of attemptsand let the user attempt 10 more times.I 'd like to do this without using a Timer and I am storing most of this info in the SessionI store the FirstAttempt DateTime on Page Load.On the Login button click : I increment NumOfAttemptsI need to check if NumOfAttempts < 10 within the same 5 minute time slot . I could get the number of minutes elapsed between FirstAttempt and DateTime.Now and do a mod of 5 , but that wo n't tell me which timeslot this is in ( In other words , a user may have attempted 3 times as of the 2nd minute and then comes back in the 7th minute to do an attempt again . The mod would give me the same value.Any thoughts on how I could do this ? <code> public class LoginExp { public DateTime FirstAttempt ; public int NumOfAttempts ; } | How to solve this Timeslot issue in C # |
C_sharp : For all DI examples I have seen , I always see the dependencies as other classes , like services . But an object may depend , heavily and/or crucially in fact , on configuration values such as Strings and resource wrappers ( File/Path/URI/URL , as opposed to an entire big value string/document , or a reader ) .Note , this is about the DI design pattern in Java or C # syntax alone , not how any particular DI framework handles this.For example , let 's say I have this class which returns a String ( relative path , based on some obscure implementation logic ) . It ( rather its various implementors ) has a configuration/initialization dependency on the `` projectLocation '' , as a user could have various projects on their machine and this class will perform some logic based on a given project whenever it is called.I am not using DI just for unit-testing ( gasp I 'm not even unit testing , existing project ) . I just want to separate my dependency/creational concerns and logic concerns period . <code> public abstract class PathResolver { protected File projectFilesLocation ; public RoutinePathResolver ( File projectFilesLocation ) { this.projectFilesLocation = projectFilesLocation ; } public abstract String getPath ( String someValue ) ; } | Are value objects valid dependencies for DI design pattern ? |
C_sharp : I keep running into a pattern whereby I want to select rows from an Entity Collection ( EF4 ) and use the data to create new rows in a different entity collection.The only way I have found to do this is to perform the following steps : If I try to create a new OtherEntity in the select then I get an EF exception.Is this the only way to proceed ? Makes the whole thing very cumbersome and seems a complete waste of keystrokes ? <code> var newEntities = ( from e in myentities where e.x == y select new { Prop1 = e.Prop1 , Prop2 = e.Prop2+e.Prop3 , Prop3 = DateTime.Now , Prop4 = `` Hardcodedstring '' } ) .AsEnumerable ( ) .Select ( n= > new OtherEntity { Prop1 = n.Prop1 , Prop2 = n.Prop2 , Prop3 = n.Prop3 , Prop4 = n.Prop4 } ) ; //insert into database and save | Is it necessary to always Select ( ) ... new { Anon } ... AsEnumerable ... Select ( new EntityType { } ) every time ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.