text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : I am trying to build an ASP.NET Core docker image with following Dockerfile : The build fails , and it gives the following error : /app/MyPCL/MyPCL.csproj ( 70,3 ) : error MSB4019 : The imported project `` /usr/share/dotnet/sdk/1.0.1/Microsoft/Portable/v4.5/Microsoft.Portable.CSharp.targets '' was not found . Confirm that the path in the declaration is correct , and that the file exists on disk.So it is having trouble building the PCL library , as it ca n't find Microsoft.Portable.CSharp.targets.My PCL project file has the following import statement : which I am thinking is causing the problem , as this path must not exist in the docker container . BTW , the project builds and runs perfectly in Visual Studio 2017.Any ideas ? <code> FROM microsoft/aspnetcore-build:1.1.1WORKDIR /appCOPY src .RUN dotnet restoreRUN dotnet publish -- output /out/ -- configuration ReleaseEXPOSE 5000ENTRYPOINT [ `` dotnet '' , '' /out/MyWebApp.dll '' ] < Import Project= '' $ ( MSBuildExtensionsPath32 ) \Microsoft\Portable\ $ ( TargetFrameworkVersion ) \Microsoft.Portable.CSharp.targets '' / > | Ca n't build ASP.NET Core app that references PCL in docker |
C_sharp : I 'm trying to zip and unzip data in memory ( so , I can not use FileSystem ) , and in my sample below when the data is unzipped it has a kind of padding ( '\0 ' chars ) at the end of my original data . What am I doing wrong ? <code> [ Test ] public void Zip_and_Unzip_from_memory_buffer ( ) { byte [ ] originalData = Encoding.UTF8.GetBytes ( `` My string '' ) ; byte [ ] zipped ; using ( MemoryStream stream = new MemoryStream ( ) ) { using ( ZipFile zip = new ZipFile ( ) ) { //zip.CompressionMethod = CompressionMethod.BZip2 ; //zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed ; zip.AddEntry ( `` data '' , originalData ) ; zip.Save ( stream ) ; zipped = stream.GetBuffer ( ) ; } } Assert.AreEqual ( 256 , zipped.Length ) ; // Just to show that the zip has 256 bytes which match with the length unzipped below byte [ ] unzippedData ; using ( MemoryStream mem = new MemoryStream ( zipped ) ) { using ( ZipFile unzip = ZipFile.Read ( mem ) ) { //ZipEntry zipEntry = unzip.Entries.FirstOrDefault ( ) ; ZipEntry zipEntry = unzip [ `` data '' ] ; using ( MemoryStream readStream = new MemoryStream ( ) ) { zipEntry.Extract ( readStream ) ; unzippedData = readStream.GetBuffer ( ) ; } } } Assert.AreEqual ( 256 , unzippedData.Length ) ; // WHY my data has trailing '\0 ' chars like a padding to 256 module ? Assert.AreEqual ( originalData.Length , unzippedData.Length ) ; // FAIL ! The unzipped data has 256 bytes //Assert.AreEqual ( originalData , unzippedData ) ; // FAIL at index 9 } | Unzipped data being padded with '\0 ' when using DotNetZip and MemoryStream |
C_sharp : Just wondering if this is considered a clear use of goto in C # : I feel like this is ok , because the snippet is small and should make sense . Is there another way people usually recover from errors like this when you want to retry the operation after handling the exception ? Edit : That was fast . To answer a few questions and clarify things a bit - this is part of a process which is essentially converting from a different kind of project . The _userInteractor.GetDatabaseConnector ( ) call is the part which will determine if the user wants to retry ( possibly with a different database than the one in the config they are loading from ) . If it returns null , then no new database connection was specified and the operation should fail completely.I have no idea why I did n't think of using a while loop . It must be getting too close to 5pm.Edit 2 : I had a look at the LoadDatabase ( ) method , and it will throw a DatabaseLoaderException if it fails . I 've updated the code above to catch that exception instead of Exception.Edit 3 : The general consensus seems to be thatUsing goto here is not necessary - a while loop will do just fine.Using exceptions like this is not a good idea - I 'm not sure what to replace it with though . <code> IDatabase database = null ; LoadDatabase : try { database = databaseLoader.LoadDatabase ( ) ; } catch ( DatabaseLoaderException e ) { var connector = _userInteractor.GetDatabaseConnector ( ) ; if ( connector == null ) throw new ConfigException ( `` Could not load the database specified in your config file . `` ) ; databaseLoader = DatabaseLoaderFacade.GetDatabaseLoader ( connector ) ; goto LoadDatabase ; } | Is this a clear use of goto ? |
C_sharp : I have an entity collection of Readings.Each Reading is linked to an entity called Meter . ( And each Meter holds multiple readings ) .each Reading holds a field for meter id ( int ) and a field for time.Here is some simplified code to demonstrate it : Given a specific period and list of meterids , what would be the most efficient way to get for each Meterthe first and last reading in that time period ? I am able to iterate through all meters and for each meter to obatinfirst and last reading for the period , but I was wandering if there is a more efficient way to acheive this.And a bonus question : same question , but with multiple periods of time to get data for , instead of just one period . <code> public class Reading { int Id ; int meterId ; DateTime time ; } public class Meter { int id ; ICollection < Readings > readings ; } | Efficient LINQ to Entities query |
C_sharp : I 'm having trouble understanding how to render a collection as a drop down list.If I have a model like : I would like the string collection to render as a drop down list . Using the html page helper InputFor does n't seem to work . It simply render 's a text box . I 've noticed that InputFor can reflect on the property type and render html accordingly . ( Like a checkbox for a boolean field ) . I also notice that FubuPageExtensions has methods for CheckBoxFor and TextBoxFor , but nothing equivalent to DropDownListFor.I 'm probably missing something quite fundamental in understanding html conventions in fubu.Do I need to build the select tag myself ? If so , what is the recommended approach to do it ? <code> public class AccountViewModel { public string [ ] Country { get ; set ; } } | fubumvc - rendering a collection as a drop down list |
C_sharp : I 'm using EntityFramework ( EF V6 ) with Asp.Net for creating one website , In that I 've Created the .edmx and .tt and DBContext.I 'm trying to create an objects for each table to summoner it later with aspxI do n't know if I 'm writing my LINQ Queries in the right way ! , that 's why I need your help on this.The Table i 'm trying to establish an LINQ object for it in this picture : This Object Class I have created : is it right or wrong ? <code> public class LINQSubjects { NewsPaperEntities ctx = new NewsPaperEntities ( ) ; // Get Subject public Subject GetSubject ( int SubjectID ) { Subject sub = ctx.Subjects.FirstOrDefault ( s= > s.Subject_ID==SubjectID ) ; return sub ; } // Get All Subject Info public List < Subject > GetAllSubjects ( ) { List < Subject > sublist = ( from s in ctx.Subjects select s ) .ToList < Subject > ( ) ; return sublist ; } // Insert a Subject public void AddSubject ( Subject Addsub ) { ctx.Subjects.Add ( Addsub ) ; ctx.SaveChanges ( ) ; } // Delete a Subject public void DeleteSubject ( int SubjectID ) { Subject sub = ctx.Subjects.FirstOrDefault ( s = > s.Subject_ID == SubjectID ) ; ctx.Subjects.Remove ( sub ) ; ctx.SaveChanges ( ) ; } // Edit a Subject public void UpdateSubject ( Subject Newsub ) { Subject Oldsub = ctx.Subjects.FirstOrDefault ( s = > s.Subject_ID == Newsub.Subject_ID ) ; Oldsub = Newsub ; ctx.SaveChanges ( ) ; } } | How to write LINQ Queries for CRUD using Entity Framework ? |
C_sharp : I 've started using Swashbuckle with Web API . None of my types are getting rendered correctly in my Swagger UI . On every method , I see something like this ( unrendered ) : So I investigated , and found this in my Swagger definitions file for many of my methods : typeName exists in the definitions listing ... but its lower-cased . They 're all lower-cased , but all of the $ ref are upper-case.How do I fix this ? Bounty edit : More information is available upon request , I 'm just not sure what else might be relevant . <code> < span class= '' strong '' > Typename is not defined ! < /span > { $ ref : `` # /definitions/Typename '' , vendorExtensions : { } } [ assembly : WebActivatorEx.PreApplicationStartMethod ( typeof ( SwaggerConfig ) , `` Register '' ) ] public class SwaggerConfig { public static void Register ( ) { var thisAssembly = typeof ( SwaggerConfig ) .Assembly ; GlobalConfiguration.Configuration .EnableSwagger ( c = > { c.SingleApiVersion ( `` v1 '' , `` MyNamespace.Api '' ) ; c.IncludeXmlComments ( Path.Combine ( AppDomain.CurrentDomain.GetDataDirectoryPath ( ) , `` MyNamespace.Api.XML '' ) ) ; } ) .EnableSwaggerUi ( ) ; } } | Can not find type name in schema definitions |
C_sharp : I have a constant flow of certain items that I need to process in parallel so I 'm using TPL Dataflow . The catch is that the items that share the same key ( similar to a Dictionary ) should be processed in a FIFO order and not be parallel to each other ( they can be parallel to other items with different values ) .The work being done is very CPU bound with minimal asynchronous locks so my solution was to create an array of ActionBlock < T > s the size of Environment.ProcessorCount with no parallelism and post to them according to the key 's GetHashCode value.Creation : Usage : So , my question is , is this the best solution to my problem ? Am I hurting performance/scalability ? Am I missing something ? <code> _actionBlocks = new ActionBlock < Item > [ Environment.ProcessorCount ] ; for ( int i = 0 ; i < _actionBlocks.Length ; i++ ) { _actionBlocks [ i ] = new ActionBlock < Item > ( _ = > ProcessItemAsync ( _ ) ) ; } bool ProcessItem ( Key key , Item item ) { var actionBlock = _actionBlocks [ ( uint ) key.GetHashCode ( ) % _actionBlocks.Length ] ; return actionBlock.Post ( item ) ; } | Hashed/Sharded ActionBlocks |
C_sharp : I created a simple WPF application for enable and disable the aero shake behavior . My code is like this : Why my code does not function ? What this application do now : When I shake my window , the others windows are minimized.What I want to do : When I shake my window , or I shake any window , no window should be minimized . <code> using System.Windows ; using System.Runtime.InteropServices ; namespace TestDisableShaking { public partial class MainWindow : Window { const uint DWM_EC_DISABLECOMPOSITION = 0 ; const uint DWM_EC_ENABLECOMPOSITION = 1 ; [ DllImport ( `` dwmapi.dll '' , EntryPoint = `` DwmEnableComposition '' ) ] extern static uint DwmEnableComposition ( uint compositionAction ) ; [ DllImport ( `` dwmapi.dll '' , EntryPoint = `` DwmEnableComposition '' ) ] protected static extern uint Win32DwmEnableComposition ( uint uCompositionAction ) ; public MainWindow ( ) { InitializeComponent ( ) ; DwmEnableComposition ( DWM_EC_DISABLECOMPOSITION ) ; Win32DwmEnableComposition ( DWM_EC_DISABLECOMPOSITION ) ; } } } | How to disable the aero shake for whole system ? |
C_sharp : Situation : Say we are executing a LINQ query that joins two in-memory lists ( so no DbSets or SQL-query generation involved ) and this query also has a where clause . This where only filters on properties included in the original set ( the from part of the query ) . Question : Does the linq query interpreter optimize this query in that it first executes the where before it performs the join , regardless of whether I write the where before or after the join ? – so it does not have to perform a join on elements that are not included later anyways.Example : For example , I have a categories list I want to join with a products list . However , I am just interested in the category with ID 1 . Does the linq interpreter internally perform the exact same operations regardless of whether I write : orPrevious research : I already saw this question but the OP author stated that his/her question is only targeting non-in-memory cases with generated SQL . I am explicitly interested with LINQ executing a join on two lists in-memory.Update : This is not a dublicate of `` Order execution of chain linq query '' question as the referenced question clearly refers to a dbset and my question explicitly addressed a non-db scenario . ( Moreover , although similar , I am not asking about inclusions based on navigational properties here but about `` joins '' . ) Update2 : Although very similar , this is also not a dublicate of `` Is order of the predicate important when using LINQ ? '' as I am asking explicitly about in-memory situations and I can not see the referenced question explicitly addressing this case . Moreover , the question is a bit old and I am actually interested in linq in the context of .NET Core ( which did n't exist in 2012 ) , so I updated the tag of this question to reflect this second point.Please note : With this question I am aiming at whether the linq query interpreter somehow optimizes this query in the background and am hoping to get a reference to a piece of documentation or source code that shows how this is done by linq . I am not interested in answers such as `` it does not matter because the performance of both queries is roughly the same '' . <code> from category in categoriesjoin prod in products on category.ID equals prod.CategoryIDwhere category.ID == 1 // < -- -- -- below joinselect new { Category = category.Name , Product = prod.Name } ; from category in categorieswhere category.ID == 1 // < -- -- -- above joinjoin prod in products on category.ID equals prod.CategoryIDselect new { Category = category.Name , Product = prod.Name } ; | Does `` where '' position in LINQ query matter when joining in-memory ? |
C_sharp : I am getting the error in my log . I spent most of my day finding the solution but could not find the one which meets my requirement.Here is the log errorseverity= [ ERROR ] , ipaddress=xxxx , subprocess=Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery , description=An exception was thrown while deserializing the token.Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException : Theantiforgery token could not be decrypted . -- - > System.Security.Cryptography.CryptographicException : The key { xxxxxxxxxx } was not found in the key ring . atMicrosoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore ( Byte [ ] protectedData , Boolean allowOperationsOnRevokedKeys , UnprotectStatus & status ) atMicrosoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect ( Byte [ ] protectedData , Boolean ignoreRevocationErrors , Boolean & requiresMigration , Boolean & wasRevoked ) atMicrosoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect ( Byte [ ] protectedData ) atMicrosoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize ( StringserializedToken ) atMicrosoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgeryTokenSerializer.Deserialize ( StringserializedToken ) atMicrosoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery.GetCookieTokenDoesNotThrow ( HttpContexthttpContext ) <code> `` Certificates '' : { `` StoreName '' : `` My '' , `` StoreLocation '' : `` LocalMachine '' `` SerialNumber '' : `` xxxxxxxxxxxx '' } , private X509Certificate2 LCertificate ( ) { var storeName = Configuration [ `` Certificates : StoreName '' ] ; var storeLocation = Configuration [ `` Certificates : StoreLocation '' ] ; string serialNumber = Configuration [ `` Certificates : SerialNumber '' ] ; using ( X509Store store = new X509Store ( storeName , storeLocation ) ) { var certificates = store.Certificates .Find ( X509FindType.FindBySerialNumber , serialNumber , acceptValidCertOnly ) ; return certificates [ 0 ] ; } } public void ConfigureServices ( IServiceCollection services ) { services.AddIdentityServer .AddSigningCredential ( new X509Certificate2 ( LCertificate ( ) ) ) } [ HttpPost ] [ ValidateAntiForgeryToken ] public async Task < IActionResult > Login ( LoginModel model ) { | An exception was thrown while deserializing the token.The antiforgery token could not be decrypted in .Net Core 2.2 application |
C_sharp : Consider the following , at first glance absurd , pattern match : Both is will return false . However if we use var the behavior changes completely : If you hover over var in VS2017 , the type is string but the behavior of is is completely different . The compiler is doing something radically different even though the inferred type is the same . How can this be ? Is this a bug ? Is the null type somehow bubbling out ? <code> string s = null ; if ( s is string ss ) //falseif ( s is string ) //false string s = null ; if ( s is var ss ) //true ! ? ! | Different behavior in pattern matching when using var or explicit type |
C_sharp : I have some working code that retrieves data from data base . It is interesting for me to get some better code for my solution . Are there some ways to combine two queries into one or something like this ? Same code with C # ( hope no syntax errors occurred ) : SCustomerInfo represented by folowing Structure ( code is simplified ) : Both C # and VB.NET solutions will be helpful . <code> Dim customerTitlesAndIDs = contex.CustomerTable.Select ( Function ( row ) New With { .ID = row.ID , .CustomerTitle = row.Title } ) .ToList ( ) Dim cutomerIdPayment = contex.CustomerPayments.Select ( Function ( table ) New With { .ID = table.CustomerID , .Range = table.PaymentsRange , .Values = table.Values } ) .ToList ( ) Dim customerInfos As New List ( Of SCustomerInfo ) For Each customer In customerTitlesAndIDs Dim cID As Integer = customer.ID customerInfo.Add ( New SCustomerInfo ( CreateCustomerTable ( ) , cID , customer.CustomerTitle ) ) For Each cutomerPayments In cutomerIdPayment If cutomerPayments.ID = cID Then Dim rangeValue ( 1 ) As Object rangeValue ( 0 ) = cutomerPayments.Range rangeValue ( 1 ) = cutomerPayments.Values Dim dtRow As DataRow = customerInfos.Last ( ) .PaymentTable.NewRow ( ) dtRow.ItemArray = rangeValue customerInfos.Last ( ) .PaymentTable.Rows.Add ( dtRow ) End If NextNextReturn customerInfos var customerTitlesAndIDs = contex.CustomerTable.Select ( row = > new { .ID = row.ID , .CustomerTitle = row.Title } ) .ToList ( ) ; var cutomerIdPayment = contex.CustomerPayments.Select ( table = > new { .ID = table.CustomerID , .Range = table.PaymentsRange , .Values = table.Values } ) .ToList ( ) ; List < SCustomerInfo > customerInfos = new List < SCustomerInfo > ; foreach ( var customer in customerTitlesAndIDs ) { int cID = customer.ID ; customerInfos.Add ( new SCustomerInfo ( CreateCustomerTable ( ) , cID , customer.CustomerTitle ) ) ; foreach ( var cutomerPayments in cutomerIdPayment ) { if ( cutomerPayments.ID = cID ) { object [ ] rangeValue = new object [ 1 ] { cutomerPayments.Range , cutomerPayments.Values } ; DataRow dtRow = customerInfos.Last ( ) .PaymentTable.NewRow ( ) ; dtRow.ItemArray = rangeValue ; customerInfos.Last ( ) .PaymentTable.Rows.Add ( dtRow ) ; } } } Public Structure SWindAltitude Public PaymentTableAs DataTable Public Title As String Public ID As IntegerEnd Structure | How merge two sequences into one ? |
C_sharp : Say , I have an array of lists , and I want to get a count of all of the items in all of the lists . How would I calculate the count with LINQ ? ( just general curiosity here ) Here 's the old way to do it : How would you LINQify that ? ( c # syntax , please ) <code> List < item > [ ] Lists = // ( init the array of lists ) int count = 0 ; foreach ( List < item > list in Lists ) count+= list.Count ; return count ; | What 's the LINQ'ish way to do this |
C_sharp : With the new readonly instance member features in C # 8 , I try to minify unnecessary copying of struct instances in my code.I do have some foreach iterations over arrays of structs , and according to this answer , it means that every element is copied when iterating over the array.I thought I can simply modify my code now to prevent the copying , like so : This sadly does not compile withHowever , using an indexer like this compiles : Is my syntax in the foreach alternative wrong , or is this simply not possible in C # 8 ( possibly because of how the enumeration is implemented internally ) ? Or is C # 8 applying some intelligence nowadays and does no longer copy the Color instances by itself ? <code> // Example struct , real structs may be even bigger than 32 bytes.struct Color { public int R ; public int G ; public int B ; public int A ; } class Program { static void Main ( ) { Color [ ] colors = new Color [ 128 ] ; foreach ( ref readonly Color color in ref colors ) // note 'ref readonly ' placed here Debug.WriteLine ( $ '' Color is { color.R } { color.G } { color.B } { color.A } . `` ) ; } } CS1510 A ref or out value must be an assignable variable static void Main ( ) { Color [ ] colors = new Color [ 128 ] ; for ( int i = 0 ; i < colors.Length ; i++ ) { ref readonly Color color = ref colors [ i ] ; Debug.WriteLine ( $ '' Color is { color.R } { color.G } { color.B } { color.A } . `` ) ; } } | Can I foreach over an array of structs without copying the elements in C # 8 ? |
C_sharp : When working with Domain Objects , how do you typically unit test a method that calls another method in the object ? For example : Unit testing GetTotalAmt ( ) is easy , but with GetExtendedTotalAmt ( ) I 'd have to use stub/mock InvoiceLine objects to make it work , when all I really want to do is test that a discount is applied if the IsDiscounted flag is true . How do other people handle this ? I do n't think it makes sense to split up the domain object since these methods are both considered part of the core Invoice functionality ( and splitting it would likely cause developers to call the wrong method more often ) .Thanks ! <code> public class Invoice { public IList < InvoiceLine > InvoiceLines ; public string Company ; public bool IsDiscounted ; public DateTime InvoiceDate ; // ... public GetTotalAmt ( ) ; public GetExtendedTotalAmt ( ) ; public decimal GetTotalAmt ( ) { decimal total ; foreach ( InvoiceLine il in InvoiceLines ) { total += il.Qty * il.Price ; } return total ; } public decimal GetExtendedTotalAmt ( ) { decimal discount ; if ( IsDiscounted ) discount = .05M ; return GetTotalAmt ( ) * discount ; } } | How to test methods that call other methods in a domain object |
C_sharp : I 've been writing things like this in my implementations : However , I do n't know exactly what 's happening here ... Maybe everything was `` copied '' to the delegate . Or maybe , like reference types , all value types will have a copy associated to the Task delegate until it exists ? I 'm just trying to understand what exactly happens in latest C # versions for performance matters . <code> public void SomeMethod ( int someValue , List < int > someValues ) { Task generatedTask = null ; { int anotherValue = 2 ; object valuesRef = someValues ; generatedTask = new Task ( delegate { anotherValue += someValue + GetSum ( valuesRef ) ; Console.WriteLine ( anotherValue ) ; } ) ; } generatedTask.Start ( ) ; } | How local variables are handled when referenced in another scope ? |
C_sharp : Possible Duplicate : What is the C # Using block and why should I use it ? My question : Is using using ( a ) { do something with a } better than declaring ' a ' and using it that way . ie : more secure , faster , ... see examples for clarification.Example 1 : ( without using ) Example 2 : ( with using ) <code> StreamWriter sw ; string line ; sw = new StreamWriter ( `` D : \\NewCon.xml '' ) ; sw.WriteLine ( `` < ? xml version=\ '' 1.0\ '' encoding=\ '' UTF-8\ '' standalone=\ '' no\ '' ? > '' ) ; sw.WriteLine ( `` < config > '' ) ; for ( int i = 0 ; i > =36 ; i++ ) { line = `` '' ; line = `` < `` + xmlnodes [ i ] + `` > '' ; line += vals [ i ] ; line += `` < / '' + xmlnodes [ i ] + `` > '' ; sw.WriteLine ( line ) ; } sw.WriteLine ( `` < /config > '' ) ; sw.Close ( ) ; sw.Dispose ( ) ; string line ; using ( sw = new StreamWriter ( `` D : \\NewCon.xml '' ) ) { sw.WriteLine ( `` < ? xml version=\ '' 1.0\ '' encoding=\ '' UTF-8\ '' standalone=\ '' no\ '' ? > '' ) ; sw.WriteLine ( `` < config > '' ) ; for ( int i = 0 ; i > = 36 ; i++ ) { line = `` '' ; line = `` < `` + xmlnodes [ i ] + `` > '' ; line += vals [ i ] ; line += `` < / '' + xmlnodes [ i ] + `` > '' ; sw.WriteLine ( line ) ; } sw.WriteLine ( `` < /config > '' ) ; } | Is using using Better ? |
C_sharp : I 'm using an API call to return some XML data from a web server . The XML data is in the following format : I can retrieve the raw XML data successfully , and I want to add the < quoteText > and < quoteAuthor > node values to strings but seem to be unable to do this . My current code : My program bombs out with An unhandled exception of type 'System.NullReferenceException ' occurred while trying to set the string value quote . I 've looked at some similar posts and made various changes but ca n't seem to get the two string values set . <code> < forismatic > < quote > < quoteText > The time you think you 're missing , misses you too. < /quoteText > < quoteAuthor > Ymber Delecto < /quoteAuthor > < senderName > < /senderName > < senderLink > < /senderLink > < quoteLink > http : //forismatic.com/en/55ed9a13c0/ < /quoteLink > < /quote > < /forismatic > private void btnGetQuote_Click ( object sender , EventArgs e ) { WebRequest req = WebRequest.Create ( `` http : //api.forismatic.com/api/1.0/ '' ) ; req.Method = `` POST '' ; req.ContentType = `` application/x-www-form-urlencoded '' ; string reqString = `` method=getQuote & key=457653 & format=xml & lang=en '' ; byte [ ] reqData = Encoding.UTF8.GetBytes ( reqString ) ; req.ContentLength = reqData.Length ; using ( Stream reqStream = req.GetRequestStream ( ) ) reqStream.Write ( reqData , 0 , reqData.Length ) ; using ( WebResponse res = req.GetResponse ( ) ) using ( Stream resSteam = res.GetResponseStream ( ) ) using ( StreamReader sr = new StreamReader ( resSteam ) ) { string xmlData = sr.ReadToEnd ( ) ; txtXmlData.Text = xmlData ; Read ( xmlData ) ; } } private void Read ( string xmlData ) { XDocument doc = XDocument.Parse ( xmlData ) ; string quote = doc.Element ( `` quote '' ) .Attribute ( `` quoteText '' ) .Value ; string auth = doc.Element ( `` quote '' ) .Attribute ( `` quoteAuthor '' ) .Value ; txtQuoteResult.Text = `` QUOTE : `` + quote + `` \r\n '' + `` AUTHOR : `` + auth ; } | C # - Setting XML Node values as Stings from StreamReader result |
C_sharp : Can I simplify this statement with a lambda expression ? <code> var project = from a in accounts from ap in a.AccountProjects where ap.AccountProjectID == accountProjectId select ap ; | Lambda Expression |
C_sharp : Some programmers argue that it is better to pass IEnumerable < T > parameters over passing implementations like List < T > , and one of the popular reasons to do this is that the API is immediately usable in more scenarios because more collections will be compatible with IEnumerable < T > than any other specific implementation , e.g . List < T > .The more I dive into multi-threaded development scenarios , the more I am starting to think that IEnumerable < T > is not the correct type either and I will try to explain why below.Have you ever received the following exception while enumerating a collection ? Collection was modified ; enumeration operation may not execute . ( an InvalidOperationException ) Basically what causes this is , you are given the collection on one thread , while someone else modifies the collection on another thread.To circumvent the problem , I then developed a habit to take a snapshot of the collection before I enumerate it , by converting the collection to an array inside the method , like this : My question is this . Would n't it be better to code towards arrays instead of enumerables as a general rule , even if it means that callers are now forced to convert their collections to arrays when using your API ? Is this not cleaner and more bullet-proof ? ( the parameter type is an array instead ) The array meets all the requirements of being enumerable and of a fixed length , and the caller is aware of the fact that you will be operating on a snapshot of the collection at that point in time , which can save more bugs.The only better alternative I can find right now is the IReadOnlyCollection which will then be even more bullet proof because the collection is then also readonly in terms of item-content.EDIT : @ DanielPryden provided a link to a very nice article `` Arrays considered somewhat harmful '' . And the comments made by the writer `` I rarely need a collection which has the rather contradictory properties of being completely mutable , and at the same time , fixed in size '' and `` In almost every case , there is a better tool to use than an array . '' kind of convinced me that arrays are not as close to the silver bullet as I had hoped for , and I agree with the risks and loopholes . I think now the IReadOnlyCollection < T > interface is a better alternative than both the array and the IEnumerable < T > , but it kind of leaves me with the question now : Does the callee enforce it by having a IReadOnlyCollection < T > parameter type in the method declaration ? Or should the caller still be allowed to decide what implementation of IEnumerable < T > he passes into the method that looks at the collection ? Thanks for all the answers . I learned a lot from these responses . <code> static void LookAtCollection ( IEnumerable < int > collection ) { foreach ( int Value in collection.ToArray ( ) /* take a snapshot by converting to an array */ ) { Thread.Sleep ( ITEM_DELAY_MS ) ; } } static void LookAtCollection ( int [ ] collection ) { foreach ( int Value in collection ) { Thread.Sleep ( ITEM_DELAY_MS ) ; } } | Is T [ ] not better than IEnumerable < T > as parameter type ? ( Considering threading challenges ) |
C_sharp : I added 3 optional boolean parameters to a method found within a VB6 DLL . The class that houses it is MultiUse ( public ) , and the method itself is Private . The class implements a specific interface from a TLB , allowing for public calls to this method.After adding the 3 optional parameters on the VB6 side , I modified related C # code so that it specified the 3 optional parameters . It built fine ... however , when I try to run that code , it fails with the following error message : Method not found : 'Boolean MyTLBName.IMyClassName.MyMethod ( System.Object , System.String , Boolean , Boolean , Int32 , Int32 ByRef , System.Object , System.Object , System.Object , Boolean , Boolean , Boolean ) '.Notice how all 3 boolean parameters are shown in the error message ? Looks fine to me ... I know I specified those 3 booleans when calling the method from C # .Suspicious , I checked out the MyTLBName.IMyClassName interface in OLEView , and saw this : [ id ( 0x60030000 ) ] Again , the 3 optional parameters are visible , and look fine . Seems to me like it should work ... but maybe I 'm missing something . Is there any way I can get this working without having to create another version of `` MyMethod '' in the TLB ? ( With a different name , and those 3 parameters as required rather than optional ) <code> HRESULT MyMethod ( //Cut out the other parameters - they are working fine . [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMyFirstOptionalBoolean , [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMySecondOptionalBoolean , [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMyThirdOptionalBoolean , [ out , retval ] VARIANT_BOOL* __MIDL_0324 ) ; | Is it possible that C # has problems calling VB6 methods that have optional parameters ? |
C_sharp : I have a class that holds on to a delegate , in order to lazily evaluate something later.Once I 've evaluated it , by calling the delegate , I clear out the reference to the delegate , hoping that it would be eligible for collection . After all , it might hold on to a world of local variables if it was constructed as an anonymous method.I tried building a unit-test to verify this , but it does n't seem to work out the way I planned , instead it seems that either my assumptions about WeakReference ( which I used for test purposes here ) , or some other assumption , does n't hold water.Take a look at this code , which you can run in LINQPadI was assuming that : Regardless of DEBUG build , debugger attached , since I created the delegate in a separate method , which I return from , there should be nothing holding on to the delegate , except the WeakReference and the Lazy < T > objectsIf I ask the Lazy < T > object to relinquish its reference to the delegate , which would reduce the references to only the one that WeakReference is holding on toAnd then force a full garbage collection , assuming that if the only reference left is the one in WeakReferenceThen the delegate would be collected , and my WeakReference would indicate that the object is no longer aliveThe output of the code was thus expected to be ( with comments ) : But instead the output is : Can anyone shed some light on what I 'm missing here ? <code> void Main ( ) { WeakReference wr ; Lazy < int > l ; CreateTestData ( out wr , out l ) ; wr.IsAlive.Dump ( ) ; // should be alive here GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; wr.IsAlive.Dump ( ) ; // and alive here as well l.Value.Dump ( ) ; // but now we clear the reference GC.Collect ( ) ; // so one of these should collect it GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; wr.IsAlive.Dump ( ) ; // and then it should be gone here GC.KeepAlive ( l ) ; } void CreateTestData ( out WeakReference wr , out Lazy < int > l ) { Func < int > f = ( ) = > 10 ; wr = new WeakReference ( f ) ; l = new Lazy < int > ( f ) ; } public class Lazy < T > { private Func < T > _GetValue ; private T _Value ; public Lazy ( Func < T > getValue ) { _GetValue = getValue ; } public T Value { get { if ( _GetValue ! = null ) { _Value = _GetValue ( ) ; _GetValue = null ; } return _Value ; } } } true // not gc'ed after constructiontrue // not gc'ed after full GC , still beind held by Lazy < T > 10 // value from calling delegatefalse // but is now gc'ed , Lazy < T > no longer has a reference to it truetrue10true | GC of delegates , what am I missing ? ( my delegate is not collected ) |
C_sharp : It 's not unusual to want a limit on the interval between certain events , and take action if the limit is exceeded . For example , a heartbeat message between network peers for detecting that the other end is alive.In the C # async/await style , it is possible to implement that by replacing the timeout task each time the heartbeat arrives : This is convenient , but each instance of the delay Task owns a Timer , and if many heartbeat packets arrive in less time than the threshold , that 's a lot of Timer objects loading the threadpool . Also , the completion of each Timer will run code on the threadpool , whether there 's any continuation still linked to it or not.You ca n't free the old Timer by calling heartbeatLost.Dispose ( ) ; that 'll give an exception InvalidOperationException : A task may only be disposed if it is in a completion stateOne could create a CancellationTokenSource and use it to cancel the old delay task , but it seems suboptimal to create even more objects to accomplish this , when timers themselves have the feature of being reschedulable.What 's the best way to integrate timer rescheduling , so that the code could be structured more like this ? <code> var client = new TcpClient { ... } ; await client.ConnectAsync ( ... ) ; Task heartbeatLost = new Task.Delay ( HEARTBEAT_LOST_THRESHOLD ) ; while ( ... ) { Task < int > readTask = client.ReadAsync ( buffer , 0 , buffer.Length ) ; Task first = await Task.WhenAny ( heartbeatLost , readTask ) ; if ( first == readTask ) { if ( ProcessData ( buffer , 0 , readTask.Result ) .HeartbeatFound ) { heartbeatLost = new Task.Delay ( HEARTBEAT_LOST_THRESHOLD ) ; } } else if ( first == heartbeatLost ) { TellUserPeerIsDown ( ) ; break ; } } var client = new TcpClient { ... } ; await client.ConnectAsync ( ... ) ; var idleTimeout = new TaskDelayedCompletionSource ( HEARTBEAT_LOST_THRESHOLD ) ; Task heartbeatLost = idleTimeout.Task ; while ( ... ) { Task < int > readTask = client.ReadAsync ( buffer , 0 , buffer.Length ) ; Task first = await Task.WhenAny ( heartbeatLost , readTask ) ; if ( first == readTask ) { if ( ProcessData ( buffer , 0 , readTask.Result ) .HeartbeatFound ) { idleTimeout.ResetDelay ( HEARTBEAT_LOST_THRESHOLD ) ; } } else if ( first == heartbeatLost ) { TellUserPeerIsDown ( ) ; break ; } } | Task-based idle detection |
C_sharp : I have a solution of three projects : CoreOutlook Add-InASP.NET WebsiteBoth , the Outlook Add-In and the Website use the same methods from Core project to get data from SQL Server . When I write my data into database , I convert all DateTime values of two tables into UTC time : andWhen I get the data in my Outlook Add-In , this is the correct result : When opening the same in my website , the picks are fine : But my start and end time are `` broken '' - the offset is added , bute the wrong hours are used : Here 's the code for my converting , that both , Outlook and the website , use : And the implementation of DateTime.FromUtc ( ) : I had the same result with DateTime.ToLocalTime ( ) .Anyone an idea ? EDIT 1 : This is how the start and end gets displayed on the website ( end with End instead of Start ) : And the picks : ao.RealAnswer returns the formated DateTime string : <code> POLL_START POLL_END2013-07-31 12:00:00.000 2013-08-01 12:00:00.000 PICK_DATE2013-07-31 12:00:48.0002013-07-31 13:00:12.000 private static void ConvertToLocalTime ( POLL item ) { item.POLL_START = item.POLL_START.FromUTC ( ) ; item.POLL_END = item.POLL_END.FromUTC ( ) ; } private static void ConvertToLocalTime ( PICK pick ) { if ( pick.PICK_DATE ! = null ) pick.PICK_DATE = ( ( DateTime ) pick.PICK_DATE ) .FromUTC ( ) ; } public static DateTime FromUTC ( this DateTime value ) { var local = TimeZoneInfo.Local ; return TimeZoneInfo.ConvertTime ( value , TimeZoneInfo.Utc , local ) ; } var startCell = new TableCell { Text = String.Format ( @ '' < a href= ' { 0 } ' title= ' { 2 } ' target='_blank ' > { 1 : dd.MM.yyyy HH : mm \U\T\Czzz } < /a > '' , Common.GetTimeAndDateHyperlink ( _poll.Start , `` Vote Start '' ) , _poll.Start , ConvertToLocalTimeZone ) , CssClass = `` InfoContent '' } ; answerCell = new TableCell { Text = String.Format ( @ '' < a href= ' { 0 } ' title= ' { 2 } ' target='_blank ' > { 1 } < /a > '' , Common.GetTimeAndDateHyperlink ( ao.Time , ao.RealAnswer ) , ao.RealAnswer , ConvertToLocalTimeZone ) } ; return String.Format ( WholeTime == true ? `` { 0 : d } '' : @ '' { 0 : dd.MM.yyyy HH : mm \U\T\Czzz } '' , Time ) ; | Converting UTC to local time returns strange result |
C_sharp : How to intentionally crash an application with an AccessViolationException in c # ? I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions . Because of that , I need to intentionally throw an AccessViolationException to test how it behaves under certain circumstances.Besides that , it must be specifically an AccessViolationException because this exception is not handled by the catch blocks.Surprisingly , this does not work : Neither this : <code> public static void Crash ( ) { throw new AccessViolationException ( ) ; } public static unsafe void Crash ( ) { for ( int i = 1 ; true ; i++ ) { var ptr = ( int* ) i ; int value = *ptr ; } } | How to make C # application crash with an AccessViolationException |
C_sharp : I am working with two C # stream APIs , one of which is a data source and the other of which is a data sink.Neither API actually exposes a stream object ; both expect you to pass a stream into them and they handle writing/reading from the stream.Is there a way to link these APIs together such that the output of the source is streamed into the sink without having to buffer the entire source in a MemoryStream ? This is a very RAM-sensitive application.Here 's an example that uses the MemoryStream approach that I 'm trying to avoid , since it buffers the entire stream in RAM before writing it out to S3 : <code> using ( var buffer = new MemoryStream ( ) ) using ( var transferUtil = new TransferUtility ( s3client ) ) { // This destructor finishes the file and transferUtil closes // the stream , so we need this weird using nesting to keep everyone happy . using ( var parquetWriter = new ParquetWriter ( schema , buffer ) ) using ( var rowGroupWriter = parquetWriter.CreateRowGroup ( ) ) { rowGroupWriter.WriteColumn ( ... ) ; ... } transferUtil.Upload ( buffer , _bucketName , _key.Replace ( `` .gz '' , `` '' ) + `` .parquet '' ) ; } | How to link two C # APIs that expect you to provide a stream ? |
C_sharp : I have 1 line with 2 known points : I 'd like to iterate through 10 pixels to the left ( or right ) to 1 line ( at x1 , y1 ) .The red dots are the ones that I 'd like process . Example : How do I iterate through these coords ? <code> PointF p2_1 = new PointF ( ) ; p2_1.X = 100 ; // x1p2_1.Y = 150 ; // y1PointF p2_2 = new PointF ( ) ; p2_2.X = 800 ; // x2p2_2.Y = 500 ; // y2float dx = p2_2.X - p2_1.X ; float dy = p2_2.Y- p2_1.Y ; float slope = dy / dx ; // slope mfloat intercept = p2_1.Y - slope * p2_1.X ; // intercept c // y = mx + c for ( int i = 10 ; i > 0 ; i -- ) { // start with distant coordinates PointF new_point = new Point ( ) ; // ( grab x , y , coords accordingly ) // repeat until I 'm at ( x1 , y1 ) } | Iterate through N points that are perpendicular to another line |
C_sharp : I have a method that I want to be `` transactional '' in the abstract sense . It calls two methods that happen to do stuff with the database , but this method does n't know that.Because in real terms the TransactionScope means that a database transaction will be used , we have an issue where it could well be promoted to a Distributed Transaction , if we get two different connections from the pool.I could fix this by wrapping the DoOperation ( ) method in a ConnectionScope : I made DbConnectionScope myself for just such a purpose , so that I do n't have to pass connection objects to sub-methods ( this is more contrived example than my real issue ) . I got the idea from this article : http : //msdn.microsoft.com/en-us/magazine/cc300805.aspxHowever I do n't like this workaround as it means DoOperation now has knowledge that the methods it 's calling may use a connection ( and possibly a different connection each ) . How could I refactor this to resolve the issue ? One idea I 'm thinking of is creating a more general OperationScope , so that when teamed up with a custom Castle Windsor lifestyle I 'll write , will mean any component requested of the container with OperationScopeLifetyle will always get the same instance of that component . This does solve the problem because OperationScope is more ambiguous than DbConnectionScope . <code> public void DoOperation ( ) { using ( var tx = new TransactionScope ( ) ) { Method1 ( ) ; Method2 ( ) ; tc.Complete ( ) ; } } public void Method1 ( ) { using ( var connection = new DbConnectionScope ( ) ) { // Write some data here } } public void Method2 ( ) { using ( var connection = new DbConnectionScope ( ) ) { // Update some data here } } public void DoOperation ( ) { using ( var tx = new TransactionScope ( ) ) using ( var connection = new DbConnectionScope ( ) ) { Method1 ( ) ; Method2 ( ) ; tc.Complete ( ) ; } } | Method knows too much about methods it 's calling |
C_sharp : I have been asked at interview ( C # 3.0 ) to provide a logic to remove a list of items from a list.I responded1 ) The interviewer replied that the algorithm i had employed will gradually take time if the items grow and asked me to give even better and faster one.What would be the efficient algorithm ? 2 ) How can i achieve the same using LINQ ? 3 ) He asked me to provide an example for Two-Way-Closure ? ( General I am aware of closure , what is Two-Way-Closure ? , I replied there is no such term exists , but he did notsatisfy ) . <code> int [ ] items= { 1,2,3,4 } ; List < int > newList = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 , 56 , 788 , 9 } ; newList.RemoveAll ( ( int i ) = > { return items.Contains ( i ) ; } ) ; | C # Improved algorithm |
C_sharp : I 'm working with some generics in C # . I have an abstract generic class : and the type parameter is specified when other classes inherit from the base class.I 'm also trying to write some code for another abstract class that needs to store one of these base classes , but it wo n't know the parameter of the base class ( and it does n't need to know ) . In Java I could simple write : But in C # it insists I give it a type parameter . If I declare it as : I can not assign any parametrized values of BaseClass to it.Is there a work around to achieve the effect of BaseClass < ? > in C # ? Obviously there are ways to restructure my code to avoid the need , such as parameterizing all of the classes that use BaseClass as well , but this would be less than ideal . Any help would be appreciated ! <code> public abstract class BaseClass < T > where T : Foo { } protected BaseClass < ? > myBaseClass ; protected BaseClass < Foo > myBaseClass ; | C # Equivalent of Java 's GenericType < ? > |
C_sharp : I 've just installed the .NET 4.5 reference source from Microsoft as I 'm trying to debug an issue I 'm seeing and I stumbled across the following in HttpApplication.cs.Notice the next-to-last line private bool _ [ ... . ] ; // per call.Is _ [ ... . ] a valid identifier ( at any level of compilation , including IL ) or has the source been changed since compilation ? <code> // execution step -- call asynchronous eventinternal class AsyncEventExecutionStep : IExecutionStep { private HttpApplication _application ; private BeginEventHandler _beginHandler ; private EndEventHandler _endHandler ; private Object _state ; private AsyncCallback _completionCallback ; private AsyncStepCompletionInfo _asyncStepCompletionInfo ; // per call private bool _ [ ... . ] ; // per call private string _targetTypeStr ; | Is ` _ [ ... . ] ` a valid identifier ? |
C_sharp : I am planning to use Auto reset Event Handle for Inter Thread communication.My producer thread code look like below In the consumer thread , I have to download data for every one minute or when producer is called Set methodMy question is if consumer thread is running doSomething function and producer calls set function , what would be state of Auto reset event object ? My requirement is as soon as producer calls set method I have to download fresh data from the Internet . If doSomething function is running , when Producer calls set method , I have to interrupt it and call again . <code> EventWaitHandle handle = new EventWaitHandle ( false , EventResetMode.AutoReset ) ; produceSomething ( ) ; handle.Set ( ) ; try { while ( true ) { handle.WaitOne ( 60000 , false ) ; doSomething ( ) ; // Downloads data from Internet . // Takes lot of time to complete it . } } catch ( ThreadAbortException ) { cleanup ( ) ; } | .NET Thread Synchronization |
C_sharp : If I look at the IL that is created in Linqpad for the two following code snippets , I wonder what happens here.In c # results in the following IL codewhereas in VBit isApparently , the c # compiler understands the the value is never used and thus simply returns nothing . In VB.NET the actual code is translated.Is that due to differences in compiler optimization or is there anything else at work ? Update : Just to clarify this - I just enter this one line into LinqPad and look at the IL it creates ( most definitely by running the respective compiler ) . There is no program . <code> int i = 42 ; IL_0000 : ret Dim i As Integer = 42 IL_0000 : ldc.i4.s 2A IL_0002 : stloc.0 | Is the c # compiler smarter than the VB.NET compiler ? |
C_sharp : I am beginner with programming in c # and i am just doing a pingpong game . I am using threads - one for collision , one for move , one for painting.My question is why the program run faster , when i open steam : D to me it seems like a nonsense.Witch slower i mean - ball is slower and the pads too . It looks like the processor is lazy to do the work or something like that . It is happening in real time - i open the game , it is slow , i open steam , it is faster and then i close steam and it is slow again . My first thought was that it is because dual graphics card but making it to use nvidia card don´t help.Another situation : i open game - slow , open skype - game is faster , skype is loaded - game is slow , closing skype - game is fast , closed skype - game is slow..How to make the game to use processor always same ? my code i move method is Here is some more code about collision with borders and score counting ... and it and with waitevent.I guess it is because the automatic overclocking of the processor but i am a newbie.. : DHere is the whole thing in one thread <code> public void move ( ) { DelegateSetScore d = new DelegateSetScore ( SetScore ) ; while ( ! isDisposing ) { pad1.Y = pad1.Y + 4 * pad1Down + 4 * pad1Up ; if ( pad1.Y < 0 ) { pad1.Y = 0 ; } if ( pad1.Y + pad1.Height > HEIGHT ) { pad1.Y = HEIGHT - pad1.Height ; } pad2.Y = pad2.Y + 4 * pad2Down + 4 * pad2Up ; if ( pad2.Y < 0 ) { pad2.Y = 0 ; } if ( pad2.Y + pad2.Height > HEIGHT ) { pad2.Y = HEIGHT - pad2.Height ; } ball.X = ball.X + 6 * ballXDirection ; ball.Y = ball.Y + 2 * ballYDirection ; waitevent.WaitOne ( 5 ) ; public void bigthread ( ) { DelegateSetScore d = new DelegateSetScore ( SetScore ) ; while ( ! isDisposing ) { //move pad1.Y = pad1.Y + 4 * pad1Down + 4 * pad1Up ; if ( pad1.Y < 0 ) { pad1.Y = 0 ; } if ( pad1.Y + pad1.Height > HEIGHT ) { pad1.Y = HEIGHT - pad1.Height ; } pad2.Y = pad2.Y + 4 * pad2Down + 4 * pad2Up ; if ( pad2.Y < 0 ) { pad2.Y = 0 ; } if ( pad2.Y + pad2.Height > HEIGHT ) { pad2.Y = HEIGHT - pad2.Height ; } ball.X = ball.X + 6 * ballXDirection ; ball.Y = ball.Y + 2 * ballYDirection ; if ( ball.X < 0 ) { ballXDirection = 1 ; intScorePlayer2++ ; this.BeginInvoke ( d , intScorePlayer2 , 2 ) ; } if ( ball.X + ball.Width > WIDTH ) { ballXDirection = -1 ; intScorePlayer1++ ; this.BeginInvoke ( d , intScorePlayer1 , 1 ) ; } if ( ball.Y < 0 ) { ballYDirection = 1 ; } if ( ball.Y + ball.Height > HEIGHT ) { ballYDirection = -1 ; } //collision if ( ( pad1.X + pad1.Width > ball.X ) & & ( ball.X + ball.Width > pad1.X ) ) if ( ( pad1.Y + pad1.Height > ball.Y ) & & ( ball.Y + ball.Height > pad1.Y ) ) { ballXDirection = 1 ; if ( pad1Down == 1 ) { ballYDirection = 1 ; } if ( pad1Up == -1 ) { ballYDirection = -1 ; } } if ( ( pad2.X + pad2.Width > ball.X ) & & ( ball.X + ball.Width > pad2.X ) ) if ( ( pad2.Y + pad2.Height > ball.Y ) & & ( ball.Y + ball.Height > pad2.Y ) ) { ballXDirection = -1 ; if ( pad2Down == 1 ) { ballYDirection = 1 ; } if ( pad2Up == -1 ) { ballYDirection = -1 ; } } //paint - platno is graphics from picturebox Platno.Clear ( Color.Black ) ; Platno.FillRectangle ( Brushes.Orange , pad1 ) ; Platno.FillRectangle ( Brushes.Orange , pad2 ) ; Platno.FillRectangle ( Brushes.Green , ball ) ; waitevent.WaitOne ( 10 ) ; } } | pingpong game run faster when i open STEAM - why ? |
C_sharp : I have the following code : The following statements works fine and the program compile despite i did n't implement the interface : So my first question is : Why did it work ? Then , i add the following interface implementation to Calculator class : When trying again the following statement : The method overriden from the abstract still called.So my second question is : Why did the program call the method from the abstract class and not the method from the interface ? <code> interface ICalculator { int Sum ( int x , int y ) ; } abstract class AbsCalculator { public abstract int Sum ( int x , int y ) ; } class Calculator : AbsCalculator , ICalculator { public override int Sum ( int x , int y ) { Console.WriteLine ( `` From overriden method '' ) ; return x + y ; } } Calculator calculator = new Calculator ( ) ; Console.WriteLine ( calculator.Sum ( 10 , 20 ) ) ; int ICalculator.Sum ( int x , int y ) { Console.WriteLine ( `` From implemented method '' ) ; return x + y ; } Calculator calculator = new Calculator ( ) ; Console.WriteLine ( calculator.Sum ( 10 , 20 ) ) ; | Code work despite the interface is not implemented |
C_sharp : I tried the following code to enable some kind of not null checking for retrieved entities to ensure they are exist before doing some concrete business : But in compile time I 'm getting : After contract block , found use of local variable 'obj ' defined in contract blockAm I using Contract.Requires in the wrong way ? <code> protected T GetRequired < T > ( object id ) where T : EntityObject { var obj = Get < T > ( id ) ; Contract.Requires < ArgumentNullException > ( obj ! = null ) ; return obj ; } | CodeContracts `` Required '' understanding |
C_sharp : I 'm reading a book about C # for beginners and I 'm at the part `` Understanding Values and References '' , but there is something I do n't understand . What I 'm seeing is that the books tries to explain this to me ( and I 've seen this happening in a couple of tutorial video 's on Youtube as well ) that the class is being used to create ... .an object ( ? ? ) of the class . I have read the whole previous chapter where that happened too and I did n't quite understand it , assuming that it would become more clear in the following chapter . It did not become more clear , so I do n't think it 's a good idea to continue until I understand the concept of the stuff I explained before.The following part is part of the book : Remember that to initialize a reference variable such as a class , you can create a new instance of the class and assign the reference variable to the new object , like this : What could I do with the code in this example and why is it handy ? Examples + explanation would be more than welcome . Thanks in advance ! <code> Circle c = new Circle ( 42 ) ; Circle copy = new Circle ( 99 ) ; //Circle refc = c ; ... copy = c ; | Point of initializing a class ? |
C_sharp : I have created a custom Attribute to decorate a number of classes that I want to query for at runtime : Each of these classes derive from an abstract base class : Do I need to put this attribute on each derived class , even if I add it to the base class ? The attribute is marked as inheritable , but when I do the query , I only see the base class and not the derived classes.From another thread : Thanks , wTs <code> [ AttributeUsage ( AttributeTargets.Class , AllowMultiple=false , Inherited=true ) ] public class ExampleAttribute : Attribute { public ExampleAttribute ( string name ) { this.Name = name ; } public string Name { get ; private set ; } } [ Example ( `` BaseExample '' ) ] public abstract class ExampleContentControl : UserControl { // class contents here } public class DerivedControl : ExampleContentControl { // class contents here } var typesWithMyAttribute = from a in AppDomain.CurrentDomain.GetAssemblies ( ) from t in a.GetTypes ( ) let attributes = t.GetCustomAttributes ( typeof ( ExampleAttribute ) , true ) where attributes ! = null & & attributes.Length > 0 select new { Type = t , Attributes = attributes.Cast < ExampleAttribute > ( ) } ; | Attribute Inheritance and Reflection |
C_sharp : What does a syntax like this mean in C # ? <code> public abstract class HostFactory < TApp > : ServiceHostFactory where TApp : IFoo | What does a syntax like this mean in C # ? |
C_sharp : I am facing some problems using GalaSoft 's RelayCommand.I have a NextCommand property that works , but only several times.Afterwards , it stops working completely . You can try this out with the sample project : http : //s000.tinyupload.com/ ? file_id=65828891881629261404The behaviour is as follows : NextCommand : pops all items until the active indexif there are less than 50 items left , pushes 1 new itemmarks new item as activeBackCommand : moves the active index back by 1 positionSteps to replicate : the '+ ' ( OemPlus ) key has been bound to NextCommandthe '- ' ( OemMinus ) key has been bound to BackCommandHold the '+ ' key until the list stops growing ( 50 items limit ) Hold the '- ' key until the first item in the list is the activeRepeatThe number of repetitions needed ( to replicate the bug ) is inconsistent.Sometimes I get it after 4 repetitions ; other times up till 9.When I stepped into the RelayCommand 's code , the execute action 's isAlive flag was false . But I ca n't seem to figure out how that might happen . <code> // Items Collectionpublic class ItemCollection : ViewModelBase { // List of Items private readonly ObservableCollection < Item > _items = new ObservableCollection < Item > ( ) ; public ObservableCollection < Item > Items { get { return _items ; } } // Constructor public ItemCollection ( ) { BackCommand = new RelayCommand ( ( ) = > { // Go to previous page var index = Items.IndexOf ( ActiveItem ) ; if ( index > 0 ) { ActiveItem = Items [ index - 1 ] ; } } , ( ) = > ActiveItem ! = null & & Items.IndexOf ( ActiveItem ) > 0 ) ; } // Back command public RelayCommand BackCommand { get ; set ; } // Next command public RelayCommand NextCommand { get ; set ; } // The currently-active item private Item _activeItem ; public Item ActiveItem { get { return _activeItem ; } set { Set ( ( ) = > ActiveItem , ref _activeItem , value ) ; } } } // Itempublic class Item : ViewModelBase { public string Title { get ; set ; } } | RelayCommand stops working after a while |
C_sharp : I am developing a portable class library in C # and I want to bit convert a double to a long . The most straightforward solution to this issue would be to use the BitConverter.DoubleToInt64Bits method , but unfortunately this method is not available in the Portable Library subset of the .NET class library.As an alternative I have come up with the following `` two-pass '' bit conversion : My tests show that this expression consistently produces the same result as DoubleToInt64Bits . However , my benchmark tests also show that this alternative formulation is approximately four times slower than DoubleToInt64Bits when implemented in a full .NET Framework application.Using only the Portable Library subset , is it possible to implement a replacement of DoubleToInt64Bits that is quicker than my formulation above ? <code> var result = BitConverter.ToInt64 ( BitConverter.GetBytes ( x ) , 0 ) ; | .NET Portable library missing BitConverter.DoubleToInt64Bits , replacement very slow |
C_sharp : I am using the Roslyn feature of generating version number from current date/time.I can see the auto generated date/time based version number gets stamped correctly as AssemblyVersion , and I can read it at runtime using API . Question : How do I get the same auto generated date time based version number stamped as file version , such that i can right click on the assembly in windows explorer and see the `` File Version '' under Details tabI see when i explicitly tag the version number ( say 1.2.3.4 ) it works fine , but not with the auto generated oneI am not using AssemblyInfo.cs and would like attributes set in .csprojI am using dotnet cli to build using below csproj for example : <code> < Project Sdk= '' Microsoft.NET.Sdk.WindowsDesktop '' > < PropertyGroup > < OutputType > WinExe < /OutputType > < TargetFramework > netcoreapp3.1 < /TargetFramework > < UseWindowsForms > true < /UseWindowsForms > < AssemblyVersion > 1.0 . * < /AssemblyVersion > < FileVersion > 1.0 . * < /FileVersion > < Deterministic > false < /Deterministic > < PackageId > Demo < /PackageId > < Company > My Company < /Company > < Copyright > Copyright © Xyzzy 2020 < /Copyright > < Description > Description < /Description > < GeneratePackageOnBuild > true < /GeneratePackageOnBuild > < GenerateAssemblyInfo > true < /GenerateAssemblyInfo > < GenerateAssemblyFileVersionAttribute > true < /GenerateAssemblyFileVersionAttribute > < GenerateAssemblyTitleAttribute > true < /GenerateAssemblyTitleAttribute > < GenerateAssemblyConfigurationAttribute > true < /GenerateAssemblyConfigurationAttribute > < GenerateAssemblyCompanyAttribute > true < /GenerateAssemblyCompanyAttribute > < GenerateAssemblyProductAttribute > true < /GenerateAssemblyProductAttribute > < GenerateAssemblyCopyrightAttribute > true < /GenerateAssemblyCopyrightAttribute > < GenerateAssemblyVersionAttribute > true < /GenerateAssemblyVersionAttribute > < GenerateAssemblyInformationalVersionAttribute > true < /GenerateAssemblyInformationalVersionAttribute > < /PropertyGroup > < /Project > | How do I get AssemblyVersion stamped as FileVersion on the binary |
C_sharp : Let 's say I have 3 DLLs ( BlueCar , RedCar , YellowCar ) that each have a named class ( BlueCarClass , etc ) that also all implement the same interface , Car , and are all built from the same namespace ( Car_Choices ) . So a DLL looks something like this before compiled : And the DLL 's name would be `` BlueCar.dll '' .In the main program , the user selects which ever car color they want , and based on their choice it dynamically loads only the appropriate DLL and runs What_Color ( ) . The main program has a copy of the Car interface . Right now I have the following , but it 's not working.I 've also triedAny help ? Are there structural changes I need to make ( such as putting each car color DLL in it 's own namespace ) ? Or am I not understanding how to load and use classes from DLLs appropriately.EDIT : Here 's the solution that I got to work , in case anyone is looking for a more detailed answer.PROJECT 1 : The shared interface ( as a Class library ) Car_Interface.csCompile into Car_Interface.dll , reference DLL in next 2 projects.PROJECT 2 : Car interface implementation , as a class libraryBlueCar.csCompile into BlueCar_PlugIn.dllPROJECT 3 : Main program/driverProgram.csNow if you move both DLLs into bin ( or where ever your program is compiled to ) and run it , it 'll be able to dynamically load BlueCar_PlugIn.dll but not neccessarily need it to run ( ex , if you have YellowCar_PlugIn.dll and also RedCar_PlugIn.dll with similar implementations , only one will need to be loaded for the program to work ) . <code> namespace Car_Choices { public interface Car { void What_Color ( ) ; } public class BlueCarClass : Car { public void What_Color ( ) { MessageBox.Show ( 'The color is blue . ' ) ; } } } static void Main ( ) { string car_choice = win_form_list.ToArray ( ) [ 0 ] ; //gets choice from a drop down Assembly car_assembly = Assembly.Load ( car_choice ) ; //car_choice is BlueCar Type car_type = car_assembly.GetType ( `` Car '' ) ; Car car = Activator.CreateInstance ( type ) as Car ; car.What_Color ( ) ; } static void Main ( ) { string car_choice = win_form_list.ToArray ( ) [ 0 ] ; //gets choice from a drop down ObjectHandle car_handle = Activator.CreateInstance ( assembly_name , `` Car_Choices . `` + car_choice ) ; Car car= ( Car ) handle.Unwrap ( ) ; car.What_Color ( ) ; } namespace Car_Interface { public interface ICar_Interface { char Start_Car ( ) ; } } namespace BlueCar_PlugIn { public class BlueCar : Car_Interface.ICar_Interface { public char Start_Car ( ) { MessageBox.Show ( `` Car is started '' ) ; } } } namespace Main_Program { public class Program { static void Main ( ) { Assembly assembly = Assembly.Load ( DLL_name ) ; //Where DLL_name is the DLL you want to load , such as BlueCar_PlugIn.dll Type type = ( Type ) assembly.GetTypes ( ) .GetValue ( 0 ) ; //Class that implements the interface should be first . A resource type could also possibly be found //OR Type type = ( Type ) assembly.GetType ( DLL_name + class_name ) ; //In this case , BlueCar_PlugIn.BlueCar Car_Interface.ICar_Interface new_car = ( Car_Interface.ICar_Interface ) Activator.CreateInstance ( type ) ; new_car.Start_Car ( ) ; } } } | How to dynamically load a DLL and use a class in it ( that implements a known interface ) [ C # ] |
C_sharp : I have the following entitiesWhat I 'm trying to do is to get Active Auctions with Auctions loaded and Auction also have Departments loadedI know that I should write Include for every object to be loaded so the generated SQL by EF will have join statement to select there object for mebut this is the existing code I do n't know How but this code works and the returned ActiveAuctions include all desired objectsI checked for SQL executed against the database and as expected it generate to separate queries.I want an explanation to understand how the returned ActiveAcutions loaded with the other mentioned entities ! ! ? <code> //Active Auction Entitypublic class ActiveAuction { public int Id { get ; set ; } public string Title { get ; set ; } public int ? FirstAuctionId { get ; set ; } public int ? SecondAuctionId { get ; set ; } public int ? ThirdAuctionId { get ; set ; } public virtual Auction FirstAuction { get ; set ; } public virtual Auction SecondAuction { get ; set ; } public virtual Auction ThirdAuction { get ; set ; } } // Auction Entitypublic class Auction { public int AuctionId { get ; set ; } public AuctionStatus AuctionStatus { get ; set ; } public int ? DepartmentId { get ; set ; } public virtual Department Department { get ; set ; } } // Department Entitypublic class Department { public int DepartmentId { get ; set ; } public string DepartmentName { get ; set ; } public int ? AdminId { get ; set ; } public virtual Admin Admin { get ; set ; } } using ( var dc = DataContext ( ) ) { await dc.Auction .Include ( `` Department.Admin '' ) .Where ( i = > i.Id == id & & i.AuctionStatus == AuctionStatus.Accepted ) .ToListAsync ( ) ; return await dc.ActiveAuction . SingleOrDefaultAsync ( i = > i.Id == id ) ; } | Entity-Framework Join Explanation |
C_sharp : I have this code which gets the value from the Test class and then converts it to the type it is . It prints correctly as `` Int32 '' but when I test the equality with another variable with the same value , it prints `` false '' . I suspect it is because it is testing reference equality and that the 2 variables are really still objects.Is there any way to compare them , keeping in mind I wo n't know the type of the value returned until runtime ( it could be a string , float , other class , etc . ) ? <code> class Test { public int y ; } static void Main ( ) { var test1 = new Test { y=1 } ; var test2 = new Test { y=1 } ; var fields = test1.GetType ( ) .GetFields ( ) ; var test1Value = fields [ 0 ] .GetValue ( test1 ) ; var test2Value = fields [ 0 ] .GetValue ( test2 ) ; var test1Converted = Convert.ChangeType ( test1Value , test1Value.GetType ( ) ) ; var test2Converted = Convert.ChangeType ( test2Value , test2Value.GetType ( ) ) ; Console.WriteLine ( test1Converted ) ; // prints Int32 Console.WriteLine ( test1Converted == test2Converted ) ; // prints false } | How can I compare value-types acquired from Reflection 's `` GetValue '' ? |
C_sharp : I need to implement SO like functionality on my asp.net MVC site.For example when user go to https : //stackoverflow.com/questions/xxxxxxxxafter loading the subject line is concatenated with the url and url becomes like this https : //stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship Above `` /rails-sql-search-through-has-one-relationship `` part is added to the url.In webforms it 's simple , I could just use url rewriting . But not sure how to accomplish this in MVCThe following line is from Global.asax filethe string that I need to concatenate is in my database so it fetches from there . How can I accomplish this ? <code> routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // URL with parameters new { controller = `` Account '' , action = `` LogOn '' , id = UrlParameter.Optional } // Parameter defaults ) ; | how to implement url rewriting similar to SO |
C_sharp : From what I understand , records are actually classes that implement their own equality check in a way that your object is value-driven and not reference driven.In short , for the record Foo that is implemented like so : var foo = new Foo { Value = `` foo '' } and var bar = new Foo { Value = `` foo '' } , the foo == bar expression will result in True , even though they have a different reference ( ReferenceEquals ( foo , bar ) // False ) .Now with records , even though that in the article posted in .Net Blog , it says : If you don ’ t like the default field-by-field comparison behavior ofthe generated Equals override , you can write your own instead.When I tried to place public override bool Equals , or public override int GetHashCode , or public static bool operator == , and etc . I was getting Member with the same signature is already declared error , so I think that it is a restricted behaviour , which is n't the case with struct objects.Failing example : Compiler result : My main question here is what if we want to customise the way the equality checker works ? I mean , I do understand that this beats the whole purpose of records , but on the other hand , equality checker is not the only feature that makes records cool to use.One use case where someone would like to override the equality of records is because you could have an attribute that would exclude a property from equality check . Take for example this ValueObject implementation.Then if you extend this ValueObject abstract class like so : then you would get the following results : So far , in order to achieve somehow the above use case , I have implemented an abstract record object and utilise it like so : and the results look like this : To conclude , I 'm a bit puzzled , is restricting the override of equality methods of record objects an expected behaviour or is it because it is still in preview stage ? If it is by design , would you implement the above behaviour in a different ( better ) way or you would just continue using classes ? dotnet -- version output : 5.0.100-rc.1.20452.10 <code> public sealed record SimpleVo : IEquatable < SimpleVo > { public bool Equals ( SimpleVo other ) = > throw new System.NotImplementedException ( ) ; public override bool Equals ( object obj ) = > obj is SimpleVo other & & Equals ( other ) ; public override int GetHashCode ( ) = > throw new System.NotImplementedException ( ) ; public static bool operator == ( SimpleVo left , SimpleVo right ) = > left.Equals ( right ) ; public static bool operator ! = ( SimpleVo left , SimpleVo right ) = > ! left.Equals ( right ) ; } SimpleVo.cs ( 11,30 ) : error CS0111 : Type 'SimpleVo ' already defines a member called 'Equals ' with the same parameter typesSimpleVo.cs ( 17,37 ) : error CS0111 : Type 'SimpleVo ' already defines a member called 'op_Equality ' with the same parameter typesSimpleVo.cs ( 20,37 ) : error CS0111 : Type 'SimpleVo ' already defines a member called 'op_Inequality ' with the same parameter types public sealed class FullNameVo : ValueObject { public FullNameVo ( string name , string surname ) { Name = name ; Surname = surname ; } [ IgnoreMember ] public string Name { get ; } public string Surname { get ; } [ IgnoreMember ] public string FullName = > $ '' { Name } { Surname } '' ; } var user1 = new FullNameVo ( `` John '' , `` Doe '' ) ; var user2 = new FullNameVo ( `` John '' , `` Doe '' ) ; var user3 = new FullNameVo ( `` Jane '' , `` Doe '' ) ; Console.WriteLine ( user1 == user2 ) ; // TrueConsole.WriteLine ( ReferenceEquals ( user1 , user2 ) ) ; // FalseConsole.WriteLine ( user1 == user3 ) ; // TrueConsole.WriteLine ( user1.Equals ( user3 ) ) ; // True public sealed record FullNameVo : ValueObject { [ IgnoreMember ] public string Name ; public string Surname ; [ IgnoreMember ] public string FullName = > $ '' { Name } { Surname } '' ; } var user1 = new FullNameVo { Name = `` John '' , Surname = `` Doe '' } ; var user2 = new FullNameVo { Name = `` John '' , Surname = `` Doe '' } ; var user3 = user1 with { Name = `` Jane '' } ; Console.WriteLine ( user1 == user2 ) ; // TrueConsole.WriteLine ( ReferenceEquals ( user1 , user2 ) ) ; // FalseConsole.WriteLine ( user1 == user3 ) ; // FalseConsole.WriteLine ( user1.Equals ( user3 ) ) ; // FalseConsole.WriteLine ( ValueObject.EqualityComparer.Equals ( user1 , user3 ) ) ; // True | Custom Equality check for C # 9 records |
C_sharp : I tried to use C # DI method to implement something . following is my code snippet.and code that creates a ServiceLocator : now , I create a test code with but , it looks like , I always get null returned by GetService ( ) function . Instead I expect to get EmailService object via GetService ( ) function , so how to do it correctly ? <code> public interface IMessageService { void Send ( string uid , string password ) ; } public class MessageService : IMessageService { public void Send ( string uid , string password ) { } } public class EmailService : IMessageService { public void Send ( string uid , string password ) { } } public static class ServiceLocator { public static object GetService ( Type requestedType ) { if ( requestedType is IMessageService ) { return new EmailService ( ) ; } else { return null ; } } } public class AuthenticationService { private IMessageService msgService ; public AuthenticationService ( ) { this.msgService = ServiceLocator .GetService ( typeof ( IMessageService ) ) as IMessageService ; } } | Regarding to Type in C # |
C_sharp : As stated here , the PropertyChangedEventManager class Provides a WeakEventManager implementation so that you can use the `` weak event listener '' pattern to attach listeners for the PropertyChanged event.There are two ways to subscribe for property changes : They both end up calling the same method : with either listener or handler set to null.I need to change some code with strong event handlers ( i.e . source.PropertyChange += handler ; ) to follow the weak pattern . This is trivial using the AddHandler method . Are there any reasons to prefer AddListener ( which requires me to implement IWeakEventListener ) ? If I were to write new code , what are the reasons to prefer one to the other ? <code> void AddHandler ( INotifyPropertyChanged source , EventHandler < PropertyChangedEventArgs > handler , string propertyName ) void AddListener ( INotifyPropertyChanged source , IWeakEventListener listener , string propertyName ) private void AddListener ( INotifyPropertyChanged source , string propertyName , IWeakEventListener listener , EventHandler < PropertyChangedEventArgs > handler ) | PropertyChangedEventManager : AddHandler vs AddListener |
C_sharp : When I have a IEnumerable < SomeClass > from which I do n't know wheter its a list or not ( in terms of List < T > ) , and I have to enumerate that IEnumerable to make sure that I dont enumerate that enumerable twice ( such as looping over it twice , or something like that ) .Resharper warns me about possible multiple enumeration of IEnumerable - which is good , sometimes you forget it - and allows you to chose quickfixes : Enumerate to array Enumerate to listWhen I chose Enumerate to list , resharper introduces a local variable , and assigns the IEnumerable the following way ( example ) : Now my question is : Why does n't it simply do items.ToList ( ) ; ? What 's the advantage of trying to cast to IList < SomeClass > first ? <code> var enumeratedItems = items as IList < SomeClass > ? ? items.ToList ( ) ; | Is casting to IList and then calling ToList ( ) when null better than plain ToList ( ) ? |
C_sharp : I 'm writing a WinForms app in C # . I need to ensure no two Datarows in my Datatable are more than 100 km apart . Each row has a UTM Zone , Easting , and Northing in separate DataColumns . All coordinates use the same datum , but some have different zones ( otherwise , I would just use pythag math since UTMs are in metres ) . So far , I 'm using the following code to do this , but it does n't seem like my DbGeography.PointFromText method is working quite right ( see * in the code ) , as when the code reaches the line of code with the '** ' at the start of it , I get an error saying `` 24201 : Latitude values must be between -90 and 90 degrees '' . I 've also tried : Only to have it complain that `` There 's no column # 17 '' ( 17 is my UTM Zone ) .I 've found very little documentation for using this stuff ... as far as I can tell , my SRIDs are correct ( I pulled them from this site ) . I 've done this kind of thing using Lat+Longs before , and it worked wonderfully . I just ca n't find proper syntax for the UTMs . <code> dtTrap.Rows [ i ] [ `` TrapGeog '' ] = DbGeography.PointFromText ( pointWellKnownText : `` POINT M ( `` + dtTrap.Rows [ i ] [ intEastingIndex ] .ToString ( ) + `` `` + dtTrap.Rows [ i ] [ intNorthingIndex ] .ToString ( ) + `` `` + dtTrap.Rows [ i ] [ Zone ] .ToString ( ) + `` ) '' , coordinateSystemId : SRID ) ; using System.Data.Entity.Spatial ; ... DataColumn dcGeog = new DataColumn ( `` TrapGeog '' , typeof ( DbGeography ) ) ; dtTrap.Columns.Add ( dcGeog ) ; byte Zone ; Int16 SRID ; for ( int i = 0 ; i < dtTrap.Rows.Count ; ++i ) { if ( dtTrap.Rows [ i ] [ intZoneIndex ] ! = null & & dtTrap.Rows [ i ] [ intNorthingIndex ] ! = null & & dtTrap.Rows [ i ] [ intEastingIndex ] ! = null & & byte.TryParse ( dtTrap.Rows [ i ] [ intZoneIndex ] .ToString ( ) , out Zone ) == true ) { if ( Zone == 15 ) { SRID = 26915 ; } else if ( Zone == 16 ) { SRID = 26916 ; } else if ( Zone == 17 ) { SRID = 26917 ; } else { SRID = 26918 ; } // shove it in : try { *dtTrap.Rows [ i ] [ `` TrapGeog '' ] = DbGeography.PointFromText ( pointWellKnownText : `` POINT ( `` + dtTrap.Rows [ i ] [ intEastingIndex ] .ToString ( ) + `` `` + dtTrap.Rows [ i ] [ intNorthingIndex ] .ToString ( ) + `` ) '' , coordinateSystemId : SRID ) ; } catch ( Exception ex ) { if ( ex.InnerException ! = null ) { **MessageBox.Show ( ex.InnerException.Message ) ; } else { MessageBox.Show ( ex.Message ) ; } } } } for ( int i = 0 ; i < dtTrap.Rows.Count - 1 ; ++i ) { for ( int k = i + 1 ; k < dtTrap.Rows.Count ; ++i ) { DbGeography iTrap = ( DbGeography ) dtTrap.Rows [ i ] [ `` TrapGeog '' ] ; DbGeography kTrap = ( DbGeography ) dtTrap.Rows [ k ] [ `` TrapGeog '' ] ; if ( iTrap.Distance ( kTrap ) > 100000 ) { sbErrorsAndWarningsLog.Append ( @ '' Warning : Line number `` + ( i + 2 ) .ToString ( ) + `` on the Trap spreadsheet has coordinates that are at least 100 km away from row `` + ( k + 2 ) .ToString ( ) + `` 's point . Please check that these coordinates are correct . `` ) .AppendLine ( ) ; boolWarningsFound = true ; break ; } } } | Parsing UTM coordinates to DBGeography in C # |
C_sharp : I 'm writing a Tiger compiler in C # and I 'm going to translate the Tiger code into IL.While implementing the semantic check of every node in my AST , I created lots of unit tests for this . That is pretty simple , because my CheckSemantic method looks like this : so , if I want to write some unit test for the semantic check of some node , all I have to do is build an AST , and call that method . Then I can do something like : orbut I 'm starting the code generation in this moment , and I do n't know what could be a good practice when writing unit tests for that phase.I 'm using the ILGenerator class . I 've thought about the following : Generate the code of the sample program I want to testSave generated code as test.exeExecute text.exe and store the output in resultsAssert against resultsbut I 'm wondering if there is a better way of doing it ? <code> public override void CheckSemantics ( Scope scope , IList < Error > errors ) { ... } Assert.That ( errors.Count == 0 ) ; Assert.That ( errors.Count == 1 ) ; Assert.That ( errors [ 0 ] is UnexpectedTypeError ) ; Assert.That ( scope.ExistsType ( `` some_declared_type '' ) ) ; | Writing unit tests in my compiler ( which generates IL ) |
C_sharp : I 'm on learning for C # .I heared C # is one of the most constructible language . so would you guys make my code more elegant and efficient ? Here is a my class ISO639 . This class provides enum for ISO639 code , but I need a type conversion on from ISO639 enum to plain string . ( ex . ISO639.ISO639Code.Italian = > `` it '' ) . I also need a type conversion from plain string to ISO639 enum . ( ex . `` it '' = > ISO639.ISO639Code.Italian ) .Is there a more efficient coding style for that ? <code> public class ISO639 { public enum ISO639Code { Afrikaans , //af Albanian , //sq Amharic , //am ... Yiddish , //yi Unknown } public static string GetISO639CodeString ( ISO639.ISO639Code l ) { switch ( l ) { case ISO639Code.English : return `` en '' ; case ISO639Code.Japanese : return `` ja '' ; ... case ISO639Code.Hebrew : return `` he '' ; default : return `` '' ; } public static ISO639.ISO639Code GetISO39CodeValue ( string s ) { switch ( s ) { case `` ko '' : return ISO639Code.Korean ; case `` en '' : return ISO639Code.English ; ... case `` hu '' : return ISO639Code.Hungarian ; default : return ISO639Code.Unknown ; } } } | more elegant design about enum |
C_sharp : I am writing an application to capture the screen using the CopyFromScreen method , and also want to save the image I capture to send over my local network.So , I am trying store the captured screen on one bitmap , and save another bitmap , which is the previously captured screen , on two threads . However , this is throwing an InvalidOperationException , which says object is currently in use elsewhere . The exception is thrown by System.Drawing.dll . I have tried locking , and am using separate bitmaps for saving and capturing the screen . How do I stop this from happening ? Relevant code : <code> Bitmap ScreenCapture ( Rectangle rctBounds ) { Bitmap resultImage = new Bitmap ( rctBounds.Width , rctBounds.Height ) ; using ( Graphics grImage = Graphics.FromImage ( resultImage ) ) { try { grImage.CopyFromScreen ( rctBounds.Location , Point.Empty , rctBounds.Size ) ; } catch ( System.InvalidOperationException ) { return null ; } } return resultImage ; } void ImageEncode ( Bitmap bmpSharedImage ) { // other encoding tasks pictureBox1.Image = bmpSharedImage ; try { Bitmap temp = ( Bitmap ) bmpSharedImage.Clone ( ) ; temp.Save ( `` peace.jpeg '' ) ; } catch ( System.InvalidOperationException ) { return ; } } private void button1_Click ( object sender , EventArgs e ) { timer1.Interval = 30 ; timer1.Start ( ) ; } Bitmap newImage = null ; private async void timer1_Tick ( object sender , EventArgs e ) { //take new screenshot while encoding the old screenshot Task tskCaptureTask = Task.Run ( ( ) = > { newImage = ScreenCapture ( _rctDisplayBounds ) ; } ) ; Task tskEncodeTask = Task.Run ( ( ) = > { try { ImageEncode ( ( Bitmap ) _bmpThreadSharedImage.Clone ( ) ) ; } catch ( InvalidOperationException err ) { System.Diagnostics.Debug.Write ( err.Source ) ; } } ) ; await Task.WhenAll ( tskCaptureTask , tskEncodeTask ) ; _bmpThreadSharedImage = newImage ; } | InvalidOperationException while saving a bitmap and using graphics.copyFromScreen parallel-y |
C_sharp : I got a scenario to create the anonymous list from the anonymous types , and i achieved that using these are the error messages System.Collections.Generic.List.Add ( AnonymousType # 1 ) ' has some invalid arguments Argument ' 1 ' : can not convert from 'AnonymousType # 2 ' to 'AnonymousType # 1'whats the reason behind that ? ? <code> public static List < T > MakeList < T > ( T itemOftype ) { List < T > newList = new List < T > ( ) ; return newList ; } static void Main ( string [ ] args ) { //anonymos type var xx = new { offsetname = x.offName , RO = y.RO1 } ; //anonymos list var customlist = MakeList ( xx ) ; //It throws an error because i have given the wrong order customlist.Add ( new { RO = y.RO2 , offsetname = x.offName } ) ; customlist.Add ( new { RO = y.RO3 , offsetname = x.offName } ) ; //but this works customlist.Add ( new { offsetname = x.offName , RO = y.RO2 } ) ; customlist.Add ( new { offsetname = x.offName , RO = y.RO3 } ) ; } | is order of field important in anonymous types automatic initialization ? |
C_sharp : Possible Duplicate : C # Why can equal decimals produce unequal hash values ? I 've come across an issue in my .NET 3.5 application ( x86 or x64 , I 've tried both ) where decimals with a different number of trailing zeros have different hash codes . For example : Outputs the following on my machine : I presume the difference in hash codes is down to the different internal representations of the two numbers caused by the differing scale factors.Whilst I can work around the issue by removing the trailing zeros I always assumed that GetHashCode should return the same value for x and y , if x == y . Is this assumption wrong , or is this a problem with Decimal.GetHashCode ? EDIT : To be clear on versions I 'm using Visual Studio 2008 SP1 , .NET 3.5 . <code> decimal x = 3575.000000000000000000M ; decimal y = 3575.0000000000000000000M ; Console.WriteLine ( x.GetHashCode ( ) ) ; Console.WriteLine ( y.GetHashCode ( ) ) ; Console.WriteLine ( x == y ) ; Console.WriteLine ( x.GetHashCode ( ) == y.GetHashCode ( ) ) ; 10850094091085009408TrueFalse | Decimal.GetHashCode Depends On Trailing Zeros |
C_sharp : I create an entry usingIt is inside a ListView > ItemTemplate > DataTemplate > ViewCellThe thing is I need a way once a user clicks the submit button in that ViewCell it gets the text for the entry in that cell . I am using Binding to set the values so I do n't how to get the text . <code> < Entry Placeholder= '' Reply ... '' / > | How to get text from entry |
C_sharp : Let 's say we have two interfaces with conflicting method signatures : and now we create a class like this : The method named as IB.F looks like a private method , however you can do something like this : So my question is : how does the C # compiler know that IB.F can be called outside the class scope ? I guess it 's that IB . prefix , but looked into the IL code and it just appears as a private method with that odd signature . <code> interface IA { void F ( ) ; } interface IB { int F ( ) ; } class Test : IA , IB { public void F ( ) { ... } int IB.F ( ) { ... } } var t = new Test ( ) ; t.F ( ) ; //Calls public method F ( ( IB ) t ) .F ( ) ; //Calls private method IB.F ! ! ! | Class implementing interfaces with conflicting method signatures |
C_sharp : First things off , I had no idea what to title this question - I 'm even confused how to state it . Now for the question . Let 's take the System.IO.FileSystemWatcher class where you set it 's NotifyFilter property : That 's quite a bit of code to set a single property . Inspecting NotifyFilter , it is an enumeration . Is there a 'lazy ' or 'shortcut ' way to set all these properties at once ? I know it 's not necessarily needed , but my curiosity is piqued.this.FileSystemWatcher1.NotifyFilter = < NotifyFilters.All > ? <code> this.FileSystemWatcher1.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size ; | Is there a way to set an Enumerated Property in a class to All available enums ? |
C_sharp : I am using this code to extract a chunk from file Is there any way to speed up this process ? Currently for a 530 MB file it takes around 4 - 5 seconds . Can this time be improved ? <code> // info is FileInfo object pointing to filevar percentSplit = info.Length * 50 / 100 ; // extract 50 % of filevar bytes = new byte [ percentSplit ] ; var fileStream = File.OpenRead ( fileName ) ; fileStream.Read ( bytes , 0 , bytes.Length ) ; fileStream.Dispose ( ) ; File.WriteAllBytes ( splitName , bytes ) ; | Improve speed of splitting file |
C_sharp : I have the following class : Can someone explain why they Customer information is coded with virtual . What does it mean ? <code> public class Delivery { // Primary key , and one-to-many relation with Customer public int DeliveryID { get ; set ; } public virtual int CustomerID { get ; set ; } public virtual Customer Customer { get ; set ; } // Properties string Description { get ; set ; } } | Why would I need to use a virtual modifier in a c # class ? |
C_sharp : I think I 'm missing something obvious here , but how do I update the GUI when using a task and retrieving the value ? ( I 'm trying to use await/async instead of BackgroundWorker ) On my control the user has clicked a button that will do something that takes time . I want to alert the parent form so it can show some progress : In my parent form I 'm listening to WorkStarted and WorkComplete to update the status bar : Correct me if I 'm wrong , but the app is hanging because `` Invoke '' is waiting for the GUI thread to become available which it wo n't until my `` ButtonClicked ( ) '' call is complete . So we have a deadlock.What 's the correct way to approach this ? <code> private void ButtonClicked ( ) { var task = Task < bool > .Factory.StartNew ( ( ) = > { WorkStarted ( this , new EventArgs ( ) ) ; Thread.Sleep ( 5000 ) ; WorkComplete ( this , null ) ; return true ; } ) ; if ( task.Result ) MessageBox.Show ( `` Success ! `` ) ; //this line causes app to block } myControl.WorkStarting += ( o , args ) = > { Invoke ( ( MethodInvoker ) delegate { toolStripProgressBar1.Visible = true ; toolStripStatusLabel1.Text = `` Busy '' ; } ) ; } ; | How do I update the GUI on the parent form when I retrieve the value from a Task ? |
C_sharp : I have an application that has a concept of a Venue , a place where events happen . A Venue has many VenueParts . So , it looks like this : A Venue can be a GolfCourseVenue , which is a Venue that has a Slope and a specific kind of VenuePart called a HoleVenuePart : In the future , there may also be other kinds of Venues that all inherit from Venue . They might add their own fields , and will always have VenueParts of their own specific type.Here are the VenuePart classes : My declarations above seem wrong , because now I have a GolfCourseVenue with two collections , when really it should just have the one . I ca n't override it , because the type is different , right ? When I run reports , I would like to refer to the classes generically , where I just spit out Venues and VenueParts . But , when I render forms and such , I would like to be specific.I have a lot of relationships like this and am wondering what I am doing wrong . For example , I have an Order that has OrderItems , but also specific kinds of Orders that have specific kinds of OrderItems.Update : I should note that these classes are Entity Framework Code-First entities . I was hoping this would n't matter , but I guess it might . I need to structure the classes in a way that Code-First can properly create tables . It does n't look like Code-First can handle generics . Sorry this implementation detail is getting in the way of an elegant solution : /Update 2 : Someone linked to a search that pointed at Covariance and Contravariance , which seemed to be a way to constrain lists within subtypes to be of a given subtype themselves . That seems really promising , but the person deleted their answer ! Does anyone have any information on how I may leverage these concepts ? Update 3 : Removed the navigation properties that were in child objects , because it was confusing people and not helping to describe the problem . <code> public abstract class Venue { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < VenuePart > VenueParts { get ; set ; } } public class GolfCourseVenue : Venue { public string Slope { get ; set ; } public virtual ICollection < HoleVenuePart > Holes { get ; set ; } } public abstract class VenuePart { public int Id { get ; set ; } public string Name { get ; set ; } public abstract string NameDescriptor { get ; } } public class HoleVenuePart : VenuePart { public override string NameDescriptor { get { return `` Hole '' ; } } public int Yardage { get ; set ; } } | How do I organize C # classes that inherit from one another , but also have properties that inherit from one another ? |
C_sharp : This question is not about managing Windows pathnames ; I used that only as a specific example of a case-insensitive string . ( And I if I change the example now , a whole bunch of comments will be meaningless . ) This may be similar to Possible to create case insensitive string class ? , but there is n't a lot of discussion there . Also , I do n't really care about the tight language integration that string enjoys or the performance optimizations of System.String.Let 's say I use a lot of Windows pathnames which are ( normally ) case-insensitive ( I 'm not actually concerned with the many details of actual paths like \ vs. / , \\\\ being the same as \ , file : // URLs , .. , etc. ) . A simple wrapper might be : Yes , all/most of the interfaces on System.String should probably be implemented ; but the above seems like enough for discussion purposes.I can now write : This allows me to `` talk about '' WindowsPathnames in my code rather than a implementation detail like StringComparison.OrdinalIgnoreCase . ( Yes , this specific class could also be extended to handle \ vs / so that c : /foo.txt would be equal to C : \FOO.TXT ; but that 's not the point of this question . ) Furthermore , this class ( with additional interfaces ) will be case-insensitive when instances are added to collections ; it would not necessary to specify an IEqualityComparer . Finally , a specific class like this also makes it easier to prevent `` non-sense '' operations such as comparing a file system path to a registry key.The question is : will such approach be successful ? Are there any serious and/or subtle flaws or other `` gotchas '' ? ( Again , having to do with trying to setup a case-insensitive string class , not managing Windows pathnames . ) <code> sealed class WindowsPathname : IEquatable < WindowsPathname > /* TODO : more interfaces from System.String */ { public WindowsPathname ( string path ) { if ( path == null ) throw new ArgumentNullException ( nameof ( path ) ) ; Value = path ; } public string Value { get ; } public override int GetHashCode ( ) { return Value.ToUpperInvariant ( ) .GetHashCode ( ) ; } public override string ToString ( ) { return Value.ToString ( ) ; } public override bool Equals ( object obj ) { var strObj = obj as string ; if ( strObj ! = null ) return Equals ( new WindowsPathname ( strObj ) ) ; var other = obj as WindowsPathname ; if ( other ! = null ) return Equals ( other ) ; return false ; } public bool Equals ( WindowsPathname other ) { // A LOT more needs to be done to make Windows pathanames equal . // This is just a specific example of the need for a case-insensitive string return Value.Equals ( other.Value , StringComparison.OrdinalIgnoreCase ) ; } } var p1 = new WindowsPathname ( @ '' c : \foo.txt '' ) ; var p2 = new WindowsPathname ( @ '' C : \FOO.TXT '' ) ; bool areEqual = p1.Equals ( p2 ) ; // true | How can System.String be properly wrapped for case-insensitivy ? |
C_sharp : I hava a mvvm wpf application that worked properly all until one moment when it freezes and causes massive memory leak.Solution files : Google Disk Solution LinkThe application uses local mdf file , uses Mahhaps , and some additional references ( for example one for displaying gifs ) This is the method call in the View model that is making the issue , the assignment of the Contacts with await is making the issue - this is used in one other view model where it makes no any issues , even here it was working all right until one moment.This is the way the View is renderedI tried removing the libraries , for gifs ( the gifs are not shown in this view in the other view which is not making any issues there ) .The same call to the repository - to fetch the Contacts data I have on one other view and it is not making any problems.This Contacts view was working good all until sudden.I tried to debug but the debugger does not even come to the code.After loading some data into the db I get a freeze.The freeze is made by the OnLoad method from the ContactsViewModel - this call to the repository is used on one other ViewModel where it has no any issues - it returns the data quicklyContactsViewModel code : ContactRepository class : This is the view that uses the ViewModel it is called ContactsView - this view is included in the MainWindow as other views areContactsView : The very bad thing is that when I try to debug it does not even go to the code - method call.Tried also to use some profiling tools but I did not come to any conclusion what is making this freeze issue ... When I run the query on the db from the db editor I get instant results . I also use a SSRS report in the app displayed using ReportViewer - it also works fine and returns the same data - it is displayed on a separate View.On one of the views I display a GIF animation using WpfAnimatedGif Library - I tried to remove this reference to see if that is making the issue but it does not the freeze goes on ... I also tried to rewrite my repository class to use using command for the creation of the new instance of db for every method but this is not what is making the issue.Solution files : Google Disk Solution Link <code> public async void OnLoad ( ) { IsRefreshEnabled = false ; IsRefreshProgressActive = true ; Contacts =await Task.Run ( ( ) = > _repository.GetContactsAsync ( ) ) ; IsRefreshEnabled = true ; IsRefreshProgressActive = false ; } < DataGrid SelectedItem= '' { Binding Contact } '' AutoGenerateColumns= '' True '' ItemsSource= '' { Binding Path=Contacts , Mode=TwoWay } '' Style= '' { StaticResource AzureDataGrid } '' x : Name= '' dataGridCodeBehind '' Margin= '' 10,54,521,0 '' VerticalAlignment= '' Top '' HorizontalAlignment= '' Stretch '' HorizontalContentAlignment= '' Stretch '' ColumnWidth= '' * '' > < DataGrid.ColumnHeaderStyle > < Style TargetType= '' DataGridColumnHeader '' > < Setter Property= '' FontSize '' Value= '' 10 '' / > < /Style > < /DataGrid.ColumnHeaderStyle > < /DataGrid > using Digital_Data_House_Bulk_Mailer.Commands ; using Digital_Data_House_Bulk_Mailer.Model ; using Digital_Data_House_Bulk_Mailer.Repository ; using System ; using System.Collections.Generic ; using System.Collections.ObjectModel ; using System.ComponentModel ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows ; using System.Windows.Input ; namespace Digital_Data_House_Bulk_Mailer.ViewModel { class ContactsViewModel : INotifyPropertyChanged { private Contact _contact ; private IContactRepository _repository = new ContactRepository ( ) ; public event PropertyChangedEventHandler PropertyChanged = delegate { } ; public static event EventHandler < PropertyChangedEventArgs > StaticPropertyChanged ; private static void NotifyStaticPropertyChanged ( string propertyName ) { if ( StaticPropertyChanged ! = null ) StaticPropertyChanged ( null , new PropertyChangedEventArgs ( propertyName ) ) ; } public RelayCommand UpdateCommand { get ; set ; } public RelayCommand LoadCommand { get ; set ; } public RelayCommand DeleteCommand { get ; set ; } public RelayCommand DeleteAllContactsCommand { get ; set ; } public RelayCommand RecreateFiltersCommand { get ; set ; } private ObservableCollection < Contact > _contacts ; public ObservableCollection < Contact > Contacts { get { return _contacts ; } set { _contacts = value ; PropertyChanged ( this , new PropertyChangedEventArgs ( `` Contacts '' ) ) ; //used in case of static Contacts property //NotifyStaticPropertyChanged ( `` Contacts '' ) ; } } public Contact Contact { get { return _contact ; } set { _contact = value ; DeleteCommand.RaiseCanExecuteChanged ( ) ; UpdateCommand.RaiseCanExecuteChanged ( ) ; PropertyChanged ( this , new PropertyChangedEventArgs ( `` Contact '' ) ) ; } } private bool _isRefreshEnabled=true ; public bool IsRefreshEnabled { get { return _isRefreshEnabled ; } set { _isRefreshEnabled = value ; PropertyChanged ( this , new PropertyChangedEventArgs ( `` IsRefreshEnabled '' ) ) ; } } private bool _isRefreshProgressActive = false ; public bool IsRefreshProgressActive { get { return _isRefreshProgressActive ; } set { _isRefreshProgressActive = value ; PropertyChanged ( this , new PropertyChangedEventArgs ( `` IsRefreshProgressActive '' ) ) ; } } public ContactsViewModel ( ) { DeleteCommand = new RelayCommand ( OnDelete , CanDelete ) ; UpdateCommand = new RelayCommand ( OnUpdate , CanUpdate ) ; LoadCommand = new RelayCommand ( OnLoad , CanLoad ) ; DeleteAllContactsCommand = new RelayCommand ( OnDeleteAllContacts , CanDeleteAllContacts ) ; RecreateFiltersCommand = new RelayCommand ( OnRecreateFilters , CanRecreateFilters ) ; OnLoad ( ) ; } public bool CanRecreateFilters ( ) { return true ; } public async void OnRecreateFilters ( ) { IsRefreshProgressActive = true ; await Task.Run ( ( ) = > _repository.ResetFilters ( ) ) ; IsRefreshProgressActive = false ; } public async void OnDeleteAllContacts ( ) { MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show ( `` Are you sure ? `` , `` DELETE ALL EXISTING CONTACTS '' , System.Windows.MessageBoxButton.YesNo ) ; if ( messageBoxResult == MessageBoxResult.Yes ) { IsRefreshProgressActive = true ; await Task.Run ( ( ) = > _repository.DeleteAllContacts ( ) ) ; IsRefreshProgressActive = false ; } } public bool CanDeleteAllContacts ( ) { return true ; } private void OnDelete ( ) { MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show ( `` Are you sure ? `` , `` Delete Contact Confirmation '' , System.Windows.MessageBoxButton.YesNo ) ; if ( messageBoxResult == MessageBoxResult.Yes ) { _repository.DeleteContactAsync ( Contact ) ; Contacts.Remove ( Contact ) ; } } private bool CanDelete ( ) { if ( Contact ! = null ) { return true ; } return false ; } private void OnUpdate ( ) { _repository.AddContactAsync ( Contact ) ; } private bool CanUpdate ( ) { if ( Contact ! = null ) { return true ; } return false ; } public async void OnLoad ( ) { IsRefreshEnabled = false ; IsRefreshProgressActive = true ; Contacts =await Task.Run ( ( ) = > _repository.GetContactsAsync ( ) ) ; IsRefreshEnabled = true ; IsRefreshProgressActive = false ; } private ObservableCollection < Contact > GetContactsAsync ( ) { return _repository.GetContactsAsync ( ) ; } public bool CanLoad ( ) { return true ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using Digital_Data_House_Bulk_Mailer.Model ; using System.Data.Entity ; using System.Collections.ObjectModel ; using System.Data.Entity.Migrations ; using System.Collections ; using System.Data.Entity.Core.Objects ; using System.Data.SqlClient ; namespace Digital_Data_House_Bulk_Mailer.Repository { class ContactRepository : IContactRepository { digital_datahouse_bulk_mailerEntities db = null ; public ContactRepository ( ) { db = new digital_datahouse_bulk_mailerEntities ( ) ; } public string SELECT_ALL { get { return `` Select All '' ; } private set { } } public ObservableCollection < StateFilter > GetStates ( ) { ObservableCollection < StateFilter > stateFilters = new ObservableCollection < StateFilter > ( ) ; foreach ( StateFilter state in db.StateFilters.ToList ( ) ) { db.Entry < StateFilter > ( state ) .Reload ( ) ; stateFilters.Add ( state ) ; } return stateFilters ; } public ObservableCollection < CountyFilter > GetCounties ( ) { ObservableCollection < CountyFilter > countyFilters = new ObservableCollection < CountyFilter > ( ) ; foreach ( CountyFilter county in db.CountyFilters.ToList ( ) ) { db.Entry < CountyFilter > ( county ) .Reload ( ) ; countyFilters.Add ( county ) ; } return countyFilters ; } public ObservableCollection < GenderFilter > GetGenders ( ) { ObservableCollection < GenderFilter > genderFilters = new ObservableCollection < GenderFilter > ( ) ; foreach ( GenderFilter gender in db.GenderFilters.ToList ( ) ) { db.Entry < GenderFilter > ( gender ) .Reload ( ) ; genderFilters.Add ( gender ) ; } return genderFilters ; } public ObservableCollection < IndustryFilter > GetIndustries ( ) { ObservableCollection < IndustryFilter > industryFilters = new ObservableCollection < IndustryFilter > ( ) ; foreach ( IndustryFilter industry in db.IndustryFilters.ToList ( ) ) { db.Entry < IndustryFilter > ( industry ) .Reload ( ) ; industryFilters.Add ( industry ) ; } return industryFilters ; } public ObservableCollection < IsContactedFilter > GetIsContacted ( ) { ObservableCollection < IsContactedFilter > isContactedFilters = new ObservableCollection < IsContactedFilter > ( ) ; foreach ( IsContactedFilter isContacted in db.IsContactedFilters.ToList ( ) ) { db.Entry < IsContactedFilter > ( isContacted ) .Reload ( ) ; isContactedFilters.Add ( isContacted ) ; } return isContactedFilters ; } public ObservableCollection < SicCodeDescriptionFilter > GetSicCodeDescriptions ( ) { ObservableCollection < SicCodeDescriptionFilter > sicCodeDescriptionFilters = new ObservableCollection < SicCodeDescriptionFilter > ( ) ; foreach ( SicCodeDescriptionFilter sicCodeDescriptionFilter in db.SicCodeDescriptionFilters.ToList ( ) ) { db.Entry < SicCodeDescriptionFilter > ( sicCodeDescriptionFilter ) .Reload ( ) ; sicCodeDescriptionFilters.Add ( sicCodeDescriptionFilter ) ; } return sicCodeDescriptionFilters ; } public void AddContactAsync ( Contact contact ) { if ( contact ! = null ) { db.Contacts.AddOrUpdate ( contact ) ; db.SaveChangesAsync ( ) ; } } public void DeleteContactAsync ( Contact contact ) { if ( contact ! = null ) { db.Contacts.Remove ( contact ) ; db.SaveChangesAsync ( ) ; } } public void UpdateContactAsync ( Contact contact ) { if ( contact ! = null ) { db.Contacts.AddOrUpdate ( contact ) ; db.SaveChangesAsync ( ) ; } } public ObservableCollection < Contact > GetContactsAsync ( ) { db = new digital_datahouse_bulk_mailerEntities ( ) ; ObservableCollection < Contact > contacts = new ObservableCollection < Contact > ( ) ; foreach ( var contact in db.Contacts.ToList ( ) ) { contacts.Add ( contact ) ; } return contacts ; } public ObservableCollection < Contact > FilterContacts ( ObservableCollection < StateFilter > states , ObservableCollection < CountyFilter > counties , ObservableCollection < GenderFilter > genders , ObservableCollection < IndustryFilter > industries , ObservableCollection < IsContactedFilter > contacted , ObservableCollection < SicCodeDescriptionFilter > codes , bool hasWebsite ) { db = new digital_datahouse_bulk_mailerEntities ( ) ; ObservableCollection < Contact > filteredContacts = new ObservableCollection < Contact > ( ) ; string [ ] stateArray = ( from s in states where s.IsChecked==true select s.State ) .ToArray ( ) ; string [ ] countyArray= ( from c in counties where c.IsChecked==true select c.County ) .ToArray ( ) ; string [ ] genderArray= ( from g in genders where g.IsChecked==true select g.Gender ) .ToArray ( ) ; string [ ] industryArray = ( from i in industries where i.IsChecked==true select i.Industry ) .ToArray ( ) ; string [ ] contactedArray = ( from c in contacted where c.IsChecked==true select c.IsContacted.ToString ( ) ) .ToArray ( ) ; string [ ] sicCodeArray = ( from c in codes where c.IsChecked==true select c.SicCodeDescription ) .ToArray ( ) ; var contacts= ( from c in db.Contacts where stateArray.Contains ( c.State ) & & countyArray.Contains ( c.County ) & & genderArray.Contains ( c.Gender ) & & industryArray.Contains ( c.Industry ) & & contactedArray.Contains ( c.IsContacted ) & & sicCodeArray.Contains ( c.SIC_Code_Description ) select c ) .ToList ( ) ; foreach ( Contact contact in contacts ) { if ( hasWebsite==true ) { if ( ! String.IsNullOrEmpty ( contact.WebSite ) ) { filteredContacts.Add ( contact ) ; } } else { filteredContacts.Add ( contact ) ; } } return filteredContacts ; } public void AddContactsRange ( ObservableCollection < Contact > contacts ) { db.Contacts.AddRange ( contacts ) ; db.SaveChanges ( ) ; } public void ResetFilters ( ) { ResetStates ( ) ; ResetCounties ( ) ; ResetIsContactedFilters ( ) ; ResetGenders ( ) ; ResetIndustries ( ) ; ResetSicFilters ( ) ; } private void ResetStates ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ StateFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < StateFilter > stateFilters = new List < StateFilter > ( ) ; var states = ( from c in db.Contacts select c.State ) .Distinct ( ) .ToList ( ) ; foreach ( var stateName in states ) { StateFilter state = new StateFilter ( ) ; state.State = stateName ; state.IsChecked = true ; stateFilters.Add ( state ) ; } db.StateFilters.AddRange ( stateFilters ) ; db.SaveChanges ( ) ; } public void DeleteAllContacts ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ Contact ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; } private void ResetCounties ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ CountyFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < CountyFilter > countyFilters = new List < CountyFilter > ( ) ; var counties = ( from c in db.Contacts select c.County ) .Distinct ( ) .ToList ( ) ; foreach ( var countyName in counties ) { CountyFilter county = new CountyFilter ( ) ; county.County = countyName ; county.IsChecked = true ; countyFilters.Add ( county ) ; } db.CountyFilters.AddRange ( countyFilters ) ; db.SaveChanges ( ) ; } private void ResetGenders ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ GenderFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < GenderFilter > genderFilters = new List < GenderFilter > ( ) ; var genders = ( from c in db.Contacts select c.Gender ) .Distinct ( ) .ToList ( ) ; foreach ( var genderName in genders ) { GenderFilter gender = new GenderFilter ( ) ; gender.Gender = genderName ; gender.IsChecked = true ; genderFilters.Add ( gender ) ; } db.GenderFilters.AddRange ( genderFilters ) ; db.SaveChanges ( ) ; } private void ResetIndustries ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ IndustryFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < IndustryFilter > industryFilters = new List < IndustryFilter > ( ) ; var industries = ( from c in db.Contacts select c.Industry ) .Distinct ( ) .ToList ( ) ; foreach ( var industryName in industries ) { IndustryFilter industry = new IndustryFilter ( ) ; industry.Industry = industryName ; industry.IsChecked = true ; industryFilters.Add ( industry ) ; } db.IndustryFilters.AddRange ( industryFilters ) ; db.SaveChanges ( ) ; } private void ResetIsContactedFilters ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ IsContactedFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < IsContactedFilter > isContactedFilters = new List < IsContactedFilter > ( ) ; var isContacted = ( from c in db.Contacts select c.IsContacted ) .Distinct ( ) .ToList ( ) ; foreach ( var contactedName in isContacted ) { IsContactedFilter contacted = new IsContactedFilter ( ) ; contacted.IsContacted = contactedName ; contacted.IsChecked = true ; isContactedFilters.Add ( contacted ) ; } db.IsContactedFilters.AddRange ( isContactedFilters ) ; db.SaveChanges ( ) ; } private void ResetSicFilters ( ) { db.Database.ExecuteSqlCommand ( `` TRUNCATE TABLE [ SicCodeDescriptionFilter ] '' ) ; db = new digital_datahouse_bulk_mailerEntities ( ) ; List < SicCodeDescriptionFilter > sicFilters = new List < SicCodeDescriptionFilter > ( ) ; var sics = ( from c in db.Contacts select c.SIC_Code_Description ) .Distinct ( ) .ToList ( ) ; foreach ( var sic in sics ) { SicCodeDescriptionFilter sicCode = new SicCodeDescriptionFilter ( ) ; sicCode.SicCodeDescription = sic ; sicCode.IsChecked = true ; sicFilters.Add ( sicCode ) ; } db.SicCodeDescriptionFilters.AddRange ( sicFilters ) ; db.SaveChanges ( ) ; } public void UpdateIsContactedInformation ( Contact contact ) { db = new digital_datahouse_bulk_mailerEntities ( ) ; contact.IsContacted = `` True '' ; contact.MessageDateSent = DateTime.Today ; db.Contacts.AddOrUpdate ( contact ) ; db.SaveChanges ( ) ; } } } < UserControl x : Class= '' Digital_Data_House_Bulk_Mailer.View.ContactsView '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : local= '' clr-namespace : Digital_Data_House_Bulk_Mailer.View '' xmlns : Controls= '' clr-namespace : MahApps.Metro.Controls ; assembly=MahApps.Metro '' xmlns : model= '' clr-namespace : Digital_Data_House_Bulk_Mailer.ViewModel '' mc : Ignorable= '' d '' d : DesignHeight= '' 300 '' d : DesignWidth= '' 300 '' > < UserControl.DataContext > < model : ContactsViewModel/ > < /UserControl.DataContext > < Grid Margin= '' 0,0 , -690 , -36 '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 61* '' / > < ColumnDefinition Width= '' 10* '' / > < /Grid.ColumnDefinitions > < Button Style= '' { StaticResource AccentedSquareButtonStyle } '' Command= '' { Binding DeleteCommand } '' Controls : TextBoxHelper.ClearTextButton= '' True '' x : Name= '' delete '' Content= '' DELETE '' HorizontalAlignment= '' Left '' Margin= '' 115,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 100 '' RenderTransformOrigin= '' 0.267,0.519 '' / > < Button Style= '' { StaticResource AccentedSquareButtonStyle } '' Command= '' { Binding UpdateCommand } '' Controls : TextBoxHelper.ClearTextButton= '' True '' x : Name= '' update '' Content= '' add / update '' HorizontalAlignment= '' Left '' Margin= '' 10,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 100 '' RenderTransformOrigin= '' 0.267,0.519 '' / > < Button Style= '' { StaticResource AccentedSquareButtonStyle } '' Controls : TextBoxHelper.ClearTextButton= '' True '' x : Name= '' bulk_import '' Content= '' import new data '' HorizontalAlignment= '' Left '' Margin= '' 220,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 110 '' RenderTransformOrigin= '' 0.267,0.519 '' Click= '' bulk_import_Click '' / > < DataGrid SelectedItem= '' { Binding Contact } '' AutoGenerateColumns= '' True '' ItemsSource= '' { Binding Path=Contacts , Mode=TwoWay } '' Style= '' { StaticResource AzureDataGrid } '' x : Name= '' dataGridCodeBehind '' Margin= '' 10,54,521,0 '' VerticalAlignment= '' Top '' HorizontalAlignment= '' Stretch '' HorizontalContentAlignment= '' Stretch '' ColumnWidth= '' * '' > < DataGrid.ColumnHeaderStyle > < Style TargetType= '' DataGridColumnHeader '' > < Setter Property= '' FontSize '' Value= '' 10 '' / > < /Style > < /DataGrid.ColumnHeaderStyle > < /DataGrid > < Button IsEnabled= '' { Binding IsRefreshEnabled } '' Style= '' { StaticResource AccentedSquareButtonStyle } '' Command= '' { Binding LoadCommand } '' x : Name= '' refreshData '' Content= '' Refresh Contacts '' HorizontalAlignment= '' Left '' Height= '' 22 '' Margin= '' 335,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 114 '' / > < Controls : ProgressRing IsActive= '' { Binding IsRefreshProgressActive } '' Foreground= '' { DynamicResource AccentColorBrush } '' Margin= '' 720,0,0,0 '' RenderTransformOrigin= '' -2.889,0.463 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' Height= '' 50 '' Width= '' 50 '' / > < Button x : Name= '' deleteContacts '' Command= '' { Binding DeleteAllContactsCommand } '' Style= '' { StaticResource AccentedSquareButtonStyle } '' Content= '' Delete All Contacts '' HorizontalAlignment= '' Left '' Height= '' 22 '' Margin= '' 454,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 114 '' / > < Button x : Name= '' recreateFilters '' Command= '' { Binding RecreateFiltersCommand } '' Content= '' Recreate TO MAIL Filters '' HorizontalAlignment= '' Left '' Style= '' { StaticResource AccentedSquareButtonStyle } '' Height= '' 22 '' Margin= '' 573,21,0,0 '' VerticalAlignment= '' Top '' Width= '' 142 '' / > < /Grid > | Wpf application freezes - massive memory leak puzzle |
C_sharp : The docs show this for a POST : But what about a GET : The problem is the ampersand in this line : /// GET /Todo ? iscomplete=true & owner=mike . The compiler complains : warning CS1570 : XML comment has badly formed XML -- 'Expected an end tag for element 'owner ' . ' I also tried & amp ; .I actually have n't found an example for GETs.What is the correct syntax ? <code> /// < summary > /// Creates a TodoItem./// < /summary > /// < remarks > /// Sample request : ////// POST /Todo/// { /// `` id '' : 1 , /// `` name '' : `` Item1 '' /// } /// < /remarks > [ HttpPost ] public ActionResult < TodoItem > Create ( TodoItem item ) { } /// < summary > /// Gets a TodoItem./// < /summary > /// < remarks > /// Sample request : ////// GET /Todo ? iscomplete=true & owner=mike/// < /remarks > [ HttpGet ] public ActionResult < TodoItem > Get ( bool isComplete , string owner ) { } | Querystring with ampersand in Swashbuckle xml comments |
C_sharp : Currently I have I want to make the path relative to the original path.For example if Tenant1/PageThatThrowsError then app.UseExceptionHandler ( `` Tenant1/Home/Error '' ) ; but if Tenant2/PageThatThrowsError then app.UseExceptionHandler ( `` Tenant2/Home/Error '' ) ; I thought I would be able to dobut this throws a 500EDIT : All the current solutions that for example uses redirects loses the current error context and does not allow the controller to for example call HttpContext.Features.Get ( ) . <code> app.UseExceptionHandler ( `` /Home/Error '' ) ; app.UseExceptionHandler ( new ExceptionHandlerOptions { ExceptionHandler = async ( ctx ) = > { //logic that extracts tenant ctx.Request.Path = new PathString ( Invariant ( $ '' { tenant } /Home/Error '' ) ) ; } } ) ; | How to handle dynamic error pages in .net MVC Core ? |
C_sharp : This is a somewhat obscure question , but after wasting an hour tracking down the bug , I though it worth asking ... I wrote a custom ordering for a struct , and made one mistake : My struct has a special state , let us call this `` min '' .If the struct is in the min state , then it 's smaller than any other struct.My CompareTo method made one mistake : a.CompareTo ( b ) would return -1 whenever a was `` min '' , but of course if b is also `` min '' it should return 0.Now , this mistake completely messed up a List < MyStruct > Sort ( ) method : the whole list would ( sometimes ) come out in a random order.My list contained exactly one object in `` min '' state.It seems my mistake could only affect things if the one `` min '' object was compared to itself.Why would this even happen when sorting ? And even if it did , how can it cause the relative order of two `` non-min '' objects to be wrong ? Using the LINQ OrderBy method can cause an infinite loop ... Small , complete , test example : <code> struct MyStruct : IComparable < MyStruct > { public int State ; public MyStruct ( int s ) { State = s ; } public int CompareTo ( MyStruct rhs ) { // 10 is the `` min '' state . Otherwise order as usual if ( State == 10 ) { return -1 ; } // Incorrect /*if ( State == 10 ) // Correct version { if ( rhs.State == 10 ) { return 0 ; } return -1 ; } */ if ( rhs.State == 10 ) { return 1 ; } return this.State - rhs.State ; } public override string ToString ( ) { return String.Format ( `` MyStruct ( { 0 } ) '' , State ) ; } } class Program { static int Main ( ) { var list = new List < MyStruct > ( ) ; var rnd = new Random ( ) ; for ( int i = 0 ; i < 20 ; ++i ) { int x = rnd.Next ( 15 ) ; if ( x > = 10 ) { ++x ; } list.Add ( new MyStruct ( x ) ) ; } list.Add ( new MyStruct ( 10 ) ) ; list.Sort ( ) ; // Never returns ... //list = list.OrderBy ( item = > item ) .ToList ( ) ; Console.WriteLine ( `` list : '' ) ; foreach ( var x in list ) { Console.WriteLine ( x ) ; } for ( int i = 1 ; i < list.Count ( ) ; ++i ) { Console.Write ( `` { 0 } `` , list [ i ] .CompareTo ( list [ i - 1 ] ) ) ; } return 0 ; } } | Why does failing to recognise equality mess up C # List < T > sort ? |
C_sharp : Using NUnit 2.6.4 & FakeItEasy 1.25.2 to unit test a C # code in Visual Studio 2013 Community EditionThe following test fragment executes as expectedhowever as soon as I decorate my fake with a CallTo/Returns ( ) or ReturnsLazily ( ) statement ... fakeStream.Read ( ) throws a System.InvalidOperationException with the message : `` The number of values for out and ref parameters specified does not match the number of out and ref parameters in the call . '' from within FakeItEasy.Configuration.BuildableCallRule.ApplyOutAndRefParametersValueProducer ( IInterceptedFakeObjectCall fakeObjectCall ) , which seems pretty odd to me as Stream.Read ( ) does n't have any out/ref parameters.Is this a bug that I should be reporting at https : //github.com/FakeItEasy , or am I missing something ? thx <code> [ Test ] public void test_whatIsUpWithStreamRead ( ) { Stream fakeStream = A.Fake < Stream > ( ) ; byte [ ] buffer = new byte [ 16 ] ; int numBytesRead = fakeStream.Read ( buffer , 0 , 16 ) ; Assert.AreEqual ( 0 , numBytesRead ) ; } [ Test ] public void test_whatIsUpWithStreamRead ( ) { Stream fakeStream = A.Fake < Stream > ( ) ; A.CallTo ( ( ) = > fakeStream.Read ( A < byte [ ] > .Ignored , A < int > .Ignored , A < int > .Ignored ) ) .Returns ( 1 ) ; byte [ ] buffer = new byte [ 16 ] ; int numBytesRead = fakeStream.Read ( buffer , 0 , 16 ) ; Assert.AreEqual ( 1 , numBytesRead ) ; } | A.Fake < Stream > ( ) .Read ( ... ) throwing InvalidOperationException |
C_sharp : I use the following razor code to generate some javascript to produce markers on a Google map.In development , this correctly becomes : However , on our production server , it becomes : Which is producing just a grey Google map . What is causing this strange ToString behavior ? editThe Point class is a custom class , not from a library . Here are the relevant parts : <code> @ foreach ( Point point in Model.Points.Take ( 3 ) ) { String longitude = point.Longitude.ToString ( CultureInfo.InvariantCulture ) ; String latitude = point.Latitude.ToString ( CultureInfo.InvariantCulture ) ; < text > var location = new google.maps.LatLng ( @ ( longitude ) , @ ( latitude ) ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; < /text > } var location = new google.maps.LatLng ( 52.2124273 , 5.9545532 ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; var location = new google.maps.LatLng ( 522124273000 , 59545532000 ) ; bounds.extend ( location ) ; var marker = new google.maps.Marker ( { position : location , map : map } ) ; public class Point { private Double latitude ; private Double longitude ; public Double Latitude { get { return latitude ; } } public Double Longitude { get { return longitude ; } } } | Invalid Double.ToString ( ) result in razor code generating javascript |
C_sharp : Its a well known fact that a static method can work only on static members.Here the Main method is static , but I have n't declared t1 as static . Is it implicitly static ? <code> public static void Main ( ) { Test t1 = new Test ( ) ; } | Are variables in the main methods static |
C_sharp : In short , I am looking for guidance on which of the following two methods should be preferred ( and why ) : Argument in favour of DistinctA : Obviously , the constraint on T is not required , because HashSet < T > does not require it , and because instances of any T are guaranteed to be convertible to System.Object , which provides the same functionality as IEquatable < T > ( namely the two methods Equals and GetHashCode ) . ( While the non-generic methods will cause boxing with value types , that 's not what I 'm concerned about here . ) Argument in favour of DistinctB : The generic parameter constraint , while not strictly necessary , makes visible to callers that the method will compare instances of T , and is therefore a signal that Equals and GetHashCode should work correctly for T. ( After all , defining a new type without explicitly implementing Equals and GetHashCode happens very easily , so the constraint might help catch some errors early . ) Question : Is there an established and documented best practice that recommends when to specify this particular constraint ( T : IEquatable < T > ) , and when not to ? And if not , is one of the above arguments flawed in any way ? ( In that case , I 'd prefer well-thought-out arguments , not just personal opinions . ) <code> static IEnumerable < T > DistinctA < T > ( this IEnumerable < T > xs ) { return new HashSet < T > ( xs ) ; } static IEnumerable < T > DistinctB < T > ( this IEnumerable < T > xs ) where T : IEquatable < T > { return new HashSet < T > ( xs ) ; } | When to specify constraint ` T : IEquatable < T > ` even though it is not strictly required ? |
C_sharp : I 've been asking questions on hex and bitwise manipulation ( here and elsewhere ) for the past week trying to wrap my head around their representation in Java . After much Googling and chagrin I must ask one final time how to perform logical arithmetic on bits that ought to be unsigned , but are represented as signed in Java.Okay : I am porting a C # program to Java . The program deals with bitmap manipulation , and as such much of the data in the app is represented as byte , an unsigned 8-bit integer . There are many suggestions to instead use the short data type in Java in order to `` mimic '' as close as possible the unsigned 8-byte integer.I do n't believe that 's possible for me as the C # code is performing various many shifting and AND operations with my byte data . For example , if data is a byte array , and this block of code exists in C # : It 's not a simple matter of just casting data as a short and being done with it to get it to work in Java . As far as the logic is concerned the requirement that my data stay in 8-bit unsigned is significant ; 16-bit unsigned would screw math like the above up . Am I right here ? Indeed , after having previously `` fake casting '' byte with 0XFF and char in Java and not getting the right results , I am afraid I hit a dead end.Now , in another part of the code , I am performing some bitmap pixel manipulation . Since it 's a long running process , I decided to make a call to native code through JNI . I realized recently that in there I could use the uint8_t data type and get the closest representation to the C # byte data type.Is the solution to make all my data-dependent functionality operate in JNI ? That seems highly inefficient , both to rewrote and to perform . Is the solution to redo the math in Java so the logic remains the same ? That seems right , but has the potential to induce an aneurysm , not to mention faulty math.I appreciate any and all suggestions . <code> int cmdtype = data [ pos ] > > 5 ; int len = ( data [ pos ] & 0x1F ) + 1 ; if ( cmdtype == 7 ) { cmdtype = ( data [ pos ] & 0x1C ) > > 2 ; len = ( ( data [ pos ] & 3 ) < < 8 ) + data [ pos + 1 ] + 1 ; pos++ ; } | Performing bitwise left shifts on `` signed '' data in Java -- better to move to JNI ? |
C_sharp : I was asked today if there was a library to take a list of strings and to compute the most efficient regex to match only those strings . I think it 's an NP Complete problem by itself , but I think we can refine the scope a bit.How would I generate and simplify a regex to match a subset of hosts from a larger set of all hosts on my network ? ( Knowing that I might not get the most efficient regex . ) The first step is easy . From the following list ; appserver1.domain.tldappserver2.domain.tldappserver3.domain.tldI can concatenate and escape them intoAnd I know how to manually simplify the regex intoFrom there I can test that pattern against the full list of hosts and verify that it only matches the selected 3 hosts . What I do n't know is how to automate the simplifying process . Are there any libraries ( in Perl , Javascript or C # ) or common practices ? ThanksUpdate I got some awesome perl modules but I would love a front end solution as well . That means Javascript . I 've searched around but nobody has ported the perl modules to JS and I 'm unsuccessful in finding the language to search for this type of library . <code> appserver1\.domain\.tld|appserver2\.domain\.tld|appserver3\.domain\.tld appserver [ 123 ] \.domain\.tld | Simplifying regex OR patterns |
C_sharp : I 'm trying to get to the bottom of an entity Framework issue when using it with a TableControllerI 've created the following setup.The basic TodoItem example provided with a new Mobile Web API which leverages EntityFramework , TableController & the default EntityDomainManagerA vanilla Web API 2 controller.I 've gone through the tablecontroller code with a fine tooth comb , digging into the Query method , which is just proxying the call via the DomainManager to add in the Where ( _ = > ! _.IsDeleted ) modification to the IQueryableYet the two queries produce VERY different SQL.For the regular Web API Controller , you get the following SQL.But for the TableController , you get the following chunk of SQL which has a *Magic* Guid in the middle of it , and results in a Nested SQL statement . The performance of this goes to complete garbage when you start dealing with any of the ODATAv3 queries like $ top , $ skip , $ filter and $ expand.You can see the results of both queries here . https : //pastebin.com/tSACq6egSo my questions are : Why is the TableController generating the SQL in this way ? What is the *magic* guid in the middle of the query ? ( it will stay the same until I stop and restart the app so I do n't know if it 's session , client or DB context specific ) Where exactly in the pipeline is the TableController making these Modifications to the IQueryable ? I assume it 's done through some middleware step or an on executed attribute later in the request after the Query ( ) method is called , but I can not for the life of me find it . <code> public class TodoItemController : TableController < TodoItem > { protected override void Initialize ( HttpControllerContext controllerContext ) { base.Initialize ( controllerContext ) ; context = new MobileServiceContext ( ) ; context.Database.Log += LogToDebug ; DomainManager = new EntityDomainManager < TodoItem > ( context , Request ) ; } public IQueryable < TodoItem > GetAllTodoItems ( ) { var q = Query ( ) ; return q ; } public class TodoItemsWebController : ApiController { private MobileServiceContext db = new MobileServiceContext ( ) ; public TodoItemsWebController ( ) { db.Database.Log += LogToDebug ; } public IQueryable < TodoItem > GetTodoItems ( ) { return db.TodoItems ; } SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Version ] AS [ Version ] , [ Extent1 ] . [ CreatedAt ] AS [ CreatedAt ] , [ Extent1 ] . [ UpdatedAt ] AS [ UpdatedAt ] , [ Extent1 ] . [ Deleted ] AS [ Deleted ] , [ Extent1 ] . [ Text ] AS [ Text ] , [ Extent1 ] . [ Complete ] AS [ Complete ] FROM [ dbo ] . [ TodoItems ] AS [ Extent1 ] SELECT TOP ( 51 ) [ Project1 ] . [ C1 ] AS [ C1 ] , [ Project1 ] . [ C2 ] AS [ C2 ] , [ Project1 ] . [ C3 ] AS [ C3 ] , [ Project1 ] . [ Complete ] AS [ Complete ] , [ Project1 ] . [ C4 ] AS [ C4 ] , [ Project1 ] . [ Text ] AS [ Text ] , [ Project1 ] . [ C5 ] AS [ C5 ] , [ Project1 ] . [ Deleted ] AS [ Deleted ] , [ Project1 ] . [ C6 ] AS [ C6 ] , [ Project1 ] . [ UpdatedAt ] AS [ UpdatedAt ] , [ Project1 ] . [ C7 ] AS [ C7 ] , [ Project1 ] . [ CreatedAt ] AS [ CreatedAt ] , [ Project1 ] . [ C8 ] AS [ C8 ] , [ Project1 ] . [ Version ] AS [ Version ] , [ Project1 ] . [ C9 ] AS [ C9 ] , [ Project1 ] . [ Id ] AS [ Id ] FROM ( SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Version ] AS [ Version ] , [ Extent1 ] . [ CreatedAt ] AS [ CreatedAt ] , [ Extent1 ] . [ UpdatedAt ] AS [ UpdatedAt ] , [ Extent1 ] . [ Deleted ] AS [ Deleted ] , [ Extent1 ] . [ Text ] AS [ Text ] , [ Extent1 ] . [ Complete ] AS [ Complete ] , 1 AS [ C1 ] , N'804f84c6-7576-488a-af10-d7a6402da3bb ' AS [ C2 ] , N'Complete ' AS [ C3 ] , N'Text ' AS [ C4 ] , N'Deleted ' AS [ C5 ] , N'UpdatedAt ' AS [ C6 ] , N'CreatedAt ' AS [ C7 ] , N'Version ' AS [ C8 ] , N'Id ' AS [ C9 ] FROM [ dbo ] . [ TodoItems ] AS [ Extent1 ] ) AS [ Project1 ] ORDER BY [ Project1 ] . [ Id ] ASC | Why is Entity Framework generating the following nested SQL for Azure Mobile Services Table Controllers |
C_sharp : I am rendering my game in a Winform in the same way as done in this sample : WinForms Series 1 : Graphics Device In my game I have some object , for example a rectangle that I can already put and move , in my game world , once created . My project here is a level-editor.What I want to do is to make every object `` sizable '' or `` scalable '' ( sorry if this is n't the correct word ) in the same way as done in every software we commonly use , I mean : I have a class like : Once the class is instantiated , inside the form I thought to do something like : ( gameWrapper is the control created with the sample to draw the game inside the form ) Inside gameWrapper : This is just what I thought to do . Draw little buttons/rectangles with a function and then handle clicks to them.Is there already written some code to achieve this behaviour ? Actually I 'm not worried about how the object will resize , but just to the estetic buttons . <code> public abstract class GameObject { protected Vector2 position_ = Vector2.Zero ; protected float rotation_ = 0.0f ; protected Vector2 scale_ = Vector2.One ; protected float depth_ = 0.0f ; protected bool is_passable_ = true ; protected GameObject ( Vector2 starting_position ) { this.position_ = starting_position ; } [ DisplayName ( `` Position '' ) ] public virtual Vector2 Position { get { return position_ ; } set { position_ = value ; } } [ BrowsableAttribute ( false ) ] public abstract Rectangle PositionRectangle { get ; } [ BrowsableAttribute ( false ) ] public abstract Rectangle SelectionRectangle { get ; } [ DisplayName ( `` Scale '' ) ] public abstract Vector2 Scale { get ; set ; } [ BrowsableAttribute ( false ) ] public virtual float Depth { get { return depth_ ; } set { depth_ = value ; } } [ DisplayName ( `` IsPassable ? '' ) ] public bool IsPassable { get { return is_passable_ ; } set { is_passable_ = value ; } } [ BrowsableAttribute ( false ) ] public abstract Vector2 TextureSize { get ; } public abstract void Update ( GameTime gameTime ) ; public abstract void Draw ( SpriteBatch spriteBatch ) ; } private void gameWrapper_MouseClick_1 ( object sender , MouseEventArgs e ) { Vector2 mouse_xy = new Vector2 ( e.Location.X , e.Location.Y ) ; GameObject obj = gameWrapper.GetObjectByPosition ( mouse_xy ) ; propertyGrid1.SelectedObject = obj ; if ( obj ! = null ) gameWrapper.SelectObject ( obj ) ; else gameWrapper.Unselect ( ) ; propertyGrid1.Refresh ( ) ; } public SelectObject ( GameObject obj ) { List < Vector2 > 4verticesList = new List ( ) ; // // Code to add 4 vertices coordinates of the SelectionRectangle to 4verticesList // foreach ( Vector2 vertex_xy in 4VerticesList ) DrawLittleRectangle ( vertex_xy ) ; } | How to make an object `` scalable '' while rendered in a form |
C_sharp : Consider the following example : This compiles well.I wonder why can not I remove < string > generic argument ? I get an error that it can not be inferred from the usage.I understand that such an inference might be challenging for the compiler , but nevertheless it seems possible.I would like an explanation of this behaviour.Edit answering Jon Hanna 's answer : Then why this works ? Here I bind only one parameter with T1 a , but T2 seems to be similarly difficult . <code> class Test { public void Fun < T > ( Func < T , T > f ) { } public string Fun2 ( string test ) { return `` '' ; } public Test ( ) { Fun < string > ( Fun2 ) ; } } class Test { public void Fun < T1 , T2 > ( T1 a , Func < T1 , T2 > f ) { } public string Fun2 ( int test ) { return test.ToString ( ) ; } public Test ( ) { Fun ( 0 , Fun2 ) ; } } | `` Two-level '' generic method argument inference with delegate |
C_sharp : A fairly common idiom in C is for functions taking a polymorphic closure to represent this as two arguments , a function pointer and void pointer ( which is passed as one of the arguments to the function pointer . An example taken from the GPGME library : Conceptually , the function pointer plus void pointer represent the same thing as a delegate in C # ( a closure ) . Is there a nice , canonical way to marshal a delegate when making this sort of P/Invoke call ? <code> typedef gpgme_error_t ( *gpgme_passphrase_cb_t ) ( void *hook , const char *uid_hint , const char *passphrase_info , int prev_was_bad , int fd ) ; void gpgme_set_passphrase_cb ( gpgme_ctx_t ctx , gpgme_passphrase_cb_t cb , void *hook_value ) ; | P/Invoke - Marshaling delegate as function pointer + void* |
C_sharp : I run into this frequently enough that I thought I 'd see what others had to say about it . Using the StyleCop conventions , I find that I often have a property name that is hard to make different than the class name it is accessing . For example : It compiles and runs , but seems like it would be an easy way to confuse things , even with the use of `` this '' . <code> public class ProjectManager { // Stuff here } public class OtherClass { private ProjectManager ProjectManager { get ; set ; } } | What is a good naming convention to differentiate a class name from a property in C # ? |
C_sharp : A few years back , I got an assignment at school , where I had to parallelize a Raytracer.It was an easy assignment , and I really enjoyed working on it.Today , I felt like profiling the raytracer , to see if I could get it to run any faster ( without completely overhauling the code ) . During the profiling , I noticed something interesting : According to the profiler , 25 % of the CPU time was spent on get_Dir and get_Pos , which is why , I decided to optimize the code in the following way : With astonishing results.In the original code , running the raytracer with its default arguments ( create a 1024x1024 image with only direct lightning and without AA ) would take ~88 seconds.In the modified code , the same would take a little less than 60 seconds.I achieved a speedup of ~1.5 with only this little modification to the code.At first , I thought the getter for Ray.Dir and Ray.Pos were doing some stuff behind the scene , that would slow the program down.Here are the getters for both : So , both return a Vector3D , and that 's it.I really wonder , how calling the getter would take that much longer , than accessing the variable directly.Is it because of the CPU caching variables ? Or maybe the overhead from calling these methods repeatedly added up ? Or maybe the JIT handling the latter case better than the former ? Or maybe there 's something else I 'm not seeing ? Any insights would be greatly appreciated.Edit : As @ MatthewWatson suggested , I used a StopWatch to time release builds outside of the debugger . In order to get rid of noise , I ran the tests multiple times . As a result , the former code takes ~21 seconds ( between 20.7 and 20.9 ) to finish , whereas the latter only ~19 seconds ( between 19 and 19.2 ) .The difference has become negligible , but it is still there . <code> // Sphere.Intersect public bool Intersect ( Ray ray , Intersection hit ) { double a = ray.Dir.x * ray.Dir.x + ray.Dir.y * ray.Dir.y + ray.Dir.z * ray.Dir.z ; double b = 2 * ( ray.Dir.x * ( ray.Pos.x - Center.x ) + ray.Dir.y * ( ray.Pos.y - Center.y ) + ray.Dir.z * ( ray.Pos.z - Center.z ) ) ; double c = ( ray.Pos.x - Center.x ) * ( ray.Pos.x - Center.x ) + ( ray.Pos.y - Center.y ) * ( ray.Pos.y - Center.y ) + ( ray.Pos.z - Center.z ) * ( ray.Pos.z - Center.z ) - Radius * Radius ; // more stuff here } // Sphere.Intersect public bool Intersect ( Ray ray , Intersection hit ) { Vector3d dir = ray.Dir , pos = ray.Pos ; double xDir = dir.x , yDir = dir.y , zDir = dir.z , xPos = pos.x , yPos = pos.y , zPos = pos.z , xCen = Center.x , yCen = Center.y , zCen = Center.z ; double a = xDir * xDir + yDir * yDir + zDir * zDir ; double b = 2 * ( xDir * ( xPos - xCen ) + yDir * ( yPos - yCen ) + zDir * ( zPos - zCen ) ) ; double c = ( xPos - xCen ) * ( xPos - xCen ) + ( yPos - yCen ) * ( yPos - yCen ) + ( zPos - zCen ) * ( zPos - zCen ) - Radius * Radius ; // more stuff here } public Vector3d Pos { get { return _pos ; } } public Vector3d Dir { get { return _dir ; } } | Why is a simple get-statement so slow ? |
C_sharp : I am working on a runtime composite resource library for ASP.NET WebForms/MVC . I support both standard ASP.NET WebForms via WebControls and have also recently added support for ASP MVC Html Helpers . One feature that I currently support with the WebForms WebControls is the concept of `` Partial '' resource definitions where a resource can be combined over the Master/View pages etc . When implementing the MVC equivalent , I am not sure what the best practise is ? I am currently leaning towards a design something like : Master PageWhich will create a `` context '' wrapper around the head ContentPlaceholder . View PageSo any view pages can extend the partial resource definition as seen above.The questions I have:1 ) Unlike all my other HtmlHelpers , these extensions do not immediately write out the HTML fragment but rather wait until the context is disposed . Should these extensions be off the ViewContext instead ( or some other object ) ? 2 ) I personally think the concept of a `` using '' makes sense to wrap a block of code rather than separate BeginCompositeResourcePartContext/EndCompositeResourcePartContext calls , would you agree ? If no , what is better about separate method calls ? Any feedback on the above would be greatly appreciated . If more detail is required , please let me know.Edit To clarify ... the block inside the head of the Master page and the subsequent reference in side a view page will be combined together in to a single resource . So when the context of CompositeResourcePartContext is disposed , all SIX files are combined in to only ONE css file and written out as a single link TAG ( or script , css sprite etc ) <code> < % using ( Html.CreateCompositeResourcePartContext ( ) ) { Html.CompositeCssResourcePart ( `` ResourceName '' , new [ ] { `` /Styles/SharedStyle1.css '' , `` /Styles/SharedStyle2.css '' } ) ; % > < asp : ContentPlaceHolder ID= '' head '' runat= '' server '' > < /asp : ContentPlaceHolder > < % } % > < asp : Content ID= '' HeadContentPlaceholder '' ContentPlaceHolderID= '' head '' runat= '' server '' > < % Html.CompositeCssResourcePart ( `` ResourceName '' , new [ ] { `` /Styles/PageStyle5.css '' , `` /Styles/PageStyle6.css '' , `` /Styles/PageStyle7.css '' } ) % > < /asp : Content > < link rel= '' stylesheet '' type= '' text/css '' href= '' /MyMergedStyleSheet.css '' / > | Help with ASP.NET MVC HtmlHelper API Design |
C_sharp : I 've been working with DDD for a few months now and I 've come across a few things I 'm unsure of . Take the simplistic example of adding a Product to an Order object . From our Controller , we 'd have an int passed via the UI which represents a Product in the database . Which of the following two examples is correct ( let me know if they 're both wrong ) ? Example One : The Controller instantiates the Product itself and adds it in via the method : Example Two : The Order domain model has the injected product repository passed to it and it gets the Product and adds it : I 've currently gone for the first example , because your Domain Model should never call a service method internally , however I 've seen a few examples lately that use my second example and it does look tidy . It seems to me that Example One is verging on Anaemic . Example Two would move all the Product addition logic into the Domain Model itself . <code> public class OrderController { // Injected Repositories private readonly IProductRepository _productRepository ; // Called by UI public void AddProduct ( int productId ) { Order order = ... ; // Persisted Order Product product = _productRepository.GetProduct ( productId ) ; order.AddProduct ( product ) ; } } void AddProduct ( Product product ) { productList.Add ( product ) ; } public class OrderController { // Injected Repositories private readonly IProductRepository _productRepository ; // Called by UI public void AddProduct ( int productId ) { Order order = ... ; // Persisted Order order.AddProduct ( productId , _productRepository ) ; } } Product AddProduct ( int productId , IProductRepository productRepository ) { Product product = productRepository.GetProduct ( productId ) ; productList.Add ( product ) ; return product ; } | Which of these examples represent correct use of DDD ? |
C_sharp : A colleague has passed me an interesting code sample that crashes with an InvalidProgramException ( `` CLR detected an Invalid Program '' ) when run.The problem seems to occur at JIT time , in that this compiles fine but throws the exception just before the method with the `` offending '' line is called - I guess as it is being JIT'd.The line in question is calling Enumerable.ToDictionary and passing in a Func as the second argument.If the Func argument is fully specified with a lambda it works ; if it is specified as a method group , if fails . Surely these two are equivalent ? This has me stumped ( and the colleague who discovered it ! ) - and it certainly seems like a JIT error . [ EDIT : Sorry - I got the pass and fail cases the wrong way round in the code sample - now corrected ( description above was correct ) ] Does anyone have an explanation ? <code> using System ; using System.Linq ; internal class Program { private static void Main ( string [ ] args ) { Test.Try ( ) ; } } public class Test { public static readonly int [ ] integers = new [ ] { 1 , 3 , 5 } ; public static void Try ( ) { var line = new Line { A = 3 , B = 5 } ; // PASSES var dict = integers.ToDictionary < int , int , decimal > ( i = > i , i = > line.Compute ( i ) ) ; // FAILS //var dict = integers.ToDictionary < int , int , decimal > ( i = > i , line.Compute ) ; Console.WriteLine ( string.Join ( `` `` , dict.Select ( kv = > kv.Key + `` - '' + kv.Value ) ) ) ; } } public class Line { public decimal A ; public decimal B ; } public static class SimpleCompute { public static decimal Compute ( this Line line , int value ) { return line.A*value + line.B ; } } | `` CLR detected an Invalid Program '' when using Enumerable.ToDictionary with an extension method |
C_sharp : I 'm working on a project that needs to support both async and sync version of a same logic/method . So for example I need to have : The async and sync logic for these methods are identical in every respect except that one is async and another one is not . Is there a legitimate way to avoid violating the DRY principle in this kind of a scenario ? I saw that people say you could use GetAwaiter ( ) .GetResult ( ) on an async method and invoke it from your sync method ? Is that thread safe in all scenarios ? Is there another , better way to do this or am I forced to duplicate the logic ? <code> public class Foo { public bool IsIt ( ) { using ( var conn = new SqlConnection ( DB.ConnString ) ) { return conn.Query < bool > ( `` SELECT IsIt FROM SomeTable '' ) ; } } public async Task < bool > IsItAsync ( ) { using ( var conn = new SqlConnection ( DB.ConnString ) ) { return await conn.QueryAsync < bool > ( `` SELECT IsIt FROM SomeTable '' ) ; } } } | How to avoid violating the DRY principle when you have to have both async and sync versions of code ? |
C_sharp : I have an empty list defined to hold 120 values , I want to insert an element at index ( 45 ) , even though the list is currently empty . Is this possible ? <code> public List < Ticket > Tickets = new List < Ticket > ( 120 ) ; Tickets.Insert ( 45 , ticket ) ; // Here I am getting the ArgumentOutOfRangeException | How to Insert an object in a list at custom index |
C_sharp : I upgraded ReSharper and seeing an error that I was not present previously . I checked around , but found nothing about the error or the underlying issue it is flagging . ** Edit ** : as pointed out below , it is actually the 'Heap Allocation Viewer ' plugin , not ReSharper itself that is marking it as an error -- though that does n't change the question itself . Slow delegate creation : from interface 'IPluginHandler ' methodthis occurs during the subscription of a plugin handler to events on an event aggregator.in the above code , Executing is an event and subscriber.OnExecuting is an appropriate event handler for the event.To be clear , this is a ReSharper 'soft error ' as the code will still build and run as expected.So my question is what is the underlying issue the good people at JetBrains are flagging for me and what are the ramifications of it.Thanks <code> public void Subscribe ( IPluginHandler subscriber ) { Executing += subscriber.OnExecuting ; // -- additional subscriptions -- } | Slow delegate creation |
C_sharp : On our application we have a clickable label which will pop up another window . I have been reading through the Microsoft Automation UI documentation , and ca n't find a way in which I 'm able to click a label control.I know that I ca n't use the Invoke Pattern as this only deals with Button controls.Below is the code from the XAML that we have <code> < Label Name= '' LblCompleteOrdersCount '' Content= '' { Binding CompleteOrders , Mode=OneWay } '' Margin= '' 434,45,0,0 '' Height= '' 62 '' Width= '' 170 '' Padding= '' 0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' VerticalContentAlignment= '' Top '' FontSize= '' 56 '' FontWeight= '' Bold '' > < Label.InputBindings > < MouseBinding Command= '' { Binding Path=CompleteOrdersCommand } '' MouseAction= '' LeftClick '' / > < /Label.InputBindings > < /Label > | Is it possible to Click a label control on WPF/WinForm App using Microsoft Automation UI |
C_sharp : For the purpose of learning , I 'm trying to understand how C # strings are internally stored in memory.According to this blog post , C # string size is ( x64 with .NET framework 4.0 ) : A string with a single character will take ( 26 + 2 * 1 ) / 8 * 8 = 32 bytes .This is indeed similar to what I measured.What puzzle me is what is in that 26 bytes overhead.I have run the following code and inspected memory : AFAIK those blocks are the following : Green : Sync block ( 8 bytes ) Cyan : Type info ( 8 bytes ) Yellow : Length ( 4 bytes ) Pink : The actual characters : 2 bytes per char + 2 bytes for NULL terminator . Look at the `` x '' string . It is indeed 32 bytes ( as calculated ) .Anyway it looks like the end of the string if padded with zeroes.The `` x '' string could end up after the two bytes for NULL terminator and still be memory aligned ( thus being 24 bytes ) .Why do we need an extra 8 bytes ? I have experimented similar results with other ( bigger ) string sizes . It looks like there is always an extra 8 bytes . <code> 26 + 2 * length string abc = `` abcdeg '' ; string aaa = `` x '' ; string ccc = `` zzzzz '' ; | How many bytes does a string take up in x64 ? |
C_sharp : I am tring to open memory mapped file in the system volume information subfolder . I know and see in explorer that it is exists there , and path is correct ( it is copy-pasted from explorer ) , moreover File.Exists for that path returns true , but MemoryMappedFile.OpenExisting fails with DirectoryNotFoundException . Why ? ( I have all rights to system volume information folder and subfolders ) .Some code : <code> const string filePath = @ '' C : \\System Volume Information\\Foo\\2.ext '' ; bool exists = File.Exists ( filePath ) ; //is trueusing ( MemoryMappedFile bitmapFile = MemoryMappedFile.OpenExisting ( filePath , MemoryMappedFileRights.Read ) ) //Throws DirectoryNotFoundException { ... } | File.Exists returns true and OpenExisting fails with DirectoryNotFoundException |
C_sharp : Ca n't find simple way to convert double to string . I need to convert large numbers without distortion . Such as : How to get string value from double value exactly the same as user enter.11111111111111111111111 = > `` 11111111111111111111111 '' 1.111111111111111111111 = > `` 1.111111111111111111111 '' Any ideas how it can be done ? <code> double d = 11111111111111111111 ; string s = d.ToString ( ) ; Console.WriteLine ( s ) ; //1.11111111111111E+19 | Get string from large double value ( C # ) |
C_sharp : I 'm hoping for a concise way to perform the following transformation . I want to transform song lyrics . The input will look something like this : And I want to transform them so the first line of each verse is grouped together as in : Lyrics will obviously be unknown , but the blank line marks a division between verses in the input . <code> Verse 1 lyrics line 1Verse 1 lyrics line 2Verse 1 lyrics line 3Verse 1 lyrics line 4Verse 2 lyrics line 1Verse 2 lyrics line 2Verse 2 lyrics line 3Verse 2 lyrics line 4 Verse 1 lyrics line 1Verse 2 lyrics line 1Verse 1 lyrics line 2Verse 2 lyrics line 2Verse 1 lyrics line 3Verse 2 lyrics line 3Verse 1 lyrics line 4Verse 2 lyrics line 4 | Tricky string transformation ( hopefully ) in LINQ |
C_sharp : I was wondering if it is possible to reference a dynamic generic class name in a comment and have it conditionally resolved in the IDE ? Simple base class example : If I now inherit from this class and happens to be class User then I 'd like to have IntelliSense show my comment as `` Retrieves all User members from the database '' .Is this possible ? <code> // < summary > // Retrieves all < T > members from the database.// < /summary > public void GetAll < T > ( ) { //magic } | Reference generic comment |
C_sharp : Question : given IEnumerable < > , how to check what sequence contains more than x items ? MCVE : The problem here is what Count ( ) will run complete sequence and that 's 1E6+ items ( ToList ( ) is also bad idea ) . I am also not allowed to change consumer code ( it 's a method accepting complete sequence ) . <code> static void Main ( string [ ] args ) { var test = Test ( ) .Where ( o = > o > 2 & & o < 6 ) ; // ToList ( ) if ( test.Count ( ) > 1 ) // how to optimize this ? foreach ( var t in test ) // consumer Console.WriteLine ( t ) ; } static IEnumerable < int > Test ( ) { for ( int i = 0 ; i < 10 ; i++ ) yield return i ; } | Optimize LINQ Count ( ) > X |
C_sharp : I 'm writing a filter function to return the specific type specified out of a larger collection of supertypes ( objects for example ) . The idea is I give you an enumerable and you return me all the strings for example . you can write it this way without generics : if we want to return generics there are a few different ways to go about it.As a straight port : Pass in an 'example ' : Ultimately what I think is cleanest : The second type would be called entirely with parameters ( and infer the type ) : where as the final version there would get called with a type specifier : What is the appropriate way to strongly type the return of a generic function , where the return type is n't automatically implied in the signature ? ( why ? ) ( Edit Note : Our input is NOT typed , e.g . IEnumerable < T > . At best it would be IEnumerable . This function is returning the Ts out of the whole collection of other types . ) <code> public static IEnumerable Filter ( IEnumerable source , Type type ) { List < object > results = new List < object > ( ) ; foreach ( object o in source ) { if ( o ! = null & & o.GetType ( ) == type ) { results.Add ( o ) ; } } return results ; } public static IEnumerable < TResult > Filter < TResult > ( IEnumerable source , Type type ) IEnumerable < TResult > Filter < TResult > ( IEnumerable source , TResult resultType ) public static IEnumerable < T > Filter < T > ( IEnumerable source ) Filter ( myList , `` exampleString '' ) ; Filter < string > ( myList ) ; | What is the appropriate way to strongly type the return of a generic function ? |
C_sharp : Can someone explain to me why I can not seem to throw an exception from inside the AppDomain.Assembly load event ? For example : When I execute this , the output is as follows : Can anyone explain this behavior to me ? Thank you.EDIT To clarify a couple things : The assembly load event runs fine , when I expect it to run . But my exception never gets thrownThis is a distilled example taken from a larger application . I want to inspect the assembly after it is loaded and if I do n't like something about it , I want to fail fast ... But my exception does n't 'happen ' <code> class Program { static Program ( ) { AppDomain.CurrentDomain.UnhandledException += ( s , a ) = > { Console.WriteLine ( `` Caught exception ! `` ) ; } ; AppDomain.CurrentDomain.AssemblyLoad += ( s , a ) = > { Console.WriteLine ( string.Format ( `` Assembly { 0 } loaded '' , a.LoadedAssembly.FullName ) ) ; throw new Exception ( ) ; Console.WriteLine ( `` Should never get here ... '' ) ; } ; } static void Main ( string [ ] args ) { Console.WriteLine ( new ClassLibrary1.Class1 ( ) .TestString ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Done ... '' ) ; Console.ReadLine ( ) ; } } Assembly ClassLibrary1 , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null loadedTestStringDone ... | Throw exception from AppDomain.AssemblyLoad event |
C_sharp : i tried this code but it takes so long and I can not get the resultplease help <code> public long getCounter ( [ FromBody ] object req ) { JObject param = Utility.GetRequestParameter ( req ) ; long input = long.Parse ( param [ `` input '' ] .ToString ( ) ) ; long counter = 0 ; for ( long i = 14 ; i < = input ; i++ ) { string s = i.ToString ( ) ; if ( s.Contains ( `` 14 '' ) ) { counter += 1 ; } } return counter ; } | how many numbers between 1 to 10 billion contains 14 |
C_sharp : Suppose we have a nested generic class : Here , typeof ( A < int > .B < > ) is in essence a generic class with two parameters where only the first is bound.If I have a single class with two parametersIs there a way to refer to `` AB with T=int and U staying open '' ? If not , is this a C # limitation , or a CLR limitation ? <code> public class A < T > { public class B < U > { } } public class AB < T , U > { } | Does .Net support curried generics ? |
C_sharp : I have a dll wich expose a type like inside this library I also have an IPackage implementation which register the MyDbContext in the container like This assembly is then referenced from two different types of applications : - a web api project - an asp.net mvc applicationThis is the initialization of the web api projectand this is the initialization of the mvc applicationWhen I receive a message from a Rebus queue ( in the mvc application ) the container try to instatiate a message handler like this but I receive an error saying Rebus.Retry.ErrorTracking.InMemErrorTracker - Unhandled exception 1 while handling message with ID 85feff07-01a6-4195-8deb-7c8f1b62ecc3 : SimpleInjector.ActivationException : The MyDbContext is registered as 'Web Request ' lifestyle , but the instance is requested outside the context of an active ( Web Request ) scope.with the following stack traceI have also tried to setup the Async Scoped Lifestyle in the mvc application but the error is substantially the same . <code> public class MyDbContext { [ ... ] } public void RegisterServices ( Container container ) { container.Register < MyDbContext > ( Lifestyle.Scoped ) ; } var container = new Container ( ) ; container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle ( ) ; InitializeContainer ( container ) ; container.RegisterWebApiControllers ( GlobalConfiguration.Configuration ) ; container.Verify ( ) ; var container = new Container ( ) ; container.Options.DefaultScopedLifestyle = new WebRequestLifestyle ( ) ; InitializeContainer ( container ) ; container.RegisterMvcControllers ( Assembly.GetExecutingAssembly ( ) ) ; container.Verify ( ) ; public class MyHandler : BaseMessageHandler , IHandleMessages < MyMessage > , IHandleMessages < IFailed < MyMessage > > { public MyHandler ( ILog logger , MyDbContext context ) { _logger = logger ; _context = context ; } } at SimpleInjector.Scope.GetScopelessInstance [ TImplementation ] ( ScopedRegistration ` 1 registration ) at SimpleInjector.Scope.GetInstance [ TImplementation ] ( ScopedRegistration ` 1 registration , Scope scope ) at SimpleInjector.Advanced.Internal.LazyScopedRegistration ` 1.GetInstance ( Scope scope ) at lambda_method ( Closure ) at SimpleInjector.InstanceProducer.GetInstance ( ) at SimpleInjector.Container.GetInstance [ TService ] ( ) | DbContext creation into message handler |
C_sharp : I 'm trying to create a shortcut ( .lnk ) on my windows filesystem.The code I have is working fine . However , when I run the same console application on a Windows 2008R2 Server , it acts differently.So I have my console application and here is what happens : My program simply creates a shortcut on the desktop with a .docx extension and all goes fine on my local machine . When I run the same console application on my Server , it creates the same shortcut but the target got modified ... it changed the target to a .doc file . In other words , when I run the console app : LocalMachine Creates MyWordFile.lnk pointing to U : \test.docxServer Creates MyWordFile.lnk pointing to U : \test.docThis is strange behaviour . Here is the codeCodeUpdate I noticed that the 4th character gets removed from the target 's extension . So , when i have a file `` file.abcdef '' , the link points at `` file.abc '' . Also spaces get replaced for underscores , so `` my file.abcd '' pointer becomes `` my_file.abc '' <code> using System ; using System.IO ; using System.Runtime.InteropServices ; using System.Runtime.InteropServices.ComTypes ; using System.Text ; namespace TestShortcut { class Program { static void Main ( string [ ] args ) { //ShortcutTarget var sTarget = @ '' U : \test.docx '' ; //ShortCutName var sName = @ '' MyWordFile.lnk '' ; IShellLink link = ( IShellLink ) new ShellLink ( ) ; link.SetPath ( sTarget ) ; IPersistFile file = ( IPersistFile ) link ; string desktopPath = Environment.GetFolderPath ( Environment.SpecialFolder.DesktopDirectory ) ; file.Save ( Path.Combine ( desktopPath , sName ) , false ) ; } } [ ComImport ] [ Guid ( `` 00021401-0000-0000-C000-000000000046 '' ) ] internal class ShellLink { } [ ComImport ] [ InterfaceType ( ComInterfaceType.InterfaceIsIUnknown ) ] [ Guid ( `` 000214F9-0000-0000-C000-000000000046 '' ) ] internal interface IShellLink { void GetPath ( [ Out , MarshalAs ( UnmanagedType.LPWStr ) ] StringBuilder pszFile , int cchMaxPath , out IntPtr pfd , int fFlags ) ; void GetIDList ( out IntPtr ppidl ) ; void SetIDList ( IntPtr pidl ) ; void GetDescription ( [ Out , MarshalAs ( UnmanagedType.LPWStr ) ] StringBuilder pszName , int cchMaxName ) ; void SetDescription ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszName ) ; void GetWorkingDirectory ( [ Out , MarshalAs ( UnmanagedType.LPWStr ) ] StringBuilder pszDir , int cchMaxPath ) ; void SetWorkingDirectory ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszDir ) ; void GetArguments ( [ Out , MarshalAs ( UnmanagedType.LPWStr ) ] StringBuilder pszArgs , int cchMaxPath ) ; void SetArguments ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszArgs ) ; void GetHotkey ( out short pwHotkey ) ; void SetHotkey ( short wHotkey ) ; void GetShowCmd ( out int piShowCmd ) ; void SetShowCmd ( int iShowCmd ) ; void GetIconLocation ( [ Out , MarshalAs ( UnmanagedType.LPWStr ) ] StringBuilder pszIconPath , int cchIconPath , out int piIcon ) ; void SetIconLocation ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszIconPath , int iIcon ) ; void SetRelativePath ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszPathRel , int dwReserved ) ; void Resolve ( IntPtr hwnd , int fFlags ) ; void SetPath ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string pszFile ) ; } } | Creating shortcut modifies the path to target |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.