text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : Parhaps a silly question ... I 'm new to C # and .Net.In the example for the SafeHandle class ( C # ) on MSDN , the code made me scratch my head a bit.My question is : How does the Win32 HANDLE from the C function CreateFile get into the MySafeFileHandle objects protected IntPtr `` handle '' variable ? The constructor of MySafeFileHandle is private and does n't even take an IntPtr as an argument ! The comment just over the CreateFile statement says something about … the CLR 's platform marshalling layer will store the handle into the SafeHandle object in an atomic fashion.I 'm not sure I know exactly what this means , can anyone explain please ? <code> [ SecurityPermission ( SecurityAction.InheritanceDemand , UnmanagedCode = true ) ] [ SecurityPermission ( SecurityAction.Demand , UnmanagedCode = true ) ] internal class MySafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { private MySafeFileHandle ( ) : base ( true ) { } // other code here } [ SuppressUnmanagedCodeSecurity ( ) ] internal static class NativeMethods { // other code ... // Allocate a file object in the kernel , then return a handle to it . [ DllImport ( `` kernel32 '' , SetLastError = true , CharSet = CharSet.Unicode ) ] internal extern static MySafeFileHandle CreateFile ( String fileName , int dwDesiredAccess , System.IO.FileShare dwShareMode , IntPtr securityAttrs_MustBeZero , System.IO.FileMode dwCreationDisposition , int dwFlagsAndAttributes , IntPtr hTemplateFile_MustBeZero ) ; // other code ... } // Later in the code the handle is created like this : MySafeFileHandle tmpHandle ; tmpHandle = NativeMethods.CreateFile ( fileName , NativeMethods.GENERIC_READ , FileShare.Read , IntPtr.Zero , FileMode.Open , 0 , IntPtr.Zero ) ;
MSDN SafeHandle example
C_sharp : This very simple code does not work the same under Linux as it does on my Windows machine : This should produce an output likeIt works well in development and if published to Windows . If published for Linux it hangs after putting out 'Hello World ' . The await Task.Delay ( ) never returns . I 've tried with a fresh installation of Ubuntu 18 and CentOS 7 . I 've tried with ASP.Net Core 3.0 runtime and 3.1 ( also both fresh installations ) .This code is only for demonstration purposes . Originally , I started to have problems when using a System.Threading.Timer in an ASP.Net BackgroundService ( registered via services.AddHostedService ( ) ) . The timer 's callback there also did n't got called . That also happened only under Linux , whereas Windows works well.Does anyone have an idea how to approach this problem ? UpdateAfter the comment from Herohtar I 've tested on a Windows subsystem Ubuntu . It is working there as well . Now I suspect the Linux image ( s ) of my hoster ( virtual server at Strato.de ) is somehow crippled.Can someone think of a limitation in Linux that could cause such issues ? <code> class Program { async static Task Main ( string [ ] args ) { Console.WriteLine ( `` Hello World ! `` ) ; for ( int i = 0 ; i < 5 ; i++ ) { await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; Console.WriteLine ( `` '' + i ) ; } Console.WriteLine ( `` Bye bye '' ) ; } } Hello World01.. 4Bye bye
Can not await Task.Delay with .Net Core under Linux
C_sharp : I 'm working on an ASP.NET MVC app , designing the domain models , using ( testing ) the new EF Code First feature.I have an Activity entity that may or may not have a Deadline , what is the best way to approach it ? 1 property : or 2 properties : At first I thought of the first option , but then I started thinking that maybe the second option would be better regarding the DB ... Is there any best practice regarding this ? <code> public DateTime ? Deadline { get ; set ; } and check vs null before using public DateTime Deadline { get ; set ; } public bool HasDeadline { get ; set ; }
Whats better design/practice : Nullable property or 1 value property and 1 bool `` has '' property ?
C_sharp : I would like to write my own custom compound statements that have a similar mechanism to using and lock mechanisms where they have code injected at the beginning and end of the statement block before compilation . I have tried searching for questions who may have asked similar questions but I could not properly figure out what this kind of `` code scoping '' is called , other than the documentation saying these are compound statements.Im aware that `` lock '' and `` using '' are keywords . I dont want to have my own keywords as I know this is not possible.Im not sure if this is possible in c # for example : Rather than doing : This could be reduced down to : Ofcourse this does not have to be just a single one line call . The start and ends of encapuslated code could be multiple lines of code thats is inserted by the custom compound statement . <code> StartContext ( 8 ) ; //make method callsEndContext ( ) ; DoSomethingInContext ( 8 ) { //make method calls }
Custom Compound statements in c #
C_sharp : I am using ASP.NET MVC 4 and Entity Framework 6 ( Code First ) and have some strange behaviour I do not want/like : I have an entity class Images which has a boolean property IsDeleted and now I would like to get the first 25 images , which are not deleted , so I used the following code : As this was very slow I investigated a little deeper and found out , that the Where ( i = > ! i.IsDeleted ) already triggers the DB query and all images are loaded ( and parsed = > slow ) and the check then happens `` in code '' . I then tried Where ( i = > i.IsDeleted.Equals ( false ) ) which worked fine and the check happend via SQL.Why ist that so or how can I avoid this problem , as I like the first syntax much better ? Is this maybe a bug uf EF 6 beta or does this happen in al EF versions ? UPDATE : The problem is the cast to IEnumerable < Image > ( I did the Where not in the same line in my code , but changed it here for simplicity ) , but I am using this also to do a .OrderBy ( ... ) .ThenBy ( ... ) using Func < T , TKey > -keys and that does return IOrderedEnumerable and not IOrderedQueryable ... UPDATE 2 : Solved by using Expression < Func < T , TKey > > keys ... <code> IEnumerable < Image > items = db.Images.Where ( i = > ! i.IsDeleted ) .Take ( 25 ) ;
.Where ( i = > ! i.IsDeleted ) does not translate to SQL but .Where ( i = > i.IsDeleted.Equals ( false ) ) does
C_sharp : Using VS2010 and ReSharper 5I have a method which returns a System.ActionReSharper , for some reason , tends to show me a correction that the return type of the method should be mapped to System.Action < T > or one of its variants . It seems that it wo n't recognize the non-generic version ! VS complies and does n't complain about this ! When I mouse over the red curly line , the tooltip shown says Incorrect number of type parameters . Candidates are : void System.Action ( T ) void System.Action ( T1 , T2 ) ... ... and the list continues until T1-T16Any ideas ? <code> private Action ExtractFile ( ) { return delegate { MessageBox.Show ( `` Test '' ) ; } ; }
ReSharper always asks to change System.Action to System.Action < T >
C_sharp : I just saw this in a c # project : I consider myself new to C # ; any one can help what it 's meaning ? <code> public char this [ int index ]
“ Strange ” C # property syntax
C_sharp : Given a simple Hotel entity as an example : Please consider the following code in C # 5.0 : Both calls to Debug.Assert ( ) pass successfully . I do n't understand how after both tasks have completed , the instance of Hotel contains the assignment from both the methods that run in parallel.I thought that when await is called ( in both SetRooms ( ) and SetStars ( ) ) , a `` snapshot '' of the hotel instance is created ( having both NumberOfRooms and StarRating set to 0 ) . So my expectation was that there will be a race condition between the two tasks and the last one to run will be the one copied back to hotel yielding a 0 in one of the two properties.Obviously I am wrong . Can you explain where I 'm misunderstanding how await works ? <code> class Hotel { public int NumberOfRooms { get ; set ; } public int StarRating { get ; set ; } } public void Run ( ) { var hotel = new Hotel ( ) ; var tasks = new List < Task > { SetRooms ( hotel ) , SetStars ( hotel ) } ; Task.WaitAll ( tasks.ToArray ( ) ) ; Debug.Assert ( hotel.NumberOfRooms.Equals ( 200 ) ) ; Debug.Assert ( hotel.StarRating.Equals ( 5 ) ) ; } public async Task SetRooms ( Hotel hotel ) { await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) .ConfigureAwait ( false ) ; hotel.NumberOfRooms = 200 ; } public async Task SetStars ( Hotel hotel ) { await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) .ConfigureAwait ( false ) ; hotel.StarRating = 5 ; }
How does C # Task.WaitAll ( ) combine object states into one ?
C_sharp : I am pulling JSON data from several remote servers concurrently over HTTP , using a WCF service on both the client and server endpoints . I 'm noticing that for each successive request that starts asynchronously the length of time that http request takes is generally increasing , even if the amount of data is not necessarily increasing . In other words if I start 12 thread pool threads ( using Func < > .BeginInvoke ) then each request , after being timed , is showing up in my logs as such : The process is pretty simple . I am simply starting each request in a loop and then calling .WaitAll ( ) on all of the operations before using the consolidated data . It looks like the Http requests are taking way longer than they should even with small amounts of data . In fact the difference between small and large amounts of data appears minimal overall . Would this sort of bottleneck be due to concurrent http requests having to share bandwidth , or is there a threading / context-switching issue possible here ? Just looking to be pointed in the right direction . EDIT -- Just for clarity , I ran the same process synchronously and here are the results : The total time ( because its synchronous ) went up , however you can see clearly that each individual request is generally faster . Unfortunately I dont know of any way to isolate the problem -- but my guess is that its a bandwidth sharing issue between the threads.So I some more straightforward question I have is:1 ) If I use a non-threadpool thread , would this improve2 ) Should I group the operations into only a few threads , rather than each request having its own ? 3 ) Is this a standard problem when trying to concurrently download data over Http ? <code> : HttpRequest invoked . Elapsed : 325ms : HttpRequest invoked . Elapsed : 27437ms : HttpRequest invoked . Elapsed : 28642ms : HttpRequest invoked . Elapsed : 28496ms : HttpRequest invoked . Elapsed : 32544ms : HttpRequest invoked . Elapsed : 38073ms : HttpRequest invoked . Elapsed : 41231ms : HttpRequest invoked . Elapsed : 47914ms : HttpRequest invoked . Elapsed : 45570ms : HttpRequest invoked . Elapsed : 61602ms : HttpRequest invoked . Elapsed : 53567ms : HttpRequest invoked . Elapsed : 79081ms : HttpRequest invoked . Elapsed : 20627ms : HttpRequest invoked . Elapsed : 16288ms : HttpRequest invoked . Elapsed : 2273ms : HttpRequest invoked . Elapsed : 4578ms : HttpRequest invoked . Elapsed : 1920ms : HttpRequest invoked . Elapsed : 564ms : HttpRequest invoked . Elapsed : 1210ms : HttpRequest invoked . Elapsed : 274ms : HttpRequest invoked . Elapsed : 145ms : HttpRequest invoked . Elapsed : 21447ms : HttpRequest invoked . Elapsed : 27001ms : HttpRequest invoked . Elapsed : 1957ms
Concurrently downloading JSON data from remote service ( s )
C_sharp : I 'd like to add parts of the source code to the XML documentation . I could copy & paste source code to some < code > elements , like this : Maintaining this will be painful . Are there other possibilities to add source code to the XML documentation in C # ? I am processing the XML documentation with Sandcastle and would like to make a technical help file ( *.chm ) out of it . I would like to add parts or complete method bodies to the that help file.EDIT : Thanks for the comment from slide_rule . I have added a more realistic and less trivial example : Suppose I have some method like this : It would be nice to have a possibility to add the information how the fee is calculated into the technical help file.The most obvious solution would be write down the algorithm as prosaic text into the comment like : `` If the bill has a total sum less than 5000 then ... '' .Another solution would be to copy & paste the body of the method into the comment field and put it into a < code > element . This method body can be understood quite easily , even without much knowledge about C # -- so there is nothing wrong to put it into a technical help file.Both solutions violate the DRY principle ! I would like to add method bodies or pieces of a method body into the help file , without duplicating information.Is this possible in C # ? ( I think RDoc for Ruby is capable of doing this , but I need some solution in C # ) <code> /// < summary > /// Says hello world in a very basic way : /// < code > /// System.Console.WriteLine ( `` Hello World ! `` ) ; /// System.Console.WriteLine ( `` Press any key to exit . `` ) ; /// System.Console.ReadKey ( ) ; /// < /code > /// < /summary > static void Main ( ) { System.Console.WriteLine ( `` Hello World ! `` ) ; System.Console.WriteLine ( `` Press any key to exit . `` ) ; System.Console.ReadKey ( ) ; } public decimal CalculateFee ( Bill bill ) { if ( bill.TotalSum < 5000 ) return 500 ; else { if ( bill.ContainsSpecialOffer ) return bill.TotalSum * 0.01 ; else return bill.TotalSum * 0.02 ; } }
How to make source code a part of XML documentation and not violate DRY ?
C_sharp : Having just spent over an hour debugging a bug in our code which in the end turned out to be something about the Enumerable.Except method which we did n't know about : or more generally : Looking at the MSDN page : This method returns those elements in first that do not appear in second . It does not also return those elements in second that do not appear in first.I get it that in cases like this : you get the empty array because every element in the first array 'appears ' in the second and therefore should be removed.But why do we only get distinct instances of all other items that do not appear in the second array ? What 's the rationale behind this behaviour ? <code> var ilist = new [ ] { 1 , 1 , 1 , 1 } ; var ilist2 = Enumerable.Empty < int > ( ) ; ilist.Except ( ilist2 ) ; // returns { 1 } as opposed to { 1 , 1 , 1 , 1 } var ilist3 = new [ ] { 1 } ; var ilist4 = new [ ] { 1 , 1 , 2 , 2 , 3 } ; ilist4.Except ( ilist3 ) ; // returns { 2 , 3 } as opposed to { 2 , 2 , 3 } var ilist = new [ ] { 1 , 1 , 1 , 1 } ; var ilist2 = new [ ] { 1 } ; ilist.Except ( ilist2 ) ; // returns an empty array
why does Enumerable.Except returns DISTINCT items ?
C_sharp : Consider the following code : When I cancel the task using the provided CancelSource , output is : OnlyOnCanceledNoneas expected.When LongRunningMethod throws an Exception output is : OnlyOnFaultedNoneas expected.When LongRunningMethod completes output is : Noneso the ContinueWith with TaskContinuationOptions.OnlyOnRanToCompletion is not executed as I would expect.I checked MyTask.Status in the last ContinueWith branch and it is still Running . So with that in mind , I would expect OnlyOnRanToCompletion to be skipped . The question is , why is the Status still Running ? Looking at the debug output , I can see that LongRunningMethod ran to the end . <code> MyTask = LongRunningMethod ( progressReporter , CancelSource.Token ) .ContinueWith ( e = > { Log.Info ( `` OnlyOnCanceled '' ) ; } , default , TaskContinuationOptions.OnlyOnCanceled , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( e = > { Log.Info ( `` OnlyOnFaulted '' ) ; } , default , TaskContinuationOptions.OnlyOnFaulted , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( e = > { Log.Info ( `` OnlyOnRanToCompletion '' ) ; } , default , TaskContinuationOptions.OnlyOnRanToCompletion , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( e = > { Log.Info ( `` None '' ) ; } , default , TaskContinuationOptions.None , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ;
Task.ContinueWith ( ) executing but Task Status is still `` Running ''
C_sharp : I have the following : and I want to use the ! operator as follows : ( it 's an Enum ) I have tried : ... but I receive an error : Parameter type of this unary operator must be the containing typeAny ideas ? <code> MovingDirection.UP ; ! MovingDirection.Up ; // will give MovingDirection.Down public static MovingDirection operator ! ( MovingDirection f ) { return MovingDirection.DOWN ; }
Is there a way to implement unary operators for enum types ?
C_sharp : Possible Duplicate : How do I Unregister 'anonymous ' event handler I have code like this : How do I now disconnect the Format event ? <code> Binding bndTitle = this.DataBindings.Add ( `` Text '' , obj , `` Title '' ) ; bndTitle.Format += ( sender , e ) = > { e.Value = `` asdf '' + e.Value ; } ;
How to disconnect an anonymous event ?
C_sharp : Updated : See end of question for how I implemented the solution.Sorry for the poorly-worded question , but I was n't sure how best to ask it . I 'm not sure how to design a solution that can be re-used where most of the code is the exact same each time it is implemented , but part of the implementation will change every time , but follow similar patterns . I 'm trying to avoid copying and pasting code.We have an internal data messaging system for updating tables across databases on different machines . We 're expanding our messaging service to send data to external vendors and I want to code a simple solution that can be re-used should we decide to send data to more than one vendor . The code will be compiled into an EXE and run on a regular basis to send messages to the vendor 's data service.Here 's a rough outline of what the code does : I want to write this code in such a way that I can re-use the parts that do n't change without having to resort to copying and pasting and filling in the code for SendMessagesToVendor ( ) . I want a developer to be able to use an OutboxManager and have all of the database code written already written , but be forced to supply their own implementation of sending data to the vendor.I 'm sure there are good object-oriented principles that can help me solve that problem , but I 'm not sure which one ( s ) would be best to use.This is the solution I ended up going with , inspired by Victor 's answer and Reed 's answer ( and comments ) to use an interface model . All of the same methods are there , but now they are tucked away into interfaces that the consumer can update if necessary.I did n't realize the power of the interface implementation until I realized that I allow the consumer of the class to plug in their own classes for the data access ( IOutboxMgrDataProvider ) and error logging ( IErrorLogger ) . While I still provide default implementations since I do n't expect this code to change , it 's still possible for the consumer to override them with their own code . Except for writing out multiple constructors ( which I may change to named and optional parameters ) , it really did n't take a lot of time to change my implementation . <code> public class OutboxManager { private List < OutboxMsg > _OutboxMsgs ; public void DistributeOutboxMessages ( ) { try { RetrieveMessages ( ) ; SendMessagesToVendor ( ) ; MarkMessagesAsProcessed ( ) ; } catch Exception ex { LogErrorMessageInDb ( ex ) ; } } private void RetrieveMessages ( ) { //retrieve messages from the database ; poplate _OutboxMsgs . //This code stays the same in each implementation . } private void SendMessagesToVendor ( ) // < == THIS CODE CHANGES EACH IMPLEMENTATION { //vendor-specific code goes here . //This code is specific to each implementation . } private void MarkMessagesAsProcessed ( ) { //If SendMessageToVendor ( ) worked , run this method to update this db . //This code stays the same in each implementation . } private void LogErrorMessageInDb ( Exception ex ) { //This code writes an error message to the database //This code stays the same in each implementation . } } public class OutboxManager { private IEnumerable < OutboxMsg > _OutboxMsgs ; private IOutboxMgrDataProvider _OutboxMgrDataProvider ; private IVendorMessenger _VendorMessenger ; private IErrorLogger _ErrorLogger ; //This is the default constructor , forcing the consumer to provide //the implementation of IVendorMessenger . public OutboxManager ( IVendorMessenger messenger ) { _VendorMessenger = messenger ; _OutboxMgrDataProvider = new DefaultOutboxMgrDataProvider ( ) ; _ErrorLogger = new DefaultErrorLogger ( ) ; } // ... Other constructors here that have parameters for DataProvider // and ErrorLogger . public void DistributeOutboxMessages ( ) { try { _OutboxMsgs = _OutboxMgrDataProvider.RetrieveMessages ( ) ; foreach om in _OutboxMsgs { if ( _VendorMessenger.SendMessageToVendor ( om ) ) _OutboxMgrDataProvider.MarkMessageAsProcessed ( om ) } } catch Exception ex { _ErrorLogger.LogErrorMessage ( ex ) } } } // ... interface code : IVendorMessenger , IOutboxMgrDataProvider , IErrorLogger// ... default implementations : DefaultOutboxMgrDataProvider ( ) , // DefaultErrorLogger ( )
How should I model my code to maximize code re-use in this specific situation ?
C_sharp : After C # 5 introduced the async and await model for asynchronous programming , the C # community arrived at a naming convention to add an `` Async '' suffix to methods returning an awaitable type , like this : Many static code analyzers ( both Roslyn-based and non-Roslyn-based ) have since been written to depend on this naming convention when detecting code smell around asynchronous programming.Now that C # 8 has introduced the concept of asynchronous enumerables , which themselves are not awaitable but can be used in conjunction with await foreach , there seems to be two options for naming methods returning IAsyncEnumerable : orHas there been a definitive naming convention guideline ( from the C # language team , the .NET Foundation , or other authorities ) regarding the options above , like how the C # 5 naming convention was unambiguously standardized and not left to opinion-based judgement of programmers ? <code> interface Foo { Task BarAsync ( ) ; } interface Foo { // No `` Async '' suffix , indicating that the return value is not awaitable . IAsyncEnumerable < T > Bar < T > ( ) ; } interface Foo { // With `` Async '' suffix , indicating that the overall logic is asynchronous . IAsyncEnumerable < T > BarAsync < T > ( ) ; }
Is there a definitive naming convention for methods returning IAsyncEnumerable ?
C_sharp : I have created a Visual Studio Add-In that adds a form to an existing Project in the opened solution.This is how I create the form : After that I can successfully get the reference to the ProjectItem of the added form , then I can get a reference to the System.Windows.Forms.Form , and through this reference I can add a button to the form like this : And then the button is successfully added to the form : However , when I try to save this form , it just won ’ t save . I click Visual Studio ’ s [ save ] button , it just doesn ’ t turn gray . Even if I click [ Save All ] , the form won ’ t be saved . Then I close Visual Studio , reopen it , and open the project to which I have added the new form with my Add-In , and the new button simply isn ’ t there . Just an empty form.I ’ ve even tried saving the project and the solution programmatically through the following code : I ’ ve thought that this would be because the instance of the Visual Studio that I was using to test my Add-In is a debug one , opened right after I run my Add-In . But I ’ ve tried using the installed Add-In ( which remained automatically after running it ) , and the problem persisted.UpdateI ’ ve just noticed two things:1 ) the button only appears on the design of the form , and nowhere else . And it doesn ’ t even let me select it to see it ’ s attributes.It ’ s name doesn ’ t appear in Intellisense , in the object list , or even on the design document of the form.As a test , I ’ ve added a button manually , and this one I can select , and interact with it : What I could get from that is that I am not adding the button properly . Then the new question regarding the button would be : How can I add a new button to a form created through EnvDTE in a way that I can interact with it in design time ? 2 ) While trying to see the differences from my funky button and my Manually added button , I ’ ve attempted something I hadn ’ t before with a programmatically created form : instantiate and run it . And here 's how I 've done it : It flashes on the screen ( apparently with none of my two buttons ) , and the execution ends . Even if I try to do something on it ’ s Form_load , it ’ s executed , then the form flashes , and the execution is ended ( the form is closed and debugging is over ) , as if I had called the Close ( ) method.Then the additional question would be : Did I skip a step while adding the form , or am I not creating it properly at all ? <code> string templatePath = sol.GetProjectItemTemplate ( `` Form.zip '' , `` csproj '' ) ; //sol is an EnvDTE80.Solution2proj.ProjectItems.AddFromTemplate ( templatePath , formName ) ; //proj is an EnvDTE.Project Button btn = new Button ( ) ; btn.Text = `` my funky button '' ; btn.Name = `` newButton '' ; btn.Size = new Size ( 150 , 23 ) ; btn.Location = new Point ( 30 , 30 ) ; frmNewForm.Controls.Add ( btn ) ; //frmNewForm is a System.Windows.Forms.Form itemForm.Save ( itemForm.Name ) ; //itemFrom is an EnvDTE.ProjectItemproj.Save ( proj.FullName ) ; //proj is an EnvDTE.Project MyFunkyForm frm = new MyFunkyForm ( ) ; frm.Show ( ) ;
Form wo n't save after creating it with EnvDTE
C_sharp : OK , that title is a little unclear , but I ca n't think of a better way of putting it , other than explaining it ... Say I have a class Animal , with a static , generic method : And I have subclasses Dog , Cat , Hamster etc . In order to get a Dog , I can write : orwhich is really the same thing . But it seems kinda silly to have to write Dog so many times , since I 'm already invoking the static method through the Dog subclass . Can you think of any clever way of writing a Create ( ) method in the base class so that I could invokewithout writing a Create ( ) method in each of the subclasses ? <code> public static T Create < T > ( ) where T : Animal { // stuff to create , initialize and return an animal of type T } Dog d = Animal.Create < Dog > ( ) ; Dog d = Dog.Create < Dog > ( ) ; Dog d = Dog.Create ( ) ; Cat c = Cat.Create ( ) ; Hamster h = Hamster.Create ( ) ;
Is it possible to detect class context in an inherited static method ?
C_sharp : I have some configuration data that I 'd like to model in code as so : With this configuration set , I then need to do lookups on bazillion ( give or take ) { Key1 , Key2 , Key3 } tuples to get the `` effective '' value . The effective value to use is based on a Key/Priority sum whereby in this example : So a specifc query which has a config entry on Key1=null , Key2=match , and Key3=match beats out one that has Key1=match , Key2=null , and Key3=null since Key2+Key3 priority > Key1 priority ... That make sense ? ! Is there an easy way to model this data structure and lookup algorithm that is generic in that the # and types of keys is variable , and the `` truth table '' ( the ordering of the lookups ) can be defined dynamically ? The types being generics instead of ints would be perfect ( floats , doubles , ushorts , etc ) , and making it easy to expand to n number of keys is important too ! Estimated `` config '' table size : 1,000 rows , Estimated `` data '' being looked up : 1e14That gives an idea about the type of performance that would be expected.I 'm looking for ideas in C # or something that can translate to C # easily . <code> Key1 , Key2 , Key3 , Valuenull , null , null , 11 , null , null , 29 , null , null , 211 , null , 3 , 3null , 2 , 3 , 41 , 2 , 3 , 5 Key1 - Priority 10Key2 - Priority 7Key3 - Priority 5 given a key of { 1 , 2 , 3 } the value should be 5.given a key of { 3 , 2 , 3 } the value should be 4.given a key of { 8 , 10 , 11 } the value should be 1.given a key of { 1 , 10 , 11 } the value should be 2.given a key of { 9 , 2 , 3 } the value should be 4.given a key of { 8 , 2 , 3 } the value should be 4.given a key of { 9 , 3 , 3 } the value should be 21 .
How to build a `` defaulting map '' data structure
C_sharp : I have a MethodInfo passed in to a function and I want to do the followingBut this does n't work because the methodInfo has a specific generic type . For the example does work if I knew that the ICollection was always of type string.How can I check whether the MethodInfo is a ANY typed instance of the generic method without caring what the type is ? Thanks.EDIT : Question clarificationAs correctly pointed out the method is not generic but the containing class is so the question is more how to I find out if the MethodInfo is for a Type which is a typed instance of ICollection < > .EDIT : more contextI am writing a Linq provider and trying to handle the `` in '' case <code> MethodInfo containsMethod = typeof ( ICollection < > ) .GetMethod ( `` Contains '' ) ; if ( methodInfo.Equals ( containsMethod ) { // do something } MethodInfo containsMethod = typeof ( ICollection < string > ) .GetMethod ( `` Contains '' ) ; if ( methodInfo.Equals ( containsMethod ) { // do something } IList < string > myList = new List < string > { `` 1 '' , `` 2 '' } ; from Something s in ... where myList.Contains ( s.name ) select s ;
How do I determine if a method is a generic instance of a generic method
C_sharp : This is a continuation of my question about downloading files in chunks . The explanation will be quite big , so I 'll try to divide it to several parts.1 ) What I tried to do ? I was creating a download manager for a Window-Phone application . First , I tried to solve the problem of downloading large files ( the explanation is in the previous question ) . No I want to add `` resumable download '' feature.2 ) What I 've already done.At the current moment I have a well-working download manager , that allows to outflank the Windows Phone RAM limit . The plot of this manager , is that it allows to download small chunks of file consequently , using HTTP Range header.A fast explanation of how it works : The file is downloaded in chunks of constant size . Let 's call this size `` delta '' . After the file chunk was downloaded , it is saved to local storage ( hard disk , on WP it 's called Isolated Storage ) in Append mode ( so , the downloaded byte array is always added to the end of the file ) . After downloading a single chunk the statementis checked . If it 's true , that means , there 's something left for download and this method is invoked recursively . Otherwise it means , that this chunk was last , and there 's nothing left to download.3 ) What 's the problem ? Until I used this logic at one-time downloads ( By one-time I mean , when you start downloading file and wait until the download is finished ) that worked well . However , I decided , that I need `` resume download '' feature . So , the facts:3.1 ) I know , that the file chunk size is a constant.3.2 ) I know , when the file is completely downloaded or not . ( that 's a indirect result of my app logic , wo n't weary you by explanation , just suppose , that this is a fact ) On the assumption of these two statements I can prove , that the number of downloaded chunks is equal to ( CurrentFileLength ) /delta . Where CurrentFileLenght is a size of already downloaded file in bytes.To resume downloading file I should simply set the required headers and invoke download method . That seems logic , is n't it ? And I tried to implement it : And what I see as a result ? The downloaded file length is equal to 2432000 bytes ( delta is 304160 , Total file size is about 4,5 MB , we 've downloaded only half of it ) . So the result is approximately 7,995 . ( it 's actually has long/int type , so it 's 7 and should be 8 instead ! ) Why is this happening ? Simple math tells us , that the file length should be 2433280 , so the given value is very close , but not equal.Further investigations showed , that all values , given from the fileStream.Length are not accurate , but all are close.Why is this happening ? I do n't know precisely , but perhaps , the .Length value is taken somewhere from file metadata . Perhaps , such rounding is normal for this method . Perhaps , when the download was interrupted , the file was n't saved totally ... ( no , that 's real fantastic , it ca n't be ) So the problem is set - it 's `` How to determine number of the chunks downloaded '' . Question is how to solve it.4 ) My thoughts about solving the problem.My first thought was about using maths here . Set some epsilon-neiborhood and use it in currentFileChunkIterator = currentFileSize / delta ; statement . But that will demand us to remember about type I and type II errors ( or false alarm and miss , if you do n't like the statistics terms . ) Perhaps , there 's nothing left to download . Also , I did n't checked , if the difference of the provided value and the true value is supposed to grow permanently or there will be cyclical fluctuations . With the small sizes ( about 4-5 MB ) I 've seen only growth , but that does n't prove anything.So , I 'm asking for help here , as I do n't like my solution.5 ) What I would like to hear as answer : What causes the difference between real value and received value ? Is there a way to receive a true value ? If not , is my solution good for this problem ? Are there other better solutions ? P.S . I wo n't set a Windows-Phone tag , because I 'm not sure that this problem is OS-related . I used the Isolated Storage Toolto check the size of downloaded file , and it showed me the same as the received value ( I 'm sorry about Russian language at screenshot ) : <code> if ( mediaFileLength > = delta ) // mediaFileLength is a length of downloaded chunk // Check file size using ( IsolatedStorageFileStream fileStream = isolatedStorageFile.OpenFile ( `` SomewhereInTheIsolatedStorage '' , FileMode.Open , FileAccess.Read ) ) { int currentFileSize = Convert.ToInt32 ( fileStream.Length ) ; int currentFileChunkIterator = currentFileSize / delta ; }
`` Where are my bytes ? '' or Investigation of file length traits
C_sharp : I have a table called visit with the following columns : I have the following SQL query : How can I convert this SQL into LINQ ? My entity name is dbcontext . Thanks in advance for any help . <code> visit_Idmember_Id visit_Date visit_Time visit_DateTime visit_Status values like ( accepted , refused ) string sql = @ '' SELECT CONCAT ( UPPER ( SUBSTRING ( visit_Status , 1 , 1 ) ) , SUBSTRING ( visit_Status FROM 2 ) ) as Status , COUNT ( ' x ' ) AS Visits FROM visits WHERE visit_Date BETWEEN '2001-09-08 ' AND '2009-09-09 ' GROUP BY visit_Status '' ;
Convert SQL query to LINQ
C_sharp : I have a need for a simple AsyncLazy < T > which behaves exactly like Lazy < T > but correctly supports handling exceptions and avoids caching them.Specifically the issue I am running into is as follows : I can write a piece of code as such : Note the use of LazyThreadSafetyMode.PublicationOnly . If the initialization method throws an exception on any thread , the exception is propagated out of the Value property on that thread . The exception is not cached.I then invoke it in the following way.and it works exactly as you would expect , where the first result is omitted because an exception occurs , the result remains uncached and the subsequent attempt to read the value succeeds returning 'Hello World'.Unfortunately however if I change my code to something like this : The code fails the first time it is invoked and subsequent calls to the property are cached ( and can therefore never recover ) .This somewhat makes sense because I suspect that the exception is never actually bubbling up beyond the task , however what I can not determine is a way to notify the Lazy < T > that the task/object initialisation has failed and should not be cached.Anyone able to provide any input ? EDIT : Thanks for your answer Ivan . I have successfully managed to get a basic example with your feedback but it turns out my problem is actually more complicated than the basic example above demonstrates and undoubtedly this problem will affect others in a similar situation . So if I change my property signature to something like this ( as per Ivans suggestion ) and then invoke it like this.the code works.However if you have a method like this which then itself calls another Async method.The Lazy caching bug manifests again and the problem can be reproduced . Here is a complete example to reproduce the problem : <code> public class TestClass { private int i = 0 ; public TestClass ( ) { this.LazyProperty = new Lazy < string > ( ( ) = > { if ( i == 0 ) throw new Exception ( `` My exception '' ) ; return `` Hello World '' ; } , LazyThreadSafetyMode.PublicationOnly ) ; } public void DoSomething ( ) { try { var res = this.LazyProperty.Value ; Console.WriteLine ( res ) ; //Never gets here } catch { } i++ ; try { var res1 = this.LazyProperty.Value ; Console.WriteLine ( res1 ) ; //Hello World } catch { } } public Lazy < string > LazyProperty { get ; } } TestClass _testClass = new TestClass ( ) ; _testClass.DoSomething ( ) ; public Lazy < Task < string > > AsyncLazyProperty { get ; } = new Lazy < Task < string > > ( async ( ) = > { if ( i == 0 ) throw new Exception ( `` My exception '' ) ; return await Task.FromResult ( `` Hello World '' ) ; } , LazyThreadSafetyMode.PublicationOnly ) ; this.LazyProperty = new Lazy < Task < string > > ( ( ) = > { if ( i == 0 ) throw new NotImplementedException ( ) ; return DoLazyAsync ( ) ; } , LazyThreadSafetyMode.PublicationOnly ) ; await this.LazyProperty.Value ; this.LazyProperty = new Lazy < Task < string > > ( ( ) = > { return ExecuteAuthenticationAsync ( ) ; } , LazyThreadSafetyMode.PublicationOnly ) ; private static async Task < AccessTokenModel > ExecuteAuthenticationAsync ( ) { var response = await AuthExtensions.AuthenticateAsync ( ) ; if ( ! response.Success ) throw new Exception ( $ '' Could not authenticate { response.Error } '' ) ; return response.Token ; } this.AccessToken = new Lazy < Task < string > > ( ( ) = > { return OuterFunctionAsync ( counter ) ; } , LazyThreadSafetyMode.PublicationOnly ) ; public Lazy < Task < string > > AccessToken { get ; private set ; } private static async Task < bool > InnerFunctionAsync ( int counter ) { await Task.Delay ( 1000 ) ; if ( counter == 0 ) throw new InvalidOperationException ( ) ; return false ; } private static async Task < string > OuterFunctionAsync ( int counter ) { bool res = await InnerFunctionAsync ( counter ) ; await Task.Delay ( 1000 ) ; return `` 12345 '' ; } try { var r = await this.AccessToken.Value ; } catch ( Exception ex ) { } counter++ ; try { //Retry is never performed , cached task returned . var r1 = await this.AccessToken.Value ; } catch ( Exception ex ) { }
Prevent Lazy < T > caching exceptions when invoking Async delegate
C_sharp : Consider this code : The code compiles successfully . Then I 'm adding the nuget package `` itext7 7.0.4 '' , and now the compilation fails because of : The reason is that the itext7 library has an internal class with extension methods in the global namespace ( here it is ) .For some reason the compiler chooses an inaccessible extension method with an incompatible signature from the global namespace instead of the accessible extension method with a compatible signature from the LINQ namespace.The question is : is this behavior expected in terms of the language specification or is it a bug in the compiler ? And why does it fail only in the case with a `` method group '' and still work with i = > a.Contains ( i ) ? <code> using System.Linq ; namespace ExtensionMethodIssue { static class Program { static void Main ( string [ ] args ) { var a = new [ ] { 1 } ; var b = new [ ] { 1 , 2 } .Where ( a.Contains ) .ToList ( ) ; var c = new [ ] { 1 , 2 } .Where ( i = > a.Contains ( i ) ) .ToList ( ) ; } } } //Error CS0122 : 'KernelExtensions.Contains < TKey , TValue > ( IDictionary < TKey , TValue > , TKey ) ' is inaccessible due to its protection levelvar b = new [ ] { 1 , 2 , 3 } .Where ( a.Contains ) .ToList ( ) ; // This is still ok.var c = new [ ] { 1 , 2 , 3 } .Where ( i = > a.Contains ( i ) ) .ToList ( ) ; internal static class KernelExtensions { public static bool Contains < TKey , TValue > ( this IDictionary < TKey , TValue > dictionary , TKey key ) { return dictionary.ContainsKey ( key ) ; } }
C # compiler chooses wrong extension method
C_sharp : I 'm primarily a Java programmer , so this would be one of those `` what is this thing from Java equivalent to in C # '' questions . So , in Java , you can restrain a Class type argument at compile time to extend a certain super-class , like so : and evenYou can even chain multiple interfaces : How is this done in C # ? I know you can use `` where T : BaseClass '' , but this is only applicable when you have an instance T. What about when you only have a Type instance ? EDIT : For explanation , here is what I would like to do : ASSEMBLY # 1 ( base.dll ) : ASSEMBLY # 2 ( sub1.dll , references base.dll ) : ASSEMBLY # 3 ( sub2.dll , references base.dll ) : ASSEMBLY # 4 ( main.dll , references base.dll ) : So , in this example , I do n't care what class the 'type ' variable represents , as long as it is derived from BaseClass , so once I create an instance , can call Foo ( ) .The parts that are not vaild C # code ( but rather some Java mockup ) are the `` generic '' Type classes : Type < T > and Type < ? : BaseClass > . <code> public < T extends BaseClass > void foo ( Class < T > type ) { ... } public < T extends BaseClass > T foo ( Class < T > type ) { ... } public < T extends BaseClass & BaseInterface1 & BaseInterface2 > void foo ( Class < T > type ) { ... } abstract class BaseClass { abstract void Foo ( ) ; } class SubClass1 : BaseClass { void Foo ( ) { // some code } } class SubClass2 : BaseClass { void Foo ( ) { // some other code } } class BaseClassUtil { static void CallFoo ( Type < T > type ) where T : BaseClass { T instance = ( T ) Activator.CreateInstance ( type ) ; instance.Foo ( ) ; } } public static void Main ( String [ ] args ) { // Here I use 'args ' to get a class type , // possibly loading it dynamically from a DLL Type < ? : BaseClass > type = LoadFromDll ( args ) ; // Loaded from DLL BaseClassUtil.CallFoo ( type ) ; }
Make sure Type instance represents a type assignable from certain class
C_sharp : Here I split the string into two string.For example , input : Helloworldoutput : Hello world.But now I need the output : dlrow olleH <code> string givenstring , outputString= '' '' ; int i , j = 0 ; Console.WriteLine ( `` Enter the string '' ) ; givenstring = Console.ReadLine ( ) ; i = ( givenstring.Length ) / 2 ; while ( j < i ) { outputString += givenstring [ j ] ; j++ ; } Console.WriteLine ( outputString ) ; outputString = string.Empty ; while ( i < givenstring.Length ) { outputString += givenstring [ i ] ; i++ ; } Console.WriteLine ( outputString ) ;
Spliting a string into two words using while
C_sharp : In my _Layout page , I have got a search form and each controller has an index view . When the user clicks the search button , it searches in the current index view . I want to show the search field if the user is index view if they go to other views , I wanted to hide it . In my _Layout I am using JQuery at the moment but it is quite difficult to put every single viewBasically , in my _Layout page , I wanted to show or hide Search form if the user is in the index view . how can i get current view name in _Layout view , please ? <code> < form asp-action= '' Index '' method= '' get '' class= '' navbar-form form-inline navbar-right '' > < input class= '' form-control mr-sm-2 '' id= '' search '' name= '' search '' type= '' search '' placeholder= '' Search '' aria-label= '' Search '' > < button class= '' btn btn-outline-success my-2 my-sm-0 '' id= '' BtnSearch '' name= '' BtnSarch '' type= '' submit '' > Search < /button > < /form > $ ( `` # search '' ) .hide ( ) ; $ ( `` # BtnSearch '' ) .hide ( ) ;
How to get the current Action name inside the View
C_sharp : After reading a question here about what things our computer could do in one second I made a little test I had in mind for a while and I 'm very surprised by the results . Look : Simple program to catch a null exception , takes almost one second to do 1900 iterations : Alternatively , checking if test == null before doing the assignation , the same pogram can do aprox 200000000 iterations in one second.Anyone has a detailed explanation on why this HUGE diference ? EDIT : Running the test in Release mode , outside Visual studio i 'm getting 35000-40000 iterations vs 400000000 iterations ( always aprox ) Note I 'm running this with a crappy PIV 3.06Ghz <code> for ( long c = 0 ; c < 200000000 ; c++ ) { try { test = null ; test.x = 1 ; } catch ( Exception ex ) { } } for ( long c = 0 ; c < 1900 ; c++ ) { test = null ; f ( ! ( test == null ) ) { test.x = 1 ; } }
Why this performance difference ? ( Exception catching )
C_sharp : In this case I have a Grid with a lot controls inside it , buttons , canvas , drawing , animations , all bound to view-models , I would like to disable all the dataTriggers , triggers , bindings inside its children and children of children , etc. , when I set the visibility of the Grid to collapsed , so it is not wasting CPU cycles , ( because a heavy animation is continuously running ) , and not crashing ! I 'm using a behaviour : http : //www.microsoft.com/design/toolbox/tutorials/pathlistbox/carousel.aspxbut it seems to have a bug that its making the app crash if the listbox is collapsed when using it , So I need to disable the databinding which activates the behaviour , from what I found : Does Visibility = IsCollapsed skip the data-binding part ? Your controls ' Templates will not be appliedSo the only way to do it is putting everything inside a controltemplate : So in this way the Template would n't be applied and everything would be off until I switch the visibility.So my question is : is this the correct way to address this issue ? <code> < ContentControl Visibility= '' Collapsed '' > < ContentControl.Template > < Grid Name= '' Heavy Animation control '' > < ! -- - animations , triggers , bindings , -- > < /Grid > < /ContentControl.Template >
How to disable all binding/triggering inside a ContentControl
C_sharp : The whole day I am trying to get this working.I am doing a dependency injection via this code : Everytime when I am executing this code I am getting the following error : I am really annoyed of that because I ca n't get it working and I have no clue about it . I am relatively new to Asp.Net and C # but this is how the tutorial said me to do . Does everyone know what my problem about the code is ? Maybe this helps.My Interface : My DebugMailService <code> public Startup ( IApplicationEnviroment appEnv ) { var builder = new ConfigurationBuilder ( ) .SetBasePath ( appEnv.ApplicationBasePath ) .AddJsonFile ( `` config.json '' ) .AddEnvironmentVariables ( ) ; Configuration = builder.Build ( ) ; } # if DEBUG services.AddScoped < IMailService , DebugMailService > ( ) ; # else services.AddScoped < IMailService , RealMailService > ( ) ; # endif public interface IMailService { bool SendMail ( string to , string from , string subject , string body ) ; } public class DebugMailService : IMailService { public bool SendMail ( string to , string from , string subject , string body ) { Debug.WriteLine ( $ '' Sending mail : To : { to } , Subject : { subject } '' ) ; return true ; } }
Dependency Injection IApplicationEnvironment Error
C_sharp : Put simply , I can create 2 dependency properties in a WPF control and put code in each property change notification to change the other property ( i.e PropA change sets PropB and PropB change sets PropA ) .I would expect this to disappear up its own backside but WPF seems to handle it nicely . That 's actually very handy for my purposes but I ca n't find this behaviour documented anywhere.So what 's going on ? Does the WPF dependency property change notification system guard against reentrancy ? Representative code follows : XAML : Code behind : <code> < Window x : Class= '' WPFReentrancy1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < Grid > < TextBox Text= '' { Binding PropB , UpdateSourceTrigger=PropertyChanged } '' / > < /Grid > < /Window > public partial class MainWindow : Window { public string PropA { get { return ( string ) GetValue ( PropAProperty ) ; } set { SetValue ( PropAProperty , value ) ; } } public static readonly DependencyProperty PropAProperty = DependencyProperty.Register ( `` PropA '' , typeof ( string ) , typeof ( MainWindow ) , new UIPropertyMetadata ( `` 0 '' , PropAChanged ) ) ; public string PropB { get { return ( string ) GetValue ( PropBProperty ) ; } set { SetValue ( PropBProperty , value ) ; } } public static readonly DependencyProperty PropBProperty = DependencyProperty.Register ( `` PropB '' , typeof ( string ) , typeof ( MainWindow ) , new UIPropertyMetadata ( `` '' , PropBChanged ) ) ; private static void PropBChanged ( DependencyObject lDependencyObject , DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs ) { ( ( MainWindow ) lDependencyObject ) .PropA = ( string ) lDependencyPropertyChangedEventArgs.NewValue ; } private static void PropAChanged ( DependencyObject lDependencyObject , DependencyPropertyChangedEventArgs lDependencyPropertyChangedEventArgs ) { ( ( MainWindow ) lDependencyObject ) .PropB = double.Parse ( ( string ) lDependencyPropertyChangedEventArgs.NewValue ) .ToString ( `` 0.000 '' ) ; } public MainWindow ( ) { InitializeComponent ( ) ; DataContext = this ; PropA = `` 1.123 '' ; } }
Dependency property re-entrancy ( or : why does this work ? )
C_sharp : I have a string that looks like that : And this class : And I want to create a List of Users with informations from that string.I have tried doing that : But I can only combine two lists using this code . Also , I have more than 4 values for each user ( the string above was just a short example ) .Is there a better method ? Thanks . <code> random text 12234another random text User infos : User name : JohnID : 221223Date : 23.02.2018Job : job1User name : AndrewID : 378292Date : 12.08.2017Job : job2User name : ChrisID : 930712Date : 05.11.2016Job : job3some random text class User { public string UserName { get ; set ; } public string ID { get ; set ; } public string Date { get ; set ; } public string Job { get ; set ; } public User ( string _UserName , string _ID , string _Date , string _Job ) { UserName = _UserName ID = _ID ; Date = _Date ; Job = _Job ; } } List < User > Users = new List < User > ( ) ; string Data = ( the data above ) string [ ] lines = Data.Split ( new string [ ] { Environment.NewLine } , StringSplitOptions.RemoveEmptyEntries ) ; List < string > UserNames = new List < string > ( ) ; List < string > IDs = new List < string > ( ) ; List < string > Dates = new List < string > ( ) ; List < string > Jobs = new List < string > ( ) ; foreach ( var line in lines ) { if ( line.StartsWith ( `` User name : `` ) ) { UserNames.Add ( Line.Remove ( 0 , 12 ) ) ; } if ( Line.StartsWith ( `` ID : `` ) ) { IDs.Add ( Line.Remove ( 0 , 5 ) ) ; } if ( Line.StartsWith ( `` Date : `` ) ) { Dates.Add ( Line.Remove ( 0 , 7 ) ) ; } if ( Line.StartsWith ( `` Job : `` ) ) { Jobs.Add ( Line.Remove ( 0 , 6 ) ) ; } } var AllData = UserNames.Zip ( IDs , ( u , i ) = > new { UserName = u , ID = i } ) ; foreach ( var data in AllData ) { Users.Add ( new User ( data.UserName , data.ID , `` date '' , `` job '' ) ) ; }
Create a list of objects with initialized properties from a string with infos
C_sharp : Here are a list of aliases in C # ( compliments of What is the difference between String and string in C # ? ) : I can see bool through char being lowercase aliases , because they are primitive types.Why are object and string not capitalized , since they are complex types ? Is this an oversight by the developers , or is there a necessary reason for them to be lowercase ? Or is this an opinionated question ? You end up with things like string.Format ( ) instead of String.Format ( ) , which just look funky and make me think string is a variable . <code> object : System.Objectstring : System.Stringbool : System.Booleanbyte : System.Bytesbyte : System.SByteshort : System.Int16ushort : System.UInt16int : System.Int32uint : System.UInt32long : System.Int64ulong : System.UInt64float : System.Singledouble : System.Doubledecimal : System.Decimalchar : System.Char
Why are the aliases for string and object in lowercase ?
C_sharp : I have tilt image capture by mobile . I want to cut section/portion of image in between two rectangles of both sides to find out circles in between them . I have all 4 co-ordinates of middle section like ( x0 , y0 ) , ( x1 , y1 ) , ( x2 , y2 ) , ( x3 , y3 ) . My Image is looks like , But crop function I have something like But above function cuts portion as rectangle as show in 1st and 2nd red color box.I am looking for code to cut portion shown in 3rd red rectangle . I had search for code and find out below code of AForge.Imaging . library but it will cut potion like below which disturb shape of circle and make it ellipse which causes issue for other calculation.please let me know how to crop image using 4 points.Or is there is any way to correct the tilt of image by passing correction angle ? <code> public static Bitmap CropImage ( int x , int y , int width , int height , Bitmap bitmap ) { Bitmap croppedImage ; var originalImage = bitmap ; { Rectangle crop = new Rectangle ( x , y , width , height ) ; croppedImage = originalImage.Clone ( crop , originalImage.PixelFormat ) ; } // Here we release the original resource - bitmap in memory and file on disk . return croppedImage ; } List < IntPoint > corners = new List < IntPoint > ( ) ; corners.Add ( new IntPoint ( x0 , y0 ) ) ; corners.Add ( new IntPoint ( x3 , y3 ) ) ; corners.Add ( new IntPoint ( x1 + 30 , y1 + 20 ) ) ; corners.Add ( new IntPoint ( x2 + 30 , y2 + 0 ) ) ; AForge.Imaging.Filters.QuadrilateralTransformation filter = new AForge.Imaging.Filters.QuadrilateralTransformation ( corners , WidthOfCut , HeightOfCut ) ; Bitmap newImage = filter.Apply ( mainOuterWindow ) ;
How to crop tilt image in c #
C_sharp : Ok , as I was poking around with building a custom enumerator , I had noticed this behavior that concerns the yieldSay you have something like this : What makes it possible underneath the compiler 's hood to execute the index ++ and the rest of the code in the while loop after you technically do a return from the function ? <code> public class EnumeratorExample { public static IEnumerable < int > GetSource ( int startPoint ) { int [ ] values = new int [ ] { 1,2,3,4,5,6,7 } ; Contract.Invariant ( startPoint < values.Length ) ; bool keepSearching = true ; int index = startPoint ; while ( keepSearching ) { yield return values [ index ] ; //The mind reels here index ++ keepSearching = index < values.Length ; } } }
The wonders of the yield keyword
C_sharp : For my homework , I 'm implementing a course registration system for a university and I implemented a simple class for Curriculum with list of semesters and other properties like name of the department , total credits etc . But I 'm wondering if I can inherit this class from a Graph Data Structure with Edges and vertices.Anybody done similar things before ? My current design is something like this : <code> public class Curriculum { public string NameOfDepartment { get ; set ; } public List < Semester > Semesters { get ; set ; } public bool IsProgramDesigned { get ; set ; } public Curriculum ( ) { IsProgramDesigned = false ; } // public string AddSemester ( Semester semester ) {
What Data Structure would you use for a Curriculum of a Department in a University ?
C_sharp : I have a function that accepts an Enum ( The base class ) as a parameter : However I ca n't for some reason cast it to int . I can get the name of the enumeration value but not it 's integral representation.I really do n't care about the type of the enumeration , I just need the integral value.Should I pass an int instead ? Or am I doing something wrong here ? <code> public void SomeFunction ( Enum e ) ;
How to cast an Enum to an int ?
C_sharp : Recently I 'm developing a software that parses and displays XML information from a website . Simple enough right ? I 'm getting LOADS of NullReferenceExceptions . For example , this method : I had to wrap an ugly as sin If around the actual foreach loop in order to prevent an exception.I feel I 'm just putting bandaids on a flat tire instead of actually fixing the problem . Is there any way I can tackle this problem ? Maybe a book I should read regarding programming patterns or what not ? Really , I 'm lost . I 'm probably asking the wrong questions . <code> private void SetUserFriends ( List < Friend > list ) { int x = 40 ; int y = 3 ; if ( list ! = null ) { foreach ( Friend friend in list ) { FriendControl control = new FriendControl ( ) ; control.ID = friend.ID ; control.URL = friend.URL ; control.SetID ( friend.ID ) ; control.SetName ( friend.Name ) ; control.SetImage ( friend.Photo ) ; control.Location = new Point ( x , y ) ; panel2.Controls.Add ( control ) ; y = y + control.Height + 4 ; } } }
I seem to have fallen into some massive , massive trouble with NullReferenceExceptions
C_sharp : I am adding image to the radtreeviewitem from resources programatically using the below code.and the image is displaying successfully . Now i need to add another image which needs to be displayed next to the first image in the radtreeviewitem.how to achieve it . ? Like the below image i need my treeviewitem to display a folder icon and a red square icon in a single treeview item . <code> `` /myAssembley ; component/Resources/image1.png ''
How to show more that one image in the radtreeview item ( wpf - telerik )
C_sharp : as per https : //www.mikesdotnetting.com/article/343/improved-remote-validation-in-razor-pagesI followed the tutorial and implemented the PageRemote . However it does not work if applied to a property of a model and I use the model as property . on my page <code> public class Draft { public int Id { get ; set ; } [ PageRemote ( ErrorMessage = `` Invalid data '' , AdditionalFields = `` __RequestVerificationToken '' , HttpMethod = `` post '' , PageHandler = `` CheckReference '' ) ] public string Reference { get ; set ; } } [ BindProperty ] public Draft Draft { get ; set ; } public JsonResult OnPostCheckReference ( ) { var valid = ! Draft.Reference.Contains ( `` 12345 '' ) ; return new JsonResult ( valid ) ; } < tab > < tab-item icon= '' fas fa-arrow-left '' url= '' @ Url.Page ( `` ../Index '' ) '' > < /tab-item > < tab-item icon= '' fas fa-list '' url= '' @ Url.Page ( `` Index '' ) '' > < /tab-item > < tab-item icon= '' fas fa-plus '' is-active= '' true '' > < /tab-item > < /tab > < form method= '' post '' > < card > < card-header icon= '' fas fa-plus '' title= '' Draft '' > < /card-header > < card-body > < input asp-for= '' Draft.Reference '' / > < span asp-validation-for= '' Draft.Reference '' class= '' text-danger '' > < /span > < /card-body > < card-footer > < button class= '' btn btn-success '' > < i class= '' fas fa-plus '' > < /i > Adicionar < /button > < /card-footer > < /card > < /form > @ section Scripts { @ { await Html.RenderPartialAsync ( `` _ValidationScriptsPartial '' ) ; } < script src= '' ~/lib/jquery-ajax-unobtrusive/dist/jquery.unobtrusive-ajax.min.js '' > < /script > }
RazorPages Page Remote not working on model
C_sharp : Is this a bug or a feature ? All code below has been simplified for the sake of brevity and easy replication and does not actually do anything useful other than highlight the behavior.I have a class that includes an int named ID : In my controller , I have an Edit actionresult that takes a parameter called 'id ' : in my index view I have a link to the edit action that specifies the 'id ' parameter : In my view I have a couple of text boxes : which renders the following in HTML : Notice that the input with an id of `` ID '' is getting its value not from the Model like I am telling it to ... but from the parameter that was supplied to my ActionResult.This behavior is the same with Html.TextBoxFor , Html.Hidden , Html.HiddenFor , etc.What gives ? EDIT : I meant to update this a long time ago but never got around to it . The reason that this is happening is because the ModelState will have an `` id '' entry with the value of the `` id '' parameter in the method and the MVC ViewEngine first checks the ModelState when filling in Html helpers instead of the Model . In order to work around this , you can simply add the following line in your controller just before the return : Now the < % = Html.TextBox ( `` ID '' , Model.ID ) % > will get the value from the Model and not the ModelState . Problem solved . <code> public class FooterLink { public int ID { get ; set ; } } public ActionResult Edit ( int id ) { return View ( new FooterLink ( ) { ID = 5 } ) ; //notice that I am explicitly setting the ID value here . } < % = Html.ActionLink ( `` Edit '' , `` Edit '' , new { id = 1 } ) % > < % = Html.TextBox ( `` ID '' , Model.ID ) % > < % = Html.TextBox ( `` Blah '' , Model.ID ) % > < input id= '' ID '' name= '' ID '' type= '' text '' value= '' 1 '' > < input id= '' Blah '' name= '' Blah '' type= '' text '' value= '' 5 '' > ModelState.Remove ( `` id '' ) ;
Why is my MVC ViewModel member overridden by my ActionResult parameter ?
C_sharp : I was discovering the IL code of a simple program : I build this code in Release mode and this IL code is generated : I figure out pretty much all the insructions except this : Now this insruction should push int.MaxValue * 2L onto the stack and then blt.s will compare it with i , if i is less than the value go back to the IL_0008.But , what I ca n't figure out is that why it loads -2 ? If I change the loop like below : It loads the expected value : So what is the meaning of -2 in this code ? <code> long x = 0 ; for ( long i = 0 ; i < int.MaxValue * 2L ; i++ ) { x = i ; } Console.WriteLine ( x ) ; .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 28 ( 0x1c ) .maxstack 2 .locals init ( [ 0 ] int64 x , [ 1 ] int64 i ) IL_0000 : ldc.i4.0 IL_0001 : conv.i8 IL_0002 : stloc.0 IL_0003 : ldc.i4.0 IL_0004 : conv.i8 IL_0005 : stloc.1 IL_0006 : br.s IL_000f IL_0008 : ldloc.1 IL_0009 : stloc.0 IL_000a : ldloc.1 IL_000b : ldc.i4.1 IL_000c : conv.i8 IL_000d : add IL_000e : stloc.1 IL_000f : ldloc.1 IL_0010 : ldc.i4.s -2 IL_0012 : conv.u8 IL_0013 : blt.s IL_0008 IL_0015 : ldloc.0 IL_0016 : call void [ mscorlib ] System.Console : :WriteLine ( int64 ) IL_001b : ret } // end of method Program : :Main IL_0010 : ldc.i4.s -2 for ( long i = 0 ; i < int.MaxValue * 3L ; i++ ) { x = i ; } IL_0010 : ldc.i8 0x17ffffffd
What is the meaning of -2 in this IL instruction ?
C_sharp : I have n't noticed this behaviour yet , maybe because i prefer query syntax in VB.NET and split the query and the execution-methods into different statements . If i try to compile following simple query : The compiler does n't like this because he expects no arguments for List.Count : `` Public Readonly Property Count As Integer '' has no parameters and its return type can not be indexed.If i declare it as IEnumerable ( Of String ) it works as expected : Why is that so ? What prevents the compiler from using the Enumerable extension method Count instead of the ICollection.Count property . Note that i 've added Imports System.Linq and both Option Strict and Option Infer are On . I 'm using.NET 4.0 ( Visual Studio 2010 ) .I 'm confused because in C # this works without a problem : <code> Dim wordList As List ( Of String ) = New List ( Of String ) Dim longWords As Int32 = wordList.Count ( Function ( word ) word.Length > 100 ) Dim wordSeq As IEnumerable ( Of String ) = New List ( Of String ) Dim longWords As Int32 = wordSeq.Count ( Function ( word ) word.Length > 100 ) List < String > wordList = new List < String > ( ) ; int longWordCount = wordList.Count ( word = > word.Length > 100 ) ;
Can not use Enumerable.Count with List , compiler assumes List.Count
C_sharp : I got an object of I need to bring this into a I have no idea how to do this with LINQ . <code> List < List < string > > List < string >
with LINQ , how to transfer a List < List < string > > to List < string > ?
C_sharp : This is the background to this question : BackgroundTake any integer n greater than 1 and apply the following algorithmIf n is odd then n = n × 3 + 1 else n = n / 2If n is equal to 1 then stop , otherwise go to step 1The following demonstrates what happens when using a starting n of 66 - 3 - 10 - 5 - 16 - 8 - 4 - 2 - 1After 8 generations of the algorithm we get to 1.It is conjectured that for every number greater than 1 the repeated application of this algorithm willeventually get to 1.The question is how can I find a number that takes exactly 500 generations to reduce to 1 ? The code below is my version but appearntly got some wrong logic . Could you help me correct this ? Thanks in advance . <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Sequence1 { class Program { static void Main ( string [ ] args ) { int start = 1 ; int flag = 0 ; int value ; while ( true ) { int temp = ( start - 1 ) / 3 ; string sta = temp.ToString ( ) ; if ( Int32.TryParse ( sta , out value ) ) { if ( ( ( start - 1 ) / 3 ) % 2 == 1 ) { start = ( start - 1 ) / 3 ; flag++ ; if ( flag == 500 ) { break ; } } else { start = start * 2 ; flag++ ; if ( flag == 500 ) { break ; } } } else { start = start * 2 ; flag++ ; if ( flag == 500 ) { break ; } } } Console.WriteLine ( `` result is { 0 } '' , start ) ; Console.ReadLine ( ) ; } } }
A recursion related issue in c #
C_sharp : I am developing UWP application for remote device using VS17 . I suddenly got this message And I am stuck at this error for about week . I dont know what cause it . Last thing that I made was that I move GPIO routines to external library . After that , each build ends with this message.What I tried : Turn off antivirus Redo last update ( library is working on other similar solutions ) Redo several last changes in buildupdate VS , repair VS and repair SDKsupdate versions of librariesreboot target devicebuild project on other PC ( with fresh VS ) , copy code on brand new project and run it on my or other PCget rid of anything that using Linq library in code.Run VS as administratorWith no success at all . I will be very happy if anyone will help me with solving this problem . <code> Error The `` WireUpCoreRuntime '' task failed unexpectedly.System.InvalidOperationException : Sequence contains no elements at System.Linq.Enumerable.Single [ TSource ] ( IEnumerable ` 1 source ) at Microsoft.Build.Net.CoreRuntimeTask.WireUpCoreRuntime.InternalExecute ( ) at Microsoft.Build.Net.CoreRuntimeTask.WireUpCoreRuntime.Execute ( ) at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute ( ) at Microsoft.Build.BackEnd.TaskBuilder. < ExecuteInstantiatedTask > d__26.MoveNext ( ) DataManagementApp
The `` WireUpCoreRuntime '' task failed unexpectedly Visual studio 2017
C_sharp : I am trying to add timeout to this code , but because I am new to this , I ca n't figure out , Also I want main thread to wait here until it timeout for 5 minutes or completes.EditOr can I use cancellation token with this , if yes then how : ( ? <code> Task.Factory.StartNew ( ( ) = > { Aspose.Words.Document doc = new Aspose.Words.Document ( inputFileName ) ; doc.Save ( Path.ChangeExtension ( inputFileName , `` .pdf '' ) ) ; } ) ;
How can I add timeout to this code
C_sharp : Basically , I 'm wondering if I should listen to ReSharper in this instance ... You 'd figure that comparing to characters one should use Char.Equals ( char ) since it avoids unboxing , but Resharper suggests using Object.Equals ( obj ) . Maybe I 'm missing something here ? I 'm guessing it 's because there is a DependencyProperty backing ? <code> private const DEFAULT_CHAR = ' # ' ; // DependencyProperty backingpublic Char SpecialChar { get { return ( Char ) GetValue ( SpecialCharProperty ) ; } } // ReSharper - Access to a static member of a type via a derived type.if ( Char.Equals ( control.SpecialChar , DEFAULT_CHAR ) ) { ... }
Char.Equals vs Object.Equals -- ReSharper suggests that I should use Object.Equals . Should I ?
C_sharp : I am trying to get the week number from a date time and in my case , the first day of the week is Monday and I want to follow the FirstFourDays convention.To check the results , I am checking this webpage : https : //espanol.epochconverter.com/semanas/2020To get the week number , I using the method : So I am trying to get the week number of the date 2019-12-29 , so I use this code : The result is week 52 . It is correct.Now I am trying to get the week number of the 2019-12-30 , the week number that I get is 53 , it is wrong , because 2019 has only 52 weeks . In fact , 2019-12-30 belongs to the same week than 2020-01-01 , that it is week 1 , that is correct , so I do n't understand why I can get two different results for the same date.How I could get the correct result always ? Or how would it be the correct way to get the week number of any date ? <code> System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear ( ) ; System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear ( new DateTime ( 2019 , 12 , 29 ) , System.Globalization.CalendarWeekRule.FirstFourDayWeek , DayOfWeek.Monday ) ;
Get the week number from a date time
C_sharp : I have an application that stores some data in firebird database . I 'm using an embedded firebird server and EntityFramework and all works greatfully but when I close my app by x button on form I get a windows system message `` application has stopped working '' and I ca n't catch this exception . I have an UnhandledExceptionHandler in my app : But this kind of exception never been catched by it . So I went to windows event log and found there this xml-view of error-event : As you see something went wrong with fbintl.DLL when app has closed already . So how I can get more detailed description about this problem ? UPDI make an app more shorter to detect a reason of my problem - now ONLY this EF code runs before app closeWhere FirebirdDbContext is : And connection params isNEW UPDATE 25.04.2017I made a simple app with firebird embedded db that demonstrates the error . U can find it hereThe app creates a firebird embedded database and connects to it in background thread ( Task TPL ) , and after work is done ( _bgTask.Status == TaskStatus.RanToCompletion ) u close the app and get the error . <code> // Add handler for UI thread exceptionsApplication.ThreadException += new ThreadExceptionEventHandler ( UIThreadException ) ; // Force all WinForms errors to go through handlerApplication.SetUnhandledExceptionMode ( UnhandledExceptionMode.CatchException ) ; //This handler is for catching non-UI thread exceptions AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler ( CurrentDomain_UnhandledException ) ; ... ..some other code ... ... ... .Application.Run ( new MainForm ( ) ) ; - < Event xmlns= '' http : //schemas.microsoft.com/win/2004/08/events/event '' > - < System > < Provider Name= '' Application Error '' / > < EventID Qualifiers= '' 0 '' > 1000 < /EventID > < Level > 2 < /Level > < Task > 100 < /Task > < Keywords > 0x80000000000000 < /Keywords > < TimeCreated SystemTime= '' 2017-03-14T23:06:25.000000000Z '' / > < EventRecordID > 36077 < /EventRecordID > < Channel > Application < /Channel > < Computer > MYPC < /Computer > < Security / > < /System > - < EventData > < Data > MyApp.exe < /Data > < Data > 1.0.0.0 < /Data > < Data > 58c7a3f0 < /Data > < Data > fbintl.DLL < /Data > < Data > 2.5.5.26952 < /Data > < Data > 5644432f < /Data > < Data > c0000005 < /Data > < Data > 00004e9c < /Data > < Data > 1d64 < /Data > < Data > 01d29d1797fb7f0d < /Data > < Data > G : \Programming\WorkSpace\C # \MyApp\bin\x86\Debug\MyApp.exe < /Data > < Data > G : \Programming\WorkSpace\C # \MyApp\bin\x86\Debug\FireBirdEmbeddedServer\intl\fbintl.DLL < /Data > < Data > d84a6ca6-090a-11e7-8151-005056c00008 < /Data > < /EventData > < /Event > public async Task GetAutoAnswerTemplate ( ) { try { using ( var db = new FirebirdDbContext ( embeddedConnectionString ) ) { //Async or sync methods does n't affect to my problem AutoAnswerTemplate template = await dbContext.AutoAnswerTemplate.FirstOrDefaultAsync ( ) ; return template ? .AutoAnswer_body ; } } catch ( Exception ex ) { throw new EmbeddedFbDataBaseTools.EmbeddedDbException ( `` Error while getting auto answer template '' + `` \r\n '' + ex.Message , ex ) ; } } public class FirebirdDbContext : DbContext { public FirebirdDbContext ( string connString ) : base ( new FbConnection ( connString ) , true ) { //* The Entity initializer is bugged with Firebird embedded : http : //stackoverflow.com/q/20959450/2504010 so I did n't use default -- - > // Database.SetInitializer < FirebirdDBContext > ( new CreateDatabaseIfNotExists < FirebirdDBContext > ( ) ) ; Database.SetInitializer < FirebirdDbContext > ( new MyCreateDatabaseIfNotExists ( ) ) ; } public DbSet < AutoAnswerTemplate > AutoAnswerTemplate { get ; set ; } public DbSet < User > User { get ; set ; } } class MyCreateDatabaseIfNotExists : IDatabaseInitializer < FirebirdDbContext > { public void InitializeDatabase ( FirebirdDbContext context ) { if ( ! context.Database.Exists ( ) ) { context.Database.Create ( ) ; } } } public static string GetEmbeddeddefaultConnectionString ( ) { FbConnectionStringBuilder builder = new FbConnectionStringBuilder { ServerType = FbServerType.Embedded , DataSource = `` localhost '' , Port = 3050 , Database = EmbeddedDbPath , //Path to embedded db ClientLibrary = EmbeddedServerDllPath , UserID = `` SYSDBA '' , Password = `` masterkey '' , Charset = `` WIN1251 '' , Dialect = 3 , ConnectionLifeTime = 15 , Pooling = true , MinPoolSize = 0 , MaxPoolSize = 50 } ; return builder.ToString ( ) ; }
Embedded server application has stopped working after exit
C_sharp : Consider : In that case , the where clause is enforcing a specification that MyClass is only a generic of a reference type.Ideally I should have a unit test that tests this specification . However , this unit test obviously wo n't work , but it explains what I 'm trying to accomplish : What can I do to test a spec that 's implemented by not allowing the code to compile ? EDIT : More info : Ok , so my reasoning for doing this ( haha ) is that I 've been following a TDD methodology , in which you ca n't write any code unless you have a failing unit test . Let 's say you had this : What test can you write that would fail unless T were a class ? Something like default ( T ) == null ? Further EDIT : So after a `` root cause analysis '' on this , the problem is that I was relying on default ( T ) being null in a consumer of this class , in an implicit way . I was able to refactor that consumer code into another class , and specify a generic type restriction there ( restricting it to class ) which effectively makes that code not compile if someone were to remove the restriction on the class I 'm talking about above . <code> class MyClass < T > where T : class { } [ Test ] [ DoesNotCompile ( ) ] public void T_must_be_a_reference_type ( ) { var test = new MyClass < int > ( ) ; } class MyClass < T > { }
How to write a unit test for `` T must be a reference type '' ?
C_sharp : Currently I 'm trying to understand dependency injection better and I 'm using asp.net MVC to work with it . You might see some other related questions from me ; ) Alright , I 'll start with an example controller ( of an example Contacts Manager asp.net MVC application ) Allright , awesome that 's working . My actions can all use the database for CRUD actions . Now I 've decided I wanted to add unit testing , and I 've added another contructor to mock a databaseAwesome , that 's working to , in my unit tests I can create my own implementation of the IContactsManagerDb and unit test my controller.Now , people usually make the following decision ( and here is my actual question ) , get rid of the empty controller , and use dependency injection to define what implementation to use.So using StructureMap I 've added the following injection rule : And ofcourse in my Testing Project I 'm using a different IContactsManagerDb implementation.But my question is , **What problem have I solved or what have I simplified by using dependency injection in this specific case '' I fail to see any practical use of it now , I understand the HOW but not the WHY ? What 's the use of this ? Can anyone add to this project perhaps , make an example how this is more practical and useful ? <code> public class ContactsController { ContactsManagerDb _db ; public ContactsController ( ) { _db = ContactsManagerDb ( ) ; } // ... Actions here } public class ContactsController { IContactsManagerDb _db ; public ContactsController ( ) { _db = ContactsManagerDb ( ) ; } public ContactsController ( IContactsManagerDb db ) { _db = db ; } // ... Actions here } x.For < IContactsManagerDb > ( ) .Use < ContactsManagerDb > ( ) ; x.For < IContactsManagerDb > ( ) .Use < MyTestingContactsManagerDb > ( ) ;
Dependency Injection what´s the big improvement ?
C_sharp : Here we are on EF Core and got 3 tables : NewsItemsLinksAnd more ( except News , Items ) : Content , Post , Form , etc.And my model definitionsTable Links describe URL for every News and every Item.This means that Links has 4 columns : IdType - news or itemRowId - contains ID of Item or News ( depends on the Type ) URLHow to setup the relationships ? Keep in mind that we need to resolve Entity by URL in Links table . <code> public class Item { public int Id { get ; set ; } public string Name { get ; set ; } public decimal Price { get ; set ; } public Link Link { get ; set ; } } public class News { public int Id { get ; set ; } public string Header { get ; set ; } public string Content { get ; set ; } public Link Link { get ; set ; } } public class Link { public int Id { get ; set ; } public string Type { get ; set ; } public int RowId { get ; set ; } public string Url { get ; set ; } }
How to setup entity relations in Entity Framework Core
C_sharp : I was reading an article on Linq to Sql and came across this : The author then translated the results in plain sql : And I thought to myself , `` holy cow ! would n't it be great if there was an extension to IQueryable that would generate these strings for you when debugging ? `` Anyone ever heard of anything like this , and if so , could you point me in the right direction ? Thanks ! <code> IQueryProvider provider = new QueryProvider ( database.GetCommand , database.ExecuteQuery ) ; IQueryable < Product > source = new Queryable < Product > ( provider , database.GetTable < Product > ( ) ) ; IQueryable < string > results = source.Where ( product = > product.CategoryID == 2 ) .OrderBy ( product = > product.ProductName ) .Select ( product = > product.ProductName ) .Skip ( 5 ) .Take ( 10 ) ; exec sp_executesql N'SELECT [ t1 ] . [ ProductName ] FROM ( SELECT ROW_NUMBER ( ) OVER ( ORDER BY [ t0 ] . [ ProductName ] ) AS [ ROW_NUMBER ] , [ t0 ] . [ ProductName ] FROM [ dbo ] . [ Products ] AS [ t0 ] WHERE [ t0 ] . [ CategoryID ] > @ p0 ) AS [ t1 ] WHERE [ t1 ] . [ ROW_NUMBER ] BETWEEN @ p1 + 1 AND @ p1 + @ p2ORDER BY [ t1 ] . [ ROW_NUMBER ] ' , N ' @ p0 int , @ p1 int , @ p2 int ' , @ p0=2 , @ p1=5 , @ p2=10
Is there an api or extension to translate IQueryable < T > lambda expressions to SQL strings ?
C_sharp : I have this scenario : I have these classes : class A has collection of class B and class Ci have one class B and different base classes.when in class A collection there is only B that Ci not reference it , I can delete class A and all the B collection also deleted ( cascade delete ) . But when in class A collection there is B that classes Ci has reference to it I ca n't delete class A instance ... My expected behavior : Class A will be deleted and all the B collection that class A has , and if Ci has reference to some of the B in the collection it will be null in the end of the delete . ( class Ci intances will not be deleted ! ) , also I do n't want to iterate throw all my Ci class to see if it has reference to the B collection that need to be deleted.I do n't want this code : someone know how to achieve it ? <code> public class A { public int Id { get ; set ; } public virtual ICollection < B > bCollection { get ; set ; } } public class B { public int Id { get ; set ; } } public class C1 : BaseClass1 { public int Id { get ; set ; } public virtual B B { get ; set ; } } public class C2 : BaseClass2 { public int Id { get ; set ; } public virtual B B { get ; set ; } } ... public class C100 : BaseClass100 { public int Id { get ; set ; } public virtual B B { get ; set ; } } MyDbContext db=new MyDbContext ( ) ; Hash < int > bCollectionToDelete=GetBCollectionToDeleteHashSet ( ) ; var C1_db_collection= db.C1Collection.ToList ( ) ; foreach ( var c1Item in C1Collection ) { if ( bCollectionToDelete.Contains ( c1Item.refrenceIdToB ) { c1Item.refrenceIdToB=null ; } } var C2_db_collection= db.C2Collection.ToList ( ) ; foreach ( var c2Item in C1Collection ) { if ( bCollectionToDelete.Contains ( c2Item.refrenceIdToB ) { c2Item.refrenceIdToB=null ; } } ... var C100_db_collection= db.C100Collection.ToList ( ) ; foreach ( var c100Item in C100Collection ) { if ( bCollectionToDelete.Contains ( c100Item.refrenceIdToB ) { c100Item.refrenceIdToB=null ; } }
Ef code first complicate cascade delete scenario
C_sharp : I have 2 tables which have many-to-many relation.Code of entitiesI map this classes as many-to-many in the conform mapping.In xml this mapping compiles into this : The issue is that I can get categories from product entity , but when I try get products from category it 's does n't work and the list is empty . <code> public class Product : BaseEntity { public virtual string Name { get ; set ; } public virtual IList < Category > ProductCategory { get ; set ; } public virtual float Price { get ; set ; } public virtual string Description { get ; set ; } public virtual DateTime DateOfAdd { get ; set ; } public virtual float Discount { get ; set ; } public virtual int SaleCount { get ; set ; } public virtual byte [ ] Image { get ; set ; } } public class Category : BaseEntity { public virtual string Name { get ; set ; } public virtual string Description { get ; set ; } public virtual IList < Product > CategoryProducts { get ; set ; } public virtual void AddProduct ( Product product ) { this.CategoryProducts.Add ( product ) ; } public virtual void DeleteProduct ( Product product ) { this.CategoryProducts.Remove ( product ) ; } } relationalMapper.ManyToMany < Product , Category > ( ) ; < class name= '' Product '' > < id name= '' Id '' type= '' Int32 '' > < generator class= '' identity '' / > < /id > < property name= '' Name '' / > < list name= '' ProductCategory '' table= '' ProductCategory '' > < key column= '' product_key '' / > < list-index / > < many-to-many class= '' Category '' column= '' category_key '' / > < /list > < property name= '' Price '' / > < property name= '' Description '' / > < property name= '' DateOfAdd '' / > < property name= '' Discount '' / > < property name= '' SaleCount '' / > < property name= '' Image '' lazy= '' true '' / > < /class > < class name= '' Category '' > < id name= '' Id '' type= '' Int32 '' > < generator class= '' identity '' / > < /id > < property name= '' Name '' / > < property name= '' Description '' / > < list name= '' CategoryProducts '' table= '' ProductCategory '' inverse= '' true '' > < key column= '' category_key '' / > < list-index / > < many-to-many class= '' Product '' column= '' product_key '' / > < /list > < /class >
NHibernate relationship has an issue with two-directional getting data
C_sharp : I have seen some code for working with AD in this stackoverflow questionI am getting confused about the using statement . I thought that it was just used for things that you are worried could become memory leak , like a WebClient , or similar ... Anyway : when I reach the line var groups = user.GetAuthorizationGroups ( ) - user is null , so that line fails with a NullReference . When I mouse over it debugging it shows null , then shows Static Members , and has all the values . If I take the line out of using statement and just have var user = UserPrincipal.FindByIdentity ( context , `` username '' ) user is populated as required.So what 's going on ? ? ? Edit : I stuffed up and was sending a bogus username . Oddly though when I check the variables during debug , when you would expect user to be completely null if I sent the bogus userid , but it showed under user : null , static members , and there had values for what I was currently logged in as-so I thought it was to do with the using statement potentially.Cheers ! <code> using ( var context = new PrincipalContext ( ContextType.Domain ) ) { using ( var user = UserPrincipal.FindByIdentity ( context , `` username '' ) ) { var groups = user.GetAuthorizationGroups ( ) ; ... } }
Confused with C # 'using '
C_sharp : What is the meaning of `` new ( ) '' at the end of the above code ? <code> public interface ICrudService < T > where T : Entity , new ( )
C # code confusion of where clause
C_sharp : I want to write c # code to make a snapshot-backup if available . This is supported since SQL Server version 2005 but only in Enterprise edition but not in Express or Standard edition . My question : how to find out in C # if the connected server supports snapshot backup ( is Enterprise Edition 2005 or newer or some kind of `` hasFeature ( ... ) ) ? My current solution puts a try catch around the following code . If I catch a SqlException I assume there is no support on the connected server . But maybe there could be other reasons to fail although the database supports snapshots ( i.e . something is locked , connection is broken , ... ) The ideal solution would be some sqlCommand.ExecuteNonQuery ( ) to find out if the feature is supported.The second best is if I had to include some extra dll that can find it ( ? sqldmo ? ) but this would create an additional dependency to the project.The third best would be some kind of exception handling . <code> sqlCommand.CommandText = String.Format ( `` CREATE DATABASE { 0 } ON `` + ( NAME = { 1 } , FILENAME = \ '' { 2 } \ '' ) AS SNAPSHOT OF { 1 } '' , databaseBackupName , databaseName , filenameOfDatabseBackup ) ; sqlCommand.ExecuteNonQuery ( ) ;
Find out in C # if my SQL Server instance supports snapshots ?
C_sharp : I use this code for drawing text in a panel : So I want to know what size the input text will be when rendered in the panel . <code> Graphics g = panel1.CreateGraphics ( ) ; g.DrawString ( ... ) ;
Graphics in C # ( .NET )
C_sharp : We inherited a somewhat poorly-designed WCF service that we want to improve . One problem with it is that it has over a hundred methods ( on two different interfaces ) , most of which we suspect are not used . We decided to put some logging on each of the methods to track when and how they 're called . To make the tracing code refactor-friendly and typo-proof , we implemented it like so : LogUsage ( ) is then called at the start of each method we want to trace.The service is very high traffic , on the order of 500,000+ calls/day . 99.95 % of the time , this code executes beautifully . But the other 0.05 % of the time , GetInterfaces ( ) returns an empty ( but not null ) array . Why would GetInterfaces ( ) occasionally return inconsistent results ? This may seem so trivial - a 0.05 % error rate is something we can usually only dream of . But the whole point is to identify all the service touchpoints , and if this error is always coming out of one ( or a few ) method calls , then our tracing is incomplete . I 've tried to reproduce this error in my development environment by calling each and every method on the service , but to no avail . <code> public void LogUsage ( ) { try { MethodBase callingMethod = new StackTrace ( ) .GetFrame ( 1 ) .GetMethod ( ) ; string interfaceName = callingMethod.DeclaringType.GetInterfaces ( ) [ 0 ] .Name ; _loggingDao.LogUsage ( interfaceName , callingMethod.Name , GetClientAddress ( ) , GetCallingUrl ( ) ) ; } catch ( Exception exception ) { _legacyLogger.Error ( `` Error in usage tracking '' , exception ) ; } }
Why does Type.GetInterfaces ( ) sometimes not return a valid list ?
C_sharp : I am looking at the code from herewhat does param in param = > this.OnRequestClose ( ) refer to ? <code> /// < summary > /// Returns the command that , when invoked , attempts/// to remove this workspace from the user interface./// < /summary > public ICommand CloseCommand { get { if ( _closeCommand == null ) _closeCommand = new RelayCommand ( param = > this.OnRequestClose ( ) ) ; return _closeCommand ; } }
C # /Lambda : What does param in the following refer to ?
C_sharp : I have 2 sets of 2 classes where each pair has a super/sub-class relationship , and the orthogonal pair has a dependency relationship . What I am trying to determine is what to do with the constructors and/or bodies of the properties to keep the model as simple as possible with minimal data duplication.Here 's the structure in code : I have considered overriding the base properties in the sub-classes , but that does n't fit very cleanly because the properties in the sub-classes do n't have the same signature and so I would have to add properties.I have also considered setting the base property in the sub-class constructor and set methods , but there is no way for the sub-class property to be updated if the base-class 's property is updated.What other options are there , and which is the cleanest ( and why ) ? Note : The above code is greatly simplified to illustrate the problem . There are additional properties and methods on the real classes , but this subset is the essence of the trouble I 'm having . <code> public class Base1 { public List < Base2 > MyBase2Things { get ; set ; } // Do things with Base2 objects } public class Sub1 : Base1 { public List < Sub2 > MySub2Things { get ; set ; } // Do things with Sub2 objects and also with Base2 objects } public class Base2 { public Base1 MyBase1 { get ; set ; } // Do things with the Base1 object } public class Sub2 : Base2 { public Sub1 MySub1 { get ; set ; } // Do things with the Sub1 object }
How can I cleanly design a parallel inheritance structure in C # ?
C_sharp : I have a very basic Web API example that I constructed using the example code from this tutorial : CodeRelevant Web.config SectionRoute ConfigurationView ModelApiControllerand it 's leveraging ITSurveyEntities , which was a generated ADO.NET Entity Data Model from the database , which only contains a single table right now , Survey.In short , I do n't think I 'm trying to do anything special here.Current ResultWhen I try and navigate to the API using something like http : //localhost:1681/api/surveys , I get a response , but the file is named surveys with no extension . Further , if I try and Save As and give it say a txt extension , the download just fails.Expected ResultI would expect that the API would return a file names surveys.json , like the example project does with products , and the browser would ask me to open or save the file.What I 've TriedComparing Web.config FilesI have compared the Web.config files between my project and the example code from the tutorial that works.Comparing RoutingI have compared the routing configuration between my project and the example code from the tutorial that works.Excluding WebDavI 've tried to exclude WebDav because my searches have indicated that it might be the cause . I did that by modifying the Web.config in a manner that matches what 's on this blog.UPDATE 1Okay , after the guidance by Joe Enos I found that the issue was that the view model was named Survey also and so it was throwing an error about ambiguity between the CLR type and the EDM type.I resolved that by renaming the view model to SurveyViewModel , and the request to http : //localhost:1681/api/surveys now returns a HTTP 200 and downloads the file as expected . <code> < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < handlers > < remove name= '' ExtensionlessUrlHandler-ISAPI-4.0_32bit '' / > < remove name= '' ExtensionlessUrlHandler-ISAPI-4.0_64bit '' / > < remove name= '' ExtensionlessUrlHandler-Integrated-4.0 '' / > < add name= '' ExtensionlessUrlHandler-ISAPI-4.0_32bit '' path= '' * . '' verb= '' GET , HEAD , POST , DEBUG , PUT , DELETE , PATCH , OPTIONS '' modules= '' IsapiModule '' scriptProcessor= '' % windir % \Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll '' preCondition= '' classicMode , runtimeVersionv4.0 , bitness32 '' responseBufferLimit= '' 0 '' / > < add name= '' ExtensionlessUrlHandler-ISAPI-4.0_64bit '' path= '' * . '' verb= '' GET , HEAD , POST , DEBUG , PUT , DELETE , PATCH , OPTIONS '' modules= '' IsapiModule '' scriptProcessor= '' % windir % \Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll '' preCondition= '' classicMode , runtimeVersionv4.0 , bitness64 '' responseBufferLimit= '' 0 '' / > < add name= '' ExtensionlessUrlHandler-Integrated-4.0 '' path= '' * . '' verb= '' GET , HEAD , POST , DEBUG , PUT , DELETE , PATCH , OPTIONS '' type= '' System.Web.Handlers.TransferRequestHandler '' preCondition= '' integratedMode , runtimeVersionv4.0 '' / > < /handlers > < /system.webServer > public static class WebApiConfig { public static void Register ( HttpConfiguration config ) { config.Routes.MapHttpRoute ( name : `` DefaultApi '' , routeTemplate : `` api/ { controller } / { id } '' , defaults : new { id = RouteParameter.Optional } ) ; } } public class Survey { public int Id { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } } public class SurveysController : ApiController { public IEnumerable < Survey > All ( ) { using ( ITSurveyEntities model = new ITSurveyEntities ( ) ) { return new List < Survey > ( from s in model.Surveys select new Survey { Id = s.Id , Name = s.Name , Description = s.Description , } ) ; } } }
Why is the response from my Web API not formed properly ?
C_sharp : I 'm working on a Fluent Api for a service which is fairly configurable , and just trying to work my options for a neat solution for the following problem.I have a class something like thisAll well and good , However can any one think of a way to achieve the following without having to verbosely specify the second generic type given i.ei really am just interest in the result IDialogWithResult < TViewModel , TSomeReturnType > even if i have to do this in 2 statements So i can call I know all the information is there and declared at compile time , also i know this is Partial Inference and its all or nothing . However i just wondering if there is some trick without having to redeclare Moreover i have a method that needs ResultType as ( you guessed it ) a result type I mean , ResultType is really just superfluous at this point in the game as its already been declared by WindowVm . it would be nice if the consumer did n't have to go looking for it ( even if it meant more than one step ) <code> public class WindowVm : DialogResultBase < MyReturnType > public IDialogWithResult < TViewModel , TSomeReturnType > DialogWithResult < TViewModel , TSomeReturnType > ( object owner = null ) where TViewModel : DialogResultBase < TSomeReturnType > .DialogWithResult < WindowVm > ( ) .DialogWithResult < WindowVm , ResultType > ( ) ; ResultType MyResult = ... DialogWithResult < WindowVm , ResultType > ( ) .ShowModal ( ) ;
Generic type inference , Fluent Api , with pre-declared types
C_sharp : I have code like the following : Is there any way to avoid doing two lookups in the Dictionary -- the first time to see if contains an entry , and the second time to update the value ? There may even be two hash lookups on line ' B ' -- one to get the int value and another to update it . <code> class MyClass { string Name ; int NewInfo ; } List < MyClass > newInfo = ... . // initialize list with some valuesDictionary < string , int > myDict = ... . // initialize dictionary with some valuesforeach ( var item in newInfo ) { if ( myDict.ContainsKey ( item.Name ) ) // ' A ' I hash the first time here myDict [ item.Name ] += item.NewInfo // ' B ' I hash the second ( and third ? ) time here else myDict.Add ( item.Name , item.NewInfo ) ; }
Do I have to hash twice in C # ?
C_sharp : Count-based filtering without a time constraintHow to introduce inactivity reset ? But how to introduce a timeout TimeSpan tooLong so that the counting would restart from zero whenever the interval between two values exceeds this maximum ? <code> IObservable filteredStream = changes.Buffer ( 3 ) ;
reset count above max time interval , in Rx count-based aggregation
C_sharp : I was looking to write a simple desktop app and a corresponding mobile app , the scenario would be : I run the desktop app on my laptopI run the mobile app on my Lumia ( on the same wifi network ) The phone app somehow finds and connects to the desktop app ( I do n't want to have to manually find and type the ip ) The two can now communicateA very basic app like that would be sending simple text messages between the two.I guess an example app would be something like a `` remote control '' for your PC on your phone , one can be found on the market here.I started with looking at UDP multicast , and spent a day trying to get it to work . The idea would be both apps join the same multicast group , phone when joining sends a message to that group , PC picks it up and responds with it 's IP , phone then makes TCP connection to the desktop app . Sounds like a valid solution , right ? Well it seems like no matter what I tried , this would happen : Scenario : mobile app running on the actual phone connected to the same WiFi as PC app : messages are being sent but never arrive.Scenario : mobile app running on an emulator on the same PC as PC app : messages send and arrive.Here is a post with code when I tried to use sockets-for-pcl for that.Here is my attempt to use what 's already in .NET : PC - sending a message only : PHONE - receive only : However , after a day I gave up , since the documentation is scarce and debugging would require me to get some network scanning tools ... When I was searching on the internet for some libraries for Network Service Discovery I found some Android docs but nothing for Windows Phone 8.1 . So I guess my question would be : is there anything like that for Windows Phone ? Or if you spot anything wrong with my code , what do I have to change to get it to communicate ? Thanks . <code> UdpClient udp = new UdpClient ( port ) ; IPAddress group_ip = IPAddress.Parse ( `` 139.100.100.100 '' ) ; IPEndPoint client_ipep = new IPEndPoint ( group_ip , 3344 ) ; byte [ ] b = System.Text.Encoding.UTF8.GetBytes ( txtEntry.Text ) ; udp.Send ( b , b.Length , client_ipep ) ; HostName hostName = new HostName ( `` 139.100.100.100 '' ) ; DatagramSocket udp = new DatagramSocket ( ) ; udp.MessageReceived += ( sender , args ) = > { uint length = args.GetDataReader ( ) .ReadUInt32 ( ) ; string text = args.GetDataReader ( ) .ReadString ( length ) ; } ; await udp.BindServiceNameAsync ( `` 3344 '' ) ; udp.JoinMulticastGroup ( hostName ) ;
Network Service Discovery on Windows Phone
C_sharp : A co-worker showed me a very strange behavior and I 'd like to know if someone could explain me why.A basic constructor with 2 string params : Method is : When this ctor is called within an aspx page with str2 as null , all works fine because if an operand of string concatenation + is null , an empty string is substituted.But when this ctor is called with str2 as null in a background thread , a NullReferenceException is fired.The problem was solved by testing str2 ! = null before using it , but I 'd really like to know why the same code sometimes fires an exception , sometimes not ! Here is the stack trace : <code> public MyClass ( string str1 , string str2 ) { this.s1 = str1 ; this.s2 = str2 ; this.s3 = Method ( str2 + `` ._className '' , str1 ) ; } public string Method ( string key , string defaultValue ) { List < string > list = _vars [ key ] ; if ( list == null ) return defaultValue ; string res = `` '' ; foreach ( string s in list ) { if ( res ! = `` '' ) res += `` , '' ; res += s ; } return res ; } Exception : System.NullReferenceException Message : Object reference not set to an instance of an object.StackTrace : at MyClass..ctor ( String str1 , String str2 ) at AbandonedCartsNotificationJob.NotifyAbandonedCarts ( ) in AbandonedCartsNotificationJobPartial.cs : line 39 at AbandonedCartsNotificationJob.work ( ) in AbandonedCartsNotificationJob.cs : line 15 at MyRuntime.JobManager.run ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.runTryCode ( Object userData ) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup ( TryCode code , CleanupCode backoutCode , Object userData ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( )
+ string concat operator with a null operand
C_sharp : I 've got some code I 'm maintaining that has a good deal of machine generated comments and machine generated regions . ( or created by a particularly misled developer ) These are comments exclusively repeating the method metadata and space expansions of pascal cased names : Is there a plug in or feature of Resharper for stripping out the comments and # region tags in bulk ? <code> # region methods/// < summary > /// Implementation of a public method foo bar , returning a void/// < /summary > /// < param name= '' value '' > A string parameter named value input < /param > public void fooBar ( string valueInput ) { } # endregion
How to strip out robo-comments and # region from C # ?
C_sharp : I have two string lists which have same size.I want to create a dictionary , the key is from listA , the value is from listB.What is the fast way ? I used the code : I do n't like this way , can I use ToDictionary method ? <code> List < string > ListA ; List < string > ListB ; Dictionary < string , string > dict = new Dictionary < string , string > ( ) ; for ( int i=0 ; i < ListA.Count ; i++ ) { dict [ key ] = listA [ i ] ; dict [ value ] = listB [ i ] ; }
Use ToDictionary to create a dictionary
C_sharp : I have a search page which contains two search result types : summary result and concrete result.Summary result page contains top 3 result per category ( top hits ) Concrete result page contains all result for a selected category.To obtain the Summary page I use the request : And I get result , for exampleSo i get few hits with the same _score.To obtain the concrete result ( by category ) page I use the request : And the result something like this : And so in the second case , for a specific category I get the _score with great precision and elastic can easily sort the results correctly . But in the case of aggregation there are results with the same _score , and in this case , the sorting is not clear how it works.Can someone direct me to the right path how to solve this problem ? or how can I achieve the same order in the results ? Maybe I can increase the accuracy for the aggregated results ? I use elasticsearch server version `` 5.3.0 '' and NEST library version `` 5.0.0 '' .Update : Native query for aggregation request : Native query for concrete request : Also i use next mapping for creating index : <code> var searchDescriptor = new SearchDescriptor < ElasticType > ( ) ; searchDescriptor.Index ( `` index_name '' ) .Query ( q = > q.MultiMatch ( m = > m .Fields ( fs = > fs .Field ( f = > f.Content1 , 3 ) .Field ( f = > f.Content2 , 2 ) .Field ( f = > f.Content3 , 1 ) ) .Fuzziness ( Fuzziness.EditDistance ( 1 ) ) .Query ( query ) .Boost ( 1.1 ) .Slop ( 2 ) .PrefixLength ( 1 ) .MaxExpansions ( 100 ) .Operator ( Operator.Or ) .MinimumShouldMatch ( 2 ) .FuzzyRewrite ( RewriteMultiTerm.ConstantScoreBoolean ) .TieBreaker ( 1.0 ) .CutoffFrequency ( 0.5 ) .Lenient ( ) .ZeroTermsQuery ( ZeroTermsQuery.All ) ) & & ( q.Terms ( t = > t.Field ( f = > f.LanguageId ) .Terms ( 1 ) ) || q.Terms ( t = > t.Field ( f = > f.LanguageId ) .Terms ( 0 ) ) ) ) .Aggregations ( a = > a .Terms ( `` category '' , tagd = > tagd .Field ( f = > f.Category ) .Size ( 10 ) .Aggregations ( aggs = > aggs.TopHits ( `` top_tag_hits '' , t = > t.Size ( 3 ) ) ) ) ) .FielddataFields ( fs = > fs .Field ( p = > p.Content1 , 3 ) .Field ( p = > p.Content2 , 2 ) .Field ( p = > p.Content3 , 1 ) ) ; var elasticResult = _elasticClient.Search < ElasticType > ( _ = > searchDescriptor ) ; { `` aggregations '' : { `` category '' : { `` doc_count_error_upper_bound '' : 0 , `` sum_other_doc_count '' : 0 , `` buckets '' : [ { `` key '' : `` category1 '' , `` doc_count '' : 40 , `` top_tag_hits '' : { `` hits '' : { `` total '' : 40 , `` max_score '' : 5.4 , `` hits '' : [ { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 5.4 , `` _source '' : { `` id '' : 1 } } , { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 4.3 , `` _source '' : { `` id '' : 3 // FAIL ! } } , { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 4.3 , `` _source '' : { `` id '' : 2 } } ] } } } ] } } } var searchDescriptor = new SearchDescriptor < ElasticType > ( ) ; searchDescriptor.Index ( `` index_name '' ) .Size ( perPage < = 0 ? 100 : perPage ) .From ( page * perPage ) .Query ( q = > q .MultiMatch ( m = > m .Fields ( fs = > fs .Field ( f = > f.Content1 , 3 ) .Field ( f = > f.Content2 , 2 ) .Field ( f = > f.Content3 , 1 ) .Field ( f = > f.Category ) ) .Fuzziness ( Fuzziness.EditDistance ( 1 ) ) .Query ( searchRequest.Query ) .Boost ( 1.1 ) .Slop ( 2 ) .PrefixLength ( 1 ) .MaxExpansions ( 100 ) .Operator ( Operator.Or ) .MinimumShouldMatch ( 2 ) .FuzzyRewrite ( RewriteMultiTerm.ConstantScoreBoolean ) .TieBreaker ( 1.0 ) .CutoffFrequency ( 0.5 ) .Lenient ( ) .ZeroTermsQuery ( ZeroTermsQuery.All ) ) & & q.Term ( t = > t.Field ( f = > f.Category ) .Value ( searchRequest.Category ) ) & & ( q.Terms ( t = > t.Field ( f = > f.LanguageId ) .Terms ( 1 ) ) || q.Terms ( t = > t.Field ( f = > f.LanguageId ) .Terms ( 0 ) ) ) ) .FielddataFields ( fs = > fs .Field ( p = > p.Content1 , 3 ) .Field ( p = > p.Content2 , 2 ) .Field ( p = > p.Content3 , 1 ) ) .Aggregations ( a = > a .Terms ( `` category '' , tagd = > tagd .Field ( f = > f.Category ) ) ) ; { `` hits '' : { `` total '' : 40 , `` max_score '' : 7.816723 , `` hits '' : [ { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 7.816723 , `` _source '' : { `` id '' : 1 } } , { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 6.514713 , `` _source '' : { `` id '' : 2 } } , { `` _index '' : `` ... '' , `` _type '' : `` ... '' , `` _id '' : `` ... '' , `` _score '' : 6.514709 , `` _source '' : { `` id '' : 3 } } ] } } { `` fielddata_fields '' : [ `` content1^3 '' , `` content2^2 '' , `` content3^1 '' ] , `` aggs '' : { `` category '' : { `` terms '' : { `` field '' : `` category '' , `` size '' : 10 } , `` aggs '' : { `` top_tag_hits '' : { `` top_hits '' : { `` size '' : 3 } } } } } , `` query '' : { `` bool '' : { `` must '' : [ { `` multi_match '' : { `` boost '' : 1.1 , `` query '' : `` sparta '' , `` fuzzy_rewrite '' : `` constant_score_boolean '' , `` fuzziness '' : 1 , `` cutoff_frequency '' : 0.5 , `` prefix_length '' : 1 , `` max_expansions '' : 100 , `` slop '' : 2 , `` lenient '' : true , `` tie_breaker '' : 1.0 , `` minimum_should_match '' : 2 , `` operator '' : `` or '' , `` fields '' : [ `` content1^3 '' , `` content2^2 '' , `` content3^1 '' ] , `` zero_terms_query '' : `` all '' } } , { `` bool '' : { `` should '' : [ { `` terms '' : { `` languageId '' : [ 1 ] } } , { `` terms '' : { `` languageId '' : [ 0 ] } } ] } } ] } } } { `` from '' : 0 , `` size '' : 100 , `` fielddata_fields '' : [ `` content1^3 '' , `` content2^2 '' , `` content3^1 '' ] , `` aggs '' : { `` category '' : { `` terms '' : { `` field '' : `` category '' } } } , `` query '' : { `` bool '' : { `` must '' : [ { `` bool '' : { `` must '' : [ { `` multi_match '' : { `` boost '' : 1.1 , `` query '' : `` ... .. '' , `` fuzzy_rewrite '' : `` constant_score_boolean '' , `` fuzziness '' : 1 , `` cutoff_frequency '' : 0.5 , `` prefix_length '' : 1 , `` max_expansions '' : 100 , `` slop '' : 2 , `` lenient '' : true , `` tie_breaker '' : 1.0 , `` minimum_should_match '' : 2 , `` operator '' : `` or '' , `` fields '' : [ `` content1^3 '' , `` content2^2 '' , `` content3^1 '' , `` category '' ] , `` zero_terms_query '' : `` all '' } } , { `` term '' : { `` category '' : { `` value '' : `` category1 '' } } } ] } } , { `` bool '' : { `` should '' : [ { `` terms '' : { `` languageId '' : [ 1 ] } } , { `` terms '' : { `` languageId '' : [ 0 ] } } ] } } ] } } } var descriptor = new CreateIndexDescriptor ( indexName ) .Mappings ( ms = > ms .Map < ElasticType > ( m = > m .Properties ( ps = > ps .Keyword ( s = > s.Name ( ecp = > ecp.Title ) ) .Text ( s = > s.Name ( ecp = > ecp.Content1 ) ) .Text ( s = > s.Name ( ecp = > ecp.Content2 ) ) .Text ( s = > s.Name ( ecp = > ecp.Content3 ) ) .Date ( s = > s.Name ( ecp = > ecp.Date ) ) .Number ( s = > s.Name ( ecp = > ecp.LanguageId ) .Type ( NumberType.Integer ) ) .Keyword ( s = > s.Name ( ecp = > ecp.Category ) ) .Text ( s = > s.Name ( ecp = > ecp.PreviewImageUrl ) .Index ( false ) ) .Text ( s = > s.Name ( ecp = > ecp.OptionalContent ) .Index ( false ) ) .Text ( s = > s.Name ( ecp = > ecp.Url ) .Index ( false ) ) ) ) ) ; _elasticClient.CreateIndex ( indexName , _ = > descriptor ) ;
ElasticSearch - different result ordering for simple request and aggregation request ( NEST )
C_sharp : I have a program that processes high volumes of data , and can cache much of it for reuse with subsequent records in memory . The more I cache , the faster it works . But if I cache too much , boom , start over , and that takes a lot longer ! I have n't been too successful trying to do anything after the exception occurs - I ca n't get enough memory to do anything . Also I 've tried allocating a huge object , then de-allocating it right away , with inconsistent results . Maybe I 'm doing something wrong ? Anyway , what I 'm stuck with is just setting a hardcoded limit on the # of cached objects that , from experience , seems to be low enough . Any better Ideas ? thanks.edit after answerThe following code seems to be doing exactly what I want : I need to test if it is slowing things down in this arrangement or not , but I can see the yellow line in Task Manager looking like a very healthy sawtooth pattern with a consistent top - yay ! ! <code> Loop Dim memFailPoint As MemoryFailPoint = Nothing Try memFailPoint = New MemoryFailPoint ( mysize ) `` // size of MB of several objects I 'm about to add to cache memFailPoint.Dispose ( ) Catch ex As InsufficientMemoryException `` // dump the oldest items here End Try `` // do worknext loop .
How do I know if I 'm about to get an OutOfMemoryException ?
C_sharp : While I try to run following code snippet , it ’ s executing wrong overload method . I 'm confused why it does that ? [ testB.TestMethod ( testValue ) method execute the public double TestMethod ( double value ) method ] Do you have any idea about this ? Is there are any way to call TestA class method via the TestB instance without cast as TestA . ? But it is not happen in JAVA and C++ <code> public class TestA { public int TestMethod ( int value ) { return value ; } } public class TestB : TestA { public double TestMethod ( double value ) { return value ; } } static void Main ( string [ ] args ) { TestB testB = new TestB ( ) ; int testValue = 3 ; testB.TestMethod ( testValue ) ; }
Why does the compiler cast automatically without going further in the inheritance ?
C_sharp : I have made a server and a client in C # which transfers files . But when transferring it pauses for some seconds and then continues . I have uploaded a video on YouTube to demonstrate : http : //www.youtube.com/watch ? v=GGRKRW6ihLoAs you can see it sometime pauses and then continues.Receiver : Sender : <code> using ( var writer = new StreamWriter ( Path.Combine ( _localPath , file.FileName ) ) ) { var buffer = new byte [ _bufferSize ] ; while ( file.Transferred < file.Size & & _active ) { int read = ns.Read ( buffer , 0 , _bufferSize ) ; writer.BaseStream.Write ( buffer , 0 , read ) ; file.Transferred += read ; } writer.Close ( ) ; } using ( var reader = new StreamReader ( file.FilePath ) ) { var buffer = new byte [ _bufferSize ] ; while ( file.Transferred < file.Size & & _active ) { int read = reader.BaseStream.Read ( buffer , 0 , _bufferSize ) ; ns.Write ( buffer , 0 , read ) ; file.Transferred += read ; } reader.Close ( ) ; }
Network transfer pauses
C_sharp : Extension methods with . operator always called , even if object is null without throwing NullReferenceException . By using operator ? . it will never called . For example : Why extension method is n't called in this case ? Is this an ambiguos feature ? <code> using System ; public class Program { public static void Main ( ) { A a = null ; a.b ( ) ; // works a ? .b ( ) ; // does n't work } } public class A { } public static class ext { public static void b ( this A a ) { Console.WriteLine ( `` I 'm called '' ) ; } }
Operator ? . and extension methods
C_sharp : I have a class like this : Somewhere else I 'm using it : I thought it will returns S , but it throw exception . Any idea what is going on ? <code> class MyClass { public object [ ] Values ; } MyClass myInstance = new MyClass ( ) { Values = new object [ ] { `` S '' , 5 , true } } ; List < Func < MyClass , object > > maps = new List < Func < MyClass , object > > ( ) ; for ( int i = 0 ; i < myInstance.Values.Length ; i++ ) { maps.Add ( obj = > obj.Values [ i ] ) ; } var result = maps [ 0 ] ( myInstance ) ; //Exception : Index outside the bounds of the array
Index was outside the bounds of array when using List < Func < T , object > >
C_sharp : Okay , this is probably very simple but , I have the below `` checks '' ( not at the same time ) and the First ALWAYS evaluates to TRUE while the Second SEEMS to work . This actually happens in each place that the row value is a number or bool ( Date seems fine ... ) . If I walk through the code in Debug it shows the value of row [ `` PersonID '' ] as 162434 , the same as tbxPersonID.EditValue . Is this just a basic and beginner truth about programming that I missed in my hodge-podge-self-education ? It seems , if I cast everything in question to a string first , I will be fine I would just like to know if I am correct and if there is a general rule as to what Types I would need to do this for ? Does n't WorkWorks <code> if ( row [ `` PersonID '' ] ! = tbxPersonID.EditValue ) { row [ `` PersonID '' ] = tbxPersonID.EditValue ; } if ( row [ `` CitizenFlag '' ] ! = chkCitizen.EditValue ) { row [ `` CitizenFlag '' ] = chkCitizen.EditValue ; _whatChanged.Add ( `` CitizenFlag '' ) ; } if ( row [ `` PersonID '' ] .ToString ( ) ! = tbxPersonID.EditValue.ToString ( ) ) { row [ `` PersonID '' ] = tbxPersonID.EditValue ; } if ( row [ `` CitizenFlag '' ] .ToString ( ) ! = chkCitizen.EditValue.ToString ( ) ) { row [ `` CitizenFlag '' ] = chkCitizen.EditValue ; _whatChanged.Add ( `` CitizenFlag '' ) ; }
Comparing expressions of type object
C_sharp : How do I enable allowed services : WINDOWS AZURE SERVICES as seen in the Management Portal in c # ? <code> _client = new SqlManagementClient ( GetSubscriptionCredentials ( ) ) ; var result = _client.Servers.CreateAsync ( new ServerCreateParameters { AdministratorUserName = _config.ServerUserName , AdministratorPassword = _config.ServerPassword , Location = _config.Location , Version = `` 12.0 '' } , CancellationToken.None ) .Result ; var sqlServerName = result.ServerName ; // This will go away once we can enable the Azure internal firewall settings == Yes var ipAddress = _firewallManagement.GetPublicIP ( ) ; var firewall = _client.FirewallRules.Create ( sqlServerName , new FirewallRuleCreateParameters ( `` Server '' , ipAddress , ipAddress ) ) ;
How do enable internal Azure Services for SQL Azure in c #
C_sharp : Given that I have three tables ( Customer , Orders , and OrderLines ) in a Linq To Sql model where Customer -- One to Many - > Orders -- One to Many - > OrderLinesWhen I useI see one query getting the customer , that makes sense . Then I see a query for the customer 's orders and then a single query for each order getting the order lines , rather than joining the two . Total of n + 1 queries ( not counting getting customer ) But if I useThen instead of seeing a single query for each order getting the order lines , I see a single query joining the two tables . Total of 1 query ( not counting getting customer ) I would prefer to use the first Linq query as it seems more readable to me , but why is n't L2S joining the tables as I would expect in the first query ? Using LINQPad I see that the second query is being compiled into a SelectMany , though I see no alteration to the first query , not sure if that 's a indicator to some problem in my query . <code> var customer = Customers.First ( ) ; var manyWay = from o in customer.CustomerOrders from l in o.OrderLines select l ; var tableWay = from o in Orders from l in OrderLines where o.Customer == customer & & l.Order == o select l ;
How can I make this SelectMany use a Join ?
C_sharp : When I use a foreach loop in C # , it appears that no compile time type checking is performed if the item type is an interface type.E.g.This will happily compile and cause an exception at runtime , when it is clear at compile time this makes no sense . If I change the item type from SomeInterface to another class , then compile time type-checking is restored : Why is there no compile time type checks when the item type is an interface ? ( This occurs with .NET 3.5 SP1 in Visual Studio 2008 ) <code> class SomeClass { } interface SomeInterface { } IEnumerable < SomeClass > stuff ; foreach ( SomeInterface obj in stuff ) { // This compiles - why ! ? } IEnumerable < SomeClass > stuff ; foreach ( Random obj in stuff ) { // This does n't compile - good ! }
Why does foreach skip compile time type checking on interface types ?
C_sharp : Consider this code in a project : This works like a charm . However , as soon as you separate these two functions into two different projects , the code breaks : The error I get in the second case is : object ' does not contain a definition for 'Name ' ( RuntimeBinderException ) Why do I get this error ? What 's the alternative method ? How can I pass a dynamic parameter to a method in another library , and use it there in a simple way ? Note : I 'm familiar with ExpandoObject and I do n't want to use that . <code> static void Main ( string [ ] args ) { DoSomething ( new { Name = `` Saeed '' } ) ; } public static void DoSomething ( dynamic parameters ) { Console.WriteLine ( parameters.Name ) ; } // This code is in a Console Applicationstatic void Main ( string [ ] args ) { ExternalClass.DoSomething ( new { Name = `` Saeed '' } ) ; } // However , this code is in a Class Library ; Another projectpublic class ExternalClass { public static void DoSomething ( dynamic parameters ) { Console.WriteLine ( parameters.Name ) ; } }
Why this dynamic parameter is not working ?
C_sharp : I ’ m making a bot that can test some card tactics on a game , the bot works but I have one problem . My card shake method is not very good . I shake the cards this way : The problem is when I calculate without a pause between the card shake process , a few players will win a lot of games . For exampleBut when I add a dialog before the card shake process the wins will get spread over the players : I guess that the Random class is not good enough for a brute force like this . How can I shuffle the cards without a problem like this ? Update : I already tried to use 1 Random class , and I also tried to shake the cards only once . <code> public void ShuffelDeck ( ) { for ( int i = 0 ; i < 5 ; i++ ) Cards = ShuffelCards ( Cards ) ; } private ArrayList ShuffelCards ( ArrayList Cards ) { ArrayList ShuffedCards = new ArrayList ( ) ; Random SeedCreator = new Random ( ) ; Random RandomNumberCreator = new Random ( SeedCreator.Next ( ) ) ; while ( Cards.Count ! = 0 ) { int RandomNumber = RandomNumberCreator.Next ( 0 , Cards.Count ) ; ShuffedCards.Insert ( ShuffedCards.Count , Cards [ RandomNumber ] ) ; Cards.RemoveAt ( RandomNumber ) ; } return ShuffedCards ; } Player 1 : 8 gamesPlayer 2 : 2 gamesPlayer 3 : 0 gamesPlayer 4 : 0 games Player 1 : 3 gamesPlayer 2 : 2 gamesPlayer 3 : 1 gamePlayer 4 : 4 games
Brute force Card shake method in C #
C_sharp : I would like to be able to generate a ( pseudo ) random number from n possible ranges , where a range is x , y and x < y . For example , executing this code : will produce something like : The signature of the method NextRanges is : And Range is defined as : The only thing I 'm not sure on is how to implement NextRanges , what the most efficient way or the most random way is ( I know random can be tricky sometimes ) . Would you choose a random Range and then use Random.Next ( ) on that ? Or would you keep choosing random numbers until you got one that was within each of the ranges ? Is it also possible to weight the ranges so that a range of 0-100 has far more weight than a range of 100-102 , for example ? <code> for ( int i = 0 ; i < 10 ; i++ ) { Console.Write ( Random.NextRanges ( new Range ( 1 , 6 ) , new Range ( 10 , 16 ) , new Range ( 20 , 31 ) ) + `` `` ) ; } 3 12 5 22 1 27 29 5 10 24 public static int NextRanges ( params Range [ ] ranges ) public struct Range { public int X ; public int Y ; public Range ( int x , int y ) { if ( x > = y ) throw new ArgumentException ( `` x must be less than y . `` ) ; X = x ; Y = y ; } }
How can I get a single random number from multiple possible ranges ?
C_sharp : I have two methods like this : I want to extract the Write ( ) and Clear ( ) methods to a new method ( Action ) to have something like this : The Write ( ) and Clear ( ) will be defined in Execute ( ) just one time.What 's the right syntax to do so ? <code> public void ExecuteA ( ) { Write ( ) ; // A specific work Clear ( ) ; } public void ExecuteB ( ) { Write ( ) ; // B specific work Clear ( ) ; } public ASpecificWork ( ) { // do A work } public BSpecificWork ( ) { // do B work } Execute ( BSpecificWork ) ; Execute ( ASpecificWork ) ;
C # Action syntax
C_sharp : I 'm a pretty big newbie when it comes to optimization . In the current game I 'm working on I 've managed to optimize a function and shave about 0.5 % of its CPU load and that 's about as 'awesome ' as I 've been.My situation is as follows : I 've developed a physics heavy game in MonoTouch using an XNA wrapper library called ExEn and try as I might I 've found it very hard to get the game to reach a playable framerate on an iPhone4 ( do n't even want to think about iPhone3GS at this point ) .The performance degradation is almost certainly in the physics calculations , if I turn physics off the framerate jumps up sharply , if I disable everything , rendering , input , audio and just leave physics on performance hovers around 15fps during physics intensive situations.I used Instruments to profile the performance and this is what I got : http : //i.imgur.com/FX25h.png The functions which drain the most performance are either from the physics engine ( Farseer ) or the ExEn XNA wrapper functions they call ( notably Vector2.Max , Vector2.Min ) .I looked into those functions and I know wherever it can Farseer is passing values by reference into those functions rather than by value so that 's that covered ( and it 's literally the only way I can think of . The functions are very simple themselves basically amounting to such operations as Basically I feel like I 'm stuck and in my limited capacity and understanding of code optimizations I 'm not sure what my options are or if I even have any options ( maybe I should just curl into a fetal position and cry ? ) . With LLVM turned on and built in release I 'm getting maybe 15fps at best . I did manage to bring the game up to 30fps by lowering the physics precision but this makes many levels simply unplayable as bodies intersect one another and collapse in on themselves.So my question is , is this a lost cause or is there anything I can do to beef up performance ? <code> return new Vector2 ( Max ( v1.x , v2.x ) , Max ( v1.y , v2.y ) )
Optimization of a GC language , any ideas ?
C_sharp : Suppose I writeThe sequence produced is 1 1 2 1 2 3 as expected . But now if I writeNow the sequence produced is 1 1 2 1 2 1 3 2 3 4 instead of what one would expect 1 1 2 1 2 3 1 2 3 4 . Why is that ? Does SelectMany ( ) do some kind of multithreaded merge ? <code> var gen = Observable.Range ( 1 , 3 ) .SelectMany ( x = > Observable.Range ( 1 , x ) ) ; var gen = Observable.Range ( 1 , 4 ) .SelectMany ( x = > Observable.Range ( 1 , x ) ) ;
Why are these Rx sequences out of order ?
C_sharp : I 've run into an issue with stringbuilder which I ca n't seem to solve . To simplify the problem I create the following method : It should just add that line 1500 times , and afterwards combine it to a string and return it . However instead of just combining it corrupts the content . Somewhere in the middle of the result you 'll find the text : The project is a simple Console . I 've also tried all other solutions to check if this is possible some other way , like : Writing the text to file ( same corruption and breaks off to early ) Writing it to a memory stream and reading that ( same corruption ) Using a List and joining that ( same corruption ) Just using += on a string ( same corruption ) using string.concat ( same corruption ) All my colleagues I asked are running into the same issue as well , so it should not be PC related . Does anybody have a clue what is happening here ? <code> private static string TestBigStrings ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 1 ; i < 1500 ; i++ ) { string line = `` This is a line is n't too big but breaks when we add to many of it . `` ; builder.AppendLine ( line ) ; } return builder.ToString ( ) ; } This is a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of ... s a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of it . This is a line is n't too big but breaks when we add to many of it .
C # Stringbuilder corrupting content when adding lots of text
C_sharp : I have a small WPF application which has a window with an Image control . Image control shows an image from File system . I want user to be able to drag the image and drop to its desktop or anywhere to save it . It 's working fine.But I want to show small image thumbnail along with mouse cursor when user drags it . Just like we drag an image from Windows file explorer to some where else . How to achieve it ? Current Behavior of Drag/DropDesired BehaviorHere is my XAML CodeHere is C # Code <code> < Grid > < Image x : Name= '' img '' Height= '' 100 '' Width= '' 100 '' Margin= '' 100,30,0,0 '' / > < /Grid > public partial class MainWindow : Window { string imgPath ; Point start ; bool dragStart = false ; public MainWindow ( ) { InitializeComponent ( ) ; imgPath = `` C : \\Pictures\\flower.jpg '' ; ImageSource imageSource = new BitmapImage ( new Uri ( imgPath ) ) ; img.Source = imageSource ; window.PreviewMouseMove += Window_PreviewMouseMove ; window.PreviewMouseUp += Window_PreviewMouseUp ; window.Closing += Window_Closing ; img.PreviewMouseLeftButtonDown += Img_PreviewMouseLeftButtonDown ; } private void Window_Closing ( object sender , System.ComponentModel.CancelEventArgs e ) { window.PreviewMouseMove -= Window_PreviewMouseMove ; window.PreviewMouseUp -= Window_PreviewMouseUp ; window.Closing -= Window_Closing ; img.PreviewMouseLeftButtonDown -= Img_PreviewMouseLeftButtonDown ; } private void Window_PreviewMouseMove ( object sender , MouseEventArgs e ) { if ( ! dragStart ) return ; if ( e.LeftButton ! = MouseButtonState.Pressed ) { dragStart = false ; return ; } Point mpos = e.GetPosition ( null ) ; Vector diff = this.start - mpos ; if ( Math.Abs ( diff.X ) > SystemParameters.MinimumHorizontalDragDistance & & Math.Abs ( diff.Y ) > SystemParameters.MinimumVerticalDragDistance ) { string [ ] file = { imgPath } ; DataObject d = new DataObject ( ) ; d.SetData ( DataFormats.Text , file [ 0 ] ) ; d.SetData ( DataFormats.FileDrop , file ) ; DragDrop.DoDragDrop ( this , d , DragDropEffects.Copy ) ; } } private void Img_PreviewMouseLeftButtonDown ( object sender , MouseButtonEventArgs e ) { this.start = e.GetPosition ( null ) ; dragStart = true ; } private void Window_PreviewMouseUp ( object sender , MouseButtonEventArgs e ) { dragStart = false ; } }
Showing Image thumbnail with mouse cursor while dragging
C_sharp : In static OOP languages , interfaces are used in order to declare that several classes share some logical property - they are disposable , they can be compared to an int , they can be serialized , etc.Let 's say .net did n't have a standard IDisposable interface , and I 've just came up with this beautiful idea : My app uses a lot of System.Windows.Forms , and I think that a Form satisfies the logical requirements for being an IDiscardable . The problem is , Form is defined outside of my project , so C # ( and Java , C++ ... ) wo n't allow me to implement IDiscardable for it . C # does n't allow me to formally represent the fact that a Form can be discarded ( and I 'll probably end up with a MyForm wrapper class or something . In contrast , Haskell has typeclasses , which are logically similar to interfaces . A Show instance can be presented ( or serialized ) as a string , Eq allows comparisons , etc . But there 's one crucial difference : you can write a typeclass instance ( which is similar to implementing an interface ) without accessing the source code of a type . So if Haskell supplies me with some Form type , writing an Discardable instance for it is trivial.My question is : from a language designer perspective , is there any advantage to the first approach ? Haskell is not an object oriented language - does the second approach violates OOP in any way ? Thanks ! <code> interface IDiscardable { void Discard ( ) ; }
Is there any advantage in disallowing interface implementation for existing classes ?
C_sharp : I have a litte problem on Console.WriteLine ( ) . I have my while ( true ) loop that would check the data if exist and it would allow checking the data 3 times . And inside my loop I have this message : Console.WriteLine ( string.format ( `` Checking data { 0 } '' , ctr ) ) ; Here 's my sample code below : Let 's assume that data was not found.My current output show like this : But the correct output that I should want to achieve should looks like this : I would show only in one line.Edit : I forgot : In addition to my problem I want to append `` Not Found '' and `` Found '' .Here 's the sample Output : if data found on the First loop output looks like this.Checking data 1 ... Found ! if data found on the Second loop output looks like this.Checking data 1 ... 2 ... Found ! if data found on the Third loop output looks like this.Checking data 1 ... 2 ... 3 ... Found ! AND If data not foundChecking data 1 ... 2 ... 3 ... Not Found ! <code> int ctr = 0 ; while ( true ) { ctr += 1 ; Console.WriteLine ( string.format ( `` Checking data { 0 } ... '' , ctr ) ) if ( File.Exist ( fileName ) ) break ; if ( ctr > 3 ) break ; } Checking data 1 ... Checking data 2 ... Checking data 3 ... Checking data 1 ... 2 ... 3 ...
Problems with console output in C #
C_sharp : I 'm using Swashbuckle.AspNetCore ( 4.0.1 ) to generate a simple SwaggerUI for testing like it 's described here . My ApiController have two routes : The SwaggerUI displays all controller endpoints two times ( one with systemId , one without systemId ) . This is good , but the problem is , when I click on e.g /api/values/example SwaggerUI expands api/ { systemId } /values/example too . Both endpoints are going to the same public C # method inside the controller , it makes sense why SwaggerUI opens both . But it 's annoying and confusing . Is it possible to stop this behavior ? <code> [ Route ( `` api/values '' ) ] [ Route ( `` api/ { systemId } /values '' ) ]
.NET Core API : Disable multiple route expanding in SwaggerUI
C_sharp : In the C # specification ( 17.2 ) it indicates there are several attribute targets when specifying an attribute . This is common when you need to apply an attribute to something that does n't often have a `` real '' place to specify an attribute . For example , the return target is used often in platform Invoke : However I noticed that there are other attribute targets , like method : Under what circumstances would I need to explicitly define the method attribute target ( say to resolve ambiguity ) , or is it just there for the sake of completeness ? <code> [ return : MarshalAs ( UnmanagedType.Bool ) ] static extern bool SomeWin32Method ( ) ; //Assume this is valid , has a DllImport , etc . [ method : DllImport ( `` somelib.dll '' ) ] static extern bool SomeWin32Method ( ) ;
What is the purpose of the method attribute-target ?
C_sharp : I have the following piece of reduced CIL code.When this CIL method is executed , an InvalidProgramException is being thrown by the CLR : My question is , why is this CIL code invalid ? Several obervations : - If localloc is removed , the code runs fine . To my knowledge , localloc replaces the parameter size on the stack with an address , so the stack remains balanced , AFAICT.- If the try and finally blocks are removed , the code runs fine.- If the first block of instructions containing localloc is moved to after the try-finally block , the code runs fine.So it seems like something in the combination of localloc and the try-finally.Some background : I got to this point after the InvalidProgramException was thrown for the original method , due to some instrumentation made in runtime . My approach for debugging this , for figuring out what is wrong with the instrumentation , is : Disassembling the faulty DLL with ildasm Applying the instrumentation code to the crashing method Recreating the DLL from the modified IL with ilasm Running the program again , and verifying it crashesKeep reducing the IL code of the crashing method gradualy , down to the minimal scenario that causes the problem ( and trying not to introduce bugs along the way ... ) Unfortunately , peverify.exe /IL did not indicate any error.I tried to console the ECMA spec and Serge Lidin 's Expert .NET IL book , but could n't figure out what is it that goes wrong.Is there something basic I am missing ? Edit : I slightly updated the IL code in question , to make it more complete ( without modifying instructions ) . The second block of instructions , including ldarg , newobj , etc. , is taken as is from the working code - the original method code.What 's weird to me is , by removing either localloc or .try-finally , the code works - but none of these , to my knowledge , should change the balancing of the stack , compared to if they 're present in the code.Here 's the IL code decompiled into C # with ILSpy : Edit 2 : More observations : - Taking the localloc block of IL code , and moving it to the end of the function , code runs fine - so it seems that code on its own is OK. - The issue does not reproduce when pasting similar IL code into a hello world test function.I 'm very puzzled ... I wish there was a way to get more information from the InvalidProgramException . It seems that the CLR does n't attach the exact failure reason to the exception object.I also thought on debugging with CoreCLR debug build , but unforunately the program I 'm debugging is not compatible with it ... <code> .method assembly hidebysig specialname rtspecialname instance void .ctor ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < class System.Windows.Input.StylusDeviceBase > styluses ) cil managed { .locals init ( class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < class System.Windows.Input.StylusDeviceBase > V_0 , class System.Windows.Input.StylusDeviceBase V_1 ) ldc.i4.8 // These instructions cause CIL to break conv.u // localloc // pop // ldarg.0 newobj instance void class [ mscorlib ] System.Collections.Generic.List ` 1 < class System.Windows.Input.StylusDevice > : :.ctor ( ) call instance void class [ mscorlib ] System.Collections.ObjectModel.ReadOnlyCollection ` 1 < class System.Windows.Input.StylusDevice > : :.ctor ( class [ mscorlib ] System.Collections.Generic.IList ` 1 < ! 0 > ) ldarg.1 callvirt instance class [ mscorlib ] System.Collections.Generic.IEnumerator ` 1 < ! 0 > class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < class System.Windows.Input.StylusDeviceBase > : :GetEnumerator ( ) stloc.0 .try { leave.s IL_0040 } finally { endfinally } IL_0040 : ret } // end of method StylusDeviceCollection : :.ctor internal unsafe StylusDeviceCollection ( IEnumerable < StylusDeviceBase > styluses ) { IntPtr arg_04_0 = stackalloc byte [ ( UIntPtr ) 8 ] ; base..ctor ( new List < StylusDevice > ( ) ) ; IEnumerator < StylusDeviceBase > enumerator = styluses.GetEnumerator ( ) ; try { } finally { } }
Why does localloc break this CIL method ?
C_sharp : I have a Windows service that every 5 seconds checks for work . It uses System.Threading.Timer for handling the check and processing and Monitor.TryEnter to make sure only one thread is checking for work . Just assume it has to be this way as the following code is part of 8 other workers that are created by the service and each worker has its own specific type of work it needs to check for . Now here 's the problem : The code above is allowing 2 Timer threads to get into the CheckForWork ( ) method . I honestly do n't understand how this is possible , but I have experienced this with multiple clients where this software is running.The logs I got today when I pushed some work showed that it checked for work twice and I had 2 threads independently trying to process which kept causing the work to fail . The logs are written asynchronously and are queued , so do n't dig too deep on the fact that the times match exactly , I just wanted to point out what I saw in the logs to show that I had 2 threads hit a section of code that I believe should have never been allowed . ( The log and times are real though , just sanitized messages ) Eventually what happens is that the 2 threads start downloading a big enough file where one ends up getting access denied on the file and causes the whole update to fail.How can the above code actually allow this ? I 've experienced this problem last year when I had a lock instead of Monitor and assumed it was just because the Timer eventually started to get offset enough due to the lock blocking that I was getting timer threads stacked i.e . one blocked for 5 seconds and went through right as the Timer was triggering another callback and they both somehow made it in . That 's why I went with the Monitor.TryEnter option so I would n't just keep stacking timer threads . Any clue ? In all cases where I have tried to solve this issue before , the System.Threading.Timer has been the one constant and I think its the root cause , but I do n't understand why . <code> readonly object _workCheckLocker = new object ( ) ; public Timer PollingTimer { get ; private set ; } void InitializeTimer ( ) { if ( PollingTimer == null ) PollingTimer = new Timer ( PollingTimerCallback , null , 0 , 5000 ) ; else PollingTimer.Change ( 0 , 5000 ) ; Details.TimerIsRunning = true ; } void PollingTimerCallback ( object state ) { if ( ! Details.StillGettingWork ) { if ( Monitor.TryEnter ( _workCheckLocker , 500 ) ) { try { CheckForWork ( ) ; } catch ( Exception ex ) { Log.Error ( EnvironmentName + `` -- CheckForWork failed. `` + ex ) ; } finally { Monitor.Exit ( _workCheckLocker ) ; Details.StillGettingWork = false ; } } } else { Log.Standard ( `` Continuing to get work . `` ) ; } } void CheckForWork ( ) { Details.StillGettingWork = true ; //Hit web server to grab work . //Log Processing //Process Work } Processing 0-3978DF84-EB3E-47F4-8E78-E41E3BD0880E.xml for Update Request . - at 09/14 10:15:501255801Stopping environments for Update request - at 09/14 10:15:501255801Processing 0-3978DF84-EB3E-47F4-8E78-E41E3BD0880E.xml for Update Request . - at 09/14 10:15:501255801Unloaded AppDomain - at 09/14 10:15:10:15:501255801Stopping environments for Update request - at 09/14 10:15:501255801AppDomain is already unloaded - at 09/14 10:15:501255801=== Starting Update Process === - at 09/14 10:15:513756009Downloading File X - at 09/14 10:15:525631183Downloading File Y - at 09/14 10:15:525631183=== Starting Update Process === - at 09/14 10:15:525787359Downloading File X - at 09/14 10:15:525787359Downloading File Y - at 09/14 10:15:525787359
Monitor.TryEnter and Threading.Timer race condition
C_sharp : Assuming I have a list How can I use LINQ to obtain a list of lists as follows : So , i have to take the consecutive values and group them into lists . <code> var listOfInt = new List < int > { 1 , 2 , 3 , 4 , 7 , 8 , 12 , 13 , 14 } { { 1 , 2 , 3 , 4 } , { 7 , 8 } , { 12 , 13 , 14 } }
Split array with LINQ
C_sharp : How could I refactor the methodif I wished to avoid using the anonymous method here ? <code> private void ListenToPropertyChangedEvent ( INotifyPropertyChanged source , string propertyName ) { source.PropertyChanged += ( o , e ) = > { if ( e.PropertyName == propertyName ) MyMagicMethod ( ) ; } ; }
How to avoid anonymous methods in `` dynamic '' event subscription ?
C_sharp : Consider this small program . Ignore , if you will , the generic catch , I 've kept it brief to try and illustrate the point : When run , the following ( with some of the path info removed ) is produced : My question is - why does the stack trace of the exception stop unwinding the method chain at the Try ( ) method ? I would expect it to unwind past that to the Main ( ) method.I have n't been able to find any documentation about what it is that stops exception unwinding going past the Try ( ) - so I 'd like to understand this . <code> private static void Main ( string [ ] args ) { Try ( Fail ) ; } private static void Fail ( ) { var x = ( ( string ) null ) .Clone ( ) ; } private static void Try ( Action action ) { try { action ( ) ; } catch ( Exception exc ) { Debug.WriteLine ( exc.StackTrace ) ; } } at Scratch.Program.Fail ( ) in Program.cs : line 27at Scratch.Program.Try ( Action action ) in Program.cs : line 34
Why does catch in a method handling an Action truncate the stack trace ?
C_sharp : This is probably not possible , but here goes : I want to create a struct where I can define the amount of arguments at declaration.for example , now I am using : but KeyValuePair can only ever take a Key , and a Value .Is it possible to make something like : I think this is n't possible , but maybe I just do n't know enough C # .I 'm also open to clever workarounds , Thank you <code> KeyValuePair < T , T > CustomValues < T , { T , { .. } } >
Variable length arguments c #
C_sharp : VS now comes with an interactive window , but unlike running the raw CSI.EXE Roslyn process , Visual Studio adds IntelliSense and a few other features such as being able to load in the current project.I want to write a VS plug-in that tracks all text editor changes in this window . Is this possible ? What I 'm looking for is something akin to PreviewKeyDown/PreviewTextInput WPF events . Can I get those on the C # interactive window and , if so , how ? Here 's how far I got so far : <code> var dte = Shell.Instance.GetComponent < DTE > ( ) ; foreach ( Window window in dte.MainWindow.Collection ) { if ( window.Kind.ToUpper ( ) .Contains ( `` TOOL '' ) ) { if ( window.Caption == `` C # Interactive '' ) { WpfWindow wpfWindow = ( WpfWindow ) HwndSource.FromHwnd ( ( IntPtr ) window.HWnd ) .RootVisual ; for ( int i = 0 ; i < VTH.GetChildrenCount ( wpfWindow ) ; ++i ) { // now what ? } } } }
Tracking changes in C # interactive window