text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : It is recommended e.g . here to use ConfigureAwait ( false ) as much as possible on awaited tasks.Does this recommendation also extend to methods that return IAsyncAction , for example StreamSocket.ConnectAsync ( ) ? That is , instead of simply writing this in my class library : I should rather write this ? <code> await socket.ConnectAsync ( hostName , port ) ; await socket.ConnectAsync ( hostName , port ) .AsTask ( ) .ConfigureAwait ( false ) ;
Should I use ConfigureAwait ( false ) when awaiting IAsyncAction ?
C_sharp : Currently , not even the simplest examples of using the 'ExpandoObject ' work on my machine.Both ( from this website ) and ( from the MSDN examples ) fail with a RuntimeBinderException . I presume I 've misconfigured something , but I am at a loss about what it might be.I am using .NET v4.0.30319 and Visual Studio 2010 SP1 Premium . Please ask for anything else you might need to know . = ) <code> dynamic obj = new ExpandoObject ( ) ; obj.Value = 10 ; var action = new Action < string > ( ( line ) = > Console.WriteLine ( line ) ) ; obj.WriteNow = action ; obj.WriteNow ( obj.Value.ToString ( ) ) ; dynamic sampleObject = new ExpandoObject ( ) ; sampleObject.test = `` Dynamic Property '' ; Console.WriteLine ( sampleObject.test ) ;
Why does ExpandoObject not work as expected ?
C_sharp : I created a simple benchmark out of curiosity , but can not explain the results.As benchmark data , I prepared an array of structs with some random values . The preparation phase is not benchmarked : Basically , I wanted to compare these two clamp implementations : Here are my benchmark methods : I 'm using BenchmarkDotNet version 0.10.12 with two jobs : And these are the results I get : I can accept that Mono is somewhat slower here in general . But what I do n't understand is : Why does Mono run the Direct method slower than Extension keeping in mind that Direct uses a very simple comparison method whereas Extension uses a method with additional method calls ? RyuJIT shows here a 4x advantage of the simple method.Can anyone explain this ? <code> struct Val { public float val ; public float min ; public float max ; public float padding ; } const int iterations = 1000 ; Val [ ] values = new Val [ iterations ] ; // fill the array with randoms static class Clamps { public static float ClampSimple ( float val , float min , float max ) { if ( val < min ) return min ; if ( val > max ) return max ; return val ; } public static T ClampExt < T > ( this T val , T min , T max ) where T : IComparable < T > { if ( val.CompareTo ( min ) < 0 ) return min ; if ( val.CompareTo ( max ) > 0 ) return max ; return val ; } } [ Benchmark ] public float Extension ( ) { float result = 0 ; for ( int i = 0 ; i < iterations ; ++i ) { ref Val v = ref values [ i ] ; result += v.val.ClampExt ( v.min , v.max ) ; } return result ; } [ Benchmark ] public float Direct ( ) { float result = 0 ; for ( int i = 0 ; i < iterations ; ++i ) { ref Val v = ref values [ i ] ; result += Clamps.ClampSimple ( v.val , v.min , v.max ) ; } return result ; } [ MonoJob ] [ RyuJitX64Job ] BenchmarkDotNet=v0.10.12 , OS=Windows 7 SP1 ( 6.1.7601.0 ) Intel Core i7-6920HQ CPU 2.90GHz ( Skylake ) , 1 CPU , 8 logical cores and 4 physical coresFrequency=2836123 Hz , Resolution=352.5940 ns , Timer=TSC [ Host ] : .NET Framework 4.7 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.7.3062.0 Mono : Mono 5.12.0 ( Visual Studio ) , 64bit RyuJitX64 : .NET Framework 4.7 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.7.3062.0 Method | Job | Runtime | Mean | Error | StdDev | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | Extension | Mono | Mono | 10.860 us | 0.0063 us | 0.0053 us | Direct | Mono | Mono | 11.211 us | 0.0074 us | 0.0062 us | Extension | RyuJitX64 | Clr | 5.711 us | 0.0014 us | 0.0012 us | Direct | RyuJitX64 | Clr | 1.395 us | 0.0056 us | 0.0052 us |
Why does Mono run a simple method slower whereas RyuJIT runs it significantly faster ?
C_sharp : Good day SO ! I was trying to add two byte variables and noticed weird result . when i tried to run the program , It displaysWhat happened to the above code ? Why does n't the compiler throws an OverflowException ? How can I possibly catch the exception ? I 'm a VB guy and slowly migrating to C # : ) Sorry for the question . <code> byte valueA = 255 ; byte valueB = 1 ; byte valueC = ( byte ) ( valueA + valueB ) ; Console.WriteLine ( `` { 0 } + { 1 } = { 2 } '' , valueA.ToString ( ) , valueB.ToString ( ) , valueC.ToString ( ) ) ; 255 + 1 = 0
byte + byte = unknown result
C_sharp : I have what seems to be a simple problem that I am having a hard time modeling in code ( C # ) -I am trying to find the highest potential credit hours available to a person attending a conference . Courses have time blocks , such as Security 101 @ 9AM-10AM , Finance 202 @ 4PM-6PM , etc.The main rule is , you ca n't attend two courses at once - so you would get credit for courses at 9-10 and 10-11 , but you could not also get credit for a course that ran for 9-11.What I would like to do is the following : I would like to get an array of valid ( valid meaning non-overlapping ) paths throughout a day.So , for example , the full set of courses for a day may be the following : There are a few paths someone might take throughout this day : FINANCE 101 ( 9-10 ) - > FINANCE 102 ( 10-11 ) - > SECURITY 101 ( 11-12 ) - > DONE FINANCE 101 ( 9-10 ) - > PYTHON 300 ( 10-11 ) - > SECURITY 101 ( 11-12 ) - > DONE FINANCE 101 ( 9-10 ) - > FINANCE 102 ( 10-11 ) - > DATABASE 200 ( 11-1 ) - > DONE FINANCE 101 ( 9-10 ) - > PYTHON 300 ( 10-11 ) - > DATABASE 200 ( 11-1 ) - > DONE ECONOMICS 101 ( 9-12 ) - > DONEThis is a somewhat simple scenario , in reality it would be possible to have multiple branching scenarios , such as having three 9-10 courses that would create more permutations on top of this.The reason I would like an array of paths ( instead of one single optimal path ) is because there is n't necessarily a direct 1 Hour = 1 Credit Hour correlation , there would be a second level calculation based on the set of paths to sum the credit hour value of the path to determine what is 'best'.My question is this - is there a technique or software pattern that I can follow in order to generate these permutations so that I can measure the results to determine the path that would yield the most credits for a course-taker ? Edited for Solution : Thanks everyone for your input and help , both solutions from Bradley Uffner and Xiaoy312 nailed it ! <code> | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| COURSE | START | END || -- -- -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -| -- -- -- -- -- -- -- -|| FINANCE 101 | 9:00 AM | 10:00 AM || FINANCE 102 | 10:00 AM | 11:00 AM || PYTHON 300 | 10:00 AM | 11:00 AM || SECURITY 101 | 11:00 AM | 12:00 PM || ECONOMICS 101 | 9:00 AM | 12:00 PM || DATABASE 200 | 11:00 AM | 1:00 PM || -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|
How do I get all non-overlapping permutations for a series of time blocks ?
C_sharp : For the life of me , I ca n't figure out why all the foos are not null.I 'm assuming the .ForAll ( ) should be executing before I call the .All ( ) method , but it 's not ? <code> public class Foo { public string Bar { get ; set ; } } static void Main ( string [ ] args ) { var foos = new List < Foo > { new Foo ( ) , new Foo ( ) , new Foo ( ) } ; var newFoos = foos .AsParallel ( ) .Select ( x = > { x.Bar = `` '' ; return x ; } ) ; newFoos.ForAll ( x = > x = null ) ; var allFoosAreNull = newFoos.All ( x = > x == null ) ; Console.WriteLine ( allFoosAreNull ) ; // False ? ? }
Parallel LINQ - .Select ( ) + .ForAll ( ) returning bizarre results
C_sharp : Why do we need more than one await statement in a C # method ? E.g . here we have three await statements : In case we will remove the second and the third await statements in the SeedAsync no extra threads will be blocked , since already after the first await we are not blocking any useful threads and we already allocated an extra thread for the first await . So , by using the second and the third await statements we are allocating the extra two threads.Am I missing something here ? Since abp.io seems to be a big project I suspect that the examples would not be unreasonable and hence there is must be a reason to the use of the three await statements instead of the one . <code> using System ; using System.Threading.Tasks ; using Volo.Abp.Data ; using Volo.Abp.DependencyInjection ; using Volo.Abp.Domain.Repositories ; namespace Acme.BookStore { public class BookStoreDataSeederContributor : IDataSeedContributor , ITransientDependency { private readonly IRepository < Book , Guid > _bookRepository ; public BookStoreDataSeederContributor ( IRepository < Book , Guid > bookRepository ) { _bookRepository = bookRepository ; } public async Task SeedAsync ( DataSeedContext context ) { if ( await _bookRepository.GetCountAsync ( ) > 0 ) { return ; } await _bookRepository.InsertAsync ( new Book { Name = `` 1984 '' , Type = BookType.Dystopia , PublishDate = new DateTime ( 1949 , 6 , 8 ) , Price = 19.84f } ) ; await _bookRepository.InsertAsync ( new Book { Name = `` The Hitchhiker 's Guide to the Galaxy '' , Type = BookType.ScienceFiction , PublishDate = new DateTime ( 1995 , 9 , 27 ) , Price = 42.0f } ) ; } } }
Why do we need more than one ` await ` statement in a C # method ?
C_sharp : When working with MVVM and Prism i find myself doing a lot of casting , as most parameters are interfacesExorMy question is , whats the cost involved . Are these operations costly memory or cpu wise , should they be avoided.Any views ? <code> public void AddCrSubSystemsToPlant ( IPlantItem plantItm , CRArticleItem crItm ) { OSiteSubSystem itm = ( OSiteSubSystem ) crItm ; itm.PartData.Order = ( ( OSiteEquipment ) plantItm ) .SubSystems.Count ( ) + 1 ; ( ( OSiteEquipment ) plantItm ) .SubSystems.Add ( itm ) ; } public void DeletePart ( IPlantItem plantItem ) { IEnumerable < IPlantItem > itmParent = GetParentPartByObjectId ( _siteDocument , plantItem ) ; if ( plantItem is OSiteEquipment ) ( ( ObservableCollection < OSiteEquipment > ) itmParent ) .Remove ( ( OSiteEquipment ) plantItem ) ; if ( plantItem is OSiteSubSystem ) ( ( ObservableCollection < OSiteSubSystem > ) itmParent ) .Remove ( ( OSiteSubSystem ) plantItem ) ; if ( plantItem is OSiteComponent ) ( ( ObservableCollection < OSiteComponent > ) itmParent ) .Remove ( ( OSiteComponent ) plantItem ) ; }
Whats the cost of casting parameters
C_sharp : In the synchronous world , C # makes the management of all things disposable really rather easy : However , when we go async , we no longer have the convenience of the using block . One of the best strategies I 've encountered is the CCR iterator which allows us to use async code `` as if it were synchronous '' . This means we can keep our using block in the iterator handler and not get too bogged down in the complex decision of when to dispose and catching all the cases where disposal is required.However , in many cases , invoking CCR can seem like overkill , and to be honest , although I 'm quite comfortable with CCR , to the uninitiated it can look like double-dutch.So my question is : what other strategies exist for the management of one 's IDisposable 's , when the disposable objects must persist beyond the immediate scope ? <code> using ( IDisposable someDisposable=bla.bla ( ) ) { //do our bidding } //do n't worry too much about it
Failsafe disposal in an async world
C_sharp : Why does the Equals method return a different result from within the generic method ? I think that there 's some automatic boxing here that I do n't understand.Here 's an example that reproduces the behavior with .net 3.5 or 4.0 : Output : Edit : This code works as desired without many compromises : Followup : I filed a bug via MS Connect and it has been resolved as fixed , so it 's possible this will be fixed in the next version of the .net framework . I 'll update with more details if they become available.PS : This appears to be fixed in .net 4.0 and later ( by looking at the disassembly of TimeZoneInfo in mscorlib ) . <code> static void Main ( string [ ] args ) { TimeZoneInfo tzOne = TimeZoneInfo.Local ; TimeZoneInfo tzTwo = TimeZoneInfo.FindSystemTimeZoneById ( tzOne.StandardName ) ; Console.WriteLine ( Compare ( tzOne , tzTwo ) ) ; Console.WriteLine ( tzOne.Equals ( tzTwo ) ) ; } private static Boolean Compare < T > ( T x , T y ) { if ( x ! = null ) { return x.Equals ( y ) ; } return y == null ; } FalseTrue private static Boolean Compare < T > ( T x , T y ) { if ( x ! = null ) { if ( x is IEquatable < T > ) { return ( x as IEquatable < T > ) .Equals ( y ) ; } return x.Equals ( y ) ; } return y == null ; }
Unexpected behavior in c # generic method on .Equals
C_sharp : Is there a linq command that will filter out duplicates that appear in a sequence ? Example with ' 4 ' : Thanks . <code> Original { 1 2 3 4 4 4 5 6 7 4 4 4 8 9 4 4 4 } Filtered { 1 2 3 4 5 6 7 4 8 9 4 }
Linq query that reduces a subset of duplicates to a single value within a larger set ?
C_sharp : While experimenting with closures in C # I found out that they work rather unexpectedly if they capture an iterator variable in a loop.The above code produces a strange result ( I 'm using .NET 4.5 compiler ) : Why is the value of i captured differently for 2 almost identical loops ? <code> var actions = new List < Action > ( ) ; foreach ( int i in new [ ] { 1 , 2 } ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; for ( int i = 3 ; i < = 4 ; i++ ) actions.Add ( ( ) = > Console.WriteLine ( i ) ) ; foreach ( var action in actions ) action ( ) ; 1255
Closures behaving differently in for and foreach loops
C_sharp : example : this causes a cyclic struct layout , but i do n't see the cycle . if Id had a field of type T , sizeof would be undefined , but it doesn't.is this a mono bug , or part of the spec ? <code> struct Id < T > { int id ; } struct Thing { public Id < Thing > id ; }
why do i get a `` cycle in the struct layout '' with phantom types in c # ?
C_sharp : `` test1 '' seems to be an IEnumerable with v1 and v2 ( params ) as fields and `` Test1 '' is NOT called . `` Test2 '' works a `` designed '' : ) whats going on ? <code> using System ; using System.Collections.Generic ; using System.Text ; using System.Collections ; namespace ConsoleApplication4 { class Program { static void Main ( string [ ] args ) { var test1 = Test1 ( 1 , 2 ) ; var test2 = Test2 ( 3 , 4 ) ; } static IEnumerable Test1 ( int v1 , int v2 ) { yield break ; } static IEnumerable Test2 ( int v1 , int v2 ) { return new String [ ] { } ; } } }
yield break ; - crazy behaviour
C_sharp : The question is about C # language specification and CIL language specification , as well as Microsoft 's and Mono 's C # compiler behavior . I 'm building some code analysis tools ( no matter what ) , which operate on CIL . Considering a few code samples , I notice that code statements ( try/catch , ifelse , ifthen , loops , ... ) generate connected blocks of MSIL . But I 'd like to be sure that I ca n't write C # code construct which yields non-connected MSIL . More specifically , can I write any C # statement which translates to ( something similar to ) : I already tried some weird stuff using goto and nested loops , but maybe I 'm not as mad as some users would be . <code> IL_0000 : IL_0001 : IL_0002 : // holeIL_001a : IL_001b :
Can a C # statement generate non connected MSIL
C_sharp : I got into an argument with a co-worker about the use of LINQ to Objects ( IEnumerable , not IQueryable ) in our C # code . I was using LINQ , and he said that we should n't be using an external vendor 's ( Microsoft ) code in our code , but that we should wrap it ourselves in our own layer of abstraction.Now I understand this methodology for use where you 've got a no-name third party dll that may go out of business next week , or when your dealing with database calls ( ie . returning a common data provider , rather than a SQL or Oracle specific one ) , but in my mind the LINQ syntax is too pretty/elegant/readable for Microsoft to abandon in the next 10 years . It 's about as likely to be dropped as the ToString ( `` Hello { 0 } '' , firstName ) ; functionality.I could give up arguing , and implement our own LINQ library that calls the standard LINQ methods under the covers , but is n't this over doing it ? Plus I could only use the extension methods , I have no idea how to be able to wrap this : What would your argument be , for or against using LINQ to objects ( the IEnumerable extension methods ) ? <code> from e in employeesselect new { e.Name , e.Id } ;
Should I not use LINQ to objects because Microsoft might change it ?
C_sharp : I 'm converting some VB6 logic to C # and have encountered the following SELECT/CASE statement.The best conversion I can think of is a series of if/then/else statements which map each range , e.g.Or is there a better way , e.g . some way to put these range values in a hash/array/collection of some sort ? <code> Select Case ZipCodeCase 1067 To 19417 , 35075 To 35085 , 48455 To 48465 , 55583 To 55596 , 67480 To 67551 , 75392 , 85126 , _ 93047 To 93059 , 21217 To 21739 , 35091 To 35096 , 48480 , 55606 To 55779 , 67655 To 67707 , 76726 To 76835 , _ 85221 To 87679 , 94315 To 94419 , 22844 To 25799 , 35102 , 48488 , 56154 To 56254 , 67731 To 67759 , 76855 To 76889 , _ 87719 To 88339 , 94428 To 94437 , 25868 , 35112 , 48499 To 48531 , 56271 , 67824 To 67829 , 77761 , 88353 , 94522 , _ 25879 , 35117 , 48653 , 56281 To 56299 , 69427 To 69429 , 77773 To 77776 , 88361 To 88364 , 94553 , 26121 To 26160 , _ 35216 To 35282 , 48720 To 48727 , 56321 To 56337 , 69437 To 69439 , 78048 To 78126 , 88368 To 88379 , 94559 , _ 26180 To 26215 , 35287 To 35469 , 49124 To 49356 , 56410 To 56479 , 70173 To 71287 , 78136 To 79117 , 88410 , 95028 To 95032 , _ 26316 To 26389 , 35576 To 35768 , 49406 , 56575 , 71332 To 71540 , 80331 To 83313 , 88481 , 95111 To 95152 , _ 26419 , 36110 , 49419 , 56626 To 56648 , 71546 To 71711 , 83324 To 83362 , 88529 , 95176 To 95185 , _ 26434 To 26441 , 36304 To 36358 , 49448 , 56727 To 56745 , 71720 To 72189 , 83365 To 83379 , 88633 , 95188 To 95194 , _ 26452 , 36367 To 36369 , 49453 , 56751 To 57339 , 72250 To 72417 , 83413 , 88662 To 90491 , 95197 if ( ( ZipCode > = 1067 & & ZipCode < =19417 ) || ( ZipCode > = 35075 & & ZipCode < =35085 ) || ...
How to best convert VB6 `` Select Case 1067 To 2938 ... '' to C # ?
C_sharp : An ex-coworker wrote this : I read articles like theseCode Project - Custom String Formatting in .NETMSDN - Custom Numeric Format StringsBut I do n't still get it how that format works . Obviously I can see the output but I do n't understand this part { 0 : # ; ; } and the second one . I want to do the same thing for specifying ages ( year , years ... ) I 'm very curious about this string format . Can someone can explain this behavior ? The author does not work with us anymore . <code> String.Format ( `` { 0 : # ; ; } { 1 : records ; no records ; record } '' , rows , rows - 1 ) ; //Rows is a integer value
Explaining confusing conditional string format
C_sharp : I need to make a class that wraps two dictionaries together , so that their values can be retrieved by a key of either an int or a string.Properties seem to be the best approach here , but is there a difference between these two implementations ? AndIn either case , the dictionary object is immutable and the elements can freely be changed , which is what I want . However , trying to change the dictionary object will result in either a ~ can not be assigned to -- it is read only or a ~ can not be used in this context because the set accessor is inaccessible . I realize the compiler will fluff out my auto properties into something similar to the top block of code anyways ... Does it actually matter which compiler error is raised ? <code> public class Atlas < TValue > { private Dictionary < int , TValue > _byIndex ; private Dictionary < string , TValue > _byName ; public Dictionary < int , TValue > ByIndex { get { return _byIndex ; } } public Dictionary < string , TValue > ByName { get { return _byName ; } } } public class Atlas < TValue > { public Dictionary < int , TValue > ByIndex { get ; private set ; } public Dictionary < string , TValue > ByName { get ; private set ; } }
Is there a difference between having a private setter OR only defining a getter ?
C_sharp : So , i 'm new to unit testing , and even more so to test first development . Is it valid for me to have just a single assert.isTrue statement in my unit test where I pass in my method and a valid parameter , and compare it to the known good answer ? MethodTest <code> public static string RemoveDash ( string myNumber ) { string cleanNumber = myNumber.Replace ( `` - '' , '' '' ) ; return cleanNumber ; } [ TestMethod ( ) ] public void TestRemoveDash ( ) { Assert.IsTrue ( RemoveDash ( `` 50-00-0 '' ) == '' 50000 '' ) ; }
Is it valid to have unit tests with only an assert statement ?
C_sharp : In C # is there any real difference ( other than syntax ) under the hood between : and ? <code> myButton.Click += new EventHandler ( myMemberMethod ) ; myButton.Click += myMemberMethod ;
Is there an actual difference in the 2 different ways of attaching event handlers in C # ?
C_sharp : I have a particular problem that I need help with . I am working with complex proteomics data and one of our plots involves a heatmap of the raw data . These heatmaps I calculate as a raw image that I then resize to fit my chart canvas . The image files that are produced that way are usually very in-balanced when it comes to the width vs height.Usually , these images are around 10 to a 100 pixels wide and 5000 to 8000 pixels high ( this is the size of my raw 2D data array that I have to convert into an image ) . The target resolution afterwards would be something of 1300 x 600 pixels.I usually use this function for resizing my image to a target sizeThis usually works fine for the dimension described above . But now I have a new dataset with the dimensions of 6 x 54343 pixels.When using the same code on this image the resized image is half blank . Original Image : http : //files.biognosys.ch/FileSharing/20170427_StackOverflow/raw.png ( the original image does not show properly in most browsers so use `` save link as ... '' ) How it should look ( using photoshop ) : http : //files.biognosys.ch/FileSharing/20170427_StackOverflow/photoshop_resize.pngHow it looks when I use the code snipped abovehttp : //files.biognosys.ch/FileSharing/20170427_StackOverflow/code_resized.pngPlease keep in mind , that this has worked for years without problem for images of 6 x 8000 so I guess I am not doing anything fundamentally wrong here.It is also important that I have NearestNeighbor interpolation for the resizing so any solution that involves other interpolations that do not result in the `` How it should look '' image are eventually not useful for me.Oli <code> public static Image Resize ( Image img , int width , int height ) { Bitmap bmp = new Bitmap ( width , height ) ; Graphics graphic = Graphics.FromImage ( ( Image ) bmp ) ; graphic.InterpolationMode = InterpolationMode.NearestNeighbor ; graphic.PixelOffsetMode = PixelOffsetMode.Half ; graphic.DrawImage ( img , 0 , 0 , width , height ) ; graphic.Dispose ( ) ; return ( Image ) bmp ; }
Large , odd ratio image resize in C #
C_sharp : I am developing a HTML form designer that needs to generate static HTML and show this to the user . I keep writing ugly code like this : Is n't there a set of strongly typed classes that describe html elements and allow me to write code like this instead : I just ca n't think of the correct namespace to look for this or the correct search term to use in Google . <code> public string GetCheckboxHtml ( ) { return ( `` & lt ; input type= '' checkbox '' name= '' somename '' / & gt ; '' ) ; } var checkbox = new HtmlCheckbox ( attributes ) ; return checkbox.Html ( ) ;
In C # 3.0 , are there any classes that help me generate static html ?
C_sharp : I 'm building a report dashboard using C # and JQuery Datatables . One of the reports on the page contains an update panel with a drop down list . When the user changes the selection , the data refreshes based on the ddl selection . Within each block there is also a link that makes a server side call to export the data to Excel . The problem is that after I click on the Excel export link , the drop down lists lose any functionality , as do the other Excel download links . Here 's my code : Here 's the jQuery : This code is in place to handle the update panel : The error I 'm getting is : Unable to get property 'style ' of undefined or null reference . This is the full error from the IE JS debugger : Not surprisingly , this works perfectly fine in Chrome , blows up in IE . <code> < div id= '' dTopProducts '' class= '' dashboardDiv '' style= '' height:400px ; width:485px ; margin-top : 15px ; margin-bottom:15px ; margin-right : 15px ; '' runat= '' server '' > < asp : UpdatePanel ID= '' upProducts '' runat= '' server '' > < Triggers > < asp : AsyncPostBackTrigger ControlID= '' ddlProductsSector '' EventName= '' SelectedIndexChanged '' / > < /Triggers > < ContentTemplate > < div style= '' float : left ; '' > < h2 > Top Products & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; & nbsp ; < /h2 > < /div > < div style= '' float : left ; `` > < asp : DropDownList ID= '' ddlProductsSector '' AutoPostBack= '' true '' EnableViewState= '' true '' OnSelectedIndexChanged= '' ddlProductsSector_SelectedIndexChanged '' runat= '' server '' / > < /div > < asp : UpdateProgress ID= '' prgProducts '' AssociatedUpdatePanelID= '' upProducts '' runat= '' server '' > < ProgressTemplate > < epriLoader : Loader runat= '' server '' / > < /ProgressTemplate > < /asp : UpdateProgress > < asp : ListView ID= '' lvTopProducts '' runat= '' server '' > < ItemTemplate > < tr style= '' padding-top : 5px ; padding-bottom : 5px ; '' > < td style= '' padding-left : 0px ; '' > < % # Eval ( `` productId '' ) % > < /td > < td > < % # Eval ( `` productDesc '' ) % > < /td > < td style= '' text-align : right ; '' > < % # Eval ( `` quantity '' ) % > < /td > < /tr > < /ItemTemplate > < EmptyDataTemplate > < div style= '' float : left ; padding-top : 25px ; '' > There are no product records found for the criteria provided < /div > < /EmptyDataTemplate > < LayoutTemplate > < table id= '' tblTopProducts '' style= '' width : 100 % '' > < thead > < tr style= '' padding-bottom : 10px ; border : none ; '' > < th style= '' text-align : left ; border : none ; padding-left : 0px ; '' > ID < /th > < th style= '' text-align : left ; border : none ; padding-left : 0px ; '' > Name < /th > < th style= '' text-align : right ; border : none ; '' > Quantity < /th > < /tr > < /thead > < tfoot > < tr > < td style= '' border : none ; '' > < /td > < td style= '' border : none ; '' > < /td > < td style= '' border : none ; '' > < /td > < /tr > < /tfoot > < tbody runat= '' server '' > < asp : PlaceHolder ID= '' itemPlaceholder '' runat= '' server '' / > < /tbody > < /table > < /LayoutTemplate > < /asp : ListView > < /ContentTemplate > < /asp : UpdatePanel > < % -- Link that calls full export from funding page -- % > < a id= '' aTopProducts '' class= '' invoicesLink '' title= '' Click here to download full report '' onserverclick= '' ExportTopProductsToExcel '' runat= '' server '' > Download full Report < /a > < /div > function bindTopProductsTable ( ) { var topProductsTable = $ ( ' # tblTopProducts ' ) .dataTable ( { `` scrollY '' : `` 225px '' , `` scrollCollapse '' : true , `` bSort '' : true , `` order '' : [ [ 2 , `` desc '' ] ] , `` paging '' : false , dom : ' < `` toolbar '' > rt < `` floatRight '' B > < `` clear '' > ' , buttons : { buttons : [ { extend : 'excel ' , text : 'Export to Excel ' , exportOption : { page : 'current ' } , footer : true , className : 'productsExportButton ' } ] } } ) ; } ; $ ( function ( ) { bindTopProductsTable ( ) ; // bind data table on first page load Sys.WebForms.PageRequestManager.getInstance ( ) .add_endRequest ( bindTopProductsTable ) ; // bind data table on every UpdatePanel refresh } ) ; j.find ( `` thead , tfoot '' ) .remove ( ) ; j.append ( h ( a.nTHead ) .clone ( ) ) .append ( h ( a.nTFoot ) .clone ( ) ) ; j.find ( `` tfoot th , tfoot td '' ) .css ( `` width '' , '' '' ) ; n=qa ( a , j.find ( `` thead '' ) [ 0 ] ) ; for ( m=0 ; m < i.length ; m++ ) o=c [ i [ m ] ] , n [ m ] .style.width=null ! ==o.sWidthOrig & & '' '' ! ==o.sWidthOrig ? x ( o.sWidthOrig ) : '' '' , o.sWidthOrig & & f & & h ( n [ m ] ) .append ( h ( `` < div/ > '' ) .css ( { width : o.sWidthOrig , margin:0 , padding:0 , border:0 , height:1 } ) ) ; if ( a.aoData.length ) for ( m=0 ; m < i.length ; m++ ) t=i [ m ] , o=c [ t ] , h ( Gb ( a , t ) ) .clone ( ! 1 ) .append ( o.sContentPadding ) .appendTo ( r ) ; h ( `` [ name ] '' ,
jQuery Datatables ASP.NET issue
C_sharp : On my page I have : a 'filter ' section - a couple of checkboxes and textboxes , a 'search ' button , grid with paging where the results are displayed . The grid is from Telerik ( http : //demos.telerik.com/aspnet-mvc/grid/index1 ) , but I do n't think this matters.Searching works OK - I can input some text or check a checkbox in the filter section and the appropriate results are displayed . Paging works OK only if I use it when the page is loaded ( that means before I click Search button , in this case the url is ' ... Home ' ) .But if click search first ( in this case the url will become ' ... Home/Search ' ) and then try to go to another page on the grid then I get an exception in the Search method , because the model.Filter parameter is null ( System.NullReferenceException : Object reference not set to an instance of an object . ) I tried to solve the problem in many different ways ( with RedirectToAction method , storing the filter to session and use it in Search method , ... ) but no solution worked in all scenarios . Any ideas ? My simplified code : HomeController : View : <code> public ActionResult Index ( ) { // On page load display all data without filters . var filter = new OverviewFilterModel { Type1 = true , Type2 = true , WorkingOrder = `` '' } ; ViewBag.Results = GetResults ( filter ) ; return View ( new HomeModel { Filter = filter } ) ; } public ActionResult Search ( HomeModel model ) { ViewBag.Results = GetResults ( model.Filter ) ; return View ( `` Index '' ) ; } public class OverviewFilterModel { public bool Type1 { get ; set ; } public bool Type2 { get ; set ; } public string WorkingOrder { get ; set ; } } public class HomeModel { public OverviewFilterModel Filter { get ; set ; } public IEnumerable < OverviewResultsModel > Results { get ; set ; } } < ! -- ... -- > @ model HomeModel < ! -- ... -- > @ using ( Html.BeginForm ( `` Search '' , `` Home '' , FormMethod.Post , new { @ class = `` form-inline '' } ) ) { < div class= '' form-group '' style= '' margin-left : 135px ; '' > @ Html.CheckBoxFor ( p = > p.Filter.Type1 ) @ Html.LabelFor ( p = > p.Filter.Type1 , new { style = `` margin : 0 15px 0 5px ; '' } ) < /div > < ! -- a bunch of other checkboxes -- > < br / > < div class= '' form-group '' > < label style= '' width : 130px ; text-align : right ; '' > Delovni nalog < /label > @ Html.TextBoxFor ( p = > p.Filter.WorkingOrder , new { @ class = `` form-control ecert-filter-small '' , @ autocomplete = `` off '' } ) < /div > < ! -- a bunch of other textboxes -- > < button class= '' k-button '' id= '' button-refresh '' style= '' margin : 10px 0 0 135px ; '' > Refresh < /button > < hr / > @ ( Html.Kendo ( ) .Grid < OverviewResultsModel > ( ) .BindTo ( ( IEnumerable < OverviewResultsModel > ) ViewBag.Results ) .Name ( `` gridOverview '' ) .Events ( p = > p.Change ( `` overviewOnRowSelect '' ) ) .Columns ( columns = > { columns.Template ( @ < text > @ Html.ActionLink ( `` WorkingOrder '' , `` Index '' , `` WO '' , new { dn = @ item.WorkingOrder } , new { @ class = `` selectable-dn '' } ) < /text > ) .Title ( `` '' ) ; columns.Bound ( p = > p.Type ) ; columns.Bound ( p = > p.WorkingOrder ) ; columns.Bound ( p = > p.Date ) ; columns.Bound ( p = > p.ProductId ) ; columns.Bound ( p = > p.ProductName ) ; } ) .Selectable ( ) .Pageable ( p = > p .Refresh ( true ) .PageSizes ( true ) .ButtonCount ( 10 ) .Messages ( q = > { q.Display ( `` { 0 } - { 1 } od { 2 } records '' ) ; q.Empty ( `` No data for selected filter '' ) ; q.ItemsPerPage ( `` Number of records per page '' ) ; } ) ) .DataSource ( p = > p.Server ( ) .PageSize ( 20 ) .Model ( q = > { q.Id ( r = > r.WorkingOrder ) ; } ) ) ) }
Model is null after postback in pager
C_sharp : What is the [ and ] in c # ? what is it used for ? what does it mean ? example <code> [ DefaultValue ( null ) ] [ JsonName ( `` name '' ) ] public string Name { get { if ( this.name == null ) { return String.Empty ; } return this.name ; } }
What is [ and ] in c # ?
C_sharp : I am reading the MCTS Self-Paced Training Kit ( Exam 70-536 ) : Microsoft .NET Framework—Application Development Foundation , Second Edition eBook.Now I am finishing off the threading chapter ( nr . 7 ) . In the questions at the end of lesson 2 , the is one question ( nr . 2 ) that asks : `` You are writing a method that can be run by multiple threads . Make sure that no thread writes to the file while any thread is reading from the file . But you have to do it as efficiently as possible with regard to multiple threads reading at the same time . `` Then there are two answers which are candidates for answers : A.and D.The subtle hint in the question that `` it has to be efficient for multiple reads '' of course means they want you to use the ReaderWriterLock , but then I thought : `` Creating a new instance of the ReaderWriterLock inside the method you are locking should n't work , every call to the method will lock a different instance of ReaderWriterLock . `` However in the answers it says : D.So IMHO this is an error in the book . They probably meant in the code sample that the new instance would be created somewhere else . If I would get this question on the exam , I would have gotten it wrong ( I would choose A ) . <code> lock ( file ) { // Read } ReaderWriterLock rwl = new ReaderWriterLock ( ) ; rwl.AcquireReaderLock ( 10000 ) ; // Readrwl.ReleaseReaderLock ( ) ;
Is this an error in the MCTS Self-Paced Training Kit ( Exam 70-536 ) ?
C_sharp : Using this construct : I get an error saying CS0165 use of unassigned local variable 'value ' which is not what I expect . How could value possibly be undefined ? If the dictionary is null the inner statement will return false which will make the outer statement evaluate to false , returning Default.What am I missing here ? Is it just the compiler being unable to evaluate the statement fully ? Or Have I messed it up somehow ? <code> var dict = new Dictionary < int , string > ( ) ; var result = ( dict ? .TryGetValue ( 1 , out var value ) ? ? false ) ? value : `` Default '' ;
Null-coalescing out parameter gives unexpected warning
C_sharp : I have the following generic classes : Somewhere in my code , I would like to test whether a given generic inherits from Base < T > , without creating a particular instance of the generic . How do I do that ? EDIT : Thank you Mark . Now I see the light . I originally tried the following : Apparently , this is correct . But it is not . The problem is that Base 's T is not the same thing as Derived 's T. So , inBase 's T is a free type . But , inBase 's T is bound to Derived 's T , which is in turn a free type . ( This is so awesome I would LOVE to see the System.Reflection 's source code ! ) Now , unbounds Base 's T. Conclusion : And now , if you all excuse me , my head is burning . <code> class Base < T > where T : ... { ... } class Derived < T > : Base < T > where T : ... { ... } class Another < T > where T : ... { ... } class DerivedFromDerived < T > : Derived < T > where T : ... { ... } static bool DerivedFromBase ( Type type ) { /* ? ? ? */ } static void Main ( string [ ] args ) { Console.WriteLine ( DerivedFromBase ( typeof ( Derived < > ) ) ) ; // true Console.WriteLine ( DerivedFromBase ( typeof ( Another < > ) ) ) ; // false Console.WriteLine ( DerivedFromBase ( typeof ( DerivedFromDerived < > ) ) ) ; // true Console.ReadKey ( true ) ; } typeof ( Derived < > ) .BaseType == typeof ( Base < > ) typeof ( Base < > ) typeof ( Derived < > ) .BaseType typeof ( Derived < > ) .BaseType.GetGenericTypeDefinition ( ) typeof ( Derived < > ) .BaseType.GetGenericTypeDefinition ( ) == typeof ( Base < > )
How to test whether two generics have a base-subclass relationship without instantiating them ?
C_sharp : first , it 's not a duplication of What does the @ symbol before a variable name mean in C # ? as group is not a preserved keyword.I wrote some code and the resharper suggested me to add @ before the variable group.Any idea why ? <code> var group = GetDefaultGroup ( ClientServiceCommon.Poco.Group ) ; filteredPairs = @ group.Pairs.ToList ( ) ;
what does @ before variabe means in c # ?
C_sharp : I 'm trying to build the C # wrappers for RDKit , but have been struggling to make progress . I 've attempted two routes : n.b . This question is long and unhelpful . Long story short use NuGet ( see answer below ) .Attempt OneDocs from RDKit /Code/JavaWrappers/csharp_wrapperThe first one is found in https : //github.com/rdkit/rdkit.There are C # wrappers with build instructions in ./Code/JavaWrappers/csharp_wrapper found at : https : //github.com/rdkit/rdkit/tree/master/Code/JavaWrappers/csharp_wrapperMy first attempt to compile the wrappers involved manually trying to build these . Following this README : https : //github.com/rdkit/rdkit/blob/master/Code/JavaWrappers/csharp_wrapper/README To build on Windows : Since cmake does n't know anything about C # , there 's an unfortunate manual step involved in this . Make sure that the cmake configuration variable RDK_BUILD_SWIG_CSHARP_WRAPPER is set to ON . Run cmake to generate the solution file and open it in Visual Studio . Select the option to add an existing project and add $ RDBASE/Code/JavaWrappers/csharp_wrapper/RDKit2DotNet.csproj Right click on the added project ( named RDKit2DotNet ) and add a dependency to RDKFuncs ( this is the project that creates the C++ dll that the C # project needs ) Build the RDKit2DotNet project . Your bin directory ( $ RDBASE/Code/JavaWrappers/csharp_wrapper/bin/Release if you did a release build ) now contains two DLLs : - RDKFuncs.dll is the C++ dll containing the RDKit functionality - RDKit2DotNet.dll contains the C # wrapper . To use the wrappers in your own projects , you should copy both dlls into your project directory and add a reference to RDKit2DotNet.dll The directory RDKitCSharpTest contains a sample test project and some code that makes very basic use of the wrapper functionality.To get cmake to run I updated the CMakeLists.txt to tell it how to find swig and to set RDK_BUILD_SWIG_CSHARP_WRAPPER ON as follows : This creates a lot of new files and one .sln file called GraphMolCSharp.sln.I was then able to follow the rest of the steps in the README . I opened GraphMolCSharp.sln and added RDKit2DotNet.csproj as a project and added RDKfuncs as a build dependency . But building this gave a lot of errors in Visual Studio , starting with : Then a lot of Unable to find x errors.If anyone can offer some guidance about anything I might have done wrong please let me know . Attempt TwoThe second uses the build.bat found here : https : //github.com/bp-kelley/rdkit-csharp To start I run : Then I have updated the build.bat to use Visual Studio 16 2019 as follows . Line 95 : cmake -G `` Visual Studio 16 2019 '' -A x64 ... andLine 111 : cmake -G `` Visual Studio 16 2019 '' ... If someone is able to offer assistance debugging the output below I 'd be most grateful.I have had to cancel the following line : But have copied nuget.exe into the expected location.This is most of the output of running build.bat <code> cmake_minimum_required ( VERSION 3.14 ) project ( GraphMolCSharp ) set ( SWIG_FOUND TRUE ) # This has been addedset ( SWIG_DIR $ { CMAKE_CURRENT_SOURCE_DIR } ) # This has been addedset ( SWIG_EXECUTABLE swig.exe ) # This has been addedset ( SWIG_VERSION 4.0 ) # This has been addedfind_package ( SWIG ) # This has been addedinclude ( UseSWIG ) # This has been addedinclude_directories ( $ { RDKit_ExternalDir } ) SET ( RDK_BUILD_SWIG_CSHARP_WRAPPER ON ) # This has been added # find the gmcs executables on non-windows systems : if ( NOT WIN32 ) find_program ( GMCS_EXE gmcs ) if ( NOT GMCS_EXE ) MESSAGE ( `` gmcs ( executable ) is not found . Please add it to PATH and rerun cmake . '' ) MESSAGE ( FATAL_ERROR `` Can not find required executable gmcs '' ) endif ( NOT GMCS_EXE ) endif ( NOT WIN32 ) SET_SOURCE_FILES_PROPERTIES ( GraphMolCSharp.i PROPERTIES CPLUSPLUS ON ) # Setup a few variables for environment-specific thingsif ( WIN32 ) ADD_DEFINITIONS ( `` /W3 /wd4716 /bigobj '' ) SET ( PATH_SEP `` ; '' ) SET ( COPY_CMD xcopy $ { COPY_SOURCE } $ { COPY_DEST } /Y /I ) else ( ) SET ( PATH_SEP `` : '' ) SET ( COPY_CMD cp -p $ { COPY_SOURCE } $ { COPY_DEST } ) endif ( ) # Coax SWIG into playing nicely with Apple environmentsif ( APPLE ) SET ( CMAKE_SIZEOF_VOID_P 4 ) endif ( APPLE ) if ( CMAKE_SIZEOF_VOID_P MATCHES 4 ) SET ( CMAKE_SWIG_FLAGS -namespace `` GraphMolWrap '' ) else ( ) if ( WIN32 ) SET ( CMAKE_SWIG_FLAGS -namespace `` GraphMolWrap '' `` -DSWIGWORDSIZE64 '' `` -DSWIGWIN '' ) else ( ) SET ( CMAKE_SWIG_FLAGS -namespace `` GraphMolWrap '' `` -DSWIGWORDSIZE64 '' ) endif ( ) endif ( ) SET ( CMAKE_SWIG_OUTDIR $ { CMAKE_CURRENT_SOURCE_DIR } /swig_csharp ) if ( RDK_BUILD_INCHI_SUPPORT ) SET ( CMAKE_SWIG_FLAGS `` -DRDK_BUILD_INCHI_SUPPORT '' $ { CMAKE_SWIG_FLAGS } ) endif ( ) if ( RDK_BUILD_AVALON_SUPPORT ) SET ( CMAKE_SWIG_FLAGS `` -DRDK_BUILD_AVALON_SUPPORT '' $ { CMAKE_SWIG_FLAGS } ) endif ( ) FILE ( GLOB SWIG_SRC_FILES `` $ { CMAKE_CURRENT_SOURCE_DIR } /../*.i '' ) # we added all source files , now remove the ones that we 're not supporting in this build : if ( NOT RDK_BUILD_AVALON_SUPPORT ) LIST ( REMOVE_ITEM SWIG_SRC_FILES `` $ { CMAKE_CURRENT_SOURCE_DIR } /../AvalonLib.i '' ) endif ( ) if ( NOT RDK_BUILD_INCHI_SUPPORT ) LIST ( REMOVE_ITEM SWIG_SRC_FILES `` $ { CMAKE_CURRENT_SOURCE_DIR } /../Inchi.i '' ) endif ( ) SET ( SWIG_MODULE_RDKFuncs_EXTRA_DEPS $ { SWIG_SRC_FILES } ) SWIG_ADD_LIBRARY ( RDKFuncs TYPE MODULE LANGUAGE CSharp SOURCES GraphMolCSharp.i ) # it doesnt seem like the threading libs should need to be here , but # as of Oct 2012 using boost 1.51 under at least ubuntu 12.04 we get a # link error if they are n't there.SWIG_LINK_LIBRARIES ( RDKFuncs $ { RDKit_Wrapper_Libs } $ { RDKit_THREAD_LIBS } ) INSTALL ( TARGETS RDKFuncs DESTINATION $ { CMAKE_CURRENT_SOURCE_DIR } ) if ( NOT WIN32 ) # code adapted from the wrapper code for # GDCM : http : //gdcm.svn.sf.net/viewvc/gdcm/trunk/Wrapping/Java/CMakeLists.txt ? view=markup ADD_CUSTOM_COMMAND ( OUTPUT $ { CMAKE_CURRENT_SOURCE_DIR } /RDKit2DotNet.dll COMMAND $ { CMAKE_COMMAND } -E make_directory swig_csharp # # 1. run this custom command only after swig has been run . COMMAND $ { GMCS_EXE } -out : RDKit2DotNet.dll -t : library `` swig_csharp/*.cs '' WORKING_DIRECTORY $ { CMAKE_CURRENT_SOURCE_DIR } DEPENDS `` $ { swig_generated_file_fullname } '' ) ADD_CUSTOM_TARGET ( RDKFuncsDLL ALL DEPENDS RDKFuncs $ { CMAKE_CURRENT_SOURCE_DIR } /RDKit2DotNet.dll COMMENT `` building mono dll '' ) endif ( NOT WIN32 ) Could not copy the file `` D : \Desktop\rdkit-master\Code\JavaWrappers\csharp_wrapper\RDKFuncs.dll '' because it was not found . RDKit2DotNet git clone https : //github.com/bp-kelley/rdkit-csharp.gitgit clone https : //github.com/rdkit/rdkit.gitcd rdkit-csharp Downloading : https : //dist.nuget.org/win-x86-commandline/latest/nuget.exe to \Desktop\Build\rdkit-csharp\nuget.exe^CTerminate batch job ( Y/N ) ? n **PS D : \Desktop\Build > git clone https : //github.com/bp-kelley/rdkit-csharp.git > > git clone https : //github.com/rdkit/rdkit.git > > cd rdkit-csharpCloning into 'rdkit-csharp ' ... remote : Enumerating objects : 12 , done.remote : Counting objects : 100 % ( 12/12 ) , done.remote : Compressing objects : 100 % ( 9/9 ) , done.remote : Total 64 ( delta 5 ) , reused 7 ( delta 3 ) , pack-reused 52Unpacking objects : 100 % ( 64/64 ) , done.Cloning into 'rdkit ' ... remote : Enumerating objects : 83 , done.remote : Counting objects : 100 % ( 83/83 ) , done.remote : Compressing objects : 100 % ( 60/60 ) , done.remote : Total 61097 ( delta 34 ) , reused 38 ( delta 22 ) , pack-reused 61014Receiving objects : 100 % ( 61097/61097 ) , 148.64 MiB | 8.96 MiB/s , done.Resolving deltas : 100 % ( 46291/46291 ) , done.Checking out files : 100 % ( 3478/3478 ) , done.PS D : \Desktop\Build\rdkit-csharp > .\build.bat///////// TOO LONG TO POST TO STACKOVERFLOW CUT LINES /////////D : \Desktop\Build\rdkit-csharp > call get_nuget https : //dist.nuget.org/win-x86-commandline/latest/nuget.exeDownloading : https : //dist.nuget.org/win-x86-commandline/latest/nuget.exe to \Desktop\Build\rdkit-csharp\nuget.exe^CTerminate batch job ( Y/N ) ? nRunning cmake ... Feeds used : C : \Users\Sarco\.nuget\packages\ https : //api.nuget.org/v3/index.json C : \Program Files ( x86 ) \Microsoft SDKs\NuGetPackages\Attempting to gather dependency information for package 'boost-vc140.1.69.0 ' with respect to project 'D : \Desktop\Build\rdkit-csharp\Nuget.Local ' , targeting 'Any , Version=v0.0'///////// TOO LONG TO POST TO STACKOVERFLOW CUT LINES /////////Build started 11/05/2019 09:36:17 . 1 > Project `` D : \Desktop\Build\rdkit-csharp\build64\ALL_BUILD.vcxproj '' on node 1 ( Build target ( s ) ) . 1 > D : \Desktop\Build\rdkit-csharp\build64\ALL_BUILD.vcxproj ( 32,3 ) : error MSB4019 : The imported project `` D : \Microsoft .Cpp.Default.props '' was not found . Confirm that the path in the < Import > declaration is correct , and that the fi le exists on disk . 1 > Done Building Project `` D : \Desktop\Build\rdkit-csharp\build64\ALL_BUILD.vcxproj '' ( Build target ( s ) ) -- FAILED.Build FAILED . `` D : \Desktop\Build\rdkit-csharp\build64\ALL_BUILD.vcxproj '' ( Build target ) ( 1 ) - > D : \Desktop\Build\rdkit-csharp\build64\ALL_BUILD.vcxproj ( 32,3 ) : error MSB4019 : The imported project `` D : \Microso ft.Cpp.Default.props '' was not found . Confirm that the path in the < Import > declaration is correct , and that the file exists on disk . 0 Warning ( s ) 1 Error ( s ) Time Elapsed 00:00:00.14D : \Desktop\Build\rdkit-csharp\build64 > copy Code\JavaWrappers\csharp_wrapper\Release\RDKFuncs.dll Code\JavaWrappers\csharp_wrapperThe system can not find the path specified.D : \Desktop\Build\rdkit-csharp\build64 > copy ..\..\rdkit\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj Code\JavaWrappers\csharp_wrapper 1 file ( s ) copied.D : \Desktop\Build\rdkit-csharp\build64 > robocopy ..\..\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp Code\JavaWrappers\csharp_wrapper\swig_csharp /E -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ROBOCOPY : : Robust File Copy for Windows -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Started : 11 May 2019 09:36:17 Source : D : \Desktop\Build\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp\ Dest : D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\swig_csharp\ Files : * . * Options : * . * /S /E /DCOPY : DA /COPY : DAT /R:1000000 /W:30 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2019/05/11 09:36:17 ERROR 2 ( 0x00000002 ) Accessing Source Directory D : \Desktop\Build\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp\The system can not find the file specified.D : \Desktop\Build\rdkit-csharp\build64 > copy D : \Desktop\Build\rdkit-csharp\\RDKit.cs Code\JavaWrappers\csharp_wrapper\swig_csharp\RDKit.csThe system can not find the path specified . 0 file ( s ) copied.D : \Desktop\Build\rdkit-csharp\build64 > msbuild `` Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' /m /p : Configuration=Release /maxcpucount:4 /t : Build /p : Platform=AnyCPUMicrosoft ( R ) Build Engine version 4.7.3056.0 [ Microsoft .NET Framework , version 4.0.30319.42000 ] Copyright ( C ) Microsoft Corporation . All rights reserved.Build started 11/05/2019 09:36:18 . 1 > Project `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' on node 1 ( Build target ( s ) ) . 1 > PrepareForBuild : Creating directory `` bin\Release\ '' . Creating directory `` obj\Release\ '' . GenerateTargetFrameworkMonikerAttribute : Skipping target `` GenerateTargetFrameworkMonikerAttribute '' because all output files are up-to-date with respect t o the input files . CoreCompile : C : \Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /errorreport : prom pt /warn:4 /define : TRACE /highentropyva- /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Microsoft\Fra mework\.NETFramework\v4.0\Microsoft.CSharp.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Micros oft\Framework\.NETFramework\v4.0\mscorlib.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Microso ft\Framework\.NETFramework\v4.0\System.Core.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Micro soft\Framework\.NETFramework\v4.0\System.Data.DataSetExtensions.dll '' /reference : '' C : \Program Files ( x86 ) \Refere nce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.dll '' /reference : '' C : \Program Files ( x86 ) \Refe rence Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll '' /reference : '' C : \Program Files ( x86 ) \Referen ce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xml.dll '' /reference : '' C : \Program Files ( x86 ) \Refere nce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xml.Linq.dll '' /debug : pdbonly /filealign:512 /opti mize+ /out : obj\Release\RDKit2DotNet.dll /target : library /utf8output 1 > CSC : warning CS2008 : No source files specified [ D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_ wrapper\RDKit2DotNet.csproj ] 1 > C : \Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets ( 3713,5 ) : error MSB3030 : Could not copy th e file `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKFuncs.dll '' because it was not found . [ D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj ] 1 > Done Building Project `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.cspro j '' ( Build target ( s ) ) -- FAILED.Build FAILED . `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' ( Build target ) ( 1 ) - > ( CoreCompile target ) - > CSC : warning CS2008 : No source files specified [ D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\cshar p_wrapper\RDKit2DotNet.csproj ] `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' ( Build target ) ( 1 ) - > ( _CopyOutOfDateSourceItemsToOutputDirectoryAlways target ) - > C : \Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets ( 3713,5 ) : error MSB3030 : Could not copy the file `` D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKFuncs.dll '' because it was no t found . [ D : \Desktop\Build\rdkit-csharp\build64\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj ] 1 Warning ( s ) 1 Error ( s ) Time Elapsed 00:00:00.63///////// TOO LONG TO POST TO STACKOVERFLOW CUT LINES ///////// -- Using unsigned short -- Check if the system is big endian - little endian -- Found Catch2 source in D : /Desktop/Build/rdkit/External/catch/catchCATCH : D : /Desktop/Build/rdkit/External/catch/catch/single_include -- Could NOT find InChI in system locations ( missing : INCHI_LIBRARY INCHI_INCLUDE_DIR ) CUSTOM_INCHI_PATH = D : /Desktop/Build/rdkit/External/INCHI-API -- Found InChI software locally -- Boost version : 1.69.0 -- Looking for pthread.h///////// TOO LONG TO POST TO STACKOVERFLOW CUT LINES ///////// in D : /Desktop/Build/rdkit/External/CoordGen/maeparserCMake Error at D : /Program Files/CMake/share/cmake-3.14/Modules/FindBoost.cmake:2147 ( message ) : Unable to find the requested Boost libraries . Boost version : 1.69.0 Boost include path : D : /Desktop/Build/rdkit-csharp/Nuget.Local/boost.1.69.0.0/lib/native/include Could not find the following Boost libraries : boost_system boost_iostreams Some ( but not all ) of the required Boost libraries were found . You may need to install these additional Boost libraries . Alternatively , set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.Call Stack ( most recent call first ) : External/CoordGen/CMakeLists.txt:39 ( find_package ) -- coordgen include dir set as coordgen_INCLUDE_DIRS-NOTFOUND -- coordgen libraries set as 'coordgen_LIBRARIES-NOTFOUND ' -- coordgen templates file set as 'coordgen_TEMPLATE_FILE-NOTFOUND ' -- Could NOT find coordgen ( missing : coordgen_INCLUDE_DIRS coordgen_LIBRARIES coordgen_TEMPLATE_FILE ) -- Found coordgenlibs source in D : /Desktop/Build/rdkit/External/CoordGen/coordgen -- Could NOT find ZLIB ( missing : ZLIB_LIBRARY ZLIB_INCLUDE_DIR ) CMake Error at D : /Program Files/CMake/share/cmake-3.14/Modules/FindBoost.cmake:2147 ( message ) : Unable to find the requested Boost libraries . Boost version : 1.69.0 Boost include path : D : /Desktop/Build/rdkit-csharp/Nuget.Local/boost.1.69.0.0/lib/native/include Could not find the following Boost libraries : boost_system boost_iostreams Some ( but not all ) of the required Boost libraries were found . You may need to install these additional Boost libraries . Alternatively , set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.Call Stack ( most recent call first ) : Code/RDStreams/CMakeLists.txt:4 ( find_package ) -- Could NOT find BoostCMake Error at D : /Program Files/CMake/share/cmake-3.14/Modules/FindBoost.cmake:2147 ( message ) : Unable to find the requested Boost libraries . Boost version : 1.69.0 Boost include path : D : /Desktop/Build/rdkit-csharp/Nuget.Local/boost.1.69.0.0/lib/native/include Could not find the following Boost libraries : boost_system boost_iostreams Some ( but not all ) of the required Boost libraries were found . You may need to install these additional Boost libraries . Alternatively , set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.Call Stack ( most recent call first ) : Code/GraphMol/FileParsers/CMakeLists.txt:7 ( find_package ) -- Could NOT find Boost== Making EnumerateLibrary without boost Serialization support== Making FilterCatalog without boost Serialization support -- Found PythonInterp : D : /Program Files/Python36-32/python.exe ( found version `` 3.6.3 '' ) == Updating Filters.cpp from pains file== Done updating pains files -- Could NOT find PkgConfig ( missing : PKG_CONFIG_EXECUTABLE ) -- Found Cairo : D : /Desktop/Build/rdkit-csharp/Nuget.Local/cairo.1.12.18.0/build/native/include== Making SubstructLibrary without boost Serialization support -- Found RapidJSON source in D : /Desktop/Build/rdkit/External -- Found SWIG : C : /swig/swig.exe ( found version `` 4.0.0 '' ) CMake Error at D : /Program Files/CMake/share/cmake-3.14/Modules/FindBoost.cmake:2147 ( message ) : Unable to find the requested Boost libraries . Boost version : 1.69.0 Boost include path : D : /Desktop/Build/rdkit-csharp/Nuget.Local/boost.1.69.0.0/lib/native/include Could not find the following Boost libraries : boost_system boost_iostreams Some ( but not all ) of the required Boost libraries were found . You may need to install these additional Boost libraries . Alternatively , set BOOST_LIBRARYDIR to the directory containing Boost libraries or BOOST_ROOT to the location of Boost.Call Stack ( most recent call first ) : Code/JavaWrappers/CMakeLists.txt:43 ( find_package ) -- Could NOT find BoostSUFFIX : JAVA_LIBS : AvalonLib ; avalon_clib ; RDInchiLib ; Inchi ; RGroupDecomposition ; SubstructLibrary ; MolStandardize ; FilterCatalog ; Catalogs ; FMCS ; MolDraw2D ; FileParsers ; SmilesParse ; Depictor ; SubstructMatch ; ChemReactions ; Fingerprints ; ChemTransforms ; Subgraphs ; GraphMol ; DataStructs ; Trajectory ; Descriptors ; PartialCharges ; MolTransforms ; DistGeomHelpers ; DistGeometry ; ForceFieldHelpers ; ForceField ; EigenSolvers ; Optimizer ; MolAlign ; Alignment ; SimDivPickers ; RDGeometryLib ; RDStreams ; RDGeneralCMake Warning ( dev ) at D : /Program Files/CMake/share/cmake-3.14/Modules/UseSWIG.cmake:600 ( message ) : Policy CMP0078 is not set : UseSWIG generates standard target names . Run `` cmake -- help-policy CMP0078 '' for policy details . Use the cmake_policy command to set the policy and suppress this warning.Call Stack ( most recent call first ) : Code/JavaWrappers/csharp_wrapper/CMakeLists.txt:63 ( SWIG_ADD_LIBRARY ) This warning is for project developers . Use -Wno-dev to suppress it.CMake Warning ( dev ) at D : /Program Files/CMake/share/cmake-3.14/Modules/UseSWIG.cmake:460 ( message ) : Policy CMP0086 is not set : UseSWIG honors SWIG_MODULE_NAME via -module flag . Run `` cmake -- help-policy CMP0086 '' for policy details . Use the cmake_policy command to set the policy and suppress this warning.Call Stack ( most recent call first ) : D : /Program Files/CMake/share/cmake-3.14/Modules/UseSWIG.cmake:695 ( SWIG_ADD_SOURCE_TO_MODULE ) Code/JavaWrappers/csharp_wrapper/CMakeLists.txt:63 ( SWIG_ADD_LIBRARY ) This warning is for project developers . Use -Wno-dev to suppress it. -- Configuring incomplete , errors occurred ! See also `` D : /Desktop/Build/rdkit-csharp/build32/CMakeFiles/CMakeOutput.log '' .See also `` D : /Desktop/Build/rdkit-csharp/build32/CMakeFiles/CMakeError.log '' .D : \Desktop\Build\rdkit-csharp\build32 > msbuild `` ALL_BUILD.vcxproj '' /m /p : PlatformTarget=x86 /p : Configuration=Release /maxcpucount:4 /t : BuildMicrosoft ( R ) Build Engine version 4.7.3056.0 [ Microsoft .NET Framework , version 4.0.30319.42000 ] Copyright ( C ) Microsoft Corporation . All rights reserved.MSBUILD : error MSB1009 : Project file does not exist.Switch : ALL_BUILD.vcxprojD : \Desktop\Build\rdkit-csharp\build32 > copy Code\JavaWrappers\csharp_wrapper\Release\RDKFuncs.dll Code\JavaWrappers\csharp_wrapperThe system can not find the path specified.D : \Desktop\Build\rdkit-csharp\build32 > copy ..\..\rdkit\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj Code\JavaWrappers\csharp_wrapper 1 file ( s ) copied.D : \Desktop\Build\rdkit-csharp\build32 > robocopy ..\..\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp Code\JavaWrappers\csharp_wrapper\swig_csharp /E -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - ROBOCOPY : : Robust File Copy for Windows -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - Started : 11 May 2019 09:36:36 Source : D : \Desktop\Build\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp\ Dest : D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\swig_csharp\ Files : * . * Options : * . * /S /E /DCOPY : DA /COPY : DAT /R:1000000 /W:30 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2019/05/11 09:36:36 ERROR 2 ( 0x00000002 ) Accessing Source Directory D : \Desktop\Build\rdkit\Code\JavaWrappers\csharp_wrapper\swig_csharp\The system can not find the file specified.D : \Desktop\Build\rdkit-csharp\build32 > copy D : \Desktop\Build\rdkit-csharp\\RDKit.cs Code\JavaWrappers\csharp_wrapper\swig_csharp\RDKit.csThe system can not find the path specified . 0 file ( s ) copied.D : \Desktop\Build\rdkit-csharp\build32 > msbuild `` Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' /m /p : Configuration=Release /maxcpucount:4 /t : Build /p : Platform=AnyCPUMicrosoft ( R ) Build Engine version 4.7.3056.0 [ Microsoft .NET Framework , version 4.0.30319.42000 ] Copyright ( C ) Microsoft Corporation . All rights reserved.Build started 11/05/2019 09:36:36 . 1 > Project `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' on node 1 ( Build target ( s ) ) . 1 > PrepareForBuild : Creating directory `` bin\Release\ '' . Creating directory `` obj\Release\ '' . GenerateTargetFrameworkMonikerAttribute : Skipping target `` GenerateTargetFrameworkMonikerAttribute '' because all output files are up-to-date with respect t o the input files . CoreCompile : C : \Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /errorreport : prom pt /warn:4 /define : TRACE /highentropyva- /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Microsoft\Fra mework\.NETFramework\v4.0\Microsoft.CSharp.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Micros oft\Framework\.NETFramework\v4.0\mscorlib.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Microso ft\Framework\.NETFramework\v4.0\System.Core.dll '' /reference : '' C : \Program Files ( x86 ) \Reference Assemblies\Micro soft\Framework\.NETFramework\v4.0\System.Data.DataSetExtensions.dll '' /reference : '' C : \Program Files ( x86 ) \Refere nce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Data.dll '' /reference : '' C : \Program Files ( x86 ) \Refe rence Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.dll '' /reference : '' C : \Program Files ( x86 ) \Referen ce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xml.dll '' /reference : '' C : \Program Files ( x86 ) \Refere nce Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Xml.Linq.dll '' /debug : pdbonly /filealign:512 /opti mize+ /out : obj\Release\RDKit2DotNet.dll /target : library /utf8output 1 > CSC : warning CS2008 : No source files specified [ D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_ wrapper\RDKit2DotNet.csproj ] 1 > C : \Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets ( 3713,5 ) : error MSB3030 : Could not copy th e file `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKFuncs.dll '' because it was not found . [ D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj ] 1 > Done Building Project `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.cspro j '' ( Build target ( s ) ) -- FAILED.Build FAILED . `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' ( Build target ) ( 1 ) - > ( CoreCompile target ) - > CSC : warning CS2008 : No source files specified [ D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\cshar p_wrapper\RDKit2DotNet.csproj ] `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj '' ( Build target ) ( 1 ) - > ( _CopyOutOfDateSourceItemsToOutputDirectoryAlways target ) - > C : \Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets ( 3713,5 ) : error MSB3030 : Could not copy the file `` D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKFuncs.dll '' because it was no t found . [ D : \Desktop\Build\rdkit-csharp\build32\Code\JavaWrappers\csharp_wrapper\RDKit2DotNet.csproj ] 1 Warning ( s ) **
Trying to build the C # wrappers for RDKit with build.bat from bp-kelley/rdkit-csharp
C_sharp : Suppose I want to check a bunch of objects to make sure none is null : It is an alluring prospect to write a helper function to accept a variable number of arguments and simplify this kind of check : Then the above code could become : Right ? Wrong . If obj is null , then I 'll get a NullReferenceException when I try to pass obj.Parameters to NoNulls.So the above approach is clearly misguided . But the if statement using the & & operator works just fine since it is short-circuited . So : is there any way to make a method short-circuited , so that its arguments are not evaluated until explicitly referenced within the method ? <code> if ( obj ! = null & & obj.Parameters ! = null & & obj.Parameters.UserSettings ! = null ) { // do something with obj.Parameters.UserSettings } static bool NoNulls ( params object [ ] objects ) { for ( int i = 0 ; i < objects.Length ; i++ ) if ( objects [ i ] == null ) return false ; return true ; } if ( NoNulls ( obj , obj.Parameters , obj.Parameters.UserSettings ) ) { // do something }
Can I force my own short-circuiting in a method call ?
C_sharp : I 'm trying to compile a .cs file using a CSharpCodeProvider from a .net 3.5 app and I want to target the .net4 compiler but I 'm getting this error `` Compiler executable file csc.exe can not be found '' . I have .net4 installed . Below is the code that I 'm using with some lines omitted for brevity . When I set CompilerVersion to `` v3.5 '' I get no errors . <code> CompilerResults results = null ; using ( CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < string , string > ( ) { { `` CompilerVersion '' , `` v4.0 '' } , } ) ) { CompilerParameters options = new CompilerParameters ( ) ; ... results = provider.CompileAssemblyFromFile ( options , Directory.GetFiles ( path , `` *.cs '' , SearchOption.AllDirectories ) ) ; }
Is it possible to target the .net4 compiler from a .net3.5 app with a CSharpCodeProvider ?
C_sharp : In C # I am trying to write code where I would be creating a Func delegate which is in itself generic . For example the following ( non-Generic ) delegate is returning an arbitrary string : I on the other hand want to create a generic which acts similarly to generic methods . For example if I want a generic Func to return default ( T ) for a type T. I would imagine that I write code as follows : Then I would use it as getDefaultObject < string > ( ) which would return null and if I were to write getDefaultObject < int > ( ) would return 0.This question is not merely an academic excercise . I have found numerous places where I could have used this but I can not get the syntax right . Is this possible ? Are there any libraries which provide this sort of functionality ? <code> Func < string > getString = ( ) = > `` Hello ! `` ; Func < T > < T > getDefaultObject = < T > ( ) = > default ( T ) ;
C # Generic Generics ( A Serious Question )
C_sharp : Possible Duplicate : Why check this ! = null ? The part I do n't understand is the fact that it is checking for the current instance , this , against null . The comment is a bit confusing , so I was wondering what does that comment actually mean ? Can anyone give an example of how this could break if that check was not there , and does this mean that I should also place that check in my classes ? <code> // Determines whether two strings match . [ ReliabilityContract ( Consistency.WillNotCorruptState , Cer.MayFail ) ] public override bool Equals ( Object obj ) { //this is necessary to guard against reverse-pinvokes and //other callers who do not use the callvirt instruction if ( this == null ) throw new NullReferenceException ( ) ; String str = obj as String ; if ( str == null ) return false ; if ( Object.ReferenceEquals ( this , obj ) ) return true ; return EqualsHelper ( this , str ) ; }
Why does String.Equals ( Object obj ) check to see if this == null ?
C_sharp : Is it possible to build up a bit mask based on the result of a linq query ; for example : <code> class MyClass { public int Flag { get ; set ; } public bool IsSelected { get ; set ; } } myVar = GetlistMyClass ( ) ; int myFlag = myVar.Where ( a = > a.IsSelected ) .Select ( ? ) ;
Building a bit flag using linq / lambda
C_sharp : I 've created a azure mobile service which basically consist of 2 Entities and 2 TableControllers . Those both entities have a 1:1 relation . The controllers are the standard scaffold generated controllers . When I 'm try to insert a entity1 instance with a reference to a already existing entity2 i get the following message : I used the following JSON in the request body : Is it possible to use an already existing entity as a reference in .NET Code First/Azure Mobile Service ? I 'm not quite sure if this is a more EF CodeFirst or azure mobile service related question.Thanks . <code> public class Entity1 : EntityData { public int Value { get ; set ; } public DateTime Date { get ; set ; } public string Name { get ; set ; } public virtual Entity2 Reference { get ; set ; } } public class Entity2 : EntityData { public string Name { get ; set ; } } { `` $ id '' : '' 1 '' , '' message '' : '' The operation failed due to a conflict : 'Violation of PRIMARY KEY constraint 'PK_Service.Entity2 ' . Can not insertduplicate key in object 'Service.Entity2 ' . The duplicate keyvalue is ( 32aec44a282e42b7bc51096052335dad ) .\r\nThe statement has been terminated. ' . '' } { `` value '' : 1 , `` date '' : `` 2015-04-27T06:51:47.641Z '' , `` name '' : `` name '' , `` project '' : { `` id '' : `` 32aec44a282e42b7bc51096052335dad '' , } }
Creating an entity with a reference to an other entity in azure mobile service
C_sharp : Why C # compiler allows this to compile and throws runtime exception when run ? This does compile with any interface and it does n't compile if you replace IDisposable with concrete class . <code> class Program { static void Main ( string [ ] args ) { IEnumerable < Test > list = new List < Test > ( ) { new Test ( ) } ; foreach ( IDisposable item in list ) { } } } public class Test { }
C # foreach unexpected behavior
C_sharp : Say I 'm trying to test a simple Set classAnd suppose I 'm trying to test that no duplicate values can exist in the set . My first option is to insert some sample data into the set , and test for duplicates using my knowledge of the data I used , for example : My second option is to test for my condition generically : Of course , in this example , I conveniently have a set implementation to check against , as well as code to compare collections ( CollectionAssert ) . But what if I did n't have either ? This code would be definitely more complicated than that of the previous option ! And this is the situation when you are testing your real life custom business logic . Granted , testing for expected conditions generically covers more cases - but it becomes very similar to implementing the logic again ( which is both tedious and useless - you ca n't use the same code to check itself ! ) . Basically I 'm asking whether my tests should look like `` insert 1 , 2 , 3 then check something about 3 '' or `` insert 1 , 2 , 3 and check for something in general '' EDIT - To help me understand , please state in your answer if you prefer OPTION 1 or OPTION 2 ( or neither , or that it depends on the case , etc ) . Just to clarify , it 's pretty clear that in this case ( IntSet ) , option 2 is better in all aspects . However , my question pertains to the cases where you do n't have an alternative implementation to check against , so the code in option 2 would be definitely more complicated than option 1 . <code> public IntSet : IEnumerable < int > { Add ( int i ) { ... } //IEnumerable implementation ... } //OPTION 1 void InsertDuplicateValues_OnlyOneInstancePerValueShouldBeInTheSet ( ) { var set = new IntSet ( ) ; //3 will be added 3 times var values = new List < int > { 1 , 2 , 3 , 3 , 3 , 4 , 5 } ; foreach ( int i in values ) set.Add ( i ) ; //I know 3 is the only candidate to appear multiple times int counter = 0 ; foreach ( int i in set ) if ( i == 3 ) counter++ ; Assert.AreEqual ( 1 , counter ) ; } //OPTION 2 void InsertDuplicateValues_OnlyOneInstancePerValueShouldBeInTheSet ( ) { var set = new IntSet ( ) ; //The following could even be a list of random numbers with a duplicate var values = new List < int > { 1 , 2 , 3 , 3 , 3 , 4 , 5 } ; foreach ( int i in values ) set.Add ( i ) ; //I am not using my prior knowledge of the sample data //the following line would work for any data CollectionAssert.AreEquivalent ( new HashSet < int > ( values ) , set ) ; }
Unit Testing - Algorithm or Sample based ?
C_sharp : Why the designers of C # did not allow for something like this ? One of the most important ways to safe multi-threading is the use of immutable objects/classes , yet there is no way to declare a class as immutable . I know I can make it immutable by proper implementation but having this enforced by class declaration would make it so much easier and safer . Commenting a class as immutable is a `` door prop '' solution at best.One look at a class declaration and you would instantly know it was immutable . If you had to modify someone else 's code you would know a class does not allow changes by intent . I can only see advantages here but I ca n't believe no one thought about this before . So why is not supported ? EDITSome say this is not very important feature but that does not really convince me . Multicore processors showed up because increasing performance by frequency hit a wall . Supercomputers are heavily multiprocessor machines . Parallel processing is more and more important and is one of the main ways to improve performance . The support for multithreading and parallel processing in .NET is significant ( various lock types , thread pool , tasks , async calls , concurrent collections , blocking collection , parallel foreach , PLINQ and so on ) and it seems to me everything that helps you write parallel code more easily gives an edge . Even if it 's non trivial to implement . <code> public readonly class ImmutableThing { ... }
Why there is no declarative immutability in C # ?
C_sharp : I need some help trying to figure what I 'm doing wrong . I 'm trying to get a collection of items from the system log on a separate thread to keep the form from being frozen during the collection process . I can get the background worker to grab them all , but I am having some issues add them to the ListBox on the form.Obviously this does n't work as expected , since there are 2 separate threads , and you ca n't change objects on different threads , as I have found out . So , If someone could guide me in the right direction , I would be thankful . <code> private void backgroundWorker1_DoWork ( object sender , DoWorkEventArgs e ) { foreach ( System.Diagnostics.EventLogEntry entry in eventLog1.Entries ) { listBox1.Items.Add ( entry.EntryType.ToString ( ) + `` - `` + entry.TimeWritten + `` - `` + entry.Source ) ; } }
Working with threads C #
C_sharp : So I have a basic crypto class . Note that this is a simplified implementation to illustrate the question.Now to my mind both these methods have an extra byte array and string instance . xmlString and bytes in Encrypt and decryptedString and decryptedBytes in DecryptSo how can I rework the usage of streams in this class to minimize the memory usage ? And here is a unit test=== Edit ===Based on the anser from Damien_The_Unbeliever I tried this . Which fails the unit test <code> class Crypto { Rijndael rijndael ; public Crypto ( ) { rijndael = Rijndael.Create ( ) ; rijndael.Key = Encoding.ASCII.GetBytes ( `` aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa '' ) ; ; rijndael.IV = Encoding.ASCII.GetBytes ( `` bbbbbbbbbbbbbbbb '' ) ; ; rijndael.Padding = PaddingMode.PKCS7 ; } public byte [ ] Encrypt ( object obj ) { var settings = new XmlWriterSettings { OmitXmlDeclaration = true } ; var ns = new XmlSerializerNamespaces ( ) ; ns.Add ( `` '' , `` '' ) ; var sb = new StringBuilder ( ) ; var xmlSerializer = new XmlSerializer ( obj.GetType ( ) ) ; using ( var xmlWriter = XmlWriter.Create ( sb , settings ) ) { xmlSerializer.Serialize ( xmlWriter , obj , ns ) ; xmlWriter.Flush ( ) ; } var xmlString = sb.ToString ( ) ; var bytes = Encoding.UTF8.GetBytes ( xmlString ) ; using ( var encryptor = rijndael.CreateEncryptor ( ) ) using ( var stream = new MemoryStream ( ) ) using ( var crypto = new CryptoStream ( stream , encryptor , CryptoStreamMode.Write ) ) { crypto.Write ( bytes , 0 , bytes.Length ) ; crypto.FlushFinalBlock ( ) ; stream.Position = 0 ; var encrypted = new byte [ stream.Length ] ; stream.Read ( encrypted , 0 , encrypted.Length ) ; return encrypted ; } } public T Decrypt < T > ( byte [ ] encryptedValue ) { byte [ ] decryptedBytes ; using ( var decryptor = rijndael.CreateDecryptor ( ) ) using ( var stream = new MemoryStream ( ) ) using ( var crypto = new CryptoStream ( stream , decryptor , CryptoStreamMode.Write ) ) { crypto.Write ( encryptedValue , 0 , encryptedValue.Length ) ; crypto.FlushFinalBlock ( ) ; stream.Position = 0 ; decryptedBytes = new Byte [ stream.Length ] ; stream.Read ( decryptedBytes , 0 , decryptedBytes.Length ) ; } var ser = new XmlSerializer ( typeof ( T ) ) ; var decryptedString = Encoding.UTF8.GetString ( decryptedBytes ) ; using ( var stringReader = new StringReader ( decryptedString ) ) using ( var xmlReader = new XmlTextReader ( stringReader ) ) { return ( T ) ser.Deserialize ( xmlReader ) ; } } } [ TestFixture ] public class Tests { [ Test ] public void Run ( ) { var before = new MyClassForSerialize ( ) { Property = `` Sdf '' } ; var dataEncryptor = new Crypto ( ) ; var encrypted = dataEncryptor.Encrypt ( before ) ; var after = dataEncryptor.Decrypt < MyClassForSerialize > ( encrypted ) ; Assert.AreEqual ( before.Property , after.Property ) ; } } public class MyClassForSerialize { public string Property { get ; set ; } } public byte [ ] Encrypt ( object obj ) { var settings = new XmlWriterSettings { OmitXmlDeclaration = true } ; var ns = new XmlSerializerNamespaces ( ) ; ns.Add ( `` '' , `` '' ) ; var xmlSerializer = new XmlSerializer ( obj.GetType ( ) ) ; using ( var encryptor = rijndael.CreateEncryptor ( ) ) using ( var stream = new MemoryStream ( ) ) using ( var crypto = new CryptoStream ( stream , encryptor , CryptoStreamMode.Write ) ) { using ( var xmlWriter = XmlWriter.Create ( crypto , settings ) ) { xmlSerializer.Serialize ( xmlWriter , obj , ns ) ; xmlWriter.Flush ( ) ; } crypto.FlushFinalBlock ( ) ; stream.Position = 0 ; return stream.ToArray ( ) ; } }
How to avoid extra memory use during encryption and decryption ?
C_sharp : I am using ThreadPool with the follwoing code : -I am not sure what does o= > does in this code . Can anyone help me out . <code> ThreadPool.QueueUserWorkItem ( o = > MyFunction ( ) ) ;
What is = > operator in this code
C_sharp : OK OK , I know this is a hack , but this was for a tiny data-manipulation project and I wanted to play around . ; - ) I was always under the impression that the compiler would examine all anonymous types used in a C # program and if the properties were the same , it would only create one class behind the scenes.So let 's say I want to create an anonymous type out of some typed datasets that I have : I can now do fun things like smallData2.Except ( smallData1 ) ; etc. , and it all works.Now , what if I have a bigger pair of anonymous types : Now when I do bigData2.Except ( bigData1 ) ; the compiler complains : Why ? Too many properties , so the compiler decides it 's not worth it to optimize ? Thanks ! <code> var smallData1 = new smallData1 ( ) .GetData ( ) .Select ( x = > new { Name = x.NAME , x.ADDRESS , City = x.CITY , State = x.STATE , Zip = x.ZIP , Country = x.COUNTRY , ManagerName = x.MANAGER_NAME , ManagerID = x.MANAGER_ID } ) ; var smallData2 = new smallData2 ( ) .GetData ( ) .Select ( x = > new { x.Name , x.ADDRESS , x.City , x.State , x.Zip , x.Country , x.ManagerName , x.ManagerID } ) ; var bigData1 = new BigAdapter1 ( ) .GetData ( ) .Select ( x = > new { x.FirstName , x.LastName , x.Address , x.City , x.State , x.Zip , x.Country , x.Phone , x.Email , x.Website , x.Custom1 , x.Custom2 , x.Custom3 , x.Custom4 , x.Custom5 , x.Custom6 , x.Custom7 , x.Custom8 , x.Custom9 , x.Custom10 , x.Custom11 , x.Custom12 , x.Custom13 , x.Custom14 , x.Custom15 , x.Custom16 , x.Custom17 , x.Custom18 , x.Custom19 , x.Custom20 , x.Custom21 , x.Custom22 , x.Custom23 , x.Custom24 , x.Custom25 , x.Custom26 , x.Custom27 , x.Custom28 , x.Custom29 } ) ; var bigData2 = new BigAdapter2 ( ) .GetData ( ) .Select ( x = > new { x.FirstName , x.LastName , x.Address , x.City , x.State , x.Zip , x.Country , x.Phone , x.Email , x.Website , x.Custom1 , x.Custom2 , x.Custom3 , x.Custom4 , x.Custom5 , x.Custom6 , x.Custom7 , x.Custom8 , x.Custom9 , x.Custom10 , x.Custom11 , x.Custom12 , x.Custom13 , x.Custom14 , x.Custom15 , x.Custom16 , x.Custom17 , x.Custom18 , x.Custom19 , x.Custom20 , x.Custom21 , x.Custom22 , x.Custom23 , x.Custom24 , x.Custom25 , x.Custom26 , x.Custom27 , x.Custom28 , x.Custom29 } ) ; Instance argument : can not convert from'System.Data.EnumerableRowCollection < AnonymousType # 1 > ' to'System.Linq.IQueryable < AnonymousType # 2 > '
Compiler optimizations of anonymous types
C_sharp : I 'm looking for some kind of OffsetTime support in NodaTime , but am not seeing anything . I am receiving data in a format such as `` 17:13:00+10:00 '' . I am to treat this as a time offset , applying it to a given date ( which the user is in control of ) to arrive at a local time for display purposes.The best I 've been able to come up with is this : I guess I 'm wondering whether I 'm overlooking a better way to do this . <code> // the date for this OffsetDateTime will be 1/1/2000var parsed = OffsetDateTimePattern.CreateWithInvariantCulture ( `` HH : mm : sso < G > '' ) .Parse ( input ) .Value ; var desiredLocalDate = new LocalDate ( 2017 , 06 , 13 ) ; var adjusted = new OffsetDateTime ( new LocalDateTime ( desiredLocalDate.Year , desiredLocalDate.Month , desiredLocalDate.Day , parsed.Hour , parsed.Minute , parsed.Second , parsed.Millisecond ) , parsed.Offset ) ; var localTime = adjusted.LocalDateTime ;
OffsetTime in NodaTime
C_sharp : I came across the following piece of code during a code review.My intuition is telling me that this is n't following proper OOP.I 'm thinking that instead the LoadObject method should return a new SomeObject object , instead of modifying the one passed into it . Though I ca n't really find a proper explanation of why this is better . Is my solution better ? and if so why ? specifically what OOP principles or standards are broken in the given code example ( if any ) ? <code> public void someMethod ( ) { ... var someObject = new SomeObject ( ) ; LoadSomeObject ( reader , someObject ) ; } private void LoadSomeObject ( SqlDataReader reader , SomeObject someObject ) { someObject.Id = reader.GetGuid ( 0 ) ; }
Returning a new Object vs modifying one passed in as a parameter
C_sharp : I have some domain classes that look something like this , that I want to model with Code First ( in EF 4.3 ) .In every example I see though , foreign object references are added in the Foo class . Can my Foo class be agnostic of the Bar and Baz class , or do I really need to do something like this ? According to this answer , classes do need to have navigation properties . I 'm new at Code First , so can anyone explain why this might be the case ? Is there a way I can avoid polluting my Foo class like this by using the Fluent API ? It seems weird to me that Foo would need to know about every class that uses it . Is my design simply fundamentally flawed in some way ? <code> public class Foo { // ... } public class Bar { // ... public Foo Foo { get ; set ; } } public class Baz { // ... public Foo Foo { get ; set ; } } public class Foo { // ... public virtual Bar { get ; set ; } public virtual Baz { get ; set ; } }
Why do Code First classes need navigation properties ?
C_sharp : I can´t remove an element from an IEnumerable list , but this list is a reference to a List , a private attribute of an other class.If I put personsCollection.Remove ( theElement ) in the same class ( class Manager ) , it works perfect , but I need to delete the element since the other class ( class ManagerDelete ) . Please how can I do this ? Thanks . <code> class Other { //Some code public IEnumerable < Person > SearchByPhone ( string value ) { return from person in personCollection where person.SPhone == value select person ; } } class ManagerDelete { //Some codeIEnumerable < Person > auxList= SearchByPhone ( value ) ; //I have a method for delete here } class Manager { //Some code private List < Person > personsCollection = new List < Person > ( ) ; }
Delete an element from a generic list
C_sharp : I 'm currently working on an upgrade to a project that extensively uses COM / MFC / ( who knows how many other technologies ) . As part of the upgrade , we 're trying to move as much functionality as we can into managed C # code , but unfortunately some stuff just ca n't move ( for reasons I wo n't go into ) . One of those things is a section of code that grossly abuses COM , and returns pointers in the HRESULTs that later get cast to various other COM-interface implementing objects . I 've tried the following code to convert an HRESULT into a pointer that I can then get an interface from : ... . but , no COM exception gets thrown , and I 'm guessing it 's because the pointer is not a negative value , and hence is n't technically a COM error . Is there any way to configure COM on the object to throw a COM exception on anything BUT S_OK ( 0 ) ? <code> MyComInterfaceInCS myObj = null ; try { world.GetTD_MyComInterfaceInCS ( ) ; } catch ( COMException comException ) { int pointerValue = Marshal.GetHRForException ( comException ) ; IntPtr myObjPointer = new IntPtr ( pointerValue ) ; myObj = ( MyComInterfaceInCS ) Marshal.GetObjectForIUnknown ( myObjPointer ) ; }
Get a COM object to throw an exception on any result except S_OK ( 0 ) in C #
C_sharp : I am creating an extension method that performs a test on an object to see if it has a specific custom attribute . I want to create a unit test for my extension method . How can I assert that the test in the extension method should fail ? Basically , the ShouldValidateTheseFields does reflection and asserts that it should have a custom attribute on the field named `` Field '' and I need to assert that it failed . <code> [ Test ] public void ShouldFailIfEmailAttributeMissingFromFieldName ( ) { // -- Arrange var model = new { Field = 1 } ; // -- Act model.ShouldValidateTheseFields ( new List < FieldValidation > { new EmailAddressFieldValidation { ErrorId = 1 , ErrorMessage = `` Message '' , FieldName = nameof ( model.Field ) } } ) ; // -- Assert }
Asserting that a system under test should throw an assertion exception
C_sharp : Assume I have an interface such asTIn being contra-variant , and TOut being co-variant.Now , I want callers to be able to specify some function to be executed on the input 's value , so naïvely I would add the following method to the interface : which … does not work . TIn is now required to be covariant , and TOut contravariant.I understand , that I can not use covariant generic types as input for methods , but I thought I could use them in a nested generic type which itself specifies the variance ( Func < in T1 , out TResult > ) .I tried creating a new delegate type with co-/contravariant types and change the interface to accept an argument of this type , to no avail ( same error ) .I there a way I can make the compiler happy ? Is this even possible ( for instance with other nested types , or additional generic arguments ) ? If not , why not ? <code> public interface IInterface < in TIn , out TOut > { IInterface < TIn , TOut > DoSomething ( TIn input ) ; } IInterface < TIn , TOut > DoSomethingWithFunc ( Func < TIn , TOut > func ) ; public delegate TOut F < in TDlgIn , out TDlgOut > ( TDlgIn input ) ; public interface IInterface < in TIn , out TOut > { IInterface < TIn , TOut > DoSomethingWithFunc ( F < TIn , TOut > func ) ; }
Co/contravariance with Func < in T1 , out TResult > as parameter
C_sharp : I am trying to convert List to json . Structure is as follow : This is producing the result as expected : How can I get the results like : - <code> public class ResourceCollection { public string Name { get ; set ; } public Resources Resources { get ; set ; } } public class Resources { public string en { get ; set ; } } List < ResourceCollection > liResourceName = new List < ResourceCollection > ( ) ; //section to add the objects in liststring json = JsonConvert.SerializeObject ( liResourceName , Newtonsoft.Json.Formatting.Indented ) ; [ { `` Name '' : `` Hello '' , `` Resources '' : { `` en '' : `` Hello '' } } , { `` Name '' : `` World '' , `` Resources '' : { `` en '' : `` World '' } } ] { `` Hello '' : { `` en '' : `` Hello '' } , `` World '' : { `` en '' : `` World '' } }
How to skip property name in json serialization ?
C_sharp : I 'm need to hash against a member variable instead of the class , so I do n't check if the reference is in the dictionary . Without overriding the defaults , it wo n't find an identical Value , but only return if it finds the same exact instance of HashedType , such that this code fails.Definition of HashedType : It looks like I can override GetHashCode ( ) and Equals ( ) to do this for me.However , MSDN recommends I create a separate class that I derive from IEqualityComparer and instantiate my dictionaries used HashedType with the HashedTypeComparer : IEqualityComparer.To help make this easier , I 've derived from Dictionary and createdThis all seems contrived.Is the only advantage I get is not changing the Equals ( ) ? I mean , really speaking , I would want Equals to compare against that single member anyway . <code> Dictionary.Add ( new HashedType ( 4 ) ) ; Dictionary.Contains ( new HashedType ( 4 ) ) ; // fails to find 4 HashedType { public HashedType ( Int32 value ) { Value = value ) ; } public HashedType ( String value ) { Value = value ) ; } public object Value ; public void Serialize ( Serializer s ) { if ( Value.GetType ( ) == typeof ( Int32 ) ) { s.Set < Int32 > ( 0 ) ; s.Set < Int32 > ( Value ) ; } else { s.Set < Int32 > ( 1 ) ; s.Set < String > ( Value ) ; } } } HashedTypeDictionary < U > : Dictionary < T , U > { public HashedTypeDictionary ( ) : base ( new HashedTypeComparer ( ) ) { } public bool Equals ( HashedType a , HashedType b ) { return a.Value == b.Value ; } publci int GetHashCode ( HashedType a ) { return a.Value.GetHashCode ( ) ; } }
Advantage of deriving external class from IEqualityComparer < > over overriding GetHashCode and Equals
C_sharp : my problem is the following . I have made a code design for a home project which is apparently not working . Maybe you can help me to figure out where the `` code smell '' comes from.Ok let 's start : I have defined some classes to wrap around different kind of archive types : To handle with those archives , I defined Manager classes . An abstract one that defines the needed behaviour , And the concrete ones , that actually implement the specific behaiour : What happens now is that during compile time , I dont know which kind of archives I will process , so I tried the following : which ended up in the following error : Can not implicitly convert type 'ZipArchiveManager ' to 'ArchiveManager'As far as I understand , the generic argument can not be implicitely converted . Is there any way to come around this ? Does this code / design `` smell '' ? Thank you very much in advance . <code> public abstract class Archive { } public class ZipArchive : Archive { } public class TarArchive : Archive { } public abstract class ArchiveManager < T > where T : Archive { public abstract void OpenArchive ( T archive ) ; } public class ZipArchiveManager : ArchiveManager < ZipArchive > { public override void OpenArchive ( ZipArchive archive ) { /* .. */ } } public class TarArchiveManager : ArchiveManager < TarArchive > { public override void OpenArchive ( TarArchive archive ) { /* .. */ } } class Program { static void Main ( string [ ] args ) { ArchiveManager < Archive > archiveManager = null ; if ( /*some condition*/ ) { archiveManager = new ZipArchiveManager ( ) ; } else { archiveManager = new TarArchiveManager ( ) ; } } }
Declaration of a abstract generic type variable
C_sharp : I am trying to do the following with Entity Framework 6 and Code First : The result however is : Unable to determine the principal end of an association between the types 'Step ' and 'Step ' . The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.When I remove one of the NextSteps , it works.I already tried a lot of approaches using either Fluent API or attributes , but it seems I can not get this working . From what I read , EF seems to try to connect my 2 NextStep properties in a parent- > child relationship and then of course fails because the principal end is not defined . But in my case those properties are not part of the same relation . <code> public class Step { public int Id { get ; set ; } public Step NextStepSuccess { get ; set ; } public Step NextStepFailure { get ; set ; } }
Multiple self referencing in Entity Framework fails with `` principal end '' error
C_sharp : I 'm following the await tutorial on the MSDN , and I 'm trying to figure out the difference between using await as a statement versus using await as an expression . This whole async-await thing is bending my mind and I ca n't find any examples for this particular case.Basically , I wanted to see how to use multiple awaits asynchronously , meaning I do n't want to have to wait for the first one to complete before the second one begins . This , to me , defeats the purpose of asynchrony to begin with : However , with a subtle change it only takes 3 seconds total for the two `` Finished '' s to appear , which is what I 'd want -- the two awaits running truly asynchronously : My question is , why do these behave differently ? What subtle point am I missing here ? <code> private async void button1_Click ( object sender , EventArgs e ) { // Using await as an expression string result_a = await WaitAsynchronouslyAsync ( ) ; string result_b = await WaitAsynchronouslyAsync ( ) ; // This takes six seconds to appear textBox1.Text = result_a + Environment.NewLine ; textBox1.Text += result_b ; } public async Task < string > WaitAsynchronouslyAsync ( ) { await Task.Delay ( 3000 ) ; return `` Finished '' ; } private async void button1_Click ( object sender , EventArgs e ) { var a = WaitAsynchronouslyAsync ( ) ; var b = WaitAsynchronouslyAsync ( ) ; // Using await as a statement await a ; await b ; // This takes three seconds to appear textBox1.Text = a.Result + Environment.NewLine ; textBox1.Text += b.Result ; }
await statement vs. expression
C_sharp : If I have two types of rows : header rows and data rows . and any row should compose of 18 columns.The number of data rows is based on the number of header rows for example : and so onI want to loop over the columns of the data rows and map to the related header col data : Let 's take The second example : I have two header rows : The problem in my code is that it always maps to the first header row whatever the number of header rows.To solve this problem I want to do a conditional loop.so If the number of header rows = array [ 36 ] /18 = 2 header rows : The first data row Iteration : parsedData.columns [ meta.col ] .toString ( ) .split ( `` - '' ) [ 0 ] the second data row iteration : parsedData.columns [ meta.col-18 ] .toString ( ) .split ( `` - '' ) [ 0 ] The third data row Iteration : parsedData.columns [ meta.col ] .toString ( ) .split ( `` - '' ) [ 0 ] The fourth data row iteration : parsedData.columns [ meta.col-18 ] .toString ( ) .split ( `` - '' ) [ 0 ] The fifth data row iteration : ( for total ) so the first parsedData.columns [ meta.col ] .toString ( ) .split ( `` - '' ) [ 0 ] Based on comments here 's an example : The header rows in this example = an array [ 36 ] The data rows are multiple arrays ( 5 ) each array = array [ 18 ] because I have 2 header rows -- - > I have 5 data rowsNow I Want to map every tool tip cell in the data rows to its equivalent of header rows as illustrated above . but it always maps to the first header row . <code> If I have 2 header rows , I should have ( 2 datarows : the first one map to the first header row , the second one map to the second header row + 2 datarows : the first one map to the first header row , the second one map to the second header row + 1 data rows for total : maps to the first header row ) = 5 datarows per groupIf I have 3 header rows , I should have ( 3 datarows : the first one map to the first header row , the second one map to the second header row , the third one maps to the third header row + 3 datarows : the first one maps to the first header row , the second one maps to the second header row , the third one mapss to the third header row + 1 for total : maps to the first header row ) = 7 datarowsper group NOTE : ALWAYS I SHOULD HAVE ONE DATA ROW FOR THE TOTAL DATA ROWS . `` render '' : function ( data , type , full , meta ) { let tooltip = isNaN ( data ) ? data : Number ( data ) ; return type === 'display ' ? ' < div id= '' tooltip '' data-tooltip= '' ' +parsedData.columns [ meta.col ] .toString ( ) .split ( `` - '' ) [ 0 ] + `` = `` + tooltip + `` | '' + meta.row + ' '' > ' + data : data ; } parsedData.columns = array [ 36 ] where 36 = 2 * 18 = number of header rows * number of columns per row.There are multiple data rows one array for each data row = one row array [ 18 ] meta.row = row index and repeat this pattern for each group of row data ( 5 data rows per group ) , may I have 3 groups so I have 15 data rows 528.00 -- > Tooltip should = A1:528.0052.80 -- > Tooltip should = B9:52.80240.00- -- > Tooltip should = B10:240.00-91.52 -- > Tooltip should = T5:91.52 2 + 2 + 1 ( total ) .
How to loop conditionally to map header rows to data rows
C_sharp : I 'm worried about the correctness of the seemingly-standard pre-C # 6 pattern for firing an event : I 've read Eric Lippert 's Events and races and know that there is a remaining issue of calling a stale event handler , but my worry is whether the compiler/JITter is allowed to optimize away the local copy , effectively rewriting the code aswith possible NullReferenceException.According to the C # Language Specification , §3.10 , The critical execution points at which the order of these side effects must be preserved are references to volatile fields ( §10.5.3 ) , lock statements ( §8.12 ) , and thread creation and termination.— so there are no critical execution points are in the mentioned pattern , and the optimizer is not constrained by that.The related answer by Jon Skeet ( year 2009 ) states The JIT is n't allowed to perform the optimization you 're talking about in the first part , because of the condition . I know this was raised as a spectre a while ago , but it 's not valid . ( I checked it with either Joe Duffy or Vance Morrison a while ago ; I ca n't remember which . ) — but comments refer to this blog post ( year 2008 ) : Events and Threads ( Part 4 ) , which basically says that CLR 2.0 's JITter ( and probably subsequent versions ? ) must not introduce reads or writes , so there must be no problem under Microsoft .NET . But this seems to say nothing about other .NET implementations . [ Side note : I do n't see how non-introducing of reads proves the correctness of the said pattern . Could n't JITter just see some stale value of SomeEvent in some other local variable and optimize out one of the reads , but not the other ? Perfectly legitimate , right ? ] Moreover , this MSDN article ( year 2012 ) : The C # Memory Model in Theory and Practice by Igor Ostrovsky states the following : Non-Reordering Optimizations Some compiler optimizations may introduce or eliminate certain memory operations . For example , the compiler might replace repeated reads of a field with a single read . Similarly , if code reads a field and stores the value in a local variable and then repeatedly reads the variable , the compiler could choose to repeatedly read the field instead . Because the ECMA C # spec doesn ’ t rule out the non-reordering optimizations , they ’ re presumably allowed . In fact , as I ’ ll discuss in Part 2 , the JIT compiler does perform these types of optimizations.This seems to contradict the Jon Skeet 's answer.As now C # is not a Windows-only language any more , the question arises whether the validity of the pattern is a consequence of limited JITter optimizations in the current CLR implementation , or it is expected property of the language.So , the question is following : is the pattern being discussed valid from the point of view of C # -the-language ? ( That implies whether a language compiler/runtime is required to prohibit certain kind of optimizations . ) Of course , normative references on the topic are welcome . <code> EventHandler localCopy = SomeEvent ; if ( localCopy ! = null ) localCopy ( this , args ) ; if ( SomeEvent ! = null ) SomeEvent ( this , args ) ;
Events and multithreading once again
C_sharp : I 'm trying to implement some functionality that was formerly provided via an Excel sheet into a C # application , but the probability mass function of Accord.NET differs for some reason from the excel function.In excel the probabilty mass function , is used this wayWhen I try it with Accord.NETBut the cumulative distribution seems to work properly ( except for the last few digits , but I assumed this is just some kind of precision error ) Excel : Accord.NET : Why are the results so different ? And is there a way to get the Excel result with Accord ? EDIT : Extreme.Numerics calculates the same result as Excel , but I do n't want to use this library , as the license system of this library always led to trouble in the past.EDIT 2 : Seems like some kind of overflow error.When I use this I get the right result : Any ideas why this could be happening ? <code> =BINOM.DIST ( 250 ; 3779 ; 0.0638 ; FALSE ) Result : 0.021944019794458 var binom = new BinomialDistribution ( 3779 , 0.0638 ) ; binom.ProbabilityMassFunction ( 250 ) ; // Result : Infinity =BINOM.DIST ( 250 ; 3779 ; 0.0638 ; TRUE ) Result : 0.736156366002849 var binom = new BinomialDistribution ( 3779 , 0.0638 ) ; binom.DistributionFunction ( 250 ) ; // Result : 0.736156366002318 Math.Exp ( binom.LogProbabilityMassFunction ( 250 ) ) ;
Accord.Net binomial probability mass function result differs from Excel result
C_sharp : Trying to understand .net 's memory model when it comes to threading . This question is strictly theoretical and I know it can be resolved in other ways such as using a lock or marking _task as volatile.Take the following piece of code for example : Now make the following assumptions : Run can be called multiple times ( from different threads ) and will never be called after Dispose has been called . Dispose will be called exactly once.Now to my question , will the value of _task ( in the Dispose method ) always be a `` fresh '' value , meaning will it be read from the `` main memory '' as opposed to being read from a register ? From what I 've been reading Interlocked creates a full fence memory barrier , so I 'm assuming _task will be read from main memory or am I completely off ? <code> class Test { Task _task ; int _working = 0 ; public void Run ( ) { if ( Interlocked.CompareExchange ( ref _working , 1 , 0 ) == 0 ) { _task = Task.Factory.StartNew ( ( ) = > { //do some work ... } ) ; _task.ContinueWith ( antecendent = > Interlocked.Exchange ( ref _working , 0 ) ) ; } } public void Dispose ( ) { if ( Interlocked.CompareExchange ( ref _working , _working , 0 ) == 1 ) { _task.ContinueWith ( antecendent = > { /*do some other work*/ } ) ; } } }
Threading & implicit memory barriers
C_sharp : Is there a way to get the underlying variable name of a target object in a Visual Studio debugger visualizer ? The built-in string visualizer does it : Clicking on the visualizer icon for myStr , you will see the `` Expression '' text box shows `` myStr '' . How can I get this in my own visualizers ? <code> string myStr = `` abc\ndef '' ; Debugger.Break ( ) ;
get variable name in debugger visualizer
C_sharp : That is , in C , we can define a function like : and it will return a higher number every time it is called . Is there an equivalent keyword in C # ? <code> func ( ) { static int foo = 1 ; foo++ ; return foo ; }
Does there exist a keyword in C # that would make local variables persist across multiple calls ?
C_sharp : Recently , I came across some code that looked like this : Calling Test.Factory ( ) results in a Test object with a Things collection containing both `` First '' and `` Second '' .It looks like the line Things = { `` Second '' } calls the Add method of Things . If the ICollection is changed to an IEnumerable , there is a syntax error stating `` IEnumerable < string > does not contain a definition for 'Add ' '' .It is also apparent that you can only use this kind of syntax in an object initialiser . Code such as this is invalid : What is the name of this feature ? In which version of C # was it introduced ? Why is it only available in object initialisers ? <code> public class Test { public ICollection < string > Things { get ; set ; } public Test ( ) { Things = new List < string > { `` First '' } ; } public static Test Factory ( ) { return new Test { Things = { `` Second '' } } ; } } var test = new Test ( ) ; test.Things = { `` Test '' } ;
Syntactic sugar for adding items to collections in object initialisers
C_sharp : I have an array x [ ] containing data . Also there is an array of `` system states '' c [ ] . The process : Is there any efficient way to find the values of f1 and f2 on 2-core system using 2 parallel threads ? I mean the following ( in pseudo-code ) : f1 and f2 are not time consumptive , but have to be calculated many times , so desired speedup is about x2 . See the diagram for graphical representation : Looking for code examples for Windows . <code> for ( i = 1 ; i < N ; i++ ) { a = f1 ( x [ i ] + c [ i-1 ] ) ; b = f2 ( x [ i ] + c [ i-1 ] ) ; c [ i ] = a + b ; } thread_1 { for ( i = 1 ; i < N ; i++ ) a = f1 ( x [ i ] + c [ i-1 ] ) ; } thread_2 { for ( i = 1 ; i < N ; i++ ) { b = f2 ( x [ i ] + c [ i-1 ] ) ; c [ i ] = a + b ; //here we somehow get a { i } from thread_1 } }
Synchronous Parallel Process in C # / C++
C_sharp : I 'm writing a Connect4 game with an AI opponent using adversarial search techniques and I have somewhat run into a wall . I feel that I 'm not far from a solution but that there 's perhaps a problem where I 'm switching perspectives ( as in : the perspective of which participant I 'm basing my evaluation scores on ) , missing a minus sign somewhere or something like that.The problem is either that in the variations that I 've tried that the AI chooses not to block the player when the player has three-in-a-row but otherwise the AI plays a perfect game , or that he prefers to block the player , even if he has the chance to win the game . It also seems to matter whether or not the search depth is an even or an uneven number , as the AI is pants-on-head retarded at a 6-ply search , which is pretty telling that something is wrong.SearchThe algorithm used is negamax with alpha-beta pruning and is implemented as follows : I do n't suspect that the problem is in this function , but it might be . EvaluationI 've based the evaluation function off of the fact that there are only 69 possible ways to get four-in-a-row on a 7x6 board . I have a look-up table of about 350 items that contains the hardcoded information for every column and row which win-combinations the row+column is a part of . For example , for row 0 and column 0 , the table looks like this : This means that column 0 , row 0 is part of win-combination 21 , 27 and 61 . I have a second table , that contains for both players how many stones it has in each of the win-combinations . When I do a move then I do the following : The opposite is of course being done for UndoMove.So after doing a move on column 0 , row 0 by Player.Human , the table will be filled with a value of 1 at index 21 , 27 and 61 . If I do another move in a cell that is also part of win-combination 27 , then the player combination table gets incremented at index 27 to 2.I hope I have made that clear , as it 's used in the evaluation function to very quickly determine how close a player is to scoring four-in-a-row.The evaluation function , where I suspect the problem lies , is as follows : So I simply loop through the 69 possible win-combinations and add an amount to the score based on whether it 's a single stone , two-in-a-row or three . The part I 'm still confused about in this whole adversarial search is whether I should care which player is doing a move ? I mean , should I pass in the player like I do here , or should I always evaluate the board from the perspective of the AI player ? I 've tried many combinations of aiScore - humanScore , or just always look from the perspective of Player.AI , and such . But I 've hit a dead end and every combination I 've tried was pretty flawed.So : Is the logic of my evaluation solid in its basis ? When should I 'switch perspective ' ? Any help would be much appreciated.UpdateI 've implemented Brennan 's suggestions below , and while it has definitely much improved , for some reason it does n't block three-in-a-rows on any column but the two left and right-most , and only when the search-depth is uneven . The AI is unbeatable at even search depths , but only until depth 8 and up . Then it refuses to block again . This is pretty telling that I 'm probably very close , but still have some crucial flaw.Perhaps this has to do with me setting the column the AI should drop a stone in as Brennan commented , but I do n't know when else to set it . Setting it only at depth 0 does n't work.Update 2Edited the code as it looks like now with Brennan 's changes . Update 3Created a Github repo with the full code . If you do n't know how to work Git , just download a zip file from here.It 's a .NET 4.0 project , and running it will create log files of the negamax algorithm in your documents/logs directory . The solution also contains a test project , that contains a test for every board column whether or not the AI chooses to block the player when the player has three-in-a-row there . <code> private int Negamax ( int depth , int alpha , int beta , Player player ) { Player winner ; if ( Evaluator.IsLeafNode ( game , out winner ) ) { return winner == player ? ( 10000 / depth ) : ( -10000 / depth ) ; } if ( depth == Constants.RecursionDepth ) { return Evaluator.Evaluate ( game , depth , player ) ; } foreach ( var move in moves ) { int row ; if ( board.DoMove ( move , player , out row ) ) { var value = -Negamax ( depth + 1 , -beta , -alpha , ( Player ) 1 - ( int ) player ) ; board.UndoMove ( move , row , player ) ; if ( value > alpha ) { alpha = value ; if ( player == Player.AI ) { bestColumn = move ; } } if ( alpha > = beta ) { return alpha ; } } } return alpha ; } //c1r1table [ 0 ] [ 0 ] = new int [ 3 ] ; table [ 0 ] [ 0 ] [ 0 ] = 21 ; table [ 0 ] [ 0 ] [ 1 ] = 27 ; table [ 0 ] [ 0 ] [ 2 ] = 61 ; public bool DoMove ( int column , Player p , out int row ) { row = moves [ column ] ; if ( row > = 0 ) { Cells [ column + row * Constants.Columns ] = p ; moves [ column ] -- ; var combinations = this.Game.PlayerCombinations [ p ] ; foreach ( int i in TerminalPositionsTable.Get ( column , row ) ) { combinations [ i ] ++ ; } return true ; } else { return false ; } } public static int Evaluate ( Game game , int depth , Player player ) { var combinations = game.PlayerCombinations [ player ] ; int score = 0 ; for ( int i = 0 ; i < combinations.Length ; i++ ) { switch ( combinations [ i ] ) { case 1 : score += 1 ; break ; case 2 : score += 5 ; break ; case 3 : score += 15 ; break ; } } return score ; }
Adverserial search troubles
C_sharp : I have a bunch of users , with a given start and end time , e.g . : I want to put them into buckets , based on times that they overlap ( based on a configurable threshold , e.g. , they need to overlap at least half an hour ) . I want buckets to be ideally 4 items big , but any range from 2-5 is acceptable.In the example above , no 4 people match , so I 'd have a bucket of 3 ( Peter , Raymond , Winston ) and one of 2 ( Dana , Egon ) .I 've prototyped an algorithm that seems to rely on chance rather than science : Order the List by StartTimeCreate an empty bucketPick the first user from the ListCheck that user against all users in the bucketIf that user overlaps with everyone in the bucket , put that person in it and remove it from the listIf the bucket has the ideal size ( 4 ) or if I 'm looping and checking the same user more than three times , close the bucket and create a new , empty oneThis works well for the first few buckets , but leads to buckets with only 2 people that could be combined better.I could change the algorithm to remove all ideal buckets from the list and reshuffle and try some more , but I feel that this should be a common problem - it 's like shift assignments for workers , or maybe the knapsack problem.Does anyone know a standard algorithm for this type of problem ? ( Tagged combinatorics because I think this is the area of math it applies , correct me if wrong ) <code> { Name = `` Peter '' , StartTime = `` 10:30 '' , EndTime = `` 11:00 '' } , { Name = `` Dana '' , StartTime = `` 11:00 '' , EndTime = `` 12:30 '' } , { Name = `` Raymond '' , StartTime = `` 10:30 '' , EndTime = `` 14:00 '' } , { Name = `` Egon '' , StartTime = `` 12:00 '' , EndTime = `` 13:00 '' } , { Name = `` Winston '' , StartTime = `` 10:00 '' , EndTime = `` 12:00 '' }
Is there a standard algorithm to balance overlapping objects into buckets ?
C_sharp : I have the following functionNow if T is en IEnumerable < > I want to have a different behaviour so I made a second functionWhen I invoke it like thisHowever when I invoke it like thisIt goes to the first one.Why does this happen and what is the best construction to solve this ? UPDATEI build a new example with the problemThe first function gets invoken now when I expect the second to be invoked . <code> public static T Translate < T > ( T entity ) { ... . } public static IEnumerable < T > Translate < T > ( IEnumerable < T > entities ) { ... . } IEnumerable < string > test = new List < string > ( ) .AsEnumerable ( ) ; Translate ( test ) ; Func < IEnumerable < string > > func = ( ) = > new List < string > ( ) .AsEnumerable ( ) ; Translate ( func.Invoke ( ) ) static void Main ( string [ ] args ) { Func < IEnumerable < string > > stringFunction = ( ) = > new List < string > ( ) .AsEnumerable ( ) ; InvokeFunction ( ExtendFunction ( stringFunction ) ) ; } private static T Convert < T > ( T text ) where T : class { return null ; } private static IEnumerable < T > Convert < T > ( IEnumerable < T > text ) { return null ; } private static Func < T > ExtendFunction < T > ( Func < T > func ) where T : class { return ( ) = > Convert ( func.Invoke ( ) ) ; } private static T InvokeFunction < T > ( Func < T > func ) { return func.Invoke ( ) ; }
C # more specific version on generic function
C_sharp : In our company there are thousands ( ! ) of cars . each car has a GPS device which sends periodically ( cycle ) its location.So each Cycle contains : List < Cars > ( cars that sent location – corresponding to the CycleNum ) CycleNum which is Cycle numberCycleNum is determined by a server.So for example in CycleNum=1 , 4 cars sent their location : Classes I used ( simplification ) Let 's fill some data : Visualization : As you can see : A new car can come in to the cycleA car can also get out from a cycleA car can change Location ( obviously ) QuestionI was asked to : For a specific given cycle Number — find all Cars that were also anticipated in the previous cycle where : ( `` new Location '' - `` previous Location '' ) < abs ( 40 ) And from that result set , find all cars PAIRS where : ( Car_A.Location - Car_B.Location ) < abs ( 65 ) In short - I need all cars that gave me info also for the previous cycle and also they did n't go very far from their previous location and finally - from those cars - I need to know which cars are near to each other.Very important : I can not check only current Location , because we need to make sure also that cars did n't get very far from their previous location.So according to the picture : looking at cycleNum=2 : The cars who anticipated also in the previous Cycle ( 1 ) were Cars : 1,2,3,4.From that result : The cars who did n't go very far from their previous location : ( `` new Location '' - `` previous Location '' ) < abs ( 40 ) Were cars : 1,2,4.From that result I need to find all pairs of car who are now not far from each other : ( Car_A.Location - Car_B.Location ) < abs ( 65 ) : So the result should be IEnumerable : ( format is n't matter ) { Car1 , Car2 , distance=17 } //the distance between those 2 cars < 65 { Car1 , Car4 , distance=33 } //the distance between those 2 cars < 65 { Car2 , Car4 , distance=50 } //the distance between those 2 cars < 65//I dont mind having all permutation ( { car1 car2 } , { car2 car1 } ) What have I tried : But I only get cars from the current cycle and not from previous cycle , Also - I need reference both to cars from current cycle and previous cycle ( without reiterating ) - for calculations.Also I think I 'm on the wrong path using SelectMany and this is suppose to be the fastest it can be ( c # , plinq ? ) . I wish it could be in one query.Any help ? Full code working onlinenb , of course I can do it in phases , but reiterating , or ToList ( ) 's are bad approach for me . I was hoping for a single plinq queryEditPosted solution works OK logically but not performantly.2 cycles , where each has 10,000 cars : > 9min ! ! ! : http : //i.stack.imgur.com/mjLvG.jpgHow can I improve it ? ( asparallel didnt work much ) <code> static int TotalCycles=0 ; class Car { public int CarId ; public int Location ; } class Cycle { public int CycleNum ; public List < Car > Cars ; public Cycle ( ) { CycleNum= ( ++TotalCycles ) ; } } List < Cycle > LstCyclces = new List < Cycle > ( ) ; Cycle cycle =null ; cycle = new Cycle ( ) ; //cycle 1 cycle.Cars = new List < Car > ( ) ; cycle.Cars.Add ( new Car { CarId=1 , Location=40 } ) ; cycle.Cars.Add ( new Car { CarId=2 , Location=21 } ) ; cycle.Cars.Add ( new Car { CarId=3 , Location=5 } ) ; cycle.Cars.Add ( new Car { CarId=4 , Location=15 } ) ; LstCyclces.Add ( cycle ) ; cycle = new Cycle ( ) ; //cycle2 cycle.Cars = new List < Car > ( ) ; cycle.Cars.Add ( new Car { CarId=1 , Location=40 } ) ; //same location cycle.Cars.Add ( new Car { CarId=2 , Location=57 } ) ; //changed location cycle.Cars.Add ( new Car { CarId=3 , Location=100 } ) ; //changed location cycle.Cars.Add ( new Car { CarId=4 , Location=7 } ) ; //changed location cycle.Cars.Add ( new Car { CarId=7 , Location=2 } ) ; //new attended ( vs previous cycle ) LstCyclces.Add ( cycle ) ; cycle = new Cycle ( ) ; //cycle3 cycle.Cars = new List < Car > ( ) ; cycle.Cars.Add ( new Car { CarId=1 , Location=40 } ) ; //same cycle.Cars.Add ( new Car { CarId=2 , Location=5 } ) ; //changed Location cycle.Cars.Add ( new Car { CarId=4 , Location=1 } ) ; //changed Location cycle.Cars.Add ( new Car { CarId=9 , Location=7 } ) ; //new attended ( vs previous cycle ) LstCyclces.Add ( cycle ) ; var cycleToCheck=2 ; //get all cars from desired cycle var requestedCycleCars = LstCyclces.Where ( c= > c.CycleNum==cycleToCheck ) .SelectMany ( c= > c.Cars ) ; //get all cars from previous cycle var previousCycleCars = LstCyclces.Where ( c= > c.CycleNum==cycleToCheck-1 ) .SelectMany ( c= > c.Cars ) ; //intersec between those var MyWrongIntersect =requestedCycleCars.Intersect ( previousCycleCars , new MyEqualityComparer ( ) ) ;
Linq fast intersect query - enhancement ?
C_sharp : Is it possible to define a function in a way that it basically returns itself as a delegate ? For example , if this was valid syntax : Then I could chain method calls together like this . <code> public class Scrub { public NotNull NotNull < T > ( T value , string name ) { if ( value == null ) throw new ArgumentNullException ( name ) ; return NotNull ; } } Scrub.NotNull ( param1 , nameof ( param1 ) ) ( param2 , nameof ( param2 ) ( param3 , nameof ( param3 ) ) ;
Function to return a function that returns a function , etc
C_sharp : I 'm used to write code like this in C # : This is the way I translated it in F # ( obj being a list ) : Is there any way to do this in F # without using a mutable variable ? Is there a more 'elegant ' way to handle this situation in F # ? Thank you ! <code> SomeObj obj ; try { // this may throw SomeException obj = GetSomeObj ( ) ; } catch ( SomeException ) { // Log error ... obj = GetSomeDefaultValue ( ) ; } obj.DoSomething ( ) ; let mutable obj = [ ] try obj < - getSomeObjwith | ex - > // Log ex obj < - getSomeDefaultValuedoSomething obj
How to write this C # code in F #
C_sharp : I am having a design problem and I know there has to be a way to make it work . I tried the solutions here : Annoying auto scroll of partially displayed items in WPF ListView But they didnt work for me because I am not allowed to work in the code-behind.I have a list of items from a wpf ListBox . like this : when I try to select the CheckBox in line 5 , the Window centers on it but does not check it . After further testing , I found that it will not select the CheckBox as long as the bottom border of the item is not in view . Here is the xaml for the ListBox and its Style : What can I do to make this select the checkbox instead of just centering it ? Any help is appreciated . <code> < ListBox Grid.Column= '' 0 '' Grid.Row= '' 1 '' Name= '' RequestCheckoutV '' ItemsSource= '' { Binding Path=CheckoutVM , Mode=TwoWay , IsAsync=True } '' SelectedItem= '' { Binding Path=SelectedPermit } '' BorderThickness= '' 0 '' KeyboardNavigation.TabNavigation= '' Continue '' > < ListBox.ItemContainerStyle > < Style TargetType= '' { x : Type ListBoxItem } '' > < Setter Property= '' KeyboardNavigation.IsTabStop '' Value= '' False '' / > < Setter Property= '' Background '' Value= '' Transparent '' / > < Setter Property= '' Control.HorizontalContentAlignment '' Value= '' Center '' / > < Setter Property= '' Control.VerticalContentAlignment '' Value= '' Top '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type ListBoxItem } '' > < ContentPresenter / > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < /ListBox.ItemContainerStyle > < /ListBox >
Selecting a partially displayed WPF checkbox
C_sharp : I 've a web site which writes a date like this : In both my PC ( Windows 7 , Service Pack 1 , Spanish culture ) and the server ( Windows Server 2012 , English Culture ) the MvcApplication.Language is es so the culture I get from the list is : es-ES.I 'd expect they both write the same string ( they have different cultures , but I 'm not using CurrentCulture ) . However the results are abr in my PC and Abr . in the server.I 've tried this isolated from MvcApplication.Language using the LinqPAD but it is still different . I 've printed the arrays of AbbreviatedDayNames and AbbreviatedMonthNames and they are different in each computer.Am I doing something wrong or this is the expected behavior ? How can I do to make it completely independent from Windows / User Culture ? <code> CultureInfo cultureInfo = CultureInfo.GetCultures ( CultureTypes.AllCultures ) .FirstOrDefault ( c = > string.Equals ( c.TwoLetterISOLanguageName , MvcApplication.Language ) ) ; return string.Concat ( date.Day , `` . `` , cultureInfo.DateTimeFormat.GetAbbreviatedMonthName ( date.Month ) ) ;
Instances of CultureInfo ( from same culture ) changing based on OS
C_sharp : I am trying to split using Regex.Split strings like this one : We have the following 'reserved words ' : NAME , COURSE , TEACHER , SCHEDULE , CAMPUS . It is required to split the original string into : The criteria for Split is : to have the simple quote , followed by one or more spaces , followed by a 'reserved word ' . The closest expression I achieved is : This is the complete source code : My code is doing this : It is deleting the last simple quote and is taking only the first letter of the reserved word . And COURSE in this sample has more than one space and is not working for it.Thanks in advance ! <code> string criteria = `` NAME='Eduard O ' Brian ' COURSE='Math II ' TEACHER = 'Chris Young ' SCHEDULE= ' 3 ' CAMPUS= ' C-1 ' `` ; NAME='Eduard O ' Brian'COURSE='Math II'TEACHER = 'Chris Young'SCHEDULE= ' 3'CAMPUS= ' C-1 ' var match = Regex.Split ( criteria , @ '' ' [ \s+ ] ( [ NAME ] | [ COURSE ] | [ TEACHER ] | [ SCHEDULE ] | [ CAMPUS ] ) '' , RegexOptions.CultureInvariant ) ; using System ; using System.Text.RegularExpressions ; namespace ConsoleApplication { class Program { static void Main ( string [ ] args ) { string criteria = `` NAME='Eduard O ' Brian ' COURSE='Math II ' TEACHER = 'Chris Young ' SCHEDULE= ' 3 ' CAMPUS= ' C-1 ' `` ; var match = Regex.Split ( criteria , @ '' ' [ \s+ ] ( [ NAME ] | [ COURSE ] | [ TEACHER ] | [ SCHEDULE ] | [ CAMPUS ] ) '' , RegexOptions.CultureInvariant ) ; foreach ( var item in match ) Console.WriteLine ( item.ToString ( ) ) ; Console.Read ( ) ; } } } NAME='Eduard O ' Brian ' COURSE='Math IITEACHER = 'Chris YoungSCHEDULE='3CAMPUS= ' C-1
C # RegEx.Split delimiter followed by specific words
C_sharp : UpdateUploaded sample project : https : //github.com/subt13/BugSamplesI have reproduced an error that has been occurring in a Windows 10 UAP application that utilizes the MVVMLight framework . I receive the error below during navigation while the CPU is under heavy load ( ~20-25 % ) and the page is `` heavy '' ( large images , lots of controls , etc. , etc . ) at System.Runtime.InteropServices.WindowsRuntime.ICommandAdapterHelpers. < > c__DisplayClass2.b__3 ( Object sender , EventArgs e ) at System.EventHandler.Invoke ( Object sender , EventArgs e ) at GalaSoft.MvvmLight.Command.RelayCommand.RaiseCanExecuteChanged ( ) at RaiseExecuteChangeRepo.ViewModel.MainViewModel.d__17.MoveNext ( ) In the sample , the error occurs on RaiseCanExecuteChanged ( ) ; Nothing special is happening during navigation other than the command associated with ExecuteLoadDataCommandAsync ( ) is getting called to load data.To reproduce , simply toggle from one page to the other rapidly for a few seconds and then just wait . After not too long the exception will be raised . <code> private async void ExecuteLoadDataCommandAsync ( ) { // cause the app to slow done . var data = await Task.Run ( ( ) = > GetData ( ) ) ; if ( data ! = null ) { this.Data.Clear ( ) ; foreach ( var item in data ) { this.Data.Add ( new AnotherVM ( item ) ) ; } } // have the select job command rerun its condition this.SelectCommand.RaiseCanExecuteChanged ( ) ; } // slow down the page public List < DataItem > GetData ( ) { var myList = new List < DataItem > ( ) ; for ( int i = 0 ; i < 100000 ; ++i ) { myList.Add ( new DataItem ( `` Welcome to MVVM Light '' ) ) ; } return myList ; } < Core : EventTriggerBehavior EventName= '' Loaded '' > < Core : InvokeCommandAction Command= '' { Binding LoadDataCommand } '' > < /Core : InvokeCommandAction > < /Core : EventTriggerBehavior >
RaiseCanExecuteChanged COM Exception during Navigation ?
C_sharp : It 's possible to determine memory usage ( according to Jon Skeet 's blog ) like this : It prints Memory used : 16 bytes ( I 'm running x64 machine ) .Consider we change Point declaration from class to struct . How then to determine memory used ? Is is possible at all ? I was unable to find anything about getting stack size in .NETP.SYes , when changed to 'struct ' , Point instances will often be stored on Stack ( not always ) , instead of Heap.Sorry for not posting it first time together with the question.P.P.SThis situation has no practical usage at all ( IMHO ) , It 's just interesting for me whether it is possible to get Stack ( short term storage ) size . I was unable to find any info about it , so asked you , SO experts ) . <code> public class Program { private static void Main ( ) { var before = GC.GetTotalMemory ( true ) ; var point = new Point ( 1 , 0 ) ; var after = GC.GetTotalMemory ( true ) ; Console.WriteLine ( `` Memory used : { 0 } bytes '' , after - before ) ; } # region Nested type : Point private class Point { public int X ; public int Y ; public Point ( int x , int y ) { X = x ; Y = y ; } } # endregion }
.NET , get memory used to hold struct instance
C_sharp : I am making an app in windows store and having a problem in writing xml in created xml file.I have followed this Editing XML file in Windows Store App but it did n't work for me.I want this xml to be wrote in my xml file on button click.Any alternate way for this stuff.. my current file is this : Here is what I have tried : I already have an xml file as mentioned above : <code> < drink > < drinkImage > ck.png < /drinkImage > < drinkTitle > COKE < /drinkTitle > < drinkDescription > ( 1793-1844 ) < /drinkDescription > < /drink > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < drinks > < drink > < drinkImage > pepsi.png < /drinkImage > < drinkTitle > PEPSI < /drinkTitle > < drinkDescription > ( 1793-1844 ) < /drinkDescription > < /drink > ** < here I Want above xml on button click > ** < /drinks > namespace DrinksApp { /// < summary > /// An empty page that can be used on its own or navigated to within a Frame . /// < /summary > public sealed partial class coke : Page { public coke ( ) { this.InitializeComponent ( ) ; } XmlDocument dom = new XmlDocument ( ) ; private void Button_Click ( object sender , RoutedEventArgs e ) { this.Frame.Navigate ( typeof ( softdrinks ) ) ; } private async void Button_Click_1 ( object sender , RoutedEventArgs e ) { XDocument xmlDoc = XDocument.Load ( `` favourite//fav.xml '' ) ; xmlDoc.Root.Add ( new XElement ( `` drink '' , new XAttribute ( `` drinkImage '' , '' ck.png '' ) , new XAttribute ( `` drinkTitle '' , '' PEPSI '' ) , new XAttribute ( `` drinkDescription '' , '' NONE '' ) ) ) ; xmlDoc.Save ( xmlDoc ) ; **//This is n't working in windows store ..** } } } }
Edit XML file in Windows Store app
C_sharp : I have a User class . One of the properties needs to be an `` associated '' user , so it 's type needs to be User . Right now when I initialize the class , I get a stack overflow when it tries to initialize the Associated property . Current code : Is this doable or am I barking up the wrong tree ? <code> public class User { public User ( ) { this.Associated = new User ( ) ; } public User Associated { get ; set ; } }
Initializing a new class in its own constructor
C_sharp : I recently discovered the following code below to effectively run lots of IO bound tasks ( see link ) .http : //blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspxI 'm under the impression the following are true : this is much better than using Parallel.ForEach because the work is not CPU bound.ForEachAsync will help in queueing as many IO tasks as possible ( without necessarily putting these on separate threads ) .The TPL will 'know ' these are IO based tasks and not spin up more threads , instead using callbacks/task completion source to signal back to the main thread , thus saving overhead of thread context switching.My question is , as Parallel.ForEach intrinsically has its own MaxDegreeOfParallelism defined how do I know what to define the dop parameter to here in the example code of the IEnumerable extension ? e.g . If I have 1000 items to process and need to carry out an IO based SQL-Server db call for each item , would I specify 1000 as the dop ? With Parallel.ForEach it is used as a limiter to prevent too many threads spinning up which might hurt performance . But here it seems to be used to partition up the minimum number of async tasks . I 'm thinking there should be at least no maximum as such ( the minimum being the total items to process ) because I want to queue as many IO based calls to the database as possible.How do I go about knowing what to see the DOP parameter too ? <code> public static Task ForEachAsync < T > ( this IEnumerable < T > source , int dop , Func < T , Task > body ) { return Task.WhenAll ( from partition in Partitioner.Create ( source ) .GetPartitions ( dop ) select Task.Run ( async delegate { using ( partition ) while ( partition.MoveNext ( ) ) await body ( partition.Current ) ; } ) ) ; }
What do I specify as the Dop parameter for ForEachAsync extension method ?
C_sharp : I took the code of DCL from Joe Duffy 's book 'Concurrent programming on windows'it is said marking m_value volatile can prevent writes reordering that will leads to other threads getting 'non null object with uninitialized fields ' . If the problem happens just because the possible writes reordering , can I just use 'Volatile Write ' instead of marking the filed volatile , like below ? ( This code looks a little awkward for demonstration , I just want to make sure if we can only use volatile write instead ) A related question is the Interlocked version from the bookSince the ECMA-CLI specs the 'Interlocked operation perform implicit acquire/release operations ' , do we still need volatile in this case ? <code> class LazyInit < T > where T : class { private volatile T m_value ; private object m_sync = new object ( ) ; private Func < T > m_factory ; public LazyInit ( Func < T > factory ) { m_factory = factory ; } public T value { get { if ( m_value == null ) { lock ( m_sync ) { if ( m_value == null ) { m_value = m_factory ( ) ; } } } return m_value ; } } } class LazyInit < T > where T : class { private object m_value ; private object m_sync = new object ( ) ; private Func < T > m_factory ; public LazyInit ( Func < T > factory ) { m_factory = factory ; } public T value { get { if ( m_value == null ) { lock ( m_sync ) { if ( m_value == null ) { Thread.VolatileWrite ( ref m_value , m_factory ( ) ) ; } } } return ( T ) m_value ; } } } class LazylnitRelaxedRef < T > where T : class { private volatile T m_value ; private Func < T > m_factory ; public LazylnitRelaxedRef ( Func < T > factory ) { m_factory = factory ; } public T Value { get { if ( m_value == null ) Interlocked.CompareExchange ( ref m_value , m_factory ( ) , null ) ; return m_value ; } } }
What kind of 'volatile ' operation is needed in Double checked locking in .NET
C_sharp : While reading Microsoft documentation , I stumbled on such an interesting code sample : It means you can cast your generic to the interface explicitly but not to the class unless you have a constraint . Well , I still can not understand the logic behind the decision as both interface and class type castings are throwing exceptions , so why would one protect against only one of these exceptions ? BTW- there is a way around the compile error but this does not remove the logic mess in my head : <code> interface ISomeInterface { ... } class SomeClass { ... } class MyClass < T > { void SomeMethod ( T t ) { ISomeInterface obj1 = ( ISomeInterface ) t ; //Compiles SomeClass obj2 = ( SomeClass ) t ; //Does not compile } } class MyOtherClass { ... } class MyClass < T > { void SomeMethod ( T t ) { object temp = t ; MyOtherClass obj = ( MyOtherClass ) temp ; } }
Why there is a restriction for explicit casting a generic to a class type but there is no restriction for casting a generic to an interface type ?
C_sharp : I 'm looking to get a value from anFor logging purposes I need to be able to fish out that guid.I tried the following code , which I feel is somewhat close to what I 'm looking for , but not quite.Now , ConstantExpression exposes a member 'Value ' , which does contain what I 'm looking for , but I 'm a bit puzzled how to actually extract this.And no : Does not work : ) SOLVEDThe end result looks like : Follow-upI did some rudementary speed testing using the following code : Turns out the compile version is MUCH slower . We 're looking at a huge difference . ( Timing is in ticks ) : GetValueWithExpressionsAndReflection : Average over 100000 , first call included : 0,93122GetValueWithExpressionsAndReflection : First call : 851GetValueWithExpressionsAndReflection : Average over 100000 , first call excluded : 0,922719227192272Versus : GetValueWithCompiledExpression : Average over 100000 , first call included : 499,53669GetValueWithCompiledExpression : First call : 16818GetValueWithCompiledExpression : Average over 100000 , first call excluded : 499,373503735037Rudementary tests or not : no doubt I will be using the reflection version.My results seem to be consistent with : http : //www.minddriven.de/index.php/technology/dot-net/c-sharp/efficient-expression-values <code> var guid = Guid.Parse ( `` SOMEGUID-GUID-GUID-GUID-SOMEGUIDGUID '' ) ; Expression < Func < Someobject , bool > > selector = x = > x.SomeId == guid ; BinaryExpression binaryExpression = ( BinaryExpression ) selector.Body ; MemberExpression memberExpression = ( MemberExpression ) ( ( UnaryExpression ) binaryExpression.Right ) .Operand ; ConstantExpression constantExpression = ( ConstantExpression ) memberExpression.Expression ; var val = ( Guid ) constantExpression.Value ; BinaryExpression binaryExpression = ( BinaryExpression ) selector.Body ; MemberExpression memberExpression = ( MemberExpression ) ( ( UnaryExpression ) binaryExpression.Right ) .Operand ; var myGuid = Expression.Lambda ( memberExpression ) .Compile ( ) .DynamicInvoke ( ) ; static void Main ( string [ ] args ) { var id = Guid.Parse ( `` bleh '' ) ; Expression < Func < Thingemebob , bool > > selector = x = > x.Id == id ; var tickList = new List < long > ( ) ; for ( int i = 0 ; i < 100000 ; i++ ) { var sw = Stopwatch.StartNew ( ) ; GetValueWithExpressionsAndReflection ( selector ) ; sw.Stop ( ) ; tickList.Add ( sw.ElapsedTicks ) ; } Trace.WriteLine ( `` GetValueWithExpressionsAndReflection : Average over 100000 , first call included : `` + tickList.Average ( ) ) ; Trace.WriteLine ( `` GetValueWithExpressionsAndReflection : First call : `` + tickList [ 0 ] ) ; Trace.WriteLine ( `` GetValueWithExpressionsAndReflection : Average over 100000 , first call excluded : `` + tickList.Skip ( 1 ) .Average ( ) ) ; tickList = new List < long > ( ) ; for ( int i = 0 ; i < 100000 ; i++ ) { var sw = Stopwatch.StartNew ( ) ; GetValueWithCompiledExpression ( selector ) ; sw.Stop ( ) ; tickList.Add ( sw.ElapsedTicks ) ; } Trace.WriteLine ( `` GetValueWithCompiledExpression : Average over 100000 , first call included : `` + tickList.Average ( ) ) ; Trace.WriteLine ( `` GetValueWithCompiledExpression : First call : `` + tickList [ 0 ] ) ; Trace.WriteLine ( `` GetValueWithCompiledExpression : Average over 100000 , first call excluded : `` + tickList.Skip ( 1 ) .Average ( ) ) ; Debugger.Break ( ) ; } private static void GetValueWithCompiledExpression ( Expression < Func < Note , bool > > selector ) { BinaryExpression binaryExpression = ( BinaryExpression ) selector.Body ; MemberExpression memberExpression = ( MemberExpression ) ( ( UnaryExpression ) binaryExpression.Right ) .Operand ; var o = Expression.Lambda ( memberExpression ) .Compile ( ) .DynamicInvoke ( ) ; } private static void GetValueWithExpressionsAndReflection ( Expression < Func < Note , bool > > selector ) { BinaryExpression binaryExpression = ( BinaryExpression ) selector.Body ; MemberExpression memberExpression = ( MemberExpression ) ( ( UnaryExpression ) binaryExpression.Right ) .Operand ; ConstantExpression constantExpression = ( ConstantExpression ) memberExpression.Expression ; FieldInfo member = ( FieldInfo ) memberExpression.Member ; var instance = constantExpression.Value ; var guid = member.GetValue ( instance ) ; }
Get value from a ConstantExpression
C_sharp : Can I retrieve basic information about all collections in a MongoDB with F # ? I have a MongoDB with > 450 collections . I can access the db with I had considered trying to just get all collections then loop through each collection name and get basic information about each collection with and but the db.GetCollection ( [ name ] ) requires me to define a type to pull the information about each collection . This is challenging for me as I do n't want to have to define a type for each collection , of which there are > 450 , and frankly , I do n't really know much about this DB . ( Actually , no one in my org does ; that 's why I 'm trying to put together a very basic data dictionary . ) Is defining the type for each collection really necessary ? Can I use the MongoCollection methods available here without having to define a type for each collection ? EDIT : Ultimately , I 'd like to be able to output collection name , the n documents in each collection , a list of the field names in each collection , and a list of each field type . <code> open MongoDB.Bsonopen MongoDB.Driveropen MongoDB.Driver.Core open MongoDB.FSharpopen System.Collections.Genericlet connectionString = `` mystring '' let client = new MongoClient ( connectionString ) let db = client.GetDatabase ( name = `` Production '' ) let collections = db.ListCollections ( ) db.GetCollection ( [ name of a collection ] )
Getting general information about MongoDB collections with FSharp
C_sharp : I will start working on xamarin shortly and will be transferring a lot of code from android studio 's java to c # .In java I am using a custom classes which are given arguments conditions etc , convert them to SQL statements and then loads the results to the objects in the project 's modelWhat I am unsure of is wether linq is a better option for filtering such data.For example what would happen currently is somethng along these linesOr if I have a conditionNow let us assume I have transferred the classes to c # and I wish to do somethng similar to the second case.So I will probably write something along the lines of : I know that the query will only be executed when I actually try to access customers , but if I have multiple accesses to customers ( let us say that I use 4 foreach loops later on ) will the get_all method be called 4 times ? or are the results stored at the first execution ? Also is it more efficient ( time wise because memory wise it is probably not ) to just keep the get_all ( ) method and use linq to filter the results ? Or use my existing setup which in effect executes And loads the results to an object ? Thanks in advance for any help you can provideEdit : yes I do know there is sqlite.net which pretty much does what my daos do but probably better , and at some point I will probably convert all my objects to use it , I just need to know for the sake of knowing <code> List < Customer > customers = ( new CustomerDAO ( ) ) .get_all ( ) List < Customer > customers = ( new CustomerDAO ( ) ) .get ( new Condition ( CustomerDAO.Code , equals , `` code1 '' ) var customers = from customer in ( new CustomerDAO ( ) ) .get_all ( ) where customer.code.equals ( `` code1 '' ) select customer Select * from Customers where code = 'code1 '
How does linq actually execute the code to retrieve data from the data source ?
C_sharp : I 'm trying to get started with JSIL . I 've followed the directions as far as I understand . I have a very basic C # dummy project with the code : I 've compiled this with jsilc , and created a website that hosts this along with the jsil scripts . My html initializes this : but ... I ca n't access the library . The console output indicates that it is loading : which is a 200 OK . However , I ca n't access it . If I run : then I get back a stub to the library , but it does n't have anything in it . There 's a asm. $ typesByName , but that is an empty object . What I want to do ( to see it work ) is to call the Multiply and Add methods.So : what am I missing ? my intent is to host a transpiled library that I can access through js , which is as I understand it : possible . I just ca n't make it work . I have uploaded my entire test project here : https : //github.com/mgravell/jsilfun <code> namespace TestLib { public class MagicType { public int Multiply ( int x , int y ) { // test instance method return x * y ; } public static int Add ( int x , int y ) { // test static int method return x + y ; } } } < script type= '' text/javascript '' > var jsilConfig = { libraryRoot : '/js/jsil/ ' , scriptRoot : '/js/testlib/ ' , manifestRoot : '/js/testlib/ ' , manifests : [ 'TestLib.dll ' ] // gets as far as Loading '/js/testlib/TestLib.dll.manifest.js ' ... // which is 200 / OK } ; var asm = null ; var runMain = function ( ) { // does n't get invoked console.log ( ' > main ' ) ; asm = JSIL.GetAssembly ( `` TestLib '' , true ) ; // ( executed outside method ) returns a stub with no content console.log ( ' < main ' ) ; } ; < /script > < script src= '' /js/jsil/jsil.js '' > < /script > Loading '/js/testlib/TestLib.dll.manifest.js ' ... var asm = JSIL.GetAssembly ( `` TestLib '' , true ) ;
How to access a basic JSIL library ( from C # ) in a web page ?
C_sharp : I 've this code I expected the output to be x = 57 and y = 94 . However , when executed it gave me 56 and 93.For some reason the post increment operator is not getting executed in line 3.Is this because we are assigning the result of expressing in line 3 to x itself ? Are there any other scenarios where the post increment operator would not result as expected.Thanks . <code> static void Main ( string [ ] args ) { int x = 20 ; int y = 35 ; x = y++ + x++ ; y = ++y + ++x ; Console.WriteLine ( x ) ; Console.WriteLine ( y ) ; Console.ReadLine ( ) ; }
Post increment question
C_sharp : Say you have 3 classes that implement IDisposable - A , B and C. Classes A and B are both dependent on class C. Would it be correct to say that classes A and B 's typical implementation of Dispose ( ) would be : If there 's an instance of A and and instance of B that share the same instance of C , how would you overcome the problem that disposing an instance of A would damage the instance of B ? Last minute addendum - If in point 2 it 's a DI container that instantiates all instances , who is responsible for disposing of the objects ? Is it the container itself ? How ? Thanks , urig <code> public void Dispose ( ) { if ( m_C ! = null ) m_C.Dispose ( ) ; }
A problematic example of the IDisposable pattern ?
C_sharp : Am getting the below error when I try to download the a .pdf file from a url through my .exe file . The server committed a protocol violation . Section=ResponseHeader Detail=CR must be followed by LFbut the same is getting downloaded when I try to debug the code from visual studio . I am totally lost , no clue of whats going on . Can somebody tell me what could be the problem My App.config fileuseUnsafeHeaderParsing= '' true '' is the obvious fix that everyone is stating on internet unfortunately it is not working Here is my webclient code Update : My .exe was able to download most of the url 's except few . Consider I have 4 url 's : A , B , C and D. My visual studio was able to download files from all 4 urls ' but my .exe download 's file from first 3 url 's . For url , D it throws The server committed a protocol violation . Section=ResponseHeader Detail=CR must be followed by LFUpdate 2 : I was trying to trace D url using fiddler . When I ran the D url from browser to download the file , I got the below header and file was downloaded . Also note that D url is redirected to another url before downloading When I tried to downlaod the file from D url using .exe I got the below headerFor some reason the User-Agent is that the problem ? Update3 : dir /s /b of the bin\debug <code> < ? xml version= '' 1.0 '' ? > < configuration > < system.net > < settings > < httpWebRequest useUnsafeHeaderParsing= '' true '' / > < /settings > < /system.net > < /configuration > public class CookieAwareWebClient : WebClient { private CookieContainer cc = new CookieContainer ( ) ; private string lastPage ; protected override WebRequest GetWebRequest ( Uri address ) { if ( address.Scheme == Uri.UriSchemeHttps ) { ServicePointManager.SecurityProtocol = ( SecurityProtocolType ) 3072 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls ; // allows for validation of SSL conversations ServicePointManager.ServerCertificateValidationCallback = delegate { return true ; } ; } WebRequest R = base.GetWebRequest ( address ) ; if ( R is HttpWebRequest ) { HttpWebRequest wr = ( HttpWebRequest ) R ; wr.CookieContainer = cc ; if ( lastPage ! = null ) { wr.Referer = lastPage ; } } lastPage = address.ToString ( ) ; return R ; } } CONNECT www.loim.com:443 HTTP/1.1Host : www.loim.com:443Connection : keep-aliveUser-Agent : Mozilla/5.0 ( Windows NT 6.2 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/61.0.3163.100 Safari/537.36 CONNECT www.loim.com:443 HTTP/1.1Host : www.loim.comConnection : Keep-Alive C : \Pradeep\TFS\proj\bin\Debug\app.publishC : \Pradeep\TFS\proj\bin\Debug\CLImport.applicationC : \Pradeep\TFS\proj\bin\Debug\CLImport.exeC : \Pradeep\TFS\proj\bin\Debug\CLImport.exe.configC : \Pradeep\TFS\proj\bin\Debug\CLImport.exe.manifestC : \Pradeep\TFS\proj\bin\Debug\CLImport.pdbC : \Pradeep\TFS\proj\bin\Debug\CLImport.vshost.applicationC : \Pradeep\TFS\proj\bin\Debug\CLImport.vshost.exeC : \Pradeep\TFS\proj\bin\Debug\CLImport.vshost.exe.configC : \Pradeep\TFS\proj\bin\Debug\CLImport.vshost.exe.manifestC : \Pradeep\TFS\proj\bin\Debug\FED.Business.Collection.dllC : \Pradeep\TFS\proj\bin\Debug\FED.Business.Collection.pdbC : \Pradeep\TFS\proj\bin\Debug\FED.Data.Collection.dllC : \Pradeep\TFS\proj\bin\Debug\FED.Data.Collection.pdbC : \Pradeep\TFS\proj\bin\Debug\FED.DataSource.Utilities.dllC : \Pradeep\TFS\proj\bin\Debug\FED.DataSource.Utilities.pdbC : \Pradeep\TFS\proj\bin\Debug\GemBox.Spreadsheet.dllC : \Pradeep\TFS\proj\bin\Debug\ICSharpCode.SharpZipLib.dllC : \Pradeep\TFS\proj\bin\Debug\IgnoredC : \Pradeep\TFS\proj\bin\Debug\itextsharp.dllC : \Pradeep\TFS\proj\bin\Debug\Microsoft.Exchange.WebServices.dllC : \Pradeep\TFS\proj\bin\Debug\ProcessedC : \Pradeep\TFS\proj\bin\Debug\tt.textC : \Pradeep\TFS\proj\bin\Debug\app.publish\CLImport.exe
File is downloading through visual studio but not through .exe
C_sharp : When using IndexOf to find a char which is followed by a large valued char ( e.g . char 700 which is ʼ ) then the IndexOf fails to recognize the char you are looking for.e.g.In this code , index should be 2 , but it returns 6.Is there a way to get around this ? <code> string find = `` abcʼabcabc '' ; int index = find.IndexOf ( `` c '' ) ;
string.IndexOf ( ) not recognizing modified characters
C_sharp : Our current web portal at work was a port from a classic ASP codebase . Currently , all pages in our project extend a custom Page class called PortalPage . It handles login/logout , provides access to a public User object for the currently authenticated user , and adds the standard page header and footer to all of our pages.Every Page in our site is 100 % designed in the codebehind . The ASPX page is not used at all . Every single div , img , and block of text is allocated as an object and added from a C # function , even if it is completely static content ( which we have a decent amount of ) .Example for a page header : Even worse , all Javascript is added to the page as a giant mess of string concatenations : Currently , one of my coworkers is arguing that allocating every object in the codebehind is hundreds of times faster than using the ASPX w/ Codebehind approach that I see every other web app using . This goes against my instincts , as it 's essentially adding runat= '' server '' to every piece of HTML on the page.He also says that all professional shops write code this way and never use ASPX pages . He says that all textbooks and sample code uses ASPX pages because they 're easier for newbie coders to understand . Is there truth to this , or are we just writing in an incredibly inefficient way for the sake of tradition ? In order for us to switch to the `` standard '' way of writing Web Forms , I need to provide some source to show that he 's wrong.My problem is , I 've never even heard of anyone else writing everything in the codebehind . Every example I 've seen uses ASPX pages for the user interface and a code-behind for logic , database calls , etc.So in summary:1 ) Are ASPX pages really that much slower than 100 % codebehind ? 2 ) Do professional shops actually use 100 % codebehind ? 3 ) If ASPX w/ codebehind is the way to go , does anyone have any creditable links that could help back me up ? <code> HtmlGenericControl wrapperDiv = new HtmlGeneric ( `` div '' ) ; HtmlAnchor bannerLink = new HtmlAnchor ( ) ; HtmlImage banner = new HtmlImage ( ) ; bannerLink.HRef = `` index.aspx '' ; banner.Src = `` mybanner.png '' ; banner.Alt = `` My Site '' ; bannerLink.Controls.Add ( banner ) ; wrapperDiv.Controls.Add ( bannerLink ) ; this.Page.Controls.Add ( wrapperDiv ) ; ClientScript.RegisterClientScriptBlock ( this.GetType ( ) , `` javascript '' , @ '' < script language='javascript ' > fullUrl = ' '' + ConfigurationManager.AppSettings [ `` fullUrl '' ] .ToString ( ) + @ '' ' ; function showModule ( ) { $ ( ' # '' + this.userModule.ClientID + @ '' ' ) .css ( 'display ' , 'block ' ) ; $ ( ' # '' + this.groupModule.ClientID + @ '' ' ) .css ( 'display ' , 'none ' ) ; $ ( ' # '' + this.listsModule.ClientID + @ '' ' ) .css ( 'display ' , 'none ' ) ; $ ( ' # '' + this.labelsModule.ClientID + @ '' ' ) .css ( 'display ' , 'none ' ) ; }
Designing all pages completely in the codebehind ?
C_sharp : I implemented an autocomplete search box on my asp.net mvc4 site . I am currently able to have the box return results that update as i type in the search box . I also am dynamically generating `` category '' buttons based on the result `` type IDs '' and inserting them in a header that appears when the autocomplete produces results.I want to introduce functionality that goes like this : when the user clicks the category button , the existing autocomplete results get filtered further so only results of that `` type ID '' are shown . After that , if the user wants to see all of the results matching the search string again , they can click the `` All '' button.To see a working version of this , please check out the search box on Discogs.com . I have also pasted a screenshot of this widget below , for reference.How can I implement this ? I ca n't find any stackoverflow posts about this because I do n't know how to phrase my question.My code is below . In it , I already have a functioning autocomplete , and I have the portion that dynamically generates the category buttons . Now what I need help with is finding a design pattern to further filter the autocomplete results when I click the category buttons that were dynamically generated . <code> @ model myproject.Models.Search_Term @ Scripts.Render ( `` ~/bundles/jquery '' ) < script type= '' text/javascript '' > //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // autopopulate input boxes //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //detect the browser resize and close the Autocomplete box when that event is triggered $ ( window ) .resize ( function ( ) { $ ( `` # searchBox '' ) .autocomplete ( `` close '' ) ; } ) ; //helper method for autopopulate . //https : //stackoverflow.com/questions/2435964/how-can-i-custom-format-the-autocomplete-plug-in-results //this helps in creating a autocomplete menu with custom HTML formatting function monkeyPatchAutocomplete ( ) { $ .ui.autocomplete.prototype._renderItem = function ( ul , item ) { var inner_html = ' < img src= '' ' + item.imgPathSmall + ' '' > ' ; return $ ( `` < li > '' ) .data ( `` ui-autocomplete-item '' , item ) .append ( inner_html ) .appendTo ( ul ) ; } ; } // look up search term $ ( document ) .ready ( function ( ) { //call this to enable the autocomplete menu with custom HTML formatting monkeyPatchAutocomplete ( ) ; //trigger autocomplete $ ( `` # searchBox '' ) .autocomplete ( { source : function ( request , response ) { $ .ajax ( { url : `` /Explore/SearchAutocomplete '' , type : `` POST '' , dataType : `` json '' , data : { search : request.term } , success : function ( data ) { response ( $ .map ( data , function ( item ) { return { objectName : item.ObjectName , detail1 : item.Detail1 , detail2 : item.Detail2 , detail3 : item.Detail3 , imgPathSmall : item.Image_Data_SmallPad_string , objectType : item.ObjectType , objectID : item.ObjectID , image_Data_SmallPad : item.Image_Data_SmallPad , image_MimeType_SmallPad : item.Image_MimeType_SmallPad } ; } ) ) } } ) } , select : function ( event , ui ) { event.preventDefault ( ) ; //redirect to result page var url ; switch ( ui.item.objectType ) { case 1 : url = ' @ Url.Action ( `` Category1 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 2 : url = ' @ Url.Action ( `` Category2 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 3 : url = ' @ Url.Action ( `` Category3 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 4 : url = ' @ Url.Action ( `` Category4 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 5 : url = ' @ Url.Action ( `` Category5 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 6 : url = ' @ Url.Action ( `` Category6 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; break ; case 7 : url = ' @ Url.Action ( `` Category7 '' , `` Explore '' ) ? i= ' + ui.item.objectID ; } window.location.href = url ; } } ) .data ( `` ui-autocomplete '' ) ._renderMenu = function ( ul , items ) { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //Append the header // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- var header = ` < li > < div class='acmenu_header ' > < div class= '' btn-group special '' role= '' group '' aria-label= '' ... '' > < button type= '' button '' class= '' btn btn-default btn-xs '' > All < /button > ` ; //helps determine the category buttons to generate var categories = [ ] ; $ .each ( items , function ( index , item ) { if ( item.objectType ) { switch ( item.objectType ) { case 1 : categories.push ( 1 ) ; break ; case 2 : categories.push ( 2 ) ; break ; case 3 : categories.push ( 3 ) ; break ; case 4 : categories.push ( 4 ) ; break ; case 5 : categories.push ( 5 ) ; break ; case 6 : categories.push ( 6 ) ; break ; case 7 : categories.push ( 7 ) ; } } } ) ; //helps determine the category buttons to generate var uniqueCategories = [ ... new Set ( categories ) ] ; var arrayLength = uniqueCategories.length ; //generate the category buttons within the header for ( var i = 0 ; i < arrayLength ; i++ ) { switch ( uniqueCategories [ i ] ) { case 1 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category1 < /button > ' break ; case 2 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category2 < /button > ' break ; case 3 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category3 < /button > ' break ; case 4 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category4 < /button > ' break ; case 5 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category5 < /button > ' break ; case 6 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category6 < /button > ' break ; case 7 : header = header + ' < button type= '' button '' class= '' btn btn-default btn-xs '' > Category7 < /button > ' } } header = header + ` < /div > < /div > < /li > ` ; $ ( ul ) .append ( header ) ; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- //append the autocomplete results var that = this ; var currentCategory = `` '' ; var currentCategoryLabel = `` '' ; $ .each ( items , function ( index , item ) { if ( item.objectType ! = currentCategory ) { if ( item.objectType ) { switch ( item.objectType ) { case 1 : currentCategoryLabel = `` Category1 '' ; break ; case 2 : currentCategoryLabel = `` Category2 '' ; break ; case 3 : currentCategoryLabel = `` Category3 '' ; break ; case 4 : currentCategoryLabel = `` Category4 '' ; break ; case 5 : currentCategoryLabel = `` Category5 '' ; break ; case 6 : currentCategoryLabel = `` Category6 '' ; break ; case 7 : currentCategoryLabel = `` Category7 '' ; } ul.append ( `` < li class='ui-autocomplete-category ' > '' + currentCategoryLabel + `` < /li > '' ) ; } currentCategory = item.objectType ; } that._renderItem ( ul , item ) ; } ) ; //append the footer var footer = ` < li > < mark > < span class= '' glyphicon glyphicon-cog '' aria-hidden= '' true '' > < /span > Advanced search < /mark > < /li > ` ; $ ( ul ) .append ( footer ) ; } ; } ) < /script > @ using ( Html.BeginForm ( `` Search '' , `` Explore '' , FormMethod.Post , new { id = `` searchFormNavbar '' , @ class = `` nav navbar-form navbar-left '' , enctype = `` multipart/form-data '' } ) ) { @ Html.AntiForgeryToken ( ) < div class= '' input-group '' id= '' searchDiv '' > @ Html.EditorFor ( m = > Model.SearchTerm , new { htmlAttributes = new { @ class = `` form-control '' , @ id = `` searchBox '' , placeholder = `` Search x , y , z , and more ... '' , style = `` width:100 % ; min-width : 380px ; '' } } ) < div class= '' input-group-btn '' > < button id= '' searchBtn '' class= '' btn btn-default '' type= '' submit '' style= '' color : steelblue '' > < span class= '' glyphicon glyphicon-search '' aria-hidden= '' true '' > < /span > < /button > < /div > < /div > }
How to use button within autocomplete dropdown to further filter the already-displayed results
C_sharp : As practice for writing fluent APIs , I thought I 'd make the following compile and run : The idea is .When will test each element in the enumeration , and if it passes the predicate , to have the action run . If the predicate fails , the item is passed down the chain.The graph I came up with was : I am running into an issue -- When ca n't foreach / yield return inside of it , because the return type is n't directly IEnumerable < T > ( although it inherits from it ) . That has thrown a mental wrench into the gears . What would the implementation of the extension methods look like ? <code> static void Main ( string [ ] args ) { Enumerable.Range ( 1 , 100 ) .When ( i = > i % 3 == 0 ) .Then ( i = > Console.WriteLine ( `` fizz '' ) ) .When ( i = > i % 5 == 0 ) .Then ( i = > Console.WriteLine ( `` buzz '' ) ) .Otherwise ( i = > Console.WriteLine ( i ) ) .Run ( ) ; Console.ReadLine ( ) ; } public static class EnumerableExtensions { public static IConditionalEnumerable < T > When < T > ( this IEnumerable < T > items , Predicate < T > test , Action < T > action ) { } public static IResolvedEnumerable < T > Then < T > ( this IConditionalEnumerable < T > items , Predicate < T > test , Action < T > action ) { } public static void Run < T > ( this IEnumerable < T > items ) { foreach ( var item in items ) ; } } public interface IConditionalEnumerable < T > : IEnumerable < T > { IResolvedEnumerable < T > Then < T > ( IConditionalEnumerable < T > items , Action < T > action ) ; } public interface IResolvedEnumerable < T > : IEnumerable < T > { IEnumerable < T > Otherwise ( Action < T > behavior ) ; }
What is the fluent object model to make this work ?
C_sharp : I stumbled upon a strange behavior of Convert.FromBase64String in .NET 4.7.2 . Normally it would throw an exception when the padding is not correct . But I found a case where adding another padding character produces an incorrect result instead of an exception . In this case correct is [ 97 , 97 ] or `` aa '' in a string form . But when I add another = : instead of getting an exception I get one byte less and incorrect is [ 88 ] or `` X '' is a string form . Weird . Is this a bug and it should be reported ? Or is it a known/documented behavior ? I could n't find any references to this.Compare to Ruby . This evaluates to `` aa '' : And this raises an exception : <code> var correct = Convert.FromBase64String ( `` YWE= '' ) ; var incorrect = Convert.FromBase64String ( `` YWE== '' ) ; Base64.strict_decode64 `` YWE= '' Base64.strict_decode64 `` YWE== '' ArgumentError : invalid base64from /usr/local/Cellar/ruby/2.6.1/lib/ruby/2.6.0/base64.rb:74 : in ` unpack1 '
Decoding Base64 in C # sometimes gives incorrect result with one extra padding character
C_sharp : This probably applies to other places , but in WinForms , when I use binding I find many methods want to take the name of the property to bind to . Something like : The big problem I keep having with this is that `` Name '' and `` Age '' are specified as strings . This means the compiler is no help if someone renames one of Person 's properties . The code will compile fine , but the bindings will be broken.Is there a standard way of solving this that I 've missed ? It feels like I need some keyword , maybe called stringof to match the existing typeof . You could use it something like : stringof could return some class that has properties for getting the full path , part of the path , or the string so you can parse it up yourself.Is something like this already do-able ? <code> class Person { public String Name { get { ... } set { ... } } public int Age { get { ... } set { ... } } } class PersonView { void Bind ( Person p ) { nameControl.Bind ( p , '' Name '' ) ; ageControl.Bind ( p , '' Age '' ) ; } } ageControl.Bind ( p , stringof ( p.Age ) .Name ) ;
Is there a way of making C # binding work statically ?
C_sharp : I really enjoy to be able to do this in C # : Whereas in Java I would have done it like that : Notice that the Java code tells the type of what is returned ( Pizza instances ) . The C # code does n't . It bugs me , especially in situations where others programmers do n't have access to the source code . Is there a way to fix this ? Update : My problem was that I used `` System.Collections '' instead of `` System.Collections.Generic '' and therefore I was using the non-generic version of IEnumerable . <code> IEnumerable GetThePizzas ( ) { yield return new NewYorkStylePizza ( ) ; yield return new SicilianPizza ( ) ; yield return new GreekPizza ( ) ; yield return new ChicagoStylePizza ( ) ; yield return new HawaiianPizza ( ) ; } Collection < Pizza > getThePizzas ( ) { ArrayList < Pizza > pizzas = new ArrayList < Pizza > ( ) ; pizzas.add ( new NewYorkStylePizza ( ) ) ; pizzas.add ( new SicilianPizza ( ) ) ; pizzas.add ( new GreekPizza ( ) ) ; pizzas.add ( new ChicagoStylePizza ( ) ) ; pizzas.add ( new HawaiianPizza ( ) ) ; return pizzas ; }
Strongly-typed method interface using yield return
C_sharp : I 'm reading an OfficeOpenXml.ExcelWorksheet and getting the ArgumentOufOfRangeException on the middle of the Collection . I 'm reading like this process.Information = sheet.Cells [ line , i++ ] .Text ; . On this line i = 22 while the sheet.Dimension.Column = 28 . When I 'm debugging and enumerate the collection I see that the Exception is thrown on the method .Text while the .Value method is showing the correct value.According to the exception stack trace , the exception is being thrown by the System.Text.StringBuilder.Insert ( ) method -- -- EDIT -- -- After the accepted answer I realized that the problem is not only on the read . I reply the same file with an extra column ( import success or insuccess ) and while I 'm doing the sheet formatation I get again the same error , all due to the method System.Text.StringBuilder.Insert ( ) . I 'm trying to AutoFit a column sheet.Column ( 22 ) .AutoFit ( ) This is the stack trace <code> at System.Text.StringBuilder.Insert ( Int32 index , Char* value , Int32 valueCount ) at System.Text.StringBuilder.Insert ( Int32 index , Char value ) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.ExcelFormatTranslator.ToNetFormat ( String ExcelFormat , Boolean forColWidth ) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.ExcelFormatTranslator..ctor ( String format , Int32 numFmtID ) at OfficeOpenXml.Style.XmlAccess.ExcelNumberFormatXml.get_FormatTranslator ( ) at OfficeOpenXml.ExcelRangeBase.GetFormattedText ( Boolean forWidthCalc ) at OfficeOpenXml.ExcelRangeBase.get_TextForWidth ( ) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns ( Double MinimumWidth , Double MaximumWidth ) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns ( Double MinimumWidth ) at OfficeOpenXml.ExcelRangeBase.AutoFitColumns ( ) at OfficeOpenXml.ExcelColumn.AutoFit ( ) at SkiptraceAPI.Models.ProcessosRepository.formatExcel ( ExcelPackage package , Boolean addValidation ) in
C # ArgumentOutOfRangeException while reading ExcelWorksheet
C_sharp : I have the following method : Right now , a user of this method has to use it like this : Why do I have to specify TResult in the method defintion ? The compiler already knows TResult since I specified it in TGenericType . Ideally ( if the C # compiler was a little smarter ) , my method would look like this : So the user could just simply use it like this : Is there a way to do what I want to do ? <code> public TResult Get < TGenericType , TResult > ( ) where TGenericType : SomeGenericType < TResult > where TResult : IConvertible { // ... code that uses TGenericType ... // ... code that sets someValue ... return ( TResult ) someValue ; } //Notice the duplicate int type specificationint number = Get < SomeGenericType < int > , int > ( ) ; public TResult Get < TGenericType > ( ) where TGenericType : SomeGenericType < TResult > where TResult : IConvertible { // ... code that uses TGenericType ... // ... code that sets someValue ... return ( TResult ) someValue ; } //Much cleanerint number = Get < SomeGenericType < int > > ( ) ;
How to get the C # compiler to infer generic types ?
C_sharp : Expanding on my previous post , I am still writing Towers of Hanoi . After having a wonderful solution explained of how to draw the rings on the pegs , I still have one question that I have been fiddling with for quite awhile now . Here is my PegClass : And here is my main method . This is the current output : My question remains , how does one move the '- ' characters from peg to peg when asked for a prompt . I 've tried tweaking it for hours and still could n't figure it out . Thank you in advance , youmeoutside <code> namespace Towers_Of_Hanoi { class PegClass { private int pegheight ; private int y = 3 ; int [ ] rings = new int [ 0 ] ; public PegClass ( ) { //this is the default constructor } public PegClass ( int height ) { pegheight = height ; } // other user defined functions public void AddRing ( int size ) { Array.Resize ( ref rings , rings.Length + 2 ) ; rings [ rings.Length - 1 ] = size ; } public void DrawPeg ( int x , int numberOfRings = 0 ) { for ( int i = pegheight ; i > = 1 ; i -- ) { string halfRing = new string ( ' ' , i ) ; if ( numberOfRings > 0 ) { if ( i < = numberOfRings ) halfRing = new string ( '- ' , numberOfRings - i + 1 ) ; } Console.SetCursorPosition ( x - halfRing.Length * 2 + i + ( halfRing.Contains ( `` - '' ) ? ( -i + halfRing.Length ) : 0 ) , y ) ; Console.WriteLine ( halfRing + `` | '' + halfRing ) ; y++ ; } if ( x < 7 ) { x = 7 ; } Console.SetCursorPosition ( x - 7 , y ) ; //print the base of the peg Console.WriteLine ( `` -- -- -- -- -- -- -- -- '' ) ; } } } namespace Tower_of_hanoi { class Program { static void Main ( string [ ] args ) { PegClass myPeg = new PegClass ( 8 ) ; PegClass myPeg2 = new PegClass ( 8 ) ; PegClass myPeg3 = new PegClass ( 8 ) ; DrawBoard ( myPeg , myPeg2 , myPeg3 ) ; Console.WriteLine ( `` \t\t\nWelcome to kTowers ! `` ) ; while ( true ) { string input = `` \nWhat peg do you want to move to commander ? `` ; Console.WriteLine ( input ) ; if ( input == `` 2 '' ) { myPeg.DrawPeg ( 2 ) ; } Console.ReadLine ( ) ; } } public static void DrawBoard ( PegClass peg1 , PegClass peg2 , PegClass peg3 ) { Console.Clear ( ) ; peg1.DrawPeg ( 20,1 ) ; peg2.DrawPeg ( 40,2 ) ; peg3.DrawPeg ( 60,4 ) ; } } } | | | | | | | | | | | | | | -|- | | -- | -- | -|- -- -| -- - -|- -- | -- -- -- | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Towers of Hanoi : Moving Rings from Peg to Peg
C_sharp : I have a method that takes three parameters : List < Class1 > source , List < Class2 ) results , and DateTime endDate . I can see why the class coupling is four . However , it jumps to ten when I add this statement : My questions : What are the six new classes that were introduced by the LINQ statement ? And since ten is the upper limit of `` good code , '' does this indicate that LINQ is not a good choice here ? <code> var warnings = from s in source join r in results on s.Field1 equals r.Field1 into joined from j in joined.DefaultIfEmpty ( ) where j == null select string.Format ( `` { 0 } { 1 } '' , A_CONSTANT , s.Field2 ) ;
Why does Class Coupling jump when I use LINQ ?
C_sharp : I 'm wondering why this C # codeis compiled to ( Because it takes 3 bytes instead of the 9 required by ldc.i8 20 . See this for more information . ) while this codeis compiled to the 9-byte instructioninstead of this 3-byte sequence ( Using mono 4.8 . ) Is this a missed opportunity or the cost of the conv.i8 outbalances the gain in code size ? <code> long b = 20 ; ldc.i4.s 0x14conv.i8 double a = 20 ; ldc.r8 20 ldc.i4.s 0x14conv.r8
Why does the compiler optimize ldc.i8 and not ldc.r8 ?
C_sharp : I have the following classes defined : Now , in my global.asax , I 've defined the following Mapping in Application_Start ( ) .Lastly , in one of my controllers , I have the following code : The first time I call the Action on my controller and this mapping is run , everything works fine and the InstrumentNumber is correctly mapped to the InstrumentNo of the Clerk object . However , the second time the Action gets called , InstrumentNo does not get mapped . InstrumentNumber definitely has a value but InstrumentNo remains null.Any ideas what might be happening here ? <code> public class ImageIndexModel { public string Description { get ; set ; } public string InstrumentNumber { get ; set ; } } public class ImageEditModel : ImageIndexModel { public int TotalCount = 0 ; } public class Clerk { //This is actually a class defined by LinqToSql public string Description { get ; set ; } public string InstrumentNo { get ; set ; } } Mapper.CreateMap < ImageIndexModel , Clerk > ( ) .ForMember ( dest = > dest.InstrumentNo , opt = > opt.MapFrom ( src = > src.InstrumentNumber ) ) ; var _existing = new Clerk ( ) ; var _default = new ImageEditModel ( ) { InstrumentNumber = `` 12345678 '' , Description = `` Test '' } ; Mapper.Map ( _default , _existing ) ;
Automapper maps correctly on first call but skips properties on second call