text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : During switching to the new .NET Core 3 's IAsynsDisposable , I 've stumbled upon the following problem.The core of the problem : if DisposeAsync throws an exception , this exception hides any exceptions thrown inside await using-block.What is getting caught is the AsyncDispose-exception if it 's thrown , and the exception from inside await using only if AsyncDispose does n't throw.I would however prefer it other way round : getting the exception from await using block if possible , and DisposeAsync-exception only if the await using block finished successfully.Rationale : Imagine that my class D works with some network resources and subscribes for some notifications remote . The code inside await using can do something wrong and fail the communication channel , after that the code in Dispose which tries to gracefully close the communication ( e. g. , unsubscribe from the notifications ) would fail , too . But the first exception gives me the real information about the problem , and the second one is just a secondary problem.In the other case when the main part ran through and the disposal failed , the real problem is inside DisposeAsync , so the exception from DisposeAsync is the relevant one . This means that just suppressing all exceptions inside DisposeAsync should n't be a good idea.I know that there is the same problem with non-async case : exception in finally overrides the exception in try , that 's why it 's not recommended to throw in Dispose ( ) . But with network-accessing classes suppressing exceptions in closing methods does n't look good at all.It 's possible to work around the problem with the following helper : and use it likewhich is kind of ugly ( and disallows things like early returns inside the using block ) .Is there a good , canonical solution , with await using if possible ? My search in internet did n't find even discussing this problem . <code> class Program { static async Task Main ( ) { try { await using ( var d = new D ( ) ) { throw new ArgumentException ( `` I 'm inside using '' ) ; } } catch ( Exception e ) { Console.WriteLine ( e.Message ) ; // prints I 'm inside dispose } } } class D : IAsyncDisposable { public async ValueTask DisposeAsync ( ) { await Task.Delay ( 1 ) ; throw new Exception ( `` I 'm inside dispose '' ) ; } } static class AsyncTools { public static async Task UsingAsync < T > ( this T disposable , Func < T , Task > task ) where T : IAsyncDisposable { bool trySucceeded = false ; try { await task ( disposable ) ; trySucceeded = true ; } finally { if ( trySucceeded ) await disposable.DisposeAsync ( ) ; else // must suppress exceptions try { await disposable.DisposeAsync ( ) ; } catch { } } } } await new D ( ) .UsingAsync ( d = > { throw new ArgumentException ( `` I 'm inside using '' ) ; } ) ;
Proper way to deal with exceptions in AsyncDispose
C_sharp : I have been chasing this issue for a day now and am stumped , so thought I would put it out to you folks for some inspiration . I 'm a bit of a novice when it comes to deadlocks and SQL Server lock modes , I rarely need to delve into this.The short story : When a user logs into our application , we want to update a SQL Server view based on the fact that they now have a `` session '' , so that when they subsequently run a SQL Server Reporting Services report based on a report model , it includes security settings for their session.The regular deadlock I 've noticed is occuring between the process that DROPs and reCREATEs the view ( which I call the AuthRuleCache ) , and a Microsoft SQL Server Reporting Services 2008 ( SSRS ) report that tries to select from the view.The if I read the SQL Profiler deadlock event properly , the AuthRuleCache has a Sch-M lock , and the report has an IS lock.The AuthRuleCache code is C # in a DotNet assembly , it 's executed when users log into our Classic ASP app.Obviously I want to avoid the deadlock because it 's preventing logins - I do n't mind how I achieve this as long as I do n't need to compromise any other functionality . I 've got full control over the AuthRuleCache and the database , but I would say that we 're `` light '' on enterprise DBA expertise.Here is an example deadlock event from SQL Profiler : The LONG story : I 've decided to do this as a Q & A.Q : Why do you have to make frequent schema changes just to enforce security on reports ? A : Well , I only arrived that this approach because our SSRS reporting mechanism is totally based on report models , and our application supports row-level security by applying rules . The rules themselves are defined in the database as little SQL fragments . These fragments are re-assembled at run-time and applied based on a ) who the user is , b ) what they are trying to do , and c ) what they are trying to do it to . So , each user may have a unique view of the data based on the rules that apply to them . We have users authoring and saving their own reports , so I wanted this security enforced at the model to prevent them from stumbling upon data they should not have access to.The challenge we faced with report models is that they are based on a data source view ( DSV ) that can only be made up of static sources , e.g . tables , named-queries , views . You can not inject some C # code into the DSV to get it to dynamically respond to the particular user running the report . You do get the UserID at the model ( SMDL ) so you can use this for filtering . Our solution is to get the DSV to expose a view with ALL of the data for ALL of the currently logged in users ' unique rulesets ( namely , the AuthRuleCache ) , then the SMDL will filter this back to the unique ruleset of the requesting user . Hey-presto , you 've got dynamic row-level , rule-based security in an SSRS report model ! The rules change infrequently , so it 's OK for these to behave the same way for the duration of a user 's session . Because we have tens of thousnds of users , but only a few hundred or so may log in during a 24 hour period , I decided to refresh the AuthRuleCache any time a user logs in and expire it after 24 hours so it contains only security info for users with current sessions.Q : What form does the AuthRuleCache take ? A : It 's a view UNIONing a buch of other views . Each user has their own view e.g . widgets_authorized_123 where widgets is the table containing data being secured , and 123 is the user id . Then , there 's a master view ( e.g . widgets_authorized ) that UNIONs together all the user viewsQ : That sounds hideously inefficient , are you a moron ? A : Possibly - however thanks to the awesomeness of the SQL Query Processor , it all seems to run nice and fast for live user reports . I experimented with using a cache table to actually hold record-ids for use with the application security and found this led to bloated-tables and delays refreshing and reading from the cache.Q : Okay , you may still be a moron , but let 's explore another option . Can you rebuild the AuthRuleCache asynchronously instead of having the user wait at logon ? A : Well , the first thing the user does after logon is hit a dashboard containing reports based on the model - so we need the security rules up and running immediately after logon.Q : Have you explored different locking modes and isolation levels ? A : Sort of - I tried enabling altering the database read_committed_snapshot ON but that seemed to make no difference . In retrospect , I think the fact that I 'm trying to do a DROP/CREATE VIEW and requiring a Sch-M lock means that Read Committed Snapshot Isolation ( RCSI ) would n't help because it 's about handling concurrency of DML statements , and I 'm doing DDL.Q : Have you explored whole-database database snapshots or mirroring for reporting purposes ? A : I would n't rule this out , but I was hoping for more of an application-centric solution rather than making infrastructural changes . This would be a jump in resources utilization and maintenance overhead which I 'd need to escalate to other people.Q : Is there anything else we should know ? A : Yes , the AuthRuleCache refresh process is wrapped in a transaction because I wanted to make sire that nobody gets to see an incomplete/invalid cache , e.g . widget_authorized view referring to widget_authorized_123 when widget_authorized_123 has been dropped because the user 's session has expired . I tested without the transaction , and the deadlocks stopped , but I started getting blocked process reports from SQL Profiler instead . I saw ~15 second delays at login , and sometimes timeouts - so put the transaction back in.Q : How often is it happening ? A : The AuthRuleCache is switched off in the production environment at the moment so it 's not affecting users . My local testing of 100 sequential logons shows that maybe 10 % deadlock or fail . I suspect it is worse for users that have a long-running report model based report on their dashboard.Q : How about report snapshots ? A : Maybe a possibility - not sure how well this works with parametized reports . My concern is that we do have some users who will be alarmed if they insert a record but do n't see it on the dashboard until half an hour later . Also , I ca n't always guarantee everyone will use report snapshots correctly all the time , so do n't want to leave the door open for deadlocks to sneak back in at a later date.Q : Can I see the full T-SQL of the AuthRuleCache refresh transaction ? A : Here are the statements issued inside one transaction captured from SQL Profiler for one user logging on : Look for expired sessions - we 'd delete the associated view if foundDrop any pre-existing view for user 'myuser ' , id 298Create a view for user id 298Get a list of ALL user specific views for the actions entityDrop the existing master actions viewCreate a new master actions view and we 're done <code> < deadlock-list > < deadlock victim= '' process4785288 '' > < process-list > < process id= '' process4785288 '' taskpriority= '' 0 '' logused= '' 0 '' waitresource= '' OBJECT : 7:617365564:0 `` waittime= '' 13040 '' ownerId= '' 3133391 '' transactionname= '' SELECT '' lasttranstarted= '' 2013-01-07T15:16:24.680 '' XDES= '' 0x8005bd10 '' lockMode= '' IS '' schedulerid= '' 8 '' kpid= '' 20580 '' status= '' suspended '' spid= '' 83 '' sbid= '' 0 '' ecid= '' 0 '' priority= '' 0 '' trancount= '' 0 '' lastbatchstarted= '' 2013-01-07T15:15:55.780 '' lastbatchcompleted= '' 2013-01-07T15:15:55.780 '' clientapp= '' .Net SqlClient Data Provider '' hostname= '' MYMACHINE '' hostpid= '' 1176 '' loginname= '' MYMACHINE\MyUser '' isolationlevel= '' read committed ( 2 ) '' xactid= '' 3133391 '' currentdb= '' 7 '' lockTimeout= '' 4294967295 '' clientoption1= '' 671088672 '' clientoption2= '' 128056 '' > < executionStack > < frame procname= '' adhoc '' line= '' 2 '' stmtstart= '' 34 '' sqlhandle= '' 0x02000000bd919913e43fd778cd5913aabd70d423cb30904a '' > SELECT CAST ( 1 AS BIT ) [ c0_is_agg ] , 1 [ agg_row_count ] , COALESCE ( [ dbo_actions2 ] . [ ActionOverdue30days ] , 0 ) [ ActionOverdue30days ] , COALESCE ( [ dbo_actions3 ] . [ ActionOverdueTotal ] , 0 ) [ ActionOverdueTotal ] , COALESCE ( [ dbo_actions4 ] . [ ActionOverdue90daysPLUS ] , 0 ) [ ActionOverdue90daysPLUS ] , COALESCE ( [ dbo_actions5 ] . [ ActionOverdue60days ] , 0 ) [ ActionOverdue60days ] , COALESCE ( [ dbo_actions6 ] . [ ActionOverdue90days ] , 0 ) [ ActionOverdue90days ] , COALESCE ( [ dbo_actions7 ] . [ ActionPlanned30days ] , 0 ) [ ActionPlanned30days ] , COALESCE ( [ dbo_actions8 ] . [ ActionPlanned60days ] , 0 ) [ ActionPlanned60days ] , COALESCE ( [ dbo_actions9 ] . [ ActionPlanned90days ] , 0 ) [ ActionPlanned90days ] , COALESCE ( [ dbo_actions10 ] . [ ActionPlanned90daysPLUS ] , 0 ) [ ActionPlanned90daysPLUS ] , COALESCE ( [ dbo_actions11 ] . [ ActionPlannedTotal ] , 0 ) [ ActionPlannedTotal ] , CASE WHEN [ dbo_actions12 ] . [ CountOfFilter ] > 0 THEN 'Overdue0-30days ' WHEN [ dbo_actions13 ] . [ CountOfFilter ] > 0 THEN 'Overdue90daysPlus ' WHEN [ dbo_actions5 ] . [ Count < /frame > < /executionStack > < inputbuf > SET DATEFIRST 7 SELECT CAST ( 1 AS BIT ) [ c0_is_agg ] , 1 [ agg_row_count ] , COALESCE ( [ dbo_actions2 ] . [ ActionOverdue30days ] , 0 ) [ ActionOverdue30days ] , COALESCE ( [ dbo_actions3 ] . [ ActionOverdueTotal ] , 0 ) [ ActionOverdueTotal ] , COALESCE ( [ dbo_actions4 ] . [ ActionOverdue90daysPLUS ] , 0 ) [ ActionOverdue90daysPLUS ] , COALESCE ( [ dbo_actions5 ] . [ ActionOverdue60days ] , 0 ) [ ActionOverdue60days ] , COALESCE ( [ dbo_actions6 ] . [ ActionOverdue90days ] , 0 ) [ ActionOverdue90days ] , COALESCE ( [ dbo_actions7 ] . [ ActionPlanned30days ] , 0 ) [ ActionPlanned30days ] , COALESCE ( [ dbo_actions8 ] . [ ActionPlanned60days ] , 0 ) [ ActionPlanned60days ] , COALESCE ( [ dbo_actions9 ] . [ ActionPlanned90days ] , 0 ) [ ActionPlanned90days ] , COALESCE ( [ dbo_actions10 ] . [ ActionPlanned90daysPLUS ] , 0 ) [ ActionPlanned90daysPLUS ] , COALESCE ( [ dbo_actions11 ] . [ ActionPlannedTotal ] , 0 ) [ ActionPlannedTotal ] , CASE WHEN [ dbo_actions12 ] . [ CountOfFilter ] > 0 THEN 'Overdue0-30days ' WHEN [ dbo_actions13 ] . [ CountOfFilter ] > 0 THEN 'Overdue90daysPlus ' WHEN [ db < /inputbuf > < /process > < process id= '' process476ae08 '' taskpriority= '' 0 '' logused= '' 16056 '' waitresource= '' OBJECT : 7:1854941980:0 `` waittime= '' 4539 '' ownerId= '' 3132267 '' transactionname= '' user_transaction '' lasttranstarted= '' 2013-01-07T15:16:18.373 '' XDES= '' 0x9a7f3970 '' lockMode= '' Sch-M '' schedulerid= '' 7 '' kpid= '' 1940 '' status= '' suspended '' spid= '' 63 '' sbid= '' 0 '' ecid= '' 0 '' priority= '' 0 '' trancount= '' 2 '' lastbatchstarted= '' 2013-01-07T15:16:33.183 '' lastbatchcompleted= '' 2013-01-07T15:16:33.183 '' clientapp= '' .Net SqlClient Data Provider '' hostname= '' MYMACHINE '' hostpid= '' 14788 '' loginname= '' MYMACHINE\MyUser '' isolationlevel= '' read committed ( 2 ) '' xactid= '' 3132267 '' currentdb= '' 7 '' lockTimeout= '' 4294967295 '' clientoption1= '' 671088672 '' clientoption2= '' 128056 '' > < executionStack > < frame procname= '' adhoc '' line= '' 3 '' stmtstart= '' 202 '' stmtend= '' 278 '' sqlhandle= '' 0x02000000cf24d22c6cc84dbf398267db80eb194e79f91543 '' > DROP VIEW [ sec ] . [ actions_authorized ] < /frame > < /executionStack > < inputbuf > IF EXISTS ( SELECT * FROM sys.VIEWS WHERE object_id = OBJECT_ID ( N ' [ sec ] . [ actions_authorized ] ' ) ) DROP VIEW [ sec ] . [ actions_authorized ] < /inputbuf > < /process > < /process-list > < resource-list > < objectlock lockPartition= '' 0 '' objid= '' 617365564 '' subresource= '' FULL '' dbid= '' 7 '' objectname= '' 617365564 '' id= '' lock932d2f00 '' mode= '' Sch-M '' associatedObjectId= '' 617365564 '' > < owner-list > < owner id= '' process476ae08 '' mode= '' Sch-M '' / > < /owner-list > < waiter-list > < waiter id= '' process4785288 '' mode= '' IS '' requestType= '' wait '' / > < /waiter-list > < /objectlock > < objectlock lockPartition= '' 0 '' objid= '' 1854941980 '' subresource= '' FULL '' dbid= '' 7 '' objectname= '' 1854941980 '' id= '' locke6f0b580 '' mode= '' IS '' associatedObjectId= '' 1854941980 '' > < owner-list > < owner id= '' process4785288 '' mode= '' IS '' / > < /owner-list > < waiter-list > < waiter id= '' process476ae08 '' mode= '' Sch-M '' requestType= '' convert '' / > < /waiter-list > < /objectlock > < /resource-list > < /deadlock > < /deadlock-list > SELECT TABLE_SCHEMA + ' . ' + TABLE_NAMEFROM INFORMATION_SCHEMA.VIEWSWHERE TABLE_SCHEMA + ' . ' + TABLE_NAME LIKE 'sec.actions_authorized_ % ' AND RIGHT ( TABLE_NAME , NULLIF ( CHARINDEX ( ' _ ' , REVERSE ( TABLE_NAME ) ) , 0 ) - 1 ) NOT IN ( SELECT DISTINCT CAST ( empid AS NVARCHAR ( 20 ) ) FROM session ) IF EXISTS ( SELECT * FROM sys.VIEWS WHERE object_id = OBJECT_ID ( N ' [ sec ] . [ actions_authorized_298 ] ' ) ) DROP VIEW [ sec ] . [ actions_authorized_298 ] CREATE VIEW [ sec ] . [ actions_authorized_298 ] ASSELECT actid , 'myuser ' AS usernameFROM actionsWHERE actid IN ( SELECT actid FROM actions WHERE ( -- A bunch of custom where statements generated from security rules in the system prior to this transaction starting ) SELECT TABLE_SCHEMA + ' . ' + TABLE_NAMEFROM INFORMATION_SCHEMA.VIEWSWHERE TABLE_SCHEMA + ' . ' + TABLE_NAME LIKE 'sec.actions_authorized_ % ' IF EXISTS ( SELECT * FROM sys.VIEWS WHERE object_id = OBJECT_ID ( N ' [ sec ] . [ actions_authorized ] ' ) ) DROP VIEW [ sec ] . [ actions_authorized ] CREATE VIEW [ sec ] . [ actions_authorized ] ASSELECT actid , usernameFROM sec.actions_authorized_182 UNIONSELECT actid , usernameFROM sec.actions_authorized_298UNION -- Repeat for a bunch of other per-user custom views , generated from the prior select -- ...
Deadlocks during logon to ASP app caused by dropping/creating SQL Server views
C_sharp : I have the following code attaching event handler : Can I unsubscribe that lambda expression from the vent ? <code> this.btnOK.Click += ( s , e ) = > { MessageBox.Show ( `` test '' ) ; } ;
Unsubscribe lambda expression from event c #
C_sharp : Would appreciate any kind of help here . A brief description about scenario -There is a COM+ running on server ( written in C # ) . The task of this COM is to take a file name , page number of a multi-paged tiff file and the resolution to convert it to a gif file image . This COM is called from a web application using a proxy . The web site gets the converted image and displays in the requested resolution . For printing - it makes 2 request - 1st for display resolution , 2nd in full resolution ( which gets printed using window.print ( ) ) .Problem -After sometime server goes out of memory and images are not getting displayed on web site . Server needs to be restarted periodically.ErrorI do not have access to production server , but error sent by sysadmin states OutOfMemory.Thus , assuming memory leak and focusing on it - my findings so far with limited experience of handling this kind of situation -Perfmon - I see that Process/Private Bytes are increasing and so is.Net CLR memory/ # of bytes in Heap . Thus , I assume it 's Managedmemory leak . I am not sure though . CPU Usage - started with 8 % and went up to 80 % only at beginning.It dropped back and stayed between 3 % - 12 % , except couple oftimes when it went back to 75 % -85 % . Not sure what is going onhere.I started to debug server COM to have a look at heap , gcroot etc.There are 2 objects for count is increasing in the heap with every request made . 1 object is that hold the image data . 2nd object is the event handler to remove the Object 1 ( image ) from cache when it expires after a certain time.Looking at the method call - both objects lead to the same method.Code Implementation wise - Requested images are getting cached ( up to a certain number ) - I can understand it is for better performance . Probably , this is why reference to objects are increasing in heap as mentioned in bullet 1.I know I gave very vague description , but I need some kind of lead to detect the real issue on server.EDIT : Image object has been disposed like <code> EventType clr20r3 , P1 imageCOM.exe , P2 1.0.0.0 , P3 4fd65854 , P4 prod.web.imaging , P5 1.0.0.0 , P6 4fd65853 , P7 1a , P8 21 , P9 system.outofmemoryexception , P10 NIL.Here is the error ( s ) on the web server ( these continuously appear every minute ) ….System.Net.WebException : Unable to connect to the remote server -- - > System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it at System.Net.Sockets.Socket.DoConnect ( EndPoint endPointSnapshot , SocketAddress socketAddress ) at System.Net.Sockets.Socket.InternalConnect ( EndPoint remoteEP ) at System.Net.ServicePoint.ConnectSocketInternal ( Boolean connectFailure , Socket s4 , Socket s6 , Socket & socket , IPAddress & address , ConnectSocketState state , IAsyncResult asyncResult , Int32 timeout , Exception & exception ) -- - End of inner exception stack trace -- - Bitmap retVal ; using ( MemoryStream buffer = new MemoryStream ( doc.FileData , 0 , doc.DocumentSize , false , false ) ) { using ( Bitmap original = new Bitmap ( buffer ) ) { //select the page to convert and //perform scaling - full resolution or the requested resolution . } } using ( MemoryStream buffer = new MemoryStream ( ) ) { retVal.Save ( buffer , ImageFormat.Gif ) ; retVal.Dispose ( ) ; return buffer.GetBuffer ( ) ; }
Possibly memory leak OR ?
C_sharp : I researched this subject but I could n't find any duplicate . I am wondering why you can use a struct in an array without creating an instance of it.For example , I have a class and a struct : When ClassAPI is used in an array , it has to be initialized with the new keyword before being able to use its properties and methods : But this is not the case with StructAPI . It looks like StructAPI does n't have to be initialized in the array : If you try the same thing with ClassAPI , you would get a NullReferenceException.Why is it different with structs when using them in an array ? I understand the difference between class and struct with struct being a value type but that still does n't make sense . To me , without the array being involved in this , it would look like I am doing this : Notice that the sp variable is not initialized and it should result in a compile-time error that says : Error CS0165 Use of unassigned local variable 'sp'but that 's a different story when the struct is put in an array.Is the array initializing the struct in it ? I would like to know what 's going on . <code> public class ClassAPI { public Mesh mesh { get ; set ; } } public struct StructAPI { public Mesh mesh { get ; set ; } } ClassAPI [ ] cAPI = new ClassAPI [ 1 ] ; cAPI [ 0 ] = new ClassAPI ( ) ; //MUST DO THIS ! cAPI [ 0 ] .mesh = new Mesh ( ) ; StructAPI [ ] sAPI = new StructAPI [ 1 ] ; sAPI [ 0 ] .mesh = new Mesh ( ) ; StructAPI sp ; sp.mesh = new Mesh ( ) ;
Why does n't a struct in an array have to be initialized ?
C_sharp : I reviewed a colleagues code and told him to reorder the boolean comparisons in the following Linq Any predicate for performance reasons . So givenandI suggested changing the following : to becomeMy reasoning was that most of the jobs in jobsList fail the test for JobType , only a few will fail the test for Running and only one will fail the test for Id . If a match fails there is no point evaluating the others and because of sequence points this will not occur.My three part question is : Is this true , is it provably true and is there a better explanation I can give to my colleague for why reordering is a good idea ? <code> public class JobResult { public JobResult ( ) ; public string Id { get ; set ; } public StatusEnum Status { get ; set ; } public string JobType { get ; set ; } } IList < JobResult > jobsList = _jobRepository.FetchJobs ( ) //Exit if there is already a job of type `` PurgeData '' runningif ( jobsList.Any ( job = > job.Status == JobStatus.Running //1 & & job.Id ! = currentJobId //2 & & job.JobType == `` PurgeData '' ) ) //3 return false ; //Exit if there is already a job of type `` PurgeData '' runningif ( jobsList.Any ( job = > job.JobType == `` PurgeData '' //3 & & job.Status == JobStatus.Running //1 & & job.Id ! = currentJobId ) ) //2 return false ;
Order of evaluation c #
C_sharp : I was reading this page , which is officially referenced in the release notes of Visual Studio 17 RC , it states the following : For the purpose of Overloading Overriding Hiding , tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent . All other differences are immaterial . When overriding a member it is permitted to use tuple types with same or different field names than in the base member . A situation where same field names are used for non-matching fields between base and derived member signatures , a warning is reported by the compilerWhen giving that a shot : I get the following errors : Error CS8139 'Bar.AbstractTuple ( ( int c , string d ) ) ' : can not change tuple element names when overriding inherited member 'Foo.AbstractTuple ( ( int a , string b ) ) 'and Error CS8139 'Bar.OverrideTuple ( ( int c , string d ) ) ' : can not change tuple element names when overriding inherited member 'Foo.OverrideTuple ( ( int a , string b ) ) 'The Questions are : Is the official design Notes wrong ? Or is this a behavior that is yet to be implemented in the official C # 7.0 Release ? If this is the correct behavior , does it make sense that the tuple Field Names has to be the same in the overridden method ? Keeping in mind that two methods with same Tuples ( int a , int b ) and ( int c , int d ) are not considered overload candidates and generate an error ! Do we have official C # 7.0 Features documentation somewhere ? <code> public abstract class Foo { public abstract void AbstractTuple ( ( int a , string b ) tuple ) ; public virtual void OverrideTuple ( ( int a , string b ) tuple ) { Console.WriteLine ( $ '' First= { tuple.a } Second = { tuple.b } '' ) ; } } public class Bar : Foo { public override void AbstractTuple ( ( int c , string d ) tuple ) { Console.WriteLine ( $ '' First= { tuple.c } Second= { tuple.d } '' ) ; } public override void OverrideTuple ( ( int c , string d ) tuple ) { base.OverrideTuple ( tuple ) ; } }
Overriding Methods with Tuples and Field Name Rules in C # 7.0
C_sharp : I 'm trying to implement a search function in a custom ListView and as such I am hiding Items with a custom ObservableCollection which allows AddRange , similar to the one defined on damonpayne.com ( for the tl ; dr-ers out there basically it suppresses firing OnCollectionChanged event while adding multiple items then fires with NotifyCollectionChangedAction.Reset ) : The MyCollection_CollectionChanged ( ) populates base.Items : The idea is that when items do not fulfill the search terms , they are removed from base.Items ( i.e . System.Windows.Forms.ListView ) but remain in this.Items ( i.e . My.Name.Space.MyListView ) . When the search is cancelled or the terms change , base.Items can be repopulated by this.Items.This works fine and as expected except for one small but important caveat : The problem is that ListViewItems ' Group is not consistently being carried from this.Items to base.Items and as such all the items appear in the group `` Default '' .Any ideas as to why this is happening and how to fix it ? UpdateI 'm still stuck on this . Surely doing the .ToArray ( ) just creates a shallow copy of the Items so the Group should be preserved ? This has been confirmed by Maverik : I just called in Linqpad , and while the list reference is different , you 're right.. object references are same.Update 2Okay after some more investigating I 've found where it is happening.When adding ListViewItems to the MyCollection < ListViewItem > : I also checked this replacing MyCollection < with the normal ObservableCollection < and the same still occurs.Update 3 - SolutionPlease see my answer . <code> public new MyCollection < ListViewItem > Items { get ; protected set ; } this.BeginUpdate ( ) ; base.Items.Clear ( ) ; base.Items.AddRange ( this.Items.ToArray ( ) ) ; this.EndUpdate ( ) ; var item0 = new ListViewItem ( ) ; var item0.Group = this.Groups [ `` foo '' ] ; //here this.Items.Count = 0this.Items.Add ( item0 ) ; //here this.Items.Count = 1 with item0 having group `` foo '' var item1 = new ListViewItem ( ) ; var item1.Group = this.Groups [ `` bar '' ] ; //here this.Items.Count = 1 with item0 having group `` foo '' this.Items.Add ( item1 ) ; //here this.Items.Count = 2 with item0 having group `` null '' and item1 having group `` bar ''
ListViewItem 's group not being preserved through another collection
C_sharp : I 've been trying to shift myself into a more test driven methodology when writing my .net MVC based app . I 'm doing all my dependency injection using constructor-based injection . Thus far it 's going well , but I 've found myself doing something repeatedly and I 'm wondering if there is a better practice out there.Let 's say I want to test a Controller . It has a dependency on a Unit Of Work ( database ) object . Simple enough ... I write my controller to take that interface in its constructor , and my DI framework ( Ninject ) can inject it at runtime . Easy . Meanwhile in my unit test , I can manually construct my controller with a mocked-up database object . I like that I can write lots of individual self-contained tests that take care of all the object construction and testing.Now I 've moved on and started adding new features & functions to my Controller object . The Controller now has one or two more dependencies . I can write more tests using these 3 dependencies , but my older tests are all broken ( wo n't compile ) , as the compiler throws a whole bunch of errors like this : What I 've been doing ( which smells bad ) is going back and updating all my unit tests , changing the construction code , and adding null parameters for all the new dependencies that my old tests do n't care about , like this : From this : To this : This gets everything to compile and gets my tests to run again , but I do n't like the prospect of going back and editing tons of old tests just to change calls to my object constructors.Is there a better way to write your unit tests ( or a better way to write your classes and do DI ? ) so they do n't all break when you add a new dependency ? <code> 'MyProject.Web.Api.Controllers.MyExampleController ' does not contain a constructor that takes 3 arguments var controllerToTest = new MyExampleController ( mockUOW.Object ) ; var controllerToTest = new MyExampleController ( mockUOW.Object , null , null ) ;
Unit tests break when I add new dependency to controller
C_sharp : I was debugging resource leaks in my application and created a test app to test GDI object leaks . In OnPaint I create new icons and new bitmaps without disposing them . After that I check the increase of GDi objects in task manager for each of the cases . However , if I keep repainting the main window of my app , the number of GDI objects increases for icons , but there is no change for bitmaps . Is there any particular reason why icons are not getting cleaned up same way as bitmaps ? Test Result : No icons and bitmaps - 30 GDI objects With bitmaps - 31 GDI object , the number does n't change . With icons - 31 and then the number increases if you repaint the window . <code> public partial class MainForm : Form { public MainForm ( ) { InitializeComponent ( ) ; } protected override void OnPaint ( PaintEventArgs e ) { base.OnPaint ( e ) ; // 1. icon increases number of GDI objects used by this app during repaint . //var icon = Resources.TestIcon ; //e.Graphics.DrawIcon ( icon , 0 , 0 ) ; // 2. bitmap does n't seem to have any impact ( only 1 GDI object ) //var image = Resources.TestImage ; //e.Graphics.DrawImage ( image , 0 , 0 ) ; } }
Is there a difference in disposing Icon and Bitmap ?
C_sharp : I am really confused , take the following code : And yes I know that I could directly cast the integer to the given Enum , but this is a simplified version of my actual code which includes the work with generic extensions.Anyhow I ran a few performance tests , because I was curious which one is faster . I am using BenchmarkDotNet and see there : The dynamic version is actually faster and not just by a bit . I ran the test multiple times and I ca n't wrap my head around it.I looked at the compiled version , if there might be any optimization , but see here . Can anyone explain this to me ? <code> [ Benchmark ] public TEnum DynamicCast ( ) { return ( TEnum ) ( dynamic ) 0 ; } [ Benchmark ] public TEnum ObjectCast ( ) { return ( TEnum ) ( object ) 0 ; } [ Benchmark ] public TEnum DirectCast ( ) { return ( TEnum ) 0 ; } public enum TEnum { Foo , Bar } BenchmarkDotNet=v0.12.0 , OS=Windows 10.0.18362Intel Core i7-6700HQ CPU 2.60GHz ( Skylake ) , 1 CPU , 8 logical and 4 physical cores.NET Core SDK=3.1.100 [ Host ] : .NET Core 3.1.0 ( CoreCLR 4.700.19.56402 , CoreFX 4.700.19.56404 ) , X64 RyuJIT DefaultJob : .NET Core 3.1.0 ( CoreCLR 4.700.19.56402 , CoreFX 4.700.19.56404 ) , X64 RyuJIT| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated || -- -- -- -- -- -- | -- -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- - : | -- -- -- - : | -- -- -- : | -- -- -- : | -- -- -- -- -- : || DynamicCast | 8.2124 ns | 0.0803 ns | 0.0671 ns | 8.2134 ns | 0.0076 | - | - | 24 B || ObjectCast | 13.9178 ns | 0.4822 ns | 0.5922 ns | 13.6714 ns | 0.0076 | - | - | 24 B || DirectCast | 0.0538 ns | 0.0422 ns | 0.0534 ns | 0.0311 ns | - | - | - | - |
Why is casting with dynamic faster than with object
C_sharp : How can I change items in my double variable based on a simple condition ? Check this example : After executing the function setDouble ( ) , these values did n't change . No errors found . How can I fix this ? <code> public partial class Form1 : Form { double [ ] vk = new double [ 11 ] { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; ... ... void setDouble ( ) { if ( bunifuDropdown1.selectedIndex == 0 ) { double [ ] vk = new double [ 11 ] { 2 , 4.86 , 11.81 , 28.68 , 69.64 , 169.13 , 410.75 , 997.55 , 2422.61 , 5883.49 , 21000 } ; } if ( bunifuDropdown1.selectedIndex == 1 ) { double [ ] vk = new double [ 11 ] { 2 , 4.51 , 10.14 , 22.81 , 51.31 , 115.46 , 259.78 , 584.51 , 1315.14 , 2959.07 , 21000 } ; } if ( bunifuDropdown1.selectedIndex == 2 ) { double [ ] vk = new double [ 11 ] { 2 , 6.86 , 18.67 , 47.33 , 116.94 , 286.01 , 696.59 , 1693.71 , 4115.30 , 9996.29 , 21000 } ; } if ( bunifuDropdown1.selectedIndex == 3 ) { double [ ] vk = new double [ 11 ] { 2 , 6.51 , 16.64 , 39.43 , 90.72 , 206.12 , 465.78 , 1049.99 , 2364.49 , 5322.09 , 21000 } ; } if ( bunifuDropdown1.selectedIndex == 4 ) { double [ ] vk = new double [ 11 ] { 2 , 6.86 , 18.67 , 47.33 , 108.94 , 264.58 , 642.55 , 1560.47 , 3789.71 , 9203.58 , 21000 } ; } if ( bunifuDropdown1.selectedIndex == 5 ) { double [ ] vk = new double [ 11 ] { 2 , 6.51 , 16.64 , 39.43 , 82.72 , 186.12 , 418.78 , 942.24 , 2120.05 , 4770.11 , 21000 } ; } }
How can I change items inside a double array ?
C_sharp : My company is on a Unit Testing kick , and I 'm having a little trouble with refactoring Service Layer code . Here is an example of some code I wrote : In this simplified case ( it is reduced from a 1,000 line class that has 1 public method and ~30 private ones ) , my boss says I should be able to test my CalculateInvoice and UpdateLine separately ( UpdateLine actually calls 3 other private methods , and performs database calls as well ) . But how would I do this ? His suggested refactoring seemed a little convoluted to me : I can see how the dependency is now broken , and I can test both pieces , but this would also create 20-30 extra classes from my original class . We only calculate invoices in one place , so these pieces would n't really be reusable . Is this the right way to go about making this change , or would you suggest I do something different ? Thank you ! Jess <code> public class InvoiceCalculator : IInvoiceCalculator { public CalculateInvoice ( Invoice invoice ) { foreach ( InvoiceLine il in invoice.Lines ) { UpdateLine ( il ) ; } //do a ton of other stuff here } private UpdateLine ( InvoiceLine line ) { line.Amount = line.Qty * line.Rate ; //do a bunch of other stuff , including calls to other private methods } } //Tiny part of original codepublic class InvoiceCalculator : IInvoiceCalculator { public ILineUpdater _lineUpdater ; public InvoiceCalculator ( ILineUpdater lineUpdater ) { _lineUpdater = lineUpdater ; } public CalculateInvoice ( Invoice invoice ) { foreach ( InvoiceLine il in invoice.Lines ) { _lineUpdater.UpdateLine ( il ) ; } //do a ton of other stuff here } } public class LineUpdater : ILineUpdater { public UpdateLine ( InvoiceLine line ) { line.Amount = line.Qty * line.Rate ; //do a bunch of other stuff } }
Refactoring Service Layer classes
C_sharp : I have an object called Page , with an instance called p that has a custom property called AssociatedAttributes . If I do the following : numMatchingAttributes ends up equaling 0 even though p has 6 AssociatedAttributes . Why does it not equal 6 ? AssociatedAttributes is of Type List < Attribute > ( Attribute is my own class , not System.Attribute ) and Attribute implements IComparable < Attribute > , I did not have it implement IEquatable , should I ? This is the implementation of CompareTo in Attribute : Id is of type Guid.this is the AssociatedAttributes property on Page : ( dbContext is a Telerik OpenAccess context ) Update : Here is what ended up working : In Page is the following method : It 's ugly , but it works . <code> int numMatchingAttributes = p.AssociatedAttributes.Intersect ( p.AssociatedAttributes ) .Distinct ( ) .Count ( ) ; public int CompareTo ( Attribute other ) { return Id.CompareTo ( other.Id ) ; } public List < Attribute > AssociatedAttributes { get { List < Attribute > list = new List < Attribute > ( ) ; using ( PredictiveRecommendor dbContext = new PredictiveRecommendor ( ) ) { if ( dbContext ! = null ) { IQueryable < Attribute > query = from a in dbContext.PageAttributes where a.Page.Id.Equals ( this.Id ) select a.Attribute ; list = query.ToList ( ) ; } } return list ; } } public int numberOfIntersectedAssociatedAttributes ( Page other ) { using ( PredictiveRecommendor dbContext = new PredictiveRecommendor ( ) ) { IQueryable < Attribute > thisAssocAttributes = from a in dbContext.PageAttributes where a.Page.Id.Equals ( this.Id ) select a.Attribute ; IQueryable < Attribute > otherAssocAttributes = from a in dbContext.PageAttributes where a.Page.Id.Equals ( other.Id ) select a.Attribute ; IQueryable < Attribute > interSection = thisAssocAttributes.Intersect ( otherAssocAttributes ) ; return interSection.ToList ( ) .Count ; } }
Can someone explain LINQ 's intersect properly to me ? I do n't understand why this does n't work
C_sharp : Do the following 2 code snippets achieve the same thing ? My original code : What ReSharper thought was a better idea : I think the above code is much easier to read , any compelling reason to change it ? Would it execute faster , and most importantly , will the code do the exact same thing ? Also if you look at the : Convert.ToBoolean ( safeFileNames.Value ) ; section , then surely this could cause a null reference exception ? Local safeFileNames is a strongly typed custom object , here is the class : <code> if ( safeFileNames ! = null ) { this.SafeFileNames = Convert.ToBoolean ( safeFileNames.Value ) ; } else { this.SafeFileNames = false ; } this.SafeFileNames = safeFileNames ! = null & & Convert.ToBoolean ( safeFileNames.Value ) ; this.SafeFileNames = bool public class Configuration { public string Name { get ; set ; } public string Value { get ; set ; } }
Are these 2 statements identical ?
C_sharp : I have a sorted array of strings.Given a string that identifies a prefix , I perform two binary searches to find the first and last positions in the array that contain words that start with that prefix : Running this code I get firstPosition and lastPosition both equal to 1 , while the right answer is to have lastPosition equal to 3 ( i.e. , pointing to the first non-matching word ) .The BinarySearch method uses the CompareTo method to compare the objects and I have found thatmeaning that the two string are considered equal ! If I change the code withI get the right answer.Moreover I have found thatcorrectly ( with respect to my needs ) returns false.Could you please help me explaining the behavior of the CompareTo method ? I would like to have the CompareTo method to behave like the == , so that the BinarySearch method returns 3 for lastPosition . <code> string [ ] words = { `` aaa '' , '' abc '' , '' abcd '' , '' acd '' } ; string prefix = `` abc '' ; int firstPosition = Array.BinarySearch < string > ( words , prefix ) ; int lastPosition = Array.BinarySearch < string > ( words , prefix + char.MaxValue ) ; if ( firstPosition < 0 ) firstPosition = ~firstPosition ; if ( lastPosition < 0 ) lastPosition = ~lastPosition ; ( `` abc '' +char.MaxValue ) .CompareTo ( `` abc '' ) ==0 int lastPosition = Array.BinarySearch < string > ( words , prefix + `` z '' ) ; ( `` abc '' +char.MaxValue ) == ( `` abc '' )
Why ( `` abc '' +char.MaxValue ) .CompareTo ( `` abc '' ) ==0 ?
C_sharp : I have a list of objects that looks like this : now , I 'd like to browse ( traverse ) it with a for each . But I want to traverse it starting from the same ID . So , first a foreach for the single/unique ID ( 2000 , 3000 , 4000 , so 3 steps ) . Than , for each `` ID '' step , each Title/Description : so 2 steps for the ID 2000 , 1 for the ID 3000 and 3 for the ID 4000 . List is ordered by ID.How can I do it ? Group by ? Uhm ... <code> ID:2000Title : '' Title 1 '' Description : '' My name is Marco '' ID:2000Title : '' Title 2 '' Description : '' My name is Luca '' ID:3000Title : '' Title 3 '' Description : '' My name is Paul '' ID:4000Title : '' Title 4 '' Description : '' My name is Anthony '' ID:4000Title : '' Title 5 '' Description : '' My name is Carl '' ID:4000Title : '' Title 6 '' Description : '' My name is Jadett ''
How can I traverse this list in this manner ?
C_sharp : Is calling Array.Resize on an array that is being used as a buffer for SAEA threadsafe ? different threads all write to their own assigned part of the array , I just want to make the array bigger without locking once the initialized size runs out as connected users increase . <code> byte [ ] buffer ; //Accessedobject expand_Lock = new object ( ) ; public void AsyncAccept ( ) { //Lock here so we do n't resize the buffer twice at once lock ( expand_Lock ) { if ( bufferFull ) { Array.Resize ( buffer , buffer.Length + 2048 * 100 ) ; //Add space for 100 more args //Is Array.Resize threadsafe if buffer can be read/wrote to at anytime ? AssignMoreSAEA ( 2048 , 100 ) ; //irrelevant to question what this does } } }
Is Array.Resize ( .. ) threadsafe ?
C_sharp : I need to be able to say something like myString.IndexOf ( c = > ! Char.IsDigit ( c ) ) , but I ca n't find any such method in the .NET framework . Did I miss something ? The following works , but rolling my own seems a little tedious here : <code> using System ; class Program { static void Main ( ) { string text = `` 555ttt555 '' ; int nonDigitIndex = text.IndexOf ( c = > ! Char.IsDigit ( c ) ) ; Console.WriteLine ( nonDigitIndex ) ; } } static class StringExtensions { public static int IndexOf ( this string self , Predicate < char > predicate ) { for ( int index = 0 ; index < self.Length ; ++index ) { if ( predicate ( self [ index ] ) ) { return index ; } } return -1 ; } }
Is there a String.IndexOf that takes a predicate ?
C_sharp : I have a base class : And a class which stores the DomainEventSubscriber references : Even though the Subscribe method type is constrained , I can not convert from DomainEventSubscriber < T > subscriber where T : DomainEvent to DomainEventSubscriber < DomainEvent > : How would I go about performing this conversion , or am I setting myself up for a nasty code smell ? <code> public abstract class DomainEventSubscriber < T > where T : DomainEvent { public abstract void HandleEvent ( T domainEvent ) ; public Type SubscribedToEventType ( ) { return typeof ( T ) ; } } public class DomainEventPublisher { private List < DomainEventSubscriber < DomainEvent > > subscribers ; public void Subscribe < T > ( DomainEventSubscriber < T > subscriber ) where T : DomainEvent { DomainEventSubscriber < DomainEvent > eventSubscriber ; eventSubscriber = ( DomainEventSubscriber < DomainEvent > ) subscriber ; if ( ! this.Publishing ) { this.subscribers.Add ( eventSubscriber ) ; } } } eventSubscriber = ( DomainEventSubscriber < DomainEvent > ) subscriber ;
Convert generic parameter with 'where ' type constraint not possible ?
C_sharp : I created a SqlDependency so that an event would fire when the results of a particular query change.When this code executes , a stored procedure is automatically created with a name like SqlQueryNotificationStoredProcedure-82ae1b92-21c5-46ae-a2a1-511c4f849f76This procedure is unencrypted , which violates requirements I have been given . I have two options : Convince the customer that it does n't matter that the auto generated procedure is unencrypted because it only does cleanup work and contains no real information ( thanks to ScottChamberlain for pointing this out ) .Find a way to encrypt the stored procedure generated by SqlDependency.How can I accomplish option 2 ? Contents of the stored procedure in question : <code> // Create a commandSqlConnection conn = new SqlConnection ( connectionString ) ; string query = `` SELECT MyColumn FROM MyTable ; '' ; SqlCommand cmd = new SqlCommand ( query , conn ) cmd.CommandType = CommandType.Text ; // Register a dependencySqlDependency dependency = new SqlDependency ( cmd ) ; dependency.OnChange += DependencyOnChange ; CREATE PROCEDURE [ dbo ] . [ SqlQueryNotificationStoredProcedure-b124707b-23fc-4002-aac3-4d52a71c5d6b ] ASBEGIN BEGIN TRANSACTION ; RECEIVE TOP ( 0 ) conversation_handle FROM [ SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ] ; IF ( SELECT COUNT ( * ) FROM [ SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ] WHERE message_type_name = 'http : //schemas.microsoft.com/SQL/ServiceBroker/DialogTimer ' ) > 0 BEGIN IF ( ( SELECT COUNT ( * ) FROM sys.services WHERE NAME = 'SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ' ) > 0 ) DROP SERVICE [ SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ] ; IF ( OBJECT_ID ( 'SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ' , 'SQ ' ) IS NOT NULL ) DROP QUEUE [ SqlQueryNotificationService-b124707b-23fc-4002-aac3-4d52a71c5d6b ] ; DROP PROCEDURE [ SqlQueryNotificationStoredProcedure-b124707b-23fc-4002-aac3-4d52a71c5d6b ] ; END COMMIT TRANSACTION ; ENDGO
Encrypt the stored procedure created by SqlDependency
C_sharp : Visual Studio C # compiler warns about accidentally assigning a variable to itself , but this warning does not apply to C # properties , only variables . As described in this other question.However , I would really like something similar that can warn me at compile time if I assign a property to itself.I 'm currently using Visual Studio 2013 but I 'm ok if the solution works at least in Visual Studio 2015 . Also , I do n't use third-party commercial plugins like ReSharper or CodeRush so I would prefer a solution that does n't involve purchasing something , but I 'm open to suggestions.Do you know how could I accomplish this ? Background : I 'm very used to the constructor dependency injection pattern using readonly public `` inspection '' properties to store the received dependency . For example , assume a class Foo that depends on an ILogger implementation . The logger instance is provided to the class in the constructor , the constructor checks for nulls and stores the dependency in an instance property called Logger : However , I often make the typing mistake of assigning the property to itself instead of the parameter passed to the constructor.Of course I always end up catching these errors while testing and debugging , but it has bitten me several times already and I do n't want to keep wasting time in such a silly mistake anymore.Any suggestions ? <code> public class Foo { public ILogger Logger { get ; private set ; } public Foo ( ILogger logger ) { if ( logger == null ) throw new ArgumentNullException ( `` logger '' ) ; this.Logger = logger ; } } public class Foo { public ILogger Logger { get ; private set ; } public Foo ( ILogger logger ) { if ( logger == null ) throw new ArgumentNullException ( `` logger '' ) ; this.Logger = Logger ; // < -- This is wrong . Property assigned to itself . } }
Compile-time detection of accidentally assign a C # property to itself
C_sharp : Here 's a bit of a tricky one . Perhaps someone 's C # -fu is superior to mine , as I could n't find a solution.I have a method that takes a parameter that holds either an enum or a string indicating the value of an Enum and returns an instance of that enum . It 's basically an implementation of Enum.Parse but implemented as a generic method . Why the .NET Framework does n't have this built in is beyond me.Now , I can do something like : And get an instance of MyEnum . If obj is null , I throw an exception.However , sometimes obj is null and I want to allow that . In this case , I 'd like to be able to do : However , for the life of me , I ca n't figure out a way to get that working . First off , even though Nullable < MyEnum > is a struct , it 's unable to be used as a type parameter to Parse < T > . I think this has something to do with all the magic the compiler does with Nullable < > , so I wo n't question it.It does n't appear you can overload the method and only differentiate it based on constraints on T. For example , if I do : I 'll get the error : Member with the same signature is already declaredSo , that leaves me with only one option left : Implement a entirely separate method designed for nullable types : I can now call this with : My Question : Is there a way to combine these two methods into a single method that will do the right thing depending on the type parameter , or create overloads where one overload will be used in the case where the type parameter is Nullable < > and the other overload called when it 's not ? <code> public static T Parse < T > ( object value ) where T : struct { if ( ! typeof ( T ) .IsEnum ) throw new ArgumentException ( `` T must be an Enum type . `` ) ; if ( value == null || value == DBNull.Value ) { throw new ArgumentException ( `` Can not parse enum , value is null . `` ) ; } if ( value is String ) { return ( T ) Enum.Parse ( typeof ( T ) , value.ToString ( ) ) ; } return ( T ) Enum.ToObject ( typeof ( T ) , value ) ; } MyEnum foo = Parse < MyEnum > ( obj ) ; MyEnum ? foo = Parse < MyEnum ? > ( obj ) ; public static T Parse < T > ( object value ) where T : new ( ) { // This should be called if I pass in a Nullable , in theory } public static T ? ParseNullable < T > ( object value ) where T : struct { if ( ! typeof ( T ) .IsEnum ) throw new ArgumentException ( `` T must be an Enum type . `` ) ; if ( value == null || value == DBNull.Value ) return null ; if ( value is String ) return Enum.Parse ( typeof ( T ) , value.ToString ( ) ) as T ? ; return Enum.ToObject ( typeof ( T ) , value ) as T ? ; } MyEnum ? foo = ParseNullable < T > ( obj ) ;
Is there any way to combine these two methods into one method , or overloaded methods ?
C_sharp : It is conventional to name namespaces in a C # solution such that they match the default namespace for the project plus the name of any sub-directories for the containing file.For example , a file called Haddock.cs is in a directory called Fish and the default namespace ( in the first tab of the project 's properties in VS ) is Lakes then the file should contain something likeThe StyleCop analyzers project contains a nice rule that validates that the class name matches the file name.Is there any way I can write a rule that verifies that the namespace name is correct ? <code> namespace Lakes.Fish { public class Haddock { } }
Can an analyzer validate that namespaces properly match the file location
C_sharp : I 'm looking to retrieve the last row of a table by the table 's ID column . What I am currently using works : Is there any way to get the same result with more efficient speed ? <code> var x = db.MyTable.OrderByDescending ( d = > d.ID ) .FirstOrDefault ( ) ;
What 's the most efficient way to get only the final row of a SQL table using EF4 ?
C_sharp : I 'm writing a small data structures library in C # , and I 'm running into an architectural problem . Essentially I have a class which implements the visitor pattern , and there are many possible implementations of visitors : Anytime I want to pass in a visitor , I have to create a visitor class , implement the interface , and pass it in like this : I do n't like writing that much boilerplate code , because it gets very messy when you have a non-trivial number of visitor implementations.I want to write something similar to anonymous classes Java ( concept code ) : Is there any way to simulate anonymous classes with interface implementations in C # ? <code> public interface ITreeVisitor < T , U > { U Visit ( Nil < T > s ) ; U Visit ( Node < T > s ) ; } public abstract class Tree < T > : IEnumerable < T > { public readonly static Tree < T > empty = new Nil < T > ( ) ; public abstract U Accept < U > ( ITreeVisitor < T , U > visitor ) ; } public sealed class Nil < T > : Tree < T > { public override U Accept < U > ( ITreeVisitor < T , U > visitor ) { return visitor.Visit ( this ) ; } } public sealed class Node < T > : Tree < T > { public Tree < T > Left { get ; set ; } public T Value { get ; set ; } public Tree < T > Right { get ; set ; } public override U Accept < U > ( ITreeVisitor < T , U > visitor ) { return visitor.Visit ( this ) ; } } class InsertVisitor < T > : ITreeVisitor < T , Tree < T > > where T : IComparable < T > { public T v { get ; set ; } ; public Tree < T > Visit ( Nil < T > s ) { return new Node < T > ( ) { Left = Tree < T > .empty , Value = v , Right = Tree < T > .empty } ; } public Tree < T > Visit ( Node < T > s ) { switch ( v.CompareTo ( s.Value ) ) { case -1 : return new Node < T > ( ) { Left = Insert ( v , s.Left ) , Value = s.Value , Right = s.Right } ; case 1 : return new Node < T > ( ) { Left = s.Left , Value = s.Value , Right = Insert ( v , s.Right ) } ; default : return s ; } } } public static Tree < T > Insert < T > ( T value , Tree < T > tree ) where T : IComparable < T > { return tree.Accept < Tree < T > > ( new InsertVisitor < T > ( ) { v = value } ) ; } public static Tree < T > Insert < T > ( T v , Tree < T > tree ) where T : IComparable < T > { return tree.Accept < Tree < T > > ( new InsertVisitor < T > ( ) { public Tree < T > Visit ( Nil < T > s ) { return new Node < T > ( ) { Left = Tree < T > .empty , Value = v , Right = Tree < T > .empty } ; } public Tree < T > Visit ( Node < T > s ) { switch ( v.CompareTo ( s.Value ) ) { case -1 : return new Node < T > ( ) { Left = Insert ( v , s.Left ) , Value = s.Value , Right = s.Right } ; case 1 : return new Node < T > ( ) { Left = s.Left , Value = s.Value , Right = Insert ( v , s.Right ) } ; default : return s ; } } } ; }
How do I simulate anonymous classes in C #
C_sharp : I am trying to create text that looks like this in WPF : Notice that it is yellow text , with a black stroke , then a yellow stroke , then another ( very thin ) black stroke . Now , I can create a single stroke with little difficult by following How to : Create Outlined Text . Note that the properties not shown are all DP 's of the containing control.So my question is , how do I take that and add another ( or several other ) stroke ( s ) to it ? <code> protected override void OnRender ( System.Windows.Media.DrawingContext drawingContext ) { // Draw the outline based on the properties that are set . drawingContext.DrawGeometry ( Fill , new System.Windows.Media.Pen ( Stroke , StrokeThickness ) , _textGeometry ) ; } /// < summary > /// Create the outline geometry based on the formatted text . /// < /summary > public void CreateText ( ) { System.Windows.FontStyle fontStyle = FontStyles.Normal ; FontWeight fontWeight = FontWeights.Medium ; if ( Bold == true ) fontWeight = FontWeights.Bold ; if ( Italic == true ) fontStyle = FontStyles.Italic ; // Create the formatted text based on the properties set . FormattedText formattedText = new FormattedText ( Text , CultureInfo.GetCultureInfo ( `` en-us '' ) , FlowDirection.LeftToRight , new Typeface ( Font , fontStyle , fontWeight , FontStretches.Normal ) , FontSize , System.Windows.Media.Brushes.Black ) ; // Build the geometry object that represents the text . _textGeometry = formattedText.BuildGeometry ( new System.Windows.Point ( 0 , 0 ) ) ; }
How do you create multiple strokes on text in WPF ?
C_sharp : I have a set of classes with the same functions but with different logic . However , each class function can return a number of objects . It is safe to set the return type as the interface ? Each class ( all using the same interface ) is doing this with different business logic.Are there any pitfalls with unit testing the return type of an function ? Also , is it considered bad design to have functions needing to be run in order for them to succeed ? In this example , Validate ( ) would have to be run before IsValid ( ) or else IsValid ( ) would always return false.Thank you . <code> protected IMessage validateReturnType ; < -- This is in an abstract classpublic bool IsValid ( ) < -- This is in an abstract class { return ( validateReturnType.GetType ( ) == typeof ( Success ) ) ; } public IMessage Validate ( ) { if ( name.Length < 5 ) { validateReturnType = new Error ( `` Name must be 5 characters or greater . `` ) ; } else { validateReturnType = new Success ( `` Name is valid . `` ) ; } return validateReturnType ; }
Is it advisable to have an interface as the return type ?
C_sharp : Which one is better to use ? ORint xyz= default ( int ) ; <code> int xyz = 0 ;
Which one is better to use and why in c #
C_sharp : I have a file that looks something like this : I need to break the file up into multiple files based on the first 6 characters starting in position 2.File 1 named 29923c.asc : File 2 named 47422K.asc : File 3 named 9875D.asc : I do n't know what will be in the file before the program gets it , just the format . The 6 digits will change depending on the customer . I do n't know what they will be.The only thing I know is the format.Can anyone give me a suggestion as to how to dynamically obtain\maintain this information so that I can parse it out into individual files ? <code> |29923C|SomeGuy , NameHere1 |00039252|042311|Some Address Info Here ||47422K|SomeGuy , NameHere2 |00039252|042311|Some Address Info Here ||98753D|SomeGuy , NameHere3 |00039252|042311|Some Address Info Here ||29923C|SomeGuy , NameHere4 |00039252|042311|Some Address Info Here ||47422K|SomeGuy , NameHere5 |00039252|042311|Some Address Info Here | |29923C|SomeGuy , NameHere1 |00039252|042311|Some Address Info Here ||29923C|SomeGuy , NameHere4 |00039252|042311|Some Address Info Here | |47422K|SomeGuy , NameHere5 |00039252|042311|Some Address Info Here ||47422K|SomeGuy , NameHere2 |00039252|042311|Some Address Info Here | |98753D|SomeGuy , NameHere3 |00039252|042311|Some Address Info Here |
C # Text File Input Multi-File Output
C_sharp : For those who are not sure what is meant by 'constrained non-determinism ' I recommend Mark Seeman 's post.The essence of the idea is the test having deterministic values only for data affecting SUT behavior . Not 'relevant ' data can be to some extent 'random'.I like this approach . The more data is abstract the more clear and expressive expectations become and indeed it becomes harder to unconsciously fit data to the test.I 'm trying to 'sell ' this approach ( along with AutoFixture ) to my colleagues and yesterday we had a long debate about it.They proposed interesting argument about not stable hard to debug tests due to random data.At first that seemed bit strange because as we all agreed that flow affecting data must n't be random and such behavior is not possible . Nonetheless I took a break to thoroughly think over that concern.And I finally came to the following problem : But some of my assumptions first : Test code MUST be treated as production code.Test code MUST must express correct expectations and specifications of system behavior.Nothing warns you about inconsistencies better than broken build ( either not compiled or just failed tests - gated check-in ) .consider these two variants of the same test : So far so god , everything works and life is beautiful but then requirements change and DoSomething changes its behavior : now it increases input only if it'is lower than 10 , and multiplies by 10 otherwise.What happens here ? The test with hardcoded data passes ( actually accidentally ) , whereas the second test fails sometimes . And they both are wrong deceiving tests : they check nonexistent behavior.Looks like it does n't matter either data is hardcoded or random : it 's just irrelevant . And yet we have no robust way to detect such 'dead ' tests.So the question is : Has anyone good advice how to write tests in the way such situations do not appear ? <code> [ TestMethod ] public void DoSomethig_RetunrsValueIncreasedByTen ( ) { // Arrange ver input = 1 ; ver expectedOutput = input+10 ; var sut = new MyClass ( ) ; // Act var actualOuptut = sut.DoeSomething ( input ) ; // Assert Assert.AreEqual ( expectedOutput , actualOutput , '' Unexpected return value . `` ) ; } /// Here nothing is changed besides input now is random . [ TestMethod ] public void DoSomethig_RetunrsValueIncreasedByTen ( ) { // Arrange var fixture = new Fixture ( ) ; ver input = fixture.Create < int > ( ) ; ver expectedOutput = input+10 ; var sut = new MyClass ( ) ; // Act var actualOuptut = sut.DoeSomething ( input ) ; // Assert Assert.AreEqual ( expectedOutput , actualOutput , '' Unexpected return value . `` ) ; }
Detecting 'dead ' tests and hardcoded data vs constrained non-determinism
C_sharp : can anyone explain why the TextBlock inside my DataTemplate does not apply the style defined in my UserControl.Resources element , but the second TextBlock ( 'Test B ' ) does ? I think it may have to do with a dependency property somewhere set to not inherit , but I ca n't be sure . <code> < UserControl.Resources > < Style TargetType= '' { x : Type TextBlock } '' > < Setter Property= '' Padding '' Value= '' 8 2 '' / > < /Style > < /UserControl.Resources > < StackPanel > < ItemsControl ItemsSource= '' { Binding } '' > < ItemsControl.ItemTemplate > < DataTemplate > < ! -- Padding does not apply -- > < TextBlock > Test A < /TextBlock > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > < ! -- Padding applies -- > < TextBlock > Test B < /TextBlock > < /StackPanel >
No Style Inheritance Inside ItemsControl / DataTemplate in WPF ?
C_sharp : I am trying to get into C # generics and have created a state machine with the state pattern and now I try to refactor.I have a state , which has a reference to the object it 's working on.and I have the object which has states , this should have a reference to its current state.But it does not work ( `` the type can not be used as type parameter 't ' in the generic type or method '' ) .What I want to achieve is something like this : Is this possible ? If it 's not this way , is there another ? Thx . <code> public abstract class AbstractState < T > where T : StatefulObject { protected T statefulObject ; public AbstractState ( T statefulObject ) { this.statefulObject = statefulObject ; } } public abstract class StatefulObject < T > : MonoBehaviour where T : AbstractState < StatefulObject < T > > { public T state ; } public class Monster : StatefulObject < MonsterState > { } public abstract class MonsterState : AbstractState < Monster > { }
C # generics , cross referencing classes for state pattern
C_sharp : Consider the following attribute.When I try to use the attribute [ Nice ( Stuff = `` test '' ) ] the compiler gives the following error . 'Stuff ' is not a valid named attribute argument . Named attribute arguments must be fields which are not readonly , static , or const , or read-write properties which are public and not static.What is the rational behind the requirement for the property to be readable ? UpdateI will try to sketch my use case for having write-only properties on attributes.There may be other implementations of ISettingsBuilder . For example one that offers a nice API to build settings through code.I ended up with implementing my getters by throwing a NotImplementedException.Can you think of a nicer way to do something like this ? <code> internal class NiceAttribute : Attribute { private string _stuff ; public string Stuff { set { _stuff = value ; } } } interface ISettingsBuilder { Settings GetSettings ( ) ; } class SettingsAttribute : Attribute , ISettingsBuilder { private readonly IDictionary < string , object > _settings = new Dictionary < string , object > ( ) ; public Settings GetSettings ( ) { // Use _settings to create an immutable instance of Settings } public string Stuff { set { _settings [ `` Stuff '' ] = value ; } } // More properties ... } public string Stuff { get { throw new NotImplementedException ( ) ; } set { _settings [ `` Stuff '' ] = value ; } }
Why do properties of attributes have to be readable ?
C_sharp : I 'm working my way through this ASP MVC tutorial . This page of the tutorial deals with writing a simple `` search '' page . The controller contains this method : According to MSDN , String.Contains is case-sensitive . But when I navigate to [ website url ] /Movies/SearchIndex ? searchString=mel , it returns a movie with the title Melancholia as a result . If I inspect the controller method in the debugger , searchString is mel ( in lower case ) as expected.Why does String.Contains match this title case-insensitively ? <code> public ActionResult SearchIndex ( string searchString ) { var movies = from m in db.Movies select m ; if ( ! String.IsNullOrEmpty ( searchString ) ) { movies = movies.Where ( s = > s.Title.Contains ( searchString ) ) ; } return View ( movies ) ; }
Why is String.Contains case-insensitive in this query ?
C_sharp : I have a Json string : I 'm using James Newton-King 's Json.NET parser and calling : Where my classes are defined as follows : This all works , but the original list might have different JackFactions rather than B , P , N and H. Ideally what I 'd like to get is : Without changing the Json string , how can I get the JackFactions as a list rather than individual objects ? <code> { `` B '' : { `` JackID '' : `` 1 '' , `` Faction '' : `` B '' , `` Regard '' : `` 24 '' , `` Currency '' : `` 1340 '' , `` factionName '' : `` Buccaneer '' , `` factionKing '' : `` 22 '' , `` Tcurrency '' : `` 0 '' , `` currencyname '' : `` Pieces of Eight '' , `` textcolor '' : `` # FFFFFF '' , `` bgcolor '' : `` # 000000 '' } , `` P '' : { `` JackID '' : `` 1 '' , `` Faction '' : `` P '' , `` Regard '' : `` 20 '' , `` Currency '' : `` 250 '' , `` factionName '' : `` Privateer '' , `` factionKing '' : `` 4 '' , `` Tcurrency '' : `` 0 '' , `` currencyname '' : `` Privateer Notes '' , `` textcolor '' : `` # 000000 '' , `` bgcolor '' : `` # FFFF00 '' } , `` N '' : { `` JackID '' : `` 1 '' , `` Faction '' : `` N '' , `` Regard '' : `` 12 '' , `` Currency '' : `` 0 '' , `` factionName '' : `` Navy '' , `` factionKing '' : `` 7 '' , `` Tcurrency '' : `` 0 '' , `` currencyname '' : `` Navy Chits '' , `` textcolor '' : `` # FFFFFF '' , `` bgcolor '' : `` # 77AADD '' } , `` H '' : { `` JackID '' : `` 1 '' , `` Faction '' : `` H '' , `` Regard '' : `` -20 '' , `` Currency '' : `` 0 '' , `` factionName '' : `` Hiver '' , `` factionKing '' : `` 99 '' , `` Tcurrency '' : `` 0 '' , `` currencyname '' : `` '' , `` textcolor '' : `` # 000000 '' , `` bgcolor '' : `` # CC9900 '' } } JackFactionList jackFactionList = JsonConvert.DeserializeObject < JackFactionList > ( sJson ) ; namespace Controller { public class JackFactionList { public JackFaction B ; public JackFaction P ; public JackFaction N ; public JackFaction H ; } public class JackFaction { public int JackId { get ; set ; } public string Faction { get ; set ; } public int Regard { get ; set ; } public int Currency { get ; set ; } // Faction details public string factionName { get ; set ; } public string factionKing { get ; set ; } public int Tcurrency { get ; set ; } public string currencyname { get ; set ; } public string textcolor { get ; set ; } public string bgcolor { get ; set ; } } } public class JackFactionList { public List < JackFaction > factionList ; }
Deserialize Json when number of objects is unknown
C_sharp : I am trying to create a method for ( at runtime ) creating wrappers for delegates of all types . This to create a flexible way of injecting additional logging ( in this case ) . In this first step i tried to create a try-catch wrap around the given input-argument.I am using a generic method call CreateWrapper2 ( see below ) For void-methods ( like Action < > ) this code does what i need . But when there is a return value i get the exception `` variable `` of type 'System.Boolean ' referenced from scope `` , but it is not defined '' Many other posts talk about Expression.Parameter called more than once for a parameter ; to me it look like here is something else is wrong here but i ca n't find it . All goes well untill the .Compile line , there it crashes.For a Func < int , bool > target = i = > i % 2 ==0 ; below is the DebugView for the generated expression.What am i missing ? ( during the debugging hours i tried : moving the Expression.Variable from inside the try-body to the toplevel.gave the catch-block the same Body.Type as the try-block via the typed-Expression.Return . ) <code> try { Console.WriteLine ( ... . ) ; // Here the original call Console.WriteLine ( ... . ) ; } catch ( Exception ex ) { Console.WriteLine ( ... .. ) ; } private static readonly MethodInfo ConsoleWriteLine = typeof ( Console ) .GetMethod ( `` WriteLine '' , new [ ] { typeof ( string ) , typeof ( object [ ] ) } ) ; private static MethodCallExpression WriteLinExpression ( string format , params object [ ] args ) { Expression [ ] expressionArguments = new Expression [ 2 ] ; expressionArguments [ 0 ] = Expression.Constant ( format , typeof ( string ) ) ; expressionArguments [ 1 ] = Expression.Constant ( args , typeof ( object [ ] ) ) ; return Expression.Call ( ConsoleWriteLine , expressionArguments ) ; } public T CreateWrapper2 < T > ( T input ) { Type type = typeof ( T ) ; if ( ! typeof ( Delegate ) .IsAssignableFrom ( type ) ) { return input ; } PropertyInfo methodProperty = type.GetProperty ( `` Method '' ) ; MethodInfo inputMethod = methodProperty ! = null ? ( MethodInfo ) methodProperty.GetValue ( input ) : null ; if ( inputMethod == null ) { return input ; } string methodName = inputMethod.Name ; ParameterInfo [ ] parameters = inputMethod.GetParameters ( ) ; ParameterExpression [ ] parameterExpressions = new ParameterExpression [ parameters.Length ] ; // TODO : Validate/test parameters , by-ref /out with attributes etc . for ( int idx = 0 ; idx < parameters.Length ; idx++ ) { ParameterInfo parameter = parameters [ idx ] ; parameterExpressions [ idx ] = Expression.Parameter ( parameter.ParameterType , parameter.Name ) ; } bool handleReturnValue = inputMethod.ReturnType ! = typeof ( void ) ; ParameterExpression variableExpression = handleReturnValue ? Expression.Variable ( inputMethod.ReturnType ) : null ; MethodCallExpression start = WriteLinExpression ( `` Starting ' { 0 } ' . `` , methodName ) ; MethodCallExpression completed = WriteLinExpression ( `` Completed ' { 0 } ' . `` , methodName ) ; MethodCallExpression failed = WriteLinExpression ( `` Failed ' { 0 } ' . `` , methodName ) ; Expression innerCall = Expression.Call ( inputMethod , parameterExpressions ) ; LabelTarget returnTarget = Expression.Label ( inputMethod.ReturnType ) ; LabelExpression returnLabel = Expression.Label ( returnTarget , Expression.Default ( returnTarget.Type ) ) ; ; GotoExpression returnExpression = null ; if ( inputMethod.ReturnType ! = typeof ( void ) ) { // Handle return value . innerCall = Expression.Assign ( variableExpression , innerCall ) ; returnExpression = Expression.Return ( returnTarget , variableExpression , returnTarget.Type ) ; } else { returnExpression = Expression.Return ( returnTarget ) ; } List < Expression > tryBodyElements = new List < Expression > ( ) ; tryBodyElements.Add ( start ) ; tryBodyElements.Add ( innerCall ) ; tryBodyElements.Add ( completed ) ; if ( returnExpression ! = null ) { tryBodyElements.Add ( returnExpression ) ; } BlockExpression tryBody = Expression.Block ( tryBodyElements ) ; BlockExpression catchBody = Expression.Block ( tryBody.Type , new Expression [ ] { failed , Expression.Rethrow ( tryBody.Type ) } ) ; CatchBlock catchBlock = Expression.Catch ( typeof ( Exception ) , catchBody ) ; TryExpression tryBlock = Expression.TryCatch ( tryBody , catchBlock ) ; List < Expression > methodBodyElements = new List < Expression > ( ) ; if ( variableExpression ! = null ) methodBodyElements.Add ( variableExpression ) ; methodBodyElements.Add ( tryBlock ) ; methodBodyElements.Add ( returnLabel ) ; Expression < T > wrapperLambda = Expression < T > .Lambda < T > ( Expression.Block ( methodBodyElements ) , parameterExpressions ) ; Console.WriteLine ( `` lambda : '' ) ; Console.WriteLine ( wrapperLambda.GetDebugView ( ) ) ; return wrapperLambda.Compile ( ) ; } .Lambda # Lambda1 < System.Func ` 2 [ System.Int32 , System.Boolean ] > ( System.Int32 $ i ) { .Block ( ) { $ var1 ; .Try { .Block ( ) { .Call System.Console.WriteLine ( `` Starting ' { 0 } ' . `` , .Constant < System.Object [ ] > ( System.Object [ ] ) ) ; $ var1 = .Call LDAP.LdapProgram. < Main > b__0 ( $ i ) ; .Call System.Console.WriteLine ( `` Completed ' { 0 } ' . `` , .Constant < System.Object [ ] > ( System.Object [ ] ) ) ; .Return # Label1 { $ var1 } } } .Catch ( System.Exception ) { .Block ( ) { .Call System.Console.WriteLine ( `` Failed ' { 0 } ' . `` , .Constant < System.Object [ ] > ( System.Object [ ] ) ) ; .Rethrow } } ; .Label .Default ( System.Boolean ) .LabelTarget # Label1 : } }
`` variable `` of type 'System.Boolean ' referenced from scope `` , but it is not defined '' in Expression
C_sharp : I know this code does not work ( and have no problems writing it in a way that will work ) . I was wondering how the compiler can build with out any errors . And you get run time errors if you where to run it ? ( assuming data was not null ) <code> using System ; using System.Collections.Generic ; public class Class1 { public void Main ( ) { IEnumerable < IEnumerable < Foo > > data = null ; foreach ( Foo foo in data ) { foo.Bar ( ) ; } } } public class Foo { public void Bar ( ) { } }
Why is the C # compiler happy with double IEnumerable < T > and foreach T ?
C_sharp : I 'm doing a component to format a list , it is an Extension , I wrote the following code , but , when in execution time , it gives me the error : Can not convert lambda expression to type 'System.Web.WebPages.HelperResult ' because it is not a delegate typeThis is the extension : View calling : I already tried to change from HelperResult to dynamic , but did n't work too.I do n't want to use only Func < object , HelperResult > as suggested in some posts in StackOverFlow , because , there will be items inside the < text > < /text > , that needs to be strongly typed as an item of ListType.The format can be different in my views , so I ca n't use a template to ListType.Is there a way to do that , even that not using the expression ? Thanks <code> public static MvcHtmlString FormatMyList < TModel , TValue > ( this HtmlHelper < TModel > htmlHelper , IEnumerable < TValue > list , Expression < Func < TValue , System.Web.WebPages.HelperResult > > formatExp = null ) { foreach ( var item in list ) { var itemFormated = formatExp.Compile ( ) .Invoke ( item ) .ToString ( ) ; } return new MvcHtmlString ( `` '' ) ; } var test = Html.FormatMyList < ModelType , ListType > ( list , formatExp : x = > @ < text > This is format of @ x.Cambio to test @ x.Fala < /text > ) ;
Expression of HelperResult to format item from a list
C_sharp : I have a collection of nullable ints . Why does compiler allows to iteration variable be of type int not int ? ? Of course I should pay attention to what I iterate through but it would be nice if compiler reprimanded me : ) Like here : <code> List < int ? > nullableInts = new List < int ? > { 1,2,3 , null } ; List < int > normalInts = new List < int > ( ) ; //Runtime exception when encounter null value //Why not compilation exception ? foreach ( int i in nullableInts ) { //do sth } foreach ( bool i in collection ) { // do sth } //Error 1 Can not convert type 'int ' to 'bool '
Iteration variable of different type than collection ?
C_sharp : After all the fuss about non-generic classes being obsolete ( well almost ) why are .NET collection classes still non-generic ? For instance , Control.ControlCollection does n't implement IList < T > but only IList , or FormCollection implements only upto ICollection and not ICollection < T > . Everytime I have to do some cool operation available on IEnumerable < T > or avail Linq niceties , I have to invariably convert the collection classes to its equivalent generic type like this : Its weird to have to specify Control in an operation like this on ControlCollection when the only thing it can hold is again a Control.Is it to maintain backward compatibility , considering these collections existed back in .Net 1.1 days ? Even if it is , why cant these collections ( there are many many more ) further implement generic interfaces along with the existing ones which I believe wouldnt break backward compatibility . I am unsure if I am missing something key to generics , may be I am not thorough with the idea..Edit : Though I asked this when I had only WinForms in mind , I find this applies to newer technologies like WPF too . As @ Dennis points out WPF too has non-generic collections . For instance WindowCollection or the ItemCollection . WPF was released along .NET 3 , but generics was introduced in .NET 2 : -oUpdate to this : There is a ticket for this now : https : //github.com/dotnet/winforms/issues/2644 ( .NET Core of course ) . <code> this.Controls.OfType < Control > ( ) ;
Why are collections classes in .NET not generic ?
C_sharp : How flexible is DataBinding in WPF ? I am new to WPF and would like to have a clear idea . Can I Bind a string variable with a Slider value ? Does it always have to be a control ? Is it at all possible to bind a string value with a Slider control so that it updates in real time ? How far up the Logical tree does the update travel or do we have to reissue all the commands to use this new value ? That was my hurried question earlier . I am posting a detailed problem . What I am trying to do is , I have an application with multiple user-controls . These user controls are grid-views and contain controls ( TextBox , Button ) and sections of my application UI . I used this approach to split my main XAML file across multiple files and it works for me till now . Now , I have a Slider in one user control and want to bind a String variable in another user control . The string variable is read-only so there is no use for two-way binding.I hope that makes my question clear . In my code , I am trying to update the variable zoomFactor in : with a Slider control . For those who could spot that , yes , it is the Google Static Maps API and yes , I am trying to zoom into the map with a slider . <code> URLQuery.Append ( `` & zoom= '' + zoomFactor + `` & size=600x500 & format=jpg & sensor=false '' ) ;
How flexible is DataBinding in WPF ?
C_sharp : I am trying to convert a 10,000 by 10,000 int array to double array with the following method ( I found in this website ) and the way I call isit gives me this error , The machine has 32GB RAM , OS is MAC OS 10.6.8 <code> public double [ , ] intarraytodoublearray ( int [ , ] val ) { int rows= val.GetLength ( 0 ) ; int cols = val.GetLength ( 1 ) ; var ret = new double [ rows , cols ] ; for ( int i = 0 ; i < rows ; i++ ) { for ( int j = 0 ; j < cols ; j++ ) { ret [ i , j ] = ( double ) val [ i , j ] ; } } return ret ; } int bound0 = myIntArray.GetUpperBound ( 0 ) ; int bound1 = myIntArray.GetUpperBound ( 1 ) ; double [ , ] myDoubleArray = new double [ bound0 , bound1 ] ; myDoubleArray = intarraytodoublearray ( myIntArray ) ; Unhandled Exception : OutOfMemoryException [ ERROR ] FATAL UNHANDLED EXCEPTION : System.OutOfMemoryException : Out of memoryat ( wrapper managed-to-native ) object : __icall_wrapper_mono_array_new_2 ( intptr , intptr , intptr )
intArray to doubleArray , Out Of Memory Exception C #
C_sharp : I am using ArangoDB and I am querying a collection named movies . Its data structure is such that categories is a List of strings . Here is the query statement : id is passed as a param and I need to retrieve all the movies that has the category matched by the id.However , above code does n't work as result gives me ALL the movies in the collection.The weird thing is when I loop through the items in the result , the same function does return false for some of the items . But it just does n't work in the Linq statement.Anybody knows what is wrong with my query statement ? <code> public class movies { [ DocumentProperty ( Identifier = IdentifierType.Key ) ] public string Key ; public List < string > categories ; public string desc ; public string img ; public List < vod_stream > streams ; public string title ; } ; var result = db.Query < movies > ( ) .Where ( p = > p.categories.Contains ( id ) ) ; foreach ( movies mov in result ) { if ( mov.categories.Contains ( id ) == false ) { continue ; } // do something here }
Linq List Contains
C_sharp : I 'm having an issue trying to create indexes on RavenDB 3.5When creating more than 3 indexes the application just dies , getting a Unable to connect to the remote server Status Code : ConnectFailureThe index creation code is farely straight forward : But the same happens if the IndexCreation.CreateIndexes ( typeof ( MyIndexClass ) .Assembly , store ) ; method is called . This happens with any 3 indexes from the list on any order.Full stack-trace is this : exception { `` A task was canceled . '' } Data : { System.Collections.ListDictionaryInternal } Etag : null HResult : -2146233088 HelpLink : null InnerException : null Message : `` A task was canceled . '' Response : { StatusCode : 503 , ReasonPhrase : 'Service Unavailable ' , Version : 1.1 , Content : , Headers : { } } ResponseString : `` Unable to connect to the remote server Status Code : ConnectFailure '' Source : `` Raven.Client.Lightweight '' StackTrace : `` at Raven.Client.Connection.Implementation.HttpJsonRequest. < > c__DisplayClass36_0. < b__0 > d.MoveNext ( ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Implementation\HttpJsonRequest.cs : line 258 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Client.Connection.Implementation.HttpJsonRequest.d__381.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs : line 312 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Client.Connection.Implementation.HttpJsonRequest. < ReadResponseJsonAsync > d__35.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Implementation\\HttpJsonRequest.cs : line 221 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Client.Connection.Async.AsyncServerClient. < > c__DisplayClass69_0. < < GetIndexAsync > b__0 > d.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\Async\\AsyncServerClient.cs : line 726 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Client.Connection.ReplicationInformerBase1.d__341.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs : line 417 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd ( Task task ) at Raven.Client.Connection.ReplicationInformerBase1.d__331.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Client.Lightweight\\Connection\\ReplicationInformerBase.cs : line 316 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Client.Connection.Async.AsyncServerClient. < ExecuteWithReplication > d__1641.MoveNext ( ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\Async\AsyncServerClient.cs : line 0 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Raven.Abstractions.Util.AsyncHelpers. < > c__DisplayClass1_11. < < RunSync > b__0 > d.MoveNext ( ) in C : \\Builds\\RavenDB-Stable-3.5\\Raven.Abstractions\\Util\\AsyncHelpers.cs : line 75 -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at Raven.Abstractions.Util.AsyncHelpers.RunSync [ T ] ( Func1 task ) in C : \Builds\RavenDB-Stable-3.5\Raven.Abstractions\Util\AsyncHelpers.cs : line 89 at Raven.Client.Connection.ServerClient.GetIndex ( String name ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Connection\ServerClient.cs : line 222\ at Raven.Client.Indexes.AbstractIndexCreationTask.Execute ( IDatabaseCommands databaseCommands , DocumentConvention documentConvention ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs : line 304 at Raven.Client.DocumentStoreBase.ExecuteIndex ( AbstractIndexCreationTask indexCreationTask ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\DocumentStoreBase.cs : line 102 at Raven.Client.Indexes.AbstractIndexCreationTask.Execute ( IDocumentStore store ) in C : \Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Indexes\AbstractIndexCreationTask.cs : line 221 at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.CreateIndexes ( IDocumentStore documentStore ) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs : line 50 at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.ConfigureDocumentStore ( IDocumentStore documentStore ) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs : line 38 at Persistence.Database.Adapter.RavenDb.RavenDbDocumentStoreFactory.Create ( String ravenDbLocation , String ravenDbDatabase ) in \my\route\Persistence.Database.Adapter\RavenDb\RavenDbDocumentStoreFactory.cs : line 22 at Persistence.Database.Adapter.PersistenceAdapter. < .ctor > b__8_0 ( ) in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs : line 53 at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenDbUtilities ( ) in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs : line 175 at Persistence.Database.Adapter.PersistenceAdapter.RegisterRavenLogic ( ) in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs : line 86 at Persistence.Database.Adapter.PersistenceAdapter.Initialize ( ) in \my\route\Persistence.Database.Adapter\PersistenceAdapter.cs : line 74 at My-Program.ConfigurePersistentAdapter ( Settings settings ) in \my\route\MessageQueueListener\MessageQueueListenerService.cs : line 153 at My-Program.AddBootstrapperExtension ( ) in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs : line 118 at My-Program.Startup ( ) in \my\route\net-stock-purchasing-service.MessageQueueListener\MessageQueueListenerService.cs : line 78 '' StatusCode : ServiceUnavailable TargetSite : { Void MoveNext ( ) } <code> private static void CreateIndexes ( IDocumentStore documentStore ) { new PurchaseOrder_QueryByExternalReference ( ) .Execute ( documentStore ) ; new SupplierDocument_QueryBySupplierName ( ) .Execute ( documentStore ) ; new ProductDocument_QueryByProductIdAndName ( ) .Execute ( documentStore ) ; new PurchaseOrderLine_QueryableIndex ( ) .Execute ( documentStore ) ; new PurchaseOrderLine_ForPurchaseOrderIndex ( ) .Execute ( documentStore ) ; }
Task Canceled exception on RavenDB when creating indexes
C_sharp : Unfortunatly , i ca n't find the original project which led me to this question . That would have perhaps given this question a bit more context.EDIT : I found the original project i 've seen this in : http : //mews.codeplex.com/SourceControl/changeset/view/63120 # 1054567 with a concrete implementation at : http : //mews.codeplex.com/SourceControl/changeset/view/63120 # 1054606 Lets say i have an abstract class with a concrete implementation that does something usefull like : This is as basic as it gets . Now in the code i 've seen on the web the author implemented inheritence by inheriting the Abstract class from the most derived type , e.g : Now why would one do such a thing ? I very vaguely remember this was a technique heavily used in ATL for performance reasons ( some way of calling concrete member implementations without working with a vtable ? ) I 'm not very sure on this part.I 've checked the generated IL for both cases and they are exactly the same.Who can explain this to me ? <code> abstract class AbstractClass { public virtual int ConvertNumber ( string number ) { string preparedNumber = Prepare ( number ) ; int result = StringToInt32 ( number ) ; return result ; } protected abstract string Prepare ( string number ) ; protected virtual int StringToInt32 ( string number ) { return Convert.ToInt32 ( number ) ; } } sealed class ConcreteClass : AbstractClass { protected override string Prepare ( string number ) { return number.Trim ( ) ; } public override int ConvertNumber ( string number ) { return base.ConvertNumber ( number ) ; } } abstract class AbstractGenericClass < TGenericClass > where TGenericClass : AbstractGenericClass < TGenericClass > { public virtual int ConvertNumber ( string number ) { string preparedNumber = Prepare ( number ) ; int result = StringToInt32 ( number ) ; return result ; } protected abstract string Prepare ( string number ) ; protected int StringToInt32 ( string number ) { return Convert.ToInt32 ( number ) ; } } sealed class ConcreteGenericClass : AbstractGenericClass < ConcreteGenericClass > { protected override string Prepare ( string number ) { return number.Trim ( ) ; } public override int ConvertNumber ( string number ) { return base.ConvertNumber ( number ) ; } }
Abstract class inheriting the most derived type
C_sharp : I have been using javascript and I made a lot of use of functions inside of functions . I tried this in C # but it seems they do n't exist . If I have the following : How can I code a method d ( ) that can only be calledfrom inside the method the method abc ( ) ? <code> public abc ( ) { }
Does C # have a concept of methods inside of methods ?
C_sharp : The following Delphi program calls method upon nil reference and runs fine . However , in a structurally similar C # program , System.NullReferenceException will be raised , which seems to be the right thing to do.Because TObject.Free uses such style , it seems to be `` supported '' to call method on nil reference in Delphi . Is this true ? ( Let 's suppose that in the if Self = nil branch , no instance field will be accessed . ) <code> program Project1 ; { $ APPTYPE CONSOLE } type TX = class function Str : string ; end ; function TX.Str : string ; begin if Self = nil then begin Result : = 'nil ' end else begin Result : = 'not nil ' end ; end ; begin Writeln ( TX ( nil ) .Str ) ; Readln ; end . namespace ConsoleApplication1 { class TX { public string Str ( ) { if ( this == null ) { return `` null '' ; } return `` not null '' ; } } class Program { static void Main ( string [ ] args ) { System.Console.WriteLine ( ( ( TX ) null ) .Str ( ) ) ; System.Console.ReadLine ( ) ; } } }
Is it `` supported '' to call method on nil reference in Delphi ?
C_sharp : In wpf , I have a textbox , the content of it coming from a txt file.in code behine it looks like : The thing is that the txt file content is changing during the runtime , is it possible to be synchronized with those changes ? I mean that the textbox content would be change if the txt file is changed . if It 's possible please give some code example i c # or XAML . My solution for now is that I made a `` Refresh '' button that reads again from the txt file <code> public MyWindow ( ) { InitializeComponent ( ) ; ReadFromTxt ( ) ; } void Refresh ( object sender , RoutedEventArgs e ) { ReadFromTxt ( ) ; } void ReadFromTxt ( ) { string [ ] lines = System.IO.File.ReadAllLines ( @ '' D : \Log.txt '' ) ; foreach ( string line in lines ) { MyTextBox.AppendText ( line + Environment.NewLine ) ; } }
Update textbox from txt file during runtime without clicking `` refresh ''
C_sharp : It is important to me that my syntax does not make other developers confused.In this example , I need to know if a parameter is a certain type . I have hit this before ; what 's the most elegant , clear approach to test `` not is '' ? Method 1 : Method 2 : Method 3 : Method 4 : [ EDIT ] Method 5 : Which is the most straight-forward approach ? <code> void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { if ( ! ( e.parameter is MyClass ) ) { /* do something */ } } void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { if ( e.parameter is MyClass ) { } else { /* do something */ } } void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { var _Parameter = e.parameter as MyClass ; if ( _Parameter ! = null ) { /* do something */ } } void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { var _Type = typeof ( MyClass ) ; switch ( e.parameter.GetType ( ) ) { case _Type : /* do nothing */ ; break ; default : /* do something */ ; break ; } } void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { if ( ( e.parameter is MyClass ) == false ) { /* do something */ } }
Best `` not is '' syntax in C #
C_sharp : I 'm trying to debug a crash that happens in our application during garbage collection and looking at the code I found two related pieces of code that , if not the cause of the problem , are at least suspicious to me : Note that from my understanding the struct is actually at least 98 bytes in size but is declared as 96 bytes long ( the code compiles though ) .The second suspicious piece of code is related to the above struct : where m_RawData is a simple unsigned byte array and TMilbusData is the C++ ( native ) code analogous of the above struct , defined as What I 'm not sure about in this second case is if the conversion from the native struct to a managed reference type is safe ( note that MilbusData is not declared as a value type ) .As I said the crashes that we are experiencing occur normaly during garbage collection but are sometimes extremely difficult to reproduce . I gave more details about the crash itself in another question but what I want to ask here is : Is the code above safe ? And if not can it be the cause for a managed heap corruption and explain therefore the crashes that we are experiencing ? EDIT : I should probably have asked if it is absolutely positive that the issues that I found in the code ( as the mismatching structure sizes between native and managed code ) can be the cause for a crash in the GC . Reason for asking is that i ) The C # compiler does n't complain about the wrong structure size and ii ) The problem is very difficult to reproduce . I 'm right now having a hard time in making it crash in the `` old '' version ( where the size of the struct is wrong ) and I wanted to avoid following a possible dead-end since each testing can take many days.. <code> [ StructLayout ( LayoutKind.Sequential , Size = 96 , CharSet = CharSet.Ansi , Pack=1 ) ] public class MilbusData { public System.Int64 TimeStamp ; public System.Int16 Lane ; public System.Int16 TerminalAddress ; public System.Int16 TerminalSubAddress ; public System.Int16 Direction ; public System.Int64 ErrorCounter ; public System.Int64 MessageCounter ; public System.Int16 RTErrorState ; [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 32 ) ] public System.UInt16 [ ] Data ; } MilbusData^ ret = nullptr ; if ( m_Stream- > Read ( m_RawData , 0 , sizeof ( TMilbusData ) ) == sizeof ( TMilbusData ) ) { GCHandle pinnedRawData = GCHandle : :Alloc ( m_RawData , GCHandleType : :Pinned ) ; ret = ( MilbusData^ ) Marshal : :PtrToStructure ( pinnedRawData.AddrOfPinnedObject ( ) , MilbusData : :typeid ) ; pinnedRawData.Free ( ) ; } typedef struct { __int64 TimeStamp ; short Lane ; short TerminalAddress ; short TerminalSubAddress ; short Direction ; __int64 ErrorCounter ; __int64 MessageCounter ; short RTErrorState ; unsigned char Data [ 64 ] ; } TMilbusData ;
Can this code cause a managed heap corruption ?
C_sharp : After reading this question ASP.NET MVC : Nesting ViewModels within each other , antipattern or no ? and Derick Bailey 's comment i think the `` consider what your viewmodel would look like as xml or json '' bit is probably the most important point , here . i often use that perspective to help me understand what the view model should look like , and to help me understand what data is `` viewmodel '' data vs `` data that goes on the HTML rendering of the view '' . helps to keep things clean and separate them nicely – Derick Bailey Apr 11 '11 at 15:45It makes me wonder how I would approach creating a View for a ViewModel with databound selection items . I 'm really struggling because I ca n't envision where the SelectList belongs . If I think in terms of JSON or XML then the SelectList is part of the View Only . All I want is a dropdown list prepopulated with a list of values for the user to select the Location Having it in the ViewModel seems wrong , but when I think about moving it to the View I do n't know where to place the logic to pull from the DB to populate the Selection ListupdateHere is a great question and answer that is really closely relatedC # mvc 3 using selectlist with selected value in viewI 've tested this implementation and it does what I think I want to do . I 'm not going to rush to pick an answer as I still have n't fully vetted this out . <code> public class SearchViewModel { public int ? page { get ; set ; } public int ? size { get ; set ; } //Land Related search criteria [ IgnoreDataMember ] public SelectList LocationSelection { get ; set ; }
Do SelectLists belong in viewModels ?
C_sharp : I understand how to get the names of parameters passed to a method , but let 's say I have a method declaration as follows : and I want to use object/property names in my template for substitution with real property values in any of the objects in my ` objects ' parameter . Let 's then say I call this method with : I will only be able to retrieve two parameter names trying to fill out the template , viz , template , and objects , and the names of the objects in the objects collection are forever lost , or not ? I could require a List < object > as my second parameter , but I feel there is somehow a more elegant solution , maybe with a lambda or something . I do n't know , I 'm not used to using lambdas outside of LINQ . <code> static void ParamsTest ( string template , params object [ ] objects ) ParamsTest ( `` Congrats '' , customer , purchase ) ;
How can I pass a variable number of named parameters to a method ?
C_sharp : I have this code : The variable p is always null . How is this posible ? Here is a print screen of what I am talking about : I also try with immediate windows I got this : p CAN NOT BE NULL since im creating a new instance of it while all of its properties are not null . I tried clean the project , restart windows , open visual studio as administrator and nothing happened . Any idea why ? The application is running on .net 4.0 , visual studio 2017 v15.2 ( 26430.13 ) relase . <code> public ObjectModel.Path GetPath ( int pathid ) { var path = this.DbContext.Paths.Find ( pathid ) ; var app = GetApplicationById ( path.ApplicationId.GetValueOrDefault ( ) ) ; var p = new Path { ApplicationId = path.ApplicationId , Id = path.Id , Password = path.Password , UserName = path.UserName , LocalUrl = string.IsNullOrEmpty ( path.LocalUrl ) ? null : System.IO.Path.Combine ( path.LocalUrl , app.Name ) } ; return p ; }
new operator returning null - C #
C_sharp : I 'm attempting to convert the following method ( simplified example ) to be asynchronous , as the cacheMissResolver call may be expensive in terms of time ( database lookup , network call ) : There are plenty of materials on-line about consuming async methods , but the advice I have found on producing them seems less clear-cut . Given that this is intended to be part of a library , are either of my attempts below correct ? Is using SemaphoreSlim the correct way to replace a lock statement in an async method ? ( I ca n't await in the body of a lock statement . ) Should I make the cacheMissResolver argument of type Func < Task < Thing > > instead ? Although this puts the burden of making sure the resolver func is async on the caller ( wrapping in Task.Run , I know it will be offloaded to a background thread if it takes a long time ) .Thanks . <code> // Synchronous versionpublic class ThingCache { private static readonly object _lockObj ; // ... other stuff public Thing Get ( string key , Func < Thing > cacheMissResolver ) { if ( cache.Contains ( key ) ) return cache [ key ] ; Thing item ; lock ( _lockObj ) { if ( cache.Contains ( key ) ) return cache [ key ] ; item = cacheMissResolver ( ) ; cache.Add ( key , item ) ; } return item ; } } // Asynchronous attemptspublic class ThingCache { private static readonly SemaphoreSlim _lockObj = new SemaphoreSlim ( 1 ) ; // ... other stuff // attempt # 1 public async Task < Thing > Get ( string key , Func < Thing > cacheMissResolver ) { if ( cache.Contains ( key ) ) return await Task.FromResult ( cache [ key ] ) ; Thing item ; await _lockObj.WaitAsync ( ) ; try { if ( cache.Contains ( key ) ) return await Task.FromResult ( cache [ key ] ) ; item = await Task.Run ( cacheMissResolver ) .ConfigureAwait ( false ) ; _cache.Add ( key , item ) ; } finally { _lockObj.Release ( ) ; } return item ; } // attempt # 2 public async Task < Thing > Get ( string key , Func < Task < Thing > > cacheMissResolver ) { if ( cache.Contains ( key ) ) return await Task.FromResult ( cache [ key ] ) ; Thing item ; await _lockObj.WaitAsync ( ) ; try { if ( cache.Contains ( key ) ) return await Task.FromResult ( cache [ key ] ) ; item = await cacheMissResolver ( ) .ConfigureAwait ( false ) ; _cache.Add ( key , item ) ; } finally { _lockObj.Release ( ) ; } return item ; } }
Correct way to convert method to async in C # ?
C_sharp : I just started using mock objects ( using Java 's mockito ) in my tests recently . Needless to say , they simplified the set-up part of the tests , and along with Dependency Injection , I would argue it made the code even more robust.However , I have found myself tripping in testing against implementation rather than specification . I ended up setting up expectations that I would argue that it 's not part of the tests . In more technical terms , I will be testing the interaction between SUT ( the class under test ) and its collaborators , and such dependency is n't part of contract or the interface of the class ! Consider that you have the following : When dealing with XML node , suppose that you have a method , attributeWithDefault ( ) that returns the attribute value of the node if it 's available , otherwise it would return a default value ! I would setup the test like the following : Well , here not only did I test that attributeWithDefault ( ) adheres to the specification , but I also tested the implementation , as I required it to use Element.getAttribute ( ) , instead of Element.getAttributeNode ( ) .getValue ( ) or Element.getAttributes ( ) .getNamedItem ( ) .getNodeValue ( ) , etc.I assume that I am going about it in the wrong way , so any tips on how I can improve my usage of mocks and best practices will be appreciated.EDIT : What 's wrong with the testI made the assumption above that the test is a bad style , here is my rationale.The specification does n't specify which method gets called . A client of the library should n't care of how attribute is retrieved for example , as long as it is done rightly . The implementor should have free reign to access any of the alternative approaches , in any way he sees fit ( with respect to performance , consistency , etc ) . It 's the specification of Element that ensures that all these approaches return identical values.It does n't make sense to re-factor Element into a single method interface with getElement ( ) ( Go is quite nice about this actually ) . For ease of use , a client of the method should be able to just to use the standard Element in the standard library . Having interfaces and new classes is just plain silly , IMHO , as it makes the client code ugly , and it 's not worth it.Assuming the spec stays as is and the test stays as is , a new developer may decide to refactor the code to use a different approach of using the state , and cause the test to fail ! Well , a test failing when the actual implementation adheres to the specification is valid.Having a collaborator expose state in multiple format is quite common . A specification and the test should n't depend on which particular approach is taken ; only the implementation should ! <code> Element e = mock ( Element.class ) ; when ( e.getAttribute ( `` attribute '' ) ) .thenReturn ( `` what '' ) ; when ( e.getAttribute ( `` other '' ) ) .thenReturn ( null ) ; assertEquals ( attributeWithDefault ( e , `` attribute '' , `` default '' ) , `` what '' ) ; assertEquals ( attributeWithDefault ( e , `` other '' , `` default '' ) , `` default '' ) ;
Use of Mocks in Tests
C_sharp : The requirement used to be that the window is CenterScreen but the client has recently asked that the window is now slightly to the right of its current position.The current definition of the window is : I was hoping that doing the following would work : But the window is still in the same position when it appears on screen.Do I need to change the startup location to Manual and position it myself ? If so , how do I get it offset from the center ? <code> public MyWindow ( ) { InitializeComponent ( ) ; // change the position after the component is initialized this.Left = this.Left + this.Width ; }
Is it possible to offset the window position by a value when WindowStartupLocation= '' CenterScreen '' ?
C_sharp : I add a MenuStrip to my form and I would like to add other controls below it like usual Point ( 0 , 0 ) is the top left corner of empty form space . After I add the menu to my form and add more controls they overlap each other . So I want to take away some height of the client rect for the menu and a button with Location = ( 0,0 ) must be RIGHT below the menu.How do I do that ? If I assign a MainMenu to Menu property of the form it does that automatically but I really want and need to use MenuStrip.Edit : this does n't work : While this works like I would like it to do with MenuStrip : <code> MenuStrip menu = new MenuStrip ( ) ; menu.Items.Add ( `` File '' ) ; menu.AutoSize = false ; menu.Height = 50 ; menu.Dock = DockStyle.Top ; MainMenuStrip = menu ; Controls.Add ( menu ) ; Button b = new Button ( ) ; b.Text = `` hello world '' ; b.SetBounds ( 0 , 25 , 128 , 50 ) ; Controls.Add ( b ) ; Menu = new MainMenu ( ) ; Menu.MenuItems.Add ( `` File '' ) ; Button b = new Button ( ) ; b.Text = `` hello world '' ; b.SetBounds ( 0 , 0 , 128 , 50 ) ; Controls.Add ( b ) ;
How to take away vertical space for programmatically added menu ?
C_sharp : Given that all controls in a WebForm are destroyed ( by my understanding ) at the end of each postback do you need to `` unwire '' any event handlers you may have wired up ? ( Assuming you want to stop handling the events and allow GC ) So for example : <code> public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load ( object sender , EventArgs e ) { //Do I need to remove this handler ? btnSubmit.ServerClick += btnSubmit_ServerClick ; } }
Do you need to `` unwire '' event handlers in ASP.NET webforms
C_sharp : In .NET Thread class has static method Yield.I see that method in coreclr implementation of Thread.But documentation does n't contain that Method description.Also .NET CLI ( dotnet build ) cant compile code with that method invocation.Why ? updruntime : 1.0.0-rc1-update1 coreclr x64 darwin project.jsonupd2I 'm not going to use Thread.Yield ( ) ; I was just wondering why some framework features are absent in coreclr . <code> { `` version '' : `` 1.0.0-* '' , `` compilationOptions '' : { `` emitEntryPoint '' : true } , `` dependencies '' : { `` NETStandard.Library '' : `` 1.0.0-rc2-* '' , `` System.Threading '' : `` 4.0.11-rc3-* '' } , `` frameworks '' : { `` dnxcore50 '' : { } } }
Thread.Yield ( ) in coreclr
C_sharp : I want to do the followingHowever I ca n't because you ca n't have static abstract members.I understand why I ca n't do this - any recommendations for a design that will achieve much the same result ? ( For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes , there are good reasons for keeping it static . ) <code> public abstract class MyAbstractClass { public static abstract int MagicId { get ; } public static void DoSomeMagic ( ) { // Need to get the MagicId value defined in the concrete implementation } } public class MyConcreteClass : MyAbstractClass { public static override int MagicId { get { return 123 ; } } }
C # class design - what can I use instead of `` static abstract '' ?
C_sharp : i was wondering if there is a way to restrict a value in construction . Here is my code : and when i make a new Student i want to restrict the Grade between > = 2.00 and < = 6.00 , like compile error or excepion on runtime . Is there a way ? ( Do n't worry about other fields FirstName , and LastName ) <code> class Student : Human { private double Grade ; public Student ( string FirstName , string LastName , double Grade ) : base ( FirstName , LastName ) { this.FirstName = FirstName ; this.LastName = LastName ; this.Grade = Grade ; } }
Constructor restrictions
C_sharp : Sometimes when using the miniprofiler , there 's just some requests that you does n't care about . In my case I do n't care much about signalr , umbraco pings , and some requests made when I wan na know if the user is idle or not.To avoid the miniprofiler using energy on ( and providing results for ) these types of requests , I have added the following code to my global.asax.cs file : Seeing that I still recieve results for URL 's containing the given strings , I have made this check later on in the Application Life Cycle in an attempt on removing the unwanted results I could see that I still got.But even though I have done this , I am still recieving the unwanted results . Does anyone know how this can be , what am I doing wrong here ? NotesIt should be noted that because I 'm using Umbraco as my fundament , I 'm using MiniProfiler 2.1.0 and I start out my Global.asax.cs file like this : <code> protected void Application_BeginRequest ( ) { if ( ( Request.IsLocal || Request.UserHostAddress == `` 37.49.143.197 '' ) & & ! ( Request.RawUrl.Contains ( `` /signalr/ '' ) || Request.RawUrl.Contains ( `` /idle/verify '' ) || Request.RawUrl.Contains ( `` /idle/interaction '' ) || Request.RawUrl.Contains ( `` /umbraco/ping '' ) ) ) { MiniProfiler.Start ( ) ; } } protected void Application_ProcessRequest ( ) { if ( Request.RawUrl.Contains ( `` /signalr/ '' ) || Request.RawUrl.Contains ( `` /idle/verify '' ) || Request.RawUrl.Contains ( `` /idle/interaction '' ) || Request.RawUrl.Contains ( `` /umbraco/ping '' ) ) { MiniProfiler.Stop ( discardResults : true ) ; } } public class MvcApplication : UmbracoApplication { protected override void OnApplicationStarted ( object sender , EventArgs e ) { // Setup profiler for Controllers via a Global ActionFilter GlobalFilters.Filters.Add ( new ProfilingActionFilter ( ) ) ; // initialize automatic view profiling var copy = ViewEngines.Engines.ToList ( ) ; ViewEngines.Engines.Clear ( ) ; foreach ( var item in copy ) { ViewEngines.Engines.Add ( new ProfilingViewEngine ( item ) ) ; } ...
How to remove specific URL 's from profiling when using MiniProfiler
C_sharp : I have the following code in my C # application.ReSharper 7.1.1 is highlighting the fact that the DateTimeFormatInfo.CurrentInfo could cause a null reference exception.Under what circumstances would this occur ? Or is this just a mistake on ReSharper 's part believing that any object whose property you access should be null checked ? <code> DateTimeFormatInfo.CurrentInfo.DayNames
How can DateTimeFormatInfo.CurrentInfo be null
C_sharp : I think this looks like a bug in the C # compiler.Consider this code ( inside a method ) : It compiles with no errors ( or warnings ) . Seems like a bug . When run , prints 0 on console.Then without the const , the code : When this is run , it correctly results in an OverflowException being thrown.The C # Language Specification mentions this case specifically and says a System.OverflowException shall be thrown . It does not depend on the context checked or unchecked it seems ( also the bug with the compile-time constant operands to the remainder operator is the same with checked and unchecked ) .Same bug happens with int ( System.Int32 ) , not just long ( System.Int64 ) .For comparison , the compiler handles dividend / divisor with const operands much better than dividend % divisor.My questions : Am I right this is a bug ? If yes , is it a well-known bug that they do not wish to fix ( because of backwards compatibility , even if it is rather silly to use % -1 with a compile-time constant -1 ) ? Or should we report it so that they can fix it in upcoming versions of the C # compiler ? <code> const long dividend = long.MinValue ; const long divisor = -1L ; Console.WriteLine ( dividend % divisor ) ; long dividend = long.MinValue ; long divisor = -1L ; Console.WriteLine ( dividend % divisor ) ;
Why does the compiler evaluate remainder MinValue % -1 different than runtime ?
C_sharp : I 'm currently migrating a Windows Azure application to Amazon AWS . In Windows Azure we used Lokad.Clout to get strongly typed access to Azure Blob Storage . For instance like this : For more detailed examples see their wiki.In the AWS SDK for .NET you do n't get strongly typed access . For instance in order to achive the above you have to execute ListBojects and then parse the key of every object in order to find the each individual property of the key ( we often use keys consisting of several properties ) .Is there any S3-equivalent to Lokad.Cloud for Azure ? UPDATE : Due to the size of the objects we can not use SimpleDB ( with Simple Savant ) . <code> foreach ( var name in storage.List ( CustomerBlobName.Prefix ( country ) ) { var customer = storage.GetBlob ( name ) ; // strong type , no cast ! // do something with 'customer ' , snipped }
Strongly typed access to Amazon S3 using C #
C_sharp : I 'm using Rob Conery 's Massive for database access . I want to wrap a transaction around a couple of inserts but the second insert uses the identity returned from the first insert . It 's not obvious to me how to do this in a transaction . Some assistance would be appreciated . <code> var commandList = new List < DbCommand > { contactTbl.CreateInsertCommand ( new { newContact.Name , newContact.Contact , newContact.Phone , newContact.ForceChargeThreshold , newContact.MeterReadingMethodId , LastModifiedBy = userId , LastModifiedDate = modifiedDate , } ) , branchContactTbl.CreateInsertCommand ( new { newContact.BranchId , ContactId = ? ? ? ? , < -- how to set Id as identity from previous command } ) , } ;
Want to use identity returned from insert in subsequent insert in a transaction
C_sharp : My question is different with the one identified . Obviously I have called `` BeginErrorReadLine '' method ( I mark it in the code below ) .I want to parse the result produced by HandleCommand lineWhen run in a command line environment , it will output something like : > handle64 -p [ PID ] Nthandle v4.11 - Handle viewer Copyright ( C ) 1997-2017 Mark Russinovich Sysinternals - www.sysinternals.com 10 : File C : \Windows 1C : File C : \Windows\SysWOW64 [ PID ] is any running process IDThe output is seperated.First 5 lines ( include empty lines ) go to the standard error , last 2 lines go to the standard output.So I can strip the header by redirecting : > handle64 -p [ PID ] 2 > nul 10 : File C : \Windows 1C : File C : \Windows\SysWOW64Winform applicationThen I try to implement this command in a C # winform application : Then I find everything go to the standard output.QuestionOk , I can seperate the header and the body by code.The question is why the program 's output behaves different between the 2 environments ? Can I make the result in the winform application behaves like it in the command line ? UpdateFor Damien 's comment , I try to run the program via 'cmd ' , unfortunately I get the same result : In output window : Output = > Output = > Nthandle v4.11 - Handle viewer Output = > Copyright ( C ) 1997-2017 Mark Russinovich Output = > Sysinternals - www.sysinternals.com Output = > Output = > 10 : File C : \Windows Output = > 1C : File C : \Windows\SysWOW64 Error = > <code> Stream streamOut , streamErr ; var p = Process.Start ( new ProcessStartInfo { FileName = `` handle64.exe '' , Arguments = `` -p [ PID ] '' , CreateNoWindow = true , UseShellExecute = false , RedirectStandardOutput = true , RedirectStandardError = true , } ) ; p.OutputDataReceived += ( sender , e ) = > { streamOut.Write ( `` Output = > `` + e.Data ) ; } ; p.ErrorDataReceived += ( sender , e ) = > { streamErr.Write ( `` Error = > `` + e.Data ) ; } ; p.BeginOutputReadLine ( ) ; p.BeginErrorReadLine ( ) ; // ! ! ! p.WaitForExit ( ) ; var p = Process.Start ( new ProcessStartInfo { FileName = `` cmd '' , Arguments = `` /C handle64.exe -p [ PID ] '' , CreateNoWindow = true , UseShellExecute = false , RedirectStandardOutput = true , RedirectStandardError = true , } ) ; ...
When run a program in C # , all the messages go to the standard output , but the standard error contains nothing
C_sharp : Is there anyway to know this ? I found one post that asked a very similar question at How to check if an object is nullable ? The answer explains how to determine if an object is nullable if there is access to a Generic Type Parameter . This is accomplished by using Nullabe.GetUnderlyingType ( typeof ( T ) ) . However , if you only have an object and it is not null , can you determine if it is actually a Nullable ValueType ? In other words , is there a better way than checking every possible nullable value type individually to determine if a boxed struct is a value type ? -UpdateI found this article at MSDN , and it says you ca n't determine if a type is a Nullable struct via a call to GetType ( ) . -Update # 2Apparently the method I suggested does n't work either because int x = 4 ; Console.WriteLine ( x is int ? ) ; is True . ( See the comment ) <code> void Main ( ) { Console.WriteLine ( Code.IsNullableStruct ( Code.BoxedNullable ) ) ; } public static class Code { private static readonly int ? _nullableInteger = 43 ; public static bool IsNullableStruct ( object obj ) { if ( obj == null ) throw new ArgumentNullException ( `` obj '' ) ; if ( ! obj.GetType ( ) .IsValueType ) return false ; return IsNullablePrimitive ( obj ) ; } public static bool IsNullablePrimitive ( object obj ) { return obj is byte ? || obj is sbyte ? || obj is short ? || obj is ushort ? || obj is int ? || obj is uint ? || obj is long ? || obj is ulong ? || obj is float ? || obj is double ? || obj is char ? || obj is decimal ? || obj is bool ? || obj is DateTime ? || obj is TimeSpan ? ; } public static object BoxedNullable { get { return _nullableInteger ; } } }
How to determine if a non-null object is a Nullable struct ?
C_sharp : Is there a way how to decorate property of datacontract object , so the generated xsd will contain MaxLenght restriction ? E.g . I can imagine I need something like this : and something like this should be included in the output from xsd.exe : Is there a way to do it ? To define the restrictions in C # class in such way , the xsd.exe tool will generate the restrictions into the xsd file ? <code> [ XmlElement ( MaxLengthAttribute = `` 12 '' ) ] public string Name ; < xs : element name= '' name '' > < xs : simpleType > < xs : restriction base= '' xs : string '' > < xs : maxLength value = `` 12 '' / > < /xs : restriction > < /xs : simpleType > < /xs : element >
How to generate XSD from Class with restrictions
C_sharp : I want to do a foreach loop while taking out members of that foreach loop , but that 's throwing errors . My only idea is to create another list inside of this loop to find which Slices to remove , and loop through the new list to remove items from Pizza . <code> foreach ( var Slice in Pizza ) { if ( Slice.Flavor == `` Sausage '' ) { Me.Eat ( Slice ) ; //This removes an item from the list : `` Pizza '' } }
Going Through A Foreach When It Can Get Modified ?
C_sharp : Lets say we have the folowing code.What is actually happening ? Cast the obj to a string and then calls the ToString Method ? Calls the ToString method on obj which is the override of string without casting ? Something else ? Witch one is better to do ? var bar = obj.ToString ( ) ; var bar = ( string ) obj ; <code> var foo = `` I am a string '' ; Object obj = foo ; var bar = obj.ToString ( ) ;
What happens when calling Object.ToString when the actual type is String
C_sharp : In C # I 've enabled tracing and a net tracing source.But longer messages get truncated ( long like 12Kb/30 lines , not long like 1GB ! ) so I end up in a situation where only part of web reqiest headers are logged.How to fix that ? Or do you know a book or some resource that explains .Net tracing and debugging in great detail ? log example : This is one message , somehow Write method on the TraceListener is called whit that single message as parameter that is being truncated ( the `` ... } . '' at the end ) Also cookies are terribly written and are almost unparsable , but I can live with that ... Yeah , sadly enough apart from tampering with System.dlls or using some odd and complex type inheritance there is not much to be done . <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5 '' / > < /startup > < system.diagnostics > < sources > < source name= '' System.Net '' tracemode= '' includehex '' maxdatasize= '' 1024 '' > < listeners > < add name= '' System.Net '' / > < /listeners > < /source > < /sources > < switches > < add name= '' System.Net '' value= '' Verbose '' / > < /switches > < sharedListeners > < add name= '' System.Net '' type= '' TraceTest.StringWriterTraceListener , TraceTest '' initializeData= '' myfile.log '' / > < /sharedListeners > < trace autoflush= '' true '' indentsize= '' 4 '' / > < /system.diagnostics > < /configuration > System.Net Information : 0 : [ 1204 ] Connection # 63291458 - Received headers { Transfer-Encoding : chunked Connection : keep-alive Keep-Alive : timeout=10 Content-Type : text/html ; charset=windows-1251 Date : Mon , 04 Jul 2016 17:50:33 GMT Set-Cookie : uid=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 , uid=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ , uid=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ ; domain=.zamunda.net , pass=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 , pass=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ , pass=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ ; domain=.zamunda.net , bitbucketz=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 , bitbucketz=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ , bitbucketz=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ ; domain=.zamunda.net , cats=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 , cats=deleted ; expires=Thu , 01-Jan-1970 00:00:01 GMT ; Max-Age=0 ; path=/ , cats=deleted ; expires= ... } .
C # Tracing truncate long messages
C_sharp : This is a very specific problem . Not quite sure how to even word it . Basically I am implementing the unit of work and repository pattern , I have a dynamic object that I convert to an int , but if I use var it will throw an exception when trying to call the method.I tried to remove all the trivial variables to this problem that I can . For some reason I only see it happen with these two design patterns . The exception I get is Additional information : 'BlackMagic.ITacoRepo ' does not contain a definition for 'DoStuff'Here is the code : EDIT : The main question I am trying to find an answer for , is why would the exception get thrown by calling DoStuff inside the unit of work ( while using the repo ) but not get thrown if DoStuff existed in the BlackMagic class . <code> class BlackMagic { static void Main ( string [ ] args ) { dynamic obj = new ExpandoObject ( ) ; obj.I = 69 ; UnitOfWork uow = new UnitOfWork ( ) ; int i1 = Convert.ToInt32 ( obj.I ) ; var i2 = Convert.ToInt32 ( obj.I ) ; if ( i1.Equals ( i2 ) ) { uow.TacoRepo.DoStuff ( i1 ) ; // Works fine uow.TacoRepo.DoStuff ( i2 ) ; // Throws Exception } } } class UnitOfWork { public ITacoRepo TacoRepo { get ; set ; } public UnitOfWork ( ) { TacoRepo = new TacoRepo ( ) ; } } class Repo < T > : IRepo < T > where T : class { public void DoStuff ( int i ) { } } interface IRepo < T > where T : class { void DoStuff ( int i ) ; } class TacoRepo : Repo < Taco > , ITacoRepo { } interface ITacoRepo : IRepo < Taco > { } class Taco { }
Casting Dynamic Object and Passing Into UnitOfWork and Repository Pattern . Throws Exception
C_sharp : I 'm building a generic flat file reader which looks something like this.It could be consumed like so.Here are the classes used.Is there a way how I could remove or encapsulate that generic type information in the GenericReader ? I 'm looking for an extra pair of eyes to show me something what I 've been missing . We already did something with returning interfaces , and making the consumer do a cast , but that just moves the responsibility to the wrong location in my opinion , plus there is a small performance penalty.Thanks.Edit : I do n't need the TComposite , I can just return the GenericComposite . How could I miss that ? <code> public class GenericReader < TComposite , THeader , TData , TTrailer > where TComposite : GenericComposite < THeader , TData , TTrailer > , new ( ) where THeader : new ( ) where TData : new ( ) where TTrailer : new ( ) { public TComposite Read ( ) { var composite = new TComposite ( ) ; composite.Header = new THeader ( ) ; composite.Data = new TData ( ) ; composite.Trailer = new TTrailer ( ) ; return composite ; } } var reader = new GenericReader < Composite < Header , Data , Trailer > , Header , Data , Trailer > ( ) ; var composite = reader.Read ( ) ; Console.WriteLine ( composite.Data.SomeProperty ) ; Console.ReadLine ( ) ; public class Composite < THeader , TData , TTrailer > : GenericComposite < THeader , TData , TTrailer > { } public class GenericComposite < THeader , TData , TTrailer > { public THeader Header { get ; set ; } public TData Data { get ; set ; } public TTrailer Trailer { get ; set ; } } public class Header { public string SomeProperty { get { return `` SomeProperty '' ; } } } public class Data { public string SomeProperty { get { return `` SomeProperty '' ; } } } public class Trailer { public string SomeProperty { get { return `` SomeProperty '' ; } } } public class GenericReader < THeader , TData , TTrailer > where THeader : new ( ) where TData : new ( ) where TTrailer : new ( ) { public GenericComposite < THeader , TData , TTrailer > Read ( ) { var composite = new GenericComposite < THeader , TData , TTrailer > ( ) ; composite.Header = new THeader ( ) ; composite.Data = new TData ( ) ; composite.Trailer = new TTrailer ( ) ; return composite ; } } public class GenericComposite < THeader , TData , TTrailer > { public THeader Header { get ; set ; } public TData Data { get ; set ; } public TTrailer Trailer { get ; set ; } }
Can I somehow tidy up this ( overuse ? ) of generics ?
C_sharp : This is my mapping class : This works fine for the Table ( [ mySchema ] . [ MyTable ] ) in my first database.But this table ( `` MyTable '' ) exists in ( actually a lot of ) different databases , but for any reason the schema is always named different ( this I dont have any control of ) : So in the Database `` OtherDB '' there is the Table [ SomeOtherSchema ] . [ MyTable ] with the same structure as [ mySchema ] . [ MyTable ] in the first db.For obvious reasons I dont want to create a different mapping class for every database.So : Is there a way to change the schema of the mapping class so I just have to create one mapping class ( Without using a singelton ! ) ? <code> class MyTableMap : ClassMap < MyTable > { public MyTableMap ( ) { Schema ( `` mySchema '' ) ; Id ( x = > x.id ) ; Map ( x = > x.SomeString ) ; } }
Fluent nHibernate : Use the same mapping files for tables with the same structure in different schemas
C_sharp : I 'm using this code to print a PDF file on a local printer with C # within a windows service.Everything works fine when I set a user to run the windows service.Whenever I run this code under the LocalSystem credential , I get the error `` there are no application associated to this operation '' which usually indicates that I do n't have a program ready to deal with a print operation of a file with the .pdf extension.My problem is that I do have the program ( Foxit Reader ) to deal with this operation as confirmed by the fact that this code works with specific user set on the service and that I 'm able to send files to the printer by right clicking them and selecting the print option.Is there anything I can change to be able to print on a local printer from within a service without an specific user ? <code> Process process = new Process ( ) ; PrinterSettings printerSettings = new PrinterSettings ( ) ; if ( ! string.IsNullOrWhiteSpace ( basePrint ) ) printerSettings.PrinterName = basePrint ; process.StartInfo.FileName = fileName ; process.StartInfo.Verb = `` printto '' ; process.StartInfo.Arguments = `` \ '' '' + printerSettings.PrinterName + `` \ '' '' ; process.Start ( ) ; process.WaitForInputIdle ( ) ;
PDF Print Through Windows Service with C #
C_sharp : What is the order of implicit conversions done in Console.WriteLine ( x ) when x is an object from user-defined class : Why I get 42 , and not 3.14 or `` 12 '' ? Why I can not add an additional implicit conversion to string /there is Compiler error on the ambiguity between CW ( int ) and CW ( string ) / : I know I should avoid using the implicit cast , but just for curiosity ! <code> class Vector { public int x = 12 ; public static implicit operator double ( Vector v1 ) { return 3.14 ; } public static implicit operator int ( Vector v1 ) { return 42 ; } public override string ToString ( ) { return this.x.ToString ( ) ; } } static void Main ( string [ ] args ) { Vector v11 = new Vector ( ) ; Console.WriteLine ( v11 ) ; } public static implicit operator string ( Vector v1 ) { return `` 42 '' ; }
Order of implicit conversions in c #
C_sharp : I am having problems figuring out the Linq syntax for a left outer join within multiple joins . I want to do a left join on RunLogEntry Table so I get records which match from this table as well as all of the Service Entries . Can some one please correct my snytax ? <code> var list = ( from se in db.ServiceEntry join u in db.User on se.TechnicianID equals u.ID join s in db.System1 on se.SystemID equals s.ID join r in db.RunLogEntry on se.RunLogEntryID equals r.ID where se.ClosedDate.HasValue == false where se.ClosedDate.HasValue == false & & se.Reconciled == false orderby se.ID descending select new ServiceSearchEntry ( ) { ID = se.ID , ServiceDateTime = se.ServiceDateTime , Technician = u.FullName , System = s.SystemFullName , ReasonForFailure = se.ReasonForFailure , RunDate = r.RunDate } ) .Skip ( ( page - 1 ) * PageSize ) ;
Linq left join syntax correction needed
C_sharp : As a newcomer to TDD I 'm stuggling with writing unit tests that deal with collections . For example at the moment I 'm trying to come up with some test scearios to essentially test the following methodWhere the method should return the index of the first item in the list list that matches the predicate predicate . So far the only test cases that I 've been able to come up with have been along the lines ofWhen list contains no items - returns -1When list contains 1 item that matches predicate - returns 0When list contains 1 item that does n't match predicate - returns -1When list contains 2 items both of which match predicate - return 0When list contains 2 items , the first of which match predicate - return 0etc ... As you can see however these test cases are both numerous and do n't satisfactorily test the actual behaviour that I actually want . The mathematician in me wants to do some sort of TDD-by-inductionWhen list contains no items - returns -1When list contains N items call predicate on the first item and then recursively call Find on the remaining N-1 itemsHowever this introduces unneccessary recursion . What sort of test cases should I be looking to write in TDD for the above method ? As an aside the method that I am trying to test really is just Find , simply for a specific collection and predicate ( which I can independently write test cases for ) . Surely there should be a way for me to avoid having to write any of the above test cases and instead simply test that the method calls some other Find implementation ( e.g . FindIndex ) with the correct arguments ? Note that in any case I 'd still like to know how I could unit test Find ( or another method like it ) even if it turns out that in this case I do n't need to . <code> int Find ( List < T > list , Predicate < T > predicate ) ;
TDD - writing tests for a method that iterates / works with collections
C_sharp : I have a generic methodThis method is used quite a lot throughout the code , and I want to find where it is used with T being a specific type.I can text-search for but most often the type argument has been omitted from the call ( inferred ) . Is there any way I can find these method invocations in VS2010 or perhaps ReSharper ? <code> public void Foo < T > ( T arg ) where T : ISomeInterface `` Foo < TheType > ( ``
How can I find generic invocations with a specific type argument in my source ?
C_sharp : How do I do that ? And , what do I take on the left side of the assignment expression , assuming this is C # 2.0 . I do n't have the var keyword . <code> sTypeName = ... //do some string stuff here to get the name of the type/*The Assembly.CreateInstance function returns a typeof System.object . I want to type cast it to the type whose name is sTypeName.assembly.CreateInstance ( sTypeName ) So , in effect I want to do something like : */assembly.CreateInstance ( sTypeName ) as Type.GetType ( sTypeName ) ;
Typecast to a type from just the string representation of the type name
C_sharp : We 're running our Win8 Metro unit tests from powershell using vstest.console.exe , which is included with Visual Studio 2012 . The way the process uses the unit test appx-package created by msbuild , and runs it : \install\location\vstest.console.exe path\to\unittest.appx /InIsolationFrom time to time the execution fails with a timeout . If checking the logs , as suggested by the tool , one can indeed see that there are some errors , but the package actually does seem to install after roughly 35 seconds . There is no real indication on the root cause of this problem though . Fierce googling did n't reveal anything , so maybe this category of problems would 've been better solved with bing ... Is this a known issue ? Are there some normal reasons for appx installation to fail with a timeout , and that can be fixed easily ? The error seems to be related specifically to installation , not the unit testing as such . Normally the whole test execution with install and uninstall finishes in a few seconds . If the answers to the questions above are no , then is it possible to increase the installation timeout either for the process , or system wide ? <code> Starting test execution , please wait ... Error : Installation of package '\absolute\path\to\unittest.appx ' failed with Error : ( 0x5B4 ) Operation timed out . Unable to install Windows app package in 15 sec.For more details look into Event Viewer under Applications and Services Logs - > Microsoft - > Windows - > AppXDeployment-Server - > Microsoft-Windows-AppXDeploymentServer/Operational .
Windows 8 Appx installation timeout during unit test execution
C_sharp : I have written the following SQL CLR function in order to hash string values larger then 8000 bytes ( the limit of input value of the T-SQL built-it HASHBYTES function ) : It is working fine for Latin strings . For example , the following hashes are the same : The issue is it is not working with Cyrillic strings . For example : I am getting NULL for MD5 , although the code returns value if it is executed as console application . Could anyone tell what I am doing wrong ? Also , I 've got the function from here and one of the comments says that : Careful with CLR SP parameters being silently truncated to 8000 bytes - I had to tag the parameter with [ SqlFacet ( MaxSize = -1 ) ] otherwise bytes after the 8000th would simply be ignored ! but I have tested this and it is working fine . For example , if I generate a hash of 8000 bytes string and a second hash of the same string plus one symbol , I get the hashes are different.Should I worry about this ? <code> [ SqlFunction ( DataAccess = DataAccessKind.None , IsDeterministic = true ) ] public static SqlBinary HashBytes ( SqlString algorithm , SqlString value ) { HashAlgorithm algorithmType = HashAlgorithm.Create ( algorithm.Value ) ; if ( algorithmType == null || value.IsNull ) { return new SqlBinary ( ) ; } else { byte [ ] bytes = Encoding.UTF8.GetBytes ( value.Value ) ; return new SqlBinary ( algorithmType.ComputeHash ( bytes ) ) ; } } SELECT dbo.fn_Utils_GetHashBytes ( 'MD5 ' , 'test ' ) ; -- 0x098F6BCD4621D373CADE4E832627B4F6SELECT HASHBYTES ( 'MD5 ' , 'test ' ) ; -- 0x098F6BCD4621D373CADE4E832627B4F6 SELECT dbo.fn_Utils_GetHashBytes ( 'MD5 ' , N'даровете на влъхвите ' ) -- NULLSELECT HashBytes ( 'MD5 ' , N'даровете на влъхвите ' ) -- 0x838B1B625A6074B2BE55CDB7FCEA2832SELECT dbo.fn_Utils_GetHashBytes ( 'SHA256 ' , N'даровете на влъхвите ' ) -- 0xA1D65374A0B954F8291E00BC3DD9DF655D8A4A6BF127CFB15BBE794D2A098844SELECT HashBytes ( 'SHA2_256 ' , N'даровете на влъхвите ' ) -- 0x375F6993E0ECE1864336E565C8E14848F2A4BAFCF60BC0C8F5636101DD15B25A DECLARE @ A VARCHAR ( MAX ) = '8000 bytes string ... 'DECLARE @ B VARCHAR ( MAX ) = @ A + ' 1'SELECT LEN ( @ A ) , LEN ( @ B ) SELECT IIF ( dbo.fn_Utils_GetHashBytes ( 'MD5 ' , @ A + ' 1 ' ) = dbo.fn_Utils_GetHashBytes ( 'MD5 ' , @ B ) , 1 , 0 ) -- 0
SQL CLR function based on .net ComputeHash is not working with Cyrrilic
C_sharp : I understand this is a beta ( just checked the new version of EF 4.3 and it does the same thing ) release and some functionality may be missing , but i haven ` t seen anything to explain why ... ... no longer creates a column of type xml when using EF 4.3 ( column is created as nvarchar ( max ) ) , I have tried EF 4.2 and that creates the column just fine . Just for reference i am connecting to sql server 2008r2 and have also tried the express edition . I am using XML to store data of constantly changing data schemas , and altho i understand that this will be passed back as a string I need the ability to create stored procedures against the xml data within sql.I have also tried using the .HasDataType ( ) method with no luck.On a side note I am however able to create varchar and I believe nchar types , but not ntext or text types using the same method . So really my questions are : Should i be able to create columns of type xml in EF 4.3 ? Why ca n't I ? Is there a correct way/work around to accomplish this ? <code> [ Column ( TypeName = `` xml '' ) ] public string SomeProperty { get ; set ; }
Entity Framework 4.3 beta [ Column ( TypeName ) ] issue , can not create columns of type xml
C_sharp : Here are two C # classes ... ... and a list of data ( filled somewhere ) ... ... and then this LINQ query : I do not understand the query : What means the `` Any '' function and what does the `` = > '' operator do ? Can someone explain me what 's going on in this code ? Thanks ! <code> public class Address { public string Country ; public string City ; } public class Traveller { public string Name ; public List < Address > TravelRoute ; } List < Traveller > Travellers ; var result = from t in Travellers where t.TravelRoute.Any ( a = > a.Country == `` F '' ) select t ; foreach ( var t in result ) System.Console.WriteLine ( t.Name ) ;
What does this LINQ query do ?
C_sharp : I feel like I played buzzword bingo with the title . Here 's a concise example of what I 'm asking . Let 's say I have some inheritance hierarchy for some entities.Now let 's say I have a generic interface for a service with a method that uses the base class : I have some concrete implementations : Assume I 've registered these all with the container . So now my question is if I 'm iterating through a List of BaseEntity how do I get the registered service with the closest match ? What I 'd like to do is have a mechanism set up such that if an entity has a type of ClassA the method would find no service for the specific class and so would return BaseEntityService . Later if someone came along and added a registration for this service : The hypothetical GetService method would start providing the ClassAEntityService for the ClassA types without requiring any further code changes . Conversely if someone came along and just removed all the services except BaseEntityService then the GetService method would return that for all classes inheriting from BaseEntity.I 'm pretty sure I could roll something even if the DI container I 'm using does n't directly support it . Am I falling into a trap here ? Is this an anti pattern ? EDIT : Some discussion with @ Funk ( see below ) and some additional Google searches those discussions made me think to look up has made me add some more buzzwords to this . It seems like I 'm trying collect all the advantages of DI Containers , the Strategy Pattern and the Decorator Pattern in a type safe way and without using a Service Locator Pattern . I 'm beginning wonder if the answer is `` Use a Functional Language . '' <code> class BaseEntity { ... } class ChildAEntity : BaseEntity { ... } class GrandChildAEntity : ChildAEntity { ... } class ChildBEntity : BaseEntity { ... } interface IEntityService < T > where T : BaseEntity { void DoSomething ( BaseEntity entity ) ... } class BaseEntityService : IEntityService < BaseEntity > { ... } class GrandChildAEntityService : IEntityService < GrandChildAEntity > { ... } class ChildBEntityService : IEntityService < ChildBEntity > { ... } var entities = List < BaseEntity > ( ) ; // ... foreach ( var entity in entities ) { // Get the most specific service ? var service = GetService ( entity.GetType ( ) ) ; // Maybe ? service.DoSomething ( entity ) ; } class ClassAEntityService : IEntityService < ChildAEntity > { ... }
Mechanism for Dependency Injection to Provide the Most Specific Implementation of a Generic Service Interface
C_sharp : If the data is on a single line the index=int.Parse ( logDataReader.ReadElementContentAsString ( ) ) ; andvalue=double.Parse ( logDataReader.ReadElementContentAsString ( ) , cause the cursor to move forward . If I take those calls out I see it loop 6 times in debug.In the following only 3 < data > are read ( and they are wrong as the value is for the next index ) on the first ( < logData id= '' Bravo '' > ) . On the second ( < logData id= '' Bravo '' > ) all < data > are read.It is not an option to edit the xml and put in line breaks as that file is created dynamically ( by XMLwriter ) . The NewLineChars setting is a line feed . From XMLwriter it is actually just one line - I broke it down to figure out where it was breaking . In the browser it is displayed properly.How to fix this ? Here is my XML : And my code : <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < log > < logData id= '' Alpha '' > < data > < index > 100 < /index > < value > 150 < /value > < /data > < data > < index > 110 < /index > < value > 750 < /value > < /data > < data > < index > 120 < /index > < value > 750 < /value > < /data > < data > < index > 130 < /index > < value > 150 < /value > < /data > < data > < index > 140 < /index > < value > 0 < /value > < /data > < data > < index > 150 < /index > < value > 222 < /value > < /data > < /logData > < logData id= '' Bravo '' > < data > < index > 100 < /index > < value > 25 < /value > < /data > < data > < index > 110 < /index > < value > 11 < /value > < /data > < data > < index > 120 < /index > < value > 1 < /value > < /data > < data > < index > 130 < /index > < value > 25 < /value > < /data > < data > < index > 140 < /index > < value > 0 < /value > < /data > < data > < index > 150 < /index > < value > 1 < /value > < /data > < /logData > < /log > static void Main ( string [ ] args ) { List < LogData > logDatas = GetLogDatasFromFile ( `` singleVersusMultLine.xml '' ) ; Debug.WriteLine ( `` Main '' ) ; Debug.WriteLine ( `` logData '' ) ; foreach ( LogData logData in logDatas ) { Debug.WriteLine ( $ '' logData.ID { logData.ID } '' ) ; foreach ( LogPoint logPoint in logData.LogPoints ) { Debug.WriteLine ( $ '' logData.Index { logPoint.Index } logData.Value { logPoint.Value } '' ) ; } } Debug.WriteLine ( `` end '' ) ; } public static List < LogData > GetLogDatasFromFile ( string xmlFile ) { List < LogData > logDatas = new List < LogData > ( ) ; using ( XmlReader reader = XmlReader.Create ( xmlFile ) ) { // move to next `` logData '' while ( reader.ReadToFollowing ( `` logData '' ) ) { var logData = new LogData ( reader.GetAttribute ( `` id '' ) ) ; using ( var logDataReader = reader.ReadSubtree ( ) ) { // inside `` logData '' subtree , move to next `` data '' while ( logDataReader.ReadToFollowing ( `` data '' ) ) { // move to index logDataReader.ReadToFollowing ( `` index '' ) ; // read index var index = int.Parse ( logDataReader.ReadElementContentAsString ( ) ) ; // move to value logDataReader.ReadToFollowing ( `` value '' ) ; // read value var value = double.Parse ( logDataReader.ReadElementContentAsString ( ) , CultureInfo.InvariantCulture ) ; logData.LogPoints.Add ( new LogPoint ( index , value ) ) ; } } logDatas.Add ( logData ) ; } } return logDatas ; } public class LogData { public string ID { get ; } public List < LogPoint > LogPoints { get ; } = new List < LogPoint > ( ) ; public LogData ( string id ) { ID = id ; } } public class LogPoint { public int Index { get ; } public double Value { get ; } public LogPoint ( int index , double value ) { Index = index ; Value = value ; } }
XmlReader behaves different with line breaks
C_sharp : I have a Windows store app that draws an image under the system 's cursor . I capture all the cursor movements using : And this is working fine if I use my mouse to move the cursor.However , I have another application - a desktop application - , that changes the position of the system 's cursor . I 'm using this method to set the position of the cursor programatically : However , when the cursor is moved programatically , the PointerMovedEvent on the store app does not fire ! Does anyone know how I can solve this problem ? <code> var window = Window.Current .Content ; window .AddHandler ( PointerMovedEvent , new PointerEventHandler ( window_PointerMoved ) , true ) ; [ DllImport ( `` user32 '' ) ] private static extern int SetCursorPos ( int x , int y ) ;
PointerMoved event not firing
C_sharp : So I use Visual Studio 2017 and everything worked ok . But then I updated to 15.6.0 and suddenly nothing is working anymore.All the references like Systme . * or Microsoft . * are with a yellow warning sign ... At every project - even new ones- I keep getting the same type of erros after ( re ) building : I have tried reinstalling Visual Studio 2017 , reinstalling .NET Framework , but I still get these type of errors on every C # project ... Is there any solution , next to completely reinstalling Windows ? <code> The `` ResolveAssemblyReference '' task could not be initialized with its input parametersThe `` ResolveAssemblyReference '' task could not be initialized with its input parameters The `` FindDependenciesOfExternallyResolvedReferences '' parameter is not supported by the `` ResolveAssemblyReference '' task . Verify the parameter exists on the task , and it is a settable public instance property This project references NuGet package ( s ) that are missing on this computer . Use NuGet Package Restore to download them
Can not find reference System
C_sharp : I 'm developing an assistive technology application ( in C # ) that overlays information on top of the currently open window . It detects clickable elements , and labels them.To do this , I 'm currently creating a borderless , transparent window with TopMost set to `` true '' , and drawing the labels on that . This means there is always a window hovering in front of the current application , on which I can draw the labels.The problem is , this window does n't cover the right-click menu - only other windows . When the user right-clicks , the context menu is drawn above the overlay . I need to be able to label elements in the right-click menu , but I ca n't draw on top of it with the current implementation . Does anybody know of a solution ? Edit : This is the relevant code for drawing the overlay . I 've set the form options in the form designer , not in the code explicity , so I 'm not sure how much it will help . I 've removed the code not related to drawing , or the form itself : <code> public partial class OverlayForm : Form { public OverlayForm ( ) { } protected override void OnPaint ( PaintEventArgs eventArgs ) { base.OnPaint ( eventArgs ) ; Graphics graphics = eventArgs.Graphics ; Brush brush = new SolidBrush ( this.labelColor ) ; foreach ( ClickableElement element in this.elements ) { Region currentRegion = element.region ; graphics.FillRegion ( brush , currentRegion ) ; } } }
How to draw on top of the right-click menu in .NET/C # ?
C_sharp : Otherwise I always need to check if the value is null before performing any other validations . It 's kinda annoying if I have many custom checks that are using Must ( ) .I placed NotEmpty ( ) at the very top of it therefore it already returns false , is it possible to stop there ? Example <code> RuleFor ( x = > x.Name ) .NotEmpty ( ) // Can we not even continue if this fails ? .Length ( 2 , 32 ) .Must ( x = > { var reserved = new [ ] { `` id '' , `` email '' , `` passwordhash '' , `` passwordsalt '' , `` description '' } ; return ! reserved.Contains ( x.ToLowerInvariant ( ) ) ; // Exception , x is null } ) ;
Is it possible to stop checking further validations when the first one fails ?
C_sharp : I have a partial class using an interface because I can ’ t inherit what was an original abstract class due to the other partial class being auto-generated from Entity Framework 4 and therefore already inheriting ObjectContext.I have the following for my partial class : Here ’ s the interface : And the implementation : Don ’ t worry about the rules , they work . The problem is if I use an abstract class in a test project , the Validate ( ) method in BusinessObject will correctly identity ( this ) as whatever class inherited the abstract class ( in this example , I would expect that to be MyObject ) .Unfortunately , switching to an Interface , ( this ) loses the inheriting class and instead identifies this as BusinessObject.How can I make it so the inheriting class is properly identified ? Here ’ s the calling console class : This should be valid but will instead be invalid because ( this ) is identified as being type BusinessObject instead of MyObject.Argh ! I 'm so close , it 's pretty vexing.Richard <code> namespace Model { using Microsoft.Practices.EnterpriseLibrary.Validation ; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators ; using Utilities.BusinessRules ; using Utilities.BusinessRules.Rules ; [ HasSelfValidation ] public partial class MyObject : IBusinessObject { private readonly IBusinessObject businessObject = new BusinessObject ( ) ; private IBusinessObject BusinessObject { get { return businessObject ; } } public Comment ( ) { AddRule ( new ValidateRequired ( `` Title '' ) ) ; } public void AddRule ( BusinessRule rule ) { BusinessObject.AddRule ( rule ) ; } [ SelfValidation ] public void Validate ( ValidationResults results ) { BusinessObject.Validate ( results ) ; } } } namespace Utilities.BusinessRules { using Microsoft.Practices.EnterpriseLibrary.Validation ; public interface IBusinessObject { void AddRule ( BusinessRule rule ) ; void Validate ( ValidationResults results ) ; } } namespace Utilities.BusinessRules { using System.Collections.Generic ; using System.Linq ; using Microsoft.Practices.EnterpriseLibrary.Validation ; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators ; public class BusinessObject : IBusinessObject { private readonly IList < BusinessRule > businessRules = new List < BusinessRule > ( ) ; public void AddRule ( BusinessRule rule ) { this.businessRules.Add ( rule ) ; } [ SelfValidation ] public void Validate ( ValidationResults results ) { foreach ( var rule in this.businessRules ) { if ( ! rule.Validate ( this ) ) { results.AddResult ( new ValidationResult ( rule.ErrorMessage , this , rule.Key , rule.Tag , null ) ) ; } } } } } namespace ModelConsumer { using Model ; using System ; using Microsoft.Practices.EnterpriseLibrary.Validation ; class Program { static void Main ( string [ ] args ) { using ( var myEntities = new MyEntities ( ) ) { var myObject= new MyObject ( ) ; myObject.Title = `` Credo '' ; var validationResults = Validation.Validate ( myObject ) ; if ( validationResults.IsValid ) { myEntities.MyObjects.AddObject ( myObject ) ; //myEntities.SaveChanges ( ) ; Console.WriteLine ( `` Valid . `` ) ; } else { foreach ( var validationResult in validationResults ) { Console.WriteLine ( validationResult.Message ) ; } } Console.Read ( ) ; } } } }
Inherited C # Class Losing `` Reference ''
C_sharp : I have several c # structs that give shape to structures in a very large data file . These structs interpret bits in the file 's data words , and convert them to first-class properties . Here is an example of one : I need to do two things , which I think are related . The first is to have the ability to validate the entire class , using a collection of validation rules . I know there are several ways to do this ; the one that most appeals to me is to annotate each property with something like this : ... and then use a Validator class to read all of the property attributes , check each property value against the annotated rule ( s ) , and return a collection of error objects . But I am concerned with how long the Reflection is going to take ; these structures have to be extremely high-performing.The second thing I need to do is to perform auditing on property changes ; that is , for each property that has changed from its original value , I need to be able to get a string that says `` Property foo changed from bar to baz . '' To do that , I 'd like a way to compare all properties of a `` before '' and `` after '' struct , and note the differences . In both cases , the code will involve iterating over all of the properties and examining each one individually , in a way that is as fast as possible.How would I approach this ? <code> [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct TimeF1_MsgDayFmt { // Time Data Words public UInt16 TDW1 ; public UInt16 TDW2 ; public UInt16 TDW3 ; /// < summary > /// Tens of milliseconds /// < /summary > public UInt16 Tmn { // Bits.Get is just a helper method in a static class get { return Bits.Get ( TDW1 , 0 , 4 ) ; } set { if ( value > 9 ) throw new ArgumentOutOfRangeException ( ) ; TDW1 = Bits.Set ( TDW1 , value , 0 , 4 ) ; } } /// Several other properties follow . [ ValidateRange ( 0,9 ) ] public UInt16 Tmn { get { return Bits.Get ( TDW1 , 0 , 4 ) ; } set { /// etc . Will probably no longer throw the ArgumentOutOfRangeException here . public List < Error > Validate ( TimeF1_MsgDayFmt original ) public List < string > Compare ( TimeF1_MsgDayFmt original , TimeF1_MsgDayFmt new )
Auditing and validating changes to C # class and structure properties in a high-performance way
C_sharp : I 've been battling with OAuth and Twitter for 2 weeks now trying to implement it . After many rewrites of my code I 've finally got a library which performs the request as it should be based on the 1.0 spec . I 've verified it by using this verifier on Google Code , and this verifier from Hueniverse.My version , the Google version and the Hueniverse version all produce the exact same signature , so I 've concluded that I am no longer the cause ( but I could be putting a foot in my mouth by stating this ... ) .I test my implementation by first creating a test request using Twitter 's API Console , in this case a status update . I copy the params that change , the oauth_nonce and oauth_timestamp , into all three signers stated above . All other params are always the same , tokens/secrets/etc.Twitter 's console produces one signature , but the other three above all produce a different signature ( from Twitter 's , identical to each other ) .So , my question is , why am I getting this : ... when I should be implementing the spec to the `` T '' ? Is there something specific that Twitter needs/wants as part of the request ? I 've counted the nonce generated by Twitter as 42 chars long , is that correct ? Should it be 42 chars long ? I would appreciate help from anyone with more insight into the API than I obviously have ... Thanks in advance ! UPDATE : Someone asked about how I send the authentication params , but has since deleted their post , idk why . Anyway , the authorization params are sent via the Authorization header.UPDATE/SOLUTION : Is moved down to the bottom where it belongs as an answer . <code> < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < hash > < request > /1/statuses/update.xml < /request > < error > Could not authenticate with OAuth. < /error > < /hash >
Is Twitter implemeting OAuth off spec ? ( C # )
C_sharp : I have an Angular front-end app and an ASP.NET Core back-end app . Everything was fine until I decided to migrate from ASP.NET Core 2.2 to 3.0-preview-9.For example , I have a DTO class : And an example JSON request : Before migration , this was a valid request because 123 was parsed as a decimal . But now , after migration , I am getting an HTTP 400 error with this body : In addition , it does n't hit the first line of my method—it is thrown before , probably during model binding.If I send the following , however : Everything works fine . But this means that I need to change every request I have written so far . The same thing is true with all other data types ( int , bool , … ) .Does anybody know how I can avoid this and make it work without changing my requests ? <code> public class DutyRateDto { public string Code { get ; set ; } public string Name { get ; set ; } public decimal Rate { get ; set ; } } { `` name '' : '' F '' , `` code '' : '' F '' , `` rate '' : '' 123 '' } { `` type '' : `` https : //tools.ietf.org/html/rfc7231 # section-6.5.1 '' , `` title '' : `` One or more validation errors occurred . `` , `` status '' : 400 , `` traceId '' : `` |3293cead-4a35656a3ae5e95b . `` , `` errors '' : { `` $ .rate '' : [ `` The JSON value could not be converted to System.Decimal . Path : $ .rate | LineNumber : 0 | BytePositionInLine : 35 . '' ] } } { `` name '' : '' F '' , `` code '' : '' F '' , `` rate '' :123 }
Model binding stopped working after migrating from .NET Core 2.2 to 3.0-preview-9
C_sharp : I wanted to get the projected Balance for the next 12 months from the current month and if the Balance is empty for that month it will get the value from the nearest Month with a Balance of greater than 0.This is what I have tried so far . This would result to : Is it possible to get a result somewhat like this : I ca n't seem to complete the query so I 've set zeroes for now . Any help would be much appreciated . Thanks ! <code> void Main ( ) { var firstDayMonth = new DateTime ( DateTime.Now.Year , DateTime.Now.Month , 1 ) ; var months = Enumerable.Range ( 0 , 12 ) .Select ( m = > new { Month = firstDayMonth.AddMonths ( m ) } ) ; List < SomeDate > SomeDates = new List < SomeDate > ( ) { new SomeDate { Id = 1 , Month = firstDayMonth.AddMonths ( 0 ) , Balance = 1m } , new SomeDate { Id = 2 , Month = firstDayMonth.AddMonths ( 2 ) , Balance = 1m } , new SomeDate { Id = 3 , Month = firstDayMonth.AddMonths ( 1 ) , Balance = 6m } , new SomeDate { Id = 4 , Month = firstDayMonth.AddMonths ( 2 ) , Balance = 5m } , new SomeDate { Id = 5 , Month = firstDayMonth.AddMonths ( 3 ) , Balance = 3m } , new SomeDate { Id = 6 , Month = firstDayMonth.AddMonths ( 2 ) , Balance = 2m } , new SomeDate { Id = 7 , Month = firstDayMonth.AddMonths ( 3 ) , Balance = 4m } , new SomeDate { Id = 8 , Month = firstDayMonth.AddMonths ( 1 ) , Balance = 2m } , new SomeDate { Id = 9 , Month = firstDayMonth.AddMonths ( 3 ) , Balance = 3m } , } ; var groupedMonths = SomeDates .GroupBy ( c = > c.Month ) .Select ( g = > new { Month = g.Key , SumBalance = g.Sum ( s = > s.Balance ) } ) ; var Projected12MonthsBalance = from m in months join gm in groupedMonths on m.Month equals gm.Month into mm from gm in mm.DefaultIfEmpty ( ) select new { Month = m.Month , Balance = gm == null ? 0m : gm.SumBalance } ; Console.WriteLine ( Projected12MonthsBalance ) ; } // Define other methods and classes herepublic class SomeDate { public int Id { get ; set ; } public DateTime Month { get ; set ; } public decimal Balance { get ; set ; } } Month | Balance7/1/2015 | 18/1/2015 | 89/1/2015 | 810/1/2015 | 1011/1/2015 | 0 ... 6/1/2016 | 0 Month | Balance7/1/2015 | 18/1/2015 | 89/1/2015 | 810/1/2015 | 1011/1/2015 | 10 < -- gets the value from the nearest month with Balance greater than 0 ... 6/1/2016 | 10 < -- gets the value from the nearest month with Balance greater than 0
How to get the next 12 months with empty months
C_sharp : I have an application that has been working for a while . I tried running it with VS2013 and it hangs on a line where it tries to initialize a DataCacheFactory object . The same code works fine with VS2010 and VS2012.No errors are generated . The code just hangs on the line factory = new DataCacheFactory ( ) . The AppFabric DLLs are current versions.I welcome any suggestions for identifying why the code hangs on this line . <code> private static DataCacheFactory GetDataCacheFactory ( ) { if ( factory == null ) { lock ( lockObject ) { if ( factory == null ) { factory = new DataCacheFactory ( ) ; //VS2013 hangs on this line } } } return factory ; }
AppFabric DataCacheFactory ( ) initialization hangs in VS2013 , works fine in VS2010 and VS2012
C_sharp : I am trying to figure out how to create an asynchronous call from Application_Error Method in MVC.I have an e-mail dll that I have written which sends out an e-mail via asynchronous call using Smtp Client.The problem is that when I call SendEmail method in my dll I have conflict of needing to await for the call . Now if I try something like this : It will not work , the method will never even be called.Is there a way for me to make an asynchronous call from a synchronous method ? My research online hinted at HttpServerUtility.TransferRequest possibly being the answer but I could not figure out how to make it work with my request , it just does n't make sense to me at the moment . <code> protected async void Application_Error ( ) { var await emailService.SendEmail ( `` Hello World '' ) ; }
Asynchronous call from Application_Error ( )
C_sharp : Browsing some forum I came across this answer in which the answerer refers to the following as the native call stackWhat exactly is the native call stack with regards to the CLR ( here we are looking at the CLR invoking the Main method I think ) and how can I view and come to understand said native call stack on my local machine for educational purposes ? <code> 00000000 ` 0014ea10 00000642 ` 7f67d4a2 0x642 ` 8015014200000000 ` 0014ea90 00000642 ` 7f5108f5 mscorwks ! CallDescrWorker+0x82 00000000 ` 0014eae0 00000642 ` 7f522ff6 mscorwks ! CallDescrWorkerWithHandler+0xe500000000 ` 0014eb80 00000642 ` 7f49a94b mscorwks ! MethodDesc : :CallDescr+0x306 00000000 ` 0014edb0 00000642 ` 7f474ae4 mscorwks ! ClassLoader : :RunMain+0x23f00000000 ` 0014f010 00000642 ` 7f5efb1a mscorwks ! Assembly : :ExecuteMainMethod+0xbc 00000000 ` 0014f300 00000642 ` 7f467d97 mscorwks ! SystemDomain : :ExecuteMainMethod+0x49200000000 ` 0014f8d0 00000642 ` 7f482c24 mscorwks ! ExecuteEXE+0x47
What exactly is the native call stack with regards to the CLR ?