text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : The following code : produces the following output in the textbox : From the first line of the output , it is clear that in the regional setting of my PC , date/time is formatted as date.month.year HHmm.ss.The second line of the output is confusing to me . Though I specified MM/dd/yyyy format for the variable s , the DateTime object is formatted as MM.dd.yyyy . Why ? This is a C # WPF program on .NET Framework 4 . <code> DateTime dt = new DateTime ( 2013 , 9 , 13 , 14 , 34 , 0 ) ; string s = dt.ToString ( `` MM/dd/yyyy '' ) ; textBox1.AppendText ( DateTime.Now + `` \n '' ) ; textBox1.AppendText ( s + `` \n '' ) ; textBox1.AppendText ( dt.ToString ( ) + `` \n '' ) ; 13.09.2013 1441.2809.13.201313.09.2013 1434.00 | Formatting DateTime to string |
C_sharp : I just programmed a simple reverse loop like this : but it does n't stop at 0 as expected but goes down far to the negative values , why ? See this ideone sample : http : //ideone.com/kkixx8 ( I tested it in c # and c++ ) <code> for ( unsigned int i = 50 ; i > = 0 ; i -- ) printf ( `` i = % d\n '' , i ) ; | strange behavior of reverse loop in c # and c++ |
C_sharp : I have a customer that is trying to access their calendars from our web application . Everything works for all of our other customers , so I am not sure what is different here except this customer is in Australia and using a non gmail.com email address . The customer is able to authorize our application and we do get a oauth token for the user . We request calendar access and the customer granted it . When we request a list of all of the calendars , we get the invalid grant message.Below is the code that we use to access their calendars . The method being called is GetAllWritableCalendars . <code> public class GoogleCalendarAdapter : ICalendarAdapter { # region attributes private readonly ISiteAuthTokenQueryRepository _tokenRepo ; private readonly GoogleCalendarSettings _settings ; private const string APPNAME = `` SomeAppName '' ; private const string ACL_OWNER = `` owner '' ; private const string ACL_WRITER = `` writer '' ; # endregion # region ctor public GoogleCalendarAdapter ( ISiteAuthTokenQueryRepository tokenRepo , GoogleCalendarSettings settings ) { _tokenRepo = tokenRepo ; _settings = settings ; } # endregion # region methods private GoogleAuthorizationCodeFlow BuildAuthorizationCodeFlow ( ) { return new GoogleAuthorizationCodeFlow ( new GoogleAuthorizationCodeFlow.Initializer ( ) { ClientSecrets = BuildClientSecrets ( ) , Scopes = BuildScopeList ( ) } ) ; } private CalendarService BuildCalendarService ( SiteAuthToken token ) { return new CalendarService ( new BaseClientService.Initializer ( ) { ApplicationName = APPNAME , HttpClientInitializer = BuildUserCredential ( token ) } ) ; } private ClientSecrets BuildClientSecrets ( ) { return new ClientSecrets ( ) { ClientId = _settings.ClientId , ClientSecret = _settings.ClientSecret } ; } private string [ ] BuildScopeList ( ) { return new [ ] { CalendarService.Scope.Calendar } ; } private UserCredential BuildUserCredential ( SiteAuthToken token ) { TokenResponse responseToken = new TokenResponse ( ) { AccessToken = token.AccessToken , RefreshToken = token.RefreshToken } ; return new UserCredential ( BuildAuthorizationCodeFlow ( ) , APPNAME , responseToken ) ; } public async Task < List < Cal > > GetAllWritableCalendars ( Guid siteGuid ) { SiteAuthToken token = await GetToken ( siteGuid ) ; CalendarService svc = BuildCalendarService ( token ) ; IList < CalendarListEntry > calendars = svc.CalendarList .List ( ) .Execute ( ) .Items ; return calendars.Where ( c = > c.AccessRole.Equals ( ACL_OWNER , StringComparison.CurrentCultureIgnoreCase ) || c.AccessRole.Equals ( ACL_WRITER , StringComparison.CurrentCultureIgnoreCase ) ) .Select ( c = > new Cal ( ) { Id = c.Id , Name = c.Summary } ) .OrderBy ( o = > o.Name ) .ToList ( ) ; } private async Task < SiteAuthToken > GetToken ( Guid siteGuid ) { SiteAuthToken retVal = await _tokenRepo.GetSiteAuthToken ( siteGuid ) ; if ( retVal == null ) { throw new ApplicationException ( $ '' Could not find a SiteAuthToken for specified site ( SiteGuid : { siteGuid } ) '' ) ; } return retVal ; } # endregion | Google Calendar returning invalid grant |
C_sharp : Is there a way to know what parameters are needed by an event in Visual Studio 2010 ? Let 's say I have a DropDownList control and I want to bind a method to the `` OnSelectedIndexChanged '' , I would do something like thisIn the ASPX File : In the codebehind : Is there a way to know what parameters the method needs ? ( In this case , an object for the sender and an EventArgs parameter for the event . ) I know you can easily create the method by double-clicking the right event in Design Mode , but it does a mess with your code so I prefer not to use it.Thanks ! <code> < asp : DropDownList ID= '' lstMyList '' runat= '' server '' OnSelectedIndexChanged= '' lstMyList_SelectedIndexChanged '' > < /asp : DropDownList > protected void lstMyList_SelectedIndexChanged ( object sender , EventArgs e ) { ... } | Find the right parameters for an event without using Design Mode in Visual Studio 2010 |
C_sharp : BackgroundWhile writing a class for parsing certain text , I needed the ability to get the line number of a specific character position ( in other words , count all linebreaks that occur before that character ) .Trying to find the most efficient code possible to achieve this I set up a couple of benchmarks , which revealed that Regex was the slowest method and that manually iterating the string was the fastest.Following is my current approach ( 10k iterations : 278 ms ) : However , while doing these benchmarks I remembered that method calls can sometimes be a bit expensive , so I decided to try moving the conditions from IsEndOfLine ( ) directly into the if-statement inside GetLineNumber ( ) as well.Like I expected , this executes more than two times faster ( 10k iterations : 112 ms ) : ProblemFrom what I 've read the JIT compiler does n't ( or at least did n't ) optimize IL code that is more than 32 bytes in size [ 1 ] unless [ MethodImplAttribute ( MethodImplOptions.AggressiveInlining ) ] is specified [ 2 ] . But despite applying this attribute to IsEndOfLine ( ) , no inlining seems to occur.Most of the talk I 've been able to find about this are from older posts/articles . In the newest one ( [ 2 ] from 2012 ) the author did apparently successfully inline a 34-byte function using MethodImplOptions.AggressiveInlining , implying that the flag allows larger IL code to be inlined if all other criteria are met.Measuring my method 's size using the following code revealed that it is 54 bytes long : Using the Dissasembly window in VS 2019 shows the following Assembly code for IsEndOfLine ( ) ( with C # source code turned on in the Viewing Options ) : ( Configuration : Release ( x86 ) , disabled Just My Code and Suppress JIT optimization on module load ) ... and the following code for the loop in GetLineNumber ( ) : I 'm not very good at reading Assembly code , but it seems to me that no inlining has occurred.QuestionWhy does n't the JIT compiler inline my IsEndOfLine ( ) method even when MethodImplOptions.AggressiveInlining is specified ? I know this flag is only a hint to the compiler , but based on [ 2 ] applying it should make it possible to inline IL larger than 32 bytes . Apart from that , to me , my code seems to satisfy all other conditions.Is there some other kind of limitation that I am missing ? BenchmarksResults : < benchmark code moved to answer for brevity > Footnotes1 To Inline or not to Inline : That is the question2 Aggressive Inlining in the CLR 4.5 JIT -- EDIT -- For some reason , after restarting VS , enabling and re-disabling the settings mentioned before as well as re-applying MethodImplOptions.AggressiveInlining , the method does now appear to be inlined . However , it has added a couple of instructions that are n't there when you inline the if-conditions manually.JIT-optimized version : My optimized version : New instructions : I still see no improvement in performance/execution speed , however ... Supposedly this is due to the extra instructions that the JIT added , and I 'm guessing this is as good as it gets without inlining the conditions myself ? <code> private string text ; /// < summary > /// Returns whether the specified character index is the end of a line./// < /summary > /// < param name= '' index '' > The index to check. < /param > /// < returns > < /returns > private bool IsEndOfLine ( int index ) { //Matches `` \r '' and `` \n '' ( but not `` \n '' if it 's preceded by `` \r '' ) . char c = text [ index ] ; return c == '\r ' || ( c == '\n ' & & ( index == 0 || text [ index - 1 ] ! = '\r ' ) ) ; } /// < summary > /// Returns the number of the line at the specified character index./// < /summary > /// < param name= '' index '' > The index of the character which 's line number to get. < /param > /// < returns > < /returns > public int GetLineNumber ( int index ) { if ( index < 0 || index > text.Length ) { throw new ArgumentOutOfRangeException ( `` index '' ) ; } int lineNumber = 1 ; int end = index ; index = 0 ; while ( index < end ) { if ( IsEndOfLine ( index ) ) lineNumber++ ; index++ ; } return lineNumber ; } while ( index < end ) { char c = text [ index ] ; if ( c == '\r ' || ( c == '\n ' & & ( index == 0 || text [ index - 1 ] ! = '\r ' ) ) ) lineNumber++ ; index++ ; } Console.WriteLine ( this.GetType ( ) .GetMethod ( `` IsEndOfLine '' ) .GetMethodBody ( ) .GetILAsByteArray ( ) .Length ) ; -- - [ PATH REMOVED ] \Performance Test - Find text line number\TextParser.cs 28 : char c = text [ index ] ; 001E19BA in al , dx 001E19BB mov eax , dword ptr [ ecx+4 ] 001E19BE cmp edx , dword ptr [ eax+4 ] 001E19C1 jae 001E19FF 001E19C3 movzx eax , word ptr [ eax+edx*2+8 ] 29 : return c == '\r ' || ( c == '\n ' & & ( index == 0 || text [ index - 1 ] ! = '\r ' ) ) ; 001E19C8 cmp eax,0Dh 001E19CB je 001E19F8 001E19CD cmp eax,0Ah 001E19D0 jne 001E19F4 001E19D2 test edx , edx 001E19D4 je 001E19ED 001E19D6 dec edx 001E19D7 mov eax , dword ptr [ ecx+4 ] 001E19DA cmp edx , dword ptr [ eax+4 ] 001E19DD jae 001E19FF 001E19DF cmp word ptr [ eax+edx*2+8 ] ,0Dh 001E19E5 setne al 001E19E8 movzx eax , al 001E19EB pop ebp 001E19EC ret 001E19ED mov eax,1 001E19F2 pop ebp 001E19F3 ret 001E19F4 xor eax , eax 001E19F6 pop ebp 001E19F7 ret 001E19F8 mov eax,1 001E19FD pop ebp 001E19FE ret 001E19FF call 70C2E2B0 001E1A04 int 3 63 : index = 0 ; 001E1950 xor esi , esi 64 : while ( index < end ) { 001E1952 test ebx , ebx 001E1954 jle 001E196C 001E1956 mov ecx , edi 001E1958 mov edx , esi 001E195A call dword ptr ds : [ 144E10h ] 001E1960 test eax , eax 001E1962 je 001E1967 65 : if ( IsEndOfLine ( index ) ) lineNumber++ ; 001E1964 inc dword ptr [ ebp-10h ] 66 : index++ ; 001E1967 inc esi 64 : while ( index < end ) { 001E1968 cmp esi , ebx 001E196A jl 001E1956 67 : } 68 : 69 : return lineNumber ; 001E196C mov eax , dword ptr [ ebp-10h ] 001E196F pop ecx 001E1970 pop ebx 001E1971 pop esi 001E1972 pop edi 001E1973 pop ebp 001E1974 ret Text length : 11645Line : 201Standard loop : 00:00:00.2779946 ( 10000 à 00:00:00.0000277 ) Line : 201Standard loop ( inline ) : 00:00:00.1122908 ( 10000 à 00:00:00.0000112 ) 66 : while ( index < end ) { 001E194B test ebx , ebx 001E194D jle 001E1998 001E194F mov esi , dword ptr [ ecx+4 ] 67 : if ( IsEndOfLine ( index ) ) lineNumber++ ; 001E1952 cmp edx , esi 001E1954 jae 001E19CA 001E1956 movzx eax , word ptr [ ecx+edx*2+8 ] 001E195B cmp eax,0Dh 001E195E je 001E1989 001E1960 cmp eax,0Ah 001E1963 jne 001E1985 001E1965 test edx , edx 001E1967 je 001E197E 001E1969 mov eax , edx 001E196B dec eax 001E196C cmp eax , esi 001E196E jae 001E19CA 001E1970 cmp word ptr [ ecx+eax*2+8 ] ,0Dh 001E1976 setne al 001E1979 movzx eax , al 001E197C jmp 001E198E 001E197E mov eax,1 001E1983 jmp 001E198E 001E1985 xor eax , eax 001E1987 jmp 001E198E 001E1989 mov eax,1 001E198E test eax , eax 001E1990 je 001E1993 001E1992 inc edi 68 : index++ ; 87 : while ( index < end ) { 001E1E9B test ebx , ebx 001E1E9D jle 001E1ECE 001E1E9F mov esi , dword ptr [ ecx+4 ] 88 : char c = text [ index ] ; 001E1EA2 cmp edx , esi 001E1EA4 jae 001E1F00 001E1EA6 movzx eax , word ptr [ ecx+edx*2+8 ] 89 : if ( c == '\r ' || ( c == '\n ' & & ( index == 0 || text [ index - 1 ] ! = '\r ' ) ) ) lineNumber++ ; 001E1EAB cmp eax,0Dh 001E1EAE je 001E1EC8 001E1EB0 cmp eax,0Ah 001E1EB3 jne 001E1EC9 001E1EB5 test edx , edx 001E1EB7 je 001E1EC8 001E1EB9 mov eax , edx 001E1EBB dec eax 001E1EBC cmp eax , esi 001E1EBE jae 001E1F00 001E1EC0 cmp word ptr [ ecx+eax*2+8 ] ,0Dh 001E1EC6 je 001E1EC9 001E1EC8 inc edi 90 : index++ ; 001E1976 setne al 001E1979 movzx eax , al 001E197C jmp 001E198E 001E197E mov eax,1 001E1983 jmp 001E198E 001E1985 xor eax , eax 001E1987 jmp 001E198E 001E1989 mov eax,1 001E198E test eax , eax | Method is not inlined by the JIT compiler even though all criteria seems to be met |
C_sharp : In C # given a function with the below signatureIf the function was called using Inside the function Foo is it possible to test that the x and y arguments reference the same variable ? A simple equivalent test of x and y is n't sufficient as this is also true in the case two different variable have the same value . <code> public static void Foo ( ref int x , ref int y ) int A = 10 ; Foo ( ref A , ref A ) | How to Test if C # ref Arguments Reference the Same Item |
C_sharp : In a collection of valuesI 'm trying to do with linqIs there someway to do it with linq ? <code> [ 0 , 2 , 25 , 30 ] [ 0 , 0 , 0 , 2 , 2 , 2 , 25 , 25 , 25 , 30 , 30 , 30 ] //Replicate 2 times ( values repeated 3 times ) | Insert duplicates values linq |
C_sharp : Let 's say I haveSometimes , instead of just sayingI end up doingor maybe evento avoid boxing or copying structs.It works fine and everything , but are there any downsides I do n't know about ( other than a negligible increase in memory usage ) ? Is this an accepted practice , or is it discouraged for any reason I might not be aware of ? <code> interface IMatrix { double this [ int r , int c ] { get ; } } struct Matrix2x2 : IMatrix { double a1 , a2 , b1 , b2 ; double this [ int r , int c ] { get { ... } } } struct Matrix3x3 : IMatrix { double a1 , a2 , a3 , b1 , b2 , b3 , c1 , c2 , c3 ; double this [ int r , int c ] { get { ... } } } class Matrix : IMatrix { // Any size double [ , ] cells ; double this [ int r , int c ] { get { ... } } } static class Matrices { static IMatrix Multiply ( IMatrix a , IMatrix b ) { ... } } static class Matrices { static IMatrix Multiply < T1 , T2 > ( T1 a , T2 b ) where T1 : IMatrix where T2 : IMatrix { ... } } static class Matrices { static IMatrix Multiply < T1 , T2 > ( [ In ] ref T1 a , [ In ] ref T2 b ) where T1 : IMatrix where T2 : IMatrix { ... } } | Using constrained generics instead of interfaces -- downsides ? |
C_sharp : So Say I have 2 entities , Post and PostHistory . Whenever I create or edit a post , I want to create an exact copy of it as PostHistory to log all changes made to a post . Say the post entity has the following definition : The problem comes when I create my first Post . For example , if I try this : That will fail because since both post and history are new entities , Post.PostHistory is null due to it not having been initialized yet . The only way I can see to do this is to first commit post to the db , then commit history to the database , but I do n't see why performing 2 separate inserts should be necessary for this.If I have a constructor that initializes the ICollection to a List < T > everything works fine , but forcing the implementation to List < T > causes other issues , and almost no code-first tutorials do this forced initiation . So what 's the best way to handle this situation ? <code> public class Post { public int Id { get ; set ; } public string Text { get ; set ; } public virtual ICollection < PostHistory > PostHistory { get ; set ; } } Post post = new Post { Text = `` Blah '' } ; context.Posts.Add ( post ) ; PostHistory history = new PostHistory { Text = `` Blah '' } ; context.PostHistory.Add ( history ) ; post.PostHistory.Add ( history ) ; | How do I create two associated entities at one time with EF4 Code-First |
C_sharp : When writing preconditions for different functions with similar parameters , I want to group assertions or exceptions into a static method , rather than writing them out explicitly . For example , instead ofI would prefer to writeThis feels more natural and helps cut down the code I need to write ( and might even reduce the number of errors in my assertions ! ) but it seems to go against the idea that preconditions should help document the exact intent of a method.Is this a common anti-pattern or are there any significant reasons not to do this ? Also , would the answer be different if I had used exceptions ? <code> GetFooForUser ( User user ) { assert ( null ! = user ) ; assert ( user.ID > 0 ) ; // db ids always start at 1 assert ( something else that defines a valid user ) ; ... // do some foo work } GetBarForUser ( User user ) { assert ( null ! = user ) ; assert ( user.ID > 0 ) ; // db ids always start at 1 assert ( something else that defines a valid user ) ; ... // do some bar work } GetFooForUser ( User user ) { CheckUserIsValid ( user ) ; // do some foo work } GetBarForUser ( User user ) { CheckUserIsValid ( user ) ; // do some bar work } static CheckUserIsValid ( User user ) { assert ( null ! = user ) ; assert ( user.ID > 0 ) ; // db ids always start at 1 assert ( something else that defines a valid user ) ; ... } | Is grouping preconditions into a method acceptable to stay DRY ? |
C_sharp : In StructureMap we can proxy TInterface and TConcreteImpl with TProxy this this : I wanted to use DispatchProxy ( and globally log before method invocation and after invocation ) and globally register it for all types being instantiated from StructureMap , I 'm wondering how to accomplish this ? More specifically , I want to run the following for all the types being instantiated : I already experimented with IInstancePolicy of StructureMap but no success because Instance is not the actual object instance.Thank you so much <code> ConfigurationExpression config = ... config.For < TInterface > ( ) .DecorateAllWith < TProxy > ( ) ; config.For < TInterface > ( ) .Use < TConcreteImpl > ( ) ; TConcreteImpl instance = ... TInterface proxy = DispatchProxyGenerator.CreateProxyInstance ( typeof ( TInterface ) , typeof ( TProxy ) ) .SetParameters ( instance ) ; public class Policy : IInstancePolicy { public void Apply ( Type pluginType , Instance instance ) { } } | StructureMap proxy all instances or modify instances just before returning |
C_sharp : I need to add the LinkButton btnAddRow in UpdatePanel upSectionB but the problem is I 'm having this error during load : A control with ID 'btnAddRow ' could not be found for the trigger in UpdatePanel 'upSectionB'.My simplified aspx <code> < asp : UpdatePanel ID= '' upSectionB '' runat= '' server '' UpdateMode= '' Conditional '' ChildrenAsTriggers= '' true '' > < ContentTemplate > Request Budget ( USD ) < asp : TextBox ID= '' txtTotal '' runat= '' server '' > < /asp : TextBox > < /ContentTemplate > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' btnAddRow '' EventName= '' Click '' / > //Poses problems when I uncomment the trigger above . btnAddRow is a LinkButton inside upSectionC < /Triggers > < /asp : UpdatePanel > < asp : UpdatePanel ID= '' upSectionC '' runat= '' server '' > < ContentTemplate > < asp : GridView ID= '' gvCostBreakdown '' runat= '' server '' AutoGenerateColumns= '' false '' ShowFooter= '' true '' > < Columns > < asp : TemplateField HeaderText= '' Amount '' > < ItemTemplate > < asp : TextBox ID= '' txtAmount '' runat= '' server '' Text= ' < % # Eval ( `` BudgetUSD '' ) % > ' > < /asp : TextBox > < /ItemTemplate > < FooterTemplate > < asp : TextBox ID= '' txtAmountTotal '' runat= '' server '' Enabled= '' false '' > < /asp : TextBox > < /FooterTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' Delete '' ItemStyle-HorizontalAlign= '' Center '' > < ItemTemplate > < asp : LinkButton ID= '' btnDeleteRow '' runat= '' server '' ToolTip= '' Delete '' OnClick= '' btnDeleteRow_Click '' CommandArgument= ' < % # Eval ( `` Id '' , '' { 0 } '' ) % > ' OnClientClick= '' '' > Delete < /asp : LinkButton > < /ItemTemplate > < FooterTemplate > < asp : LinkButton ID= '' btnAddRow '' runat= '' server '' CausesValidation= '' true '' ValidationGroup= '' vgAddRow '' ToolTip= '' Add Row '' OnClick= '' btnAddRow_Click '' > Add Row < /asp : LinkButton > < /FooterTemplate > < /asp : TemplateField > < /Columns > < /asp : GridView > < /ContentTemplate > < /asp : UpdatePanel > | Update textbox from 1st UpdatePanel using LinkButton from 2nd UpdatePanel 's gridview . Control could not be found |
C_sharp : I have an example that I can get to break every time I use an iterator , but it works fine with a for loop . All code uses variables local to the executing method . I am stumped . There is either a fact about iterators that I am not aware of , or there is an honest to goodness bug in .Net . I 'm betting on the former . Pleae help.This code reliably work every time . It loops through ( let 's say 10 ) all elements one at a time and starts a new thread , passing the integer to the new thread as an argument in a method . It starts 10 threads , one for each item.1,2,3,4,5,6,7,8,9,10 - this always works.WORKING CODE : And this code actually repeat elements . It iterates through ( let 's say 10 ) all elements one at a time and starts a new thread . It starts 10 threads , but it does not reliably get all 10 integers . I am seeing it start 1,2,3,3,6,7,7,8,9,10 . I am losing numbers.BUSTED CODE : <code> //lstDMSID is a populated List < int > with 10 elements.for ( int i=0 ; i < lstDMSID.Count ; i++ ) { int dmsId = lstDMSID [ i ] ; ThreadStart ts = delegate { // Perform some isolated work with the integer DoThreadWork ( dmsId ) ; } ; Thread thr = new Thread ( ts ) ; thr.Name = dmsId.ToString ( ) ; thr.Start ( ) ; } //lstDMSID is a populated List < int > with 10 elements.foreach ( int dmsId in lstDMSID ) { ThreadStart ts = delegate { // Perform some isolated work with the integer DoThreadWork ( dmsId ) ; } ; Thread thr = new Thread ( ts ) ; thr.Name = dmsId.ToString ( ) ; thr.Start ( ) ; } | Why would an iterator ( .Net ) be unreliable in this code |
C_sharp : Can anyone explain why the default Asp.Net Web Application template , with Individual user identification , comes with an error in the Manage Controller ? In this code line ; View is Red , because there is no SendVerificationEmail view . Is this normal ? Can this be resolved ? I could specify a view to route to likebut is that really where the Asp.Net team intended this to go from here ? <code> [ HttpPost ] [ ValidateAntiForgeryToken ] public async Task < IActionResult > SendVerificationEmail ( IndexViewModel model ) { if ( ! ModelState.IsValid ) { return View ( model ) ; } var user = await _userManager.GetUserAsync ( User ) ; if ( user == null ) { throw new ApplicationException ( $ '' Unable to load user with ID ' { _userManager.GetUserId ( User ) } ' . `` ) ; } var code = await _userManager.GenerateEmailConfirmationTokenAsync ( user ) ; var callbackUrl = Url.EmailConfirmationLink ( user.Id , code , Request.Scheme ) ; var email = user.Email ; await _emailSender.SendEmailConfirmationAsync ( email , callbackUrl ) ; StatusMessage = `` Verification email sent . Please check your email . `` ; return RedirectToAction ( nameof ( Index ) ) ; } return View ( model ) ; if ( ! ModelState.IsValid ) { return View ( nameof ( Index ) , model ) ; } | Default Asp.Net Core web template comes with error |
C_sharp : Please I have a string such as this RemoteAuthorizationTestScope|Start : En Attente Validation|:001|:01195|21/01/2015I can extract the string from the | symbol using this codehowever , there are also text such `` Start : En Attente Validation '' in the string that needs to be separated , how do I achieve this so that I can have the string separated in this manner . <code> var userInfo= '' RemoteAuthorizationTestScope|Start : En Attente Validation|:001|:01195|21/01/2015 '' var entries=userInfo.Split ( '| ' ) ; RemoteAuthorizationTestScopeStartEn Attente Validation001 0119521/01/2015 | Need to extract string from a separator in c # |
C_sharp : Is it possible to add the attribute StretchDirection to a VisualBrush ? My VisualBrush contains a media element , and the media element has this attribute , but not the VisualBrush . When I apply the StretchDirection attribute to this MediaElement , it is ignored . I am guessing because VisualBrush is overriding it 's attributes . <code> < VisualBrush x : Key= '' vb_zoneOneAdvertisement '' TileMode= '' None '' Stretch= '' Uniform '' AlignmentX= '' Center '' AlignmentY= '' Center '' > < VisualBrush.Visual > < MediaElement / > < /VisualBrush.Visual > < /VisualBrush > | Can I add StretchDirection to a VisualBrush ? |
C_sharp : I 'm trying to write classes which handle different number types . I know that C # ( and .Net in general , I believe ) has no INumber interface , so I can not use something like the following : That 's okay , though , because I 'd like to avoid the boxing/unboxing of every one of my numbers . I could , however , use conditional compilation for each type I want to support : This means I 'll need to compile a different Library.dll and LibraryF.dll , however . Is there any more elegant solution to this ? Obviously , in my example , I can simply write the code twice . I would like to use this process , however , to create large complicated data structures with an integer version and floating-point version , so do not want the possibility of copy-paste errors when updating my structure . Nor do I want the speed loss from wrapping the floating-point structure in an integral-wrapper , and unnecessarily converting all inputs to the more lenient data type . <code> public class Adder < T > where T : INumber { public T Add ( T a , T b ) { return a + b ; } } # if FLOAT public class AdderF { public float Add ( float a , float b ) # else public class Adder { public int Add ( int a , int b ) # endif { return a + b ; } } | How can I write a single class to compile multiple times with different number types ? |
C_sharp : In my program , you can write a string where you can write variables.For example : The name of my dog is % x % and he has % y % years old.The word where I can replace is any between % % . So I need to get a function where tells which variables I have in that string . <code> GetVariablesNames ( string ) = > result { % x % , % y % } | How to count the number of occurrences of some symbols ? |
C_sharp : I 'm sorry if this is a duplicate but I have n't found anything relevant to it.So , how can I print 0 for the numbers having a whole square root with the following code ? Current O/P : <code> for ( n = 1.0 ; n < = 10 ; n++ ) { Console.WriteLine ( `` Fractional Part : { 0 : # . # # # # } '' , ( Math.Sqrt ( n ) - ( int ) Math.Sqrt ( n ) ) ) ; } | Printing whole numbers with { # } in C # ? |
C_sharp : It appears that default parameters do not work on a readonly struct in c # . Am I misunderstanding something ? Instantiating an instance of this struct using var test = new ReadonlyStruct ( ) ; does not appear to honor the default values . What am I doing wrong ? <code> public readonly struct ReadonlyStruct { public ReadonlyStruct ( int p1 = 1 , byte p2 = 2 , bool p3 = true ) { P1 = p1 ; P2 = p2 ; P3 = p3 ; } public int P1 { get ; } public byte P2 { get ; } public bool P3 { get ; } } | Can you have default parameters on a readonly struct in c # ? |
C_sharp : In this variable , i would like to add some \ before every '.I would like to get that after Replace : Any ideas ? Thanks ! <code> string html = `` < a href=\ '' annee-prochaine.html\ '' > Calendrier de l'annee prochaine < /a > '' html = html.Replace ( `` ' '' , `` \ ' '' ) ; //No changehtml = html.Replace ( `` \ ' '' , `` \ ' '' ) ; //No changehtml = html.Replace ( `` \ ' '' , `` \\ ' '' ) ; //html = > < a href=\ '' annee-prochaine.html\ '' > Calendrier de l\\'annee prochaine < /a > html = html.Replace ( `` \ ' '' , @ '' \ ' '' ) ; //html = > < a href=\ '' annee-prochaine.html\ '' > Calendrier de l\\'annee prochaine < /a > //html = > < a href=\ '' annee-prochaine.html\ '' > Calendrier de l\'annee prochaine < /a > | Replace ' with \ ' in C # |
C_sharp : I have a class called Foo that has a function that looks like the followingBoth Foo and Bar are in a library that I want to reuse in other projects . Now I am working on a new project and I want to subclass Bar . Let 's call it NewBar.What is a simple and flexible way to get Foo.LoadData to return a list of NewBar ? I think that a factory is needed or perhaps just a delegate function . Can anyone provide an example ? Thanks , Andy <code> List < Bar > LoadData ( ) ; | C # Class Factories |
C_sharp : consider the following string as inputI need to remove all instances of substring like reference : url , xcon.xfocus.net/XCon2010_ChenXie_EN.pdf ; but this reference : tag is of variable length . Need to search `` Reference : '' keyword and remove all the text till I reach the character `` ; '' .I 've used Replace function of string class but it replaces only the fixed length substring.desired output is <code> ( msg : '' ACTIVEX Possible Microsoft WMI Administration Tools WEBSingleView.ocx ActiveX Buffer Overflow Attempt Function Call '' ; flow : to_client , established ; file_data ; content : '' ActiveXObject '' ; nocase ; distance:0 ; content : '' WBEM.SingleViewCtrl.1 '' ; nocase ; distance:0 ; pcre : '' /WBEM\x2ESingleViewCtrl\x2E1.+ ( AddContextRef|ReleaseContext ) /smi '' ; reference : url , xcon.xfocus.net/XCon2010_ChenXie_EN.pdf ; reference : url , wooyun.org/bug.php ? action=view & id=1006 ; classtype : attempted-user ; sid:2012157 ; rev:1 ; metadata : affected_product Windows_XP_Vista_7_8_10_Server_32_64_Bit , attack_target Client_Endpoint , deployment Perimeter , tag ActiveX , signature_severity Major , created_at 2011_01_06 , updated_at 2016_07_01 ; ( msg : '' ACTIVEX Possible Microsoft WMI Administration Tools WEBSingleView.ocx ActiveX Buffer Overflow Attempt Function Call '' ; flow : to_client , established ; file_data ; content : '' ActiveXObject '' ; nocase ; distance:0 ; content : '' WBEM.SingleViewCtrl.1 '' ; nocase ; distance:0 ; pcre : '' /WBEM\x2ESingleViewCtrl\x2E1.+ ( AddContextRef|ReleaseContext ) /smi '' ; classtype : attempted-user ; sid:2012157 ; rev:1 ; metadata : affected_product Windows_XP_Vista_7_8_10_Server_32_64_Bit , attack_target Client_Endpoint , deployment Perimeter , tag ActiveX , signature_severity Major , created_at 2011_01_06 , updated_at 2016_07_01 ; | Replace substring of variable length from a text file |
C_sharp : I 've run into a really strange problem when using the default keyword in a DLL project . In my DLL project ( compiled with VS2013 ) I have the following class : Now , if I use this inside the DLL project , it works perfectly . I can create classes that derive from this base class without issue . But , as soon as I try to use the DLL in another project ( compiled with Mono 2.0.0 ) , deriving from the base class with a value type causes a compiler error . This : causes this : Assets/ChildClass.cs ( 8,14 ) : error CS1502 : The best overloaded method match for BaseClass < int > .BaseClass ( int , bool ) ' has some invalid arguments Assets/ChildClass.cs ( 8,14 ) : error CS1503 : Argument # 1 ' can not convertnull ' expression to type ` int'However , the base class with value types can be used in fields without an issue : I looked at the DLL using ILSpy and noticed this : Note that default < T > in the constructor has been replaced with null . This seems to be the cause of the problem , as null would be an invalid value for a value type.So what 's going on here ? EDIT : As discovered in the comments , this does n't occur when the second project is compiled with VS2013 , or with newer versions of Mono . <code> public class BaseClass < T > { public T value ; public bool enabled ; public BaseClass ( T value = default ( T ) , bool enabled = true ) { this.value = value ; this.enabled = enabled ; } } public class ChildClass : BaseClass < int > { } public class OtherClass { public BaseClass < int > baseInt ; } public class BaseClass < T > { public T value ; public bool enabled ; public BaseClass ( T value = null , bool enabled = true ) { this.value = value ; this.enabled = enabled ; } } | Using default keyword in a DLL |
C_sharp : Using WPF and MVVM I 'm trying to display camera images into a Image.Each frame camera got , a callback is called : ViewmodelEach frame , I update the variable _bmpImage : ViewModelIn order to convert the Bitmap to BitmapImage I use a converter : ConverterFinnaly bind to my view : It 's work good the 15 first second , but after this delay : my Image becomes white . In the Converter , image is never null so camera works well . The problem is the component Image stop repainting.When the Image is white , I can resize the window or move it and the image becomes good because Image is repainting.There is something I do wrong ? There are a way to force Image repainting ? Why Image stop repainting ? ThanksEDIT1 : After some verification , when image becomes white , all ui freeze ( so my button are not clickable until I resize or move the window ) EDIT2as Dennis in the comment suggered me , I tryed to do the conversion in my ViewModel : For that , I add a property which represent the converted image : And I converted _bmpImage directly into OnNewFrame : and bind directly the TestImage on my ImageViewAnd with this code I 've the exception : EDIT 3I have considered your remarks and it 's my new code : I 've the same exception on RaisePropertyChanged ( `` TestImage '' ) ; Juste note that Edit2 and Edit3 are a test and does n't answer to the my original questionSorry for the long post <code> public void OnNewFrame ( object sender , EventArgs e ) { Camera camera = sender as MyCamera ; camera.ToBitmap ( out _bmpImage ) ; RaisePropertyChanged ( `` BMPImage '' ) ; } private Bitmap _bmpImage ; public Bitmap BMPImage { get { return _bmpImage ; } private set { _bmpImage = value ; RaisePropertyChanged ( `` BMPImage '' ) ; } } public class ImageToSource : IValueConverter { public object Convert ( object value , Type targetType , object parameter , System.Globalization.CultureInfo culture ) { Image image = value as Image ; if ( image ! = null ) { MemoryStream ms = new MemoryStream ( ) ; image.Save ( ms , ImageFormat.Bmp ) ; ms.Seek ( 0 , SeekOrigin.Begin ) ; BitmapImage bi = new BitmapImage ( ) ; bi.BeginInit ( ) ; bi.StreamSource = ms ; bi.EndInit ( ) ; return bi ; } return null ; } public object ConvertBack ( object value , Type targetType , object parameter , System.Globalization.CultureInfo culture ) { throw new NotImplementedException ( ) ; } } < Image Source= '' { Binding Main.BMPImage , Converter= { StaticResource ImageToSource } } '' > < /Image > private BitmapImage _testImage ; public BitmapImage TestImage { get { return _testImage ; } private set { _testImage = value ; RaisePropertyChanged ( `` TestImage '' ) ; } } public void OnNewFrame ( object sender , EventArgs e ) { Camera camera = sender as MyCamera ; camera.ToBitmap ( out _bmpImage ) ; //RaisePropertyChanged ( `` BMPImage '' ) ; if ( _bmpImage ! = null ) { // Convertion MemoryStream ms = new MemoryStream ( ) ; _bmpImage.Save ( ms , ImageFormat.Bmp ) ; ms.Seek ( 0 , SeekOrigin.Begin ) ; _testImage = new BitmapImage ( ) ; _testImage.BeginInit ( ) ; _testImage.StreamSource = ms ; _testImage.EndInit ( ) ; RaisePropertyChanged ( `` TestImage '' ) ; } } < Image Source= '' { Binding Main.TestImage } '' / > Must create DependencySource on same Thread as the DependencyObject if ( _bmpImage ! = null ) { // Convertion Console.WriteLine ( `` ok '' ) ; MemoryStream ms = new MemoryStream ( ) ; _bmpImage.Save ( ms , ImageFormat.Bmp ) ; ms.Seek ( 0 , SeekOrigin.Begin ) ; _testImage = new BitmapImage ( ) ; _testImage.BeginInit ( ) ; _testImage.StreamSource = ms ; _testImage.EndInit ( ) ; ms.Dispose ( ) ; System.Windows.Application.Current.Dispatcher.BeginInvoke ( ( Action ) ( ( ) = > { RaisePropertyChanged ( `` TestImage '' ) ; } ) ) ; } | WPF image stop repainting |
C_sharp : Lets say i have an array myarr will be of length 13 ( 0-12 Index ) which will also be the length of int [ ] val.I want to check index of myarr where its value is 4 i.e . 1,3,8,11.Then i want One way of doing this is using for loopWe can use Array.indexof but it returns the first index of that value meaning that value has to be unique and my myarr has lots of same values . Can this be done using linq ? <code> byte [ ] myarr = { 1,4,3,4,1,2,1,2,4,3,1,4,2 } ; int [ ] val = new int [ 13 ] ; val [ 1 ] ++ ; val [ 3 ] ++ ; val [ 8 ] ++ ; val [ 11 ] ++ ; for ( int i=0 ; i < myarr.length ; i++ ) { if ( myarr [ i ] == 4 ) val [ i ] ++ ; } | Does LINQ work on Index ? |
C_sharp : Currently I have the following block of Rx/ReactiveUI code : As you can see , it flagrantly violates the DRY principle , but I dont know how I could parameterize away the passing of properties and delegates.What is the usual way of automating the creation of these method chains in Rx/ReactiveUI ? <code> this.WhenAnyValue ( x = > x.Listras ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( im = > GetArray.FromChannels ( im , 0 , 1 ) ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.Grayscale , out _grayscale ) ; this.WhenAnyValue ( x = > x.Grayscale ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( ar = > Gaussian.GaussianConvolution ( ar , 1.5 ) ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.BlurMenor , out _blurMenor ) ; this.WhenAnyValue ( x = > x.BlurMenor ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( ar = > { ConversorImagem.Converter ( ar , out BitmapSource im ) ; return im ; } ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.ImagemBlurMenor , out _imagemBlurMenor ) ; this.WhenAnyValue ( x = > x.BlurMenor ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( ar = > Gaussian.VerticalGaussianConvolution ( ar , 5 ) ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.BlurMaior , out _blurMaior ) ; this.WhenAnyValue ( x = > x.BlurMaior ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( ar = > { ConversorImagem.Converter ( ar , out BitmapSource im ) ; return im ; } ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.ImagemBlurMaior , out _imagemBlurMaior ) ; this.WhenAnyValue ( x = > x.BlurMenor , x = > x.BlurMaior ) .Where ( tuple = > tuple.Item1 ! = null & & tuple.Item2 ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( tuple = > ArrayOperations.Diferença ( tuple.Item1 , tuple.Item2 ) ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.Diferença , out _diferença ) ; this.WhenAnyValue ( x = > x.Diferença ) .Where ( item = > item ! = null ) .Throttle ( TimeSpan.FromMilliseconds ( millis ) ) .ObserveOn ( TaskPoolScheduler.Default ) .Select ( ar = > { ConversorImagem.Converter ( ar , out BitmapSource im ) ; return im ; } ) .ObserveOn ( RxApp.MainThreadScheduler ) .ToProperty ( this , x = > x.ImagemDiferença , out _imagemDiferença ) ; | How to encapsulate the creation of long reactive chains of observables |
C_sharp : Being a computer programming rookie , I was given homework involving the use of the playing card suit symbols . In the course of my research I came across an easy way to retrieve the symbols : gives you ♠ gives you ♥and so on ... However , I still do n't understand what logic C # uses to retrieve those symbols . I mean , the ♠ symbol in the Unicode table is U+2660 , yet I did n't use it . The ASCII table does n't even contain these symbols.So my question is , what is the logic behind ( char ) int ? <code> Console.Write ( ( char ) 6 ) ; Console.Write ( ( char ) 3 ) ; | Where does ( char ) int get its symbols from ? |
C_sharp : I have a block of code where I want to apply the using statement to each command in the commands enumerable . What is the C # syntax for this ? Edit : Rider / ReSharper seems to think these two are equivalent , or at least I get a prompt to convert the for into a foreach ( this is clearly wrong ) : andEdit 2 : After some discussion and a few helpful answers , this is what I 'm going with : <code> await using var transaction = await conn.BeginTransactionAsync ( cancel ) ; IEnumerable < DbCommand > commands = BuildSnowflakeCommands ( conn , tenantId ) ; var commandTasks = new List < Task > ( ) ; foreach ( var command in commands ) { command.CommandTimeout = commandTimeout ; command.Transaction = transaction ; commandTasks.Add ( command.ExecuteNonQueryAsync ( cancel ) ) ; } try { await Task.WhenAll ( commandTasks ) ; } catch ( SnowflakeDbException ) { await transaction.RollbackAsync ( cancel ) ; return ; } await transaction.CommitAsync ( cancel ) ; for ( var i = 0 ; i < commands.Count ; i++ ) { await using var command = commands [ i ] ; command.CommandTimeout = commandTimeout ; command.Transaction = transaction ; commandTasks.Add ( command.ExecuteNonQueryAsync ( cancel ) ) ; } foreach ( var command in commands ) { command.CommandTimeout = commandTimeout ; command.Transaction = transaction ; commandTasks.Add ( command.ExecuteNonQueryAsync ( cancel ) ) ; } var transaction = await conn.BeginTransactionAsync ( cancel ) ; var commands = BuildSnowflakeCommands ( conn , tenantId ) ; var commandTasks = commands.Select ( async command = > { await using ( command ) { command.CommandTimeout = commandTimeout ; command.Transaction = transaction ; await command.ExecuteNonQueryAsync ( cancel ) ; } } ) ; try { await Task.WhenAll ( commandTasks ) ; await transaction.CommitAsync ( cancel ) ; } catch ( SnowflakeDbException ) { await transaction.RollbackAsync ( cancel ) ; } finally { await transaction.DisposeAsync ( ) ; } | Await using on enumerable |
C_sharp : I have a method in a controller : It responds to /Apps/SendNotification/ { guid } ? { SendNotification properties } SendNotification is a model with multiple string properties . My issue is that SendNotification is NEVER null . No matter how I call the action .NET seems to always instantiate an object of SendNotification ( with all fields null ) .I even tested with the System.Web.Http.FromUri and System.Web.Http.FromBody and it still does that . Any ideas ? Note : this is not WebApi . This is regular MVC.My project only have the default route : <code> public ActionResult SendNotification ( Guid ? id=null , SendNotification notification =null ) routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; | Optional Parameter always filled |
C_sharp : The goalGet one of each result returned by a foreach.The scenarioTake a look in the follow Razor 's code fragment : The return to the client is : Xbox 360Xbox 360Xbox 360Xbox 360Playstation 3Playstation 3Playstation 3Now , let me explain : my application compares the price of products in different stores . In my case , there are Xbox 360 in four stores while Playstation 3 exists in three stores — that 's why their names repeat.What I want is simple : get the name of each product just one time to fill a HTML 's table column — can you all understand ? PhilosophyEach product is added on Session . In our case , there are two products on session — the first one is Xbox 360 and the second is Playstation 3 . So , as you can see I can use Session to work with this ( `` for each item on Session , do something ... '' ) , but I think it is n't necessary because invariably I 'll have to run a query on the database and , by logic , its returns me what I need . In other words , I do not need to use the Session except to temporarily store what the users need.SpotlightThe Model.Collection.Products is of type List < Products > .What do I tried ? Something like this : But , of course , unsuccessful . Basically I need something like FirstOfEach ( ) . <code> @ foreach ( var product in Model.Collection.Products ) { < p > @ product.name < /p > } @ foreach ( var product in Model.Collection.Products.FirstOrDefault ( ) ) { [ ... ] } | Get one of each |
C_sharp : Could you please help me understand why variable a is not incremented in the first case but it is in the second case ? Case 1 : Case 2 : I 've gone through other similar questions but could n't find any specifics.UPDATE 1 : How I think the program flowsCase 1 : Case 2 : UPDATE 2 : Thanks to all the answers , i think i 've understood it , please correct me if i 'm wrong.Case 1 : Case 2 : <code> int a = 10 ; a = a++ ; Console.WriteLine ( a ) ; //prints 10 int a = 10 ; int c = a++ ; Console.WriteLine ( a ) ; //prints 11 1 . ' a ' is assigned 102 . ' a ' is assigned 10 before increment happens3 . ' a ' is incremented by 1 ( Why does n't this step affect the final value of ' a ' ? ) 4 . ' a ' is printed -- > 10 1 . ' a ' is assigned 102 . ' c ' is assigned 10 before ' a ' is incremented3 . ' a ' is incremented by 1 ( Why does the increment of ' a ' work here ? ) 4 . ' a ' is printed -- > 11 1 . ` a ` is assigned 102 . Compiler evaluates ` a++ ` , stores old value 10 and new value 11 as well . Since it 's a post increment operation , assigns the old value to ` a ` . What i thought was , compiler would assign the old value 10 first and evaluate the ` ++ ` operation later . This is where i was wrong , compiler evaluates the RHS beforehand and assigns the value based on the operator.4 . ' a ' is printed -- > 10 1 . ` a ` is assigned 102 . Compiler evaluates ` a++ ` , stores old value 10 and new value 11 as well . Since it 's a post increment operation , assigns the old value to ` c ` but value of ` a ` is preserved with ` 11 ` .4 . ' a ' is printed -- > 11 | Unexpected post-increment behavior in assignment |
C_sharp : Why VS complains about this finalizer ? VS 2017 -- 15.3.5Microsoft Code Analysis 2017 -- 2.3.0.62003 <code> using System ; namespace ConsoleApp { class DisposableClass : IDisposable { # if DEBUG ~DisposableClass ( ) // CA1821 Remove empty Finalizers { System.Diagnostics.Debug.Fail ( `` Forgot Dispose ? `` ) ; } # endif public void Dispose ( ) { # if DEBUG GC.SuppressFinalize ( this ) ; # endif } } class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` Hello World ! `` ) ; } } } | CA1821 Remove empty Finalizers |
C_sharp : What is the cause for the second case ? I know I cant cast a boxed enum to int ? directly , but I do a two stage casting , ie Cast < int > .Cast < int ? > which should be working.Edit : This is surprising considering the below works : <code> enum Gender { Male , Female } var k = new [ ] { Gender.Male } .Cast < int > ( ) .ToList ( ) .Cast < int ? > ( ) .ToList ( ) ; //alrightvar p = new [ ] { Gender.Male } .Cast < int > ( ) .Cast < int ? > ( ) .ToList ( ) ; //InvalidCastException object o = Gender.Male ; int i = ( int ) o ; // so here the cast is not to an entirely different type , which works | Cast < int > .Cast < int ? > applied on generic enum collection results in invalid cast exception |
C_sharp : I have downloaded the source code files from here of a magnifier glass effect : http : //www.codeproject.com/Articles/18235/Simple-MagnifierAnd this is the main Form code : Now it will work on two cases : The mouse should be on the Form area on the magnifier glass icon.The mouse button left button should be pressed down nonstop and then dragging the mouse will move the magnifier glass.I want to change it to : Click on a button.After clicked the button you can move the magnifier glass effect anywhere around without pressing down the mouse left button all the time.I tried many different things , but could n't figure out how to do it.How can I do it ? <code> /// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /// Class : MagnifierMainForm/// Purpose : Provide simple magnifier . /// Written by : Ogun TIGLI/// History : 31 May 2006/Wed starting date./// 22 Dec 2006/Fri minor code fixes and hotsot support addition./// 01 Apr 2007/Sun XML serialization support added./// /// Notes : /// This software is provided 'as-is ' , without any express or implied /// warranty . In no event will the author be held liable for any damages /// arising from the use of this software./// /// Permission is granted to anyone to use this software for any purpose , /// including commercial applications , and to alter it and redistribute it /// freely , subject to the following restrictions : /// 1 . The origin of this software must not be misrepresented ; /// you must not claim that you wrote the original software . /// If you use this software in a product , an acknowledgment /// in the product documentation would be appreciated . /// 2 . Altered source versions must be plainly marked as such , and /// must not be misrepresented as being the original software./// 3 . This notice can not be removed , changed or altered from any source /// code distribution./// /// ( c ) 2006-2007 Ogun TIGLI . All rights reserved . /// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Text ; using System.Windows.Forms ; namespace Magnifier20070401 { public partial class MagnifierMainForm : Form { public MagnifierMainForm ( ) { InitializeComponent ( ) ; GetConfiguration ( ) ; // -- - My Init -- - FormBorderStyle = FormBorderStyle.None ; TopMost = true ; StartPosition = FormStartPosition.CenterScreen ; mImageMagnifierMainControlPanel = Properties.Resources.magControlPanel ; if ( mImageMagnifierMainControlPanel == null ) throw new Exception ( `` Resource can not be found ! `` ) ; Width = mImageMagnifierMainControlPanel.Width ; Height = mImageMagnifierMainControlPanel.Height ; HotSpot hsConfiguration = new HotSpot ( new Rectangle ( 50 , 15 , 35 , 30 ) ) ; hsConfiguration.OnMouseDown += new HotSpot.MouseEventDelegate ( hsConfiguration_OnMouseDown ) ; hsConfiguration.OnMouseUp += new HotSpot.MouseEventDelegate ( hsConfiguration_OnMouseUp ) ; hsConfiguration.OnMouseMove += new HotSpot.MouseEventDelegate ( hsConfiguration_OnMouseMove ) ; HotSpot hsMagnfier = new HotSpot ( new Rectangle ( 10 , 15 , 30 , 30 ) ) ; hsMagnfier.OnMouseMove += new HotSpot.MouseEventDelegate ( hsMagnfier_OnMouseMove ) ; hsMagnfier.OnMouseDown += new HotSpot.MouseEventDelegate ( hsMagnfier_OnMouseDown ) ; hsMagnfier.OnMouseUp += new HotSpot.MouseEventDelegate ( hsMagnfier_OnMouseUp ) ; HotSpot hsExit = new HotSpot ( new Rectangle ( 95 , 20 , 15 , 15 ) ) ; hsExit.OnMouseUp += new HotSpot.MouseEventDelegate ( hsExit_OnMouseUp ) ; mHotSpots.Add ( hsConfiguration ) ; mHotSpots.Add ( hsMagnfier ) ; mHotSpots.Add ( hsExit ) ; ShowInTaskbar = false ; } protected override void OnShown ( EventArgs e ) { base.OnShown ( e ) ; if ( mConfiguration.LocationX ! = -1 & & mConfiguration.LocationY ! = -1 ) { Location = new Point ( mConfiguration.LocationX , mConfiguration.LocationY ) ; } } private string mConfigFileName = `` configData.xml '' ; private void GetConfiguration ( ) { try { mConfiguration = ( Configuration ) XmlUtility.Deserialize ( mConfiguration.GetType ( ) , mConfigFileName ) ; } catch { mConfiguration = new Configuration ( ) ; } } private void SaveConfiguration ( ) { try { XmlUtility.Serialize ( mConfiguration , mConfigFileName ) ; } catch ( Exception e ) { Console.WriteLine ( `` Serialization problem : `` + e.Message ) ; } } private void hsConfiguration_OnMouseMove ( Object sender ) { } private void hsConfiguration_OnMouseUp ( Object sender ) { ConfigurationForm configForm = new ConfigurationForm ( mConfiguration ) ; configForm.ShowDialog ( this ) ; } private void hsConfiguration_OnMouseDown ( Object sender ) { } private void hsMagnfier_OnMouseUp ( object sender ) { } private void hsMagnfier_OnMouseDown ( object sender ) { int x = mLastCursorPosition.X ; int y = mLastCursorPosition.Y ; MagnifierForm magnifier = new MagnifierForm ( mConfiguration , mLastCursorPosition ) ; magnifier.Show ( ) ; } private void hsMagnfier_OnMouseMove ( object sender ) { } private void hsExit_OnMouseUp ( Object sender ) { SaveConfiguration ( ) ; Application.Exit ( ) ; } protected override void OnPaint ( PaintEventArgs e ) { Graphics g = e.Graphics ; if ( mImageMagnifierMainControlPanel ! = null ) { g.DrawImage ( mImageMagnifierMainControlPanel , 0 , 0 , Width , Height ) ; } } protected override void OnMouseDown ( MouseEventArgs e ) { int x = e.X ; int y = e.Y ; mPointMouseDown = new Point ( e.X , e.Y ) ; mLastCursorPosition = Cursor.Position ; foreach ( HotSpot hotSpot in mHotSpots ) { // If mouse event handled by this hot-stop then return ! if ( hotSpot.ProcessMouseDown ( e ) ) return ; } } protected override void OnMouseUp ( MouseEventArgs e ) { foreach ( HotSpot hotSpot in mHotSpots ) { // If mouse event handled by this hot-stop then return ! if ( hotSpot.ProcessMouseUp ( e ) ) return ; } } protected override void OnMouseMove ( MouseEventArgs e ) { foreach ( HotSpot hotSpot in mHotSpots ) { // If mouse event handled by this hot-stop then return ! if ( hotSpot.ProcessMouseMove ( e ) ) { Cursor = Cursors.Hand ; return ; } } Cursor = Cursors.SizeAll ; if ( e.Button == MouseButtons.Left ) { int dx = e.X - mPointMouseDown.X ; int dy = e.Y - mPointMouseDown.Y ; Left += dx ; Top += dy ; mConfiguration.LocationX = Left ; mConfiguration.LocationY = Top ; } } private Image mImageMagnifierMainControlPanel = null ; private List < HotSpot > mHotSpots = new List < HotSpot > ( ) ; private Point mPointMouseDown ; private Point mLastCursorPosition ; private Configuration mConfiguration = new Configuration ( ) ; } } | How can I make the effect to be shown only when moving the mouse ? |
C_sharp : To check the validity of a Binary Search Tree , I use a method . But the method always returns false , when tested against a valid Binary Search Tree.Online Demo HereThe code <code> public class Program { public static void Main ( ) { BinarySearchTree < int > tree = new BinarySearchTree < int > ( ) ; tree.Insert ( 2 ) ; tree.Insert ( 1 ) ; tree.Insert ( 3 ) ; Console.WriteLine ( tree.IsValidBinarySearchTreeRecursive ( tree.root ) .ToString ( ) ) ; // this is supposed to return true when tested against the simple tree above } } public class Node < T > where T : IComparable { public Node < T > left ; public Node < T > right ; public T data ; public Node ( T data ) { this.left = null ; this.right = null ; this.data = data ; } } public class BinarySearchTree < T > where T : IComparable { public Node < T > root ; public BinarySearchTree ( ) { this.root = null ; } public bool Insert ( T data ) { Node < T > before = null ; Node < T > after = this.root ; while ( after ! = null ) { before = after ; if ( data.CompareTo ( after.data ) < 0 ) after = after.left ; else if ( data.CompareTo ( after.data ) > 0 ) after = after.right ; else return false ; } Node < T > newNode = new Node < T > ( data ) ; if ( this.root == null ) { this.root = newNode ; } else { if ( data.CompareTo ( before.data ) < 0 ) before.left = newNode ; else before.right = newNode ; } return true ; } private bool _HelperForIsValidBinarySearchTreeRecursive ( Node < T > node , T lower , T upper ) { if ( node == null ) return true ; T val = node.data ; Type nodeType = typeof ( T ) ; if ( nodeType.IsNumeric ( ) ) { if ( val.CompareTo ( lower ) < = 0 ) return false ; if ( val.CompareTo ( upper ) > = 0 ) return false ; } else { if ( lower ! = null & & val.CompareTo ( lower ) < = 0 ) return false ; if ( upper ! = null & & val.CompareTo ( upper ) > = 0 ) return false ; } if ( ! _HelperForIsValidBinarySearchTreeRecursive ( node.right , val , upper ) ) return false ; if ( ! _HelperForIsValidBinarySearchTreeRecursive ( node.left , lower , val ) ) return false ; return true ; } public bool IsValidBinarySearchTreeRecursive ( Node < T > root ) { Type nodeType = typeof ( T ) ; if ( nodeType.IsNumeric ( ) ) return _HelperForIsValidBinarySearchTreeRecursive ( root , root.data , root.data ) ; return _HelperForIsValidBinarySearchTreeRecursive ( root , default ( T ) , default ( T ) ) ; } } public static class StaticUtilities { private static readonly HashSet < Type > NumericTypes = new HashSet < Type > { typeof ( int ) , typeof ( double ) , typeof ( decimal ) , typeof ( long ) , typeof ( short ) , typeof ( sbyte ) , typeof ( byte ) , typeof ( ulong ) , typeof ( ushort ) , typeof ( uint ) , typeof ( float ) } ; public static bool IsNumeric ( this Type myType ) { return NumericTypes.Contains ( Nullable.GetUnderlyingType ( myType ) ? ? myType ) ; } } | Is Valid Generic Binary Search Tree with Recursion |
C_sharp : I am developing an application that using IDocumentClient to perform query to CosmosDB . My GenericRepository support for query by Id and Predicate.I am in trouble when change Database from SqlServer to CosmosDb , in CosmosDb , we have partition key . And I have no idea how to implement repository that support query by partition key without change interface to pass partition key as a argument.My implementationAny help is greatly appreciated , thanks . <code> public interface IRepository < T > { //I can handle this one by adding value of partition key to id and split it by `` : '' Task < T > FindByIdAsync ( string id ) ; // I am stuck here ! ! ! Task < T > FindByPredicateAsync ( Expression < Func < T , bool > > predicate ) ; } public class Repository < T > : IRepository < T > { private readonly IDocumentClient _documentClient ; private readonly string _databaseId ; private readonly string _collectionId ; public Repository ( IDocumentClient documentClient , string databaseId , string collectionId ) { _documentClient = documentClient ; _databaseId = databaseId ; _collectionId = collectionId ; } public async Task < T > FindByIdAsync ( string id ) { var documentUri = UriFactory.CreateDocumentUri ( _databaseId , _collectionId , id ) ; try { var result = await _documentClient.ReadDocumentAsync < TDocument > ( documentUri , new RequestOptions { PartitionKey = ParsePartitionKey ( documentId ) } ) ; return result.Document ; } catch ( DocumentClientException e ) { if ( e.StatusCode == HttpStatusCode.NotFound ) { throw new EntityNotFoundException ( ) ; } throw ; } } public async Task < T > FindByPredicateAsync ( Expression < Func < T , bool > > predicate ) { //Need to query CosmosDb with partition key here ! } private PartitionKey ParsePartitionKey ( string entityId ) = > new PartitionKey ( entityId.Split ( ' : ' ) [ 0 ] ) ; } | Repository that support query by partition key without change interface |
C_sharp : In the constructor of an object , Listener , we take an argument and subscribe to one of its events . If an exception is thrown within the constructor after the event is subscribed the OnSomethingChanged ( ) method is still called when the event is raised - even through the object was not successfully constructed and , as far as I 'm aware , no instance exists.Now I can fix this by obviously re-factoring the design slightly , however I 'm more interested in why an instance method is called even though the constructor did not complete successfully ? If the method uses any local variables that have not been initialised before the exception then obviously it goes BOOM ! <code> class Program { static void Main ( string [ ] args ) { Input input = new Input ( ) ; try { new Listener ( input ) ; } catch ( InvalidOperationException ) { // swallow } input.ChangeSomething ( ) ; // prints `` Something changed ! '' } } public class Listener { public Listener ( Input input ) { input.SomethingChanged += OnSomethingChanged ; // subscibe throw new InvalidOperationException ( ) ; // do not let constructor succeed } void OnSomethingChanged ( object sender , EventArgs e ) { Console.WriteLine ( `` Something changed ! `` ) ; } } public class Input { public event EventHandler SomethingChanged ; public void ChangeSomething ( ) { SomethingChanged ( this , EventArgs.Empty ) ; } } | Local event listener called even though object failed to be constructed |
C_sharp : I have groups of logic that consist of static classes such as : In this case , A and B are static classes that implement the same behavior via a group of functions ( e.g . mutate ) . I would like to use something like an interface for this pattern , however since static classes can not implement interfaces I am not sure what to do . What is the best way to implement this type of behavior cleanly ? EDIT : Here is an example of what I am currently doing . The classes have no state so normally I would make them static . <code> static class A { static int mutate ( int i ) { /**implementation*/ } ; static double prop ( double a , double b ) { /**implementation*/ } ; } static class B { static int mutate ( int i ) { /**implementation*/ } ; static double prop ( double a , double b ) { /**implementation*/ } ; } Interface IMutator { int mutate ( int i ) ; } class A : IMutator { int mutate ( int i ) { /**implementation*/ } ; } class B : IMutator { int mutate ( int i ) { /**implementation*/ } ; } class C { public List < IMutator > Mutators ; public C ( List < IMutator > mutators ) { Mutators = mutators ; } } //Somewhere else ... //The new keyword for A and B is what really bothers me in this case.var Cinstance = new C ( new List < IMutator > ( ) { new A ( ) , new B ( ) /** ... */ } ) ; | grouping static classes with the same behavior |
C_sharp : I 've been working on a calculator using C # and came across an issue I have n't been able to work past.Currently when a user enters a number divided by zero then the answer defaults to 0.00 when instead it should be invalid.I have no idea why and after tinkering with it for awhile I have n't been able to figure it out . Here is the relevant code : Does anyone have any ideas on how I can fix this ? It seems pretty straight forward but I 'm missing something . <code> private void button1_Click ( object sender , EventArgs e ) { double number1 , number2 , ans ; // Identify variables as double to account for decimals . number1 = Convert.ToDouble ( num1.Text ) ; // Convert the contents of the textBox into a double . number2 = Convert.ToDouble ( num2.Text ) ; // ans = 0.0 ; string symbol = modifier1.Text ; if ( symbol == `` / '' & & number2 == 0 ) // This part seems to be broken . answer.Text = `` Invalid input . `` ; else if ( symbol == `` + '' ) ans = number1 + number2 ; else if ( symbol == `` - '' ) ans = number1 - number2 ; else if ( symbol == `` / '' ) ans = number1 / number2 ; else if ( symbol == `` * '' ) ans = number1 * number2 ; else ans = 0 ; answer.Text = ans.ToString ( `` n '' ) ; // Change label value to a number . } | Why is my `` Divide by Zero '' prevention not working ? |
C_sharp : I have application based on this tutorialMethod I use to get user list from service : Service main function : Other classes are inClasses.csMy question is : why I ca n't send anything that is not generic type ? I need to send List < User > or User [ ] but I ca n't even send int [ 2 ] ( sending int or string is possible ) .When I try to send List from service to client , service works but I get exception in client : <code> public class PBMBService : IService { public ServiceResponse UserList ( ) { try { sql.Open ( ) ; List < User > result = new List < User > ( ) ; //filling list from database return new ServiceResponse ( SRFlag.OK , result ) ; } catch ( Exception ex ) { return new ServiceResponse ( SRFlag.EXCEPTION , ex ) ; } } //other methods } class Program { static void Main ( string [ ] args ) { Uri baseAddress = new Uri ( `` http : //localhost:8000/PBMB '' ) ; ServiceHost selfHost = new ServiceHost ( typeof ( PBMBService ) , baseAddress ) ; try { selfHost.AddServiceEndpoint ( typeof ( IService ) , new WSHttpBinding ( ) , `` PBMBService '' ) ; ServiceMetadataBehavior smb = new ServiceMetadataBehavior ( ) ; smb.HttpGetEnabled = true ; selfHost.Description.Behaviors.Add ( smb ) ; selfHost.Open ( ) ; Console.WriteLine ( `` Serwis gotowy . `` ) ; Console.WriteLine ( `` Naciśnij < ENTER > aby zamknąć serwis . `` ) ; Console.WriteLine ( ) ; Console.ReadLine ( ) ; selfHost.Close ( ) ; } catch ( CommunicationException ce ) { Console.WriteLine ( `` Nastąpił wyjątek : { 0 } '' , ce.Message ) ; selfHost.Abort ( ) ; } } } namespace PBMB { public enum SRFlag { OK , EXCEPTION } ; [ DataContract ] public class ServiceResponse { private SRFlag _flag ; private Object _content ; public ServiceResponse ( SRFlag srf , Object c ) { _flag = srf ; _content = c ; } [ DataMember ] public SRFlag Flag { set { _flag = value ; } get { return _flag ; } } [ DataMember ] public Object Content { set { _content = value ; } get { return _content ; } } } [ DataContract ] public class User { [ DataMember ] public string Login { get ; set ; } [ DataMember ] public string FirstName { get ; set ; } [ DataMember ] public string MiddleName { get ; set ; } [ DataMember ] public string LastName { get ; set ; } [ DataMember ] public string Email { get ; set ; } } } An error occurred while receiving the HTTP response to http : //localhost:8000/PBMB/PBMBService . This could be due to the service endpoint binding not using the HTTP protocol . This could also be due to an HTTP request context being aborted by the server ( possibly due to the service shutting down ) . See server logs for more details . | Ca n't send anything that is not generic type |
C_sharp : Basically , I have the following scenario : But , the problem I see here is that I could have done ConcreteFooB : FooBase < ConcreteFooA > { ... } , which would completely mess up the class at runtime ( it would n't meet the logic I 'm trying to achieve ) , but still compile correctly.Is there some way I have n't thought of to enforce the generic , T , to be whatever the derived class is ? Update : I do end up using the generic parameter , T , in the FooBase < T > class , I just did n't list every method that has it as an out and in parameter , but I do have a use for T . <code> public abstract class FooBase < T > where T : FooBase < T > { public bool IsSpecial { get ; private set ; } public static T GetSpecialInstance ( ) { return new T ( ) { IsSpecial = true } ; } } public sealed class ConcreteFooA : FooBase < ConcreteFooA > { ... } public sealed class ConcreteFooB : FooBase < ConcreteFooB > { ... } | Is it possible to programmatically enforce a derived class to pass itself into a base class as the generic type ? |
C_sharp : I 'm making a Rebar wrapper for .NET . Here 's how I 've made my control.I tested my control by adding a REBARBANDINFO into the control and IT WORKED.I wo n't include the implementation of my p/invoke signatures because everything is fine there.The problem starts hereThe control does n't work the way I 've expected , the Rebar cursor is n't respected and Cursor property takes control over the cursor , it even overrides the resize cursor.ExpectationRealityIs that even possible ? Yes , it isCheck out this example of a ListView . It IS possible to make a Control that respects its original cursor messages.How can I make my Rebar decide the mouse cursor instead of Cursor property ? Aditional : I 've done my best to ask a good question . I double-checked the question to ensure it can be understood . <code> public class Rebar : Control { public Rebar ( ) : base ( ) { //Control wo n't even work if I let UserPaint enabled SetStyle ( ControlStyles.UserPaint , false ) ; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ClassName = `` ReBarWindow32 '' ; //REBARCLASSNAME cp.ExStyle |= 0x00000080 ; //WS_EX_TOOLWINDOW //Windows Forms will control the position and size , not the native control cp.Style |= 0x00000004 | 0x00000008 ; //CCS_NORESIZE and CCS_NOPARENTALIGN return cp ; } } } REBARBANDINFO info = new REBARBANDINFO ( ) ; info.cbSize = Marshal.SizeOf ( typeof ( REBARBANDINFO ) ) ; info.fMask = RBBIM_TEXT ; // 0x00000004info.lpText = `` example '' ; SendMessage ( this.Handle , RB_INSERTBANDW , -1 , ref myband ) ; | How can I let .NET wrapper for Rebar decide the mouse cursor ? |
C_sharp : I am relatively new to using TDD and have been reading about mocking objects lately . I have the following test to test a method that given a date returns the next saturday . first off , does this represent good testing practices ? Second , what is the advantage of utilizing a mock framework to create this test ? Let me know if I can offer any more information.Thanks for any thoughts <code> [ TestMethod ( ) ] public void NextSaturdayTest ( ) { DateTime date = new DateTime ( ) ; date = DateTime.Parse ( `` 2010-08-14 '' ) ; DateTime expected = new DateTime ( ) ; expected = DateTime.Parse ( `` 2010-08-21 '' ) ; DateTime actual ; actual = DateExtensions.NextSaturday ( date ) ; Assert.AreEqual ( expected , actual ) ; date = DateTime.Parse ( `` 2010-08-19 '' ) ; expected = DateTime.Parse ( `` 2010-08-21 '' ) ; actual = DateExtensions.NextSaturday ( date ) ; Assert.AreEqual ( expected , actual ) ; } | Should I use mocking for the following example |
C_sharp : I have a simple AngularJS $ http block like so ; My issue is that when my ASP.NET Controller returns a HTTP error code , the JS errorCallback receives an object like ; No matter what I do , I ca n't seem to populate the data property in my callback.If instead my controller returns a HTTP OK code , then the 'success ' callback is invoked , and the return data is available . But not when it 's an error ... help ! The controller function is a WebAPI POST handler and looks like ; The same construct , but with ; Is successfully received in the success callback in the JS . <code> $ http ( req ) .then ( function successCallback ( response ) { alert ( response ) ; } , function errorCallback ( response ) { alert ( response ) ; } ) ; { data : `` '' , status : 304 , config : Object , statusText : `` Not Modified '' } [ System.Web.Http.HttpPost ] public async Task < HttpResponseMessage > Save ( [ FromBody ] object data ) { ... < snip > ... return new HttpResponseMessage { StatusCode = HttpStatusCode.NotModified , Content = new JsonContent ( JObject.FromObject ( new { success = false , message = `` User not authorised to perform this action . '' } ) ) } ; } StatusCode = HttpStatusCode.OK | AngularJS $ http ( ... ) errorHandler receives empty string for data |
C_sharp : If I Invoke a method onto the UI Thread is it searilized by the Windows message queue and subsequently does n't need to be re-entrant ? Clarification : It is only the UI thread that will be accessing _counter . <code> private void CalledFromWorkerThread ( ) { //changed from 'InvokeRequired ' Anti-Pattern this.Invoke ( ( Action ) ( ( ) = > _counter++ ; /* Is this ok ? */ ) ) ; } | Does a method marshalled on the UI Thread need to be thread-safe |
C_sharp : Edit : Please read carefully , I have and issue Loading data for without cartesian production . Deleting data works fine if the references are loaded properly . I 'm trying to delete a large group of entities , However due to a many-to-many assoication OwnerRoles whenever I try to delete them I receive an error : SqlException : The DELETE statement conflicted with the REFERENCE constraint `` FK_OwnerRoles_aspnet_Roles_RoleId '' When I try to avoid cartesian production by loading the aspnet_roles using a select many , The assoicated OwnerRoles is not loaded , so when I attempt to remove all of the references : There is nothing loaded to remove so , I get my referencial constraint when deleting.This is my db structureNotes : I can not use CascadeOnDeleteI 'm using and Edmx with EntityFramework v6.2I 'd prefer to not use save changes multiple times.Everything works fine if I use includes instead of SelectMany , Because include loads the tables connecting However I would like to make seperate queries to avoid Cartesian production , so the result set sent back over the wire is n't so large.How can I Load my data properly to avoid caretesian production , while still being able to delete many to many collections ? I 'm looking for a way to explicitly load the references of a collection table ( e.g there is no Poco class or DB set for that entity ) OR I 'm looking for a way to explicitly delete from EntityFramework ( with out calling a stored procedure because that will circumvent the audit log ) <code> var rolesQuery = context.Organizations .Where ( x = > x.OrganizationId == organizationId ) .SelectMany ( x = > x.aspnet_Roles ) ; var roles = rolesQuery.ToArray ( ) ; rolesQuery.SelectMany ( x = > x.Permissions ) .Load ( ) ; rolesQuery.SelectMany ( x = > x.Organizations ) .Load ( ) ; roles.ForEach ( r = > r.Organizations.ToArray ( ) .ForEach ( o = > r.Organizations.Remove ( o ) ) ) ; context.Permissions.RemoveRange ( roles.SelectMany ( x = > x.Permissions ) ) ; context.aspnet_Roles.RemoveRange ( roles ) ; context.SaveChanges ( ) ; Organizations : * = > * aspnet_Roles ( Many To Many connected by intermediate table **OwnerRoles** ) aspnet_Roles : 1 = > * permissions ( aspnet_Roles has many permissions ) | Entity Framework Reference constraint error on delete when using selectmany |
C_sharp : EDITI took Jon 's comment and retried the whole thing . And indeed , it is blocking the UI thread . I must have messed up my initial test somehow . The string `` OnResume exits '' is written after SomeAsync has finished . If the method is changed to use await Task.WhenAll ( t ) it will ( as expected ) not block . Thanks for the input ! I was first thinking about deleting the question because the initial assumption was just wrong but I think the answers contains valuable information that should not be lost.The original post : Trying to understand the deeper internals of async-await . The example below is from an Android app using Xamarin . OnResume ( ) executes on the UI thread.SomeAsync ( ) starts a new task ( = it spawns a thread ) . Then it is using Task.WaitAll ( ) to perform a blocking wait ( let 's not discuss now if WhenAll ( ) would be a better option ) .I can see that the UI is not getting blocked while Task.WaitAll ( ) is running . So SomeAsync ( ) does not run on the UI thread . This means that a new thread was created.How does the await `` know '' that it has to spawn a thread here - will it always do it ? If I change the WaitAll ( ) to WhenAll ( ) , there would not be a need for an additional thread as fast as I understand . <code> // This runs on the UI thread.async override OnResume ( ) { // What happens here ? Not necessarily a new thread I suppose . But what else ? Console.WriteLine ( `` OnResume is about to call an async method . `` ) ; await SomeAsync ( ) ; // Here we are back on the current sync context , which is the UI thread . SomethingElse ( ) ; Console.WriteLine ( `` OnResume exits '' ) ; } Task < int > SomeAsync ( ) { var t = Task.Factory.StartNew ( ( ) = > { Console.WriteLine ( `` Working really hard ! `` ) ; Thread.Sleep ( 10000 ) ; Console.WriteLine ( `` Done working . `` ) ; } ) ; Task.WhenAll ( t ) ; return Task.FromResult ( 42 ) ; } | How does the runtime know when to spawn a thread when using `` await '' ? |
C_sharp : I tried the following to detach a graph of entity objects , and then attach it to a new context : I have two issues with this approach : After detaching all entity objects , newParent.Children becomes emptyAn InvalidOperationException is raised when re-attaching saying that `` An entity object can not be referenced by multiple instances of IEntityChangeTracker '' .Does anyone know how to properly detach a graph from an ObjectContext , and re-attach it to another one ? UPDATE : Ok good news for me , I figured out how to change the underlying database connection within the same ObjectContext , so I do n't need to detach/attach anymore . If anybody 's interested , here 's how I do it ( here I use SQLite and change the database file ) : I 'll accept Ladislav 's answer as it seems to be correct and answers my question as it was asked . <code> // create a contextvar ctx = new TestEntities ( ) ; var parents = ctx.Parents ; // populate the graphvar newParent = new Parent { Nb = 1 , Title = `` Parent1 '' } ; parents.AddObject ( newParent ) ; newParent.Children.Add ( new Child { Nb = 1 , Title = `` Child1 '' } ) ; // put all entity objects in Unchanged state before detachingctx.SaveChanges ( ) ; // detach all entity objectsforeach ( var objectStateEntry in ctx.ObjectStateManager.GetObjectStateEntries ( ~EntityState.Detached ) ) ctx.Detach ( objectStateEntry.Entity ) ; // create a new contextctx = new TestEntities ( ) ; // attach graphs to new contextforeach ( var p in parents ) ctx.Attach ( p ) ; var sc = ( ( EntityConnection ) ctx.Connection ) .StoreConnection ; sc.ConnectionString = @ '' Data Source= '' + newFile + `` ; '' ; | Can a graph be detached from an ObjectContext and be re-attached to another one ? |
C_sharp : I have seen on various websites how developers version their css/javascripts files by specifying querystrings similar to : How is that done ? Is it a good practice ? I 've been searching around but apparently , I 'm not looking for the right terms . If it matters , I 'm using ASP.NET.Edit : : I just noticed ( via Firebug ) that if I `` version '' my files ( ? v=1 ) they will always be loading and will always override the cache . Is there a way around that ? Thanks in advance . <code> < head > < link rel= '' stylesheet '' href= '' css/style.css ? v=1 '' > < script src= '' js/helper.js ? v=1 '' > < /head > | How to version files in the < HEAD > section ? |
C_sharp : I 'm building a small chat program that consists of a server and client . The server keeps a list of clients that it interacts with.I 've got two worker threads on the server . One handles incoming client connections . The other handles incoming client messages.Now , since both threads interact with a List called 'clients ' , I 've done something like this.Is this a correct use of locks to prevent my List from being altered by two different threads at once ? I have n't had any problems doing this so far , but I just want to make sure it 's correct . <code> // The clients list looks something like this ... List < TcpClient > clients ; // This is running on one thread.ConnectionHandler ( ) { while ( true ) { // Wait for client to connect , etc . etc . // Now , add the client to my clients List . lock ( clients ) clients.Add ( myNewClient ) ; } } // This is running on another thread.ClientHandler ( ) { while ( true ) { lock ( clients ) { /* This will be handling things like incoming messages and clients disconnecting ( clients being removed from the 'clients ' List */ } } } | Is this a correct use of multithreading design ? ( C # ) |
C_sharp : I have a List of Objects and within the Object there is a List of strings . What I want to do is find out how many of each string value there are.So to create a simple example with the languages spoken by people in a team.Create the test data ... To visualise the data : I can get the result I want by finding the distinct string values using SelectMany ( ) .Distinct ( ) then matching within a foreach loop : Output : But there has to be a better way to do this using GroupBy ( ) .I 'm just stuck about how to get the individual distinct values out of the List of languages . <code> public class PeopleLanguages { public string Name ; public List < string > Languages ; } List < PeopleLanguages > peopleLanguages = new List < PeopleLanguages > ( ) ; peopleLanguages.Add ( new PeopleLanguages { Name = `` Rod '' , Languages = new List < string > { `` English '' , `` French '' , `` German '' } } ) ; peopleLanguages.Add ( new PeopleLanguages { Name = `` Jane '' , Languages = new List < string > { `` English '' , `` Spanish '' , `` Greek '' } } ) ; peopleLanguages.Add ( new PeopleLanguages { Name = `` Fredie '' , Languages = new List < string > { `` French '' , `` Arabic '' , `` Italian '' } } ) ; peopleLanguages.Add ( new PeopleLanguages { Name = `` Viktor '' , Languages = new List < string > { `` English '' , `` Krakozhian '' } } ) ; * Rod = > English | French | German * Jane = > English | Spanish | Greek * Fredie = > French | Arabic | Italian * Viktor = > English | Krakozhian foreach ( string language in peopleLanguages.SelectMany ( p = > p.Languages ) .Distinct ( ) ) { Console.WriteLine ( $ '' { language } = { peopleLanguages.Where ( p = > p.Languages.Contains ( language ) ) .Count ( ) } '' ) ; } English = 3French = 2German = 1Spanish = 1Greek = 1Arabic = 1Italian = 1Krakozhian = 1 | c # linq GroupBy on the values of a List within a List |
C_sharp : I have the following script : And I need to return the following XML : The idea is that I will convert the XML into a DataSet with 2 DataTables ( one for Columns and the other for Rows ) . I will use this to populate a DataGridView.However , my problem is that the XML I 'm generating currently is malformed and is n't the same as I 'm expecting.What is the correct syntax to generate the XML as expected ? <code> DECLARE @ columns TABLE ( Caption varchar ( 50 ) , Width int ) ; INSERT INTO @ columns VALUES ( 'Id ' , 0 ) , ( 'Name ' , 100 ) ; DECLARE @ rows TABLE ( Id int , [ Name ] varchar ( 50 ) ) ; INSERT INTO @ rows VALUES ( 1 , 'John ' ) , ( 2 , 'Steve ' ) ; SELECT * , ( SELECT * FROM @ rows FOR XML PATH ( 'Row ' ) , ROOT ( 'Rows ' ) , TYPE , ELEMENTS ) FROM @ columnsFOR XML PATH ( 'Column ' ) , ROOT ( 'Results ' ) , TYPE , ELEMENTS ; < Results > < Columns > < Column > < Caption > Id < /Caption > < Width > 0 < /Width > < /Column > < Column > < Caption > Name < /Caption > < Width > 100 < /Width > < /Column > < /Columns > < Rows > < Row > < Id > 1 < /Id > < Name > John < /Name > < /Row > < Row > < Id > 2 < /Id > < Name > Steve < /Name > < /Row > < /Rows > < /Results > | How to return multiple tables as one XML ? |
C_sharp : Most of the applications consuming my add-in return `` C : \Users\ [ username ] \AppData\Local\Temp\ '' path . But one application is returning `` C : \Users\ [ username ] \AppData\Local\Temp\1affa5dd-2f26-4c96-9965-7a78f5c76321\ '' . The GUID in the end changes every time I launch the application.The application that I am running my add-in from are Revit 2015-2020 . Revit versions 2015-2019 return the correct path . But Revit 2020 is returning the path with GUID appended in the end . The code remains the same.I am expecting the path , '' C : \Users\ [ username ] \AppData\Local\Temp\ '' While I am actually getting path , '' C : \Users\ [ username ] \AppData\Local\Temp\1affa5dd-2f26-4c96-9965-7a78f5c76321\ '' <code> public static string GetLocalFilePath ( string sourceUri , string fileName , string extension ) { string [ ] sasTokenSeparated = sourceUri.Split ( ' ? ' ) ; string [ ] uriParts = sasTokenSeparated [ 0 ] .Split ( '/ ' ) ; string documentId = uriParts [ uriParts.Length - 2 ] ; documentId = documentId.Split ( ' . ' ) [ 0 ] ; string extensionWithDot = string.Empty ; if ( ! extension.StartsWith ( `` . '' ) ) { extensionWithDot = `` . '' + extension ; } else { extensionWithDot = extension ; } string localPath = Path.Combine ( Path.GetTempPath ( ) , documentId , fileName + fileExtension ) ; return localPath ; } | Path.GetTempPath ( ) method returns UserTempPath with GUID in the end when using Revit 2020 |
C_sharp : I basically want two separate overloads for string/FormattableString ( the background is that I want to nudge people towards using string constants for log messages and pass parameters via structured logging instead of the log message to simplify analysis . So the FormattableString logging method would be obsoleted ) . Now due to the way the compiler works , you can not directly overload the methods , because a FormattableString devolves to a string before it 's being passed . What does work though is to have a wrapper struct that defines implicit overloads : So far so good . What I do n't understand : Why does removing the cause the call Log ( $ '' Hello '' ) to become ambiguous ? CS0121 The call is ambiguous between the following methods or properties : Test.Log ( StringIfNotFormattableStringAdapter ) ' and 'Test.Log ( FormattableString ) ' ` <code> public struct StringIfNotFormattableStringAdapter { public string StringValue { get ; } private StringIfNotFormattableStringAdapter ( string s ) { StringValue = s ; } public static implicit operator StringIfNotFormattableStringAdapter ( string s ) { return new StringIfNotFormattableStringAdapter ( s ) ; } public static implicit operator StringIfNotFormattableStringAdapter ( FormattableString fs ) { throw new InvalidOperationException ( `` This only exists to allow correct overload resolution. `` + `` This should never be called since the FormattableString overload should be preferred to this . `` ) ; } } public static class Test { public static void Log ( StringIfNotFormattableStringAdapter msg ) { } public static void Log ( FormattableString msg ) { } public static void Foo ( ) { Log ( `` Hello '' ) ; // resolves to StringIfNotFormattableStringAdapter overload Log ( $ '' Hello '' ) ; // resolves to FormattableString overload } } implicit operator StringIfNotFormattableStringAdapter ( FormattableString fs ) | Overload Resolution with implicit conversions |
C_sharp : I 'm inserting a special ( summary ) row into a DataTable , and I want it to appear last in a sorted DataView . I know the DataView is being sorted ( ascending ) by a particular string column , and for display purposes it does n't matter what value appears in that column of the summary row.What string can I place in that field to make sure my summary row gets sorted to the very end ? For columns of nearly any other datatype , I could use T.MaxValue , but there unfortunately is no System.String.MaxValue constant.I already triedbut that sorted to the top ! ( DataView sorting is lexicographical , not based on numeric value of the codepoint ) <code> footerRow [ colGrouping ] = `` \uFFFF '' ; | Who is the greatest among all strings ? |
C_sharp : In my class I have these setters/getters : DateTime is a non-nullable type . So , when I retrieve my data from my legacy database that I pass to the class constructor , I get an error when the StartDate is null.How should I go about designing around this ? ThanksEric <code> public int Id { get ; set ; } public String ProjectName { get ; set ; } public String ProjectType { get ; set ; } public String Description { get ; set ; } public String Status { get ; set ; } public DateTime StartDate { get ; set ; } | How to design class around null values from database ? |
C_sharp : I 'm currently dealing with 2 systems that expose interop via their own RESTful JSON APIs . One is in C # with JSON.NET and one is Java Spring Boot Starter ( Jackson JSON ) . I have full control over both systems.Both systems need to transfer JSON data with reference handling . Whilst both JSON serialization frameworks support it , C # JSON.NET uses `` $ id '' and `` $ ref '' syntax to signify references whilst Java 's Jackson uses something plainer with only `` id '' .I am much less familiar with Java than I am C # so I would more readily accept and understand any solution on getting JSON ref handling working both ways on the C # side . How can I get these two systems to interop with JSON refs ? C # JSON.NET reference handling documentation.Example JSON coming from Java JacksonNote that it is possible to mark up what class property Jackson uses as the reference . In this case I am using the Id variable as it will always locally unique to the type . <code> { `` Resources '' : [ { `` Id '' : 0 , `` Name '' : `` Resource 0 '' } , { `` Id '' : 1 , `` Name '' : `` Resource 1 '' } ] , `` Tasks '' : [ { `` Id '' : 0 , `` Name '' : `` Task 0 '' , `` Resource '' : 0 } , { `` Id '' : 1 , `` Name '' : `` Task 1 '' , `` Resource '' : 1 } , { `` Id '' : 2 , `` Name '' : `` Task 2 '' , `` Resource '' : 0 } , { `` Id '' : 3 , `` Name '' : `` Task 3 '' , `` Resource '' : 1 } , { `` Id '' : 4 , `` Name '' : `` Task 4 '' , `` Resource '' : 0 } ] } | Dealing with JSON interop between Java and C # REST APIs |
C_sharp : I refer to the Examples in How to : Combin Data with Linq by using joins . We have two Lists the first holds person objects ( First- and Lastname ) . The second List holds Pet objects ( Name ) that holds a person object ( pet owner ) . One Person can own > = 0 pets . What happend now is I performed the group join LinqPad shows me the result : This looks to me like Linq is producing a lot of redundancies ( but I might be wrong here ! ) . The first result object would hold the person object three times . Two questions arises here for me as a Linq nooby ( but maybe I read the output not the right way ) : Are the person objects references ? Unfortunately I couldnt find anything about it.Following the example mentioned above the query continues withIf we have all information about the Person Object in the PetList , why not just query this object ? In my opinion we dont need the pers Object anymore . <code> Dim result1 = From pers in people Group Join pet in pets on pers Equals pet.Owner Into PetList = Group Select pers.FirstName , pers.LastName , PetName = If ( pet is Nothing , String.Empty , pet.Name ) | Does Linq produces redundancies ? |
C_sharp : I have tried two ways but they both didnt work..the first way : :the second way : :is there something wrong i dont see ... my xml file looks like this : :and i used a query string to load the values from a gridView located in another page using `` QueryString '' ... .thanks in advance . <code> string filepath = Server.MapPath [ this is not a link ] ( `` XMLFile2.xml '' ) ; XmlDocument xdoc = new XmlDocument ( ) ; xdoc.Load ( filepath ) ; XmlNode root = xdoc.DocumentElement ; XmlNode idNode = root.SelectSingleNode ( `` /students/student/id '' ) ; if ( idNode.Value == 9.ToString ( ) ) { var nodeOfStudent = xdoc.SelectNodes ( `` /students/student [ @ id= ' 9 ' ] '' ) ; nodeOfStudent [ 1 ] .InnerXml = TextBox_firstname.Text ; nodeOfStudent [ 2 ] .InnerXml = TextBox_lastname.Text ; nodeOfStudent [ 3 ] .InnerXml = TextBox_dob.Text ; nodeOfStudent [ 4 ] .InnerXml = TextBox_class.Text ; nodeOfStudent [ 5 ] .InnerXml = TextBox_section.Text ; nodeOfStudent [ 6 ] .InnerXml = TextBox_telephone.Text ; } string filepath = Server.MapPath ( `` XMLFile2.xml '' ) ; XmlDocument xdoc = new XmlDocument ( ) ; xdoc.Load ( filepath ) ; XmlNode root = xdoc.DocumentElement ; XmlNode idNode = root.SelectSingleNode ( `` /students/student/id '' ) ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /firstname '' ) .InnerXml = TextBox_firstname.Text ; xdoc.DocumentElement.AppendChild ( firstname ) ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /lastname '' ) .InnerXml = TextBox_firstname.Text ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /dob '' ) .InnerXml = TextBox_firstname.Text ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /class '' ) .InnerXml = TextBox_firstname.Text ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /section '' ) .InnerXml = TextBox_firstname.Text ; xdoc.SelectSingleNode ( `` /students/student [ @ id='10 ' ] /telephone '' ) .InnerXml = TextBox_firstname.Text ; xdoc.Save ( filepath ) ; < students > < student > < id > 1 < /id > < first_name > ahmad < /first_name > < last_name > hani < /last_name > < DOB > 12/5/1998 < /DOB > < class > sixth < /class > < section > A < /section > < telephone > 06555632 < /telephone > < /student > < /students > | xml nodes editing based on an xmlElement |
C_sharp : In my application I want to join multiple strings with a dictionary of replacement values . The readTemplateBlock gets fed with FileInfos and returns their contents as string.The getReplacersBlock gets fed ( once ) with a single replacers dictionary.The joinTemplateAndReplacersBlock should join each item of the readTemplateBlock with the one getReplacersBlock result . In my current setup it requires me to post the same replacers dictionary again for each file I post.Is there a better block I 'm missing ? Maybe a configuration option I overlooked ? <code> // Buildvar readTemplateBlock = new TransformBlock < FileInfo , string > ( file = > File.ReadAllText ( file.FullName ) ) ; var getReplacersBlock = new WriteOnceBlock < IDictionary < string , string > > ( null ) ; var joinTemplateAndReplacersBlock = new JoinBlock < string , IDictionary < string , string > > ( ) ; // Assemblevar propagateComplete = new DataflowLinkOptions { PropagateCompletion = true } ; readTemplateBlock.LinkTo ( joinTemplateAndReplacersBlock.Target1 , propagateComplete ) ; getReplacersBlock.LinkTo ( joinTemplateAndReplacersBlock.Target2 , propagateComplete ) ; joinTemplateAndReplacersBlock.LinkTo ( replaceTemplateBlock , propagateComplete ) ; // Postforeach ( var template in templateFilenames ) { getFileBlock.Post ( template ) ; } getFileBlock.Complete ( ) ; getReplacersBlock.Post ( replacers ) ; getReplacersBlock.Complete ( ) ; | A datablock to join a single result with multiple other results |
C_sharp : IntroI am working with a complex external library , where I am attempting to execute it 's functionality on a large list of items . The library does not expose a good async interface , so I 'm stuck with some quite old-fashioned code . My aim is to optimize the time it takes to complete a batch of processing , and to demonstrate the problem without having to include the actual 3rd party library I have created an approximation of the problem belowProblemGiven a non-async action , where you can know the `` size '' ( ie , complexity ) of the action in advance : And given there are 3 variants of this action : How could you optimize a long list of these actions , so that when run in some sort of parallel fashion , the entire batch completes as fast as possible ? Naively , you could just throw the entire lot at a Parallel.ForEach , with a reasonably high Parallelism and that certainly works - but there must be a way to optimally schedule them so some of the biggest are started first.To further illustrate the problem , if we take a super-simplified example1 task of size 105 tasks of size 210 tasks of size 1And 2 available threads . I could come up with 2 ( of many ) ways to schedule these tasks ( The black bar being dead time - nothing to schedule ) : Clearly the first one completes earlier than the second.Minimal Complete & Verifiable CodeEntire test code if anyone fancies a bash ( try to make it faster than my naive implementation below ) : <code> public interface IAction { int Size { get ; } void Execute ( ) ; } public class LongAction : IAction { public int Size = > 10000 ; public void Execute ( ) { Thread.Sleep ( 10000 ) ; } } public class MediumAction : IAction { public int Size = > 1000 ; public void Execute ( ) { Thread.Sleep ( 1000 ) ; } } public class ShortAction : IAction { public int Size = > 100 ; public void Execute ( ) { Thread.Sleep ( 100 ) ; } } class Program { static void Main ( string [ ] args ) { MainAsync ( ) .GetAwaiter ( ) .GetResult ( ) ; Console.ReadLine ( ) ; } static async Task MainAsync ( ) { var list = new List < IAction > ( ) ; for ( var i = 0 ; i < 200 ; i++ ) list.Add ( new LongAction ( ) ) ; for ( var i = 0 ; i < 200 ; i++ ) list.Add ( new MediumAction ( ) ) ; for ( var i = 0 ; i < 200 ; i++ ) list.Add ( new ShortAction ( ) ) ; var swSync = Stopwatch.StartNew ( ) ; Parallel.ForEach ( list , new ParallelOptions { MaxDegreeOfParallelism = 20 } , action = > { Console.WriteLine ( $ '' { DateTime.Now : HH : mm : ss } : Starting action { action.GetType ( ) .Name } on thread { Thread.CurrentThread.ManagedThreadId } '' ) ; var sw = Stopwatch.StartNew ( ) ; action.Execute ( ) ; sw.Stop ( ) ; Console.WriteLine ( $ '' { DateTime.Now : HH : mm : ss } : Finished action { action.GetType ( ) .Name } in { sw.ElapsedMilliseconds } ms on thread { Thread.CurrentThread.ManagedThreadId } '' ) ; } ) ; swSync.Stop ( ) ; Console.WriteLine ( $ '' Done in { swSync.ElapsedMilliseconds } ms '' ) ; } } public interface IAction { int Size { get ; } void Execute ( ) ; } public class LongAction : IAction { public int Size = > 10000 ; public void Execute ( ) { Thread.Sleep ( 10000 ) ; } } public class MediumAction : IAction { public int Size = > 1000 ; public void Execute ( ) { Thread.Sleep ( 1000 ) ; } } public class ShortAction : IAction { public int Size = > 100 ; public void Execute ( ) { Thread.Sleep ( 100 ) ; } } | Time optimization of parallel long-running tasks |
C_sharp : If a dependency container , or data access factory , can return types that may implement IDisposable , should it be the client 's responsibility to check for that and handle it ? In my code below , one data class implements IDisposable and the other does n't . Either can be returned by the data access factory.The reason I ask is that this seems to place a burden on the client code to have to handle this , and how do you let clients know , when building an API , that they may need to call dispose ? Is there a better way to handle this where the client does n't have to check for IDisposable ? In the interest of a full working example , here are the other classes : <code> private static void TestPolymorphismWithDisposable ( ) { // Here we do n't know if we 're getting a type that implements IDisposable , so // if we just do this , then we wo n't be disposing of our instance . DataAccessFactory.Resolve ( ) .Invoke ( ) ; // Do we just have to do something like this ? IFoo foo = DataAccessFactory.Resolve ( ) ; foo.Invoke ( ) ; var fooAsDisposable = foo as IDisposable ; if ( fooAsDisposable ! = null ) { fooAsDisposable.Dispose ( ) ; } } public interface IFoo { void Invoke ( ) ; } public class DataAccessBaseNotDisposable : IFoo { public void Invoke ( ) { Console.WriteLine ( `` In Invoke ( ) in DataAccessBaseNotDisposable . `` ) ; } } public class DataAccessBaseDisposable : IFoo , IDisposable { public void Invoke ( ) { Console.WriteLine ( `` Invoke ( ) in DataAccessBaseDisposable . `` ) ; } public void Dispose ( ) { Console.WriteLine ( `` In Dispose ( ) in DataAccessBaseDisposable . `` ) ; } } public static class DataAccessFactory { public static IFoo Resolve ( ) { return new DataAccessBaseDisposable ( ) ; //return new DataAccessBaseNotDisposable ( ) ; } } | Polymorphism when concrete types *might* be disposable |
C_sharp : I want to declare several constant objects that each have two subobjects , and I 'd like to store these in an enum for organizational purposes.Is it possible to do something like this in C # ? <code> enum Car { carA = { 'ford ' , 'red ' } carB = { 'bmw ' , 'black ' } carC = { 'toyota ' , 'white ' } } | Is it possible to create an enum containg arrays ? |
C_sharp : I 'm trying to estimate the widths in pixel if a text would be rendered in Chrome by using C # for a specific font ( Arial 18px ) in a tool that I 'm creating.Comparing my results with this tool ( uses the browser to render the width ) : http : //searchwilderness.com/tools/pixel-length/ the string : Is calculated to be 439 pixels wide.But with this code in C # I get 445px : Can I modify my code so it renders similar to the browser ? I 've tried to output a label with the font and text and compared with browser rendering they do match ( +/- 1px ) . <code> `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . '' var font = new Font ( `` Arial '' , 18 , FontStyle.Regular , GraphicsUnit.Pixel ) ; var text = `` Lorem ipsum dolor sit amet , consectetur adipiscing elit . `` ; var size = TextRenderer.MeasureText ( text , font , new Size ( int.MaxValue , int.MaxValue ) , TextFormatFlags.NoPadding ) ; | C # : Pixel width matching text rendered in a browser |
C_sharp : Followup to this question : Why is Nullable < T > considered a struct and not a class ? I have two classes that essentially maintain a tuple of some user-supplied value with an internal object.When the type of the user-supplied value is a primitive , I have to wrap it in a Nullable < T > so that it can take on a null value in the Tuple.I 'd prefer it if I could do this with a single class that can take either primitives or classes as a type parameter , but I do n't see any way around it . Not without coming up with some sort of custom Nullable class that can box any type ( not just types where T : struct ) so as to ensure that Value can always be assigned null ; It seems like I should at least be able to define the latter class as But even that fails since Nullable < T > does not meet the : class constraint ( as per the linked question ) . <code> public class BundledClass < T > where T : class { private Tuple < T , object > _bundle ; public T Value { get { return _bundle == null ? null : _bundle.Item1 ; } set { _bundle = new Tuple < T , object > ( value , internalObj ) ; } } // ... public class BundledPrimitive < T > where T : struct { private Tuple < T ? , object > _bundle ; public T ? Value { get { return _bundle == null ? null : _bundle.Item1 ; } set { _bundle = new Tuple < T ? , object > ( value , internalObj ) ; } } // ... public class BundledPrimitive < T > : BundledClass < T ? > { } | Is there any way to combine these almost identical classes into one ? |
C_sharp : This is more of a C # syntax question rather than an actual problem that needs solving . Say I have a method that takes a delegate as parameter . Let 's say I have the following methods defined : Now if I want to call TakeSomeDelegates with FirstAction and SecondFunc as arguments , As far as I can tell , I need to do something like this : But is there a more convenient way to use a method that fits the required delegate signature without writing a lambda ? Ideally something like TakeSomeDelegates ( FirstAction , SecondFunc ) , although obviously that does n't compile . <code> void TakeSomeDelegates ( Action < int > action , Func < float , Foo , Bar , string > func ) { // Do something exciting } void FirstAction ( int arg ) { /* something */ } string SecondFunc ( float one , Foo two , Bar three ) { /* etc */ } TakeSomeDelegates ( x = > FirstAction ( x ) , ( x , y , z ) = > SecondFunc ( x , y , z ) ) ; | Is there any way to use C # methods directly as delegates ? |
C_sharp : My main page sends an API request in async way and then sets the main page to some other other page like this : These are my WebView events : Now the problem is when the page containing WebView is set to main page when app starts it is opening the website fine . But when it is set from another main page then it goes into failure section of Navigated event . I am not seeing any exception in Output Window . <code> async private void GetContacts ( ) { try { activityIndicator.IsVisible = true ; activityIndicator.IsRunning = true ; var contacts = await Plugin.ContactService.CrossContactService.Current.GetContactListAsync ( ) ; var contactsWithPhone = contacts ! = null & & contacts.Count > 0 ? contacts.Where ( c = > c.Number ! = null & & c.Number.Trim ( ) .Length > 0 ) : contacts ; if ( contactsWithPhone.Count ( ) > 0 ) { Application.Current.Properties [ `` FirstTime '' ] = false ; activityIndicator.IsVisible = false ; activityIndicator.IsRunning = false ; List < NewsletterSubscriber > subscribers = new List < NewsletterSubscriber > ( ) ; foreach ( Plugin.ContactService.Shared.Contact contact in contactsWithPhone ) { subscribers.Add ( new NewsletterSubscriber ( ) { Name = contact.Name ! = null & & contact.Name.Trim ( ) .Length > 0 ? contact.Name : `` Unknown '' , Phone = contact.Number } ) ; } SendContacts ( subscribers ) ; } Application.Current.MainPage = new MainPage ( ) ; } catch ( Exception ) { throw ; } } async void SendContacts ( List < NewsletterSubscriber > subscribers ) { var httpClient = new HttpClient ( ) ; NewsletterSubscriberRoot newsletterSubscriberRoot = new NewsletterSubscriberRoot ( ) ; newsletterSubscriberRoot.newsletterSubscribers = subscribers.OrderBy ( c = > c.Name ) .ToList ( ) ; var content = newsletterSubscriberRoot.AsJson ( ) ; try { var result = await httpClient.PostAsync ( url , content ) ; } catch ( Exception ) { throw ; } } private void MainPage_Appearing ( object sender , EventArgs e ) { webView.Navigated += WebView_Navigated ; webView.Navigating += WebView_Navigating ; webView.Source = `` https : //appsoln.com '' ; } private void WebView_Navigating ( object sender , WebNavigatingEventArgs e ) { activityIndicator.IsRunning = true ; activityIndicator.IsVisible = true ; webView.IsVisible = false ; } protected override bool OnBackButtonPressed ( ) { if ( webView.CanGoBack ) { webView.GoBack ( ) ; return true ; } base.OnBackButtonPressed ( ) ; return false ; } private void WebView_Navigated ( object sender , WebNavigatedEventArgs e ) { if ( e.Result == WebNavigationResult.Success ) { activityIndicator.IsRunning = false ; activityIndicator.IsVisible = false ; webView.IsVisible = true ; } else { DisplayAlert ( `` No connection ( ER : CON2 ) '' , `` Please check your Internet Connection . `` , `` OK '' ) ; var closer = DependencyService.Get < ICloseApplication > ( ) ; closer ? .closeApplication ( ) ; } } | Trying to change MainPage but WebView on the new page fails to load site . But it is successful when I set it as the main page when application starts |
C_sharp : I just bumped into a really strange C # behavior , and I ’ d be glad if someone could explain it to me.Say , I have the following class : As I get it , in the line of commentary I have the following objects in my field of view : len variable and call.Inside of lambda , I have local parameter len and Program.len variable.However , after declaring such lambda , I can not use len variable in the scope of Main method anymore . I have to either refer to it as to Program.len either rewrite lambda to be anyOtherNameBesidesLen = > 1.Why is it happening ? Is this correct behavior of language , or I ’ ve encountered a bug in the language ? If this is correct behavior , how is it justified by the language architecture ? Why is it okay for lambda capture variable to mess with code outside lambda ? Edit : Alessandro D'Andria has got quite nice examples ( number 1 and 2 in his comment ) .edit2 : This code ( equal to the one I wrote at the beginning ) is illegal : This code however , despite having exactly the same scope structure , is perfectly legal : <code> class Program { static int len = 1 ; static void Main ( string [ ] args ) { Func < double , double > call = len = > 1 ; len = 1 ; // error : 'len ' conflicts with the declaration 'csutils.Program.len ' Program.len = 1 ; // ok } } class Program { static int len = 0 ; static void Main ( string [ ] args ) { { int len = 1 ; } int x = len ; } } class Other { static int len = 0 ; class Nested { static void foo ( ) { int len = 1 ; } static int x = len ; } } | Lambda capture parameter provoking ambiguity |
C_sharp : Suppose to have a polygon class like this one : To make triangles , squares , hexagons would you rather : Inherit from Polygon your Triangle , Square , etc . class that provides aspecific constructor and generate points programmatically ? Add a CreateSquare static method that returns a ready to use Polygon class ? This : or this : What approach is more correct from the OOP programming point of view ? Please note that there derived classes do n't add anything to original Polygon one.In addition , in the latter case , is there any convenient naming convention ? Is there any additional approach I do n't know about ? Thanks . <code> public class Polygon { Point [ ] _vertices ; public class Polygon ( Point [ ] vertices ) { _vertices = vertices ; } } public class Square : Polygon { public class Polygon ( double size ) { _vertices = new Point [ ] { new Point ( 0,0 ) , new Point ( size,0 ) , new Point ( size , size ) , new Point ( 0 , size ) } ; } } public class Polygon { Point [ ] _vertices ; public class Polygon ( Point [ ] vertices ) { _vertices = vertices ; } public static Polygon CreateSquare ( double size ) { double verts = new Point [ ] { new Point ( 0,0 ) , new Point ( size,0 ) , new Point ( size , size ) , new Point ( 0 , size ) } ; return new Polygon ( verts ) ; } } | OOP object creation guidelines |
C_sharp : I am trying to render a simple view with the TinyWeb framework and Spark view engine.Enviroment is Visual Studio 2011 developer preview & .net 4.5Rendering a template with no model binding works fine.However when I bind a model then it no longer works.I get this error : The name 'Model ' does not exist in the current context.Handler : View : <code> public class IndexHandler { Route route = new Route ( `` / '' ) ; public IResult Get ( ) { var model = new { message = `` Hello World '' } ; return View.Spark ( model , `` Views/base.spark '' ) ; } } < html > < head > < title > This is a test < /title > < /head > < body > < p > $ { Model.message } < /p > < /body > < /html > | Can not render view in TinyWeb framework |
C_sharp : Update : Heinzi is right . AutoCAD Polyline is reference type and not a struct . Good point . But I have simplified the scenario as what I am dealing with in the real application is an AutoCAD object which is struct . So please consider both as struct not reference type.I am looking for the right approach to take in this situation and would appreciate if anyone can shed light or help me to better understanding.There is an interface in the data access layer with two implementations to deal with two different providers : AutoCad and Sketchup APIs . Autocad implementation of GetPoly would return Polyline object as this is what defined in Autocad APIs as polyline , whereas Sketchup would return Face object.I have defined the return type ( and the parameter ) as object to deal with these different types . The cost is performance issue where boxing/unboxing happens . And it shows itself more boldly where the return/parameter is object [ ] . I first wondered making the method return/parameter type generic is the solution but then I think it would n't be as the implementations are type specific . <code> interface IEntity { void object GetPoly ( ) ; void void InsertPoly ( object poly ) ; } class AutocadEntity { void object GetPoly ( ) { //calling Autocad APIs return Autocad Polyline object } void InsertPoly ( object poly ) { ... } } | Using generic in the interface |
C_sharp : I want to store Sub instances in a collection . However , to get it to actually work , I have to declare an interface and store instances of that interface.Is there a more elegant way of doing this ? <code> class B : A { } class Sub < T > where T : A { // ... } var c = new List < Sub < A > > ( ) ; c.Add ( new Sub < B > ( ) ) ; //does n't work interface IBase { void DoStuff ( A a ) ; } var c = new List < IBase > ( ) ; c.Add ( new Sub < B > ( ) ) ; //works | Generics and casting |
C_sharp : I have this problem : I want to generate a new source code file from a object information.I make something like this : dictParamMapping is a Dictionary < string , Type > where the string is a variable name and Type is the type of that variable.I get the type to build new code using : When Type is int , string , datatable etc ... everything works fine but when it is a dictionary , list or any other like that it returns something like : Which is not correct to build that new source code . I would like to get something like Dictionary < int , double > Can any one help me ? <code> dictParamMapping [ pairProcess.Value ] .Type.Name ( or FullName ) System.Collections.Generic.Dictionary ` 2 [ [ System.Int32 , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] , [ System.Double , mscorlib , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] | How to reuse Type returned value to generate new source code |
C_sharp : I 'm currently using Visual Studio ( specifically , 2012 Express ) . I have an interface already defined as follows : If I have an empty class : And I right-click on the IMyInterface , I can select `` Implement Interface '' . When I do this , the auto-generated code produces the following : My question is , is there a way that I could have the following auto-generated : Instead of : ? <code> interface IMyInterface { public String Data { get ; set ; } } class MyClass : IMyInterface { } class MyClass : IMyInterface { public string Data { get { throw new NotImplementedException ( ) ; } set { throw new NotImplementedException ( ) ; } } } public String Data public string Data | How can I prevent the generated implementation of an interface from using a type alias ? |
C_sharp : I 've been working on a project for a client and had a lot of fun integrating SignalR into the system.Everything seems to work really well and the client is really excited about how the SignalR gives true real-time feedback for their application.For the most part everything has gone swimmingly , however I 've come into a strange issue I simply can not pin down.Everything works great for the following locales : en-USen-GBitnlHowever these languages simply never get a callback from the hub : frdeesen-ZW - we use English Zimbabwe to check all the strings are translated.I can step through the code right up until Clients.Client ( ConnectionId ) .update ( Result ) ; ( where ConnectionId is the correct Connection ID , and Result is the object ready to be serialized , with the first four languages this goes flawlessly and I get my Javascript method with the expected output.On the last four languages however , the method is fired , but nothing comes through to the other side . Nothing . Zip.If I replace the Strings.fr.resx file with the default Strings.resx then my site functions as expected , but since the Strings.en-ZW.resx file is identical to Strings.resx ( only each string is wrapped in [ ( ) ] ) I doubt that is the issue . I also tried using the fr locale with all unicode translations ( ` , é , â , etc ) removed , but that did n't help.I 've been going over this for almost a full day now and found nothing that would indicate the issue , and the fact that en works fine and en-ZW does not really confuses me.Anyone have any suggestions ? Hub method : Javascript : <code> public class ClientHub : Hub { [ ... ] protected void UpdateRecords ( List < Int32 > ChangedValues ) { using ( var database = new DbContext ( ) ) { foreach ( Record R in database.Records.Where ( Rc = > ChangedValues.Contains ( Rc.Id ) ) { SignalRFormattedRecord Serialized = new SignalRFormattedRecord ( Record ) ; foreach ( SavedFilter Filter in SavedFilters.ByRecord ( Record ) ) { // Next line is always called . Clients.Client ( Filter.ConnectionId ) .updateRow ( Serialized ) ; } } } } [ ... ] } $ .connection.clientHub.updateRow = function ( value ) { debugger ; // update code works in all languages except FR , DE , ES and en-ZW . } $ .connection.start ( ) ; | SignalR client calls fail for certain languages |
C_sharp : I have a DoDragDrop where I set the data to a Point.when I drag within one instance – everything 's OK . But when I drag between two instances of the program Visual Studio gives me this error : The specified record can not be mapped to a managed value class.Why ? EDIT : here 's the code : And : <code> DataObject d = new DataObject ( ) ; d.SetData ( `` ThePoint '' , MyPoint ) ; DragDropEffects e = DoDragDrop ( d , DragDropEffects.Move ) ; Point e2 = ( Point ) e.Data.GetData ( `` ThePoint '' ) ; | Why ca n't I drag a Point between two instances of a program ? |
C_sharp : First , excuse the rather funny name of my question . I 'm no native speaker and it took me 10 minutes to express my thoughts in these few characters.What I 'm trying to do is to create a dictionary in C # that allows the value to be either an int , a string or a bool . What first had come to my mind was using generics , but as far as I know , I can only define one type as possible value-type , not `` be one of those '' . Using object would also be possible , but boxing seems to be quite a performance-killer.Is there any way to do this ? Here 's a sample of what has come to my mind : My ultimate goal is to provide a library for other developers . This feature should enable them to define `` variables '' during runtime and give them a type.Edit : //Firefox ' about : config page has something very close to what I want to achieve <code> Dictionary < string , ( string , int , bool ) > foo = new Dictionary < string , ( string , int , bool ) > ( ) ; foo.Add ( `` key1 '' , `` Hello , World ! `` ) ; //Correct - Value is a stringfoo.Add ( `` key2 '' , 37 ) ; //Correct - Value is an intfoo.Add ( `` key3 '' , true ) ; //Correct - Value is a booleanfoo.Add ( `` key4 '' , new Foobar ( ) ) ; //Compiler error - Value is a Foobar | Dictionary with limited number of types |
C_sharp : Say , we have 2 classes : Then whyThe same for explicit operator.P.S . : casting each element manually ( separetely ) works <code> public class A { public int a ; } public class B { public int b ; public static implicit operator B ( A x ) { return new B { b = x.a } ; } } A a = new A { a = 0 } ; B b = a ; //OKList < A > listA = new List < A > { new A { a = 0 } } ; List < B > listB = listA.Cast < B > ( ) .ToList ( ) ; //throws InvalidCastException List < B > listB = listA.Select < A , B > ( s = > s ) .ToList ( ) ; //OK | Why Enumerable.Cast does not utilize user-defined casts ? |
C_sharp : ( let 's assume I have 10 cores ) When I write : Questions : What is the formula of assigning amount of numbers to each core ? ( is it 100/10 ? ) At execution point , does each core already know which numbers is is gon na handle ? Or does it consume each time a new number/s from the [ 0..100 ] repository ( let 's ignore chunk or range for now ) ? The i parameter - does it refer to the 0..100 index or is it a relative index in each thread and its `` gon na handle '' numbers ? <code> Parallel.For ( 0 , 100 , ( i , state ) = > { Console.WriteLine ( i ) ; } ) ; | Parallel and work division in c # ? |
C_sharp : Here I have a list from my class AssinantesAnd I needed to group by City , ClientCod and Num , which I 've already done here : Then , I needed to generate an html string with Linq , like the example below : Could somebody give me any sugestion ? <code> new Assinante { City= `` BAURU '' , Num= 112 , ClientCode= 3123 , Phone= `` 1412345675 '' } , new Assinante { City= `` BAURU '' , Num= 45 , ClientCode= 3123 , Phone= `` 214464347 '' } var listGroup= ( from a in lista group a by new { a.City , a.ClientCode , a.Num } ) ; < div > < h2 > Bauru < /h2 > < ul > < li > 3123 < /li > < ul > < li > 112 < /li > < ul > < li > 1412345675 < /li > < /ul > < li > 45 < /li > < ul > < li > 214464347 < /li > < /ul > < /ul > < /ul > < /div > | How do I generate an html string from group by |
C_sharp : I have a problemI have a table with 44839 recordsBut when I try to load my table through EF with this code : I only get 16311 recordsBut when I use this I get all my recordsWhy is this happening ? ? <code> dbContext = new MyDbContext ( `` MyContext '' ) ; dbContext.SalesRegister.Load ( ) ; BindingList < SalesRegister > db =dbContext.SalesRegister.Local.ToBindingList ( ) ; gridControl.DataSource = db ; bsiRecordsCount.Caption = `` RECORDS : `` + db.Count ; dbContext = new MyDbContext ( `` MyContext '' ) ; List < SaleRegister > db = dbContext.SalesRegister.SqlQuery ( `` select * from vwSalesRegister '' ) .ToList ( ) ; gridControl.DataSource = db ; bsiRecordsCount.Caption = `` RECORDS : `` + db.Count ; | Entity Framework Load ( ) method does n't load everything |
C_sharp : FINAL EDITI 've more thoroughly tested the `` feature '' and written a complete article about it : Optional passed by reference parameters with C # for VBA COM APIsAny feedback is welcome.For whatever reason in C # a method ca n't have optional passed by reference ( marked with ref or out ) parameters.But in other infrastructures like VBA , VB6 or COM this is possible.When bridging C # with VBA using COM I 've found a way to overcome the C # limitation by marking the ref parameters as [ Optional ] which is AFAIK what the C # compiler generates at the end of its plumbing.This seems to work like a charm : when calling from VBA to C # I can omit the ref parameters and of course I can read and change them from the .Net/C # side.But as I 've not found any writing about it I 'd like to be sure there is no bad side effects with this `` trick '' .Do you know any ? Can you imagine any ? EDITWith [ DefaultParameterValue ] attribute I may have found a way to have VBA see the default values for the parameter , but only for some types.I 'll do more tests to confirm this is working as expected ... <code> void SomeDotNetCSMethod ( [ Optional ] ref someParameter ) | Possible nasty side effects of tricking .Net to have optional ref parameters for COM |
C_sharp : I have custom class deriving from a library ( Satsuma ) like so : and a Neighbors method in the library that returns List < Node > . I want to be able to do this : But Any sees n as a Node , not DCBaseNode , so it does n't understand .selected.So I tried : ... which gives me this error : Error CS1928 : Type System.Collections.Generic.List < Satsuma.Node > ' does not contain a memberAny ' and the best extension method overload ` System.Linq.Enumerable.Any ( this System.Collections.Generic.IEnumerable , System.Func ) ' has some invalid arguments ... but I 'm not clear on how the arguments are invalid . <code> public class DCBaseNode : Node { public bool selected = false ; } graph.Neighbors ( theNode ) .Any ( n = > n.selected == true ) ; graph.Neighbors ( theNode ) .Any < DCBaseNode > ( n = > n.selected == true ) ; | C # - Error CS1928 : Checking for list element with derived class |
C_sharp : This code works : ... and so does this ( with the same result ) : Is there a reason to prefer one ( First , or Find ) over the other ? UPDATESo , using Reed 's suggestion , all I need is this : ... and it 's safe / it fails gracefully ( or not at all , of course , when provided a proper ID val ) . <code> public SiteMapping GetById ( int ID ) { var entity = siteMappings.First ( p = > p.Id == ID ) ; return entity == null ? null : entity ; } public SiteMapping GetById ( int ID ) { var entity = siteMappings.Find ( p = > p.Id == ID ) ; return entity == null ? null : entity ; } public SiteMapping GetById ( int ID ) { return = siteMappings.FirstOrDefault ( p = > p.Id == ID ) ; } | Is Find preferred over First , or vice versa , in LINQ ? |
C_sharp : We have a web ASP.NET application with target framework 4.5.1 , which references some library built with target framework 2.0 . So , 4.5.1 can use 2.0 , that 's okay.But both app and library uses log4net 1.2.11 and app uses package for 4.0 framework , when library uses package for 2.0 framework.Here how it looks : When I build application , in bin folder I have : app.dll , library.dll and log4net.dll . And log4net here is built targeting 4.0 framework . So here is the question : how library.dll ( built targeting 2.0 ) is using log4net ( built targeting 4.0 ) in this situation ? Is it because runtime is 4.5.1 and targeting frameworks means nothing , all code is executed in 4.5.1 context ? <code> Application [ 4.5.1 ] -- > Library [ 2.0 ] | | V V log4net [ 4.0 ] log4net [ 2.0 ] | How target framework really works ( and why lib for 2.0 can use lib for 4.0 ) ? |
C_sharp : I want to add a form-feed to my panel after each Item that I print so that I can have each Item print on its own page.Is that even possible to do ? For example I can add a line-break to my panel but not sure how to add a form-feed.Example : Any help would be appreciated.Thank you <code> Panel1.Controls.Add ( new LiteralControl ( `` < br / > '' ) ) ; | Is it possible to add a form-feed to an asp.net panel ? |
C_sharp : How can i work with Array in Object ArrayPlease see picture for more info : I use from forech for get Object and then i want to work with Array in Object but it 's not possibleI want to get value from array and work with them for example i want to get `` TestCategory_1 '' or etc but i ca n't now how can i work with value like this ? Kind regards <code> foreach ( object element in result ) | work with array in object array |
C_sharp : I am trying to understand need for static constructors . None of information I found answered following question I have . Why would you do thisas opposed to this ? This is not dupe of other question , this is about static constructors which do n't accept parameters . <code> class SimpleClass { // Static variable that must be initialized at run time . static readonly long baseline ; // Static constructor is called at most one time , before any // instance constructor is invoked or member is accessed . static SimpleClass ( ) { baseline = DateTime.Now.Ticks ; } } class SimpleClass { // Static variable that must be initialized at run time . static readonly long baseline = DateTime.Now.Ticks ; // Static constructor is called at most one time , before any // instance constructor is invoked or member is accessed . //static SimpleClass ( ) // { // } } | Trying to understand static constructors |
C_sharp : I want DateTime in the following format.Output : I want to subtract 4 hours from this time . So I have used this line of code : Now , not only is the wrong time being shown , the above format is also disturbed.Expected Output : <code> DateTime a = Convert.ToDateTime ( DateTime.UtcNow.ToString ( `` s '' ) + `` Z '' ) ; 2018-05-29T09:16:59Z var result = a.AddHours ( -4 ) ; 29-05-2018 10:52:51 2018-05-29T05:16:59Z | DateTime.AddHours gives wrong output and datetime format changes |
C_sharp : So , I know very little about decorators / adorners , but was given a great answer here which uses them.I have tried to implement them , but they ust dont seem to work as they do for the person who gave the answer . I have tried to keep everything as identical as I can.Here is my XAML : Here is the Adorner class : And finally , here is my viewmodel : When I press the button which calls the command , the command runs fine , and the value of ShowLoginTip changes to true . However , it does n't run anything in the decorator etc . <code> < models : TipFocusDecorator x : Name= '' LoginDecorator '' TipText= '' Enter your username and password and click 'Login ' '' IsOpen= '' { Binding ShowLoginTip } '' Grid.Column= '' 1 '' Grid.Row= '' 1 '' > < Image Grid.Column= '' 1 '' Grid.Row= '' 1 '' Source= '' { Binding EnemyImagePath , FallbackValue= { StaticResource DefaultImage } } '' MaxWidth= '' 500 '' MaxHeight= '' 500 '' > < i : Interaction.Triggers > < i : EventTrigger EventName= '' MouseUp '' > < i : InvokeCommandAction Command= '' { Binding EnemyAttack } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /Image > < /models : TipFocusDecorator > public class TipFocusDecorator : Decorator { public bool IsOpen { get { return ( bool ) GetValue ( IsOpenProperty ) ; } set { SetValue ( IsOpenProperty , value ) ; } } // Using a DependencyProperty as the backing store for Open . This enables animation , styling , binding , etc ... public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register ( `` IsOpen '' , typeof ( bool ) , typeof ( TipFocusDecorator ) , new FrameworkPropertyMetadata ( false , FrameworkPropertyMetadataOptions.BindsTwoWayByDefault , IsOpenPropertyChanged ) ) ; public string TipText { get { return ( string ) GetValue ( TipTextProperty ) ; } set { SetValue ( TipTextProperty , value ) ; } } // Using a DependencyProperty as the backing store for TipText . This enables animation , styling , binding , etc ... public static readonly DependencyProperty TipTextProperty = DependencyProperty.Register ( `` TipText '' , typeof ( string ) , typeof ( TipFocusDecorator ) , new UIPropertyMetadata ( string.Empty ) ) ; public bool HasBeenShown { get { return ( bool ) GetValue ( HasBeenShownProperty ) ; } set { SetValue ( HasBeenShownProperty , value ) ; } } // Using a DependencyProperty as the backing store for HasBeenShown . This enables animation , styling , binding , etc ... public static readonly DependencyProperty HasBeenShownProperty = DependencyProperty.Register ( `` HasBeenShown '' , typeof ( bool ) , typeof ( TipFocusDecorator ) , new UIPropertyMetadata ( false ) ) ; private static void IsOpenPropertyChanged ( object sender , DependencyPropertyChangedEventArgs e ) { var decorator = sender as TipFocusDecorator ; if ( ( bool ) e.NewValue ) { if ( ! decorator.HasBeenShown ) decorator.HasBeenShown = true ; decorator.Open ( ) ; } if ( ! ( bool ) e.NewValue ) { decorator.Close ( ) ; } } TipFocusAdorner adorner ; protected void Open ( ) { adorner = new TipFocusAdorner ( this.Child ) ; var adornerLayer = AdornerLayer.GetAdornerLayer ( this.Child ) ; adornerLayer.Add ( adorner ) ; MessageBox.Show ( TipText ) ; // Change for your custom tip Window IsOpen = false ; } protected void Close ( ) { var adornerLayer = AdornerLayer.GetAdornerLayer ( this.Child ) ; adornerLayer.Remove ( adorner ) ; adorner = null ; } } public class TipFocusAdorner : Adorner { public TipFocusAdorner ( UIElement adornedElement ) : base ( adornedElement ) { } protected override void OnRender ( System.Windows.Media.DrawingContext drawingContext ) { base.OnRender ( drawingContext ) ; var root = Window.GetWindow ( this ) ; var adornerLayer = AdornerLayer.GetAdornerLayer ( AdornedElement ) ; var presentationSource = PresentationSource.FromVisual ( adornerLayer ) ; Matrix transformToDevice = presentationSource.CompositionTarget.TransformToDevice ; var sizeInPixels = transformToDevice.Transform ( ( Vector ) adornerLayer.RenderSize ) ; RenderTargetBitmap rtb = new RenderTargetBitmap ( ( int ) ( sizeInPixels.X ) , ( int ) ( sizeInPixels.Y ) , 96 , 96 , PixelFormats.Default ) ; var oldEffect = root.Effect ; root.Effect = new BlurEffect ( ) ; rtb.Render ( root ) ; root.Effect = oldEffect ; drawingContext.DrawImage ( rtb , adornerLayer.TransformToVisual ( AdornedElement ) .TransformBounds ( new Rect ( adornerLayer.RenderSize ) ) ) ; drawingContext.DrawRectangle ( new SolidColorBrush ( Color.FromArgb ( 22 , 0 , 0 , 0 ) ) , null , adornerLayer.TransformToVisual ( AdornedElement ) .TransformBounds ( new Rect ( adornerLayer.RenderSize ) ) ) ; drawingContext.DrawRectangle ( new VisualBrush ( AdornedElement ) { AlignmentX = AlignmentX.Left , TileMode = TileMode.None , Stretch = Stretch.None } , null , AdornedElement.RenderTransform.TransformBounds ( new Rect ( AdornedElement.DesiredSize ) ) ) ; } } private ICommand testDebug ; public ICommand TestDebug { get { if ( testDebug == null ) { testDebug = new RelayCommand ( param = > this.TestDebugEx ( ) , null ) ; } return testDebug ; } } private void TestDebugEx ( ) { ShowLoginTip = true ; OnPropertyChanged ( `` ShowLoginTip '' ) ; } public bool ShowLoginTip = true ; | Why wont my custom decorator / adorner function when bool changes to true ? |
C_sharp : Consider the following code snippet , a traversal of a three dimensional array of singles , in terms of execution efficiency , assuming that process1 ( ) and process2 ( ) take identical lengths of time to execute : Now , it 's known that C # organizes arrays in the .NET framework as row-major structures . Without any optimization I would assume that the first loop will execute much faster than the second one.The question is : Does the CLR 's JIT or the cs.exe/vb.exe compilers detect and optimize loops like this , perhaps reordering the nesting , or should I always be on my guard for potential performance hits , especially in terms of what might happen if I tried to parallelize the loops ? <code> float arr [ mMax , nMax , oMax ] ; for ( m = 0 ; m < mMax ; m++ ) for ( n = 0 ; n < nMax ; n++ ) for ( o = 0 ; o < oMax ; o++ ) { process1 ( arr [ m , n , o ] ) ; } for ( o = 0 ; o < oMax ; o++ ) for ( n = 0 ; n < nMax ; n++ ) for ( m = 0 ; m < mMax ; m++ ) { process2 ( arr [ m , n , o ] ) ; } | .NET Compiler -- Are there nested loop optimizations built-in ? |
C_sharp : I want to underline a word with a round brace . This should be part of a C # Text but if it is easier in CSS , no problem . My problem is that the length of the Word can vary , so the bow must by calculated for each word.My first idea was using CSS box-shadow : CSS : HTML : Unfortunately due to the dynamic Text sizes I ca n't calculate them.Is there a smarter approach to this problem ? <code> # test { font-size : 50px ; background : transparent ; border-radius : 70px ; height : 65px ; width : 90px ; box-shadow : 0px 6px 0px -2px # 00F ; font-family : sans-serif ; } < div id= '' test '' > Hey < /div > | Dynamic text underlined by braces |
C_sharp : Is there a way to change `` ABCDEFGHIJKLMNOP '' to `` ABCD-EFGH-IJKL-MNOP '' using string.format ( ) function or perhaps LINQ ? I am using this statement is there a better and clearer way to accomplish this ? <code> Out= String.Format ( `` { 0 } - { 1 } '' , String.Format ( `` { 0 } - { 1 } - { 2 } '' , In.Substring ( 0 , 4 ) , In.Substring ( 4 , 4 ) , In.Substring ( 8 , 4 ) ) , In.Substring ( 12 , 4 ) ) ; | What is the best way to separate string using string.format ( ) function or LINQ ? |
C_sharp : Dabbling in reactive programming , I often encounter situations where two streams depend on each other . What is an idiomatic way to solve these cases ? A minimal example : There are buttons A and B , both display a value . Clicking on A must increment the value of A by B. Clicking on B must set the value of B to A.First solution I could come up with ( example in F # , but answers in any language are welcome ) : This solution uses mutable state and subjects , it not very readable and does not look idiomatic.The second solution I tried involves creating a method which links two dependent streams together : This seems a bit better , but since there exists no method like dependency in the reactive library , I believe there exist a more idiomatic solution . It is also easy to introduce infinite recursion by using the second approach.What is the recommended way to approach problems involving cycling dependency between streams , such as in the example above , in reactive programming ? <code> let solution1 buttonA buttonB = let mutable lastA = 0 let mutable lastB = 1 let a = new Subject < _ > ( ) let b = new Subject < _ > ( ) ( OnClick buttonA ) .Subscribe ( fun _ - > lastA < - lastA + lastB ; a.OnNext lastA ) ( OnClick buttonB ) .Subscribe ( fun _ - > lastB < - lastA ; b.OnNext lastB ) a.Subscribe ( SetText buttonA ) b.Subscribe ( SetText buttonA ) a.OnNext 0 b.OnNext 1 let dependency ( aGivenB : IObservable < _ > - > IObservable < _ > ) ( bGivenA : IObservable < _ > - > IObservable < _ > ) = let bProxy = new ReplaySubject < _ > ( ) let a = aGivenB bProxy let b = bGivenA a b.Subscribe ( bProxy.OnNext ) a , blet solution2 buttonA buttonB = let aGivenB b = Observable.WithLatestFrom ( OnClick buttonA , b , fun click bValue - > bValue ) .Scan ( fun acc x - > acc + x ) .StartWith ( 0 ) let bGivenA a = Observable.Sample ( a , OnClick buttonB ) .StartWith ( 1 ) let a , b = dependency aGivenB bGivenA a.Subscribe ( SetText buttonA ) b.Subscribe ( SetText buttonB ) | Cycling dependencies between streams in reactive programming |
C_sharp : Today I tested the following code in Visual Studio 2010 ( .NET Framework version 4.0 ) And I was shocked to find these two on the list : System.Collections.Generic.IReadOnlyList ` 1 [ [ System.Int32 , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 System.Collections.Generic.IReadOnlyCollection ` 1 [ [ System.Int32 , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089I have used these two interfaces before in environments with framework 4.5+ installed , and according to the documentation , both of them were created for 4.5 . This does not compile in my environment : The type or namespace name 'IReadOnlyCollection ' does not exist in the namespace 'System.Collections.Generic ' ( are you missing an assembly reference ? ) When I try this : count equals 3 , as expected . What is going on here ? Edit : I do not think framework 4.5 is installed on my machine : Edit 2 : Thanks @ ScottChamberlain , it turns out I did have it installed . <code> Type [ ] interfaces = typeof ( int [ ] ) .GetInterfaces ( ) ; System.Collections.Generic.IReadOnlyList < int > list = new int [ 3 ] ; int [ ] array = new int [ 3 ] ; Type iReadOnlyCollection = Type.GetType ( `` System.Collections.Generic.IReadOnlyCollection ` 1 [ [ System.Int32 , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' ) ; int count = ( int ) iReadOnlyCollection.GetProperty ( `` Count '' ) .GetValue ( array , null ) ; | How can Type int [ ] implement interfaces that do not yet exist ( for me ) ? |
C_sharp : I have an object model that has a property like this : I want the DoSomeWork function to execute automatically after the SomeString property changes . I tried this but it 's not working : What 's the correct syntax ? <code> public class SomeModel { public string SomeString { get ; set ; } public void DoSomeWork ( ) { ... . } } public string SomeString { get ; set { DoSomeWork ( ) ; } } | Setting only a setter property |
C_sharp : There is DataTable with primary key to store information about files . There happen to be 2 files which differ in names with symbols ' 4 ' and ' 4 ' ( 0xff14 , a `` Fullwidth Digit Four '' symbol ) . The DataTable fails to include them both because of failed uniqueness . However , in Windows filesystem they seem to be able to coexist without any issues.The behavior does not seem to depend on locale settings , I changed `` Region & Language- > Formats- > Format '' from English to japanese , also `` language for non-unicode programs '' changes . Locale was printed as `` jp-JP '' , `` en-GB '' . Always same result.Questions : what would be less intrusive way to fix it ? I could switch to using containers instead of System.Data . * but I 'd like to avoid it . Is it possible to define custom comparer for the column or otherwise better check the uniqueness ? Enabling case sensitivity ( which would fix this one ) would cause other issues.is there any chance that some global settings would fix it without rebuilding the software ? The demo program with failure : The exceptionPS : The locale is seen as : <code> using System ; using System.Data ; namespace DataTableUniqueness { class Program { static void Main ( string [ ] args ) { var changes = new DataTable ( `` Rows '' ) ; var column = new DataColumn { DataType = Type.GetType ( `` System.String '' ) , ColumnName = `` File '' } ; changes.Columns.Add ( column ) ; var primKey = new DataColumn [ 1 ] ; primKey [ 0 ] = column ; changes.PrimaryKey = primKey ; changes.Rows.Add ( `` 4.txt '' ) ; try { changes.Rows.Add ( `` 4.txt '' ) ; // throws the exception } catch ( Exception e ) { Console.WriteLine ( `` Exception : { 0 } '' , e ) ; } } } } Exception : System.Data.ConstraintException : Column 'File ' is constrained to be unique . Value ' 4.txt ' is already present . at System.Data.UniqueConstraint.CheckConstraint ( DataRow row , DataRowAction action ) at System.Data.DataTable.RaiseRowChanging ( DataRowChangeEventArgs args , DataRow eRow , DataRowAction eAction , Boolean fireEvent ) at System.Data.DataTable.SetNewRecordWorker ( DataRow row , Int32 proposedRecord , DataRowAction action , Boolean isInMerge , Boolean suppressEnsurePropertyChanged , Int32 position , Boolean fireEvent , Exception & deferredException ) at System.Data.DataTable.InsertRow ( DataRow row , Int64 proposedID , Int32 pos , Boolean fireEvent ) at System.Data.DataRowCollection.Add ( Object [ ] values ) | ' 4 ' and ' 4 ' clash in primary key but not in filesystem |
C_sharp : For example . Lets say we have a stackpanel on a form . Its full of both Grids and Labels . I want to loop through all the Grids and do some operation on them but leave the Lables intact . At the moment I am doing it this way.So i 'm using the fact that `` as '' returns null if it can not cast into the required type . Is this an ok thing to do or is there a better solution to this problem ? <code> foreach ( UIElement element in m_stacker.Children ) { Grid block = element as Grid ; if ( block ! = null ) { //apply changes here } } | Using `` as '' and expecting a null return |
C_sharp : I have a small Dotnet core program ( 3.1.8 ) , with some FileWatchers.They watch folders on a network drive.With some load ( 200 - 250 files maximum here ) , the program crashes unexpectedly.These files come at the same time , moved by another process on another server thanks to a Biztalk app , I do n't think it 's relevant here but I wanted to mention it.The filewatchers initialization : And here we have , the `` process '' part for each event triggered by the filewatcher : I tried to avoid any real process on triggered file system events , so I push the file path in the memoryCache and later I send it to a ServiceBus queue for processing the file by any consumer.All this stuff seem to work pretty fine during all day , no high CPU no high Memory during all day . We 're already logging all the application metrics in ApplicationInsights.It 's a 'real ' crash so we do n't have any logs , only a poor event in the Event Viewer and a dump file.Event viewer : Faultinq module name : coreclr.dll , version : 470020.41105 , time stamp : Ox5f3397ecWe can see , thanks to dotnet-dump , the error catched in the dump file : As you can see , the error seems to happen directly on the FileSystemWatcher , in the Win32 API.I ca n't reproduce it , and it happens only on our Production environment , so no need to tell you I 'm in an `` emergency mode '' .WinDbg is maybe a bit more detailed <code> private void InitializeInnerFilewatcher ( List < string > filters ) { _watcher = new FileSystemWatcher ( WatchPath ) ; _watcher.InternalBufferSize = 65536 ; if ( filters.Count > 1 ) { _watcher.Filter = FILTER_ALL ; // * . * _customFilters = filters ; } else _watcher.Filter = filters.First ( ) ; _watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName ; _watcher.Changed += new FileSystemEventHandler ( FileCreatedOrChanged ) ; _watcher.Created += new FileSystemEventHandler ( FileCreatedOrChanged ) ; _watcher.Renamed += new RenamedEventHandler ( FileRenamed ) ; _watcher.Error += Watcher_Error ; _watcher.EnableRaisingEvents = true ; } private void TryHandle ( FileSystemEventArgs arg ) { if ( ! File.Exists ( arg.FullPath ) ) return ; if ( ! _customFilters.Any ( ) || _customFilters.Any ( x = > PatternMatcher.MatchPattern ( x , arg.Name ) ) ) _memoryCache.AddOrGetExisting ( arg.FullPath , arg , _cacheItemPolicy ) ; } > clrstackOS Thread Id : 0xfd4c ( 27 ) Child SP IP Call Site00000022D55BE150 00007ffccc46789f [ FaultingExceptionFrame : 00000022d55be150 ] 00000022D55BE650 00007FFC6D7A49D4 System.IO.FileSystemWatcher.ParseEventBufferAndNotifyForEach ( Byte [ ] ) [ /_/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @ 249 ] 00000022D55BE6F0 00007FFC6D7A48E6 System.IO.FileSystemWatcher.ReadDirectoryChangesCallback ( UInt32 , UInt32 , System.Threading.NativeOverlapped* ) [ /_/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs @ 242 ] 00000022D55BE750 00007FFC6D6F189C System.Threading.ExecutionContext.RunInternal ( System.Threading.ExecutionContext , System.Threading.ContextCallback , System.Object ) [ /_/src/System.Private.CoreLib/shared/System/Threading/ExecutionContext.cs @ 201 ] 00000022D55BE7C0 00007FFC6D7359B5 System.Threading._IOCompletionCallback.PerformIOCompletionCallback ( UInt32 , UInt32 , System.Threading.NativeOverlapped* ) [ /_/src/System.Private.CoreLib/src/System/Threading/Overlapped.cs @ 59 ] 00000022D55BE8F0 00007ffccc336ba3 [ GCFrame : 00000022d55be8f0 ] 00000022D55BEAB0 00007ffccc336ba3 [ DebuggerU2MCatchHandlerFrame : 00000022d55beab0 ] > peException object : 000001e580001198Exception type : System.ExecutionEngineExceptionMessage : < none > InnerException : < none > StackTrace ( generated ) : < none > StackTraceString : < none > HResult : 80131506 | .NetCore - FileSystemWatcher on a network drive , unsafe code Win32 API crash |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.