text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I have a method that returns a new list ( it pertains to a multiple choice answer ) : If I examine the result of this method - I see the correct data , e.g . Red = False , Green = True , Blue = FalseI then try to filter the returned result using the LINQ Where extension method : When I materialise tmpA , 2 things happen : The data in the SOURCE list changes - E.g . Red = True , Green =True , Blue = True The data in tmpA is set to the same wrong datathat the source list has been changed toAny ideas ? <code> public static List < questionAnswer > GetAnswersWithSelections ( this Questions_for_Exam__c question ) { List < questionAnswer > answers = new List < questionAnswer > ( ) ; answers.Add ( new questionAnswer ( ) { Ordinal = 1 , AnswerText = question.AN1__c , Selected = ( bool ) question.Option1__c } ) ; ... return answers ; } List < questionAnswer > CorrectSelections = question.GetAnswersWithSelections ( ) ; var tmpA = CorrectSelections.Where ( opt = > opt.Selected = true ) ; | LINQ WHERE method alters source collection |
C_sharp : Given documentation for string.StartsWith and this snippet ( targeting .net core 2.x ) : This method compares the value parameter to the substring at the beginning of this string that is the same length as value , and returns a value that indicates whether they are equal . To be equal , value must be an empty string ( String.Empty ) , must be a reference to this same instance , or must match the beginning of this instance . This method performs a comparison using the specified casing and culture . https : //docs.microsoft.com/en-us/dotnet/api/system.string.startswith ? view=netcore-2.1It produces expected result on Windows : but when run on Linux ( via docker ) the result is : Would you consider this a bug ? Platform dependent behavior ? Please note I 'm not asking how to make it work ( change to str.StartsWith ( unicodeCtrl , StringComparison.OrdinalIgnoreCase ) ) but rather if you believe this is intended/correct behavior.Edit : I tried to match my local locale on Linux , but it did not make a difference . I tried default C ( en-US-POSIX ) and pl_PL.UTF8 <code> static void Main ( string [ ] args ) { var unicodeCtrl = `` \u0000 '' ; var str = `` x '' ; Console.WriteLine ( $ '' Is it empty = > { unicodeCtrl == string.Empty } '' ) ; Console.WriteLine ( $ '' Lenghts = > { str.Length } { unicodeCtrl.Length } '' ) ; Console.WriteLine ( $ '' Are they equal = > { str == unicodeCtrl } '' ) ; Console.WriteLine ( $ '' Are they ref eq = > { Object.ReferenceEquals ( str , unicodeCtrl ) } '' ) ; Console.WriteLine ( $ '' Contains = > { str.Contains ( unicodeCtrl ) } '' ) ; Console.WriteLine ( $ '' Starts with = > { str.StartsWith ( unicodeCtrl ) } '' ) ; } Is it empty = > False Lenghts = > 1 1Are they equal = > False Are they ref eq = > False Contains = > False Starts with = > False Is it empty = > FalseLenghts = > 1 1Are they equal = > FalseAre they ref eq = > FalseContains = > FalseStarts with = > True | Inconsistent string.StartsWith on different platforms |
C_sharp : In my app I 'm creating folders for archiving old stuff from a harddisc.When creating a new folder I must copy all NTFS rights ( Groups / Users ) from the source folder to the newly created destination folder.Here is what I 've written so far : Is this really all I ought to do or am I missing something important ? <code> FileSecurity fileSecurity = File.GetAccessControl ( filenameSource , AccessControlSections.All ) ; FileAttributes fileAttributes = File.GetAttributes ( filenameSource ) ; File.SetAccessControl ( filenameDest , fileSecurity ) ; File.SetAttributes ( filenameDest , fileAttributes ) ; | How do I copy security information when creating a new folder ? |
C_sharp : I need to assign continuous Ids for some threads when i 'm creating them , and does n't matter what starting id is ( like 11 , 12 , 13 , .. or 9 , 10 , 11 ) This is what i have done , here i am creating 4 threads and invoke My_function ( ) it seems working but can i be guaranteed that i always assign continuous id 's for them <code> for ( byte i = 0 ; i < 4 ; i++ ) { myThreadArray [ i ] = new Thread ( new ParameterizedThreadStart ( My_function ) ) ; myThreadArray [ i ] .Start ( i ) ; } | how to make threads with continuous id 's |
C_sharp : I have a method that uses recursion to traverse a tree and update the items.Currently the method takes pretty long to process all the items , so i started optimizing things . Among those things is the use of a dictionary instead of executing a DB query for each item.The dictionary is defined asThe key type is defined asWhen the method runs it takes around 5000 recursions to update all items.Initially it took around 100 seconds without the dictionary.A first approach with DB queries replaced by the use of a dictionary with int keys took 22 seconds.Now , with DB queries replaced by the use of the dictionary defined above and proper TryGetValue ( ) calls it takes 97 seconds < - WAT.What is going on here ? What could cause this massive performance drop ? EditAt first , it seemed like a hash collision issue to me , so i added a breakpoint in EffectivePermissionKey.Equals ( ) to verify that this method is called but it 's not called , therefore no hash collision i guess.Edit2Now i 'm confused . I thought Equals ( ) only gets called when the hash code does not match . After printing out the hash codes of my keys and the keys used in TryGetValue ( ) i see that these codes match . Then i looked at the source code of Dictionary < > and there 's a line in FindEntry ( ) that looks like this : This means that for each item key in the dictionary the GetHashCode ( ) and Equals ( ) gets called because i process all items in the dictionary as the items are the result of the DB query whereas these results where processed before the dictionary approach anyway . <code> System.Collections.Generic.Dictionary < EffectivePermissionKey , MyData > private struct EffectivePermissionKey { // http : //blog.martindoms.com/2011/01/03/c-tip-override-equals-on-value-types-for-better-performance/ public override bool Equals ( object aObject ) { if ( aObject == null ) return false ; else return aObject is EffectivePermissionKey & & Equals ( ( EffectivePermissionKey ) aObject ) ; } public bool Equals ( EffectivePermissionKey aObject ) { return this.ID == aObject.ID & & this.OrchardUserID == aObject.OrchardUserID ; } public override int GetHashCode ( ) { // http : //stackoverflow.com/a/32502294/3936440 return unchecked ( ID.GetHashCode ( ) * 23 * 23 + OrchardUserID.GetHashCode ( ) * 23 ) ; } public int ID ; public int OrchardUserID ; } if ( entries [ i ] .hashCode == hashCode & & comparer.Equals ( entries [ i ] .key , key ) ) return i ; | Why is my dictionary performing poorly with composite keys in C # ? |
C_sharp : Example : I want the output same charterers as per given input string length . The output should be `` aaaaa '' .I dont like to use own FOR or While loops logic , is there any alternatives to accomplish it . <code> string input = `` super '' ; string rep = `` a '' ; | How to replace whole characters in a string as same characters in c # ? |
C_sharp : I inherited some code and ca n't figure out one piece of it : Can anyone tell what 's happening here ? <code> byte [ ] b = new byte [ 4 ] { 3 , 2 , 5 , 7 } ; int c = ( b [ 0 ] & 0x7f ) < < 24 | b [ 1 ] < < 16 | b [ 2 ] < < 8 | b [ 3 ] ; | Need help understanding usage of bitwise operators |
C_sharp : Shortly , The new C # 6.0 Auto-Implemented Property allows us to make thisNow in somewhere , I changed the property IsSoundEffects = false , So accessing it will be false.hmm , So how to get the actual real default compile-time auto-implemented property value.Something Like : Type.GetPropertyDefaultValue ( IsSoundEffects ) ; // A real compile-time one = trueOR Why I need that ? because I filling the properties from the database . and restore it if user need to restore the default values . for example settings.Looks strange ? I searched enough but all examples about the auto-implemented feature did not restore the default value.EditedThe best approaches provided by xiangbin.pang answer for reflection way [ Short-One ] Christopher answers for constants as default values . <code> public static bool IsSoundEffects { get ; set ; } = true ; // C # 6.0 allows this default ( IsSoundEffects ) // idk , something like that | How to get default compile-time value of Auto-Implemented property C # 6.0 after it changed ? |
C_sharp : I 've started using nullable reference types in C # 8 . So far , I 'm loving the improvement except for one small thing.I 'm migrating an old code base , and it 's filled with a lot of redundant or unreachable code , something like : Unfortunately , I do n't see any warning settings that can flag this code for me ! Was this an oversight by Microsoft , or am I missing something ? I also use ReSharper , but none of its warning settings appear to capture this either . Has anybody else found a solution to this ? Edit : I 'm aware that technically this is still reachable because the nullability checks are n't bulletproof . That 's not really the point . In a situation like this , where I declare a paramater as NOT nullable , it is a usually a mistake to check if it 's null . In the rare event that null gets passed in as a non-nullable type , I 'd prefer to see the NullReferenceException and track down the offending code that passed in null by mistake . <code> void Blah ( SomeClass a ) { if ( a == null ) { // this should be unreachable , since a is not nullable } } | In C # 8 , how do I detect impossible null checks ? |
C_sharp : Here are a few example of classes and properties sharing the same identifier : This problem occurs more frequently when using POCO with the Entity Framework as the Entity Framework uses the Property Name for the Relationships.So what to do ? Use non-standard class names ? YukOr use more descriptive Property Names ? Less than ideal , but can live with it I suppose.Or JUST LIVE WITH IT ? What are you best practices ? <code> public Coordinates Coordinates { get ; set ; } public Country Country { get ; set ; } public Article Article { get ; set ; } public Color Color { get ; set ; } public Address Address { get ; set ; } public Category Category { get ; set ; } public ClsCoordinates Coordinates { get ; set ; } public ClsCountry Country { get ; set ; } public ClsArticle Article { get ; set ; } public ClsColor Color { get ; set ; } public ClsAddress Address { get ; set ; } public ClsCategory Category { get ; set ; } public Coordinates GeographicCoordinates { get ; set ; } public Country GeographicCountry { get ; set ; } public Article WebArticle { get ; set ; } public Color BackgroundColor { get ; set ; } public Address HomeAddress { get ; set ; } public Category ProductCategory { get ; set ; } | How to avoid using the same identifier for Class Names and Property Names ? |
C_sharp : I wrote the following method to determine the max file size : Code Complete recommends to `` use recursion selectively '' . That being the case , I was wondering if the community thought this was a valid use of recursion . If not , is there a better technique of doing this ? EDIT : I ca n't use LINQ because its not available in .NET 2.0 , but I do n't want to tag this as a .NET 2.0 question only to further discussion points like Jared 's below . EDIT : Cleaned up code based on an issue that was spotted in not getting the root directory 's files . <code> public static long GetMaxFileSize ( string dirPath , long maxFileSize ) { DirectoryInfo [ ] dirInfos = new DirectoryInfo ( dirPath ) .GetDirectories ( ) ; foreach ( DirectoryInfo dirInfo in dirInfos ) { DirectoryInfo [ ] subDirInfos = dirInfo.GetDirectories ( ) ; foreach ( DirectoryInfo subDirInfo in subDirInfos ) maxFileSize = GetMaxFileSize ( dirInfo.FullName , maxFileSize ) ; FileInfo [ ] fileInfos = dirInfo.GetFiles ( ) ; foreach ( FileInfo fileInfo in fileInfos ) { if ( maxFileSize < fileInfo.Length ) maxFileSize = fileInfo.Length ; } } return maxFileSize ; } public static long GetMaxFileSize ( DirectoryInfo dirInfo , long maxFileSize ) { DirectoryInfo [ ] subDirInfos = dirInfo.GetDirectories ( ) ; foreach ( DirectoryInfo subDirInfo in subDirInfos ) { maxFileSize = GetMaxFileSize ( subDirInfo , maxFileSize ) ; } FileInfo [ ] fileInfos = dirInfo.GetFiles ( ) ; foreach ( FileInfo fileInfo in fileInfos ) { if ( maxFileSize < fileInfo.Length ) maxFileSize = fileInfo.Length ; } return maxFileSize ; } | Is Recursion the Best Option for Determining the Max File Size in a Directory |
C_sharp : Same different behavior can be founded when compiling Expression.Convert for this conversions : Single - > UInt32Single - > UInt64Double - > UInt32Double - > UInt64Looks strange , is n't it ? < === Added some my research === > I 'm looked at the compiled DynamicMethod MSIL code using DynamicMethod Visualizer and some reflection hack to get DynamicMethod from the compiled Expression < TDelegate > : And what I get is this MSIL code : And the equal C # -compiled method has this body : Do anybody see now that ExpressionTrees compiles not valid code for this conversion ? <code> using System ; using System.Linq.Expressions ; class Program { static void Main ( ) { Expression < Func < float , uint > > expr = x = > ( uint ) x ; Func < float , uint > converter1 = expr.Compile ( ) ; Func < float , uint > converter2 = x = > ( uint ) x ; var aa = converter1 ( float.MaxValue ) ; // == 2147483648 var bb = converter2 ( float.MaxValue ) ; // == 0 } } Expression < Func < float , uint > > expr = x = > ( uint ) x ; Func < float , uint > converter1 = expr.Compile ( ) ; Func < float , uint > converter2 = x = > ( uint ) x ; // get RTDynamicMethod - compiled MethodInfovar rtMethodInfo = converter1.Method.GetType ( ) ; // get the field with the referencevar ownerField = rtMethodInfo.GetField ( `` m_owner '' , BindingFlags.NonPublic | BindingFlags.Instance ) ; // get the reference to the original DynamicMethodvar dynMethod = ( DynamicMethod ) ownerField.GetValue ( converter1.Method ) ; // show me the MSILDynamicMethodVisualizer.Visualizer.Show ( dynMethod ) ; IL_0000 : ldarg.1IL_0001 : conv.i4IL_0002 : ret IL_0000 : ldarg.0IL_0001 : conv.u4IL_0002 : ret | Is this is an ExpressionTrees bug ? |
C_sharp : I 'm getting the error `` FormatException was unhandled '' - on this : I need to be able to do addition and division so that 's why I 'm trying to convert them into an integer . So I 'm not sure how to handle this , would I need to convert them back to string ? The Code : The Hours.txt file includes this : I 'm just trying to modify the digits of Hours and Minutes . Calculating the time elapsed ( the amount of how long the program has been opened ) and adding it to the amount already stored in the text file . Then save it back to the file instead of outputting it to console . ( I parse the file and use regex to grab the digits and I think I need to do if statement to minutes > 60 conversion similar to this afaik ) : <code> List < int > myStringList = LoadHours.ConvertAll ( s = > Int32.Parse ( s ) ) ; //string txt = `` Account : xxx123xxx\r\nAppID 10 : 55 Hours 4 Minutes\r\n\r\nAccount : xxx124xxx\r\nAppID 730 : 62 Hours 46 Minutes\r\nAppID 10 : 3 Hours 11 Minutes\r\n\r\nAccount : xxx125xxx\r\nAppID 10 : 0 Hours 31 Minutes\r\n '' ; string path = @ '' Hours.txt '' ; string text = File.ReadAllText ( @ '' Hours.txt '' ) ; Regex pattern = new Regex ( @ '' ^ ( ( AppID ( ? < appid > \d+ ) : ( ( ? < hours > \d+ ) Hours ) ? ( ( ? < minutes > \d+ ) Minutes ) ? ) | ( Account : ( ? < account > xxx\d+xxx ) ) ) '' , RegexOptions.Multiline ) ; string [ ] lines = File.ReadAllLines ( path ) ; int HrElapsed ; int MinElapsed ; Int32.TryParse ( HoursElapsed ( ) , out HrElapsed ) ; Int32.TryParse ( MinutesElapsed ( ) , out MinElapsed ) ; List < string > LoadHours = new List < string > ( ) ; List < string > LoadMinutes = new List < string > ( ) ; // Iterate through lines foreach ( string line in lines ) { //Check if line matches your format here Match match = pattern.Match ( line ) ; LoadHours.Add ( match.Groups [ `` hours '' ] .Value ) ; LoadMinutes.Add ( match.Groups [ `` minutes '' ] .Value ) ; //File.WriteAllText ( @ '' Hours.txt '' , Regex.Replace ( File.ReadAllText ( @ '' Hours.txt '' ) , @ '' AppID \d+ : \s ( \d+\s\w+\s\d+\s\w+ ) '' , LogTime ) ) ; } List < int > myStringList = LoadHours.ConvertAll ( s = > Int32.Parse ( s ) ) ; List < int > myStringList2 = LoadMinutes.ConvertAll ( s = > Int32.Parse ( s ) ) ; for ( int i = 0 ; i < myStringList.Count ; ++i ) { myStringList [ i ] = myStringList [ i ] + HrElapsed ; } for ( int i = 0 ; i < myStringList2.Count ; ++i ) { myStringList2 [ i ] = myStringList2 [ i ] + MinElapsed ; } string [ ] the_array = myStringList.Select ( i = > i.ToString ( ) ) .ToArray ( ) ; string [ ] the_array2 = myStringList2.Select ( i = > i.ToString ( ) ) .ToArray ( ) ; Regex re = new Regex ( @ '' ^ ( ( AppID ( ? < appid > \d+ ) : ( ( ? < hours > \d+ ) Hours ) ? ( ( ? < minutes > \d+ ) Minutes ) ? ) | ( Account : ( ? < account > xxx\d+xxx ) ) ) '' , RegexOptions.Multiline ) ; string hackount = `` '' ; ( from m in re.Matches ( text ) .Cast < Match > ( ) let acc = m.Groups [ `` account '' ] .Value let app = m.Groups [ `` appid '' ] .Value // let hrs = m.Groups [ `` hours '' ] .Value // let mins = m.Groups [ `` minutes '' ] .Value let timHours = the_array let timMinutes = the_array2 let obj = new { Account = acc == `` '' ? hackount : ( hackount = acc ) , AppId = app , Time = the_array , the_array2 } where app ! = `` '' select obj ) .ToList ( ) .ForEach ( Console.WriteLine ) ; Account : xxx123xxxAppID 10 : 1 Hours 5 MinutesAccount : xxx124xxxAppID 10 : 2 Hours 6 MinutesAppID 10 : 3 Hours 7 MinutesAccount : xxx125xxxAppID 10 : 4 Hours 8 Minutes int TotalHours = HrElapsed + HrStored ; int TotalMinutes = MinElapsed + MinStored ; // Just making sure the minutes do n't end up as `` 141 minutes '' so it 's incrementing hours . if ( TotalMinutes > = 60 ) { int remainder = TotalMinutes % 60 ; int whole = TotalMinutes / 60 ; TotalMinutes = remainder ; TotalHours = TotalHours + whole ; } | C # - An unhandled exception of type System.FormatException - List String to List int |
C_sharp : We 've been using a legacy version ( 3.9.8 ) of ServiceStack for a while now and I decided to try an upgrade to the latest version ( 3.9.70 ) and while it was a clean , no hassle package upgrade - everything compiles and runs - every service URL now returns a `` Handler for Request not found '' 404 result.An example of a URL that used to work : http : //somewebserver.com/services/servicestack/jsv/syncreply/getuserWe use the old API ( IService < T > ) and make no use of REST routes or anything of the sort.The ServiceStack application runs inside an ASP.NET MVC 3 web application , which lives on the URL http : //somewebserver.com/management/controller/action . It does n't seem like it 's interfering as it 's been configured to ignore the ServiceStack route : The ServiceStack code is definitely running as going to http : //somewebserver.com/services/servicestack redirects me to the metadata page , which works.I 've tried following these steps : https : //github.com/ServiceStack/ServiceStack/wiki/Run-servicestack-side-by-side-with-another-web-frameworkBut it does n't seem to make a difference . What I changed in the config to try and make this work:1 ) Removed this old line in system.webServer/handlers2 ) Added this location section:3 ) Added this in the app host setup : Calling the URL fails for both POST and GET , which used to both work.This is all running under IIS 8 . I 'd love to know what 's going on here , so we can finally upgrade and live in 2013 : ) <code> routes.IgnoreRoute ( `` servicestack/ { *pathInfo } '' ) ; < add path= '' servicestack '' name= '' ServiceStack.Factory '' type= '' ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory , ServiceStack '' verb= '' * '' preCondition= '' integratedMode '' resourceType= '' Unspecified '' allowPathInfo= '' true '' / > < location path= '' servicestack '' > < system.web > < httpHandlers > < add path= '' * '' type= '' ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory , ServiceStack '' verb= '' * '' / > < /httpHandlers > < /system.web > < system.webServer > < modules runAllManagedModulesForAllRequests= '' true '' / > < validation validateIntegratedModeConfiguration= '' false '' / > < handlers > < add path= '' * '' name= '' ServiceStack.Factory '' type= '' ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory , ServiceStack '' verb= '' * '' preCondition= '' integratedMode '' resourceType= '' Unspecified '' allowPathInfo= '' true '' / > < /handlers > < /system.webServer > < /location > this.Config.ServiceStackHandlerFactoryPath = `` servicestack '' ; | 404 after upgrading ServiceStack from 3.9.8 to 3.9.70 ( new API ) |
C_sharp : We are seeing a memory leak with one of our WCF applications and I was wondering if someone could clarify something for me . Using windbg I ran ! finalizequeue and it shows thousands of objects in each Heap set as `` Ready for finalization '' . That tells me that the finalizer thread is stuck . So I ran the ! Threads command in windbg to get the finalizer thread id and this is what it shows ... .The first thread in the list is the finalizer thread and the thread id is XXXX . What does that mean ? I 'm guessing it means the thread does not exist anymore , or is n't running . Can someone confirm that or correct my understanding ? UPDATE I ran ~2s ; kb command like Kjell Gunnar suggested in the comments and here 's the output.What does the ZwRemoveIoCompletion mean ? <code> Heap 0generation 0 has 464 finalizable objects ( 0000000033877190- > 0000000033878010 ) generation 1 has 52 finalizable objects ( 0000000033876ff0- > 0000000033877190 ) generation 2 has 19958 finalizable objects ( 0000000033850040- > 0000000033876ff0 ) Ready for finalization 228791 objects ( 0000000033878010- > 0000000033a36dc8 ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Heap 1generation 0 has 1508 finalizable objects ( 000000002ee2e168- > 000000002ee31088 ) generation 1 has 91 finalizable objects ( 000000002ee2de90- > 000000002ee2e168 ) generation 2 has 23498 finalizable objects ( 000000002ee00040- > 000000002ee2de90 ) Ready for finalization 249421 objects ( 000000002ee31088- > 000000002f0182f0 ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Heap 2generation 0 has 66 finalizable objects ( 00000000292660d0- > 00000000292662e0 ) generation 1 has 63 finalizable objects ( 0000000029265ed8- > 00000000292660d0 ) generation 2 has 19411 finalizable objects ( 0000000029240040- > 0000000029265ed8 ) Ready for finalization 238531 objects ( 00000000292662e0- > 00000000294380f8 ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Heap 3generation 0 has 510 finalizable objects ( 0000000034e470d8- > 0000000034e480c8 ) generation 1 has 77 finalizable objects ( 0000000034e46e70- > 0000000034e470d8 ) generation 2 has 19910 finalizable objects ( 0000000034e20040- > 0000000034e46e70 ) Ready for finalization 226933 objects ( 0000000034e480c8- > 0000000035003470 ) Statistics for all finalizable objects ( including all objects ready for finalization ) : ThreadCount : 2969UnstartedThread : 0BackgroundThread : 187PendingThread : 0DeadThread : 2782Hosted Runtime : no Lock ID OSID ThreadOBJ State GC Mode GC Alloc Context Domain Count Apt ExceptionXXXX 2 19e8 0000000001f64b10 80039220 Preemptive 0000000000000000:0000000000000000 000000000d4aacb0 0 Ukn ( Finalizer ) 18 3 cb4 000000000d9bf7a0 102a220 Preemptive 0000000000000000:0000000000000000 000000000150e940 0 MTA ( Threadpool Worker ) 19 4 1a24 000000000f762720 21220 Preemptive 0000000000000000:0000000000000000 000000000150e940 0 Ukn 20 6 e1c 0000000010f4eae0 3029220 Preemptive 0000000000000000:0000000000000000 000000000d4aacb0 0 MTA ( Threadpool Worker ) 22 48 1548 000000001feb1880 21220 Preemptive 0000000000000000:0000000000000000 000000000150e940 0 Ukn 23 49 11a4 000000001feb2050 21220 Preemptive 0000000000000000:0000000000000000 000000000150e940 0 Ukn 24 50 a64 000000001feb2820 21220 Preemptive 0000000000000000:0000000000000000 000000000150e940 0 Ukn 0:028 > ~2s ; kbntdll ! ZwRemoveIoCompletion+0xa:00000000 ` 77c1bdca c3 retRetAddr : Args to Child : Call Site000007fe ` fe0e16ad : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : ntdll ! ZwRemoveIoCompletion+0xa00000000 ` 776f9991 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : KERNELBASE ! GetQueuedCompletionStatus+0x39000007fe ` fb7f6bb1 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : kernel32 ! GetQueuedCompletionStatusStub+0x1100000000 ` 777059cd : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : nativerd ! NOTIFICATION_THREAD : :ThreadProc+0x7100000000 ` 77bfa561 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : kernel32 ! BaseThreadInitThunk+0xd00000000 ` 00000000 : 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 00000000 ` 00000000 : ntdll ! RtlUserThreadStart+0x1d | Finalizer Thread Id |
C_sharp : According to MSDN Libraryusing Statement ( C # Reference ) Defines a scope , outside of which an object or objects will be disposed.But I got this code posted here by some user and I got confused about this : ( please see my comment on the code ) In the above code , does the using statement properly used ? I 'm confused , can anyone please explain how to use using statement and its scoping and when , where and why to use it . Thank you.. <code> using ( OleDBConnection connection = new OleDBConnection ( connectiongString ) ) { if ( connection.State ! = ConnectionState.Open ) connection.Open ( ) ; string sql = `` INSERT INTO Student ( Id , Name ) VALUES ( @ idParameter , @ nameParameter ) '' ; using ( OleDBCommand command = connection.CreateCommand ( ) ) { command.CommandText = sql ; command.CommandType = CommandType.Text ; OleDBParameter idParameter = command.CreateParameter ( ) ; idParameter.DbType = System.Int32 ; idParameter.Direction = Parameterdirection.Input ; idParameter.Name = `` @ idParameter '' ; idParameter.Value = studentId ; OleDBParameter nameParameter = command.CreateParameter ( ) ; try { command.ExecuteNonQuery ( ) ; } finally { // Is it still necessary to dispose these objects here ? command.Dispose ( ) ; connection.Dispose ( ) ; } } } | Confused using `` using '' Statement C # |
C_sharp : I have a model where I am using a discriminator.As I can not share the original code , here is a mockupNow I want my entities to be sorted by the Discriminator , having SomeDog first and only after these , having my Dog entities.Is there any way to actually sort on my Discriminator ? Or do I have to find a workaround ? <code> public class Dog { } public class SomeDog : Dog { } | Sort on discriminator - EF |
C_sharp : I 'm writing a bijective dictionary class , but I want to ensure the two generic types are not the same type for two reasons.Firstly , I would like it to implement the IDictionary interface in both directions , but gives me `` 'BijectiveDictionary < TKey , TValue > ' can not implement both 'IDictionary < TKey , TValue > ' and 'IDictionary < TValue , TKey > ' because they may unify for some type parameter substitutions `` ( which is understandable , but undesirable . ) Secondly , I would like to write an optimized solution if both types are the same.Is this possible ? If not , I can consider not implementing IDictionary , but I could n't guarantee TValue this [ TKey key ] and TKey this [ TValue key ] would be different , which would be unfortunate.It looks like the problem here is that when the two types are the same , the special cases arise.My original intent was to create a dictionary which maps exactly one key to exactly one value , and visa versa , such that for every KeyValuePair < TKey , TValue > ( X , Y ) , a KeyValuePair < TValue , TKey > ( Y , X ) exists as well.When TKey = TValue , then this can be simplified down to a single dictionary : In this case , you can not Add ( 2,3 ) ; Add ( 3,4 ) because Add ( 2,3 ) maps 3 to 2 as well , and [ 3 ] would return 2.However , Jaroslav Jandek 's solution proposed using a second dictionary to do this for cases when TKey ! = TValue . And although this works wonderfully for those cases , ( and what I decided to implement , in the end ) it does n't quite follow my original intent when TKey = TValue , by allowing Add ( 2,3 ) ; Add ( 3,4 ) to map a single key 3 to two values ( 2 in one direction , and 4 in the other , ) though I believe strictly speaking is still a valid bijective function . <code> public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TValue > , IDictionary < TValue , TKey > public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TValue > where TValue : TKey { // Optimized solution } public class BijectiveDictionary < TKey , TValue > : IDictionary < TKey , TValue > , IDictionary < TValue , TKey > where TValue : ! TKey { // Standard solution } public T this [ T key ] { get { return this [ key ] ; } set { base.Add ( key , value ) ; base.Add ( value , key ) ; } } | Using Where to specify different generics |
C_sharp : The ProblemConsider these two extension methods which are just a simple map from any type T1 to T2 , plus an overload to fluently map over Task < T > : Now , when I use the second overload with a mapping to a reference type ... ... I get the following error : CS0121 : The call is ambiguous between the following methods or properties : 'Ext.Map ( T1 , Func ) ' and 'Ext.Map ( Task , Func ) 'Mapping to a value type works fine : But only as long the mapping actually uses the input to produce an output : The QuestionCan anyone please explain to me what is going on here ? I 've already given up on finding a feasible fix for this error , but at least I 'd like to understand the root cause of this mess.Additional NotesSo far I found three workarounds which are unfortunately not acceptable in my use case . The first is to specify the type arguments of Task < T1 > .Map < T1 , T2 > ( ) explicitly : Another workaround is to not use lambdas : And the third option is to restrict the mappings to endofunctions ( i.e . Func < T , T > ) : I created a .NET Fiddle where you can try out all the above examples yourself . <code> public static class Ext { public static T2 Map < T1 , T2 > ( this T1 x , Func < T1 , T2 > f ) = > f ( x ) ; public static async Task < T2 > Map < T1 , T2 > ( this Task < T1 > x , Func < T1 , T2 > f ) = > ( await x ) .Map ( f ) ; } var a = Task .FromResult ( `` foo '' ) .Map ( x = > $ '' hello { x } '' ) ; // ERRORvar b = Task .FromResult ( 1 ) .Map ( x = > x.ToString ( ) ) ; // ERROR var c = Task .FromResult ( 1 ) .Map ( x = > x + 1 ) ; // worksvar d = Task .FromResult ( `` foo '' ) .Map ( x = > x.Length ) ; // works var e = Task .FromResult ( 1 ) .Map ( _ = > 0 ) ; // ERROR var f = Task .FromResult ( `` foo '' ) .Map < string , string > ( x = > $ '' hello { x } '' ) ; // worksvar g = Task .FromResult ( 1 ) .Map < int , int > ( _ = > 0 ) ; // works string foo ( string x ) = > $ '' hello { x } '' ; var h = Task .FromResult ( `` foo '' ) .Map ( foo ) ; // works public static class Ext2 { public static T Map2 < T > ( this T x , Func < T , T > f ) = > f ( x ) ; public static async Task < T > Map2 < T > ( this Task < T > x , Func < T , T > f ) = > ( await x ) .Map2 ( f ) ; } | How to explain this `` call is ambiguous '' error ? |
C_sharp : I wish to transform code like : To : As a first step in making the code more readable , I am willing to use a 3rd party refactoring tool if need be . ( Please do not tell me to use parameter objects and factor methods etc , these may come later once I can at least read the code ! ) <code> var p = new Person ( `` Ian '' , `` Smith '' , 40 , 16 ) var p = new Person ( surname : `` Ian '' , givenName : '' Smith '' , weight:40 , age:16 ) | Is there any tools to help me refactor a method call from using position-based to name-based parameters |
C_sharp : In my Web API controller method , before I map the UpdatePlaceDTO to PlaceMaster , I make a database call to populate the properties that are not covered by the Map but for some reason AutoMapper makes those properties null.I 've tried many of the solutions to IgnoreExistingMembers but none of them work.This is what I have This is the extensionI 've used Modules to inject the mapper to my depedenciesI 've seen in some thread that _mapper.Map actually creates a new object so how we make it to sort of `` add-on '' to the existing property values ? <code> var mappedPlaceMaster = _mapper.Map < PlaceMaster > ( placeMasterDTO ) ; // mappedPlaceMaster.EntityId is null public class PlaceMapperProfile : Profile { protected override void Configure ( ) { // TO DO : This Mapping doesnt work . Need to ignore other properties //CreateMap < UpdatePlaceDto , PlaceMaster > ( ) // .ForMember ( d = > d.Name , o = > o.MapFrom ( s = > s.Name ) ) // .ForMember ( d = > d.Description , o = > o.MapFrom ( s = > s.Description ) ) // .ForMember ( d = > d.ParentPlaceId , o = > o.MapFrom ( s = > s.ParentPlaceId ) ) // .ForMember ( d = > d.LeftBower , o = > o.MapFrom ( s = > s.LeftBower ) ) // .ForMember ( d = > d.RightBower , o = > o.MapFrom ( s = > s.RightBower ) ) .IgnoreAllNonExisting ( ) ; } } public static IMappingExpression < TSource , TDestination > IgnoreAllNonExisting < TSource , TDestination > ( this IMappingExpression < TSource , TDestination > expression ) { foreach ( var property in expression.TypeMap.GetUnmappedPropertyNames ( ) ) { expression.ForMember ( property , opt = > opt.Ignore ( ) ) ; } return expression ; } protected override void Load ( ContainerBuilder builder ) { //register all profile classes in the calling assembly var profiles = from t in typeof ( Navigator.ItemManagement.Data.MappingProfiles.PlaceMapperProfile ) .Assembly.GetTypes ( ) where typeof ( Profile ) .IsAssignableFrom ( t ) select ( Profile ) Activator.CreateInstance ( t ) ; builder.Register ( context = > new MapperConfiguration ( cfg = > { foreach ( var profile in profiles ) { cfg.AddProfile ( profile ) ; } } ) ) .AsSelf ( ) .SingleInstance ( ) ; builder.Register ( c = > c.Resolve < MapperConfiguration > ( ) .CreateMapper ( c.Resolve ) ) .As < IMapper > ( ) .SingleInstance ( ) ; } | AutoMapper 4.2 not ignoring properties in profile |
C_sharp : In Microsoft 's example for how to use the PixelShader they use a singleton . I 've seen the same pattern in other places , and here they say The pixel shader is stored in a private static field _pixelShader . This field is static , because one instance of the compiled shader code is enough for the whole class.We 've seen several memory leak issues when using this pattern . The PixelShader is involved is event handling that do n't always get cleared correctly . We had to freeze them , and saw some improvement . We had to manually do some detachments And even now under stress there are still memory leaks in that area . Does anyone know if the PixelShader uses heavy resources worth the trouble with using a singleton ? <code> // Attach/detach effect as UI element is loaded/unloaded . This avoids // a memory leak in the shader code as described here : element.Loaded += ( obj , args ) = > { effect.PixelShader = ms_shader ; element.Effect = effect ; } ; element.Unloaded += ( obj , args ) = > { effect.PixelShader = null ; element.Effect = null ; } ; | Should using a singleton PixelShader be a best practice ? |
C_sharp : I need to make the graph and I want to the edges and the vertices to be generic typeBut , the edge required the vertex type and the vertex required the edge typeWhat should I do ? <code> public interface IVertex < TVertex , TEdge > where TVertex : IVertex < ? > where TEdge : IEdge < ? > { bool AddEdge ( TEdge e ) ; TEdge FindEdge ( TVertex v ) ; } public interface IEdge < TVertex > where TVertex : IVertex < ? > { TVertex From { get ; } } | Looping generic type in c # |
C_sharp : We have a Single Page App which calls our back-end services ( C # and Python ) , authorizing these requests using the Auth0 SPA flow.Our back end services only make requests to each other as part of processing a request from an SPA user , so currently we just forward the Authorization header from the SPA request , using it to authorize the operation on each called service.I now want to add back-end processing jobs that will make requests between our services , making calls to the existing endpoints . These requests will will not have any existing auth header to forward , so will need to construct their own.Based on the Auth0 docs , here and here , I believe I ought to authorize these requests using a Client Credentials Grant , and I infer that our existing endpoints will therefore need to accept requests authorized in two different ways : from the SPA or from other services.The problem is that JWTs from the SPA are signed using one secret key , while those from services are signed using their respective secret keys . Am I right that I need to configure my endpoints so that they will accept JWTs constructed using any of these secret keys ? So my core question is : Is this understanding correct , or should I be doing it a different way altogether ? Details : The two types of Authorization JWT tokens that our endpoints will need to handle are:1 Requests from our SPA , containing : signed using HS256 ( for historical reasons ) using our SPA 's client secret.2 Service-to-service requests , containing : signed using HS256 ( for now to keep things simple ) using our calling service 's client secret.If one endpoint is going to decode and verify both requests , firstly it will fail because 'aud ' values are different . I think the 'aud ' value of our existing SPA calls is an error - it ought to be the ID of the API receiving the request . Then the 'aud ' values in both requests will be the same.The next difference is that they are each signed with a different secret key - either the SPA 's or the calling service 's ( and potentially with a different algorithm too , if I chose to make the new service calls using RS256 as Auth0 recommends . ) I ca n't spot obvious ways to modify the Python and C # quickstarts to accept tokens encoded with different keys . I 'm thinking about coding it myself , to manually try one , and if it fails then try the other . I 'm confident I can do it for the Python endpoint authorization , which I wrote myself based on the Auth0 quickstart using PyJWT , but less familiar with our C # stuff , which is also based on an Auth0 quickstart but seem to use some built-in .NET JWT validation middleware , and I 'm not at all sure I can get at its innards to add the above functionality.But if I 'm doing this the right way , then surely this is a common requirement ? Apologies if this question is badly-formed , I 'm know nothing about auth , and am reading the Auth0/Oath2 docs to figure it out as I go . <code> sub : SPA-USER-IDaud : SPA-CLIENT-ID sub : SERVICE-ID @ clientsaud : API-IDscope : `` '' | Using Auth0 to Authorize API requests from both our SPA and our other back-end services |
C_sharp : I have a console application and website that use the same System.Runtime.Serialization.Primitives.dll assembly . However , when I run the website , my assembly is the one on the right , but if I run consolation application , the DLL for the website turns to the one on the left and causes errors . Both projects are v4.7 and this started happening after I upgraded all my projects to that Framework.Both projects have this in it <code> < dependentAssembly > < assemblyIdentity name= '' System.Runtime.Serialization.Primitives '' publicKeyToken= '' b03f5f7f11d50a3a '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 0.0.0.0-4.1.2.0 '' newVersion= '' 4.1.2.0 '' / > < /dependentAssembly > | Different DLL but should be the same in console application and website |
C_sharp : When I call an async method and get a task back , will that immediately throw or will it wait until I await the task ? In other words , will this code work ? Or will I have to wrap the method call in the try-block as well ? <code> Task task = ThisMethodWillThrow ( ) ; try { await task ; } catch ( Exception e ) { Console.WriteLine ( `` oops '' ) ; } | Do async methods throw exceptions on call or on await ? |
C_sharp : For all of my POCOs , the navigation and collection properties are all null.Let me provide some background . I have a complex code first project using EF 4.3.1 . Proxy generation was disabled . Collection and navigation properties were managed manually.I 'm now enabling proxy creation and lazy loading . When debugging , I can see that my entity ( which is cast to my known POCO type ) is now actually an auto generated proxy class . So far so good . Now , when I look at my navigation properties , they are null . Similarly , my collection properties are null.Using reflection , I can see that the proxy class HAS overridden my navigation and collection properties.All navigation and collection properties are virtual . e.g : Also , all tables are initialised as such : I can also confirm that the database is generated as expected . Foreign keys are all present and are associated with the expected fields.Why are they null ? How can I diagnose this further ? <code> public virtual NavigationType NavigationName { get ; set ; } public virtual ICollection < CollectionType > CollectionName { get ; set ; } modelBuilder.Entity < TEntity > ( ) .Map ( m = > { m.MapInheritedProperties ( ) ; m.ToTable ( `` TableName '' ) ; } ) ; | code first auto gen proxy class navigation and collection properties are null |
C_sharp : ( Apologies for the long setup . There is a question in here , I promise . ) Consider a class Node that has an immutable unique ID that is assigned at construction time . This ID is used for serialization when persisting the object graph , among other things . For example , when an object is deserialized , it gets tested against the main object graph by ID to look for a collision and reject it.Also , a Node is only instantiated by a private system , and all public accesses to them are done via the INode interface.So we have something like this common pattern : My questions are around these comparison/equality-related features of .NET : IEquatable < T > IComparable / IComparable < T > operator == / operator ! =Here are the questions , finally . When implementing a class like Node : Which of the above interfaces/operators do you implement as well ? Why ? Do you extend IEquatable < T > from INode or Node ? Given that IEquatable < T > only seems to get used ( mostly in the BCL ) through runtime type checks , is there a point to/not to extend from INode ? For those that you do implement , do you do them just on the class itself , or do you additionally do it on the ID as well ? For example , is IEquatable < NodeID > also a part of the Node ? Do you test for obj as NodeID in Equals ? After working in C # for over a decade , I 'm embarrassed not to have a thorough understanding of these interfaces and best practices related to them . ( Note that our .NET systems are built in 95 % C # , 5 % C++/CLI , 0 % VB ( if it makes a difference ) . ) <code> interface INode { NodeID ID { get ; } // ... other awesome stuff } class Node : INode { readonly NodeID _id = NodeID.CreateNew ( ) ; NodeID INode.ID { get { return _id ; } } // ... implement other awesome stuff public override bool Equals ( object obj ) { var node = obj as INode ; return ReferenceEquals ( node , null ) ? false : _id.Equals ( node.ID ) ; } public override int GetHashCode ( ) { return _id.GetHashCode ( ) ; } } | How do immutable ID properties affect .NET equality ? |
C_sharp : I 'm trying to create a shared library project containing some POCO classes used to serialize data among multiple clients ( WPF / SL5 / Asp.Net ) . Before Asp.Net vNext , I was using PCL without problem . Now MVC 6 is there , I tried to add Asp.Net Core 5 target to the PCL , but it seems impossible : I guess the corresponding PCL profile does n't exists yet , so I tried to create a `` Class Library Package '' and add the SL5 target but unfortunately , even if the target is added to the Reference tree without any error , it fails at compilation : with errors like : Like if 'Micorosft.CSharp ' was n't present for 'sl5 ' target ... I can not add 'mscorlib ' to `` sl5 '' dependencies , and even adding BCL does n't helps . I 'm lost.What am I missing ? <code> `` frameworks '' : { `` dotnet '' : { } , `` dnx46 '' : { } , `` dnxcore50 '' : { } , `` sl5 '' : { } } Error CS0518 : Predefined type 'System.Object ' is not defined or imported Error CS0246 : The type or namespace name 'String ' could not be found ( are you missing a using directive or an assembly reference ? ) | Class Library Package : sl5 target issue |
C_sharp : So , I have the airdrop feature working but I need different things to happen if the user presses accept and if the user presses deny for the airdrop request . Currently , the same actions happen whether the user accepts or denies the airdrop request . I 'm using which has this signature : The problem is none of these parameters I can use . Completed always returns true if the user makes either choice and returnedItems is null . What can I use or do to detect if the user denied the Airdrop request ? This is for a Xamarin.iOS app but answers in Swift/native iOS are fine too . Similar SO question with no answer : UIActivityViewController Airdrop - Check the status when 'sent ' or 'declined ' <code> activityViewController.SetCompletionHandler ( HandleActivityViewControllerCompletion ) ; private async void HandleActivityViewControllerCompletion ( NSString activityType , bool completed , NSExtensionItem [ ] returnedItems , NSError error ) | Is there a way to detect if user presses accept or deny for Airdrop request ? |
C_sharp : I 've implemented simple IQueryable and IQueryProvider classes that collect statistical data on LINQ expression trees . This part works fine . Next , I would like to pass the expression tree off to the default LINQ-to-Objects provider for evaluation , since I do n't need to execute it any differently . In order words , I 'd like my provider to collect stats as a side-effect , passing the query on to the default LINQ implementation.However , I am having difficulty getting a handle to the default provider . I thought that I could simply save a reference to the original IEnumerable collection and then return the default provider ( from my custom IQueryable ) like : but this does not work correctly . The code eventually throws a StackOverflowException . What I think is happening ( gleaned from single-stepping in debug mode ) is that the LINQ runtime fetches the provider from the above method , then it fetches the expression tree from my custom IQueryable , and then it notices that the top-level expression is my custom IQueryable . So it starts the process over again , trying to find the appropriate provider . It does this endlessly until a stack overflow occurs.Right now , the only thing I can think of is to come up with another visitor which produces another expression tree with the custom IQueryable nodes removed so that the LINQ runtime will call the default provider . That 's a fair amount of work , since I need to visit every leaf to ensure that there are no nested Call expressions which call my custom IQueryable again . Is there a simpler approach ? Thanks for the help . <code> IQueryProvider IQueryable.Provider { get { return _my_provider.OriginalIEnum ( ) .AsQueryable ( ) .Provider ; } } | LINQ passthrough provider ? |
C_sharp : I expected the following lines of code to throw an exception since I am accessing the Value property of a nullable variable that is assigned a value of null . However , I do not get any exception when I execute the below : But when I do : I do get an exception , as could be expected.But what is the difference between the 2 ways of accessing x.Value ? Why do I not get an exception in the first case ? Both pieces of code are after all trying to access the x.Value property.Note : I am running the above pieces of code on the www.compileonline.com website , btw . Not sure if trying on the Visual Studio compiler would yield different results , but I do not have access to Visual Studio currently.TIA . <code> int ? x=null ; Console.WriteLine ( x.Value==null ) ; Console.WriteLine ( x.Value ) ; | Why does this code not throw an exception ? |
C_sharp : I have code like this : How can I write this code in a convenient way such that : There is no nullability warning , because the type nonNullItems is inferred as IEnumerable < string > .I do n't need to add unchecked non-nullability assertions like item ! ( because I want to benefit from the compilers sanity checking , and not rely on me being an error-free coder ) I do n't add runtime checked non-nullability assertions ( because that 's pointless overhead both in code-size and at runtime , and in case of human error that fails later than ideal ) .The solution or coding pattern can apply more generally to other sequences of items of nullable-reference type.I 'm aware of this solution , which leverages the flow-sensitive typing in the C # 8.0 compiler , but it 's ... . not so pretty , mostly because it 's so long and noisy : Is there a better alternative ? <code> IEnumerable < string ? > items = new [ ] { `` test '' , null , `` this '' } ; var nonNullItems = items.Where ( item = > item ! = null ) ; //inferred as IEnumerable < string ? > var lengths = nonNullItems.Select ( item = > item.Length ) ; //nullability warning hereConsole.WriteLine ( lengths.Max ( ) ) ; var notNullItems = items.SelectMany ( item = > item ! = null ? new [ ] { item } : Array.Empty < string > ( ) ) ) ; | Is there a convenient way to filter a sequence of C # 8.0 nullable references , retaining only non-nulls ? |
C_sharp : I have part of a code that has dependencies that look as follows : My module configuration looks as followsAs can be seen , I have circular dependencies in my classes which I was able to resolve by using the ..PropertiesAutowired ( PropertyWiringFlags.AllowCircularDependencies ) ... My Question : What exactly does this flag do behind the scenes to solve these circular dependencies ? ? <code> public class MyPage : Page //ASPX WebForms page { public IPersonBl PersonBl { get ; set ; } } public class PersonBl : IPersonBl { public PersonBl ( ISomeMagicBl magicBl ) { ... } } public class SomeMagicBl : ISomeMagicBl { public IPersonBl PersonBl { get ; set ; } public SomeMagicBl ( /*Other dependencies*/ ) { ... } } ... builder.RegisterAssemblyTypes ( ThisAssembly ) .Where ( t = > t.Name.EndsWith ( `` BL '' ) ) .AsImplementedInterfaces ( ) .PropertiesAutowired ( PropertyWiringFlags.AllowCircularDependencies ) .InstancePerLifetimeScope ( ) ; ... | AutoFac : What does PropertyWiringFlags.AllowCircularDependencies do ? |
C_sharp : I 've created a rollback/retry mechanism using the Command Pattern and a custom retry mechanism with the RetryCount and timeout threshold properties as input ( As described here Which is the best way to add a retry/rollback mechanism for sync/async tasks in C # ? ) . I also tried the Polly framework instead and it is great ! Now , I want to wrap them in an abstraction . I could describe it as commands plan mechanism or command based decision mechanism.So , Based on the different combinations of command results I have to decide which of the accomplished commands will be reverted and which of them not ( I want to offer the ability to press a ReTry button and some off the commands should n't be reverted ) .These commands are grouped in some categories and I have to take different rollback strategy for the different groups and commands ( based on the result ) . Some kind of different policies would take place here ! IMPORTANT : I want to avoid IF/ELSE etc.Maybe the Chain-of-responsibility pattern would help me but I DO N'T know and I really want help : Another idea could be observables or event handlers but the question is how to use them ( ? ) . Or just by using a list/stack/queue of Commands and check that list to take the next-step decision ( ? ) : SCENARIOSFinally , You can think of twenty ( 20 ) commands grouped in four ( 4 ) categories.Scenario 1Group 1 Commands ( 5 ) were successfulGroup 2 Commands 1 and 2 were successful but Command 3 wasFAILED.Command 4 and 5 not executedGroup 3 not executedGroup 4 not executedDecision 1Rollback Commands 1 and 2 from Group 2 BUT not the whole Group 1CommandsScenario 2Group 1 Commands ( 5 ) were successfulGroup 2 Commands ( 5 ) were successfulGroup 3 Commands ( 5 ) were successfulGroup 4 Commands 1 - 4 were successful BUT Command 5 wasFAILEDDecision 2Rollback All Commands from all GroupsI want to guide me and help me with CODE examples in C # . <code> //Pseudo-code ... CommandHandler actionManager1 = new Action1Manager ( ) ; CommandHandler actionManager2 = new Action2Manager ( ) ; CommandHandler actionManager2 = new Action3Manager ( ) ; actionManager1.SetNextObjManager ( Action2Manager ) ; actionManager2.SetNextObjManager ( Action3Manager ) ; actionManager1.ProcessAction ( ) { ... } actionManager1.ProcessAction ( ) { ... } ... private List < ICommand > rollbackCommandsOfAllGroups ; private List < ICommand > rollbackCommandsOfGroup1 ; private List < ICommand > rollbackCommandsOfGroup2 ; ... | How to create a strategy decision mechanism based on the results combinations of multi-commands in C # |
C_sharp : I have this : And my utility class for databinding does this : But PropertyInfo.CanWrite does not care whether the set is publicly accessible , only that it exists.How can I determine if there 's a public set , not just any set ? <code> public string Log { get { return log ; } protected set { if ( log ! = value ) { MarkModified ( PropertyNames.Log , log ) ; log = value ; } } } PropertyInfo pi = ReflectionHelper.GetPropertyInfo ( boundObjectType , sourceProperty ) ; if ( ! pi.CanWrite ) SetReadOnlyCharacteristics ( boundEditor ) ; | How do I tell if a class property has a public set ( .NET ) ? |
C_sharp : How do I know if a class in C # is unmanaged , so that if I use it in a self defined class I know whether I have to implement the IDisposable interface ? If I get this article on the MSDN network right , I always have to implement the IDisposible interface when I use an unmanaged resource.So I 've created a little example that you can find below : The following MSDN article says for example that File is an unamanged ressource , which is also used in my test class . So how can I see , that this class is unamanged ? The compiler and ReSharper did n't complain anything.Thanks in advance . <code> class TestClass { private StreamReader reader ; public UsingTestClass ( ) { reader = File.OpenText ( `` C : \\temp\\test.txt '' ) ; string s ; while ( ! string.IsNullOrEmpty ( s = reader.ReadLine ( ) ) ) { Console.WriteLine ( s ) ; } } } | How do I know if a class is a wrapper for an unmanaged resource |
C_sharp : When a class is IComparable , then we know everything to overload the < , > and == operators due to the CompareTo functionality , right ? Then why are n't these overloaded automatically ? Take a look at the example below : I was wondering why something like this would n't work by default : We know that obj1 < obj2 == true because of our implementation of CompareTo , but because the < operator is not overloaded , this will not work . ( I know that obj1.CompareTo ( obj2 ) < 0 will give the desired result , but that 's less obvious in most cases . ) Only when I add the code below to the class , it will work the way I expected : This is very generic functionality , so what 's the reason these comparisons do n't work by default on every IComparable ? <code> public class MyComparable : IComparable < MyComparable > { public int Value { get ; } public MyComparable ( int value ) { Value = value ; } public int CompareTo ( MyComparable other ) = > Value.CompareTo ( other.Value ) ; } MyComparable obj1 = new MyComparable ( 1 ) , obj2 = new MyComparable ( 2 ) ; if ( obj1 < obj2 ) { /* ... */ } public static bool operator < ( MyComparable x , MyComparable y ) = > x.CompareTo ( y ) < 0 ; public static bool operator > ( MyComparable x , MyComparable y ) = > x.CompareTo ( y ) > 0 ; // And for equality : public static bool operator ! = ( MyComparable x , MyComparable y ) = > ! ( x == y ) ; public static bool operator == ( MyComparable x , MyComparable y ) { if ( ReferenceEquals ( x , y ) ) return true ; if ( ( ( object ) x == null ) || ( ( object ) y == null ) ) return false ; return x.CompareTo ( y ) == 0 ; } | Why are the comparison operators not automatically overloaded with IComparable ? |
C_sharp : I have a particular situation where I need to trap exceptions and return an object to the client in place of the exception . I can not put the exception handling logic at a higher level i.e . wrap Foo within a try clause.It 's best to demonstrate with some sample code . The exception handling logic is clouding the intention of the method and if I have , many methods of similar intent , in the Foo class , I find myself repeating most of the catch logic . What would be the best technique to wrap the common exception functionality in the code below ? <code> public class Foo { public Bar SomeMethodThatCanThrowExcepetion ( ) { try { return new Bar ( ) .Execute ( ) ; } catch ( BazException ex ) { WriteLogMessage ( ex , Bar.ErrorCode ) ; return new Bar ( ) { ErrorMessage = ex.Message , ErrorCode = Bar.ErrorCode ; } } } public Baz SomeMethodThatCanThrowExcepetion ( SomeObject stuff ) { try { return new Baz ( stuff ) .Execute ( ) ; } catch ( BazException ex ) { WriteLogMessage ( ex , Baz.ErrorCode ) ; return new Baz ( ) { ErrorMessage = ex.Message , ErrorCode = Baz.ErrorCode ; } } } } | How can I make this exception handling code adhere to the DRY principle ? |
C_sharp : I 'm reviewing some code on the project I recently joined , and in a C # Win Forms Application for .NET 3.5 I found this : When I click `` EndPoint/Go To Definition '' it says `` Can not Navigate to Endpoint '' but the project as a whole is pretty small and compiles/runs without error , so it 's not a missing reference or anything.What is EndPoint and what is this syntax with the name : { } ? <code> public void foo ( ) { //Normal code for function foo.//This is at the end and it is left-indented just as I put it here.EndPoint : { } } | EndPoint : Syntax in C # - what is this ? |
C_sharp : i 'm trying to do for an expression tree and try to let it return a simple int value . but it not working anymore <code> var method = typeof ( Console ) .GetMethod ( `` WriteLine '' , new Type [ ] { typeof ( string ) } ) ; var result = Expression.Variable ( typeof ( int ) ) ; var block = Expression.Block ( result , Expression.Assign ( result , Expression.Constant ( 0 ) ) , Expression.IfThenElse ( Expression.Constant ( true ) , Expression.Block ( Expression.Call ( null , method , Expression.Constant ( `` True '' ) ) , Expression.Assign ( result , Expression.Constant ( 1 ) ) ) , Expression.Block ( Expression.Call ( null , method , Expression.Constant ( `` False '' ) ) , Expression.Assign ( result , Expression.Constant ( 0 ) ) ) ) , result ) ; Expression.Lambda < Func < int > > ( block ) .Compile ( ) ( ) ; | How to return value in ExpressionTree |
C_sharp : I created labels and textboxes dynamically . everything goes fine , but the second label does n't want to appear at all . where i am wrong ? this is my code in C # : <code> private void checkedListBox1_SelectedIndexChanged ( object sender , EventArgs e ) { OracleDataReader reader ; int x = 434 ; int y = 84 ; int i = 0 ; try { conn.Open ( ) ; foreach ( var itemChecked in checkedListBox1.CheckedItems ) { Label NewLabel = new Label ( ) ; NewLabel.Location = new Point ( x + 100 , y ) ; NewLabel.Name = `` Label '' + i.ToString ( ) ; Controls.Add ( NewLabel ) ; TextBox tb = new TextBox ( ) ; tb.Location = new Point ( x , y ) ; tb.Name = `` txtBox '' + i.ToString ( ) ; Controls.Add ( tb ) ; y += 30 ; OracleCommand cmd = new OracleCommand ( `` SELECT distinct data_type from all_arguments where owner='HR ' and argument_name= ' '' + itemChecked.ToString ( ) + `` ' '' , conn ) ; reader = cmd.ExecuteReader ( ) ; while ( reader.Read ( ) ) { label [ 0 ] .Text = reader [ `` data_type '' ] .ToString ( ) ; } i++ ; } } finally { if ( conn ! = null ) conn.Close ( ) ; } } private void Procedure ( ) { string proc = `` '' ; try { conn.Open ( ) ; if ( this.listView1.SelectedItems.Count > 0 ) proc = listView1.SelectedItems [ 0 ] .Text ; OracleCommand cmd = new OracleCommand ( `` '' + proc + `` '' , conn ) ; cmd.CommandType = CommandType.StoredProcedure ; cmd.CommandTimeout = 600 ; int i = 0 ; foreach ( var itemChecked1 in checkedListBox1.Items ) { Control [ ] txt = Controls.Find ( `` txtBox '' + i.ToString ( ) , false ) ; Control [ ] label = Controls.Find ( `` Label '' + i.ToString ( ) , false ) ; cmd.Parameters.Add ( new OracleParameter ( `` select distinct data_type from all_arguments where owner='HR ' and argument_name=toupper ( `` +itemChecked1.ToString ( ) + '' ) '' , conn ) ) ; cmd.Parameters [ `` : '' +itemChecked1.ToString ( ) + '' '' ] .Value=label [ 0 ] .Text ; cmd.Parameters.Add ( new OracleParameter ( `` : '' + itemChecked1.ToString ( ) + `` '' , OracleDbType.Varchar2 ) ) ; cmd.Parameters [ `` : '' + itemChecked1.ToString ( ) + `` '' ] .Value = txt [ 0 ] .Text ; i++ ; | where I am wrong ? creating labels dynamically c # |
C_sharp : I have a string in the following format.My desired output should be something like this below : But currently , I get the one below : I am very new to C # and any help would be appreciated . <code> string instance = `` { 112 , This is the first day 23/12/2009 } , { 132 , This is the second day 24/12/2009 } '' private void parsestring ( string input ) { string [ ] tokens = input.Split ( ' , ' ) ; // I thought this would split on the , seperating the { } foreach ( string item in tokens ) // but that does n't seem to be what it is doing { Console.WriteLine ( item ) ; } } 112 , This is the first day 23/12/2009132 , This is the second day 24/12/2009 { 112This is the first day 23/12/2009 { 132This is the second day 24/12/2009 | Efficiently split a string in format `` { { } , { } , ... } '' |
C_sharp : I 'm trying to iterate through some files and fetch their shell icons ; to accomplish this , I 'm using DirectoryInfo.EnumerateFileSystemInfos and some P/Invoke to call the Win32 SHGetFileInfo function . But the combination of the two seems to corrupt memory somewhere internally , resulting in ugly crashes.I 've boiled down my code to two similar test cases , both of which crash seemingly without reason . If I do n't call DirectoryInfo.EnumerateFileSystemInfos , no crash appears ; if I do n't call SHGetFileInfo , no crash appears . Note that I 've removed the actual use of the FileSystemInfo objects in my code , since I can get it to reproduce simply by iterating over them and asking for the text file icon over and over . But why ? Here are my complete , minimal test cases . Run them under the VS debugger to ensure no optimizations are enabled : Can anyone spot the bug ? Any help is appreciated ! <code> using System ; using System.Linq ; using System.Collections.Generic ; using System.Diagnostics ; using System.IO ; using System.Runtime.InteropServices ; using System.Windows ; using System.Windows.Interop ; using System.Windows.Media.Imaging ; namespace IconCrashRepro { // Compile for .NET 4 ( I 'm using 4.5.1 ) . // Also seems to fail in 3.5 with GetFileSystemInfos ( ) instead of EnumerateFileSystemInfos ( ) public class Program { // Compile for .NET 4 ( I 'm using 4.5.1 ) public static void Main ( ) { // Keep a list of the objects we generate so // that they 're not garbage collected right away var sources = new List < BitmapSource > ( ) ; // Any directory seems to do the trick , so long // as it 's not empty . Within VS , ' . ' should be // the Debug folder var dir = new DirectoryInfo ( @ '' . `` ) ; // Track the number of iterations , just to see ulong iteration = 0 ; while ( true ) { // This is where things get interesting -- without the EnumerateFileSystemInfos , // the bug does not appear . Without the call to SHGetFileInfo , the bug also // does not appear . It seems to be the combination that causes problems . var infos = dir.EnumerateFileSystemInfos ( ) .ToList ( ) ; Debug.Assert ( infos.Count > 0 ) ; foreach ( var info in infos ) { var shFileInfo = new SHFILEINFO ( ) ; var result = SHGetFileInfo ( `` .txt '' , ( uint ) FileAttributes.Normal , ref shFileInfo , ( uint ) Marshal.SizeOf ( shFileInfo ) , SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON ) ; //var result = SHGetFileInfo ( info.FullName , ( uint ) info.Attributes , ref shFileInfo , ( uint ) Marshal.SizeOf ( shFileInfo ) , SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON ) ; if ( result ! = IntPtr.Zero & & shFileInfo.hIcon ! = IntPtr.Zero ) { var bmpSource = Imaging.CreateBitmapSourceFromHIcon ( shFileInfo.hIcon , Int32Rect.Empty , BitmapSizeOptions.FromEmptyOptions ( ) ) ; sources.Add ( bmpSource ) ; // Originally I was releasing the handle , but even if // I do n't the bug occurs ! //DestroyIcon ( shFileInfo.hIcon ) ; } // Execution fails during Collect ; if I remove the // call to Collect , execution fails later during // CreateBitmapSourceFromHIcon ( it calls // AddMemoryPressure internally which I suspect // results in a collect at that point ) . GC.Collect ( ) ; ++iteration ; } } } public static void OtherBugRepro ( ) { // Rename this to Main ( ) to run . // Removing any single line from this method // will stop it from crashing -- including the // empty if and the Debug.Assert ! var sources = new List < BitmapSource > ( ) ; var dir = new DirectoryInfo ( @ '' . `` ) ; var infos = dir.EnumerateFileSystemInfos ( ) .ToList ( ) ; Debug.Assert ( infos.Count > 0 ) ; // Crashes on the second iteration -- says that // ` infos ` has been modified during loop execution ! ! foreach ( var info in infos ) { var shFileInfo = new SHFILEINFO ( ) ; var result = SHGetFileInfo ( `` .txt '' , ( uint ) FileAttributes.Normal , ref shFileInfo , ( uint ) Marshal.SizeOf ( shFileInfo ) , SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON ) ; if ( result ! = IntPtr.Zero & & shFileInfo.hIcon ! = IntPtr.Zero ) { if ( sources.Count == 1000 ) { } } } } [ StructLayout ( LayoutKind.Sequential ) ] private struct SHFILEINFO { public IntPtr hIcon ; public int iIcon ; public uint dwAttributes ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 260 ) ] public string szDisplayName ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 80 ) ] public string szTypeName ; } private const uint SHGFI_ICON = 0x100 ; private const uint SHGFI_LARGEICON = 0x0 ; private const uint SHGFI_SMALLICON = 0x1 ; private const uint SHGFI_USEFILEATTRIBUTES = 0x10 ; [ DllImport ( `` shell32.dll '' , CharSet = CharSet.Unicode ) ] private static extern IntPtr SHGetFileInfo ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszPath , uint dwFileAttributes , ref SHFILEINFO psfi , uint cbSizeFileInfo , uint uFlags ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] private static extern bool DestroyIcon ( IntPtr hIcon ) ; } } | Why does this interop crash the .NET runtime ? |
C_sharp : I 'm using WindowsPrincipal 's IsInRole method to check group memberships in WPF and Winforms apps . I 'm generating an identity token which can be for any AD user ( not necessarily the user who 's actually logged into the computer -- depending on what I 'm doing I do n't necessarily authenticate , I just use the basic informational level token ( I think the proper name for it is `` identity token '' ) .The first time this code is run on a particular computer the operating system generates the identity token for the user specified . That token is then used by the IsInRole function to validate group memberships . It 's fast so I really like it . However , subsequent calls to create the WindowsIdentity/WindowsPrincipal reference the existing token instead of creating a new one . The only way I know how to update the token is to log out of the computer or reboot ( which clears the token cache ) . Does anyone know a better way to reset cached identity tokens ? Example Code C # : VB : <code> Using System.Security.Principal ; WindowsIdentity impersonationLevelIdentity = new WindowsIdentity ( `` Some_UserID_That_Isn't_Me '' , null ) ; WindowsPrincipal identityWindowsPrincipal = new WindowsPrincipal ( impersonationLevelIdentity ) ; If ( identityWindowsPrincipal.IsInRole ( `` AN_AD_GROUP '' ) ) { ... Imports System.Security.PrincipalDim impersonationLevelIdentity = New WindowsIdentity ( `` Some_UserID_That_Isn't_Me '' , Nothing ) Dim identityWindowsPrincipal = New WindowsPrincipal ( impersonationLevelIdentity ) if identityWindowsPrincipal.IsInRole ( `` AN_AD_GROUP '' ) then ... | IsInRole Getting New Security Token |
C_sharp : Just playing around with concurrency in my spare time , and wanted to try preventing torn reads without using locks on the reader side so concurrent readers do n't interfere with each other.The idea is to serialize writes via a lock , but use only a memory barrier on the read side . Here 's a reusable abstraction that encapsulate the approach I came up with : Do n't worry about overflow on the version variable , I avoid that another way . So is my understanding and application of Thread.MemoryBarrier correct in the above ? Are any of the barriers unnecessary ? <code> public struct Sync < T > where T : struct { object write ; T value ; int version ; // incremented with each write public static Sync < T > Create ( ) { return new Sync < T > { write = new object ( ) } ; } public T Read ( ) { // if version after read == version before read , no concurrent write T x ; int old ; do { // loop until version number is even = no write in progress do { old = version ; if ( 0 == ( old & 0x01 ) ) break ; Thread.MemoryBarrier ( ) ; } while ( true ) ; x = value ; // barrier ensures read of 'version ' avoids cached value Thread.MemoryBarrier ( ) ; } while ( version ! = old ) ; return x ; } public void Write ( T value ) { // locks are full barriers lock ( write ) { ++version ; // ++version odd : write in progress this.value = value ; // ensure writes complete before last increment Thread.MemoryBarrier ( ) ; ++version ; // ++version even : write complete } } } | C # /CLR : MemoryBarrier and torn reads |
C_sharp : Given the following function : I would like to accomplish this . The function GetValue ( ) can be called from different parts of the program . While GetValueFromServer ( ) is running I do n't want to initiate another call to it . All calls to to GetValue ( ) while GetValueFromServer ( ) is running should return the same value and not initiate another call . A call to GetValue ( ) while GetValueFromServer ( ) is not running should initiate a new call to GetValueFromServer ( ) .An example : The calls to GetValue ( ) at 0.0 , 0.3 and 0.6 should only trigger a single call to GetValueFromServer ( ) . All three callers should receive the same value . The call to GetValue ( ) at 0.9 should trigger another call to GetValueFromServer ( ) .I 'm still stuck in Objective-C thinking where I would use blocks to accomplish this . I would queue up the blocks and when the request to the server returns call each block that was queued . Now I would like to accomplish the same thing but using the async/await pattern . This is for use in a Windows Phone 8.1 ( RT ) app and if possible I would like to avoid a third party library/framework . <code> public async Task < int > GetValue ( ) { var value = await GetValueFromServer ( ) ; return value ; } 0.0 : var a = await GetValue ( ) 0.1 : call to GetValueFromServer ( ) 0.3 : var b = await GetValue ( ) ; 0.6 : var c = await GetValue ( ) ; 0.7 : GetValueFromServer ( ) returns 1 0.9 : var d = await GetValue ( ) ; 1.0 : call to GetValueFromServer ( ) 1.3 GetValueFromServer ( ) returns 2 - ( void ) getValue : ( void ( ^ ) ( int value ) ) block { [ _runningBlocks addObject : [ block copy ] ] ; if ( _runningBlocks.count > 1 ) { return ; } [ self getValueFromServer : ^ ( int value ) { for ( void ( ^ ) ( int ) b in _runningBlocks ) { b ( value ) ; } [ _runningBlocks removeAllObjects ] ; ] ; } | Return the same value for multiple function calls while a request is ongoing using async/await |
C_sharp : Is it a bad practice or code smell to use an IoC container while installing dependencies ? This is my composition root : My AutoMapperProfileInstallerneeds to resolve a profile which contains dependencies in order to initialize the mapperThis feels wrong on many levels , what would be a better way to initialize AutoMapper profiles ? <code> public void Install ( IWindsorContainer container , IConfigurationStore store ) { Assembly modelAssembly = typeof ( UserLoginModel ) .Assembly ; Assembly controllerAssembly = typeof ( HomeController ) .Assembly ; container.Install ( new MvcInfrastructureInstaller ( modelAssembly , viewAssembly , controllerAssembly , applicationTitle , resourceAssemblyLocations ) , new MiniMembershipInstaller ( ) , new ServiceInstaller ( ) , new RepositoryInstaller ( ) , new LibraryInstaller ( ) , new AutoMapperProfileInstaller ( ) // this installer needs to resolve dependencies such as repositories through the container itself , so it goes last . ) ; } public class AutoMapperProfileInstaller : IWindsorInstaller { public void Install ( IWindsorContainer container , IConfigurationStore store ) { Profile entityToViewModel = container.Resolve < EntityToViewModelProfile > ( ) ; Profile [ ] profiles = new [ ] { entityToViewModel } ; Mapper.Initialize ( config = > { config.ConstructServicesUsing ( container.Resolve ) ; foreach ( Profile profile in profiles ) { config.AddProfile ( profile ) ; } } ) ; } } | Is it a bad practice or code smell to use an IoC container while installing dependencies ? |
C_sharp : I am currently working on windows phone 8 and I have created a ListBox with Ellipse inside it to show images . Now I want to change the Stroke Colour for it when user selects any item in ListBox . My ListBox XAML code and its DataTemplate is belowDataTemplateI know how to change foreground of an entire list item , but I am not aware how to change ellipse stroke colour.To change Foreground color for ListBox , I implemented below code <code> < ListBox x : Name= '' OwnerList '' ScrollViewer.HorizontalScrollBarVisibility= '' Auto '' ScrollViewer.VerticalScrollBarVisibility= '' Disabled '' ItemsPanel= '' { StaticResource FileItemsPanel } '' ItemTemplate= '' { StaticResource OwnerListTemplate } '' SelectionMode= '' Multiple '' SelectionChanged= '' OwnerList_SelectionChanged '' / > < DataTemplate x : Key= '' OwnerListTemplate '' > < StackPanel Margin= '' 20,0,20,0 '' > < Ellipse Height= '' 120 '' Width= '' 120 '' Margin= '' 4 '' Stroke= '' Blue '' StrokeThickness= '' 2 '' > < Ellipse.Fill > < ImageBrush ImageSource= '' { Binding PHOTO , Converter= { StaticResource Imageconverter } } '' / > < /Ellipse.Fill > < /Ellipse > < TextBlock x : Name= '' OwnerName '' Text= '' { Binding NAME } '' FontSize= '' 22 '' Foreground= '' Gray '' FontWeight= '' Bold '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < TextBlock x : Name= '' distance '' Text= '' { Binding DISTANCE } '' FontSize= '' 20 '' Foreground= '' Gray '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /StackPanel > < /DataTemplate > < ItemsPanelTemplate x : Key= '' FileItemsPanel '' > < StackPanel Orientation= '' Horizontal '' > < StackPanel.RenderTransform > < TranslateTransform X= '' 0 '' / > < /StackPanel.RenderTransform > < /StackPanel > < /ItemsPanelTemplate > < Style x : Key= '' DynamicDataGenericListViewContainerStyle '' TargetType= '' ListBoxItem '' > < Setter Property= '' HorizontalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' Margin '' Value= '' 0,0,0,1 '' / > < Setter Property= '' Padding '' Value= '' 0 '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' ListBoxItem '' > < Border x : Name= '' LayoutRoot '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' Background= '' { TemplateBinding Background } '' HorizontalAlignment= '' { TemplateBinding HorizontalAlignment } '' VerticalAlignment= '' { TemplateBinding VerticalAlignment } '' > < VisualStateManager.VisualStateGroups > < VisualStateGroup x : Name= '' CommonStates '' > < VisualState x : Name= '' Normal '' / > < VisualState x : Name= '' MouseOver '' / > < VisualState x : Name= '' Disabled '' > < Storyboard > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Background '' Storyboard.TargetName= '' LayoutRoot '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource TransparentBrush } '' / > < /ObjectAnimationUsingKeyFrames > < DoubleAnimation Duration= '' 0 '' To= '' .5 '' Storyboard.TargetProperty= '' Opacity '' Storyboard.TargetName= '' ContentContainer '' / > < /Storyboard > < /VisualState > < /VisualStateGroup > < VisualStateGroup x : Name= '' SelectionStates '' > < VisualState x : Name= '' Unselected '' / > < VisualState x : Name= '' Selected '' > < Storyboard > < ObjectAnimationUsingKeyFrames Storyboard.TargetName= '' LayoutRoot '' Storyboard.TargetProperty= '' BorderThickness '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' 0,0,0,2 '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetName= '' LayoutRoot '' Storyboard.TargetProperty= '' BorderBrush '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource DynamicDataColor } '' / > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' Foreground '' Storyboard.TargetName= '' ContentContainer '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' Value= '' { StaticResource DynamicDataColor } '' / > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < /VisualStateGroup > < /VisualStateManager.VisualStateGroups > < ContentControl x : Name= '' ContentContainer '' ContentTemplate= '' { TemplateBinding ContentTemplate } '' Content= '' { TemplateBinding Content } '' Foreground= '' { TemplateBinding Foreground } '' HorizontalContentAlignment= '' { TemplateBinding HorizontalContentAlignment } '' Margin= '' { TemplateBinding Padding } '' VerticalContentAlignment= '' { TemplateBinding VerticalContentAlignment } '' / > < /Border > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > | How to change stroke of Ellipse when ListBox item is selected in Windows Phone 8 ? |
C_sharp : I have been doing a little work with regex over the past week and managed to make a lot of progress , however , I 'm still fairly n00b . I have a regex written in C # : For some reason , when calling the regular expression IsMethodRegex.IsMatch ( ) it hangs for 30+ seconds on the following string : Does anyone how the internals of Regex works and why this would be so slow on matching this string and not others . I have had a play with it and found that if I take out the * and the parenthesis then it runs fine . Perhaps the regular expression is poorly written ? Any help would be so greatly appreciated . <code> string isMethodRegex = @ '' \b ( public|private|internal|protected ) ? \s* ( static|virtual|abstract ) ? `` + @ '' \s* ( ? < returnType > [ a-zA-Z\ < \ > _1-9 ] * ) \s ( ? < method > [ a-zA-Z\ < \ > _1-9 ] + ) \s*\ '' + @ '' ( ( ? < parameters > ( ( [ a-zA-Z\ [ \ ] \ < \ > _1-9 ] *\s* [ a-zA-Z_1-9 ] *\s* ) [ , ] ? \s* ) + ) \ ) '' ; IsMethodRegex = new Regex ( isMethodRegex ) ; `` \t * Returns collection of active STOP transactions ( transaction type 30 ) `` | Regular Expressions in C # running slowly |
C_sharp : I have a snippet of code that I thought would work because of closures ; however , the result proves otherwise . What is going on here for it to not produce the expected output ( one of each word ) ? Code : Output : <code> string [ ] source = new string [ ] { `` this '' , `` that '' , `` other '' } ; List < Thread > testThreads = new List < Thread > ( ) ; foreach ( string text in source ) { testThreads.Add ( new Thread ( ( ) = > { Console.WriteLine ( text ) ; } ) ) ; } testThreads.ForEach ( t = > t.Start ( ) ) otherotherother | Odd ( loop / thread / string / lambda ) behavior in C # |
C_sharp : I just started looking at IL a bit and I 'm curious if my attempt ( shown below ) to remove excess code from the output of the compiler had any unintended side effects.A couple of quesiton about the results : What is the purpose of the nop operations in the original ? What is the purpose of the br.s at the end of the methods in the original ? Is the re-written version improper in any way ? Original C # Code : Compiled with csc.exe and disassembled it with ildasm.exe ( Original ) : Re-written ( produces identical output ) : <code> class Program { public static int Main ( ) { return Add ( 1 , 2 ) ; } public static int Add ( int a , int b ) { return a + b ; } } .method public hidebysig static int32 Main ( ) cil managed { .entrypoint .maxstack 2 .locals init ( int32 V_0 ) IL_0000 : nop IL_0001 : ldc.i4.1 IL_0002 : ldc.i4.2 IL_0003 : call int32 Program : :Add ( int32 , int32 ) IL_0008 : stloc.0 IL_0009 : br.s IL_000b IL_000b : ldloc.0 IL_000c : ret } .method public hidebysig static int32 Add ( int32 a , int32 b ) cil managed { .maxstack 2 .locals init ( int32 V_0 ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.1 IL_0003 : add IL_0004 : stloc.0 IL_0005 : br.s IL_0007 IL_0007 : ldloc.0 IL_0008 : ret } .method public hidebysig static int32 Main ( ) cil managed { .entrypoint .maxstack 2 ldc.i4.1 ldc.i4.2 call int32 Program : :Add ( int32 , int32 ) ret } .method public hidebysig static int32 Add ( int32 a , int32 b ) cil managed { .maxstack 2 ldarg.0 ldarg.1 add ret } | Questions about hand coded IL based on disassembled simple C # code |
C_sharp : I 'm trying to register a user using C # in asp.net and then put their details into my database . Everything seems to work fine but the details do n't go into the database.Here 's what I have so far : and on the web.config page I have the connection string : Any idea what I 'm doing wrong ? Any help would be appreciated . <code> protected void CreateUser_Click ( object sender , EventArgs e ) { var manager = Context.GetOwinContext ( ) .GetUserManager < ApplicationUserManager > ( ) ; var signInManager = Context.GetOwinContext ( ) .Get < ApplicationSignInManager > ( ) ; var user = new ApplicationUser ( ) { UserName = Email.Text , Email = Email.Text } ; IdentityResult result = manager.Create ( user , Password.Text ) ; if ( result.Succeeded ) { signInManager.SignIn ( user , isPersistent : false , rememberBrowser : false ) ; IdentityHelper.RedirectToReturnUrl ( Request.QueryString [ `` ReturnUrl '' ] , Response ) ; manager.AddToRole ( user.Id , `` users '' ) ; string connectionString = WebConfigurationManager.ConnectionStrings [ `` MyDatabaseConnection '' ] .ConnectionString ; SqlConnection con = new SqlConnection ( connectionString ) ; string sql ; sql = `` INSERT INTO users ( username , title , gname , sname , dob , address , suburb , state , postcode , phone , email ) VALUES ( @ UserName , @ Title1 , @ FirstName , @ FamilyName , @ DateOfBirth , @ Address , @ Suburb , @ State , @ Postcode , @ Phone , @ Email ) '' ; SqlCommand cmd = new SqlCommand ( sql , con ) ; cmd.Parameters.AddWithValue ( `` @ Username '' , Email.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Title1 '' , Title1.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ FirstName '' , FirstName.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ FamilyName '' , FamilyName.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ DateOfBirth '' , DateOfBirth.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Address '' , Address.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Suburb '' , Suburb.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ State '' , State.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Postcode '' , Postcode.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Phone '' , Phone.Text.Trim ( ) ) ; cmd.Parameters.AddWithValue ( `` @ Email '' , Email.Text.Trim ( ) ) ; using ( con ) { con.Open ( ) ; int rowCount = cmd.ExecuteNonQuery ( ) ; if ( rowCount > 0 ) { lblResult.Text = `` Success . New User Registered '' ; } } } else { ErrorMessage.Text = result.Errors.FirstOrDefault ( ) ; } } < connectionStrings > < add name= '' MyDatabaseConnection '' connectionString= '' Data Source= ( LocalDB ) \v11.0 ; AttachDbFilename=|DataDirectory|\MyDatabaseConnection.mdf ; Integrated Security=True '' providerName= '' System.Data.SqlClient '' / > < /connectionStrings > | Enter user details into database after registration |
C_sharp : Why if I write it compiles.And in case if I write It does n't ? It 's clear that from pure functional point of view the declaration of the variable in the second example is useless , but why it magically becomes usefull in first example , so ? The IL code produced by both examples is exactly the same . EDIT : Forgot to mantion that to produce the IL code for the second case ( so the case which is not compilable ) , it 's enough to compile without string sDirectory = <code> void Main ( ) { string value = @ '' C : \ '' ; if ( ! string.IsNullOrEmpty ( value ) ) { string sDirectory = Path.GetDirectoryName ( value ) ; } } void Main ( ) { string value = @ '' C : \ '' ; if ( ! string.IsNullOrEmpty ( value ) ) string sDirectory = Path.GetDirectoryName ( value ) ; } IL_0000 : ldstr `` C : \ '' IL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : call System.String.IsNullOrEmptyIL_000C : brtrue.s IL_0015IL_000E : ldloc.0 IL_000F : call System.IO.Path.GetDirectoryName | Why this compile error |
C_sharp : I have an extension method for testing so I can do this : The extension method : This shows : Is there any hack I can pull off to get the name of the property `` BrainsConsumed '' from within my extension method ? Bonus points would be the instance variable and type Zombie.UPDATE : The new ShouldBe : and this prints out : Thanks everyone , esp . Matt Dotson , this is awesome . BTW do n't feed the silky trolls people . <code> var steve = new Zombie ( ) ; steve.Mood.ShouldBe ( `` I 'm hungry for brains ! `` ) ; public static void ShouldBe < T > ( this T actual , T expected ) { Assert.That ( actual , Is.EqualTo ( expected ) ) ; } Expected : `` I 'm hungry for brains ! `` But was : `` I want to shuffle aimlessly '' public static void ShouldBe < T > ( this T actual , T expected ) { var frame = new StackTrace ( true ) .GetFrame ( 1 ) ; var fileName = frame.GetFileName ( ) ; var lineNumber = frame.GetFileLineNumber ( ) - 1 ; var code = File.ReadAllLines ( fileName ) .ElementAt ( lineNumber ) .Trim ( ) .TrimEnd ( ' ; ' ) ; var codeMessage = new Regex ( @ '' ( ^ . * ) ( \.\s*ShouldBe\s*\ ( ) ( [ ^\ ) ] + ) \ ) '' ) .Replace ( code , @ '' $ 1 should be $ 3 '' ) ; var actualMessage = actual.ToString ( ) ; if ( actual is string ) actualMessage = `` \ '' '' + actual + `` \ '' '' ; var message = string.Format ( @ '' { 0 } but was { 1 } '' , codeMessage , actualMessage ) ; Assert.That ( actual , Is.EqualTo ( expected ) , message ) ; } steve.Mood should be `` I 'm hungry for brains ! '' but was `` I want to shuffle aimlessly '' | Is this possible in C # ? |
C_sharp : Is there any ready to use solution to group events ? Say I have two events : A and B.I want a Method M to be executed when A and B have been fired , they do not need to fire exactly at the same time . Something like : Group event G fires after both , A and B have fired . I need to register Method M only at Group event G. A can fire more than one time , G will only fire after B has fired . Same other way.I 'm looking for a library , which has these events.Edit : ExampleF means the event fires , 0 it does not . <code> Events : A | B | G1 F 0 02 0 F F3 0 F 0 4 0 F 0 5 0 F 0 6 F 0 F7 F 0 08 0 F F9 0 0 0 10 F F F | grouping events in C # |
C_sharp : This is my code : My code takes a set of cards and represents your maximum possible score when playing against a deterministic opponent . After each of your opponent 's plays you have 2 choices until cards are all picked . Is there a way to somehow store my results of the iterations so I can improve my algorithm ? So the recursion does n't do unnecessary iterations ? Because after 40 or 50 cards it becomes very slow . <code> static int cardGameValue ( List < int > D , int myScore , int opponentScore ) { if ( D.Count == 0 ) return myScore ; else if ( D.Count == 1 ) { opponentScore += D [ 0 ] ; return myScore ; } else { if ( D [ 0 ] < = D [ D.Count - 1 ] ) { opponentScore += D [ D.Count - 1 ] ; D.RemoveAt ( D.Count - 1 ) ; } else { opponentScore += D [ 0 ] ; D.RemoveAt ( 0 ) ; } int left = cardGameValue ( new List < int > ( D.GetRange ( 1 , D.Count - 1 ) ) , myScore + D [ 0 ] , opponentScore ) ; int right = cardGameValue ( new List < int > ( D.GetRange ( 0 , D.Count - 1 ) ) , myScore + D [ D.Count - 1 ] , opponentScore ) ; if ( left > = right ) { return left ; } else { return right ; } } } } | Improving recursion method in C # |
C_sharp : This is my first post here , hoping to start also posting more often in the future : ) I have been trying to learn to use Castle Windsor rather than using Ninject but there 's one feature I have n't been able to sort of `` translate '' to use in Windsor , and that is WhenInjectedInto . Here 's one example taken from Pro ASP.NET MVC 5 book , with NinjectThis is a conditional binding , meaing that when it 's LinqValueCalculator that is being bound to IValueCalculator , it should use FlexibleDiscountHelper when binding to IDiscountHelper , rather than any other object.How can I replicate this with Windsor , if it 's even possible ? So far I have : Thanks in advance , Bruno <code> kernel.Bind < IValueCalculator > ( ) .To < LinqValueCalculator > ( ) ; kernel.Bind < IDiscountHelper > ( ) .To < FlexibleDiscountHelper > ( ) .WhenInjectedInto < LinqValueCalculator > ( ) ; container.Register ( Component.For < IValueCalculator > ( ) .ImplementedBy < LinqValueCalculator > ( ) ) ; container.Register ( Component.For < IDiscountHelper > ( ) .ImplementedBy < FlexibleDiscountHelper > ( ) ) ; | Ninject feature ( WhenInjectedInto ) equivalent in Windsor |
C_sharp : What should I put in the ? ? to force objects that inherit from both Animal and IHasLegs ? I do n't want to see a Snake in that cage neither a Table. -- -- -- -- -- -- -- EDIT -- -- -- -- -- -- -- Thank you all for your answers , but here is the thing : What I actually want to do is this : TextBox/ComboBox is of course a Control.Now if I make an abstract class that inherits both Control and IClonable , I will loose the TextBox/ComboBox inheritance that I need . Multiple class inheritance is not allowed , so I have to work with interfaces . Now that I think of it again , I could create another interface that inherits from IClonable : and thenThank you ! ! <code> // interfacepublic interface IHasLegs { ... } // base classpublic class Animal { ... } // derived classes of Animalpublic class Donkey : Animal , IHasLegs { ... } // with legspublic class Lizard : Animal , IHasLegs { ... } // with legspublic class Snake : Animal { ... } // without legs// other class with legspublic class Table : IHasLegs { ... } public class CageWithAnimalsWithLegs { public List < ? ? > animalsWithLegs { get ; set ; } } public interface IClonable { ... } public class MyTextBox : TextBox , IClonable { ... } public class MyComboBox : ComboBox , IClonable { ... } public interface IClonableControl : IClonable { ... } public class MyTextBox : TextBox , IClonableControl { ... } public class MyComboBox : ComboBox , IClonableControl { ... } List < IClonableControl > clonableControls ; | C # declare both , class and interface |
C_sharp : I stumbled across a method in my code where a rounded value is calculated wrong in my code.I am aware about the problem with comparing double values generated unexpected results.ExampleExplanation here : http : //csharpindepth.com/Articles/General/FloatingPoint.aspxHowever , until now , I expected the Math.Round ( ) method to be accurate even with double values.Look at this code.For me , it is totally clear that result2 should be 4.73 . However , it is not the case.Can someone explain why ? <code> double x = 19.08 ; double y = 2.01 ; double result = 21.09 ; if ( x + y == result ) { // this is never reached } var decimals = 2 ; var value1 = 4.725 ; var value2 = 4.725M ; var result1 = Math.Round ( value1 , decimals , MidpointRounding.ToEven ) ; var result2 = Math.Round ( value1 , decimals , MidpointRounding.AwayFromZero ) ; var result3 = Math.Round ( value2 , decimals , MidpointRounding.ToEven ) ; var result4 = Math.Round ( value2 , decimals , MidpointRounding.AwayFromZero ) ; Console.WriteLine ( `` Double ( ToEven ) : { 0 } '' , result1 ) ; // outputs 4.72 Console.WriteLine ( `` Double ( AwayFromZero ) : { 0 } '' , result2 ) ; // outputs 4.72 ( expected : 4.73 ) Console.WriteLine ( `` Decimal ( ToEven ) : { 0 } '' , result3 ) ; // outputs 4.72 Console.WriteLine ( `` Decimal ( AwayFromZero ) : { 0 } '' , result4 ) ; // outputs 4.73 | Math.Round ( ) yields unexpected result for double |
C_sharp : I have a list of lists that contain integers ( this list can be any length and can contain any number of integers : What I want to do next is combine the lists where any integer matches any integer from any other list , in this case : I have tried many different approaches but am stuck for an elegant solution . <code> { { 1,2 } , { 3,4 } , { 2,4 } , { 9,10 } , { 9,12,13,14 } } result = { { 1,2,3,4 } , { 9,10,12,13,14 } } | Combine similar character in string in C # |
C_sharp : I have a data source that is comma-delimited , and quote-qualified . A CSV . However , the data source provider sometimes does some wonky things . I 've compensated for all but one of them ( we read in the file line-by-line , then write it back out after cleansing ) , and I 'm looking to solve the last remaining problem when my regex-fu is pretty weak.Matching a Quoted String inside of another Quoted StringSo here is our example string ... I am looking to match the substring `` chez Métral '' , in order to replace it with the substring chez Métral . Ideally , in as few lines of code as possible . The final goal is to write the line back out ( or return it as a method return value ) with the replacement already done.So our example string would end up as ... I know I could define a pattern such as ( ? < quotedstring > \ '' \w+ [ ^ , ] +\ '' ) to match quoted strings , but my regex-fu is weak ( database developer , almost never use C # ) , so I 'm not sure how to match another quoted string within the named group quotedstring.FYI : For those noticing the large integer that is formatted with commas but not quote-qualified , that 's already handled . As is the random use of row-delimiters ( sometimes CR , sometimes LF ) . As other problems ... <code> `` foobar '' , 356 , `` Lieu-dit `` chez Métral '' , Chilly , FR '' , `` -1,000.09 '' , 467 , `` barfoo '' , 1,345,456,235,231 , `` 935.18 '' `` foobar '' , 356 , `` Lieu-dit chez Métral , Chilly , FR '' , `` -1,000.09 '' , 467 , `` barfoo '' , 1,345,456,235,231 , `` 935.18 '' | Regular Expression to match a quoted string embedded in another quoted string |
C_sharp : In C # , I have a simple 3D vector class.the output is , vector a= 10 , 5 , 10vector b= 10 , 5 , 10I assign a before i change a.x to 10 . So i was expecting vector a= 10 , 5 , 10vector b= 0 , 5 , 10From what i understand = operator assigns a reference to object like a pointer ? And in C # i cant overload = operator . Do i have to manually assign each property ? <code> static void Main ( string [ ] args ) { Vector3D a , b ; a = new Vector3D ( 0 , 5 , 10 ) ; b = new Vector3D ( 0 , 0 , 0 ) ; b = a ; a.x = 10 ; Console.WriteLine ( `` vector a= '' + a.ToString ( ) ) ; Console.WriteLine ( `` vector b= '' + b.ToString ( ) ) ; Console.ReadKey ( ) ; } | c # = operator problem |
C_sharp : I have this code to combine 2 different csv files . My BoxData = data1 ; data2 ; data3 ; data4 ; data5At the moment data2 to data5 is getting in JobStart file . Data5 should n't be included inside JobStart file . I want to set data5 as a global variable.How can I do this , I just can not figure this out , need help . This can help understanding my problem : How to compare 2 .csv files and create a new .csv containing parts from both csv files ? <code> try { var jobStartLine = File.OpenText ( PackAuftrag ) .ReadLine ( ) ; var comparisonField = jobStartLine.Split ( ' ; ' ) [ 4 ] ; foreach ( var line in File.ReadAllLines ( BoxData ) ) { var fields = line.Split ( new char [ ] { ' ; ' } , 2 ) ; if ( comparisonField == fields [ 0 ] ) { File.WriteAllLines ( JobStart , new string [ ] { jobStartLine + `` ; '' + fields [ 1 ] } ) ; break ; } } } | How to Ignore a field and set the ignored field as a global variable within the function ? |
C_sharp : I am trying to list all objects ( Cube , dimension , partition , ... ) found in a SSAS server . I am able to do that using the following project : GitHub - SSASAMODBI am trying to retrieve the relevant directory ( within the data directory ) for each object . I am unable to do that since files names contains some Incremental number that change each time you made changes to the objects in the database . Example : Cube name : TestCubeFolder : After changing and reprocessing the Cube it changes to another valueIs there is a property in AMO classes that returns the Folder Path of each object ? What is the value of the Incremental number included in the Folder name ? Is there some workaround to do that ? Since i only have SQL Server Data Tools Business Intelligence tools installed i need a solution compatible with SSIS script Task since it is the only way that i can process the data . Note that there are many articles online for using AMO from script taskEnvironment : SQL Server 2014 <code> |Data Dir|\ < SSASDB > \TestCube.0.cub |Data Dir|\ < SSASDB > \TestCube.1.cub | Retrieve multidimensional database objects directories |
C_sharp : I have a utility I 'm testing with a few other people , that takes screenshots of another window and then uses OpenCV to find smaller images within that screenshot.That 's working without a problem , however , I 'm trying to make it more efficient , and was wondering , rather than taking a screenshot of the window every X milliseconds , if there was a way I could `` stream '' the screen to my app , and then run a function against every new frame that comes through.This is my current code : I 'm not entirely sure that this is the most efficient way to accomplish what I 'm attempting , any help would be brilliant.Thank you . <code> public static bool ContainsImage ( Detection p_Detection , out long elapsed ) { Stopwatch stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; Image < Gray , byte > imgHaystack = new Image < Gray , byte > ( CaptureApplication ( p_Detection.WindowTitle ) ) ; Image < Gray , byte > imgNeedle = new Image < Gray , byte > ( p_Detection.Needle ) ; if ( imgHaystack.Width > = p_Detection.Settings.Resolution || imgHaystack.Height > = p_Detection.Settings.Resolution ) { imgHaystack = imgHaystack.Resize ( imgHaystack.Width / p_Detection.Settings.Scale , imgHaystack.Height / p_Detection.Settings.Scale , Emgu.CV.CvEnum.Inter.Area ) ; imgNeedle = imgNeedle.Resize ( imgNeedle.Width / p_Detection.Settings.Scale , imgNeedle.Height / p_Detection.Settings.Scale , Emgu.CV.CvEnum.Inter.Area ) ; } if ( imgNeedle.Height < imgHaystack.Height & & imgNeedle.Width < imgHaystack.Width ) { using ( Image < Gray , float > result = imgHaystack.MatchTemplate ( imgNeedle , Emgu.CV.CvEnum.TemplateMatchingType.CcoeffNormed ) ) { result.MinMax ( out double [ ] minValues , out double [ ] maxValues , out Point [ ] minLocations , out Point [ ] maxLocations ) ; if ( maxValues [ 0 ] > p_Detection.Settings.MatchThreshold ) { stopWatch.Stop ( ) ; elapsed = stopWatch.ElapsedMilliseconds ; imgHaystack.Dispose ( ) ; imgNeedle.Dispose ( ) ; return true ; } } } stopWatch.Stop ( ) ; elapsed = stopWatch.ElapsedMilliseconds ; imgHaystack.Dispose ( ) ; imgNeedle.Dispose ( ) ; return false ; } | Alternative to taking rapid screenshots of a window |
C_sharp : Consider the following code , the first demonstrates that the `` cleanup '' executes when we 're finished iterating over the IEnumerable of strings . The second pass is what is causing me grief . I need to be able abandon the IEnumerable before reaching the end , and then have the clean up code execute . But if you run this you 'll see that in the second pass the clean up never fires.What is the preferred way of abandoning an IEnumerable like this ? <code> static void Main ( string [ ] args ) { // first pass foreach ( String color in readColors ( ) ) Console.WriteLine ( color ) ; // second pass IEnumerator < string > reader = readColors ( ) .GetEnumerator ( ) ; if ( reader.MoveNext ( ) ) { Console.WriteLine ( reader.Current ) ; reader.Dispose ( ) ; } } static IEnumerable < string > readColors ( ) { string [ ] colors = { `` red '' , `` green '' , `` blue '' } ; for ( int i = 0 ; i < colors.Length ; i++ ) yield return colors [ i ] ; Console.WriteLine ( `` Cleanup goes here '' ) ; } | How can I abandon an IEnumerator without iterating to the end ? |
C_sharp : I 'm porting Haskell's/LiveScript each function to C # and I 'm having some troubles . The signature of this function is ( a → Undefined ) → [ a ] → [ a ] and I work very well with typing and lambda expressions in Haskell or LS , but C # makes me confused . The final use of this extension method should be : And , with this , My output should be : My current own implementation of each is : The problem is that here I just ca n't pass a parameter in my lambda expression . I ca n't do ( x ) = > ... .How can I pass parameters to lambda expression ? It was very easier to work with first-class-functions in Haskell than in C # . I 'm just very confused.For that who do n't know Each 's implementation , it is used for side-effects , returns the own list and applies a closure iterating and passing each value of the list as an argument . Its implementation in PHP should be : Can somebody help me ? I searched for it but it is n't clear for me . [ And I do n't wish use Linq ] <code> String [ ] str = { `` Haskell '' , `` Scheme '' , `` Perl '' , `` Clojure '' , `` LiveScript '' , `` Erlang '' } ; str.Each ( ( x ) = > Console.WriteLine ( x ) ) ; HaskellSchemePerlClojureLiveScriptErlang public static void Each < T > ( this IEnumberable < T > list , Action closure ) { foreach ( var result in list ) { Delegate d = closure ; object [ ] parameters = { result } ; d.DynamicInvoke ( parameters ) ; } } public static function each ( $ func ) { // where $ this- > value is a list foreach ( $ this- > value as $ xs ) { $ func ( $ xs ) ; } return $ this- > value ; // Or return $ this ; in case of method-chaining } | Mixing extension methods , generics and lambda expressions |
C_sharp : i am trying to add field in json while deserializing the response from server and then storing it into database here is the model of Response QuotationConverter code where i am fetching customer name from another json and store it into quotationhere is the JsonConverterJson received from serverexpected json Quotation modelupdated this is how my deserialize get called Response responseData = await Task.Run ( ( ) = > JsonConvert.DeserializeObject ( content ) ) ; <code> public class Response : RealmObject { [ JsonConverter ( typeof ( QuotationConverter ) ) ] [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public IList < Quotation > quotationsList { get ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public IList < Order > ordersList { get ; } } protected override IList < Quotation > parseArray ( Type objectType , JArray jsonArray ) { try { Realm realm = Realm.GetInstance ( ) ; foreach ( JObject data in jsonArray ) { String customerId = data.GetValue ( `` customerId '' ) .ToString ( ) ; Customer customer = realm.All < Customer > ( ) .Where ( c = > c.customerId == Java.Lang.Long.ParseLong ( customerId ) ) .FirstOrDefault ( ) ; if ( customer ! = null ) { String customerName = customer.customerName ; data.Add ( `` customerName '' , customerName ) ; } } realm.Dispose ( ) ; var quotationsList = jsonArray.ToObject < IList < Quotation > > ( ) ; List < Quotation > quotation = new List < Quotation > ( quotationsList ) ; return quotationsList ; } catch ( Exception e ) { Debug.WriteLine ( `` exception `` +e.StackTrace ) ; } return null ; } protected override Quotation parseObject ( Type objectType , JObject jsonObject ) { throw new NotImplementedException ( ) ; } } public abstract class JsonConverter < T > : Newtonsoft.Json.JsonConverter { public override bool CanConvert ( Type objectType ) { return ( objectType == typeof ( JsonConverter < T > ) ) ; } protected abstract T parseObject ( Type objectType , JObject jsonObject ) ; protected abstract IList < T > parseArray ( Type objectType , JArray jsonArray ) ; public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { try { var jsonArray = JArray.Load ( reader ) ; var data= parseArray ( objectType , jsonArray ) ; return data ; } catch ( Exception e ) { Debug.WriteLine ( e.StackTrace ) ; } return null ; } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { Debug.WriteLine ( `` Mo `` + value ) ; } } the issue is when i am getting Response object inside that quotationsList is coming blank . quotationsList : [ { `` account '' : null , `` contactId '' : 0 , `` currency '' : `` USD '' , `` customerId '' : 5637144583 , `` deliveryAddress '' : `` 19TH and Edwardsville RD ( RT203 ) \nGranite City , IL62040\nUSA '' , `` expiryDate '' : `` 2017-09-04 '' , `` followUpDate '' : `` 2017-09-01 '' , `` mQuotationId '' : null , `` opportunityId '' : 0 , `` postedOn '' : null , `` prospectId '' : 0 , `` quotationFor '' : null , `` quotationId '' : 5637155076 , `` quotationName '' : `` United States Steel '' , `` quotationNumber '' : `` UST1-000022 '' , `` quotationStatus '' : `` Confirmed '' , `` requestReceiptDate '' : `` 2017-08-05 '' , `` requestShipDate '' : `` 2017-08-05 '' , `` siteId '' : `` GLEN1 '' , `` wareHouseId '' : `` 37 '' } quotationsList : [ { `` account '' : null , `` contactId '' : 0 , `` currency '' : `` USD '' , `` customerId '' : 5637144583 , `` deliveryAddress '' : `` 19TH and Edwardsville RD ( RT203 ) \nGranite City , IL62040\nUSA '' , `` expiryDate '' : `` 2017-09-04 '' , `` followUpDate '' : `` 2017-09-01 '' , `` mQuotationId '' : null , `` opportunityId '' : 0 , `` postedOn '' : null , `` prospectId '' : 0 , `` quotationFor '' : null , `` quotationId '' : 5637155076 , `` quotationName '' : `` United States Steel '' , `` quotationNumber '' : `` UST1-000022 '' , `` quotationStatus '' : `` Confirmed '' , `` requestReceiptDate '' : `` 2017-08-05 '' , `` requestShipDate '' : `` 2017-08-05 '' , `` siteId '' : `` GLEN1 '' , `` wareHouseId '' : `` 37 '' , `` customerName '' : '' Jhon Caro '' } public class Quotation : RealmObject , IMaster , IMedia , IProduct { [ PrimaryKey ] [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public String mQuotationId { get ; set ; } = Guid.NewGuid ( ) .ToString ( ) ; [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public long quotationId { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public String customerName { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string quotationName { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string quotationNumber { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string deliveryAddress { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string expiryDate { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string requestShipDate { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string requestReceiptDate { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public long prospectId { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string followUpDate { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public long opportunityId { get ; set ; } [ JsonProperty ( NullValueHandling = NullValueHandling.Ignore ) ] public string postedOn { get ; set ; } } protected override IList < Quotation > parseArray ( Type objectType , JArray jsonArray ) { try { Realm realm = Realm.GetInstance ( ) ; var data = jsonArray.ToObject < IList < Quotation > > ( ) ; List < Quotation > quotationList = new List < Quotation > ( data ) ; foreach ( Quotation quotation in quotationList ) { long customerId = quotation.customerId ; Customer customer = realm.All < Customer > ( ) .Where ( c = > c.customerId == customerId ) .FirstOrDefault ( ) ; if ( customer ! = null ) { String customerName = customer.customerName ; quotation.customerName = customerName ; } } realm.Dispose ( ) ; return quotationList ; } catch ( Exception e ) { Debug.WriteLine ( `` exception `` +e.StackTrace ) ; } return null ; } | unable to update existing json list using jsonconverter |
C_sharp : I have a dozen methods in my project ( C # 2.0 ) that look like this : ... but for different 'entity ' classes . ( Okay , not quite that trivial , I 've simplified the code here . ) It looks like a good candidate for generics and I came up with this : And of course I get the `` Can not create an instance of the type parametrer 'T ' because it does not have the new ( ) constraint '' error.The problem is that these 'entity ' classes do not have a public parameterless constructor , nor a way of adding the 'row ' data in afterwards . And as EntityBase is part of the company framework I have no control over it ( ie I ca n't change it ) .Is there any way around this ? <code> internal bool ValidateHotelStayEntity ( DataRow row ) { return ( new HotelStayEntity ( row ) ) .Validate ( ) ; } internal bool ValidateEntity < T > ( DataRow row ) where T : EntityBase { return ( new T ( row ) ) .Validate ( ) ; } | Generics without new ( ) |
C_sharp : Why does this program print `` Child Name '' instead of `` Base Name '' ? I expect that when I cast child to INamedObject , Name property of INamedObject explicit implementation will be invoked . But what happens is that Child.Name property is called.Why when I declare Child class like that ( removing INamedObject from Child ) : it starts printing `` Base Name '' ? <code> using System ; class Program { static void Main ( string [ ] args ) { var child = new Child ( ) ; Console.WriteLine ( ( ( INamedObject ) child ) .Name ) ; Console.ReadLine ( ) ; } } interface INamedObject { string Name { get ; } } class Base : INamedObject { string INamedObject.Name { get { return `` Base Name '' ; } } } class Child : Base , INamedObject { public string Name { get { return `` Child Name '' ; } } } class Child : Base { public string Name { get { return `` Child Name '' ; } } } | Why explicit interface implementation works that way ? |
C_sharp : I have an Entity Framework Code First model for which I made a static generic class which has a search method which is called for every item in a list.Admitting that this is over my head , I thought making the class static would improve code clarity and maybe even performance as one does not have to create instances in many different places.The goal of all of this is to automate which properties can be searched , exported , etc by the user.The primary question is : If MakeGenericType ( ... ) is called for every item ( potentially 1000s ) which has a reference type property , is a generic type for that reference type property generated once and saved somewhere or generated 1000s of times ? Pointing out any other performance crimes or code smells is appreciated . <code> public static class SearchUserVisibleProperties < T > { private static List < PropertyInfo > userVisibleProperties { get ; set ; } static SearchUserVisibleProperties ( ) { userVisibleProperties = typeof ( T ) .GetProperties ( ) .Where ( prop = > Attribute.IsDefined ( prop , typeof ( UserVisibleAttribute ) ) ) .ToList ( ) ; } public static bool search ( T item , string searchString ) { foreach ( PropertyInfo pInfo in userVisibleProperties ) { object value = pInfo.GetValue ( item ) ; if ( value == null ) { continue ; } if ( pInfo.PropertyType == typeof ( string ) || pInfo.PropertyType.IsValueType ) { ... unrelevant string matching code ... } else if ( ( bool ) typeof ( SearchUserVisibleProperties < > ) .MakeGenericType ( new Type [ ] { value.GetType ( ) } ) .InvokeMember ( nameof ( search ) , BindingFlags.InvokeMethod , null , null , new object [ ] { value , searchString } ) ) { return true ; } } return false ; } } | Does calling MakeGenericType ( ... ) multiple times create a new type every time ? |
C_sharp : Trying to study how C # reacts to overflows , I wrote this simple code : I get this output : I find surprising that it ran so well , as the int subtraction in diff should give a result greater than int.MaxValue.However , if I write this , which seems to be equivalent to the above code : C # wo n't even compile , because the code could overflow.What makes the first code run without overflow , while the compiler wo n't even compile the second line ? <code> static uint diff ( int a , int b ) { return ( uint ) ( b - a ) ; } static void Main ( string [ ] args ) { Console.Out.WriteLine ( int.MaxValue ) ; uint l = diff ( int.MinValue , int.MaxValue ) ; Console.Out.WriteLine ( l ) ; Console.In.ReadLine ( ) ; } 21474836474294967295 uint l = ( uint ) ( int.MaxValue - int.MinValue ) ; | Why does n't this program overflow ? |
C_sharp : We currently have a little situation on our hands - it seems that someone , somewhere forgot to close the connection in code . Result is that the pool of connections is relatively quickly exhausted . As a temporary patch we added Max Pool Size = 500 ; to our connection string on web service , and recycle pool when all connections are spent , until we figure this out.So far we have done this : to get SPID 's that are n't used for 15 minutes . We 're now trying to get the query that was executed last using that SPID with : but the queries displayed are various , meaning either something on base level regarding connection manipulation was broken , or our deduction is erroneous ... Is there an error in our thinking here ? Does the DBCC / sysprocesses give results we 're expecting or is there some side-effect catch ? ( for example , connections in pool influence ? ) ( please , stick to what we could find out using SQL since the guys that did the code are many and not all present right now ) <code> SELECT SPIdFROM MASTER..SysProcessesWHERE DBId = DB_ID ( 'MyDb ' ) and last_batch < DATEADD ( MINUTE , -15 , GETDATE ( ) ) DBCC INPUTBUFFER ( 61 ) | All connections in pool are in use |
C_sharp : I am reading up on c # arrays so my question is initially on arrays.What does declaring an array actually mean ? I know you declare a variable of type array . When I have the following , what is actually happening ? Is it in memory by the time it is declared ? If not then where is it ? Is the array actually created here ? Then I go and instantiate an the array and initialise it with some values like : Does this actually go and create the array now ? I have read that arrays are created when they are declared , others say that arrays are created when they are instantiated . I am trying to get my terminology right.The same goes for an integer variable . If I have : andWhen is int created ? When is it added to memory ? Sorry for the dumb questions . I understand the concept but would like to know the technicallity behind the scenes of arrays . <code> int [ ] values ; int [ ] values = new int [ ] { 1 , 2 , 3 } ; int value ; int value = 1 ; | What does declaring and instantiating a c # array actually mean ? |
C_sharp : I am using LINQ : Desired result : I tried but fail : How can I do this using LINQ ? <code> List < String > listA = new List < string > { `` a '' , `` b '' , `` c '' , `` d '' , `` e '' , `` f '' , `` g '' } ; List < String > listB = new List < string > { `` 1 '' , `` 2 '' , `` 3 '' } ; { `` a '' , `` 1 '' , `` b '' , `` 2 '' , `` c '' , `` 3 '' , `` d '' , `` 1 '' , `` e '' , `` 2 '' , `` f '' , `` 3 '' , `` g '' , `` 1 '' } var mix = ListA.Zip ( ListB , ( l1 , l2 ) = > new [ ] { l1 , l2 } ) .SelectMany ( x = > x ) ; //Result : { `` a '' , `` 1 '' , `` b '' , `` 2 '' , `` c '' , `` 3 '' } var mix = ListA.Zip ( ListB , ( a , b ) = > new [ ] { a , b } ) .SelectMany ( x = > x ) .Concat ( ListA.Count ( ) < ListB.Count ( ) ? ListB.Skip ( ListA.Count ( ) ) : ListA.Skip ( ListB.Count ( ) ) ) .ToList ( ) ; //Result : { `` a '' , `` 1 '' , `` b '' , `` 2 '' , `` c '' , `` 3 '' , `` d '' , `` e '' , `` f '' , `` g '' } | Join two lists of different length |
C_sharp : I have a huge problem with the following code : the problem is , C # uses the system date separator instead of always using `` / '' as i specified . If I run that code , I get the following output : but if I go to `` control panel '' - > `` regional and language options '' and change the date separator to `` - '' , I getEven if in the toString method I specified to use '/ ' . Am I missing something or this is a C # / .Net Framework bug ? <code> DateTime date = DateTime.Now ; String yearmonthday = date.ToString ( `` yyyy/MM/dd '' ) ; MessageBox.Show ( yearmonthday ) ; 2011/03/18 2011-03-18 | c # Date component bug or am i missing something ? |
C_sharp : I recently came across this SO article and tweaked it for my scenario which follows : Running this program gives the following expected result : However change this : To this ( using Object Initializer syntax ) : Gives the following output : What 's going on here ? Why would lifetime of the reference be different just because of using Object Initializer ? <code> using System ; using System.Collections.Generic ; namespace ConsoleApplication18 { class Program { static void Main ( string [ ] args ) { Manager mgr = new Manager ( ) ; var obj = new byte [ 1024 ] ; var refContainer = new RefContainer ( ) ; refContainer.Target = obj ; obj = null ; mgr [ `` abc '' ] = refContainer.Target ; GC.Collect ( GC.MaxGeneration , GCCollectionMode.Forced ) ; Console.WriteLine ( mgr [ `` abc '' ] ! = null ) ; // true ( still ref 'd by `` obj '' ) refContainer = null ; GC.Collect ( GC.MaxGeneration , GCCollectionMode.Forced ) ; Console.WriteLine ( mgr [ `` abc '' ] ! = null ) ; // false ( no remaining refs ) } } class RefContainer { public object Target { get ; set ; } } class Manager { Dictionary < string , WeakReference > refs = new Dictionary < string , WeakReference > ( ) ; public object this [ string key ] { get { WeakReference wr ; if ( refs.TryGetValue ( key , out wr ) ) { if ( wr.IsAlive ) return wr.Target ; refs.Remove ( key ) ; } return null ; } set { refs [ key ] = new WeakReference ( value ) ; } } } } TrueFalsePress any key to continue . . . var refContainer = new RefContainer ( ) ; refContainer.Target = obj ; var refContainer = new RefContainer ( ) { Target = obj } ; TrueTruePress any key to continue . . . | Why does using an Object Initializer keep an object alive ? |
C_sharp : I 'm trying to implement an Audit Trail ( track what changed , when and by whom ) on a selection of classes in Entity Framework Core.My current implementation relies on overriding OnSaveChangesAsync : This is simple , clean and very easy to use ; any entity that needs an audit trail only needs to inherit AuditableEntity.However , there is a severe limitation to this approach : it can not capture changes made to navigation properties.Our entities make good use of Value Objects , such as an EmailAddress : Now if the user changes an email address of this entity , the State of the Entity is never changed to modified . EF Core seems to handle ValueObjects as Navigation Properties , which are handled separately.So I think there are a few options : Stop using ValueObjects as entity properties . We could still utilize them as entity constructor parameters , but this would cause cascading complexity to the rest of the code . It would also diminish the trust in the validity of the data.Stop using SaveChangesAsync and build our own handling for auditing . Again , this would cause further complexity in the architecture and probably be less performant.Some weird hackery to the ChangeTracker - this sounds risky but might work in theorySomething else , what ? <code> public override Task < int > SaveChangesAsync ( bool acceptAllChangesOnSuccess , CancellationToken cancellationToken = default ) { var currentUserFullName = _userService.CurrentUserFullName ! ; foreach ( var entry in ChangeTracker.Entries < AuditableEntity > ( ) ) { switch ( entry.State ) { case EntityState.Added : entry.Entity.CreatedBy = currentUserFullName ; entry.Entity.Created = _dateTime.Now ; break ; case EntityState.Modified : var originalValues = new Dictionary < string , object ? > ( ) ; var currentValues = new Dictionary < string , object ? > ( ) ; foreach ( var prop in entry.Properties.Where ( p = > p.IsModified ) ) { var name = prop.Metadata.Name ; originalValues.Add ( name , prop.OriginalValue ) ; currentValues.Add ( name , prop.CurrentValue ) ; } entry.Entity.LastModifiedBy = currentUserFullName ; entry.Entity.LastModified = _dateTime.Now ; entry.Entity.LogEntries.Add ( new EntityEvent ( _dateTime.Now , JsonConvert.SerializeObject ( originalValues ) , JsonConvert.SerializeObject ( currentValues ) , currentUserFullName ) ) ; break ; } } return base.SaveChangesAsync ( acceptAllChangesOnSuccess , cancellationToken ) ; } public class EmailAddress : ValueObjectBase { public string Value { get ; private set ; } = null ! ; public static EmailAddress Create ( string value ) { if ( ! IsValidEmail ( value ) ) { throw new ArgumentException ( `` Incorrect email address format '' , nameof ( value ) ) ; } return new EmailAddress { Value = value } ; } } ... Entity.cspublic EmailAddress Email { get ; set ; } ... Entity EF configurationentity.OwnsOne ( e = > e.Email ) ; ... Updatingentity.Email = EmailAddress.Create ( `` e @ mail.com '' ) ; | EF Core - how to audit trail with value objects |
C_sharp : I have come across this odd behaviour : when my projects settings are set to Any CPU and Prefer 32-bit on a 64bit Windows 7 OS the .Net 4.5program below works as expected . If however I turn off Prefer 32-bit then when stepping through the program , I can see that the code never steps into the interface implementation - but also does not throw any errors.I have distilled it down to its simplest form in the following console application : As expected , when toggling Prefer 32-bit the program will alternate between the .net 32bit assemblies and the 64bit assemblies - where it works as expected with the 32bit assemblies and `` breaks silently '' with the 64bit assemblies.As suggested by @ Athari it appears to be related to the size of the Large struct.What am I doing wrong that is causing this behaviour ? <code> namespace BugCheck { interface IBroken { bool Broken < TValue > ( TValue gen , Large large ) ; } class Broke : IBroken { public bool Broken < TValue > ( TValue gen , Large large ) { return true ; } } struct Large { int a , b , c ; } class Program { static void Main ( string [ ] args ) { //32bit can step in . 64bit ca n't ( ( IBroken ) new Broke ( ) ) .Broken ( 1 , new Large ( ) ) ; } } } | Odd debugger behavior with Interface and Generics on 64bit OS when toggling 'Prefer 32-Bit |
C_sharp : I long for those sweet optional arguments from the days when I programmed in C++ more . I know they do n't exist in C # , but my question is Why . I think method overloading is a poor substitute which makes things messy very quickly . I just do not understand what the reasoning is . The C # compiler would obviously not have a problem supporting this just Microsoft elected not to support it.Why , when C # was designed , did they not want to support optional arguments ? <code> void foo ( int x , int y , int z=0 ) { //do stuff ... } //is so much more clean thanvoid foo ( int x , int y ) { foo ( x , y,0 ) ; } void foo ( int x , int y , int z ) { //do stuff } | What is the reasoning for C # not supporting optional/default arguments ? |
C_sharp : I just saw a brand-new video on the Rx framework , and one particular signature caught my eye : At 23:55 , Bart de Smet says : The earliest version would be Action of Action.If Action is a parameterized type , how can it appear unparameterized inside the angle brackets again ? Would n't it have to be Action < Action < Action < ... > > > ad infinitum , which is obviously impossible ? <code> Scheduler.schedule ( this IScheduler , Action < Action > ) | What does Action < Action > mean ? |
C_sharp : I have an issue with binding on Xamarin.iOS.I have 2 libraries : libA.alibB.aAnd libB.a is depend on libA.a classes . In libA I have this class : And in libB I have this code : I have no source code of libA.a and libB.a but only universal static libraries and headers.I tried to add libA binding project and final A.dll as a Reference for libB binding but it says `` namespace ABC not found '' .How should I make a correct binding for libB ? <code> namespace ABC { [ BaseType ( typeof ( NSObject ) ) ] public partial interface ClassAbc { [ Export ( `` setString : '' ) ] void SetString ( string abc ) ; } } namespace ABCUsage { [ BaseType ( typeof ( NSObject ) ) ] public partial interface ClassAbcUsage { [ Export ( `` setAbc : '' ) ] void SetAbc ( ClassAbc abc ) ; } } | Create binding for 2 dependent static libraries in Xamarin.iOS |
C_sharp : I 'm new to C # ( worked in PHP , Python , and Javascript ) and I 'm trying to more or less make a duplicate of another page and change some things - to make a form and database submission.Anyway , here 's the code : I really have little idea what I 'm doing - I 'm reading the tutorials , but C # is a significantly different language than I am used to.I get the Javascript alert when I do not change the text currently , but submission is n't working - I want it to submit to peer_review_comment database table , and fill in employeeid as well as the submitted comment.Sorry if my understanding is so spotty , I am a TOTAL C # newbie ( currently reading http : //www.csharp-station.com/Tutorial/CSharp/ ) <code> public partial class commenter : System.Web.UI.Page { string employee_reviewed ; //public Commenter ( ) ; public void SaveBtn_Click ( object sender , EventArgs e ) { if ( CommentTB.Text == `` Please enter a comment . '' ) { String csname = `` Email Error '' ; Type cstype = this.GetType ( ) ; ClientScriptManager cs = Page.ClientScript ; if ( ! cs.IsStartupScriptRegistered ( cstype , csname ) ) { String cstext = `` alert ( 'Please submit at least one comment . ' ) ; '' ; cs.RegisterStartupScript ( cstype , csname , cstext , true ) ; } FormMessage.Text = `` Please submit at least one comment . `` ; return ; } string comment = CommentTB.Text ; comment = comment.Replace ( `` ' '' , `` '' '' ) ; comment = comment.Replace ( `` ’ '' , `` '' '' ) ; comment = comment.Replace ( `` ` `` , `` '' '' ) ; try { //myCommand.Connection.Open ( ) ; //myCommand.ExecuteNonQuery ( ) ; //myCommand.Connection.Close ( ) ; MySqlCommand myCommand ; MySqlConnection connection ; string connStringName = `` server=localhost ; database=hourtracking ; uid=username ; password=password '' ; connection = new MySqlConnection ( connStringName ) ; string sql_query ; sql_query = `` insert into peer_review_comment `` + `` ( emp_id , comment ) '' + `` values ( ? employeeid , ? comment ) `` ; //String csname = `` Email Error '' ; //Type cstype = this.GetType ( ) ; //ClientScriptManager cs = Page.ClientScript ; //cs.RegisterStartupScript ( cstype , csname , sql_query , true ) ; myCommand = new MySqlCommand ( sql_query , connection ) ; //FormMessage.Text = sql_query ; //return ; Trace.Write ( `` comment = `` , comment ) ; myCommand.Parameters.Add ( new MySqlParameter ( `` ? employeeid '' , ViewState [ `` employeeid '' ] .ToString ( ) ) ) ; myCommand.Parameters.Add ( new MySqlParameter ( `` ? comment '' , comment ) ) ; try { myCommand.Connection.Open ( ) ; myCommand.ExecuteNonQuery ( ) ; myCommand.Connection.Close ( ) ; } catch ( Exception ex ) { FormMessage.Text = `` Error : SaveBtn_Click - `` + ex.Message ; } //SendNotification ( from , to , cc , subject , body , attach ) ; FormMessage.Text = `` \n Thank you for leaving anonymous feedback for `` + employee_reviewed ; ; ThankyouDiv.Visible = true ; FormFieldDiv.Visible = false ; reviewHeader.Visible = false ; } catch ( Exception ex ) { FormMessage.Text = `` Error : SaveBtn_Click - `` + ex.Message ; } } } | New to C # - trying to write code to do a simple function |
C_sharp : As C # lacks support for freestanding functions , I find it hard to find a place to put conversion functions . For example , I 'd like to convert an enum to a number . In C++ , I would make the following freestanding function for this : How can I elegantly do this in C # ? Should I make a dummy static class for holding the function , and if so , how can I find a meaningful name for it ? Or should I make a partial class Convert ? Any ideas ? Thanks in advance.Update : In retrospect , my example was not very well chosen , as there exists a default conversion between enum and int . This would be a better example : <code> UINT32 ConvertToUint32 ( const MyEnum e ) ; Person ConvertToPerson ( const SpecialPersonsEnum e ) ; | Where to put conversion functions ? |
C_sharp : I 'm looking to see if there is a method or tool to view how things like closures or query expressions are created by the c # compiler `` under the hood '' . I 've noticed that many blog posts dealing with these issues will have the original code with syntactic sugar and the underlying c # code that the compiler converts that to . So for example with linq and query expressions they would show : then the resulting code would beIs it possible with a tool or do you just have to know how it works from the spec and go from there ? <code> var query = from x in myList select x.ToString ( ) ; var query = myList.Select ( x= > x.ToString ( ) ) ; | How to view c # compiler output of syntactic sugar |
C_sharp : I have a handy utility method which takes code and spits out an in-memory assembly . ( It uses CSharpCodeProvider , although I do n't think that should matter . ) This assembly works like any other with reflection , but when used with the dynamic keyword , it seems to fail with a RuntimeBinderException : 'object ' does not contain a definition for 'Sound'Example : Does anyone know the reason why the DLR is not able to handle this ? Is there anything that could be done to fix this scenario ? EDIT : createAssembly method : Disclaimer : some of this stuff contains extension methods , custom types , etc . It should be self-explanatory though . <code> var assembly = createAssembly ( `` class Dog { public string Sound ( ) { return \ '' woof\ '' ; } } '' ) ; var type = assembly.GetType ( `` Dog '' ) ; Object dog = Activator.CreateInstance ( type ) ; var method = type.GetMethod ( `` Sound '' ) ; var test1Result = method.Invoke ( dog , null ) ; //This returns `` woof '' , as you 'd expectdynamic dog2 = dog ; String test2Result = dog2.Sound ( ) ; //This throws a RuntimeBinderException private Assembly createAssembly ( String source , IEnumerable < String > assembliesToReference = null ) { //Create compiler var codeProvider = new CSharpCodeProvider ( ) ; //Set compiler parameters var compilerParameters = new CompilerParameters { GenerateInMemory = true , GenerateExecutable = false , CompilerOptions = `` /optimize '' , } ; //Get the name of the current assembly and everything it references if ( assembliesToReference == null ) { var executingAssembly = Assembly.GetExecutingAssembly ( ) ; assembliesToReference = executingAssembly .AsEnumerable ( ) .Concat ( executingAssembly .GetReferencedAssemblies ( ) .Select ( a = > Assembly.Load ( a ) ) ) .Select ( a = > a.Location ) ; } //End if compilerParameters.ReferencedAssemblies.AddRange ( assembliesToReference.ToArray ( ) ) ; //Compile code var compilerResults = codeProvider.CompileAssemblyFromSource ( compilerParameters , source ) ; //Throw errors if ( compilerResults.Errors.Count ! = 0 ) { throw new CompilationException ( compilerResults.Errors ) ; } return compilerResults.CompiledAssembly ; } | Attempting to bind a dynamic method on a dynamically-created assembly causes a RuntimeBinderException |
C_sharp : I have a device that transmits binary data . To interpret the data I have defined a struct that matches the data format . The struct has a StuctLayoutAttribute with LayoutKind.Sequential . This works as expected , e.g : Now I wish to treat one struct similar to an other struct , so I experimented with the structure implementing an interface : To my surprise the offsets and size of DemoWithInterface remain the same as DemoPlain and converting the same binary data from the device to either an an array of DemoPlain or an array of DemoWithInterface both work . How is this possible ? C++ implementations often use a vtable ( see Where in memory is vtable stored ? ) to sore virtual methods . I believe that in C # methods published in an interface , and methods that are declared virtual , are similar to virtual methods in C++ and that it requires something similar to a vtable to find the correct method . Is this correct or does C # do it completely different ? If correct , where is the vtable like structure stored ? If different , how is C # implemented with respect to interface inheritance and virtual methods ? <code> [ StructLayout ( LayoutKind.Sequential ) ] struct DemoPlain { public int x ; public int y ; } Marshal.OffsetOf < DemoPlain > ( `` x '' ) ; // yields 0 , as expectedMarshal.OffsetOf < DemoPlain > ( `` y '' ) ; // yields 4 , as expectedMarshal.SizeOf < DemoPlain > ( ) ; // yields 8 , as expected interface IDemo { int Product ( ) ; } [ StructLayout ( LayoutKind.Sequential ) ] struct DemoWithInterface : IDemo { public int x ; public int y ; public int Product ( ) = > x * y ; } Marshal.OffsetOf < DemoWithInterface > ( `` x '' ) .Dump ( ) ; // yields 0Marshal.OffsetOf < DemoWithInterface > ( `` y '' ) .Dump ( ) ; // yields 4Marshal.SizeOf < DemoWithInterface > ( ) .Dump ( ) ; // yields 8 | Where does C # store a structure 's vtable when unmarshalling using [ StructLayout ( LayoutKind.Sequential ) ] |
C_sharp : I 'm writing an application that creates a `` Catalog '' of files , which can be attributed with other meta data files such as attachments and thumbnails.I 'm trying to abstract the interface to a catalog to the point where a consumer of a catalog does not need to know about the underlying file system used to store the files . So I 've created an interface called IFileSystemAdaptor which is shown below.Essentially my IFileSystemAdaptor interface exposes a flat list of files , that can also be associated with additional meta data files.As you can see I 'm using references to generic Stream objects to abstract the interface to a file 's data . This way one implementation of a Catalog could return files from a hard disk , while another could return the data from a web server.Now I 'm trying to figure out how to keep my program from leaving streams open . Is there a rule of thumb for what members should close streams ? Should the consumer of a stream close it , or should the member that original created the stream be responsible for closing it . <code> public interface IFileSystemAdaptor : IDisposable { void WriteFileData ( string fileName , Stream data ) ; Stream ReadFileData ( string filename ) ; void DeleteFileData ( string filename ) ; void ClearAllData ( ) ; void WriteMetaFileData ( string filename , string path , Stream data ) ; Stream ReadMetaFileData ( string filename , string path ) ; void DeleteMetaFileData ( string filename , string path ) ; void ClearMetaFilesData ( string filename ) ; } | Who should be responsible for closing a stream |
C_sharp : Here is some code to return a linear function ( y=ax+b ) .I could do the same thing with expression trees , but I 'm not sure it is worth the effort.I know that the lambda will capture the parameters , which is a downside . Are there any more pros/cons which I 'm not aware of ? My main question is , is it worth it to use expression trees in this scenario ? Why or why not ? <code> public static Func < double , double > LinearFunc ( double slope , double offset ) { return d = > d * slope + offset ; } | Creating a Func < > dynamically - Lambdas vs . Expression trees |
C_sharp : I have an abstract class : and I have a List < A > a and I want to get a first item of given type T : Is there a way to do it ? Edit : It shows : The type parameter 'T ' can not be used with the 'as ' operator because it does not have a class type constraint nor a 'class ' constraint <code> abstract class A { // some stuff float val = 0 ; abstract float Foo ( ) ; } class B1 : A { override float Foo ( ) { Console.WriteLine ( `` B1 : `` + val ) ; } } class B2 : A { override float Foo ( ) { Console.WriteLine ( `` B2 : `` + val ) ; } } public T GetTypeFromList < T > ( ) { foreach ( var item in a ) { T tmp = item as T ; // does n't compile if ( tmp ! = null ) return tmp ; } throw new Exception ( `` Type is n't in list . `` ) ; } | How to cast abstract class into type T ? |
C_sharp : I am trying to optimize my code and was running VS performance monitor on it.It shows that simple assignment of float takes up a major chunk of computing power ? ? I do n't understand how is that possible.Here is the code for TagData : So all I am really doing is : I am confused . <code> public class TagData { public int tf ; public float tf_idf ; } float tag_tfidf = td.tf_idf ; | C # huge performance drop assigning float value |
C_sharp : Suppose we have a list of strings like below : There are some items with the length of more than 3.By the help of Linq I want to divide them into new items in the list , so the new list will have these items : Do n't ask me why Linq . I am a Linq fan and do n't like unLinq code : D <code> List < string > myList = new List < string > ( ) { `` one '' , `` two '' , `` three '' , `` four '' } ; { `` one '' , `` two '' , `` thr '' , `` ee '' , `` fou '' , `` r '' } ; | Modify list of strings to only have max n-length strings ( use of Linq ) |
C_sharp : After reading a lot about immutability in C # , and understading it 's benefits ( no side effects , safe dictionary keys , multithreading ... ) a question has come to my mind : Why there is not a keyword in C # for asserting that a class ( or struct ) is immutable ? This keyword should check at compile time that there is no way you can mutate the class ( or struct ) . For example : I think the compiler work would be quite easy , as it would need to check just a few things : All public fields are readonly.All public properties only have getters.All public fields or properties have immutable types as well ( simple value types , or immutable classes/structs ) .All public functions or public property getters only depend on immutable fields or properties ( public fields/props as described before , or private fields/props which comply to the same restrictions ) . This of course includes Equals ( ) , GetHashCode ( ) and ToString ( ) .Some possible problems come to my mind with this design : For the compiler to know that a compiled class/struct is immutable , it would probably be necesary to make changes in the intermediate language.Readonly generic collection ( such as IEnumerable < T > ) immutability would depend on the immutability of the type < T > . The proposed immutable keyword would not be useful in this context , as you could not declare that IEnumerable < string > is immutable , even though it is.Are the reasons stated before enough for this keyword to not exist ? Am I missing any other drawbacks ? Is this just not necessary enough for such big changes in the language ? <code> public immutable class MyImmutableClass { public readonly string field ; public string field2 ; //This would be a compile time error public readonly AnyMutableType field3 ; //This would be a compile time error public string Prop { get ; } public string Prop2 { get ; set ; } //This would be a compile time error public AnyMutableType Prop3 { get ; } //This would be a compile time error } | Guaranteeing immutability in c # |
C_sharp : I have public functions like this : Basically I want to individually handle reference types and nullable types . It compiles ; until i call for value types . For reference types it compiles.What real ambiguity is here ? When T is int , cant it call the struct overload appropriately ? Also : Why is the compiler only detecting the reference type overload ? I tried having two separate overloads : The problem persisted . And obviously , the first two methods dont compile here since overloading does n't work merely on the basis of constraints.I tried by removing the class constrained overload and keeping just the struct constrained one , like this : Am I only left with renaming the two functions ? I feel its appropriate to have a unified name so that the caller just doesnt have to worry about the implementation detail , but just call Get for any type.Update : Marc 's solution doesnt work if I have to avoid the optional parameter.But there 's more magic : ( : ( By all means I 'm expecting the same compiler bug ( according to me ) to annoy me . But no it works this time.So if overload resolution comes before constraint checking as Marc says , should n't I get the same error this time too ? But no . Why is it so ? ? What the hell is going on ? : x <code> public static T Get < T > ( this Mango m , T defaultValue = default ( T ) ) where T : class { //do something ; return something ; } public static T ? Get < T > ( this Mango m , T ? defaultValue = default ( T ? ) ) where T : struct { //do something ; return something ; } mango.Get < string > ( ) ; // compiles..mango.Get ( `` '' ) ; // compiles..mango.Get < int > ( ) ; // The type 'int ' must be a reference type in order to use it as // parameter 'T ' in the generic type or method Get < T > ( Mango , T ) //also // The call is ambiguous between the following methods or properties : // Get < int > ( Mango , int ) and Get < int > ( Mango , int ? ) mango.Get < int > ( 0 ) ; // The type 'int ' must be a reference type in order to use it as // parameter 'T ' in the generic type or method Get < T > ( Mango , T ) public static T Get < T > ( this Mango m ) where T : class { return default ( T ) ; } public static T ? Get < T > ( this Mango m ) where T : struct { return default ( T ) ; } public static T Get < T > ( this Mango m , T def ) where T : class { return default ( T ) ; } public static T ? Get < T > ( this Mango m , T ? def ) where T : struct { return default ( T ) ; } public static T ? Get < T > ( this Mango m , T ? defaultValue = default ( T ? ) ) where T : struct { //do something ; return something ; } mango.Get < int > ( ) ; // voila compiles ! mango.Get < int > ( 0 ) ; // no problem at all..// but now I ca n't have mango.Get < string > ( ) for instance : ( mango.Get < int > ( ) ; // still wouldnt work ! ! public static bool IsIt < T > ( this T ? obj ) where T : struct { return who knows ; } public static bool IsIt < T > ( this T obj ) where T : class { return perhaps ; } Guid ? g = null ; g.IsIt ( ) ; //just fine , and calls the struct constrained overload '' abcd '' .IsIt ( ) ; //just fine , and calls the class constrained overload | Compiler not calling appropriate generic overload when passed with value type |
C_sharp : I am currently optimizing a low-level library and have found a counter-intuitive case . The commit that caused this question is here.There is a delegateand an instance methodOn this line , if I use the method as a delegate , the program allocates many GC0 for the temp delegate wrapper , but the performance is 10 % faster ( but not stable ) .If I instead cache the method in a delegate outside the loop like this : then the program does not allocate at all , numbers are very stable but much slower.I looked through generated IL and it is doing the same thing , but in the later case newobj is called only once and then local variable if loaded.With cached delegate IL_0034 : With temp allocations IL_0037 : Why the code with allocations is faster here ? What is needed to avoid allocations but keep the performance ? ( testing on .NET 4.5.2/4.6.1 , x64 , Release , on two different machines ) UpdateHere is standalone example that behaves as expected : cached delegate performs more than 2x faster with 4 sec vs 11 sec . So the question is specific to the referenced project - what subtle issues with JIT compiler or something else could cause the unexpected result ? <code> public delegate void FragmentHandler ( UnsafeBuffer buffer , int offset , int length , Header header ) ; public void OnFragment ( IDirectBuffer buffer , int offset , int length , Header header ) { _totalBytes.Set ( _totalBytes.Get ( ) + length ) ; } var fragmentsRead = image.Poll ( OnFragment , MessageCountLimit ) ; FragmentHandler onFragmentHandler = OnFragment ; IL_002d : ldarg.0IL_002e : ldftn instance void Adaptive.Aeron.Samples.IpcThroughput.IpcThroughput/Subscriber : :OnFragment ( class [ Adaptive.Agrona ] Adaptive.Agrona.IDirectBuffer , int32 , int32 , class [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.Header ) IL_0034 : newobj instance void [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.FragmentHandler : :.ctor ( object , native int ) IL_0039 : stloc.3IL_003a : br.s IL_005a// loop start ( head : IL_005a ) IL_003c : ldloc.0 IL_003d : ldloc.3 IL_003e : ldsfld int32 Adaptive.Aeron.Samples.IpcThroughput.IpcThroughput : :MessageCountLimit IL_0043 : callvirt instance int32 [ Adaptive.Aeron ] Adaptive.Aeron.Image : :Poll ( class [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.FragmentHandler , int32 ) IL_0048 : stloc.s fragmentsRead IL_002c : stloc.2IL_002d : br.s IL_0058// loop start ( head : IL_0058 ) IL_002f : ldloc.0 IL_0030 : ldarg.0 IL_0031 : ldftn instance void Adaptive.Aeron.Samples.IpcThroughput.IpcThroughput/Subscriber : :OnFragment ( class [ Adaptive.Agrona ] Adaptive.Agrona.IDirectBuffer , int32 , int32 , class [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.Header ) IL_0037 : newobj instance void [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.FragmentHandler : :.ctor ( object , native int ) IL_003c : ldsfld int32 Adaptive.Aeron.Samples.IpcThroughput.IpcThroughput : :MessageCountLimit IL_0041 : callvirt instance int32 [ Adaptive.Aeron ] Adaptive.Aeron.Image : :Poll ( class [ Adaptive.Aeron ] Adaptive.Aeron.LogBuffer.FragmentHandler , int32 ) IL_0046 : stloc.s fragmentsRead using System ; using System.Diagnostics ; namespace TestCachedDelegate { public delegate int TestDelegate ( int first , int second ) ; public static class Program { static void Main ( string [ ] args ) { var tc = new TestClass ( ) ; tc.Run ( ) ; } public class TestClass { public void Run ( ) { var sw = new Stopwatch ( ) ; sw.Restart ( ) ; for ( int i = 0 ; i < 1000000000 ; i++ ) { CallDelegate ( Add , i , i ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Non-cached : `` + sw.ElapsedMilliseconds ) ; sw.Restart ( ) ; TestDelegate dlgCached = Add ; for ( int i = 0 ; i < 1000000000 ; i++ ) { CallDelegate ( dlgCached , i , i ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Cached : `` + sw.ElapsedMilliseconds ) ; Console.ReadLine ( ) ; } public int CallDelegate ( TestDelegate dlg , int first , int second ) { return dlg ( first , second ) ; } public int Add ( int first , int second ) { return first + second ; } } } } | C # Why using instance method as delegate allocates GC0 temp objects but 10 % faster than a cached delegate |
C_sharp : The problem : I have Dictionary < String , String > that I need an alias to , but I also need to serialize/deserialize it.Solutions I 've tried : but that work because I would have to create a Deserialization constructor and that would be a bit silly when Dictionary already can be deserialized.I also triedbut I need this to work in more that one file and if add that line in all the files that need it , I 'll be removing half the point of typedefs ( that is , if I need to change the type , I can do so easily ) What can I do about this ? <code> class Foo : Dictionary < String , String > { } using Foo = System.Collections.Generic.Dictionary < String , String > ; | C # Typedef that preserves attributes |
C_sharp : Possible Duplicate : What do two question marks together mean in C # ? I just came across the code below and not really sure what it means and ca n't google it because google omits the ? ? Is the second line some sort of if else statement , what does the ? ? mean <code> int ? x = 32 ; int y = x ? ? 5 ; | Is this an if else statement |
C_sharp : I 've thought of this before and it came to mind again when reading this question.Are there any plans for `` extension properties '' in a future version of C # ? It seems to me they might be pretty stright-forward to implement with a little more `` compiler magic '' . For example , using get_ and set_ prefixes on extension method names would turn that method into an extension property : Are there any technical restrictions which would prevent this ? Would this create too much stuff going on behind the scenes ? Not important enough to be worth the effort ? <code> public class Foo { public string Text { get ; set ; } } public static class FooExtensions { public static string get_Name ( this Foo foo ) { return foo.Text ; } public static void set_Name ( this Foo foo , string value ) { foo.Text = value ; } } | Are there any plans for `` extension properties '' in a future version of C # ? |
C_sharp : I am on Admin area now want to send the values to Account Controller which is in default area how i can send this is my other action in Account Controller where i want to redirect my code <code> ChangePasswordModel mode = new ChangePasswordModel ( ) ; mode.ConfirmPassword = password ; mode.NewPassword = password ; mode.OldPassword = user.Password ; return RedirectToAction ( `` ChangePassword '' , `` Account '' , new { area = '/ ' } , new { model = mode } ) ; [ Authorize ] [ HttpPost ] public ActionResult ChangePassword ( ChangePasswordModel model ) { if ( ModelState.IsValid ) { // ChangePassword will throw an exception rather // than return false in certain failure scenarios . bool changePasswordSucceeded ; try { MembershipUser currentUser = Membership.GetUser ( User.Identity.Name , true /* userIsOnline */ ) ; changePasswordSucceeded = currentUser.ChangePassword ( model.OldPassword , model.NewPassword ) ; } catch ( Exception ) { changePasswordSucceeded = false ; } if ( changePasswordSucceeded ) { return RedirectToAction ( `` ChangePasswordSuccess '' ) ; } else { ModelState.AddModelError ( `` '' , `` The current password is incorrect or the new password is invalid . `` ) ; } } // If we got this far , something failed , redisplay form return View ( model ) ; } | Redirect action to action in other area with model as parmenter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.