text
stringlengths
46
37.3k
title
stringlengths
12
162
C_sharp : I have a model which has is below and when I add ComboProducts object with the linq below I am getting the error . Is there something I am missing in this code ? Errorappears in two structurally incompatible initializations within a single LINQ to Entities query . A type can be initialized in two places in the same query , but only if the same properties are set in both places and those properties are set in the same order.ModelCode <code> public class Product { public int ProductId { get ; set ; } public string Name { get ; set ; } public List < Product > ComboProducts { get ; set ; } } ListOfProducts = ( from p in db.Products join ptp in db.ProductToProducts on p.ProductId equals ptp.ParentProductId join pr in db.Pricings on ptp.ProductToProductId equals pr.ProductToProductId where p.SubProductTypeId == ( int ) SubProductTypeId select new Model.Product { ProductId = p.ProductId , Name = p.Name , PreviewUrl = p.PreviewURL , ShortName = p.ShortName , Description = p.Description , PublicProduct = p.PublicProduct , Price = pr.Price , ComboProducts = ( from ptpx in db.ProductToProducts join ap in db.Products on ptpx.ChildProductId equals ap.ProductId where ptpx.ParentProductId == p.ProductId select new Model.Product { Name = ap.Name , ProductId = ap.ProductId } ) .OrderBy ( p2 = > p2.Name ) .ToList ( ) , DisplayOrder = p.DisplayOrder ! = null ? ( int ) p.DisplayOrder : 0 } ) .GroupBy ( grp = > new { grp.ProductId } ) .Select ( x = > x.FirstOrDefault ( ) ) .ToList ( ) ; return ListOfProducts ;
Error with two structurally incompatible initializations within a single LINQ
C_sharp : I am using .Replace ( ) method to replace a placeholder [ CITY ] in arabic language.I get the following output As you can see the city instead of being placed next to ABC is added at the extreme right.This issue happens only for arabic and works fine for other languages ( english/thai/spanish etc ) Not sure whats going wrong here.C # fiddle - https : //dotnetfiddle.net/mvIcHt <code> public static void Main ( ) { Console.WriteLine ( `` Hello World '' ) ; var replace = `` سنغافورة '' ; var input = `` ABC [ CITY ] مرحبا بالعالم '' ; Console.WriteLine ( input ) ; var final = input.Replace ( `` [ CITY ] '' , replace ) ; Console.WriteLine ( final ) ; } ABC [ CITY ] مرحبا بالعالمABC سنغافورة مرحبا بالعالم
C # .Replace ( ) method does not work correctly with Arabic language
C_sharp : Is there any point in doing this ? ... as supposed to this : Setting aside the obvious null dereference possibility , If I where to write a lot of value types using this method would n't the former be much better because it will have it 's own version of the write method to call , or is it just gon na bloat the binary in terms of a lot of additional code being generated ? The performance implication of such a thing might be negligible , but I 'm curious , it 's a lot more compact than providing an overload for each and every value type in the BCL , like most writers in the BCL already do . <code> public static void Write < T > ( T value ) { textWriter.Write ( value.ToString ( ) ) ; } public static void Write ( object value ) { textWriter.Write ( value.ToString ( ) ) ; }
Boxing , a thing of the past ?
C_sharp : My question is simple , why GC ca n't figure it out that timer object in the main should be garbage collected along with the timer inside TestTimer and associated EventHandler ? Why am I continously getting console.Writeline output ? <code> class Program { public static void Main ( ) { TestTimer timer = new TestTimer ( ) ; timer = null ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.ReadKey ( ) ; } } public class TestTimer { private Timer timer ; public TestTimer ( ) { timer = new Timer ( 1000 ) ; timer.Elapsed += new ElapsedEventHandler ( timer_Elapsed ) ; timer.Start ( ) ; } private void timer_Elapsed ( Object sender , ElapsedEventArgs args ) { Console.Write ( `` \n '' + DateTime.Now ) ; } }
Why ca n't GC figure it out ?
C_sharp : I am not a Java programmer . I read the documentation on `` final '' , and understand it to mean `` a variable 's value may be set once and only once . `` I am translating some Java to C # . The code does not execute as expected . I tried to figure out why , and found some uses of final that do n't make sense.Code snippet 1 : Will PRED [ 1 ] be 0 or 3 ? Code snippet 2 : Surely PRED [ 0 ] will remain as 0 ? <code> final int [ ] PRED = { 0 , 0 , 0 } ; ... PRED [ 1 ] = 3 ; final int [ ] PRED = new int [ this.Nf ] ; for ( int nComponent = 0 ; nComponent < this.Nf ; nComponent++ ) { PRED [ nComponent ] = 0 ; } ... PRED [ 1 ] = 3 ;
Understanding Java 's `` final '' for translation to C #
C_sharp : I have this method : What I would like to do is to delete from three tables that are here : Is there a delete function in EF6 that I can use to delete all the rows or should I somehow make a SQL call ? <code> [ Route ( `` Delete '' ) ] public IHttpActionResult Delete ( ) { } public System.Data.Entity.DbSet < SampleSentence > SampleSentences { get ; set ; } public System.Data.Entity.DbSet < Synonym > Synonyms { get ; set ; } public System.Data.Entity.DbSet < WordForm > WordForms { get ; set ; }
How can I delete rows from tables using EF when inside an Asp.Net method ?
C_sharp : BackgroundI have a couple of utility methods I would like to add to a solution on which I am working and use of dependency injection would open many more potential uses of said methods.I am using C # , .NET 4Here is an example of what I am trying to accomplish ( this is just an example ) : What I have done here is create a method to test the performance of certain elements of my code when debugging . Here is an example of how you would use it : QuestionThe `` PerformanceTest '' method expects to be passed ( injected ) a function of known type . But what if I want `` PerformanceTest '' to allow injection of various functions that return various types ? How do I do that ? <code> public static void PerformanceTest ( Func < ? ? ? > func , int iterations ) { var stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; for ( int i = 0 ; i < iterations ; i++ ) { var x = func ( ) ; } stopWatch.Stop ( ) ; Console.WriteLine ( stopWatch.ElapsedMilliseconds ) ; } Utilities.PerformanceTest ( someObject.SomeCustomExtensionMethod ( ) ,1000000 ) ;
How do I write a C # method that will accept an injected dependency of unknown type ?
C_sharp : This is normal LINQ , and this Test succeeds : But when you insert the data into a database and try to do the same when using LINQ to Entities , it seems like the resulting SQL is the same , regardless of the sorting you apply.Can somebody please help me ? - > Please show me how to keep my sorting when grouping when using LINQ to Entities . <code> using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Collections.Generic ; using System.Linq ; namespace TestLINQ.Tests { [ TestClass ] public class UnitTest2 { [ TestMethod ] public void TestGroupingAndOrdering ( ) { var persons = GetTestPersons ( ) ; //Try get oldest Man and oldest Woman . var Oldest = persons .Where ( p = > p.Sex == TestGender.Male || p.Sex == TestGender.Female ) .OrderBy ( p = > p.DateOfBirth ) .GroupBy ( p = > p.Sex ) .Select ( g = > g.First ( ) ) ; //Try get youngest Man and youngest Woman . var youngest = persons .Where ( p = > p.Sex == TestGender.Male || p.Sex == TestGender.Female ) .OrderByDescending ( p = > p.DateOfBirth ) //reversed sorting . .GroupBy ( p = > p.Sex ) .Select ( g = > g.First ( ) ) ; Assert.AreEqual ( Oldest.ToList ( ) .Count , 2 ) ; Assert.AreEqual ( youngest.ToList ( ) .Count , 2 ) ; Assert.AreEqual ( Oldest.First ( ) .Name , `` Navya '' ) ; //Oldest Woman Assert.AreEqual ( Oldest.Last ( ) .Name , `` Pranav '' ) ; //Oldest Man ( Note : last ( ) gets the second grouping ) Assert.AreEqual ( youngest.First ( ) .Name , `` Aditya '' ) ; // Youngest Man . Assert.AreEqual ( youngest.Last ( ) .Name , `` Ananya '' ) ; // Youngest Woman . } public class TestPerson { public string Name { get ; set ; } public DateTime DateOfBirth { get ; set ; } public TestGender Sex { get ; set ; } public TestPerson ( string name , DateTime dob , TestGender sex ) { Name = name ; DateOfBirth = dob ; Sex = sex ; } } public enum TestGender { Male , Female , Unknown } private List < TestPerson > GetTestPersons ( ) { var list = new List < TestPerson > ( ) ; //LOL @ using indian names . list.Add ( new TestPerson ( `` Advik '' , new DateTime ( 625909337000000000 ) , TestGender.Male ) ) ; list.Add ( new TestPerson ( `` Navya '' , new DateTime ( 608385600000000000 ) , TestGender.Female ) ) ; list.Add ( new TestPerson ( `` Ananya '' , new DateTime ( 626631005000000000 ) , TestGender.Female ) ) ; list.Add ( new TestPerson ( `` Aditya '' , new DateTime ( 630061565000000000 ) , TestGender.Male ) ) ; list.Add ( new TestPerson ( `` Veer '' , new DateTime ( 614074365000000000 ) , TestGender.Male ) ) ; list.Add ( new TestPerson ( `` Ishaan '' , new DateTime ( 617700836000000000 ) , TestGender.Male ) ) ; list.Add ( new TestPerson ( `` Pranav '' , new DateTime ( 610170773000000000 ) , TestGender.Male ) ) ; list.Add ( new TestPerson ( `` Purusha '' , new DateTime ( 629134727000000000 ) , TestGender.Unknown ) ) ; list.Add ( new TestPerson ( `` Avani '' , new DateTime ( 624015444000000000 ) , TestGender.Female ) ) ; list.Add ( new TestPerson ( `` Pari '' , new DateTime ( 625879085000000000 ) , TestGender.Female ) ) ; list.Add ( new TestPerson ( `` Nirguna '' , new DateTime ( 630489769000000000 ) , TestGender.Unknown ) ) ; return list ; } } } [ TestMethod ] public void TestGroupingAndOrdering ( ) { using ( var context = new TestCRM ( ) ) { var persons = context.Persons ; var result = persons .Where ( p = > p.Sex == Gender.Male || p.Sex == Gender.Female ) .OrderBy ( p = > p.DateOfBirth ) // REGARDLESS of what you do here , the resulting SQL is the same . .GroupBy ( p = > p.Sex ) .Select ( g = > g.FirstOrDefault ( ) ) ; var EndResult = result.ToList ( ) ; Assert.AreEqual ( EndResult.Count , 2 ) ; } }
LINQ versus LINQ to Entities , keep Sorting when Grouping
C_sharp : I 'm using Entity Framework 4 along with MSSQL to store and access data on my Windows Forms application.Here is an example class I use to access data : And here 's an example of how I use it.Someone suggested that I use IDisposable to properly `` clean up '' the connection , but I do n't know how to implement this . Any suggestions ? <code> public class StudentRepository : IDisposable { ColegioDBEntities db = new ColegioDBEntities ( ) ; public IQueryable < Student > FindAllStudents ( ) { return db.Students ; } public Student FindStudent ( int id ) { return db.Students.SingleOrDefault ( c = > c.StudentId == id ) ; } public void Add ( Student Student ) { db.AddToStudents ( Student ) ; } public void Save ( ) { db.SaveChanges ( ) ; } public void Dispose ( ) { db.Dispose ( ) ; } } private void btnLogin_Click ( object sender , EventArgs e ) { UserRepository repo = new UserRepository ( ) ; var result = repo.FindAllUsers ( ) .Where ( u = > u.Username == txtUsername.Text & & u.Password == txtPassword.Text ) ; if ( result.Count ( ) > 0 ) { MainForm form = new MainForm ( txtUsername.Text ) ; form.Show ( ) ; this.Hide ( ) ; } else { MessageBox.Show ( `` Usuario y/o contraseña incorrecta . `` , `` Acceso Denegado '' , MessageBoxButtons.OK , MessageBoxIcon.Stop , MessageBoxDefaultButton.Button1 ) ; txtUsername.Focus ( ) ; txtPassword.Focus ( ) ; } }
How would I implement IDisposable in this context ?
C_sharp : Is it possible to write the folowing using lambda ( C # ) <code> private static void GetRecordList ( List < CustomerInfo > lstCustinfo ) { for ( int i = 1 ; i < = 5 ; i++ ) { if ( i % 2 == 0 ) lstCustinfo.Add ( new CustomerInfo { CountryCode = `` USA '' , CustomerAddress = `` US Address '' + i.ToString ( ) , CustomerName = `` US Customer Name '' + i.ToString ( ) , ForeignAmount = i * 50 } ) ; else lstCustinfo.Add ( new CustomerInfo { CountryCode = `` UK '' , CustomerAddress = `` UK Address '' + i.ToString ( ) , CustomerName = `` UK Customer Name '' + i.ToString ( ) , ForeignAmount = i * 80 } ) ; } }
Rewriting a statement using LINQ ( C # )
C_sharp : I have an abstract Model and an implementationMy coins object does not show `` Coins '' as its label in my view when I use Html.LabelFor on it , it shows `` Label '' . If I move the DisplayName attribute into Treasure , it works ... but I need to be able to change the label for different implementations of the Treasure class . Is this possible ? <code> public abstract class Treasure { public abstract int Value { get ; } public abstract string Label { get ; } } public class Coins : Treasure { [ DisplayName ( `` Coin Value '' ) ] public override int Value { get { ... } } [ DisplayName ( `` Coins '' ) ] public override string Label { get { ... } }
MVC Attributes on abstract properties
C_sharp : Since I do n't have much reputation to post image , I am elaborating as a big question.I have three windows forms in which the execution of events get increased each time the form is created.1 . Form1 ( MainForm ) Here I call the second form ( SubForm ) which contains a user control . 2 . Form2 ( SubForm ) Here I call the second form ( ChildForm ) by clicking the user control.3 . Form3 ( ChildForm ) It contains an OK button.Here is my problem . First I open MainForm and click the button to open second form ( SubForm ) .Now in second form ( SubForm ) I click the user control which shows third form ( ChildForm ) .When I click OK button in the third form , the form gets closed.Now I close the second form ( SubForm ) without closing first form ( Main form ) and click the button in the first form ( MainForm ) to open second form ( SubForm ) again.Now I click user control in the second form ( SubForm ) and the third form ( ChildForm ) is opened.Now , when I click OK in the third form ( ChildForm ) , the event in the second Form ( SubForm ) is fired once again and third form ( ChildForm ) gets opened four times.Now when I close the second form ( SubForm ) again and clicks the user control and take third form ( ChildForm ) , the third form ( ChildForm ) gets opened three times etc etc.Here is the code in first form ( MainForm ) Here is the code in second form ( SubForm ) which contains user controlHere is the code in first form ( MainForm ) Anyone knows why this is happening ? <code> private void button1_Click ( object sender , EventArgs e ) { SubForm obj = new SubForm ( ) ; obj.ShowDialog ( ) ; } // Event generationUserControl1.MouseUp += new EventHandler ( this.Node_Click ) ; // Event that calls the ChildForm private void Node_Click ( object sender , EventArgs e ) { ChildForm obj = new ChildForm ( ) ; obj.ShowDialog ( ) ; } private void btnOK_Click ( object sender , EventArgs e ) { this.Close ( ) ; }
How do I restrict events firing more than once at a time
C_sharp : I have a XML file that contains multiple < p > tags in it . Some of the < p > tags contain < br/ > in it . So , I am supposed to create a new XElement for each < br/ > in the tag . I have tried to achieve by reading each line using foreach and replacing each < br/ > with < /p > + Environment.NewLine + < p > .It works but if < p > contains tags like < b > or < i > , then < and > become & lt ; and & gt ; respectively . Which is why , I want a linq approach or a foreach approach , so that I am able to do the changes while in XML format.Plase help.What I want : What I tried : I got this code from StackOverflow itslef in one of my older questions.What I get : <code> < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE repub SYSTEM `` C : \repub\Repub_V1.dtd '' > < ? xml-stylesheet href= '' C : \repub\repub.xsl '' type= '' text/xsl '' ? > < repub > < head > < title > xxx < /title > < /head > < body > < sec > < title > First Title < /title > < break name= '' 1-1 '' / > < pps > This is Sparta < /pps > < h1 > < page num= '' 1 '' / > First Heading < /h1 > < bl > This is another text < /bl > < fig > < img src= '' images/img_1-1.jpg '' alt= '' '' / > < fc > This is a caption < /fc > < /fig > < p > This is a sentence < br/ > that will be broken down < br/ > into separate paragraph tags. < /p > < /break > < /sec > < /body > < /repub > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE repub SYSTEM `` C : \repub\Repub_V1.dtd '' > < ? xml-stylesheet href= '' C : \repub\repub.xsl '' type= '' text/xsl '' ? > < repub > < head > < title > xxx < /title > < /head > < body > < sec > < title > First Title < /title > < break name= '' 1-1 '' / > < pps > This is Sparta < /pps > < h1 > < page num= '' 1 '' / > First Heading < /h1 > < bl > This is another text < /bl > < fig > < img src= '' images/img_1-1.jpg '' alt= '' '' / > < fc > This is a caption < /fc > < /fig > < p > This is a sentence < /p > < p > that will be broken down < /p > < p > into separate paragraph tags. < /p > < /break > < /sec > < /body > < /repub > List < XElement > brs = xdoc.Descendants ( `` br '' ) .ToList ( ) ; for ( int i = brs.Count - 1 ; i > = 0 ; i -- ) { brs [ i ] .ReplaceWith ( new XElement ( `` br '' , new XElement ( `` p '' , new object [ ] { brs [ i ] .Attributes ( ) , brs [ i ] .Nodes ( ) } ) ) ) ; } < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE repub SYSTEM `` C : \repub\Repub_V1.dtd '' > < ? xml-stylesheet href= '' C : \repub\repub.xsl '' type= '' text/xsl '' ? > < repub > < head > < title > xxx < /title > < /head > < body > < sec > < title > First Title < /title > < break name= '' 1-1 '' / > < pps > This is Sparta < /pps > < h1 > < page num= '' 1 '' / > First Heading < /h1 > < bl > This is another text < /bl > < fig > < img src= '' images/img_1-1.jpg '' alt= '' '' / > < fc > This is a caption < /fc > < /fig > < p > This is a sentence < br > < p/ > < /br > that will be broken down < br > < p/ > < /br > into separate paragraph tags. < /p > < /break > < /sec > < /body > < /repub >
How do I replace multiple < br/ > tags with a specific element in a new line ?
C_sharp : I 've encounter a weird problem with C # threading.This is my sample program using thread to `` activate '' the Print ( ) function at each agent in the agentList.And here is the result when I run the above program : But what I expected is something contains all 4 agents likeThe most amazing thing is that if I called the threads outside the foreach , it works ! The result of the above code is exactly what I expected . So what 's the problem here ? <code> class Program { static void Main ( string [ ] args ) { List < Agent > agentList = new List < Agent > ( ) ; agentList.Add ( new Agent ( `` lion '' ) ) ; agentList.Add ( new Agent ( `` cat '' ) ) ; agentList.Add ( new Agent ( `` dog '' ) ) ; agentList.Add ( new Agent ( `` bird '' ) ) ; foreach ( var agent in agentList ) { new Thread ( ( ) = > agent.Print ( ) ) .Start ( ) ; } Console.ReadLine ( ) ; } } class Agent { public string Name { get ; set ; } public Agent ( string name ) { this.Name = name ; } public void Print ( ) { Console.WriteLine ( `` Agent { 0 } is called '' , this.Name ) ; } } Agent cat is calledAgent dog is calledAgent bird is calledAgent bird is called Agent lion is calledAgent cat is calledAgent dog is calledAgent bird is called class Program { static void Main ( string [ ] args ) { List < Agent > agentList = new List < Agent > ( ) ; agentList.Add ( new Agent ( `` leecom '' ) ) ; agentList.Add ( new Agent ( `` huanlv '' ) ) ; agentList.Add ( new Agent ( `` peter '' ) ) ; agentList.Add ( new Agent ( `` steve '' ) ) ; new Thread ( ( ) = > agentList [ 0 ] .Print ( ) ) .Start ( ) ; new Thread ( ( ) = > agentList [ 1 ] .Print ( ) ) .Start ( ) ; new Thread ( ( ) = > agentList [ 2 ] .Print ( ) ) .Start ( ) ; new Thread ( ( ) = > agentList [ 3 ] .Print ( ) ) .Start ( ) ; Console.ReadLine ( ) ; } }
Weird Threading with C #
C_sharp : I 've noticed a difference in the way the C # 8.0 compiler builds closure classes for captured IDisposable variables that are declared with a C # 8.0 using declaration , as opposed to variables declared with the classic using statement.Consider this simple class : And this sample code : The compiler generates this code : This looks perfectly ok . But then I noticed that if I declare those two variables with a using statement , the closure class is generated pretty differently . This is the sample code : And this is what I get : Why does this happen ? The rest of the code looks identical , and I thought that a using declaration was supposed to be exactly the same as a using statement that considered as block the current block it 's declared within.Not to mention that the way the closure class is generated for using declarations looks way clearer , and most importantly , much easier to explore through reflection.I 'd love some insights , if anyone knows why this is happening.Thanks ! <code> public class DisposableClass : IDisposable { public void Dispose ( ) { } } public void Test ( ) { using var disposable1 = new DisposableClass ( ) ; using var disposable2 = new DisposableClass ( ) ; Action action = ( ) = > Console.Write ( $ '' { disposable1 } { disposable2 } '' ) ; } [ CompilerGenerated ] private sealed class < > c__DisplayClass0_0 { public DisposableClass disposable1 ; public DisposableClass disposable2 ; internal void < Test > b__0 ( ) { Console.Write ( string.Format ( `` { 0 } { 1 } '' , disposable1 , disposable2 ) ) ; } } public void Test ( ) { < > c__DisplayClass0_0 < > c__DisplayClass0_ = new < > c__DisplayClass0_0 ( ) ; < > c__DisplayClass0_.disposable1 = new DisposableClass ( ) ; try { < > c__DisplayClass0_.disposable2 = new DisposableClass ( ) ; try { Action action = new Action ( < > c__DisplayClass0_. < Test > b__0 ) ; } finally { if ( < > c__DisplayClass0_.disposable2 ! = null ) { ( ( IDisposable ) < > c__DisplayClass0_.disposable2 ) .Dispose ( ) ; } } } finally { if ( < > c__DisplayClass0_.disposable1 ! = null ) { ( ( IDisposable ) < > c__DisplayClass0_.disposable1 ) .Dispose ( ) ; } } } public void Test ( ) { using ( var disposable1 = new DisposableClass ( ) ) using ( var disposable2 = new DisposableClass ( ) ) { Action action = ( ) = > Console.Write ( $ '' { disposable1 } { disposable2 } '' ) ; } } [ CompilerGenerated ] private sealed class < > c__DisplayClass0_0 { public DisposableClass disposable1 ; } [ CompilerGenerated ] private sealed class < > c__DisplayClass0_1 { public DisposableClass disposable2 ; public < > c__DisplayClass0_0 CS $ < > 8__locals1 ; internal void < Test > b__0 ( ) { Console.Write ( string.Format ( `` { 0 } { 1 } '' , CS $ < > 8__locals1.disposable1 , disposable2 ) ) ; } }
Why are closures different for variables from C # 8.0 using declarations ?
C_sharp : Given the following program : Which produces the following output : I chose to use dynamic here to avoid the following : using switch/if/else statements e.g . switch ( foo.GetType ( ) .Name ) explicit type checking statements e.g . foo is Foo1explicit casting statements e.g . ( Foo1 ) fooBecause of the dynamic conversion , the correct ApplyFooDefaults method gets invoked based on the type of the object passed into HandleFoo ( FooBase foo ) . Any objects that do not have an appropriate ApplyFooDefaults handler method , fall into the `` catch all '' method , ApplyFooDefaults ( FooBase unhandledFoo ) .One key part here is that FooBase and the derived classes represent types that are outside of our control and can not be derived from to add additional interfaces.Is this a `` good '' use for dynamic or can this problem be solved in an OOP way without adding additional complexity given the constraints and the fact that this is just to set default property values on these objects ? *UPDATED*After Bob Horn 's answer , I realized that my scenario was n't complete . Additional constraints : You ca n't create the Foos directly , you have to use the FooFactory.You ca n't assume the Foo type because the Foo type is specified inconfiguration and created reflectively.. <code> using System ; using System.Collections.Generic ; namespace ConsoleApplication49 { using FooSpace ; class Program { static void Main ( string [ ] args ) { IEnumerable < FooBase > foos = FooFactory.CreateFoos ( ) ; foreach ( var foo in foos ) { HandleFoo ( foo ) ; } } private static void HandleFoo ( FooBase foo ) { dynamic fooObject = foo ; ApplyFooDefaults ( fooObject ) ; } private static void ApplyFooDefaults ( Foo1 foo1 ) { foo1.Name = `` Foo 1 '' ; Console.WriteLine ( foo1 ) ; } private static void ApplyFooDefaults ( Foo2 foo2 ) { foo2.Name = `` Foo 2 '' ; foo2.Description = `` SomeDefaultDescription '' ; Console.WriteLine ( foo2 ) ; } private static void ApplyFooDefaults ( Foo3 foo3 ) { foo3.Name = `` Foo 3 '' ; foo3.MaxSize = Int32.MaxValue ; Console.WriteLine ( foo3 ) ; } private static void ApplyFooDefaults ( Foo4 foo4 ) { foo4.Name = `` Foo 4 '' ; foo4.MaxSize = 99999999 ; foo4.EnableCache = true ; Console.WriteLine ( foo4 ) ; } private static void ApplyFooDefaults ( FooBase unhandledFoo ) { unhandledFoo.Name = `` Unhandled Foo '' ; Console.WriteLine ( unhandledFoo ) ; } } } /////////////////////////////////////////////////////////// Assume this namespace comes from a different assemblynamespace FooSpace { //////////////////////////////////////////////// // these can not be changed , assume these are // from the .Net framework or some 3rd party // vendor outside of your ability to alter , in // another assembly with the only way to create // the objects is via the FooFactory and you // do n't know which foos are going to be created // due to configuration . public static class FooFactory { public static IEnumerable < FooBase > CreateFoos ( ) { List < FooBase > foos = new List < FooBase > ( ) ; foos.Add ( new Foo1 ( ) ) ; foos.Add ( new Foo2 ( ) ) ; foos.Add ( new Foo3 ( ) ) ; foos.Add ( new Foo4 ( ) ) ; foos.Add ( new Foo5 ( ) ) ; return foos ; } } public class FooBase { protected FooBase ( ) { } public string Name { get ; set ; } public override string ToString ( ) { return String.Format ( `` Type = { 0 } , Name=\ '' { 1 } \ '' '' , this.GetType ( ) .FullName , this.Name ) ; } } public sealed class Foo1 : FooBase { internal Foo1 ( ) { } } public sealed class Foo2 : FooBase { internal Foo2 ( ) { } public string Description { get ; set ; } public override string ToString ( ) { string baseString = base.ToString ( ) ; return String.Format ( `` { 0 } , Description=\ '' { 1 } \ '' '' , baseString , this.Description ) ; } } public sealed class Foo3 : FooBase { internal Foo3 ( ) { } public int MaxSize { get ; set ; } public override string ToString ( ) { string baseString = base.ToString ( ) ; return String.Format ( `` { 0 } , MaxSize= { 1 } '' , baseString , this.MaxSize ) ; } } public sealed class Foo4 : FooBase { internal Foo4 ( ) { } public int MaxSize { get ; set ; } public bool EnableCache { get ; set ; } public override string ToString ( ) { string baseString = base.ToString ( ) ; return String.Format ( `` { 0 } , MaxSize= { 1 } , EnableCache= { 2 } '' , baseString , this.MaxSize , this.EnableCache ) ; } } public sealed class Foo5 : FooBase { internal Foo5 ( ) { } } //////////////////////////////////////////////// } Type = ConsoleApplication49.Foo1 , Name= '' Foo 1 '' Type = ConsoleApplication49.Foo2 , Name= '' Foo 2 '' , Description= '' SomeDefaultDescription '' Type = ConsoleApplication49.Foo3 , Name= '' Foo 3 '' , MaxSize=2147483647Type = ConsoleApplication49.Foo4 , Name= '' Foo 4 '' , MaxSize=99999999 , EnableCache=TrueType = ConsoleApplication49.Foo5 , Name= '' Unhandled Foo '' Press any key to continue . . .
Using dynamic to set disparate properties of uncontrolled ( third party ) sealed types
C_sharp : I 've got a class with readonly fields that indicate the state of my object . These fields should be visible from the outside.At first I showed these fields with properties like this : But as this is readonly , users of my class ca n't change the instance of the state . Therefore , I removed my property , set the readonly field as public and rename it in Pascal Case . So far , the only problem I saw was refactoring but as my public property is in camel case like my public readonly , I can move it into a property seamlessly.Can Jimmy mess up my object ( without modifying the code ) or is it more secure to anyway use a property ? <code> public class MyClass { private readonly MyState mystate = new MyState ( ) ; public MyState MyState { get { return this.mystate ; } } }
Can readonly fields be public ?
C_sharp : Consider the following : I am able fill dictionary manually . However is it possible add it dynamically ? How I may convert generic method to Func ? <code> public interface ISomething { string Something ( ) ; } public class A : ISomething { public string Something ( ) { return `` A '' ; } } public class B : ISomething { public string Something ( ) { return `` B '' ; } } public class Helper { private static readonly Dictionary < string , Func < string , string > > Actions = new Dictionary < string , Func < string , string > > ( StringComparer.OrdinalIgnoreCase ) ; public Helper ( ) { Actions [ `` A '' ] = DoSomething < A > ; Actions [ `` B '' ] = DoSomething < B > ; var types = Assembly.GetExecutingAssembly ( ) .GetTypes ( ) .Where ( t = > t.GetInterfaces ( ) .Contains ( typeof ( ISomething ) ) ) ; foreach ( var type in types ) { Console.WriteLine ( type.Name ) ; // Actions [ type.Name ] = ? ? ? ? ; } } public static string DoSomething < T > ( string data ) where T : ISomething { T obj = JsonConvert.DeserializeObject < T > ( data ) ; // Some manipulations return obj.Something ( ) ; } } void Main ( ) { var h = new Helper ( ) ; }
How to populate dictionary of Func < T > dynamically
C_sharp : I 'm converting a project from Java to C # . I 've tried to search this , but all I come across is questions about enums . There is a Hashtable htPlaylist , and the loop uses Enumeration to go through the keys . How would I convert this code to C # , but using a Dictionary instead of a Hashtable ? <code> // My C # Dictionary , formerly a Java Hashtable.Dictionary < int , SongInfo > htPlaylist = MySongs.getSongs ( ) ; // Original Java code trying to convert to C # using a Dictionary.for ( Enumeration < Integer > e = htPlaylist.keys ( ) ; e.hasMoreElements ( ) ; { // What would nextElement ( ) be in a Dictonary ? SongInfo popularSongs = htPlaylist.get ( e.nextElement ( ) ) ; }
Converting Enumeration < Integer > for loop from Java to C # ? What exactly is an Enumeration < Integer > in C # ?
C_sharp : I have a small issue with visual studio.I have a method that throws a CustomExceptionIf I wrap the code that calls this method in a try/catch I can see the exception details in the debuggerif I remove the try/catch I can see that the `` errors '' property has Count=4 but I can not see the errors ... Is this expected or is it a bug ? I 'm using vs2015 enterprise and .NET 4.5.2You can easily reproduce it:1 ) Create a class library with this2 ) Create a console app with this : PSI can solve my problem using the `` DebuggerDisplay '' Attribute , I 'm just wondering why Visual Studio does n't work as expectedUpdateIf I change my List to Array , I have the same problem , but if I change it to Dictionary I can see the first record ! ! ! <code> using System ; using System.Collections.Generic ; using System.Linq ; namespace ClassLibrary1 { public static class Class1 { public static void DoSomethingThatThrowsException ( ) { throw new MyException ( Enumerable.Range ( 1 , 4 ) .Select ( e = > new MyError ( ) { Message = `` error `` + e.ToString ( ) } ) .ToList ( ) ) ; } } public class MyException : Exception { public IEnumerable < MyError > errors { get ; set ; } public MyException ( IEnumerable < MyError > theErrors ) { errors = theErrors ; } } public class MyError { public string Message { get ; set ; } } } using ClassLibrary1 ; namespace ConsoleApplicationException { class Program { static void Main ( string [ ] args ) { try { Class1.DoSomethingThatThrowsException ( ) ; } catch ( MyException ex ) { //Here I can expand ex.errors ; } //Here I can see that Count=4 but I can not see the errors ... Class1.DoSomethingThatThrowsException ( ) ; } } } [ DebuggerDisplay ( `` FullDetails = { FullDetails } '' ) ] public class MyException : Exception { public IEnumerable < MyError > errors { get ; set ; } public MyException ( IEnumerable < MyError > theErrors ) { errors = theErrors ; } public string FullDetails { get { return string.Join ( `` , '' , errors.Select ( e = > e.Message ) ) ; } } }
View Detail window does not expand Collection properties
C_sharp : I 'm trying to create a program that parses data from game 's chat log . So far I have managed to get the program to work and parse the data that I want but my problem is that the program is getting slower.Currently it takes 5 seconds to parse a 10MB text file and I noticed it drops down to 3 seconds if I add RegexOptions.Compiled to my regex.I believe I have pinpointed the problem to my regex matches . One line is currently read 5 times because of the 5 regexes so the program would get even slower when I add more later.What should I do so my program would not slow down with multiple regexes ? All suggestions to make the code better are appreciated ! And here 's a sample text : <code> if ( sender.Equals ( ButtonParse ) ) { var totalShots = 0f ; var totalHits = 0f ; var misses = 0 ; var crits = 0 ; var regDmg = new Regex ( @ '' ( ? < =\bSystem\b . * You inflicted ) \d+.\d '' , RegexOptions.Compiled ) ; var regMiss = new Regex ( @ '' ( ? < =\bSystem\b . * Target evaded attack ) '' , RegexOptions.Compiled ) ; var regCrit = new Regex ( @ '' ( ? < =\bSystem\b . * Critical hit - additional damage ) '' , RegexOptions.Compiled ) ; var regHeal = new Regex ( @ '' ( ? < =\bSystem\b . * You healed yourself ) \d+.\d '' , RegexOptions.Compiled ) ; var regDmgrec = new Regex ( @ '' ( ? < =\bSystem\b . * You take ) \d+.\d '' , RegexOptions.Compiled ) ; var dmgList = new List < float > ( ) ; //New list for damage values var healList = new List < float > ( ) ; //New list for heal values var dmgRecList = new List < float > ( ) ; //New list for damage received values using ( var sr = new StreamReader ( TextBox1.Text ) ) { while ( ! sr.EndOfStream ) { var line = sr.ReadLine ( ) ; var match = regDmg.Match ( line ) ; var match2 = regMiss.Match ( line ) ; var match3 = regCrit.Match ( line ) ; var match4 = regHeal.Match ( line ) ; var match5 = regDmgrec.Match ( line ) ; if ( match.Success ) { dmgList.Add ( float.Parse ( match.Value , CultureInfo.InvariantCulture ) ) ; totalShots++ ; totalHits++ ; } if ( match2.Success ) { misses++ ; totalShots++ ; } if ( match3.Success ) { crits++ ; } if ( match4.Success ) { healList.Add ( float.Parse ( match4.Value , CultureInfo.InvariantCulture ) ) ; } if ( match5.Success ) { dmgRecList.Add ( float.Parse ( match5.Value , CultureInfo.InvariantCulture ) ) ; } } TextBlockTotalShots.Text = totalShots.ToString ( ) ; //Show total shots TextBlockTotalDmg.Text = dmgList.Sum ( ) .ToString ( `` 0. # # '' ) ; //Show total damage inflicted TextBlockTotalHits.Text = totalHits.ToString ( ) ; //Show total hits var hitChance = totalHits / totalShots ; //Calculate hit chance TextBlockHitChance.Text = hitChance.ToString ( `` P '' ) ; //Show hit chance TextBlockTotalMiss.Text = misses.ToString ( ) ; //Show total misses var missChance = misses / totalShots ; //Calculate miss chance TextBlockMissChance.Text = missChance.ToString ( `` P '' ) ; //Show miss chance TextBlockTotalCrits.Text = crits.ToString ( ) ; //Show total crits var critChance = crits / totalShots ; //Calculate crit chance TextBlockCritChance.Text = critChance.ToString ( `` P '' ) ; //Show crit chance TextBlockDmgHealed.Text = healList.Sum ( ) .ToString ( `` F1 '' ) ; //Show damage healed TextBlockDmgReceived.Text = dmgRecList.Sum ( ) .ToString ( `` F1 '' ) ; //Show damage received var pedSpent = dmgList.Sum ( ) / ( float.Parse ( TextBoxEco.Text , CultureInfo.InvariantCulture ) * 100 ) ; //Calculate ped spent TextBlockPedSpent.Text = pedSpent.ToString ( `` 0. # # '' ) + `` PED '' ; //Estimated ped spent } } 2014-09-02 23:07:22 [ System ] [ ] You inflicted 45.2 points of damage.2014-09-02 23:07:23 [ System ] [ ] You inflicted 45.4 points of damage.2014-09-02 23:07:24 [ System ] [ ] Target evaded attack.2014-09-02 23:07:25 [ System ] [ ] You inflicted 48.4 points of damage.2014-09-02 23:07:26 [ System ] [ ] You inflicted 48.6 points of damage.2014-10-15 12:39:55 [ System ] [ ] Target evaded attack.2014-10-15 12:39:58 [ System ] [ ] You inflicted 56.0 points of damage.2014-10-15 12:39:59 [ System ] [ ] You inflicted 74.6 points of damage.2014-10-15 12:40:02 [ System ] [ ] You inflicted 78.6 points of damage.2014-10-15 12:40:04 [ System ] [ ] Target evaded attack.2014-10-15 12:40:06 [ System ] [ ] You inflicted 66.9 points of damage.2014-10-15 12:40:08 [ System ] [ ] You inflicted 76.2 points of damage.2014-10-15 12:40:12 [ System ] [ ] You take 18.4 points of damage.2014-10-15 12:40:14 [ System ] [ ] You inflicted 76.1 points of damage.2014-10-15 12:40:17 [ System ] [ ] You inflicted 88.5 points of damage.2014-10-15 12:40:19 [ System ] [ ] You inflicted 69.0 points of damage.2014-10-19 05:56:30 [ System ] [ ] Critical hit - additional damage ! You inflict 275.4 points of damage.2014-10-19 05:59:29 [ System ] [ ] You inflicted 92.8 points of damage.2014-10-19 05:59:31 [ System ] [ ] Critical hit - additional damage ! You inflict 251.5 points of damage.2014-10-19 05:59:35 [ System ] [ ] You take 59.4 points of damage.2014-10-19 05:59:39 [ System ] [ ] You healed yourself 84.0 points .
Regular Expressions slowing down the program
C_sharp : I have array of strings and I have to add hyperlink to every single match of item in array and given string.Principally something like in Wikipedia.Something like : string p = `` The Domesday Book records the manor of Greenwich as held by Bishop Odo of Bayeux ; his lands were seized by the crown in 1082 . A royal palace , or hunting lodge , has existed here since before 1300 , when Edward I is known to have made offerings at the chapel of the Virgin Mary . `` ; returned string = @ '' The < a href = `` # domesday book '' > Domesday Book < /a > records the manor of Greenwich as held by Bishop < a href = `` # odo of bayeux '' > Odo of Bayeux < /a > ; his lands were seized by the crown in 1082 . A royal palace , or hunting lodge , has existed here since before 1300 , when < a href = `` # edward '' > Edward < a/ > I is known to have made offerings at the chapel of the Virgin Mary . `` ; What is the best way of doing that ? <code> private static string AddHyperlinkToEveryMatchOfEveryItemInArrayAndString ( string p , string [ ] arrayofstrings ) { } arrayofstrings = { `` Domesday book '' , `` Odo of Bayeux '' , `` Edward '' } ;
How to make programmatically html text with hyperlinks like in Wikipedia ?
C_sharp : This is the example : but it says acnnot convert Anonymous type # 1 to FotoLiveLove . <code> public class FotoLiveLove { public string Tipologia { get ; set ; } public string URL { get ; set ; } } IList < FotoLiveLove > fotoLiveLove = xDoc [ `` statuses '' ] .Select ( x = > new { Tipologia = `` twitter '' , URL = ( string ) x [ `` URLJSON '' ] } ) .ToList ( ) ;
Can I populate a list of my own class directly in LINQ ?
C_sharp : Is there a way to specify that a generic type be of one type or another type ? <code> public class SoftDrink < T > where T : TypeOne or TypeTwo { }
Specify a C # Generic Constraint to be of ClassA OR ClassB ?
C_sharp : I take user input on a form and bind it to a parameter which will then tie to my report . Can I use a single collection to hold all of my parameters ? It seems redundant to have to create a collection and a parameter for every item I want to pass to my report . To make this work the way I require , I 've had to add a collection for each param on my form : Then I created the actual parameter : Bound the value : Added the parameters to the collection : And applied the collections to the form : <code> // # 1 Setup a collections ParameterValues firstNameCollection = new ParameterValues ( ) ; ParameterValues lastNameCollectoin = new ParameterValues ( ) ; // # 2 Set the parameters ParameterDiscreteValue firstNameParam = new ParameterDiscreteValue ( ) ; ParameterDiscreteValue lastNameParam = new ParameterDiscreteValue ( ) ; // # 3 Set the values firstNameParam.Value = `` First Name '' ; lastNameParam.Value = `` Last Name '' ; // # 4 Add the parameters to the collection firstNameCollection.Add ( firstNameParam ) ; lastNameCollectoin.Add ( lastNameParam ) ; // # 5 Apply the collections to the report MyReport.DataDefinition.ParameterFields [ `` FirstName '' ] .ApplyCurrentValues ( firstNameCollection ) ; MyReport.DataDefinition.ParameterFields [ `` LastName '' ] .ApplyCurrentValues ( lastNameCollectoin ) ;
Use a single collection to hold all parameters
C_sharp : I have some client code that sends date in the following format `` 1/31/2013 11:34:28 AM '' ; I am trying to cast it into DateTime objectthis throws String was not recognized as a valid DateTime.how can i cast it ? <code> string dateRequest = `` 1/31/2013 11:34:28 AM '' ; DateTime dateTime = DateTime.Parse ( dateRequest ) ;
DateTime.Parse throws exception when parsing string
C_sharp : The following program will print the fields and whether the are constant or not using IsLiteralIt works correctly for all types , except for decimal is will return false.Can anyone explain this behavior ? And is there a better way to see if a field is constant ? <code> public static class Program { public static void Main ( string [ ] args ) { foreach ( var field in typeof ( Program ) .GetFields ( ) ) { System.Console.WriteLine ( field.Name + `` IsLiteral : `` + field.IsLiteral ) ; } System.Console.ReadLine ( ) ; } public const decimal DecimalConstant = 99M ; public const string StringConstant = `` StringConstant '' ; public const int IntConstant = 1 ; public const double DoubleConstant = 1D ; }
Why does IsLiteral return false for decimal ?
C_sharp : I work with multethreading bug . Now I see that for some reason lock is n't executed even once but is locked . I have the next class : I paused all threads in the VS , inspected all of them and see that there is only one thread in the SomeMethod and it is waiting for lock ( _lock ) to be freed ( _inCnt = 0 ) .I resumed threads , waited for a while , paused threads and see the same picture , the same ( and only one ) thread is still waiting for the lock ( _lock ) in SomeMethod and _inCnt is zero ! But it will be one or more if lock will be ever entred ( _inCnt++ is the first line after lock ( _lock ) no exception can happens , we do n't abort threads ) . How can it be zero and lock is locked ? <code> public sealed class Foo { private readonly object _lock = new object ( ) ; private static ulong _inCnt = 0 ; public void SomeMethod ( ulong poo ) { lock ( _lock ) { _inCnt++ ; ... [ some code ] } } }
Corrupted lock ? Magic deadlock ?
C_sharp : I 'm aware of technique to handle IDisposable in a traditional manner . Say , in OnStop ( ) method of windows service I close message queue client : For the first time today I saw one guy doing that this way : What is exactly happening inside his `` using '' or does he dispose correctly at all ? <code> if ( client ! = null ) { client.Dispose ( ) ; } using ( client ) { client = null ; }
Disposing by setting to null ?
C_sharp : I 've an XML file such as below : For some reasons , I need to create child and nested nodes from the Element node attributes.The output that I want is : How can i do it ? Or any idea , reference , article ... Thanks . <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LayoutControl ID= '' rootlyt '' Type= '' LayoutControl '' > < LayoutGroup ID= '' lgp8 '' Header= '' PersonalInfo '' IsCollapsed= '' False '' IsLocked= '' False '' Orientation= '' Vertical '' View= '' GroupBox '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' Width= '' 380 '' Height= '' 295 '' Type= '' GroupItem '' Properties= '' IsCollapsible=False , IsCollapsed=False , IsLocked=False , '' > < Element ID= '' layout2 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' Width= '' 300 '' Height= '' 25 '' Label= '' Name '' Background= '' # 00FFFFFF '' ContentName= '' txt2 '' Type= '' TextEdit '' / > < /LayoutGroup > < /LayoutControl > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LayoutControl ID= '' rootlyt '' Type= '' LayoutControl '' > < LayoutGroup ID= '' lgp8 '' Header= '' PersonalInfo '' IsCollapsed= '' False '' IsLocked= '' False '' Orientation= '' Vertical '' View= '' GroupBox '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' Width= '' 380 '' Height= '' 295 '' Type= '' GroupItem '' Properties= '' IsCollapsible=False , IsCollapsed=False , IsLocked=False , '' > < Element > < ID > layout2 < /ID > < HorizontalAlignment > Left < /HorizontalAlignment > < VerticalAlignment > Top < /VerticalAlignment > < Width > 300 < /Width > < Height > 25 < /Height > < Label > Name < /Label > < Background > # 00FFFFFF < /Background > < ContentName > txt2 < /ContentName > < Type > TextEdit < /Type > < /Element > < /LayoutGroup > < /LayoutControl >
Convert inline XML node to nested nodes in asp.net using c #
C_sharp : I 'm just curious how .NET defines a process architectural interface if I compile the source code under `` Any CPU '' configuration setting . I always thought that if you run that process in a x64 computer , it will be a 64-bit process . However , the example below shows a totally different thing.I have a simple console program with code like this : and the configuration setting is like this : And my processor is 64 bit : Finally , the result showsCould you please give some insights ? <code> static void Main ( string [ ] args ) { Console.WriteLine ( `` Process Type : { 0 } '' , Environment.Is64BitProcess ? `` 64 Bit '' : '' 32 Bit '' ) ; Console.ReadLine ( ) ; }
How does .NET define a process architectural interface ?
C_sharp : I 'm working on modifying Roslyn , and in this file I come across this code : Following the reference to specializedMethodReference.UnspecializedVersion gets me to this file , and this code : I 've read those comments three times , and I 've done a bit of Googling , and I have no idea what they 're talking about . Could someone please provide me with some explanation , preferably with some examples ? EDIT : Thanks to the answer by @ DaisyShipton and the comments by @ HansPassant I now think I have a vague idea of what it 's all about . Roslyn optimizes usage of generic fields and methods when possible ( calling it specialized ) , but then to be compatible with the C # metadata standards it has to emit unoptimized metadata ( calling it unspecialized ) .To test @ DaisyShipton 's answer I copied the Foo < T > and Bar classes from the answer into a C # program I was using as a test program . Then I modified this bit of Roslyn : as follows : Here 's the result : I do n't understand why this bit of code was hit so many times ( 9 ) . It can be seen that for the 8 cases where the field reference was considered specialized it 's either because int was the known result or the type of T was known to be string . But I ca n't relate the 9 hits to this code with specific bits of source code in the test program . <code> ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference ; if ( specializedMethodReference ! = null ) { methodReference = specializedMethodReference.UnspecializedVersion ; } /// < summary > /// Represents the specialized event definition./// < /summary > internal interface ISpecializedEventDefinition : IEventDefinition { /// < summary > /// The event that has been specialized to obtain this event . When the containing type is an instance of type which is itself a specialized member ( i.e . it is a nested /// type of a generic type instance ) , then the unspecialized member refers to a member from the unspecialized containing type . ( I.e . the unspecialized member always /// corresponds to a definition that is not obtained via specialization . ) /// < /summary > IEventDefinition/* ! */ UnspecializedVersion { get ; } } /// < summary > /// Represents reference specialized field./// < /summary > internal interface ISpecializedFieldReference : IFieldReference { /// < summary > /// A reference to the field definition that has been specialized to obtain the field definition referred to by this field reference . /// When the containing type of the referenced specialized field definition is itself a specialized nested type of a generic type instance , /// then the unspecialized field reference refers to the corresponding field definition from the unspecialized containing type definition . /// ( I.e . the unspecialized field reference always refers to a field definition that is not obtained via specialization . ) /// < /summary > IFieldReference UnspecializedVersion { get ; } } /// < summary > /// Represents reference specialized method./// < /summary > internal interface ISpecializedMethodReference : IMethodReference { /// < summary > /// A reference to the method definition that has been specialized to obtain the method definition referred to by this method reference . /// When the containing type of the referenced specialized method definition is itself a specialized nested type of a generic type instance , /// then the unspecialized method reference refers to the corresponding method definition from the unspecialized containing type definition . /// ( I.e . the unspecialized method reference always refers to a method definition that is not obtained via specialization . ) /// < /summary > IMethodReference UnspecializedVersion { get ; } } /// < summary > /// Represents the specialized property definition./// < /summary > internal interface ISpecializedPropertyDefinition : IPropertyDefinition { /// < summary > /// The property that has been specialized to obtain this property . When the containing type is an instance of type which is itself a specialized member ( i.e . it is a nested /// type of a generic type instance ) , then the unspecialized member refers to a member from the unspecialized containing type . ( I.e . the unspecialized member always /// corresponds to a definition that is not obtained via specialization . ) /// < /summary > IPropertyDefinition/* ! */ UnspecializedVersion { get ; } } internal BlobHandle GetFieldSignatureIndex ( IFieldReference fieldReference ) { BlobHandle result ; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference ; if ( specializedFieldReference ! = null ) { fieldReference = specializedFieldReference.UnspecializedVersion ; } internal BlobHandle GetFieldSignatureIndex ( IFieldReference fieldReference ) { BlobHandle result ; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference ; // Added code if ( fieldReference.Name == `` field '' ) { if ( specializedFieldReference == null ) Console.WriteLine ( fieldReference.ToString ( ) + `` Not considered specialized . `` ) ; else { Console.WriteLine ( fieldReference.ToString ( ) + `` Is considered specialized , converted to : `` + specializedFieldReference.UnspecializedVersion.ToString ( ) ) ; } } if ( specializedFieldReference ! = null ) { fieldReference = specializedFieldReference.UnspecializedVersion ; }
What are specialized events , fields , methods and properties ?
C_sharp : I must be reinventing the wheel here - but I 've searched and I ca n't find anything quite the same ... Here 's my code for creating a sequence of zero or more objects that have a default constructor : My question is quite simple : Is there a Linq equivalent of this I should be using ? <code> public static IEnumerable < T > CreateSequence < T > ( int n ) where T : new ( ) { for ( int i = 0 ; i < n ; ++i ) { yield return new T ( ) ; } }
Linq method for creating a sequence of separate objects ?
C_sharp : In the following C # snippet I override the == method . _type is a number of type short . So I 'm actually saying that two WorkUnitTypes are the same when those two shorts are the same.Because R # warns me , and it is totally clear why , that type1/type2 could potentially be null I 'm trying to catch that with the if statement above.Now I 'm getting a StackOverflowException which makes totally sense because I 'm actually calling the override.Question : How do I write this method `` correct '' . How can I catch the case that type1 or type2 can be null ? My best guess : Maybe I 'm just misusing == here and checking for equality should be done with the Equals override . But still I think the problem exists . So where is my error in reasoning ? <code> public static bool operator == ( WorkUnitType type1 , WorkUnitType type2 ) { if ( type1 == null || type2 == null ) return false ; return type1._type == type2._type ; }
Check for null in == override
C_sharp : BackgroundI have a convenience class which is essentially a dictionary that holds a tag/value pair list for submission to an API.At its very basic level all I did is this : This maps well to the needs of the API , since the whole thing gets sent and parsed as a string . However , it 's not so great for the caller ; for example , the caller has to know how to format the Date properly.To address this , I started adding tag-specific properties that are type safe . I have them sequestered in separate interface so they do n't get confused with the normal Dictionary properties.After introducing this interface , the caller has a choice oforThe latter is less work for the caller , especially since API_DATE_FORMAT is actually private.The issueI want the caller to be able to use object initializer syntax : ... but this does not compile ( the error is `` Invalid initializer member declarator '' ) .So it seems that the caller will need to use ... which is obviously not as well encapsulated or convenient.Is there any way to initialize an object using object initializer syntax when the property you wish to access is exposed via an interface that is not included in the default class interface ? <code> enum Tag { Name , Date , //There are many more } class RequestDictionary : Dictionary < Tag , string > { } enum Tag { Name , Date } interface ITags { string Name { get ; set ; } DateTime Date { get ; set ; } } class RequestDictionary : Dictionary < Tag , string > , ITags { public ITags Tags { get { return this ; } } string ITags.Name { get { return this [ Tag.Name ] ; } set { this [ Tag.Name ] = value ; } } DateTime ITags.Date { get { return DateTime.ParseExact ( this [ Tag.Date ] , API_DATE_FORMAT , CultureInfo.InvariantCulture ) ; } set { this [ Tag.Name ] = value.ToString ( API_DATE_FORMAT ) ; } } } dict [ Tag.Date ] = DateTime.Now.ToString ( API_DATE_FORMAT ) ; dict.Tags.Date = DateTime.Now ; var dict = new RequestDictionary { Tags.Date = DateTime.Now } var dict = new RequestDictionary { { Tags.Date , DateTime.Now.ToString ( API_DATE_FORMAT ) } } ;
Use object initializer syntax with an interface
C_sharp : This only happens on a Windows 8.1+ touch device . I have some panels where the user can slide around with their finger . I have implemented PreFilterMessage so that I can catch the mouse move globally throughout the application without having to worry about child controls interfering.I sometimes receive the generic error when clicking the form on a touch device : I do my test in a blank form with no tool bar or toolstrips . There are only two panels . One has a large label , and the other has buttons and a textbox . Here is my mouse move filter where I am passing the sender that raised the event to the function that raises the exception.Next I am just doing a check to see if the control being moved over is a textbox , and if it 's text is being highlighted . I also check a static boolean variable from another public class . If either of these are true , I set LastTouchedPanel to null . ( Which is of type Panel ) How can an object send an event if it is null , and how do you handle this for ARM devices ? This works fine on Vista to Windows 10 , but not Windows 10 ARM.Edit : I noticed Control.FromHandle ( m.HWnd ) sometimes returns Null in my PreMessageFilter on and ARM device . Putting a null check in obviously resolves the exception , but than some move events are missed . <code> IsCanceledMove ( ) Object reference not set to an instance of an object . private static void mouseFilter_MouseFilterMove ( object sender , MouseFilterEventArgs e ) { IsCanceledMove ( sender as Control ) ; } public bool PreFilterMessage ( ref Message m ) { Point mousePosition = Control.MousePosition ; var args = new MouseFilterEventArgs ( MouseButtons.Left , 0 , mousePosition.X , mousePosition.Y , 0 ) ; switch ( m.Msg ) { case WM_MOUSEMOVE : if ( MouseFilterMove ! = null ) MouseFilterMove ( Control.FromHandle ( m.HWnd ) , args ) ; break ; // more cases } // Always allow message to continue to the next filter control return args.Handled ; } // On Mouse move check if text is behing high lightedprivate static void IsCanceledMove ( Control c ) { try { // If highlighting text , stop moving if ( c.GetType ( ) == typeof ( TextBox ) ) if ( ( c as TextBox ) .SelectionLength > 0 ) LastTouchedPanel = null ; // Checks a static boolean variable from another control class . if ( UKSlider.IsSliding ) LastTouchedPanel = null ; } catch ( Exception ex ) { MessageBox.Show ( `` IsCanceledMove ( ) `` + ex.Message ) ; } }
How can a mouse event sender be null ? ( Only on Windows 8.1+ TOUCH )
C_sharp : I understand that async which awaits a task yields execution back to the caller , allowing it to continue until it needs the result.My interpretation of what I thought would come out of this was correct up until a certain point . It looks as though there 's some sort of interleaving going on . I expected Do3 ( ) to complete and then back up the call stack to Do2 ( ) . See the results.Which callsThe expected outcome : Actual output : What 's going on here exactly ? I 'm using .NET 4.5 and a simple WPF app to test my code . <code> await this.Go ( ) ; async Task Go ( ) { await Do1 ( async ( ) = > await Do2 ( `` Foo '' ) ) ; Debug.WriteLine ( `` Completed async work '' ) ; } async Task Do1 ( Func < Task > doFunc ) { Debug.WriteLine ( `` Start Do1 '' ) ; var t = Do2 ( `` Bar '' ) ; await doFunc ( ) ; await t ; } async Task Do2 ( string id ) { Debug.WriteLine ( `` Start Do2 : `` + id ) ; await Task.Yield ( ) ; await Do3 ( id ) ; Debug.WriteLine ( `` End Do2 : `` + id ) ; } async Task Do3 ( string id ) { Debug.WriteLine ( `` Start Do3 : `` + id ) ; await Task.Yield ( ) ; Debug.WriteLine ( `` End Do3 : `` + id ) ; // I did not expect Do2 to execute here once the method call for Do3 ( ) ended } // Start Do1// Start Do2 : Bar// Start Do2 : Foo// Start Do3 : Bar// Start Do3 : Foo// End Do3 : Bar// End Do2 : Bar// End Do3 : Foo// End Do2 : Foo//Completed async work //Start Do1//Start Do2 : Bar//Start Do2 : Foo//Start Do3 : Bar//Start Do3 : Foo//End Do3 : Bar//End Do3 : Foo//End Do2 : Bar//End Do2 : Foo//Completed async work
Can exiting an async method yield control back to a different async method ?
C_sharp : Today I have taken a look at the implementation of the Thumb control in order to learn how it works . What struck me is , that there are 3 methods which seem to override internal virtual parent methods , namelyI am not so much interested in what these methods do specifically , but rather what could be valid reasons to allow overriding them only internally ( Microsoft ) . I could n't find any obvious information about this.Why should the ability to extend some functionality of Control/FrameworkElement/UIElement/etc . not be available to the general user ? To me the only plausible explanation seems to be , that this functionality is designed for specific child classes of WPF , which is somehow a violation of OOP principles , is n't it ? I silently assume that it 's not just that Microsoft can say : `` we can do something with our framework that you ca n't , tee-hee '' .Follow-up : most of the internal stuff in Thumb was somehow related to visual states . So I have come to the conclusion that I can safely get rid of that part of the interface in the new class I am creating , and implement my own visual states if I ever need them . <code> internal override int EffectiveValuesInitialSize { get ; } internal override DependencyObjectType DTypeThemeStyleKey { get ; } internal override void ChangeVisualState ( bool useTransitions ) ;
Why do WPF shipped classes have internal virtual methods ?
C_sharp : My code : At times my application will stop at the cpuLabel invoke and throw an `` ArgumentOutOfRangeException '' when it was handled and fixed in my code . I tried increasing the timer that activates the thread that activates CPUStats ( ) , but to no avail . Why would this happen ? <code> public void CPUStats ( ) { var cpuCounter = new PerformanceCounter ( `` Processor '' , `` % Processor Time '' , `` _Total '' ) ; var ramCounter = new PerformanceCounter ( `` Memory '' , `` Available MBytes '' ) ; ramCounter.NextValue ( ) ; cpuCounter.NextValue ( ) ; System.Threading.Thread.Sleep ( 1000 ) ; string cpusage = cpuCounter.NextValue ( ) .ToString ( ) ; string ramusage = ramCounter.NextValue ( ) .ToString ( ) ; //Occurs here v try { //exception thrown here v cpuLabel.Invoke ( ( MethodInvoker ) ( ( ) = > cpuLabel.Text = `` CPU : `` + cpusage.Remove ( cpusage.IndexOf ( ' . ' ) ) + `` % '' ) ) ; } catch ( ArgumentOutOfRangeException ) { cpuLabel.Invoke ( ( MethodInvoker ) ( ( ) = > cpuLabel.Text = `` CPU : `` + cpusage + `` % '' ) ) ; } ramLabel.Invoke ( ( MethodInvoker ) ( ( ) = > ramLabel.Text = `` Free RAM : `` + ramusage + `` mb '' ) ) ; }
Exception that is handled is still thrown ?
C_sharp : If I have an event like this : And adds an eventhandler like this : ... is it then possible to register this somehow ? In other words - is it possible to have something like : <code> public delegate void MyEventHandler ( object sender , EventArgs e ) ; public event MyEventHandler MyEvent ; MyEvent += MyEventHandlerMethod ; MyEvent.OnSubscribe += MySubscriptionHandler ;
Is it possible to subscribe to event subscriptions in C # ?
C_sharp : Hi I am developing a chatbot on amazon lex and I want to send a response card using the lambda function but on using response card function inside the close response format it gives the error of null exception . Can anyone tell the solution to it ? PS I am using FlowerOrder blueprint created by Nikki.Exception : -2020-06-09 17:31:20 : Object reference not set to an instance of an object . : NullReferenceException at EVS_Test_Abbar_Lambda_Function.OrderWatchIntentProcessorTest.Process ( LexEvent lexEvent , ILambdaContext context ) in D : \AWS Project\Abbrar Projects\EVS_Test_Abbar_Lambda_Function\EVS_Test_Abbar_Lambda_Function\OrderWatchIntentProcessorTest.cs : line 52 at EVS_Test_Abbar_Lambda_Function.Function.FunctionHandler ( LexEvent lexEvent , ILambdaContext context ) in D : \AWS Project\Abbrar Projects\EVS_Test_Abbar_Lambda_Function\EVS_Test_Abbar_Lambda_Function\Function.cs : line 43 at lambda_method ( Closure , Stream , Stream , LambdaContextInternal ) <code> if ( slots [ greet ] ! = null ) { var validateGreet = ValidateUserGreeting ( slots [ greet ] ) ; if ( validateGreet.IsValid ) { return Close ( sessionAttributes , `` Fulfilled '' , new LexResponse.LexMessage { ContentType = `` PlainText '' , Content = String.Format ( `` Hello Kindly choose one option '' ) } , new LexResponse.LexResponseCard { Version = 1 , ContentType = `` application/vnd.amazonaws.card.generic '' , GenericAttachments = { new LexResponse.LexGenericAttachments { Buttons = { new LexResponse.LexButton { Text = `` Shop Now '' , Value = `` Shop Now '' } } , AttachmentLinkUrl = null , Title = `` Shopping '' , SubTitle = `` Sub Shopping '' , ImageUrl = null } } } ) ; }
How to send a response card using AWS Lambda in C #
C_sharp : I want to open the folder where a file had been just saved and select the file , for that I use this little code : It works perfectly.I need to put this code in several places so I decided to create a method , there is also a condition in this method : This does n't work as expected : this opens the parent folder ( of the folder containing my file ) . It also selects the folder.Why this difference in behavior and how to solve it ? <code> var psi = new ProcessStartInfo ( `` Explorer.exe '' , `` /select , '' + dlg.FileName ) ; Process.Start ( psi ) ; private static void OpenFolderAndSelectMyFile ( string fileName ) { if ( MySettings.Default.openFolder == true ) { var psi = new ProcessStartInfo ( `` Explorer.exe '' , `` /select , '' + fileName ) ; psi.WindowStyle = ProcessWindowStyle.Maximized ; Process.Start ( psi ) ; } }
Open folder issue
C_sharp : This might be lame , but here : Now I want to create an instance of the ImplementedInterface and initialize it 's members.Can this be done somehow like this ( using initialization lists ) or the same behavior can only be achieved using the constructor with Double argument ? <code> public interface Interface < T > { T Value { get ; } } public class InterfaceProxy < T > : Interface < T > { public T Value { get ; set ; } } public class ImplementedInterface : InterfaceProxy < Double > { } var x = new ImplementedInteface { 30.0 } ;
C # initialization question
C_sharp : I have the following class : I have a method that takes in Person and a String as parameters : Since Person was passed by reference , it should change the Name of the passed instance . But is this method more readable than the one above ? <code> public class Person { public String Name { get ; set ; } } public void ChangeName ( Person p , String name ) { p.Name = name ; } public Person ChangeName ( Person p , String name ) { p.Name = name ; return p ; }
Pass by reference : Which is more readable/right ?
C_sharp : I have created a new VS 2010 extensibility package . So far , all I want to do is have the user press a button and fill a listview with the entire contents of the solution . I have the following code : This does seem to work , however , it populates the list with the contents of the solution with the package in it and not the experimental instance that is launched when this is run . Am I instantiating the reference wrongly ? <code> EnvDTE80.DTE2 dte = ( EnvDTE80.DTE2 ) System.Runtime.InteropServices.Marshal . GetActiveObject ( `` VisualStudio.DTE.10.0 '' ) ; foreach ( Project project in dte.Solution.Projects ) { foreach ( ProjectItem pi in project.ProjectItems ) { listView1.Items.Add ( pi.Name.ToString ( ) ) ; } }
Visual Studio Extensibility Package not looking at correct project
C_sharp : I am a little confused on content equality in reference types specifically . I am not overriding Equality in either case - so why is the behavior different . See 2 simple code examples : Example 1 : Returns TrueExample 2 : Both statements return False <code> class Program { static void Main ( string [ ] args ) { object o1 = `` ABC '' ; object o2 = `` ABC '' ; Console.WriteLine ( `` object1 and object2 : { 0 } '' , o1.Equals ( o2 ) ) ; } } class Program { static void Main ( string [ ] args ) { Person person1 = new Person ( `` John '' ) ; Person person2 = new Person ( `` John '' ) ; Console.WriteLine ( `` person1 and person2 : { 0 } '' , person1.Equals ( person2 ) ) ; Console.WriteLine ( `` person1 and person2 : { 0 } '' , ( ( object ) person1 ) .Equals ( ( object ) person2 ) ) ; Console.ReadLine ( ) ; } } public class Person { private string personName ; public Person ( string name ) { this.personName = name ; } }
Equality in Reference Types
C_sharp : My class structure ( simplified ) Now , having only the type FinalClass1 and FinalClass2 I need to get their respective T types from the Foo interface - SomeClass for FinalClass1 and SomeOtherClass for FinalClass2 . The abstract classes can implement more generic interfaces , but always only one Foo.How can I achieve this , using reflection ? How can I also ensure that the type is implementing Foo regardless of what type the T is ? Something likebool bIsFoo = typeof ( SomeType ) .IsAssignableFrom ( Foo < > ) The above does n't work . <code> interface Foo < T > { } abstract class Bar1 : Foo < SomeClass > { } abstract class Bar2 : Foo < SomeOtherClass > { } class FinalClass1 : Bar1 { } class FinalClass2 : Bar2 { }
Generic type from base interface
C_sharp : I am wanting to find out if there is a way to initialize a List < T > where T is an object much like a simple collection gets initialized ? Simple Collection Initializer : Object Collection Initilizer : The question is , how and if you can do something like this ? <code> List < int > digits = new List < int > { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; List < ChildObject > childObjects = new List < ChildObject > { new ChildObject ( ) { Name = `` Sylvester '' , Age=8 } , new ChildObject ( ) { Name = `` Whiskers '' , Age=2 } , new ChildObject ( ) { Name = `` Sasha '' , Age=14 } } ; List < ChildObject > childObjects = new List < ChildObject > { { `` Sylvester '' , 8 } , { `` Whiskers '' , 2 } , { `` Sasha '' , 14 } } ;
Object Initializer for object collections
C_sharp : Hi , I have the following code which produces a strange behaviour.A property of an instance of objects contained in an IEnumerable produced by linq to Objects , does not get updated in subsequent foreach statements . The foreach statement should enuemerate the IEnumerable . Instead the solution is to enumerate it before.Although I found the solution I have not seen this documented anywhere either in books or articles , dealing with similar examples . Perhaps somebody with intricate knowledge of linq can explain it . It took me a day to pinpoint the exact cause of the error , and is not easy to debug in a large application . I then reproduced it in a much simpler environment , presented below.output : in list 1 value is 40 : in list 1 value is 40 : in MyClassExtra list v1.val is 40 , prop1 is 0 in MyClassExtra list v1.val is 40 , prop1 is 0 As you can see prop1 does not get updated to 40. ! ! <code> public class MyClass { public int val ; } public class MyClassExtrax { public MyClass v1 { get ; set ; } public int prop1 { get ; set ; } } void Main ( ) { List < MyClass > list1 = new List < MyClass > ( ) ; MyClass obj1 = new MyClass ( ) ; obj1.val = 10 ; list1.Add ( obj1 ) ; MyClass obj2 = new MyClass ( ) ; obj2.val = 10 ; list1.Add ( obj2 ) ; IEnumerable < MyClassExtrax > query1 = from v in list1 where v.val > = 0 select new MyClassExtrax { v1=v , prop1=0 } ; //query1=query1.ToList ( ) ; solves the problem..but why is this needed.. ? foreach ( MyClassExtrax fj in query1 ) { fj.v1.val = 40 ; fj.prop1 = 40 ; //property does not get updated.. } foreach ( MyClass obj in list1 ) { Console.WriteLine ( `` in list 1 value is { 0 } : `` , obj.val ) ; } foreach ( MyClassExtrax obj in query1 ) { Console.WriteLine ( `` in MyClassExtra list v1.val is { 0 } , prop1 is { 1 } `` , obj.v1.val , obj.prop1 ) ; } }
Strange behaviour in linq c # under delayed execution
C_sharp : I am generating two sets of repeating events in seperate loop iterations but am having a conflict when comparing the generated results for conflicts . This seems to be when the times go backwards and I am unsure how to solve this ? The first repeat event will : repeat everyday at 00:00 to 01:00 in `` Europe/Stockholm '' timefrom 03/11/2015 looping until forever.The second repeat event will : repeat everyday at 01:00 to 02:00 in `` Europe/Stockholm '' timefrom 03/11/2015 again looping forever.To generate the events I am looping through everyday in the local time zone `` Europe/Stockholm '' using Nodatime like this : My issue arises on October 29/30th 2016 When the clocks go backwards and the 2nd rule conflicts with the first . http : //www.timeanddate.com/time/change/sweden/stockholm ? year=2016The conflict times are as follows : '' 2016-10-29T23:00:00Z '' to `` 2016-10-30T01:00:00Z '' '' 2016-10-30T00:00:00Z '' to `` 2016-10-30T01:00:00Z '' I am using an algorithm like this one to test for conflictshttps : //stackoverflow.com/a/325964/884132How should I handle these time shifting conflicts ? <code> String timeZone = `` Europe/Stockholm '' ; for ( ZonedDateTime date_Local = repeatSeriesStartDate_Local ; date_Local < = LoopEndDate_Local ; date_Local = new ZonedDateTime ( Instant.FromDateTimeUtc ( date_Local.ToDateTimeUtc ( ) .AddDays ( 1 ) .ToUniversalTime ( ) ) , timeZone ) )
How to handle when timezone goes backwards in the future
C_sharp : For some weird reason , both the System.Runtime.Remoting.Messaging.CallContext and AsyncLocal classes are only available using the full CLR . This makes it really hard to do asynchronous scoping while working with Portable Class Libraries or Windows Phone applications , especially since Windows Phone APIs are becoming async-only ; so we do n't really have an option in not using async/await.What this practically means is that in WPF or WinForms , we can write methods like this : In WPF and WinForms , the framework ensures that each click to the same button get their own context and with that can run in isolation . It 's hard to achieve the same using ThreadLocal < T > and [ ThreadStatic ] since every click will get executed on the UI thread.My question is , how would we solve this problem in Windows Phone , Store and other application types that do n't support CallContext and AsyncLocal < T > ? Some background information : Very often we want ( business ) logic to run in some sort of context . This context can contain information that the business logic can use throughout the operation . In a server environment this is really easy to imagine , because you need to run requests in a database transaction , need to access the current user , tenant id , etc . But even in a client application , operations might need to access contextual information such as a correlation id for the current running operation or context for logging . During such operation ( like an click event ) we might need to resolve additional services ( from our Composition Root ) . For the operation to work successfully , we might need to reuse the same component throughout the entire client operation and that means that our Composition Root needs to be aware of the context it is running.Although all this information can be passed on through the entire system using method calls of the services ' public API , this would not only force us to pollute the API of the services in our application with implementation details , it would lead to severe maintenance issues , because we would have to pass through all this information throughout the system , and a simple internal change to one of our components would propagate up the call stack through all the methods calls . And when it comes to our Composition Root , we definitely do n't want to pass though some cache/scope object of our DI library through the application , because that would tightly couple our business logic to an external library . Obviously , neither do we want to pass on some sort of service locator.So implementing scoping using something like CallContext or AsyncLocal < T > is very important in client applications . <code> private async void button_Click ( object sender , EventArgs e ) { CallContext.LogicalSetData ( `` x '' , new object ( ) ) ; await Something ( ) ; var context = CallContext.LogicalGetData ( `` x '' ) ; }
Implementing asynchronous scoping in PCL and Windows Phone applications
C_sharp : Sometimes it 's useful to have something like : because X describes both what the type is ( as a class name ) , and the value being accessed/mutated ( as the property name ) . So far so good . Suppose you wanted to do the same thing , but in a generic way : For this example , the compiler complains that : The type ' Z < T > ' already contains a definition for 'T'.This happens for properties , variables and methods , and I do n't quite understand why - surely the compiler knows that T is a type and can therefore figure it out the same way as in the first example ? Short version : Why does the first example work , but not the second ? EDIT : I 've just discovered that if I `` Refactor > Rename '' the type parameter , say from T to U , the IDE changes it to : so something in there knows what 's a type and what 's a member name <code> class X { ... } class Y { X X { get { ... } set { ... } } } class Z < T > { T T { get { ... } set { ... } } } class Z < U > { U T { get { ... } set { ... } } }
Why is there a name clash between generic type parameter and other members
C_sharp : Consider the following code ... In my tests for a RELEASE ( not debug ! ) x86 build on a Windows 7 x64 PC ( Intel i7 3GHz ) I obtained the following results : It seems that using a Func < > to define a delegate to create new objects is more than 6 times faster than calling `` new T ( ) '' directly . I find this slightly unexpected ... I guess it 's because of some inlining done by the Jitter , but I 'd have thought that it would have been able to optimize the `` new T ( ) '' just as well.Does anyone have an explanation for this ? Maybe I 'm making some mistake . ( I 've considered the effect the garbage collector might have , but rearranging the code and adding GC.Collect ( ) and so on does n't change the results significantly ) .Anyway , here 's the code : <code> CreateSequence ( ) with new ( ) took 00:00:00.9158071CreateSequence ( ) with creator ( ) took 00:00:00.1383482CreateSequence ( ) with new ( ) took 00:00:00.9198317CreateSequence ( ) with creator ( ) took 00:00:00.1372920CreateSequence ( ) with new ( ) took 00:00:00.9340462CreateSequence ( ) with creator ( ) took 00:00:00.1447375CreateSequence ( ) with new ( ) took 00:00:00.9344077CreateSequence ( ) with creator ( ) took 00:00:00.1365162 using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; namespace ConsoleApplication6 { class Program { static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; int repeats = 100 ; int count = 100000 ; for ( int outer = 0 ; outer < 4 ; ++outer ) { sw.Restart ( ) ; for ( int inner = 0 ; inner < repeats ; ++inner ) { CreateSequence < object > ( count ) .Count ( ) ; } Console.WriteLine ( `` CreateSequence ( ) with new ( ) took `` + sw.Elapsed ) ; sw.Restart ( ) ; for ( int inner = 0 ; inner < repeats ; ++inner ) { CreateSequence ( count , ( ) = > new object ( ) ) .Count ( ) ; } Console.WriteLine ( `` CreateSequence ( ) with creator ( ) took `` + sw.Elapsed ) ; Console.WriteLine ( ) ; } } public static IEnumerable < T > CreateSequence < T > ( int n ) where T : new ( ) { for ( int i = 0 ; i < n ; ++i ) { yield return new T ( ) ; } } public static IEnumerable < T > CreateSequence < T > ( int n , Func < T > creator ) { for ( int i = 0 ; i < n ; ++i ) { yield return creator ( ) ; } } } }
Why is using a Func < > so much faster than using the new ( ) constraint on a generic sequence creator
C_sharp : We have our own certificate that we use as part of the ClientCredentials in Transport Client Credentials as seen below.Our partner also provided us with a copy of their certificate that is used on the server in order to validate their server . Calls to the service currently succeed without us having installed or done anything with this certificate.We are using ColdFusion and generally we have to install these into the java certificate store - but its odd to me that service communication is working under Visual Studio when I have not done anything with the service 's certificateWhat is the role/purpose of the service certificate ? Do clients install it in the MMC Certificate Trusted People in or reference it in the client-side configuration e.g . WSHttpBinding above ? <code> WSHttpBinding wsBinding = new WSHttpBinding ( ) ; wsBinding.Security.Mode = System.ServiceModel.SecurityMode.Transport ; wsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate ; wsClient = new WSService.WSClient ( wsBinding , new EndpointAddress ( serviceURL ) ) ; wsClient.ClientCredentials.ClientCertificate.SetCertificate ( StoreLocation.LocalMachine , StoreName.My , X509FindType.FindBySubjectName , clientCertificateSubjectName ) ;
What role does a public certificate play in WCF ?
C_sharp : I want to create a TCP Listener using Kestrel and the System.IO.Pipelines package . The messages I receive will always be HL7 messages . An example message could beMSH|^~ & |MegaReg|XYZHospC|SuperOE|XYZImgCtr|20060529090131-0500||ADT^A01^ADT_A01|01052901|P|2.5EVN||200605290901||||200605290900PID|||56782445^^^UAReg^PI||KLEINSAMPLE^BARRY^Q^JR||19620910|M||2028-9^^HL70005^RA99113^^XYZ|260GOODWIN CREST DRIVE^^BIRMINGHAM^AL^35209^^M~NICKELL ’ S PICKLES^10000 W100TH AVE^BIRMINGHAM^AL^35200^^O|||||||0105I30001^^^99DEF^ANPV1||I|W^389^1^UABH^^^^3||||12345^MORGAN^REX^J^^^MD^0010^UAMC^L||67890^GRAINGER^LUCY^X^^^MD^0010^UAMC^L|MED|||||A0||13579^POTTER^SHERMAN^T^^^MD^0010^UAMC^L|||||||||||||||||||||||||||200605290900OBX|1|NM|^Body Height||1.80|m^Meter^ISO+|||||F OBX|2|NM|^BodyWeight||79|kg^Kilogram^ISO+|||||F AL1|1||^ASPIRIN DG1|1||786.50^CHESTPAIN , UNSPECIFIED^I9|||AThe only important thing to note is that each incoming HL7 message starts with a vertical tab character so you know where the message begins . Each HL7 message contains multiple segments so I think I will have to loop through each segment . After processing the request I want to send back a HL7 message as a response . First of all I came up with thisUnfortunately I 'm struggling with some things : The part int bytesRead = 32 ; , how do I get to know how many bytes have been read ? Or how to read with the writer instance ? Currently the debugger does not hit the code at // ... Process the line ... . Basically I have to extract the whole HL7 message so I can use my HL7 parser to convert the message string.Where do I have to respond ? After calling await ReadPipe ( pipe.Input ) ; ? By using await connection.Transport.Output.WriteAsync ( /* the HL7 message to send back */ ) ; ? <code> internal class HL7Listener : ConnectionHandler { public override async Task OnConnectedAsync ( ConnectionContext connection ) { IDuplexPipe pipe = connection.Transport ; await FillPipe ( pipe.Output ) ; await ReadPipe ( pipe.Input ) ; } private async Task FillPipe ( PipeWriter pipeWriter ) { const int minimumBufferSize = 512 ; while ( true ) { Memory < byte > memory = pipeWriter.GetMemory ( minimumBufferSize ) ; try { int bytesRead = 32 ; // not sure what to do here if ( bytesRead == 0 ) { break ; } pipeWriter.Advance ( bytesRead ) ; } catch ( Exception ex ) { // ... something failed ... break ; } FlushResult result = await pipeWriter.FlushAsync ( ) ; if ( result.IsCompleted ) { break ; } } pipeWriter.Complete ( ) ; } private async Task ReadPipe ( PipeReader pipeReader ) { while ( true ) { ReadResult result = await pipeReader.ReadAsync ( ) ; ReadOnlySequence < byte > buffer = result.Buffer ; SequencePosition ? position ; do { position = buffer.PositionOf ( ( byte ) '\v ' ) ; if ( position ! = null ) { ReadOnlySequence < byte > line = buffer.Slice ( 0 , position.Value ) ; // ... Process the line ... buffer = buffer.Slice ( buffer.GetPosition ( 1 , position.Value ) ) ; } } while ( position ! = null ) ; pipeReader.AdvanceTo ( buffer.Start , buffer.End ) ; if ( result.IsCompleted ) { break ; } } pipeReader.Complete ( ) ; } }
How to create a responding TCP listener with the System.IO.Pipelines package ?
C_sharp : I have two bytes . I need to turn them into two integers where the first 12 bits make one int and the last 4 make the other . I figure i can & & the 2nd byte with 0x0f to get the 4 bits , but I 'm not sure how to make that into a byte with the correct sign.update : just to clarify I have 2 bytesand I need to do something like this with itsorry for the confusion.thanks for all of the help . <code> byte1 = 0xabbyte2 = 0xcd var value = 0xabc * 10 ^ 0xd ;
Perform signed arithmetic on numbers defined as bit ranges of unsigned bytes
C_sharp : I really do n't understand why c # compiler allows some useless statements but disallows some other useless statements . <code> static void Main ( ) { string ( ' a ' , 1 ) ; // useless but allowed // '' a '' ; // useless and disallowed new int ( ) ; // useless but allowed //0 ; // useless and disallowed new char ( ) ; // useless but allowed //'\0 ' ; // useless and disallowed new bool ( ) ; // useless but allowed //false ; // useless and disallowed //new int [ ] { 1 , 2 } ; // useless and disallowed //new [ ] { 1 , 2 } ; // useless and disallowed //new int [ 2 ] ; // useless and disallowed //new int [ 2 ] .Length ; // useless and disallowed int [ ] var = new int [ 2 ] ; // useful //var.Length ; // useless and disallowed string s = string.Empty ; // useful //string.Empty ; // useless and disallowed }
Why are some useless statements partially allowed ?
C_sharp : I 'm using Unity to make a game . I have multiple animal enemies in the game.I 'm working on missions inside the game that you have to kill a random number of random animals , this I already have.What I have a problem with is to increase the mission count when you kill an animal.I got a script ( dead ) sitting on each animal , when the animal dies it calls a public function inside the dead script.From the dead script it should increase an int value in the `` MissionHolder '' script where all the animals have a int value to increase when you kill a animal.The problem is I do n't know which animal gets killed when the player kills a animal , what I did is this : etc.Now I just name each animal by its name on the dead script but this is not really efficient.Does anyone knows a better way to do this ? <code> public string Name ; public MissionHolder missionHolder ; public void Kill ( ) { if ( name == `` Tiger '' ) { missionHolder.Tiger += 1 ; } if ( name == `` Hyena '' ) { missionHolder.Hyena += 1 ; } if ( name == `` Gorilla '' ) { missionHolder.Gorilla += 1 ; } if ( name == `` Giraffe '' ) { missionHolder.Giraffe += 1 ; } if ( name == `` Gazelle '' ) { missionHolder.Gazelle += 1 ; }
How can I simplify this long series of if statements ?
C_sharp : I 'm trying to assign a static List < PropertyInfo > of all DbSet properties in the Entities class.However when the code runs the List is empty because .Where ( x = > x.PropertyType == typeof ( DbSet ) ) always returns false.I tried multiple variations in the .Where ( ... ) method like typeof ( DbSet < > ) , Equals ( ... ) , .UnderlyingSystemType , etc . but none works.Why does .Where ( ... ) always return false in my case ? My code : <code> public partial class Entities : DbContext { //constructor is omitted public static List < PropertyInfo > info = typeof ( Entities ) .getProperties ( ) .Where ( x = > x.PropertyType == typeof ( DbSet ) ) .ToList ( ) ; public virtual DbSet < NotRelevant > NotRelevant { get ; set ; } //further DbSet < XXXX > properties are omitted ... . }
Linq .Where ( type = typeof ( xxx ) ) comparison is always false
C_sharp : I 'm working on a VS Extension that needs to be aware of which class member the text-cursor is currently located in ( methods , properties , etc ) . It also needs an awareness of the parents ( e.g . class , nested classes , etc ) . It needs to know the type , name , and line number of the member or class . When I say `` Type '' I mean `` method '' or `` property '' not necessarily a `` .NET Type '' .Currently I have it working with this code here : So that currently works , if I call GetCodeElementAtCursor I will get the member and it 's parents back . ( This is kinda old code , but I believe I originally snagged it from Carlos ' blog and ported it from VB ) .My problem is that when my extension is used on code that is very large , like auto-generated files with a couple thousand lines , for example , it brings VS to a crawl . Almost unusable . Running a profiler shows that the hot lines areSo the third one is obvious , it 's a recursive call to itself so whatever is affecting it will affect a call to itself . The first two , however , I 'm not sure how to fix . Is there an alternative method I could use to retrieve the type of member my cursor is on ( class , method , prop , etc ) , the name , line # , and the parents ? Is there something that I could do to make the TextPoint.GreaterThan and TestPoint.LessThan methods perform better ? Or , am I S.O.L . ? Whatever the method is , it just needs to support VS2015 or newer.Thank you ! UPDATE : To answer Sergey 's comment - it does indeed seem to be caused by .GreaterThan / .LessThan ( ) . I 've separated the code and the slow-down is definitely occurring on those method calls , NOT the property accessor for element.StartPoint and element.EndPoint . <code> public static class CodeElementHelper { public static CodeElement [ ] GetCodeElementAtCursor ( DTE2 dte ) { try { var cursorTextPoint = GetCursorTextPoint ( dte ) ; if ( cursorTextPoint ! = null ) { var activeDocument = dte.ActiveDocument ; var projectItem = activeDocument.ProjectItem ; var codeElements = projectItem.FileCodeModel.CodeElements ; return GetCodeElementAtTextPoint ( codeElements , cursorTextPoint ) .ToArray ( ) ; } } catch ( Exception ex ) { Debug.WriteLine ( `` [ DBG ] [ EXC ] - `` + ex.Message + `` `` + ex.StackTrace ) ; } return null ; } private static TextPoint GetCursorTextPoint ( DTE2 dte ) { var cursorTextPoint = default ( TextPoint ) ; try { var objTextDocument = ( TextDocument ) dte.ActiveDocument.Object ( ) ; cursorTextPoint = objTextDocument.Selection.ActivePoint ; } catch ( Exception ex ) { Debug.WriteLine ( `` [ DBG ] [ EXC ] - `` + ex.Message + `` `` + ex.StackTrace ) ; } return cursorTextPoint ; } private static List < CodeElement > GetCodeElementAtTextPoint ( CodeElements codeElements , TextPoint objTextPoint ) { var returnValue = new List < CodeElement > ( ) ; if ( codeElements == null ) return null ; int count = 0 ; foreach ( CodeElement element in codeElements ) { if ( element.StartPoint.GreaterThan ( objTextPoint ) ) { // The code element starts beyond the point } else if ( element.EndPoint.LessThan ( objTextPoint ) ) { // The code element ends before the point } else { if ( element.Kind == vsCMElement.vsCMElementClass || element.Kind == vsCMElement.vsCMElementProperty || element.Kind == vsCMElement.vsCMElementPropertySetStmt || element.Kind == vsCMElement.vsCMElementFunction ) { returnValue.Add ( element ) ; } var memberElements = GetCodeElementMembers ( element ) ; var objMemberCodeElement = GetCodeElementAtTextPoint ( memberElements , objTextPoint ) ; if ( objMemberCodeElement ! = null ) { returnValue.AddRange ( objMemberCodeElement ) ; } break ; } } return returnValue ; } private static CodeElements GetCodeElementMembers ( CodeElement codeElement ) { CodeElements codeElements = null ; if ( codeElement is CodeNamespace ) { codeElements = ( codeElement as CodeNamespace ) .Members ; } else if ( codeElement is CodeType ) { codeElements = ( codeElement as CodeType ) .Members ; } else if ( codeElement is CodeFunction ) { codeElements = ( codeElement as CodeFunction ) .Parameters ; } return codeElements ; } } private static List < CodeElement > GetCodeElementAtTextPoint ( CodeElements codeElements , TextPoint objTextPoint ) { foreach ( CodeElement element in codeElements ) { ... /* -- > */ if ( element.StartPoint.GreaterThan ( objTextPoint ) ) // HERE < -- - { // The code element starts beyond the point } /* -- > */ else if ( element.EndPoint.LessThan ( objTextPoint ) ) // HERE < -- -- { // The code element ends before the point } else { ... var memberElements = GetCodeElementMembers ( element ) ; /* -- > */ var objMemberCodeElement = GetCodeElementAtTextPoint ( memberElements , objTextPoint ) ; // AND , HERE < -- - ... } } return returnValue ; }
VS Extension : TextPoint.GreaterThan / LessThan very slow for large files
C_sharp : I am trying to Pinvoke the lmdif1 method in the cminpack_dll.dll from c # and i am running into some curious errors . The 2nd and third parameters passed to lmdif1 are ints , and for my test the values in order are 12 and 9 . Now when ther are in the C code , the value that was 12 is now 9 and the value that was 9 varies between 308000 and 912000 . No idea why . First of all , I was wondering if the signature I am using is validthe C # signature : The C signature : And the way I am calling it : Now this is my first time dealing with PInvoke , and my C is n't great , having never really done it before , so any help would be great . My suspicion is that I may need to Marshal things , but I 've tried marshalling the ints as I4 and as U4 and it still does the same . Cheers in Advance for your help.EDIT : Here is the comment that describes the C function , if that helps : <code> [ DllImport ( `` cminpack_dll.dll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern int lmdif1 ( IntPtr fcn , int m , int n , double [ ] x , double [ ] fVec , double tol , int [ ] iwa , double [ ] wa , int lwa ) ; int __cminpack_func__ ( lmdif1 ) ( __cminpack_decl_fcn_mn__ void *p , int m , int n , real *x , real *fvec , real tol , int *iwa , real *wa , int lwa ) //All of the variables passed in match the types in C # signature above.var info =lmdif1 ( functionPointer , pointsetLength , initialGuessLength , initialGuess , fVec , tol , iwa , wa , lwa ) ; /* ********** *//* subroutine lmdif1 *//* the purpose of lmdif1 is to minimize the sum of the squares of *//* m nonlinear functions in n variables by a modification of the *//* levenberg-marquardt algorithm . this is done by using the more *//* general least-squares solver lmdif . the user must provide a *//* subroutine which calculates the functions . the jacobian is *//* then calculated by a forward-difference approximation . *//* the subroutine statement is *//* subroutine lmdif1 ( fcn , m , n , x , fvec , tol , info , iwa , wa , lwa ) *//* where *//* fcn is the name of the user-supplied subroutine which *//* calculates the functions . fcn must be declared *//* in an external statement in the user calling *//* program , and should be written as follows . *//* subroutine fcn ( m , n , x , fvec , iflag ) *//* integer m , n , iflag *//* double precision x ( n ) , fvec ( m ) *//* -- -- -- -- -- *//* calculate the functions at x and *//* return this vector in fvec . *//* -- -- -- -- -- *//* return *//* end *//* the value of iflag should not be changed by fcn unless *//* the user wants to terminate execution of lmdif1 . *//* in this case set iflag to a negative integer . *//* m is a positive integer input variable set to the number *//* of functions . *//* n is a positive integer input variable set to the number *//* of variables . n must not exceed m. *//* x is an array of length n. on input x must contain *//* an initial estimate of the solution vector . on output x *//* contains the final estimate of the solution vector . *//* fvec is an output array of length m which contains *//* the functions evaluated at the output x . *//* tol is a nonnegative input variable . termination occurs *//* when the algorithm estimates either that the relative *//* error in the sum of squares is at most tol or that *//* the relative error between x and the solution is at *//* most tol . *//* info is an integer output variable . if the user has *//* terminated execution , info is set to the ( negative ) *//* value of iflag . see description of fcn . otherwise , *//* info is set as follows . *//* info = 0 improper input parameters . *//* info = 1 algorithm estimates that the relative error *//* in the sum of squares is at most tol . *//* info = 2 algorithm estimates that the relative error *//* between x and the solution is at most tol . *//* info = 3 conditions for info = 1 and info = 2 both hold . *//* info = 4 fvec is orthogonal to the columns of the *//* jacobian to machine precision . *//* info = 5 number of calls to fcn has reached or *//* exceeded 200* ( n+1 ) . *//* info = 6 tol is too small . no further reduction in *//* the sum of squares is possible . *//* info = 7 tol is too small . no further improvement in *//* the approximate solution x is possible . *//* iwa is an integer work array of length n. *//* wa is a work array of length lwa . *//* lwa is a positive integer input variable not less than *//* m*n+5*n+m . *//* subprograms called *//* user-supplied ... ... fcn *//* minpack-supplied ... lmdif *//* argonne national laboratory . minpack project . march 1980 . *//* burton s. garbow , kenneth e. hillstrom , jorge j. more *//* ********** *//* check the input parameters for errors . */
PInvoke lmdif1 signature
C_sharp : I need to integrate an ASP.NET MVC website with a 3rd party COM application . The code looks something like this : The problem is that after a while I start getting COMExceptions most probably because I never close that context using obj.ReleaseApplicationContext ( ) . So I 'm thinking about writing a wrapper implementing IDisposable so that I can initialize the context in the constructor and release it when it 's disposed . But then I would need a lock so that another thread would not close the context while the current thread is still working . The code would look like this : I know very little about thread safety so what I 'm asking you is the following : Is there anything wrong with my approach ? Is there anything else I should consider ( like deadlocks or something else ) ? Would you recommend a different approach ? Edit 1 : I looked up the progID of the COM class in the registry and found that ThreadingModel=Apartment so the COM application uses a Single-Threaded Apartment type.Edit 2 : The COM application uses a system to generate ids for objects so that when these objects are persisted in the database they already have an Id . This system involves writing some information in the registry . After a while something goes wrong with this system and I start getting violation of primary key constraint errors.Edit 3 : I sometimes get a System.ArgumentNullException : Value can not be null . Parameter name : type at Activator.CreateInstance ( Type type ) . Could this be because I 'm trying to create a new STA object from another thread ? Edit 4 : Someone asked me to post the full the full stack of the COMExceptions , but I 'm afraid this will make my question too localized and useless for anyone else but me . Furthermore , I actually found the cause of the problem : there were some very rare cases when the context was not initialised before using some com objects and this messed up the system , but the errors only showed up at a later time . So I made sure that the context is always initialized prior to using any com object and the problem went away.I 'm still interested in an answer about thread safety and my proposed solution . Or maybe the question should be closed as too localized ? <code> Type type = Type.GetTypeFromProgID ( progID ) ; dynamic obj = Activator.CreateInstance ( type ) ; if ( ! obj.DBOpenedStatus ) { obj.InitApplicationContext ( ) ; //do stuff with other COM objects } lock ( _locker ) { using ( MyComContextWrapper comContext = new MyComContextWrapper ( ) ) { //do stuff with other COM objects } }
COM and thread safety
C_sharp : I have been working on a Windows 8.1 RT app where the user loads an image with Stretch=Uniform . The image can be as small as possible and as big as possible.The clipping happens in my user control and my user control appears when I tap/press and hold on the screen/image.Clipping happens when when I tap and hold and move my finger/mouse around the image that is in the background . The Problems I am facing are Whenever the app is loaded for the first time on Emulator , and for the very first time when the tap /clicks and holding is performed , the user control appears on the top left on the screen and then it comes above my clicked/hold area . What I require is it should always appear wherever I click and hold and whenever I click and hold . On releasing the finger/mouse , it should collapse.I am using center transform . I want the region ( the pixel ) where my mouse is currently to be displayed exactly in the center of the user control , If i am loading a small resolution image 480*800 or even smaller , the region of my mouse is not coming into the center.To be more clearer , Imagine I am tapping and holding on the CORNEA of the human eye.The cornea should be displayed in the center of the user control and area above and below should cover the rest of the part.I do n't want my control to go outside my image boundary , if my mouse is at the last pixel of the image , some part of image and some part of background should be displayed.I need to rotate the control as shown in the videoFind the complete code below.MainPage.XAMLMAINPAGE.XAML.CSMagnifier.XAMLFor ease , the project can be downloaded from here . For better understanding , I would like you to see this video . This is what exactly I need to implement . <code> < Page x : Class= '' App78.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : App78 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' > < Grid x : Name= '' LayoutGrid '' Margin= '' 0,0 '' Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' Holding= '' LayoutGrid_Holding '' PointerMoved= '' LayoutGrid_OnPointerMoved '' PointerWheelChanged= '' LayoutGrid_OnPointerWheelChanged '' PointerPressed= '' LayoutGrid_OnPointerPressed '' PointerReleased= '' LayoutGrid_OnPointerReleased '' > < Image x : Name= '' BigImage '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' Stretch= '' Uniform '' Source= '' http : //blog.al.com/space-news/2009/04/iss015e22574.jpg '' / > < local : Magnifier VerticalAlignment= '' Top '' HorizontalAlignment= '' Left '' x : Name= '' MagnifierTip '' Visibility= '' Collapsed '' / > < /Grid > < /Page > using System ; using System.Diagnostics ; using Windows.UI.Xaml.Controls ; using Windows.UI.Xaml.Input ; using Windows.UI.Xaml.Media ; using Windows.UI.Xaml.Media.Imaging ; namespace App78 { public sealed partial class MainPage : Page { private double zoomScale = 2 ; private double pointerX = 0 ; private double pointerY = 0 ; private const double MinZoomScale = .25 ; private const double MaxZoomScale = 32 ; public MainPage ( ) { this.InitializeComponent ( ) ; var bi = ( BitmapImage ) BigImage.Source ; bi.ImageOpened += bi_ImageOpened ; this.SizeChanged += MainPage_SizeChanged ; } void MainPage_SizeChanged ( object sender , Windows.UI.Xaml.SizeChangedEventArgs e ) { this.UpdateImageLayout ( ) ; } void bi_ImageOpened ( object sender , Windows.UI.Xaml.RoutedEventArgs e ) { this.UpdateImageLayout ( ) ; } private void UpdateImageLayout ( ) { var bi = ( BitmapImage ) BigImage.Source ; if ( bi.PixelWidth < this.LayoutGrid.ActualWidth & & bi.PixelHeight < this.LayoutGrid.ActualHeight ) { this.BigImage.Stretch = Stretch.None ; } else { this.BigImage.Stretch = Stretch.Uniform ; } this.UpdateMagnifier ( ) ; } private void LayoutGrid_OnPointerMoved ( object sender , PointerRoutedEventArgs e ) { //DV : If pointer is not in contact we can ignore it if ( ! e.Pointer.IsInContact ) { return ; } var point = e.GetCurrentPoint ( this.LayoutGrid ) ; this.pointerX = point.Position.X ; this.pointerY = point.Position.Y ; this.UpdateMagnifier ( ) ; } private void UpdateMagnifier ( ) { var bi = ( BitmapImage ) BigImage.Source ; double offsetX = 0 ; double offsetY = 0 ; double imageScale = 1 ; var imageRatio = ( double ) bi.PixelWidth / bi.PixelHeight ; var gridRatio = this.LayoutGrid.ActualWidth / this.LayoutGrid.ActualHeight ; if ( bi.PixelWidth < this.LayoutGrid.ActualWidth & & bi.PixelHeight < this.LayoutGrid.ActualHeight ) { offsetX = 0.5 * ( this.LayoutGrid.ActualWidth - bi.PixelWidth ) ; offsetY = 0.5 * ( this.LayoutGrid.ActualHeight - bi.PixelHeight ) ; //imageScale = 1 ; - remains } else if ( imageRatio < gridRatio ) { offsetX = 0.5 * ( this.LayoutGrid.ActualWidth - imageRatio * this.LayoutGrid.ActualHeight ) ; offsetY = 0 ; imageScale = BigImage.ActualHeight / bi.PixelHeight ; } else { offsetX = 0 ; offsetY = 0.5 * ( this.LayoutGrid.ActualHeight - this.LayoutGrid.ActualWidth / imageRatio ) ; imageScale = BigImage.ActualWidth / bi.PixelWidth ; } //DV : This is probably not need anymore //MagnifierTip.MagnifierTransform.X = this.pointerX ; //MagnifierTip.MagnifierTransform.Y = this.pointerY ; MagnifierTip.PositionTransform.X = ( -this.pointerX + offsetX ) / imageScale ; MagnifierTip.PositionTransform.Y = ( -this.pointerY + offsetY ) / imageScale ; //DV : I have n't tested the Scaling/Zoom MagnifierTip.ZoomTransform.ScaleX = imageScale * zoomScale ; MagnifierTip.ZoomTransform.ScaleY = imageScale * zoomScale ; MagnifierTip.CenterTransform.X = MagnifierTip.MagnifierEllipse.ActualWidth / 2 - MagnifierTip.MagnifierEllipse.StrokeThickness / 2 ; MagnifierTip.CenterTransform.Y = MagnifierTip.MagnifierEllipse.ActualHeight / 2 - MagnifierTip.MagnifierEllipse.StrokeThickness / 2 ; //DV : I added a GlobalGrid Transform which translates every children MagnifierTip.MagnifierTransformGrid.X = this.pointerX - ( MagnifierTip.ActualWidth / 2 ) ; MagnifierTip.MagnifierTransformGrid.Y = this.pointerY - ( MagnifierTip.ActualHeight ) ; ; } private void LayoutGrid_OnPointerWheelChanged ( object sender , PointerRoutedEventArgs e ) { if ( e.GetCurrentPoint ( this.LayoutGrid ) .Properties.MouseWheelDelta > 0 ) { zoomScale = Math.Max ( MinZoomScale , Math.Min ( MaxZoomScale , zoomScale * 1.2 ) ) ; } else { zoomScale = Math.Max ( MinZoomScale , Math.Min ( MaxZoomScale , zoomScale / 1.2 ) ) ; } this.UpdateMagnifier ( ) ; } //DV : Holding usually only works with touch https : //msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.uielement.holding.aspx ? f=255 & MSPPError=-2147217396 private void LayoutGrid_Holding ( object sender , HoldingRoutedEventArgs e ) { // } //DV : pointer pressed supports both mouse and touch but fires immeadiatley . You 'll have to figure out a delay strategy or using holding for touch and right click for mouse private void LayoutGrid_OnPointerPressed ( object sender , PointerRoutedEventArgs e ) { MagnifierTip.Visibility = Windows.UI.Xaml.Visibility.Visible ; } //DV : pointer released supports both mouse and touch . private void LayoutGrid_OnPointerReleased ( object sender , PointerRoutedEventArgs e ) { MagnifierTip.Visibility = Windows.UI.Xaml.Visibility.Collapsed ; } } } < UserControl x : Class= '' App78.Magnifier '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : App78 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Height= '' 230 '' Width= '' 170 '' > < Grid Height= '' 230 '' Width= '' 170 '' > < ! -- DV : This is the global transform I added -- > < Grid.RenderTransform > < TransformGroup > < TranslateTransform x : Name= '' MagnifierTransformGrid '' x : FieldModifier= '' public '' / > < /TransformGroup > < /Grid.RenderTransform > < Ellipse Opacity= '' 1 '' Visibility= '' Visible '' Fill= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Top '' IsHitTestVisible= '' False '' Width= '' 135 '' Height= '' 128 '' StrokeThickness= '' 3 '' Margin= '' 0,17,0,0 '' / > < Ellipse x : Name= '' MagnifierEllipse '' x : FieldModifier= '' public '' Opacity= '' 1 '' Visibility= '' Visible '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' IsHitTestVisible= '' False '' Width= '' 150 '' Height= '' 150 '' Stroke= '' White '' StrokeThickness= '' 3 '' Margin= '' 11,8,0,0 '' > < Ellipse.Fill > < ImageBrush ImageSource= '' http : //blog.al.com/space-news/2009/04/iss015e22574.jpg '' Stretch= '' None '' AlignmentX= '' Left '' AlignmentY= '' Top '' > < ImageBrush.Transform > < TransformGroup > < TranslateTransform x : FieldModifier= '' public '' x : Name= '' CenterTransform '' / > < TranslateTransform x : FieldModifier= '' public '' x : Name= '' PositionTransform '' / > < ScaleTransform x : FieldModifier= '' public '' x : Name= '' ZoomTransform '' / > < /TransformGroup > < /ImageBrush.Transform > < /ImageBrush > < /Ellipse.Fill > < /Ellipse > < Path Data= '' M25.533,0C15.457,0,7.262,8.199,7.262,18.271c0,9.461,13.676,19.698,17.63,32.338 c0.085,0.273,0.34,0.459,0.626,0.457c0.287-0.004,0.538-0.192,0.619-0.467c3.836-12.951,17.666-22.856,17.667-32.33 C43.803,8.199,35.607,0,25.533,0z M25.533,32.131c-7.9,0-14.328-6.429-14.328-14.328c0-7.9,6.428-14.328,14.328-14.328 c7.898,0,14.327,6.428,14.327,14.328C39.86,25.702,33.431,32.131,25.533,32.131z '' Fill= '' # FFF4F4F5 '' Stretch= '' Fill '' Stroke= '' Black '' UseLayoutRounding= '' False '' Height= '' 227 '' Width= '' 171 '' > < /Path > < /Grid > < /UserControl >
Clipping a low resolution image using Transforms and assigning it to my user control
C_sharp : In python I have the following : this is a structure to represent a graph and that I find nice because its structure is the same as the one of one of it 's nodes so I can use it directly to initiate a search ( as in depth-first ) . The printed version of it is : And it can be used like : Now , I 'm curious to know how would one implement it in C++ , C # and Java without resorting to `` Object '' tricks that would fill the code with ugly casts . For C++ I was thinking in templatemeta programming but that would generate `` finite data types '' when what is needed is something like <code> graph = { } graph [ 1 ] = { } graph [ 2 ] = { } graph [ 3 ] = { } graph [ 1 ] [ 3 ] = graph [ 3 ] graph [ 2 ] [ 1 ] = graph [ 1 ] graph [ 2 ] [ 3 ] = graph [ 3 ] graph [ 3 ] [ 2 ] = graph [ 2 ] { 1 : { 3 : { 2 : { 1 : { ... } , 3 : { ... } } } } , 2 : { 1 : { 3 : { 2 : { ... } } } , 3 : { 2 : { ... } } } , 3 : { 2 : { 1 : { 3 : { ... } } , 3 : { ... } } } } graph [ 1 ] [ 3 ] [ 2 ] [ 3 ] [ 2 ] [ 1 ] [ 3 ] [ 2 ] [ 1 ] [ 3 ] [ 2 ] .keys ( ) map < int , map < int , ... > > or map < int , ... >
Creating in c # , c++ and java a strong typed version of a python weak typed structure
C_sharp : I have a Xamarin.Forms app that implements certificate pinning utilizing the ServicePointManager.ServerCertificateValidationCallback class and method . On Android and iOS , this works without issue in that it will allow connections to expected services whose certificate keys have been pinned and disallow connections for those that I have not.However , on UWP , all connections are allowed regardless whether the certificate key has been pinned or not . I have explicitly returned false from the certificate validation method and the connection is still allowed . I am sure the check is being performed as I have debugged and stepped through the certificate validation method.What could be causing the connection to proceed even though I am returning false from the validation check ? <code> ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertficate ; private static bool ValidateServerCertficate ( object sender , X509Certificate certificate , X509Chain chain , SslPolicyErrors sslPolicyErrors ) { return false ; }
UWP ServicePointManager.ServerCertificateValidationCallback
C_sharp : Is there any way of being notified when something subscribes to an event in my class , or do I need to wrap subscription/unsubsription in methods eg : instead ofThe reason I ask is because the event is already exposed directly on a ISomeInterface but this particular implementation needs to know when stuff subscribes/unsubscribes . <code> public class MyClass : ISomeInterface { public event SomeEventHandler SomeEvent ; //How do I know when something subscribes ? private void OnSomeEventSubscription ( SomeEventHandler handler ) { //do some work } private void OnSomeEventUnsubscription ( SomeEventHandler handler ) { //do some work } } public class MyClass : ISomeInterface { private SomeEventHandler _someEvent ; public void SubscribeToSomeEvent ( SomeEventHandler handler ) { _someEvent += handler ; //do some work } public void UnsubscribeFromSomeEvent ( SomeEventHandler handler ) { _someEvent -= handler ; //do some work } }
Any way to be notified when something subscribes to an event / delegate ?
C_sharp : The following code compiles : because defau1t is interpreted as a goto label . However in the following case : the compiler correctly identifies the mistake : error CS1525 : Unexpected symbol defau1t ' , expecting } ' , case ' , ordefault : 'Why is that ? What 's the reason of allowing arbitrary labels inside the switch statements if it leads to ( seemingly ) incoherent behaviour ? Side note : The same problem can be observed for similar snippets for C++ and Java . <code> int a = 0 ; switch ( a ) { case 1 : return ; defau1t : // note the typo return ; } switch ( a ) { defau1t : return ; }
What 's the reason of allowing arbitrary labels inside the switch statements ?
C_sharp : I want to create a generic class where the type of the class can Parse strings.I want to use this class for any class that has a static function Parse ( string ) , like System.Int32 , System.Double , but also for classes like System.Guid . They all have a static Parse functionSo my class needs a where clause that constraints my generic type to types with a Parse functionI 'd like to use it like this : What to write in the where clause ? <code> class MyGenericClass < T > : where T : ? ? ? what to do ? ? ? { private List < T > addedItems = new List < T > ( ) public void Add ( T item ) { this.AddedItems.Add ( item ) ; } public void Add ( string itemAsTxt ) { T item = T.Parse ( itemAsTxt ) ; this.Add ( item ) ; } }
Generic class where type can Parse strings
C_sharp : I 'm trying to find a good way to cumulatively apply up to 5 Func 's to the same IEnumerable . Here is what I came up with : I thought that it would apply these in a cumulative fashion , however , I can see from the results that it 's actually just applying the last one ( DepartmentFilter ) .There are 2^4 possible combinations so brute-force if/elses are not going to work . ( I want to AND using a particular lambda only when the corresponding key is present in the Dictionary . ) EDIT : Here is the solution that I accepted , but it causes a StackOverflowException when it is evaluated . Anybody see why ? EDIT : Here is the very nice explanation of why this resulted in a StackOverflowException from friend and mentor Chris Flather-The important thing to understanding why the infinite recursion occurs is understanding when the symbols in a lambda are resolved ( i.e . at runtime and not at definition ) .Take this simplified example : If it were resolved statically at definition this would work and be the same as : But it doesn ’ t actually attempt to figure out what the demo embedded in demo2 does until runtime – at which time demo2 has been redefined to demo . Essentially the code now reads : <code> private Func < SurveyUserView , bool > _getFilterLambda ( IDictionary < string , string > filters ) { Func < SurveyUserView , bool > invokeList = delegate ( SurveyUserView surveyUserView ) { return surveyUserView.deleted ! = `` deleted '' ; } ; if ( filters.ContainsKey ( `` RegionFilter '' ) ) { invokeList += delegate ( SurveyUserView surveyUserView ) { return surveyUserView.Region == filters [ `` RegionFilter '' ] ; } ; } if ( filters.ContainsKey ( `` LanguageFilter '' ) ) { invokeList += delegate ( SurveyUserView surveyUserView ) { return surveyUserView.Locale == filters [ `` LanguageFilter '' ] ; } ; } if ( filters.ContainsKey ( `` StatusFilter '' ) ) { invokeList += delegate ( SurveyUserView surveyUserView ) { return surveyUserView.Status == filters [ `` StatusFilter '' ] ; } ; } if ( filters.ContainsKey ( `` DepartmentFilter '' ) ) { invokeList += delegate ( SurveyUserView surveyUserView ) { return surveyUserView.department == filters [ `` DepartmentFilter '' ] ; } ; } return invokeList ; } private Func < SurveyUserView , bool > _getFilterLambda ( IDictionary < string , string > filters ) { Func < SurveyUserView , bool > resultFilter = ( suv ) = > suv.deleted ! = `` deleted '' ; if ( filters.ContainsKey ( `` RegionFilter '' ) ) { Func < SurveyUserView , bool > newFilter = ( suv ) = > resultFilter ( suv ) & & suv.Region == filters [ `` RegionFilter '' ] ; resultFilter = newFilter ; } if ( filters.ContainsKey ( `` LanguageFilter '' ) ) { Func < SurveyUserView , bool > newFilter = ( suv ) = > resultFilter ( suv ) & & suv.Locale == filters [ `` LanguageFilter '' ] ; resultFilter = newFilter ; } if ( filters.ContainsKey ( `` StatusFilter '' ) ) { Func < SurveyUserView , bool > newFilter = ( suv ) = > resultFilter ( suv ) & & suv.Status == filters [ `` StatusFilter '' ] ; resultFilter = newFilter ; } if ( filters.ContainsKey ( `` DepartmentFilter '' ) ) { Func < SurveyUserView , bool > newFilter = ( suv ) = > resultFilter ( suv ) & & suv.department == filters [ `` DepartmentFilter '' ] ; resultFilter = newFilter ; } return resultFilter ; } Func < int , int > demo = ( x ) = > x * 2 ; Func < int , int > demo2 = ( y ) = > demo ( y ) + 1 ; demo = demo2 ; int count = demo ( 1 ) ; Func < int , int > demo2 = ( y ) = > ( y * 2 ) + 1 ; Int count = demo2 ( 1 ) ; Func < int , int > demo2 = ( y ) = > demo2 ( y ) + 1 ; Int count = demo2 ( 1 ) ;
Need to & & together an indeterminate number of Func < TEntity , bool >
C_sharp : My task is simple : I have a CSV file inside a C # string , split with semicolons . I need to add spaces for each empty cell . A ; B ; ; ; ; C ; should become A ; B ; ; ; ; C ; . Right now , I 'm using the replace method twice : That 's necessary , because in the first pass , it will replace any occurance of ; ; with a space between , but there 's no lookback , so the second semicolon of the replaced sequence wo n't be checked again . Therefore I would end up with a A ; B ; ; ; ; C ; , which is not what I want.Is there a more elegant , clear , and less redundand way to solve that task ? <code> csv = csv.Replace ( `` ; ; '' , `` ; ; '' ) .Replace ( `` ; ; '' , `` ; ; '' ) ;
Better way to add spaces between double semicolons
C_sharp : There is a confusion in the arrangement of codes and the place where it pleases so I hope to find an explanation for the following : When I have a server `` https : //localhost:48009/ '' and the application is equipped with all the requirements of Signal-R and also Hub exists on it.in folder Hubs There is a Hub Class ChatHub.csand in Chat.cshtmlEverything works fine as you open the page on more than one browserHere all operations occur within the server `` https : //localhost:48009/ '' I happened to have another project on another server For example `` http : //localhost:18098/ '' in index.cshtmlHere I also seem to apply solutions to similar problems . Is this method correct ? Knowing another server `` http : //localhost:18098/ '' It is also equipped Signal-RI want to bring Hub content from there to another server Hub . <code> using System ; using System.Web ; using Microsoft.AspNet.SignalR ; namespace SignalRChat { public class ChatHub : Hub { public void Send ( string name , string message ) { // Call the addNewMessageToPage method to update clients . Clients.All.addNewMessageToPage ( name , message ) ; } } } @ { ViewBag.Title = `` Chat '' ; } < h2 > Chat < /h2 > < div class= '' container '' > < input type= '' text '' id= '' message '' / > < input type= '' button '' id= '' sendmessage '' value= '' Send '' / > < input type= '' hidden '' id= '' displayname '' / > < ul id= '' discussion '' > < /ul > < /div > @ section scripts { < ! -- Script references . -- > < ! -- The jQuery library is required and is referenced by default in _Layout.cshtml . -- > < ! -- Reference the SignalR library . -- > < script src= '' ~/Scripts/jquery.signalR-2.1.0.min.js '' > < /script > < ! -- Reference the autogenerated SignalR hub script . -- > < script src= '' ~/signalr/hubs '' > < /script > < ! -- SignalR script to update the chat page and send messages. -- > < script > $ ( function ( ) { // Reference the auto-generated proxy for the hub . var chat = $ .connection.chatHub ; // Create a function that the hub can call back to display messages . chat.client.addNewMessageToPage = function ( name , message ) { // Add the message to the page . $ ( ' # discussion ' ) .append ( ' < li > < strong > ' + htmlEncode ( name ) + ' < /strong > : ' + htmlEncode ( message ) + ' < /li > ' ) ; } ; // Get the user name and store it to prepend to messages . $ ( ' # displayname ' ) .val ( prompt ( 'Enter your name : ' , `` ) ) ; // Set initial focus to message input box . $ ( ' # message ' ) .focus ( ) ; // Start the connection . $ .connection.hub.start ( ) .done ( function ( ) { $ ( ' # sendmessage ' ) .click ( function ( ) { // Call the Send method on the hub . chat.server.send ( $ ( ' # displayname ' ) .val ( ) , $ ( ' # message ' ) .val ( ) ) ; // Clear text box and reset focus for next comment . $ ( ' # message ' ) .val ( `` ) .focus ( ) ; } ) ; } ) ; } ) ; // This optional function html-encodes messages for display in the page . function htmlEncode ( value ) { var encodedValue = $ ( ' < div / > ' ) .text ( value ) .html ( ) ; return encodedValue ; } < /script > } @ { ViewBag.Title = `` index '' ; } < h2 > Chat < /h2 > < div class= '' container '' > < input type= '' text '' id= '' message '' / > < input type= '' button '' id= '' sendmessage '' value= '' Send '' / > < input type= '' hidden '' id= '' displayname '' / > < ul id= '' discussion '' > < /ul > < /div > @ section scripts { < ! -- Script references . -- > < ! -- The jQuery library is required and is referenced by default in _Layout.cshtml . -- > < ! -- Reference the SignalR library . -- > < script src= '' ~/Scripts/jquery.signalR-2.1.0.min.js '' > < /script > < ! -- Reference the autogenerated SignalR hub script . -- > ///////////////////gotohub here < script src= '' https : //localhost:48009//signalr/hubs '' > < /script > < ! -- SignalR script to update the chat page and send messages. -- > < script > $ ( function ( ) { // Reference the auto-generated proxy for the hub . ///////Link to the other server var chat = $ .connection.chatHub.url= '' https : //localhost:48009/ '' ; // Create a function that the hub can call back to display messages . chat.client.addNewMessageToPage = function ( name , message ) { // Add the message to the page . $ ( ' # discussion ' ) .append ( ' < li > < strong > ' + htmlEncode ( name ) + ' < /strong > : ' + htmlEncode ( message ) + ' < /li > ' ) ; } ; // Get the user name and store it to prepend to messages . $ ( ' # displayname ' ) .val ( prompt ( 'Enter your name : ' , `` ) ) ; // Set initial focus to message input box . $ ( ' # message ' ) .focus ( ) ; // Start the connection . $ .connection.hub.start ( ) .done ( function ( ) { $ ( ' # sendmessage ' ) .click ( function ( ) { // Call the Send method on the hub . chat.server.send ( $ ( ' # displayname ' ) .val ( ) , $ ( ' # message ' ) .val ( ) ) ; // Clear text box and reset focus for next comment . $ ( ' # message ' ) .val ( `` ) .focus ( ) ; } ) ; } ) ; } ) ; // This optional function html-encodes messages for display in the page . function htmlEncode ( value ) { var encodedValue = $ ( ' < div / > ' ) .text ( value ) .html ( ) ; return encodedValue ; } < /script > }
How to bring Hub content from Any server to *another server* project Hub ?
C_sharp : I 'm working through some computer science exercises and I 'm embarrassed to say I do n't know how to console print the above stated code in VS Studio . I 've tried over a number of days , and part of my problem is that I do n't actually know the name of the above mentioned construction ( figuratively speaking ) . I 've done my homework , read the manual , but now there 's nothing to do but put up my hand and ask the question . Online there seems to be many examples of using IEnumerable < int > but nothing outputting the tuple that I could find . Any example code posted would be appreciated . Output : <code> public static class PythagoreanTriplet { public static IEnumerable < ( int a , int b , int c ) > TripletsWithSum ( int sum ) { return Enumerable.Range ( 1 , sum - 1 ) .SelectMany ( a = > Enumerable.Range ( a + 1 , sum - a - 1 ) .Select ( b = > ( a : a , b : b , c : sum - a - b ) ) ) .Where ( x = > x.a * x.a + x.b * x.b == x.c * x.c ) ; } } public static class testclass { public static void Main ( ) { int input = 121 ; var data = PythagoreanTriplet.TripletsWithSum ( input ) ; Console.WriteLine ( data ) ; } } System.Collections.Generic.List ` 1 [ System.ValueTuple ` 3 [ System.Int32 , System.Int32 , System.Int32 ] ]
How to Console.Writeline IEnumerable < ( int a , int b , int c ) > ?
C_sharp : Is any difference between : And ? What are the benefits of use the first one method ? <code> public void Method1 < T > ( class1 c , T obj ) where T : Imyinterface public void Method2 ( class1 c , Imyinterface obj )
interface as argument or generic method with where - what is the difference ?
C_sharp : I am learning the reflections concepts in c # . I have a class like this In another class I would like to extract the values from the list . I have stupid ways to do it likeThe operations in the foreach loops are similar . How can I do this in a clear way by using reflections ? <code> public class pdfClass { public List < AttributeProperties > TopA { get ; set ; } public List < AttributeProperties > TopB { get ; set ; } public List < AttributeProperties > TopC { get ; set ; } } public void ExtractValue ( pdfClass incomingpdfClass , string type ) { switch ( type ) { case `` TopA '' : foreach ( var listitem in incomingPdfClass.TopA ) { ... } breaks ; case `` TopB '' : foreach ( var listitem in incomingPdfClass.TopB ) { ... } breaks ; ... } }
Simple question : Reflections in C #
C_sharp : style that I have to create in code-behind . It has a checkbox that looks like this..How I do in code-behind ? <code> < GridView > < GridViewColumn Width= '' 30 '' > < GridViewColumn.CellTemplate > < DataTemplate > < StackPanel > < CheckBox/ > < /StackPanel > < /DataTemplate > < /GridViewColumn.CellTemplate > < /GridViewColumn > -- > < GridViewColumn Header= '' Groups '' DisplayMemberBinding= '' { Binding Groups } '' / > < GridViewColumn Header= '' SiteTitle '' DisplayMemberBinding= '' { Binding SiteTitle } '' / > < GridViewColumn Header= '' SiteUrl '' DisplayMemberBinding= '' { Binding SiteUrl } '' / > < /GridView >
WPF How to set checkbox in Gridview binding in code behind
C_sharp : I have a consumer class responsible for consuming a string and deciding what to do with it . It can either parse and insert the parse data in a database or notify an administrator . Below is my implementation.Below is my unit test.Is it code smell to mix mocks and real implementation in unit tests ? Also , how do always having to test whether method abc ( ) always ran once ? It does n't seem right that once I add a new unit test every time I add a function inside my if block . Seems like if I continue adding to my Consume method I 'm create a trap.Thank you . <code> public void Consume ( string email ) { if ( _emailValidator.IsLocate ( email ) ) { var parsedLocate = _parser.Parse ( email ) ; // Insert locate in database } else if ( _emailValidator.IsGoodNightCall ( email ) ) { // Notify email notifying them that a locate email requires attention . _notifier.Notify ( ) ; } } // Arrangevar validator = new EmailValidator ( ) ; var parser = new Mock < IParser > ( ) ; var notifier = new Mock < INotifier > ( ) ; var consumer = new LocateConsumer ( validator , parser.Object , notifier.Object ) ; var email = EmailLiterals.Locate ; // Actconsumer.Consume ( email ) ; // Assertparser.Verify ( x = > x.Parse ( email ) , Times.Once ( ) ) ;
Is it a test smell to mix in real implementation and mocks ?
C_sharp : After some resent tests I have found my implementation can not handle very much recursion . Although after I ran a few tests in Firefox I found that this may be more common than I originally thought . I believe the basic problem is that my implementation requires 3 calls to make a function call . The first call is made to a method named Call that makes sure the call is being made to a callable object and gets the value of any arguments that are references . The second call is made to a method named Call which is defined in the ICallable interface . This method creates the new execution context and builds the lambda expression if it has not been created . The final call is made to the lambda that the function object encapsulates . Clearly making a function call is quite heavy but I am sure that with a little bit of tweaking I can make recursion a viable tool when using this implementation . <code> public static object Call ( ExecutionContext context , object value , object [ ] args ) { var func = Reference.GetValue ( value ) as ICallable ; if ( func == null ) { throw new TypeException ( ) ; } if ( args ! = null & & args.Length > 0 ) { for ( int i = 0 ; i < args.Length ; i++ ) { args [ i ] = Reference.GetValue ( args [ i ] ) ; } } var reference = value as Reference ; if ( reference ! = null ) { if ( reference.IsProperty ) { return func.Call ( reference.Value , args ) ; } else { return func.Call ( ( ( EnviromentRecord ) reference.Value ) .ImplicitThisValue ( ) , args ) ; } } return func.Call ( Undefined.Value , args ) ; } public object Call ( object thisObject , object [ ] arguments ) { var lexicalEnviroment = Scope.NewDeclarativeEnviroment ( ) ; var variableEnviroment = Scope.NewDeclarativeEnviroment ( ) ; var thisBinding = thisObject ? ? Engine.GlobalEnviroment.GlobalObject ; var newContext = new ExecutionContext ( Engine , lexicalEnviroment , variableEnviroment , thisBinding ) ; Engine.EnterContext ( newContext ) ; var result = Function.Value ( newContext , arguments ) ; Engine.LeaveContext ( ) ; return result ; }
How can I improve the recursion capabilities of my ECMAScript implementation ?
C_sharp : For ExampleTo something like <code> txtUnitTotalQty.Text = `` '' ; txtPrice.Text = `` '' ; txtUnitPrice.Text = `` '' ; lblTotalvalue.Text = `` '' ; ( txtUnitTotalQty , txtPrice , txtUnitPrice , lblTotalvalue ) .Text = `` '' ;
Can I run multiple control but same method in C #
C_sharp : I tried the following code : This code work fine and result will contain -2 ( I know why ) .But when doing this : This will not compile because of overflow problem.Why ? <code> int x , y ; x = y = int.MaxValue ; int result = x + y ; const int x = int.MaxValue ; const int y = int.MaxValue ; int result = x + y ;
Overflow error when doing arithmetic operations with constants
C_sharp : I have a class , which holds some details in a large data structure , accepts an algorithm to perform some calculations on it , has methods to validate inputs to the data structure . But then I would like to return the data structure , so that it can be transformed into various output forms ( string / C # DataTable / custom file output ) by the View Model.I know that you are supposed to use the `` depend on interface not implementation '' design principle , so I want to create an interface for the class . How can I avoid writing the following interface ? Reason being it would expose implementation details and bind any other concrete implementations to return the same form.How can I easily iterate over the data structure to form different varieties of outputs without bluntly exposing it like this ? EDIT : Since the class takes in IFunc < IDictionary < string , IDictionary < int , ISet < IPeriod > > > > in the constructor to iterate over the data structure and perform calculations , I could supply it with another IFunc , which would construct the output instead of running calculations . However , I do n't know how I could do this aside from the concrete class constructor . <code> class MyProductsCollection { private IDictionary < string , IDictionary < int , ISet < Period > > > products ; // ctors , verify input , add and run_algorithm methods } interface IProductsCollection { IDictionary < string , IDictionary < int , ISet < IPeriod > > > GetData ( ) ; // other methods }
OO Design - Exposing implementation details through an interface
C_sharp : Whats the difference between these three ways of creating a new List < string > in C # ? <code> A = new List < string > ( ) ; B = new List < string > { } ; C = new List < string > ( ) { } ;
Whats the difference between these three ways of creating a new List < string > in C # ?
C_sharp : Okay - I 'm not even sure that the term is right - and I 'm sure there is bound to be a term for this - but I 'll do my best to explain . This is not quite a cross product here , and the order of the results are absolutely crucial.Given : Where each inner enumerable represents an instruction to produce a set of concatenations as follows ( the order here is important ) : I want to produce set ordered concatenations as follows : So clearly , there are going to be a lot of combinations ! I can see similarities with Numeric bases ( since the order is important as well ) , and I 'm sure there are permutations/combinations lurking in here too.The question is - how to write an algorithm like this that 'll cope with any number of sets of strings ? Linq , non-Linq ; I 'm not fussed.Why am I doing this ? Indeed , why ! ? In Asp.Net MVC - I want to have partial views that can be redefined for a given combination of back-end/front-end culture and language . The most basic of these would be , for a given base view View , we could have View-en-GB , View-en , View-GB , and View , in that order of precedence ( recognising of course that the language/culture codes could be the same , so some combinations might be the same - a Distinct ( ) will solve that ) .But I also have other views that , in themselves , have other possible combinations before culture is even taken into account ( too long to go into - but the fact is , this algo will enable a whole bunch of really cool that I want to offer my developers ! ) .I want to produce a search list of all the acceptable view names , iterate through the whole lot until the most specific match is found ( governed by the order that this algo will produce these concatenations in ) then serve up the resolved Partial View.The result of the search can later be cached to avoid the expense of running the algorithm all the time.I already have a really basic version of this working that just has one enumerable of strings . But this is a whole different kettle of seafood ! Any help greatly appreciated . <code> IEnumerable < IEnumerable < string > > sets = new [ ] { /* a */ new [ ] { `` a '' , `` b '' , `` c '' } , /* b */ new [ ] { `` 1 '' , `` 2 '' , `` 3 '' } , /* c */ new [ ] { `` x '' , `` y '' , `` z '' } } ; set a* = new string [ ] { `` abc '' , `` ab '' , `` a '' } ; set b* = new string [ ] { `` 123 '' , `` 12 '' , `` 1 '' } ; set c* = new string [ ] { `` xyz '' , `` xy '' , `` x '' } ; set final = new string { a* [ 0 ] + b* [ 0 ] + c* [ 0 ] , /* abc123xyz */ a* [ 0 ] + b* [ 0 ] + c* [ 1 ] , /* abc123xy */ a* [ 0 ] + b* [ 0 ] + c* [ 2 ] , /* abc123x */ a* [ 0 ] + b* [ 0 ] , /* abc123 */ a* [ 0 ] + b* [ 1 ] + c* [ 0 ] , /* abc12xyz */ a* [ 0 ] + b* [ 1 ] + c* [ 1 ] , /* abc12xy */ a* [ 0 ] + b* [ 1 ] + c* [ 2 ] , /* abc12x */ a* [ 0 ] + b* [ 1 ] , /* abc12 */ a* [ 0 ] + b* [ 2 ] + c* [ 0 ] , /* abc1xyz */ a* [ 0 ] + b* [ 2 ] + c* [ 1 ] , /* abc1xy */ a* [ 0 ] + b* [ 2 ] + c* [ 2 ] , /* abc1x */ a* [ 0 ] + b* [ 2 ] , /* abc1 */ a* [ 0 ] , /* abc */ a* [ 1 ] + b* [ 0 ] + c* [ 0 ] , /* ab123xyz */ /* and so on for a* [ 1 ] */ /* ... */ a* [ 2 ] + b* [ 0 ] + c* [ 0 ] , /* a123xyz */ /* and so on for a* [ 2 ] */ /* ... */ /* now lop off a [ * ] and start with b + c */ b* [ 0 ] + c* [ 0 ] , /* 123xyz */ /* rest of the combinations of b + c with b on its own as well */ /* then finally */ c [ 0 ] , c [ 1 ] , c [ 2 ] } ;
Calculate a set of concatenated sets of n sets
C_sharp : Is there a way to lock or freeze a part of code against formatting in Visual Studio ? I want to protect the following code : to be formatted as : but still be able to format the rest of the document . <code> Method ( `` This is a long text '' , 12 , true ) ; Method ( `` Hi '' , 558 , true ) ; Method ( `` Short text '' , 1 , false ) ; Method ( `` This is a long text '' , 12 , true ) ; Method ( `` Hi '' , 558 , true ) ; Method ( `` Short text '' , 1 , false ) ;
Freeze part of code against formatting
C_sharp : So I am recently writing a relatively complex application written in C # that performs an array of small tasks repeatedly . When I first started the application I realized that a lot of the code I was typing was repetitive and so I began encapsulating the majority of the app 's logic into separate helper classes that I could call as needed.Needless to say the size of my app ( and amount of code ) was cut in half . But as I was going through I noticed something else in my application that seemed to be repetitive and looked like it could be improved.Now most of my methods in my helper classes are either making a HttpWebRequest or performing save/delete operations on files . Having said that I need to handle the possibility that eventually the call wo n't complete , or the file ca n't save because there is n't enough space , or whatever . The problem I 'm running into is that I have to keep writing try/catch statements every time I call one of the methods . On top of that I have to retype the error message ( or Eventually a status message . I would like to know when it succeeds as well ) .So here 's kind of a snippet of what I have to type : From what I have concluded so far is : To me this is overkill having to write this over 50 times for my app.Sounds like I should be including this in the helper class andinclude the full set of catches.But how could I know the result ? I was maybe thinking of returning astring that contains the error/success message.Really for these types of methods it does n't require the method from which the helper method is being called from to enclose it in a try/catch block.Is this approach correct ? Is there another way of doing this ? Should I be using a try/catch in the calling method at all ? Since this kind of my first shot at this I would really like to hear what others who have handled this scenario have to say . <code> try { ItemManager.SaveTextPost ( myPostItem ) ; } // Majority of the time there is more than one catch ! catch { //^^^Not to mention that I have to handle multiple types of exceptions //in order to log them correctly ( more catches..ugh ! ) MessageBox.Show ( `` There was an error saving the post . `` ) ; //Perform logging here as well }
Where is the correct the place to handle exceptions in my C # applications ?
C_sharp : The instructions : Please write a piece of code that takes as an input a list in which each element is another list containing an unknown type and which returns a list of all possible lists that can be obtained by taking one element from each of the input lists . For example : [ [ 1 , 2 ] , [ 3 , 4 ] ] , should return : [ [ 1 , 3 ] , [ 1 , 4 ] , [ 2 , 3 ] , [ 2 , 4 ] ] . [ [ ' 1 ' ] , [ ' 2 ' ] , [ ' 3 ' , ' 4 ' ] ] , should return [ [ ' 1 ' , ' 2 ' , ' 3 ' ] , [ ' 1 ' , ' 2 ' , ' 4 ' ] ] .My code : How could I make it work with polymorphic method that returns a generic list ? <code> public static void Main ( string [ ] args ) { //Create a list of lists of objects . var collections = new List < List < object > > ( ) ; collections.Add ( new List < object > { 1 , 5 , 3 } ) ; collections.Add ( new List < object > { 7 , 9 } ) ; collections.Add ( new List < object > { `` a '' , `` b '' } ) ; //Get all the possible permutations var combinations = GetPermutations ( collections ) ; //Loop through the results and display them in console foreach ( var result in combinations ) { result.ForEach ( item = > Console.Write ( item + `` `` ) ) ; Console.WriteLine ( ) ; } Console.WriteLine ( `` Press any key to exit . `` ) ; Console.ReadKey ( ) ; } private static List < List < object > > GetPermutations ( List < List < object > > collections ) { List < List < object > > permutations = new List < List < object > > ( ) ; //Check if the input list has any data , else return the empty list . if ( collections.Count < = 0 ) return permutations ; //Add the values of the first set to the empty List < List < object > > //permutations list foreach ( var value in collections [ 0 ] ) permutations.Add ( new List < object > { value } ) ; /* Skip the first set of List < List < object > > collections as it was * already added to the permutations list , and loop through the * remaining sets . For each set , call the AppendValues function * to append each value in the set to the permuations list . * */ foreach ( var set in collections.Skip ( 1 ) ) permutations = AppendNewValues ( permutations , set ) ; return permutations ; } private static List < List < object > > AppendNewValues ( List < List < object > > permutations , List < object > set ) { //Loop through the values in the set and append them to each of the //list of permutations calculated so far . var newCombinations = from additional in set from value in permutations select new List < object > ( value ) { additional } ; return newCombinations.ToList ( ) ; }
Generate permutations using polymorphic method
C_sharp : I mostly develop using C # , but I think this question might be suitable for other languages as well.Also , it seems like there is a lot of code here but the question is very simple.Inlining , as I understand it , is the compiler ( in the case of C # the Virtual Machine ) replacing a method call by inserting the body of the method in every place the method was called from.Let 's say I have the following program : ... the body of the method IsEven : I could understand how code will look like after inlining the method : An obviously simple and correct program.But if I tweak the body of IsEven a little bit to include an absolute return path ... I personally like this style a bit more in some situations . Some refractoring tools might even suggest that I do change the first version to look like this one - but when I tried to imagine how this method would look like when it 's inlined I was stumped.If we inline the second version of the method : The question to be asked : How does the Compiler / Virtual Machine deal with inlining a method that has an absolute return path ? It seems extremely unlikely that something like this would really prevent method inlining , so I wonder how such things are dealt with . Perhaps the process of inlining is n't as simple as this ? Maybe one version is more likely to being inlined by the VM ? Edit : Profiling both methods ( and manual inlining of the first one ) showed no difference in performance , so I can only assume that both methods get inlined and work in the same or similar manner ( at least on my VM ) .Also , these methods are extremely simple and seem almost interchangeable , but complex methods with absolute return paths might be much more difficult to change into versions without absolute return paths . <code> static Main ( ) { int number = 7 ; bool a ; a = IsEven ( number ) ; Console.WriteLine ( a ) ; } bool IsEven ( int n ) { if ( n % 2 == 0 ) // Two conditional return paths return true ; else return false ; } static Main ( ) { int number = 7 ; bool a ; if ( number % 2 == 0 ) a = true ; else a = false ; Console.WriteLine ( a ) ; // Will print true if 'number ' is even , otherwise false } bool IsEven ( int n ) { if ( n % 2 == 0 ) return true ; return false ; // < - Absolute return path ! } static Main ( ) { int number = 7 ; bool a ; if ( number % 2 == 0 ) a = true ; a = false ; Console.WriteLine ( a ) ; // Will always print false ! }
How does a method with an absolute return path gets inlined ?
C_sharp : If I create an extension method on Enum called HasFlag , whenever I try to call HasFlag on an enum instance , it uses the extension method , rather than the instance method . Why ? With code : Compiles to : Why does n't the compiler use the Enum.HasFlag instance method ? <code> public static class Extensions { public static bool HasFlag ( this Enum e ) { return false } } public enum Foo { A , B , C } public void Whatever ( ) { Foo e = Foo.A ; if ( e.HasFlag ( ) ) { // ... } } public void Whatever ( ) { Foo e = Foo.A ; if ( Extensions.HasFlag ( e ) ) { // ... } }
Why does HasFlag extension method on Enum trump Enum.HasFlag ?
C_sharp : I 'm looking for something similar to what would have a signature like this : This needs to avoid potential race conditions across threads , processes , and even other machines accessing the same filesystem , without requiring the current user to have any more permissions than they would need for File.Create . Currently , I have the following code , which I do n't particularly like : Is there another way to do this that I 'm missing ? This fits into the following helper method , designed to create the `` next '' sequential empty file for the directory and return its path , again avoiding potential race conditions across threads , processes , and even other machines accessing the same filesystem . So I guess a valid solution could involve a different approach to this : Edit1 : We can assume that files will not be deleted from the directory while this code is executing . <code> static bool TryCreateFile ( string path ) ; static bool TryCreateFile ( string path ) { try { // If we were able to successfully create the file , // return true and close it . using ( File.Open ( path , FileMode.CreateNew ) ) { return true ; } } catch ( IOException ) { // We want to rethrow the exception if the File.Open call failed // for a reason other than that it already existed . if ( ! File.Exists ( path ) ) { throw ; } } return false ; } static string GetNextFileName ( string directoryPath ) { while ( true ) { IEnumerable < int ? > fileNumbers = Directory.EnumerateFiles ( directoryPath ) .Select ( int.Parse ) .Cast < int ? > ( ) ; int nextNumber = ( fileNumbers.Max ( ) ? ? 0 ) + 1 ; string fileName = Path.Combine ( directoryPath , nextNumber.ToString ( ) ) ; if ( TryCreateFile ( fileName ) ) { return fileName ; } } }
How do I try to create a file , and return a value indicating whether it was created or not ?
C_sharp : I am confused about what I need to do in order to correctly `` set up '' my unverifiable method so that it conforms to code access security guidelines.Given the following methodwhich is deemed unverifiable by PEVerify , what attributes do I absolutely need to apply to the method definition ? [ SecurityCritical ] ? [ SecuritySafeCritical ] ? How do I decide between those two ? Further , do I need to set [ SecurityPermission ( SecurityAction.Demand , Flags = SecurityPermissionFlag.UnmanagedCode ) ] ? If so , do I use SecurityAction.Demand or something else ? Are there any other attributes I definitely need to apply ? Are there any that I could apply , although not neccessary ? <code> [ MethodImpl ( MethodImplOptions.ForwardRef ) ] private extern void DoStuffUnverifiable ( ) ;
Confusion regarding code access security with unverifiable code
C_sharp : I want to test if an xml attribute is present . Given this : This first test works : '' GetNamedItem '' is supposed to return null , but the following test throws an exception complaining about the null it returns.Why the difference ? Just curious . <code> XmlAttributeCollection PG_attrColl = SomeNodeorAnother.Attributes ; if ( null ! = PG_attrColl [ `` SomeAttribute '' ] ) if ( null ! = PG_attrColl.GetNamedItem ( `` SomeAttribute '' ) .Value ; )
Why can one null return be tested but another throws an exception ?
C_sharp : There 's a lot of code like this in company 's application I 'm working at : From my understanding of Lazy this is totally meaningless , but I 'm new at the company and I do n't want to argue without reason.So - does this code have any sense ? <code> var something = new Lazy < ISomething > ( ( ) = > ( ISomething ) SomethingFactory .GetSomething < ISomething > ( args ) ) ; ISomething sth = something.Value ;
C # Using Lazy.Value right after its declaration
C_sharp : I have a use case in Q # where I have qubit register qs and need to apply the CNOT gate on every qubit except the first one , using the first one as control . Using a for loop I can do it as follows : Now , I wanted to give it a more functional flavor and tried instead to do something like : The Q # compiler does not accept an expression like this , informing me that it encountered an unexpected code fragment . That 's not too informative for my taste . Some documents claim that Q # supports anonymous functions a'la C # , hence the attempt above . Can anybody point me to a correct usage of lambdas in Q # or dispel my false belief ? <code> for ( i in 1..Length ( qs ) -1 ) { CNOT ( qs [ 0 ] , qs [ i ] ) ; } ApplyToEach ( q = > CNOT ( qs [ 0 ] , q ) , qs [ 1..Length ( qs ) -1 ] ) ;
Can I use lambda in Q # to operate on qubits ?
C_sharp : The .Net Equals ( ) returns different results , though we are comparing the same values . Can someone explain me why that is the case ? Has it got to do anything with the range of the types we are comparing against ? <code> class Program { static void Main ( string [ ] args ) { Int16 a = 1 ; Int32 b = 1 ; var test1 = b.Equals ( a ) ; //true var test2 = a.Equals ( b ) ; //false } }
Why does Int32.Equals ( Int16 ) return true where the reverse does n't ?
C_sharp : I had an interesting interview question the other day , which I really struggled with . The ( highly ambitious ) spec required me to write , in C # , parsers for two different data streams . Here is a made-up example of the first stream : where 30 is the currency pair , 35 is the number of tenors , and 50,51,52 are the tenor , bid and ask respectively . The bid and ask are optional , but a correct tenor-bid-ask tuple will have at least one of the two prices . The framework code they supplied implied that the result of parsing this line should be 3 individual objects ( DataElement instances ) . I ended up with a rather nasty switch-statement and loop-based implementation that I am not sure actually worked.What techniques are there for reading this kind of stream ? I tried to figure out something with recursion , which I could n't get right . EDIT : Based on @ evanmcdonnall 's answer ( accepted ) here is the fully compiling and working code , in case it 's useful for anyone else.The main concepts are : Have a separate counter for the `` inner loop '' of repeating items in each lineHave a boolean flag to indicate when that `` inner loop '' beginsAllocate the array of objects to store the `` inner loop '' results at the point where the length is known ( i.e. , tag 50 ) For simplicity and clarity , have a function that reads just a single line , then call it multiple times from a separate function . <code> 30=EUR/USD,35=3,50=ON,51=12.5,52=13.5,50=6M,51=15.4,52=16.2,50=1Y,51=17.2,52=18.3 List < DataElement > Parse ( string row ) { string currency=string.Empty ; DataElement [ ] elements = null ; int j = 0 ; bool start = false ; string [ ] tokens = row.Split ( ' , ' ) ; for ( int i = 0 ; i < tokens.Length ; i++ ) { string [ ] kv = tokens [ i ] .Split ( '= ' ) ; switch ( kv [ 0 ] ) { case `` 30 '' : currency = kv [ 1 ] ; break ; case `` 35 '' : elements = new DataElement [ int.Parse ( kv [ 1 ] ) ] ; break ; case `` 50 '' : if ( start ) j++ ; elements [ j ] = new DataElement ( ) { currency = currency , tenor = kv [ 1 ] } ; start = true ; break ; case `` 51 '' : elements [ j ] .bid = double.Parse ( kv [ 1 ] ) ; break ; case `` 52 '' : elements [ j ] .ask = double.Parse ( kv [ 1 ] ) ; break ; } } return elements.ToList ( ) ; }
Processing a data feed format
C_sharp : I 've got a list of 369 different names and I want to print these names into a csv file . All 's going well until I take a look at the outputted csv file and it only has 251 rows . I 've tried outputting to a .txt instead , and still it only outputs 251 rows . Ive stepped through with the debugger and it is still calling writer.WriteLine ( ) 369 times.Is there some sort of writing restriction in place ? If so , why 251 ? How do I write all 369 names ? Here 's my code just in case : The output on the console shows all 369 names and the names.Count prints 369 . <code> List < String > names = new List < String > ( ) ; //Retrieve names from a separate source.var writer = new StreamWriter ( File.OpenWrite ( @ '' C : names.txt '' ) ) ; for ( int i = 0 ; i < names.Count ; i++ ) { System.Console.WriteLine ( names [ i ] .ToString ( ) ) ; writer.WriteLine ( names [ i ] .ToString ( ) ) ; } System.Console.Write ( names.Count ) ;
Why does my C # program only write 251 rows to a file ?
C_sharp : I am trying to add collection initializing to my class . I read about the initializers here : https : //msdn.microsoft.com/en-us/library/bb384062.aspx # Anchor_2I 'll quote the important part that puzzles me : Collection initializers let you specify one or more element initializers when you initialize a collection class that implements IEnumerable or a class with an Add extension method.Ok , so I want to emphasize on the word or . As I read it , I should be able to make a class with an Add method , and then the collection initializer should work on this class ? This does n't seem to be the case . One thing I did note , was that it does in fact say an Add extension method . So I tried creating the Add as an extension method as well , but to no avail.Here 's a small sample I tried that does not work : Is the quote subject to other interpretations than mine ? I tried reading it over and over again , to see if I could interpret it in any other way , but failed to do so.So I guess my question is : Am I interpreting it wrong , am I missing something , or is there an error in the description of collection initializers on MSDN ? <code> public class PropertySpecificationCollection { private List < PropertySpecification > _internalArr ; public void Add ( PropertySpecification item ) { _internalArr.Add ( item ) ; } }
Using collection initializer on my own class
C_sharp : Why is it necessary in .NET Web API to have a a method that reads the content of an HTTP response asynchronously , given that there is already a method to make the request asynchronously ? Said another way , if I am using HttpClient.GetAsync ( or PostAsync , or PutAsync , etc ) , is the code really any more asynchronous by also reading the content out asynchronously ? If so , how/why ? Is this : better than this : and why ? <code> using ( var client = new HttpClient ( ) ) { var response = await client.GetAsync ( `` ... '' ) ; response.EnsureSuccessStatusCode ( ) ; return await response.Content.ReadAsAsync < Foo > ( ) ; } using ( var client = new HttpClient ( ) ) { var response = await client.GetAsync ( `` ... '' ) ; response.EnsureSuccessStatusCode ( ) ; return response.Content.ReadAsAsync < Foo > ( ) .Result ; }
Why await both the asynchronous request and the reading of its contents ?
C_sharp : I recently had a program fail in a production server because the server was missing a time zone , so the following line threw an exception : I fixed it exporting the time zone registry branch from a test server , importing it to the production server.My question is , is it possible to install time zones selectively ? How is it possible that one was missing ? <code> TimeZoneInfo.ConvertTime ( date , TimeZoneInfo.Local , TimeZoneInfo.FindSystemTimeZoneById ( `` Argentina Standard Time '' ) )
Is it possible to install time zones on a server ?
C_sharp : I 've been refactoring a common pattern in my project and found it 's not as simple as using a LINQ Select to an async function.For context , here is how it is done currently.Now if I try to replace the ForEach loop section using LINQ : It complains Type arguments can not be inferred by the usage which leads me to believe I 'm not returning anything from the Select , but I clearly am returning the Func I want.Is there a better way of creating a list of Func 's , ideally avoiding explicit casts ? Also is there any explanation why the compiler is unable to infer the type when the Select 'd async method is clearly telling it what the type should be ? To be clear , I do need to pass the CancellationToken to the Func 's because it is a different token than the external one ( specifically , it is a linked token tying the external one to another internal one ) . <code> async Task < ICollection < Group > > ExecuteQueryGroupsForDomain ( DomainInfo domain , int batchSize , CancellationToken ct ) { try { return await BlahBlahActuallyGoGetGroupsForDomainHere ( domain , batchSize , ct ) ; } catch ( Exception e ) { return null ; } } var executeQueries = new List < Func < CancellationToken , Task < ICollection < Group > > > > ( ) ; domains.ForEach ( domain = > executeQueries.Add ( async ( ct ) = > await ExecuteQueryGroupsForDomain ( domain , 123 , ct ) ) ) ; var executeQueries = domains.Select ( domain = > async ( ct ) = > await ExecuteQueryGroupsForDomain ( domain , 123 , ct ) ) ;
Better way to Select to an async Func ?
C_sharp : Let 's say I have : And containers of these two types of animals : Is there a way to cast 'lions ' and 'boars ' so that I can pass them into a function like this ? <code> public class Animal { virtual public void Attack ( ) { } ; } public class Lion : Animal { public override void Attack ( ) { base.Attack ( ) ; } } public class Boar : Animal { public override void Attack ( ) { base.Attack ( ) ; } } Dictionary < int , Lion > lions ; Dictionary < int , Boar > boars ; void IterateTable ( Dictionary < int , Animal > dictionary ) { foreach ( var entry in dictionary ) entry.Value.Attack ( ) ; }
How do you cast a dictionary < int , child > to dictionary < int , parent > ?