text
stringlengths 46
37.3k
| title
stringlengths 12
162
|
|---|---|
C_sharp : I have run some tests on the new spatial library SqlGeography in SQL Server 2016 , which according to Microsoft should be a lot faster than the previous versions : SQL Server 2016 – It Just Runs Faster : Native Spatial Implementation ( s ) . Apply SQL Server 2016 and a breadth of methods and spatial activities are faster and scale better . There are no application or database changes just the SQL Server binary updates showing dramatic improvement.However , the tests shows that the new library is slower than the old one . I have tested it in C # with the Nugets published by Microsoft , Microsoft.SqlServer.Types . I have tested version 11 against version 14 ( SQL Server 2016 ) . What should I do in order to get the new spatial library to perform better ? The source code for the small test is : <code> var line1 = CreateLine ( 56 , -4 , 58 , 16 ) ; var line2 = CreateLine ( 58 , -4 , 56 , 16 ) ; for ( int i = 0 ; i < 50000 ; i++ ) { var intersection = line1.STIntersects ( line2 ) ; var contains = line1.STBuffer ( 1000 ) .STContains ( line1 ) ; } public static SqlGeography CreateLine ( double fromLat , double fromLon , double toLat , double toLon ) { SqlGeographyBuilder constructed = new SqlGeographyBuilder ( ) ; constructed.SetSrid ( 4326 ) ; constructed.BeginGeography ( OpenGisGeographyType.LineString ) ; constructed.BeginFigure ( fromLat , fromLon ) ; constructed.AddLine ( toLat , toLon ) ; constructed.EndFigure ( ) ; constructed.EndGeography ( ) ; var line = constructed.ConstructedGeography ; return line ; }
|
SqlGeography spatial operations slow - SQL Server 2016
|
C_sharp : Exhibit 1 : some code wrapping an Async ( not async ! ) network call into a TaskInstalling .Net 4.5 ( not pointing VS at it , nor recompiling ) stops this working . The callback is never invoked.Any ideas what could be causing this , and otherwise , what I can do to try and further narrow down the root cause of the problem or work around it ? <code> public static Task < byte [ ] > GetAsync ( IConnection connection , uint id ) { ReadDataJob jobRDO = new ReadDataJob ( ) ; //No overload of FromAsync takes 4 extra parameters , so we have to wrap // Begin in a Func so that it looks like it takes no parameters except // callback and state Func < AsyncCallback , object , IAsyncResult > wrapped = ( callback , state ) = > jobRDO.Begin ( connection , 0 , 0 , id , callback , state ) ; return Task < byte [ ] > .Factory.FromAsync ( wrapped , ar = > { ErrorCode errorCode ; UInt32 sError ; UInt32 attribute ; byte [ ] data = new byte [ 10 ] ; jobRDO.End ( out errorCode , out sError , out attribute , out data ) ; if ( error ! = ErrorCode.NO_ERROR ) throw new Exception ( error.ToString ( ) ) ; return data ; } , jobRDO ) ; }
|
.Net 4.5 killed my TPL , now what ?
|
C_sharp : I try to get a data record ID from Entity Framework : The problem is , that there is a PlantArea with the ID 0 . SingleOrDefault returns 0 , though , if it does n't find any record . So how can I differenciate between ID 0 and the case , where no data was found ? My first idea was to provide a default value -1 , but SingleOrDefault does n't seem to support that in this constellation.How can I do that ? <code> var plantAreaID = await db.PlantAreas .Where ( p = > p.Plant.CompanyNo == companyNo & & p.Plant.Abbreviation == companyAbbr ) .Select ( p = > p.ID ) .SingleOrDefaultAsync ( ) ;
|
Define default value for SingleOrDefault Linq method
|
C_sharp : Assume I have an array of bytes which are truly random ( e.g . captured from an entropy source ) . Now , I want to get a random double precision floating point value , but between the values of 0 and positive 1 ( like the Random.NextDouble ( ) function performs ) .Simply passing an array of 8 random bytes into BitConverter.ToDouble ( ) can yield strange results , but most importantly , the results will almost never be less than 1 . I am fine with bit-manipulation , but the formatting of floating point numbers has always been mysterious to me . I tried many combinations of bits to apply randomness to and always ended up finding the numbers were either just over 1 , always VERY close to 0 , or very large.Can someone explain which bits should be made random in a double in order to make it random within the range 0 and 1 ? <code> byte [ ] myTrulyRandomBytes = MyEntropyHardwareEngine.GetBytes ( 8 ) ;
|
Get random double ( floating point ) value from random byte array between 0 and 1 in C # ?
|
C_sharp : I have a KeyPressed signal in Gtk # /mono C # for two different purposes which are not present in the default TreeView : a ) go to the next cell by pressing TAB , and b ) start editing by pressing any key.The TreeView is simple , it has a ListStore showing only rows and columns , i.e . it holds tabular data.The code I have is below.I have two questions : How can I signal to the TreeView that a cell has been finished editing ? The problem is that if you press TAB when no cell is being edited , everything works fine . However , if the user is editing a cell , then the contents entered so far is lost . So , in case the user is editing a cell , I want to signal to the TreeView to finish the edition , and the carry on with the current behaviour.How can I avoid losing the first key when editing a cell ? Say you are over a cell . You press the keys 1 , 2 , 3 , and 4 . My handler correctly interferes , and puts the current cell in edition mode . However , the cell only gets 2 , 3 , and 4 , though I am setting arg.RetVal to false.Info about my functionsGetCurrentCell ( row , col ) translates the current cell from a TreePath to a pair of ints.SetCurrentCell ( row , col , [ edit ] ) uses TreeView.SetCursor ( ) in order to make a cell current . edit can be true or false . If true , then the cell is put in edition . If it is false , nothing is edited . <code> [ GLib.ConnectBefore ] protected void OnTableKeyPressed ( object o , Gtk.KeyPressEventArgs args ) { int rowIndex ; int colIndex ; // Do not `` eat '' the key , by default args.RetVal = false ; // Get the current position , needed in both cases . this.GetCurrentCell ( out rowIndex , out colIndex ) ; // Adapt the column colIndex += NumFixedColumns ; if ( args.Event.Key ! = Gdk.Key.ISO_Enter ) { if ( args.Event.Key == Gdk.Key.Tab || args.Event.Key == Gdk.Key.ISO_Left_Tab ) { if ( args.Event.State == Gdk.ModifierType.ShiftMask ) { // Back colIndex -= 1 ; if ( colIndex < 1 ) { colIndex = document.Columns ; -- rowIndex ; } rowIndex = Math.Max ( 0 , rowIndex ) ; } else { // Advance colIndex += 1 ; if ( colIndex > document.Columns ) { colIndex = 1 ; ++rowIndex ; } rowIndex = Math.Min ( rowIndex , document.Rows ) ; } this.SetCurrentCell ( rowIndex , colIndex ) ; args.RetVal = true ; // Eat the TAB } else { this.SetCurrentCell ( rowIndex , colIndex , true ) ; } } return ; }
|
How to manage key pressings for special purposes in Gtk # TreeView ?
|
C_sharp : I have a WPF application that does a lot of matching across large datasets , and currently it uses C # and LINQ to match POCOs and display in a grid . As the number of datasets included has increased , and the volume of data has increased , I 've been asked to look at performance issues . One of the assumptions that I was testing this evening was whether there 's a substantive difference if we were to convert some of the code to C++ CLI . To that end I wrote a simple test that creates a List < > with 5,000,000 items , and then does some simple matching . The basic object structure is : One thing that I noticed was that on average , for the simple test of creating the list and then building a sub-list of all objects with an even ID , the C++/CLI code was about 8 % slower on my development machine ( 64bit Win8 , 8GB of RAM ) . For example , the case of a C # object being created and filtered took ~7 seconds , while the C++/CLI code took ~8 seconds on average . Curious as to why this would be , I used ILDASM to see what was happening under the covers , and was surprised to see that the C++/CLI code has extra steps in the constructor . First the test code : The C # class is above . The C++ class is defined as : When I extract the IL for both classes ' constructors , this is what I get . First the C # : And then the C++ : My question is : why is the C++ code using the local to store the value of the call from DateTime.Now ? Is there a C++-specific reason for this to happen , or is it just how they chose to implement the compiler ? I know already that there are many other ways to improve performance , and I know that I 'm pretty far down the rabbit hole as it is , but I was curious to know if anyone could shed some light on this . It 's been a long time since I 've done C++ , and with the advent of Windows 8 , and Microsoft 's renewed focus on C++ , I thought it would be good to refresh , and that was also part of my motivation for this exercise , but the difference between the two compiler outputs caught my eye . <code> public class CsClassWithProps { public CsClassWithProps ( ) { CreateDate = DateTime.Now ; } public long Id { get ; set ; } public string Name { get ; set ; } public DateTime CreateDate { get ; set ; } } static void CreateCppObjectWithMembers ( ) { List < CppClassWithMembers > results = new List < CppClassWithMembers > ( ) ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; for ( int i = 0 ; i < Iterations ; i++ ) { results.Add ( new CppClassWithMembers ( ) { Id = i , Name = string.Format ( `` Name { 0 } '' , i ) } ) ; } var halfResults = results.Where ( x = > x.Id % 2 == 0 ) .ToList ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Took { 0 } total seconds to execute '' , sw.Elapsed.TotalSeconds ) ; } public ref class CppClassWithMembers { public : long long Id ; System : :DateTime CreateDateTime ; System : :String^ Name ; CppClassWithMembers ( ) { this- > CreateDateTime = System : :DateTime : :Now ; } } ; .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { // Code size 21 ( 0x15 ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : call instance void [ mscorlib ] System.Object : :.ctor ( ) IL_0006 : nop IL_0007 : nop IL_0008 : ldarg.0 IL_0009 : call valuetype [ mscorlib ] System.DateTime [ mscorlib ] System.DateTime : :get_Now ( ) IL_000e : stfld valuetype [ mscorlib ] System.DateTime CsLibWithMembers.CsClassWithMembers : :CreateDate IL_0013 : nop IL_0014 : ret } // end of method CsClassWithMembers : :.ctor .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { // Code size 25 ( 0x19 ) .maxstack 2 .locals ( [ 0 ] valuetype [ mscorlib ] System.DateTime V_0 ) IL_0000 : ldarg.0 IL_0001 : call instance void [ mscorlib ] System.Object : :.ctor ( ) IL_0006 : call valuetype [ mscorlib ] System.DateTime [ mscorlib ] System.DateTime : :get_Now ( ) IL_000b : stloc.0 IL_000c : ldarg.0 IL_000d : ldloc.0 IL_000e : box [ mscorlib ] System.DateTime IL_0013 : stfld class [ mscorlib ] System.ValueType modopt ( [ mscorlib ] System.DateTime ) modopt ( [ mscorlib ] System.Runtime.CompilerServices.IsBoxed ) CppLibWithMembers.CppClassWithMembers : :CreateDateTime IL_0018 : ret } // end of method CppClassWithMembers : :.ctor
|
Differences Between Output of C # Compiler and C++/CLI Compiler
|
C_sharp : Say I have the following class definitions : If I would want to do the work done in DoWork ( ) , on the form , asynchronously I could add a method ( GetCalculationTask ) that returns a task using Task.Run ( ) and add a async eventhandler i.e . For a button ( MethodOne ) . Please correct me if I 'm wrong , but it seems to me that this would be the only option when the ClassThatUsesACalculator and Calculator classes reside in a library I do n't own.In the case I do own the library I think there are two more options , one of which very much like the first one . Probably due to the lack of my own understanding.Create a method on on ClassThatUsesACalculator that encapsulates the DoWork ( ) method and then call that from an asynchronous method on the form.or , Encapsulate the LongRunningCalculation ( ) on the Calculator class with a Task.Run ( ) .Create an async method on ClassThatUsesACalculator the calls that awaits the newly created method.Create an asynchronous method on the form ( MethodThree ) Now , in my opinion the last option would be the best as I would remain more control . But maybe I 'm way off and would like someone 's opinion or pointers on this as I can only find explanations on how to consume async , but never really how to build methods for others to consume . <code> public class Calculator { public CalculatorResult Calculate ( ) { return LongRunningCalculation ( ) ; } private CalculatorResult LongRunningCalculation ( ) { return new CalculatorResult ( 0.00 ) ; } } public class ClassThatUsesACalculator { private readonly Calculator calculator ; public ClassThatUsesACalculator ( ) { this.calculator = new Calculator ( ) ; } public void DoWork ( ) { for ( int i = 0 ; i < 10 ; i++ ) { var result = calculator.Calculate ( ) ; DoSomethingWithCalculationResult ( result ) ; DoLightWork ( ) ; OnProgressChanged ( ) ; } } } public partial class Form : Form { public Form ( ) { InitializeComponent ( ) ; } private void Method ( object sender , EventArgs e ) { DoWork ( ) ; } private void DoWork ( ) { var calculator = new ClassThatUsesACalculator ( ) ; calculator.ProgressChanged += ( s , e ) = > { // Update progressbar } ; calculator.DoWork ( ) ; } } private Task GetCalculationTask ( IProgress < CalculatorProgress > progress ) { var calculator = new ClassThatUsesACalculator ( ) ; calculator.ProgressChanged += ( s , e ) = > { progress.Report ( new CalculatorProgress ( 0 ) ) ; } ; return Task.Run ( ( ) = > { calculator.DoWork ( ) ; } ) ; } private async void MethodOne ( object sender , EventArgs e ) { IProgress < CalculatorProgress > progress = new Progress < CalculatorProgress > ( UpdateProgressBar ) ; await GetCalculationTask ( progress ) ; } public Task < CalculatorResult > CalculateAsync ( ) { return Task.Run ( ( ) = > { return LongRunningCalculation ( ) ; } ) ; } public async Task DoWorkAsync ( ) { for ( int i = 0 ; i < 10 ; i++ ) { var result = await calculator.CalculateAsync ( ) ; DoSomethingWithCalculationResult ( result ) ; DoLightWork ( ) ; OnProgressChanged ( ) ; } } private async void MethodThree ( object sender , EventArgs e ) { IProgress < CalculatorProgress > progress = new Progress < CalculatorProgress > ( UpdateProgressBar ) ; var calculator = new ClassThatUsesACalculator ( ) ; calculator.ProgressChanged += ( s , args ) = > { progress.Report ( new CalculatorProgress ( 0 ) ) ; } ; await calculator.DoWorkAsync ( ) ; }
|
Best practice on using async / await
|
C_sharp : I have following code in c # In this case I am getting 0 and 3 but in the following case I am getting 3,3 why is it so ? <code> class Test { public static int X = Y ; public static int Y = 3 ; } static void Main ( ) { Console.WriteLine ( Test.X ) ; Console.WriteLine ( Test.Y ) ; } class Test { public static int X = 3 ; public static int Y = X ; } static void Main ( ) { Console.WriteLine ( Test.X ) ; Console.WriteLine ( Test.Y ) ; }
|
Static field initializers in c #
|
C_sharp : I 'm trying to trim a string with String.Trim : But I 'm getting the result of : Instead of : I also tried using : But it still returns the same result.Also if I do : I get : I 'm really confused why this is happening . Could it be because the semicolon is not the last character in the string ? Here is the full code : It 's true that my while loop is pointless , but it is `` WIP '' and not the final version . <code> split [ 2 ] .Trim ( ' ; ' ) System ; System split [ 2 ] .TrimEnd ( ' ; ' ) split [ 2 ] .Trim ( 'S ' , ' ; ' ) ystem ; string line = @ '' using System ; using System.Windows.Forms ; class HelloWorld { static void Main ( ) { # if DebugConfig Console.WriteLine ( `` WE ARE IN THE DEBUG CONFIGURATION '' ) ; # endif Console.WriteLine ( `` Hello , world ! `` ) ; DialogResult result ; result = MessageBox.Show ( `` Itsyeboi '' , `` Yup '' , MessageBoxButtons.YesNo ) ; if ( result == DialogResult.Yes ) { Console.WriteLine ( `` Yes '' ) ; Console.ReadLine ( ) ; } else { Console.WriteLine ( `` No '' ) ; Console.ReadLine ( ) ; } } } '' string [ ] split = line.Split ( ' ' , '\n ' ) ; while ( true ) { if ( split [ counter4 ] == `` using '' ) { richTextBox1.Text = split [ 1 ] .Trim ( ' ; ' ) ; break ; } else { richTextBox1.Text = line ; break ; } }
|
Why is String.Trim not trimming a semicolon ?
|
C_sharp : With the new C # 8 Using Declaration Syntax , what is containing scope of a second consecutive using statement ? TL ; DRPrevious to C # 8 , having a consecutive using statement like : would expand to something like the following ( My Source ) : I know that there are two other possible expansions but they all are roughly like thisAfter upgrading to C # 8 , Visual studio offered a Code Cleanup suggestion that I 'm not certain I believe is an equivalent suggestion.It converted the above consecutive using statement to : To me this changes the second 's scope to the same scope as the first . In this case , It would probably coincidentally dispose of the streams in the correct order , but I 'm not certain I like to rely on that happy coincidence.To be clear on what VS asked me to do : I first converted the inner ( which made sense because the inner was still contained in the outer 's scope ) . Then I converted the outer ( which locally made sense because it was still contained in the method 's scope ) . The combination of these two clean ups is what I 'm curious about.I also recognize that my thinking on this could be slightly ( or even dramatically ) off , but as I understand it today , this does n't seem correct . What is missing in my assessment ? Am I off base ? The only thing I can think of is that there is some sort of an implicit scope inserted in the expansion for everything following a declaration statement . <code> using ( var disposable = new MemoryStream ( ) ) { using ( var secondDisposable = new StreamWriter ( disposable ) ) { } } MemoryStream disposable = new MemoryStream ( ) ; try { { StreamWriter secondDisposable = new StreamWriter ( disposable ) ; try { { } } finally { if ( secondDisposable ! = null ) ( ( IDisposable ) secondDisposable ) .Dispose ( ) ; } } } finally { if ( disposable ! = null ) ( ( IDisposable ) disposable ) .Dispose ( ) ; } using var disposable = new MemoryStream ( ) ; using var secondDisposable = new StreamWriter ( disposable ) ;
|
C # 8 Using Declaration Scope Confusion
|
C_sharp : Short and simple . Does the new string interpolation in C # 6.0 rely on reflection ? I.e . doesuse reflection at runtime to find the variable `` name '' and its value ? <code> string myStr = $ '' Hi { name } , how are you ? `` ;
|
Does C # 6.0 's String interpolation rely on Reflection ?
|
C_sharp : When I use Entity Framework against a SQL table , it only refers to the necessary columns in the generated SQL : becomesHowever , if I make an analogous query against a SQL view , Entity Framework generates SQL referring to every column in the view : becomesI 'm sure SQL Server will perform its own optimization to end up ignoring all the columns it does n't care about , but this still results in a massive block of SQL being sent to the server . ( My actual example included a join , which resulted in every column from several tables being selected ... ) Is there a good reason for Entity Framework to do this ? Is there a way to make it not do this ? <code> ctx.Types.Select ( rdi = > rdi.Name ) SELECT [ Extent1 ] . [ Name ] AS [ Name ] FROM [ dbo ] . [ Types ] AS [ Extent1 ] ViewTypes.Select ( rdi = > rdi.Name ) SELECT [ Extent1 ] . [ Name ] AS [ Name ] FROM ( SELECT [ ViewTypes ] . [ Name ] AS [ Name ] , ... every other column in my view ... FROM [ dbo ] . [ ViewReferenceDataTypes ] AS [ ViewReferenceDataTypes ] ) AS [ Extent1 ]
|
Entity Framework selects too many columns in views
|
C_sharp : Quick Question , See this code : And : Why result.Add ( value ) not executed ? However this not executed , Another question that is have a way do a foreach on a IEnumerable with Extention Method ? Except this way : IEnumerable.ToList ( ) .Foreach ( p= > ... ) <code> List < int > result = new List < int > ( ) ; var list = new List < int > { 1 , 2 , 3 , 4 } ; list.Select ( value = > { result.Add ( value ) ; //Does not work ? ? return value ; } ) ; result.Count == 0 //true
|
Foreach with Extension Method on IEnumerable
|
C_sharp : This works perfectly.. This returns a compiler error ... Same happen when using reflection ... So , does somebody know why the enum-base is just an integral-type ? <code> public enum NodeType : byte { Search , Analysis , Output , Input , Audio , Movement } public enum NodeType : Byte { Search , Analysis , Output , Input , Audio , Movement }
|
Why can you use just the alias to declare a enum and not the .NET type ?
|
C_sharp : I came across this line of code in a book : This sort of thing seems like tail-chasing to me ... Why is the c = > c. necessary ? Would n't the following be understandable ( by the compiler , and even more so by humans ) ? I 'm sure there 's all kinds of fancy stuff going on behind the scenes that purportedly needs this weird lambda syntax , but again : Why ? Is it really necessary ? Ca n't the compiler figure out DatePosted is the column by which to sort ? <code> var data = db.Query ( sql ) .OrderByDescending ( c = > c.DatePosted ) ; var data = db.Query ( sql ) .OrderByDescending ( DatePosted ) ;
|
Why do lambdas require = > as part of their syntax ?
|
C_sharp : Recently I moved from VB to C # , so I often use a C # to VB.NET converter to understand syntax differences.While moving next method to VB I noticed an interesting thing.C # original code : VB.NET result : C # 's ++ operator replaced with System.Threading.Interlocked.IncrementDoes it mean that not threadsafe ++ operator become threadsafe if used in foreach loop ? Is it a kind of syntax sugar ? If that is true , then why converter placed Interlocked.Increment in VB version ? I thought foreach in both C # and VB works exactly the same . Or it 's just a converter `` insurance '' ? <code> public bool ExceedsThreshold ( int threshold , IEnumerable < bool > bools ) { int trueCnt = 0 ; foreach ( bool b in bools ) if ( b & & ( ++trueCnt > threshold ) ) return true ; return false ; } Public Function ExceedsThreshold ( threshold As Integer , bools As IEnumerable ( Of Boolean ) ) As BooleanDim trueCnt As Integer = 0For Each b As Boolean In bools If b AndAlso ( System.Threading.Interlocked.Increment ( trueCnt ) > threshold ) Then Return True End IfNextReturn False End Function
|
Does C # ++ operator become threadsafe in foreach loop ?
|
C_sharp : I know how to use locks in my app , but there still few things that I do n't quite understand about locking ( BTW - I know that the lock statement is just a shorthand notation for working with Monitor class type ) .From http : //msdn.microsoft.com/en-us/library/ms173179.aspx : The argument provided to the lock keyword must be an object based on a reference type , and is used to define the scope of the lock . In the example above , the lock scope is limited to this function because no references to the object lockThis exist outside the function . If such a reference did exist , lock scope would extend to that object . a ) I don ’ t understand how lockThis object defines the scope of the lock . Scope of the lock is all the code between lock ( lockThis ) { and adjacent } , so what exactly is it meant by “ lock scope would extend to that object ” ? b ) What does the term locking on object lockThis mean ? Simply that we use a reference to lockThis to lock a region of code ? Thus , the term does n't suggest that we locked lockThis object ? thanxReplying to David Morton : I apologize if my reply is a bit long winded , but I could n't think of any other way to word my questions and still be somewhat coherent : The scope of the lock , in this situation , is the individual instance of the class itself . This is opposed to crossing all instance of the specific class . You could have your lock cross all instances TestThreading by making lockThis static . That 's what 's meant by the `` scope '' of the lock : whether it 's applicable to a single instance , or applicable to every instance of a particular type . Other objects could still access lockThis from another thread , but they would n't be able to process code that is surrounded by a lock on that object.If we call the code surrounded by lock ( located inside TestThreading.Function ) C , then since TestThreading.Function is not static , each TestThreading instance has its own copy of C. But if TestThreading.Function was static , then all TestThreading instances would share the same copy of C. As an analogy , if C is a room and if TestThreading.Function is not static , then each TestThreading instance would have its own C room , but if function was static , then all TestThreading instances would share the same C room . Following that analogy , I interpret lockThis as a key to room C. If lockThis is static and if TestThreading.Function is not static , then all TestThreading instances would use same key to enter their own C rooms . Thus , I don ’ t see any significance in lockThis being static or not , since in either case each TestThreading instance will use lockThis to enter its own room C ( assuming TestThreading.Function is not static ) . Thus , following that logic , should n't the scope of the lock always be individual instance of the class ( assuming TestThreading.Function is not static ) ? Similarly , I don ’ t see any significance in lockThis being private or public , since again TestThreading instance will use lockThis to enter its own room C ( assuming TestThreading.Function is not static ) Second reply to David Morton In response to your response : There is a significance . If TestThreading.Function is static , then lockThis has to be static , otherwise , TestThreading.Function can not access lockThis at all . I ’ m not sure what you mean by TestThreading.Function not being able to access lockThis ? ! Again assume we call the code surrounded by lock ( located inside TestThreading.Function ) C.If TestThreading.Function is static and thus there is only one room , but lockThis is non-static , and if we have the following definition : ,then whenever some thread would access room C , it would use a new key . Thus , if 100 threads accessed room C , then same room would be opened using 100 different keys ? ! So the code does work , it just doesn ’ t make much sense , since there would be no synchronization at all between threads ? ! The scope of the lock , in this situation , is the individual instance of the class itself . This is opposed to crossing all instance of the specific class . You could have your lock cross all instances TestThreading by making lockThis static.I was confused with the term scope of the lock , since I ’ ve interpret it as : if the lockThis was static , then all TestThread instances would share the same room ( aka lock ) , even though TestThread.Function isn ’ t static . Assuming I understand it correctly now , then the term lock is referring to the key ( thus lock doesn ’ t refer to the room ? ! ) used for opening the doors ? As such , if we assume that lockThis is static and TestThread.Function is not static , then the scope of the key/lock is all TestThread instances , which means that all TestThread instances share the same key and thus when one TestThread instance opens the door to its room using this key , the other instances won ’ t be able to open the doors to their rooms until first instance releases that key ? Third reply to David Morton No , if Function is static , then all TestThread instances would share the same room , if lockThis is static , then all TestThread instances would share the same key.Do you agree that the word lock used in a sentence scope of the lock at least in a way refers to the key ( key being lockThis instance ) ? The room is the code that is executed within the lock , not the lockThis object itself , that 's simply the key . [ Defense mode ON ] That ’ s what I ’ ve said in my last reply . ; ) [ Defense mode OFF ] <code> public class TestThreading { private System.Object lockThis = new System.Object ( ) ; public void Function ( ) { lock ( lockThis ) { // Access thread-sensitive resources . } } } public class TestThreading { private System.Object lockThis = new System.Object ( ) ; public static void Function ( ) { lock ( new TestThreading ( ) .lockThis ) { // Access thread-sensitive resources . } } }
|
Few confusing things about locks
|
C_sharp : I find myself quite often in the following situation : I have a user control which is bound to some data . Whenever the control is updated , the underlying data is updated . Whenever the underlying data is updated , the control is updated . So it 's quite easy to get stuck in a never ending loop of updates ( control updates data , data updates control , control updates data , etc . ) .Usually I get around this by having a bool ( e.g . updatedByUser ) so I know whether a control has been updated programmatically or by the user , then I can decide whether or not to fire off the event to update the underlying data . This does n't seem very neat.Are there some best practices for dealing with such scenarios ? EDIT : I 've added the following code example , but I think I have answered my own question ... ? <code> public partial class View : UserControl { private Model model = new Model ( ) ; public View ( ) { InitializeComponent ( ) ; } public event EventHandler < Model > DataUpdated ; public Model Model { get { return model ; } set { if ( value ! = null ) { model = value ; UpdateTextBoxes ( ) ; } } } private void UpdateTextBoxes ( ) { if ( InvokeRequired ) { Invoke ( new Action ( ( ) = > UpdateTextBoxes ( ) ) ) ; } else { textBox1.Text = model.Text1 ; textBox2.Text = model.Text2 ; } } private void textBox1_TextChanged ( object sender , EventArgs e ) { model.Text1 = ( ( TextBox ) sender ) .Text ; OnModelUpdated ( ) ; } private void textBox2_TextChanged ( object sender , EventArgs e ) { model.Text2 = ( ( TextBox ) sender ) .Text ; OnModelUpdated ( ) ; } private void OnModelUpdated ( ) { DataUpdated ? .Invoke ( this , model ) ; } } public class Model { public string Text1 { get ; set ; } public string Text2 { get ; set ; } } public class Presenter { private Model model ; private View view ; public Presenter ( Model model , View view ) { this.model = model ; this.view = view ; view.DataUpdated += View_DataUpdated ; } public Model Model { get { return model ; } set { model = value ; view.Model = model ; } } private void View_DataUpdated ( object sender , Model e ) { //This is fine . model = e ; //This causes the circular dependency . Model = e ; } }
|
Event circularity
|
C_sharp : I need an idea how to do the following animation idea . Lets assume I have a view model defined as such : The IPage object is , plainly spoken , a piece of paper with the title and the description written on it . When the IPage object changes in my view model I want to have an animation as outlined below : The paper should spin 180° . At the stage when it spun 90° I need to update the shown content.Is that possible with my view models ? Are there any nice WPF tricks for that ? <code> public interface IMyViewModel { IPage CurrentPage { get ; set ; } } public interface IPage { string Title { get ; set ; } string Description { get ; set ; } }
|
WPF animation idea for flipping a page
|
C_sharp : I was tasked with converting a solution from VB to C # . There were 22 projects and hundreds of classes , so I decided to research converters . I finally settled on SharpDevelop , which is an IDE with an included converter . I ran it on each of my projects , and have plenty of errors to fix , but I should be able to go through them and hopefully figure them out . The main issue I am having is with the summary log . I have hundreds of lines for various classes reading : I 've looked this up , but am not finding a good explanation on what it really means or how to correct it . most of what I find are lines of commented code that say something like:40 : Could someone please provide a bit more information on what causes this error means and how to correct it . Thank you . <code> -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality // ERROR : Case labels with binary operators are unsupported : LessThan
|
Converting from VB to C #
|
C_sharp : I have list object 's . But it has duplicate records for 2 key - itemId and itemTypeId . How do I remove duplicates from the list ? I tried GroupBy - but it can only use one key at a time.Actual Result : to1 and to3 <code> public class TestObject { public string Name ; public int itemTypeId ; public int itemId ; public int id ; } List < TestObject > testList = new List < TestObject > ( ) ; TestObject to1 = new TestObject ( ) ; TestObject to2 = new TestObject ( ) ; TestObject to3 = new TestObject ( ) : to1.id = 1 ; to1.itemId = 252 ; to1.itemTypeId = 1 ; to1.Name = `` to1 '' ; to2.id = 2 ; to2.itemId = 252 ; to2.itemTypeId = 1 ; to2.Name = `` to2 '' ; to3.id = 3 ; to3.itemId = 252 ; to3.itemTypeId = 2 ; to3.Name = `` to3 '' testList.Add ( to1 ) ; testList.Add ( to2 ) ; testList.Add ( to3 ) ; var result = testList.GroupBy ( x= > x.itemId ) .Select ( g = > g.First ( ) ) .ToList ( ) ;
|
How to remove duplicate object in List with double key
|
C_sharp : I have two methods ( in C # ) : These operations have no common objects ( aside from the pizzas that are passed from one to the other ) , and are thread-safe . They each take several seconds to execute and they each use different resources ( oven vs car ) . As such , I want to run them at the same time.How do I organize the threading with these constraints : I know all of the Orders at the start ( say , I have 100,000 of them ) . An Order can consist of multiple Pizzas and I do n't know how many Pizzas are in any Order until after those Pizzas are cooked . ( wierd I know ) . Generally an Order has 1 Pizza , but there can be as many as 10.The number of active Pizzas should not generally exceed 100 . This includes Pizzas freshly cooked and Pizzas being delivered . This is a soft limit , so I can exceed it some ( for example , when a big Order was cooked ) . The hard limit is probably closer to 500.Both of the operations are more efficient when they are given a lot of work . Generally , CookPizza is most efficient when given at least 20 Orders . Deliver Pizza is most efficient when given at least 50 Pizzas . That is to say , I will see performance degrade if I give fewer items to those methods than those amounts . It 's fine to use fewer items if that 's all that is left.The main issue I 'm stuggling with is how the methods may need to wait on each other.DeliverPizza might need to wait around for CookPizza to complete 50.CookPizza might need to wait around for DeliverPizza to reduce the number of active Pizzas to 100 . <code> List < Pizza > CookPizza ( List < Order > ) ; List < HappyCustomers > DeliverPizza ( List < Pizza > ) ;
|
Pizza , Threading , Waiting , Notifying . What does it mean ?
|
C_sharp : I was writing some unit tests for a utility library when I came across a test I would expect to fail that actually passed . The issue is related to comparing two float variables , versus comparing one float ? and one float variable.I 'm using the latest versions of both NUnit ( 2.6.0.12051 ) and FluentAssertions ( 1.7.1 ) , and below is a small code snipped illustrating the issue : As you can see from my comments , in TestFloatEquality ( ) both A and B fails correctly ( just comment out the first failing test to get to the second one ) .In TestNullableFloatEquality ( ) however , D passes but C fails . I would have expected C to fail here as well . And just to have mentioned it , if I add assertions using NUnit : those pass and fail as expected.So , to the question : Is this a bug in FluentAssertions , or am I missing something with respect to nullable comparison ? <code> using FluentAssertions ; using FluentAssertions.Assertions ; using NUnit.Framework ; namespace CommonUtilities.UnitTests { [ TestFixture ] public class FluentAssertionsFloatAssertionTest { [ Test ] public void TestFloatEquality ( ) { float expected = 3.14f ; float notExpected = 1.0f ; float actual = 3.14f ; actual.Should ( ) .BeApproximately ( expected , 0.1f ) ; actual.Should ( ) .BeApproximately ( notExpected , 0.1f ) ; // A : Correctly fails ( Expected value 3,14 to approximate 1 +/- 0,1 , but it differed by 2,14 . ) actual.Should ( ) .BeInRange ( expected , expected ) ; actual.Should ( ) .BeInRange ( notExpected , notExpected ) ; // B : Correctly fails ( Expected value 3,14 to be between 1 and 1 , but it was not . ) } [ Test ] public void TestNullableFloatEquality ( ) { float expected = 3.14f ; float notExpected = 1.0f ; float ? actual = 3.14f ; actual.Should ( ) .BeApproximately ( expected , 0.1f ) ; actual.Should ( ) .BeApproximately ( notExpected , 0.1f ) ; // C : Passes ( I expected it to fail ! ) actual.Should ( ) .BeInRange ( expected , expected ) ; actual.Should ( ) .BeInRange ( notExpected , notExpected ) ; // D : Correctly fails ( Expected value 3,14 to be between 1 and 1 , but it was not . ) } } } Assert.AreEqual ( expected , actual ) ; // PassesAssert.AreEqual ( notExpected , actual ) ; // Fails ( Expected : 1.0f But was : 3.1400001f )
|
Is this a bug when comparing a nullable type with its underlying type using FluentAssertions ?
|
C_sharp : I have a list of prime numbers up to 2 000 000 . That 's a list containing almost 150 000 very large integers . I want a sum of all the numbers in it . Here 's a random list of large integers just for demonstration : I 'm getting a `` Arithmetic operation resulted in an overflow '' exception . I guess the sum is too large , but converting it to Int64 did n't help , it still throws the same exception.I even tried saving the sum into Int64 variable and then using it , but this did n't work either.Is there any data type that can hold this large number , or am I making the mistake somewhere else ? Thanks for any help . <code> List < int > numbers = new List < int > ( ) ; for ( int i = 0 ; i < 100 ; i++ ) { numbers.Add ( 1000000000 ) ; } Console.WriteLine ( numbers.Sum ( ) .ToString ( ) ) ; Console.WriteLine ( Convert.ToUInt64 ( numbers.Sum ( ) ) .ToString ( ) ) ; long sum = numbers.Sum ( ) ; Console.WriteLine ( sum.ToString ( ) ) ;
|
List sum too large , throwing overflow exception
|
C_sharp : I 'm using an ActiveDirectory server to query the groups that a user belongs to . I would like to get all the groups that a user belongs to , but using the Network Management funcions of the Network API.I realized that already exist a function called NetUserGetGroups , but unfortunately , this function does not include the groups that a member indirect belongs to.ExampleFor example , if I have the following structure : Using NetUserGetGroups call will return : Using System.DirectoryServices.AccountManagement , will return : This code returns : The problem is that I 'm using .NET2 , and I can not get access to the System.DirectoryServices . I only have access to the NetworkAPI . My questionSomeone knows how could I implement the user.GetAuthorizationGroups ( ) call , using the NetworkAPI ? <code> MyGroup1 |_ MyGroup2 |_ MyUser MyGroup2 public static List < string > GetUserGroupsAD ( string dc , string userName ) { var result = new List < string > ( ) ; try { using ( var context = new PrincipalContext ( ContextType.Domain , dc.Replace ( `` \\ '' , `` '' ) ) ) { var user = UserPrincipal.FindByIdentity ( context , userName ) ; var groups = user.GetAuthorizationGroups ( ) ; foreach ( Principal p in groups2 ) result.Add ( p.Name ) ; } } catch ( Exception ex ) { Console.WriteLine ( `` An error happened in GetUserGroups '' , ex ) ; } return result ; } MyGroup1 < -- this is what I need , loading the indirect groups ! MyGroup2 ( and others )
|
How to get user 's groups using the Network API
|
C_sharp : I 'm creating a chain of responsibility pipeline using System.Func < T , T > where each function in the pipeline holds a reference to the next.When building the pipeline , I 'm unable to pass the inner function by reference as it throws a StackOverflowException due to the reassignment of the pipeline function , for example : I can work around this with a closure : However , I would like to know if there is a more efficient way to build up this chain of functions , perhaps using Expressions ? <code> Func < string , Func < string , string > , string > handler1 = ( s , next ) = > { s = s.ToUpper ( ) ; return next.Invoke ( s ) ; } ; Func < string , string > pipeline = s = > s ; pipeline = s = > handler1.Invoke ( s , pipeline ) ; pipeline.Invoke ( `` hello '' ) ; // StackOverFlowException Func < string , Func < string , string > , string > handler1 = ( s , next ) = > { s = s.ToUpper ( ) ; return next.Invoke ( s ) ; } ; Func < Func < string , string > , Func < string , string > > closure = next = > s = > handler1.Invoke ( s , next ) ; Func < string , string > pipeline = s = > s ; pipeline = closure.Invoke ( pipeline ) ; pipeline.Invoke ( `` hello '' ) ;
|
Chain of responsibility using Func
|
C_sharp : Hi lets say i have tree of following typelets say root of the tree is I know it is possible to check length of this tree using recursionbut is this possible to check length of this tree using linq ? <code> public class Element { public List < Element > element ; } Element root = GetTree ( ) ;
|
Checking length of tree using linq
|
C_sharp : I 'm trying to create a binding from code in a library that targets multiple frameworks ( WPF , WinRT , UWP etc ) , and I 'm hitting a brick wall . The property I 'm trying to bind to is a custom attached property . In WPF , I can pass the DependencyProperty itself as the binding path : But in WinRT the PropertyPath class only accepts a string . I tried to pass the name of the property like this : but of course it does n't work , since my class is not in the default namespace . In XAML I could map the namespace to a prefix and use that prefix , but as far as I know it 's not possible to do this from code.Is there any way to create this binding in code ? <code> new PropertyPath ( MyClass.MyAttachedProperty ) new PropertyPath ( `` ( MyClass.MyAttachedProperty ) '' )
|
Binding from code to a custom attached property in WinRT/UWP
|
C_sharp : I am new to MVC and started with MVC 4 . I want to make an online shop application.-Same shopping logic will be used by two different web sites/domains.-And the views must alter according to domain name and their mobile versions.Logic file structe is like this : View file structure for first domain : View file structure for second domain : The question is : How do switch between domain specific view folders automatically ? It can be done manually by repeating this line everywhere : Is there any easier way to change base view folder globally with one shot ? Thanks in advance , <code> Controllers/HomeController.csControllers/ProductController.csModels/Home.csModels/Product.cs Views/my_1st_Domain/Home/Index.cshtmlViews/my_1st_Domain/Home/Index.Mobile.cshtmlViews/my_1st_Domain/Home/Terms.cshtmlViews/my_1st_Domain/Home/Terms.Mobile.cshtmlViews/my_1st_Domain/Product/Index.cshtmlViews/my_1st_Domain/Product/Index.Mobile.cshtmlViews/my_1st_Domain/Product/Detail.cshtmlViews/my_1st_Domain/Product/Detail.Mobile.cshtml Views/my_2nd_Domain/Home/Index.cshtmlViews/my_2nd_Domain/Home/Index.Mobile.cshtmlViews/my_2nd_Domain/Home/Terms.cshtmlViews/my_2nd_Domain/Home/Terms.Mobile.cshtmlViews/my_2nd_Domain/Product/Index.cshtmlViews/my_2nd_Domain/Product/Index.Mobile.cshtmlViews/my_2nd_Domain/Product/Detail.cshtmlViews/my_2nd_Domain/Product/Detail.Mobile.cshtml return View ( `` ~/Views/ '' + getDomainSpecificFolder ( ) + `` /Home/Index '' + getMobileSuffixIfNeeded ( ) + `` .cshtml '' ) ;
|
MVC 4 same logic with different view folders
|
C_sharp : We are using System.Linq.Expressions.Expression to build custom expressions which are applied on the .Where ( ) of our IQueryable.What I want to achieve is , to apply the .HasFlag ( ) method ( introduced in EF 6.1 ) on the property which is then used in the .Where ( ) expression.I have following code : The value of propertyExpression is being displayed as { x.Type } and the hasFlagMethod is being shown as { Boolean HasFlag ( System.Enum ) } which both look fine to me.The value of hasFlagExpression is { x.Type.HasFlag ( Convert ( Foo ) ) } which also looks completely fine to me except the Convert ( Foo ) part but doing this was necessary otherwhise I would get another Exception that it is complaining that the parameter can not be applied to this method as it is not System.Enum.And at the time we enumerate the IQueryable with this .Where ( ) we get following exception : Calling it directly on the IQueryable works though ( we are also using EF 6.1 which added support for Enum.HasFlag ( ) ) as inBut calling it like this is not an option as it needs to be generic for all our entities . ( We put those .Where ( ) conditions together according to the filtered columns in our Datatables ) <code> var memberExpression = propertyExpression as MemberExpression ; var targetType = memberExpression ? .Type ? ? typeof ( decimal ? ) ; var value = Enum.Parse ( type , searchValue ) ; var hasFlagMethod = targetType.GetMethod ( nameof ( Enum.HasFlag ) ) ; var hasFlagExpression = Expression.Call ( propertyExpression , hasFlagMethod , Expression.Convert ( Expression.Constant ( value ) , typeof ( Enum ) ) ) ; NotSupportedException : LINQ to Entities does not recognize the method'Boolean HasFlag ( System.Enum ) ' method , and this method cannotbe translated into a store expression . Entities.Where ( x = > x.Type.HasFlag ( BarEnum.Foo ) ) ;
|
LINQ to Entities does not recognize the method 'Boolean HasFlag ( System.Enum ) ' when creating the expression via System.Linq.Expressions.Expression
|
C_sharp : According to MSDN , Environment.StackTrace can throw ArgumentOutOfRangeException but I do n't understand how this is possible.Environment.cs StackTrace ( source ) Calls GetStackTrace ( Exception , bool ) where Exception is null.Environment.cs GetStackTrace ( Exception , bool ) ( source ) ( comments removed , they are irrelevant ) The above method has the potential to call two constructors of StackTrace , StackTrace ( bool ) and StackTrace ( Exception , bool ) .We know from the first call that if this method is reached via the Environment.StackTrace call then StackTrace ( bool ) is guaranteed to be called.But StackTrace ( bool ) does n't throw any exceptions according to MSDN . The other possible constructor call , StackTrace ( Exception , bool ) ( MSDN ) does throw an exception , but it 's ArgumentNullException not ArgumentOutOfRangeException . I do n't see any other method calls made in the code that would throw ArgumentOutOfRangeException.So what am I missing ? Is it actually possible for Environment.StackTrace to throw an exception and if so how ? <code> public static String StackTrace { [ System.Security.SecuritySafeCritical ] get { Contract.Ensures ( Contract.Result < String > ( ) ! = null ) ; new EnvironmentPermission ( PermissionState.Unrestricted ) .Demand ( ) ; return GetStackTrace ( null , true ) ; } } internal static String GetStackTrace ( Exception e , bool needFileInfo ) { StackTrace st ; if ( e == null ) st = new StackTrace ( needFileInfo ) ; else st = new StackTrace ( e , needFileInfo ) ; return st.ToString ( System.Diagnostics.StackTrace.TraceFormat.Normal ) ; }
|
How can Environment.StackTrace throw ArgumentOutOfRangeException ?
|
C_sharp : I 'm implementing some real-time charts in a C # WPF application , but am using WinForms charts as they are generally easy to work with and are surprisingly performant.Anyway , I 've got the charts working just fine except for one major issue which I ca n't for the life of me figure out : When I add data to the chart , it sometimes just resizes itself . Sometimes it does that a lot , giving itself the wiggles and making the chart super annoying to read and deal with.My question is : how can I prevent this damned chart from constantly resizing itself ? ! Some additional information : The chart is included in my XAML as such : Gets initialized via : And data points get added via : Any help you can offer would be GREATLY appreciated , this has been driving me crazy for way too long ! <code> < WindowsFormsHost Grid.Row= '' 1 '' Grid.ColumnSpan= '' 2 '' Margin= '' 5 '' > < winformchart : Chart Dock= '' Fill '' x : Name= '' Session0Chart '' > < winformchart : Chart.ChartAreas > < winformchart : ChartArea/ > < /winformchart : Chart.ChartAreas > < /winformchart : Chart > < /WindowsFormsHost > // initialize it ! chart.Palette = ChartColorPalette.Bright ; // setup the labelsFont monoSpaceFont = new Font ( `` Consolas '' , 10 ) ; chart.ChartAreas [ 0 ] .AxisX.LabelStyle.Font = monoSpaceFont ; chart.ChartAreas [ 0 ] .AxisY.LabelStyle.Font = monoSpaceFont ; // set the axis limits appropriatelychart.ChartAreas [ 0 ] .AxisY.Maximum = 600 ; chart.ChartAreas [ 0 ] .AxisY.Minimum = -200 ; // set up grid lines and axis styleschart.ChartAreas [ 0 ] .AxisX.MinorGrid.Enabled = true ; chart.ChartAreas [ 0 ] .AxisX.MinorGrid.LineDashStyle = ChartDashStyle.Dash ; chart.ChartAreas [ 0 ] .AxisX.MinorGrid.LineColor = System.Drawing.Color.Gray ; chart.ChartAreas [ 0 ] .AxisX.MinorGrid.Interval = 0.04 ; chart.ChartAreas [ 0 ] .AxisX.LabelStyle.Format = `` F2 '' ; chart.ChartAreas [ 0 ] .AxisX.LabelAutoFitStyle = LabelAutoFitStyles.None ; chart.ChartAreas [ 0 ] .AxisY.MajorGrid.Enabled = true ; chart.ChartAreas [ 0 ] .AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Solid ; chart.ChartAreas [ 0 ] .AxisY.MajorGrid.Interval = 200 ; chart.ChartAreas [ 0 ] .AxisY.LabelAutoFitStyle = LabelAutoFitStyles.None ; chart.ChartAreas [ 0 ] .AxisY.LabelStyle.Format = `` F0 '' ; chart.Series.Clear ( ) ; Series s = new Series ( ) ; s.ChartType = SeriesChartType.FastLine ; chart.Series.Add ( s ) ; chart.Refresh ( ) ; // if we get too many points , remove the headif ( session.Chart.Series [ 0 ] .Points.Count > = Properties.Settings.Default.ECGDataPoints ) { session.Chart.Series [ 0 ] .Points.RemoveAt ( 0 ) ; } // add the pointsfor ( int i = data.samples.Length - 1 ; i > = 0 ; i -- ) { session.Chart.Series [ 0 ] .Points.AddXY ( session.ecgT , data.samples [ i ] ) ; session.ecgT += session.ECGPeriod / ( double ) data.samples.Length ; } // only look at the last few secondssession.Chart.ChartAreas [ 0 ] .AxisX.Maximum = session.ecgT ; session.Chart.ChartAreas [ 0 ] .AxisX.Minimum = session.ecgT - Properties.Settings.Default.ECGTimeWindow ;
|
How to cure C # winforms chart of the wiggles ?
|
C_sharp : It is possible to register dependencies manually : When there are too much dependencies , it becomes difficult to register all dependencies manually.What is the best way to implement a convention based binding in MVC 6 ( beta 7 ) ? P.S . In previous projects I used Ninject with ninject.extensions.conventions . But I ca n't find a Ninject adapter for MVC 6 . <code> services.AddTransient < IEmailService , EmailService > ( ) ; services.AddTransient < ISmsService , SmsService > ( ) ;
|
Convention based binding in ASP.NET 5 / MVC 6
|
C_sharp : WCF makes it easy to call services synchronously or asynchronously , regardless of how the service is implemented . To accommodate clients using ChannelFactory , services can even define separate sync/async contract interfaces . For example : This allows the client to reference either contract version , and WCF translates the actual API calls automatically.One drawback to providing both contract versions is that they must be kept in-sync . If you forget to update one , the client may receive a contract mismatch exception at runtime.Is there an easy way to unit test the interfaces to ensure they match from a WCF metadata perspective ? <code> public interface IFooService { int Bar ( ) ; } [ ServiceContract ( Name = `` IFooService '' ) ] public interface IAsyncFooService { Task < int > BarAsync ( ) ; }
|
Unit-test WCF contracts match for sync / async ?
|
C_sharp : I have been handing the closing and aborting of channels this way : Assume only a single thread uses the channel . How do we know the channel will not fault right after checking the state ? If such a thing were to happen , the code would try to Close ( ) and Close ( ) will throw an exception in the finally block . An explanation about why this is safe/unsafe and examples of a better , safer way would be appreciated . <code> public async Task < MyDataContract > GetDataFromService ( ) { IClientChannel channel = null ; try { IMyContract contract = factory.CreateChannel ( address ) ; MyDataContract returnValue = await player.GetMyDataAsync ( ) ; channel = ( IClientChannel ) ; return returnValue ; } catch ( CommunicationException ) { // ex handling code } finally { if ( channel ! = null ) { if ( channel.State == CommunicationState.Faulted ) { channel.Abort ( ) ; } else { channel.Close ( ) ; } } } }
|
Is it possible for a WCF channel to fault right after checking the state ( single thread ) ?
|
C_sharp : How would you create a Class that whichever class extends the Class , methods are automatically invoked/called . Just edit my question if it sounds misleading . I 'll just showcase some samplesExample 1 : In unity when you extend monobehavior your methods are automatically called . I do n't know if I 'm right . on libgdxAs What I have Understand and Tried Implementing it my selfI 'm sorry , but I still really do n't know how it works or what you call this technique.Especially in unity , when creating multiple controllers that extends Monobehavior , all that controllers method that been implemented are called . Who 's calling this classes and methods ? Some reference or books on this would be a great help . Note : Please edit my title for the right term to use on this . thanks <code> public class MyController : MonoBehaviour { void Start ( ) { //Being Called Once } void FixedUpdate ( ) { //Being Called every update } Game implements ApplicationListener { @ Override public void render ( ) { //Called multiple times } } public abstract Test { protected Test ( ) { onStart ( ) ; } public abstract void onStart ( ) ; } public class Test2 extends Test { public Test2 ( ) { } @ Override public void onStart ( ) { //Handle things here } }
|
Calling methods from a super class when a subclass is instantiated
|
C_sharp : I have the following code which is in a transaction . I 'm not sure where/when I should be commiting my unit of work.On purpose , I 've not mentioned what type of Respoistory i 'm using - eg . Linq-To-Sql , Entity Framework 4 , NHibernate , etc.If someone knows where , can they please explain WHY they have said , where ? ( i 'm trying to understand the pattern through example ( s ) , as opposed to just getting my code to work ) .Here 's what i 've got : - <code> using ( TransactionScope transactionScope = new TransactionScope ( TransactionScopeOption.RequiresNew , new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted } ) ) { _logEntryRepository.InsertOrUpdate ( logEntry ) ; //_unitOfWork.Commit ( ) ; // Here , commit # 1 ? // Now , if this log entry was a NewConnection or an LostConnection , // then we need to make sure we update the ConnectedClients . if ( logEntry.EventType == EventType.NewConnection ) { _connectedClientRepository.Insert ( new ConnectedClient { LogEntryId = logEntry.LogEntryId } ) ; //_unitOfWork.Commit ( ) ; // Here , commit # 2 ? } // A ( PB ) BanKick does _NOT_ register a lost connection , // so we need to make sure we handle those scenario 's as a LostConnection . if ( logEntry.EventType == EventType.LostConnection || logEntry.EventType == EventType.BanKick ) { _connectedClientRepository.Delete ( logEntry.ClientName , logEntry.ClientIpAndPort ) ; //_unitOfWork.Commit ( ) ; // Here , commit # 3 ? } _unitOfWork.Commit ( ) ; // Here , commit # 4 ? transactionScope.Complete ( ) ; }
|
At which line in the following code should I commit my unit of work ?
|
C_sharp : Given the following method : This works if I call it passing a array of strings : But will not work if I call it using string arguments : I understand that the compiler will wrap Michael and Jordan on an array , so should n't the results be the same on both cases ? <code> static void ChangeArray ( params string [ ] array ) { for ( int i = 0 ; i < array.Length ; i++ ) array [ i ] = array [ i ] + `` s '' ; } string [ ] array = { `` Michael '' , `` Jordan '' } // will become { `` Michaels '' , `` Jordans '' } ChangeArray ( array ) ; string Michael = `` Michael '' ; string Jordan = `` Jordan '' ; ChangeArray ( Michael , Jordan ) ; // This will NOT change the values of the variables
|
C # Inconsistent results using params keyword
|
C_sharp : I was just looking at the question `` SubQuery using Lambda Expression '' and wondered about compiler optimization of Linq predicates.Suppose I had a List < string > called names , and I was looking for the items with the shortest string length . So we have the query names.Where ( x = > x.Length == names.Min ( y = > y.Length ) ) ( from the question mentioned above ) . Simple enough.Now , we know the C # specification does not allow you to modify a collection while enumerating it . So I believe it is technically safe to assume the above call to Min ( ) will always return the same value for every call . But , my hypothesis is the compiler truly has no way of knowing what the lambda inside the Enumerable.Min extension method returns . Since , for example we could do : Which would mean the query in question is really O ( n² ) - the result of Min ( ) will be calculated for each iteration . And to get the desired O ( n ) implementation , you would have to be explicit : Is my hypothesis correct , or is there something special about Linq or the C # specification that allows the compiler to look inside the lambda and optimize this call to Min ( ) ? @ spender is absolutely correct . Consider the following snippet : This will return only `` r '' , and not `` q '' , because while the old reference to names is being iterated ( foreach x ) , the call to Min after the first iteration is actually called with the new instance of names . But , a human looking at the query in the top of the question can say for certain nothing gets modified . So my question still stands : is the compiler smart enough to see this ? <code> int i = 0 ; return names.Where ( x = > x.Length == names.Min ( y = > ++i ) ) ; int minLength = names.Min ( y = > y.Length ) ; return names.Where ( x = > x.Length == minLength ) ; List < string > names = new List < string > ( new [ ] { `` r '' , `` abcde '' , `` bcdef '' , `` cdefg '' , `` q '' } ) ; return names.Where ( x = > { bool b = ( x.Length == names.Min ( y = > y.Length ) ) ; names = new List < string > ( new [ ] { `` ab '' } ) ; return b ; } ) ;
|
In a Linq predicate , will the compiler optimize a `` scalar '' call to Enumerable.Min ( ) or will it be called for each item ?
|
C_sharp : I have two questions : Question 1 Background : I noticed when looking at the implementation of 'AsEnumerable ( ) ' method in LINQ from Microsoft , which was : Question 1 : I was expecting some kind of casting or something here , but it simply returns the value it was passed . How does this work ? Question 2/3 Background : I have been trying to understand Covariance , contravariance and Invariant . I think , I have a vague understanding that 'in ' and 'out ' keywords determine the polymorphic behavior when assigning a subtype to a parent type . Question 2 : I know from reading that IEnumerable is covariant , and List is invariant then why is this not possible : Question 3 : If IList implements IEnumerable then why is this not possible : Please help me understanding , thank you in advance . <code> public static IEnumerable < TSource > AsEnumerable < TSource > ( this IEnumerable < TSource > source ) { return source ; } List < char > content = `` testString '' .AsEnumerable ( ) ; IEnumerable < char > content1 = `` testString '' ; IList < char > content2 = content1 ;
|
Internal Implementation of AsEnumerable ( ) in LINQ
|
C_sharp : I have a problem with writing a C # linq query for retrieving data from the database , based on multiple columns of a filter list.The list of items contains multiple columns ( For example A and B ) and is dynamic.My first idea was to write an any statement in an where statement , but this is not allowed in EF.I also tried the filter first only on A , retrieve all data and filter on B , but that did not perform well.An other way would be to create some c # code to generate something like this : But there is no decent way to do this.Has anyone an idea how to fix this issue ? <code> var result = _repository.Where ( x = > items.Any ( y = > x.A == y.A & & x.B == y.B ) ) ; var ListA = items.Select ( x = > x.A ) .ToList ( ) ; var result = _repository.Get ( x = > ListA.Contains ( x.A ) ) ; SELECT A , B , C , DFROM Items WHERE ( A = 1 AND b = 1 ) OR ( A = 7 AND b = 2 ) OR ( A = 4 AND b = 3 )
|
Retrieve records from the database matching multiple values of a list
|
C_sharp : I am drawing a header for a timeline control.It looks like this : I go to 0.01 millisecond per line , so for a 10 minute timeline I am looking at drawing 60000 lines + 6000 labels.This takes a while , ~10 seconds.I would like to offload this from the UI thread.My code is currently : I had looked into BackgroundWorker , except you ca n't create UI elements on a non-UI thread.Is it possible at all to do drawHeaderLines in a non-UI thread ? Could I use data binding for drawing the lines ? Would this help with UI responsiveness ? I would imagine I can use databinding , but the Styling is probably beyond my current WPF ability ( coming from winforms and trying to learn what all these style objects are and binding them ) .Would anyone be able to supply a starting point for tempting this out ? Or Google a tutorial that would get me started ? <code> private void drawHeader ( ) { Header.Children.Clear ( ) ; switch ( viewLevel ) { case ViewLevel.MilliSeconds100 : double hWidth = Header.Width ; this.drawHeaderLines ( new TimeSpan ( 0 , 0 , 0 , 0 , 10 ) , 100 , 5 , hWidth ) ; //Was looking into background worker to off load UI //backgroundWorker = new BackgroundWorker ( ) ; //backgroundWorker.DoWork += delegate ( object sender , DoWorkEventArgs args ) // { // this.drawHeaderLines ( new TimeSpan ( 0 , 0 , 0 , 0 , 10 ) , 100 , 5 , hWidth ) ; // } ; //backgroundWorker.RunWorkerAsync ( ) ; break ; } } private void drawHeaderLines ( TimeSpan timeStep , int majorEveryXLine , int distanceBetweenLines , double headerWidth ) { var currentTime = new TimeSpan ( 0 , 0 , 0 , 0 , 0 ) ; const int everyXLine100 = 10 ; double currentX = 0 ; var currentLine = 0 ; while ( currentX < headerWidth ) { var l = new Line { ToolTip = currentTime.ToString ( @ '' hh\ : mm\ : ss\.fff '' ) , StrokeThickness = 1 , X1 = 0 , X2 = 0 , Y1 = 30 , Y2 = 25 } ; if ( ( ( currentLine % majorEveryXLine ) == 0 ) & & currentLine ! = 0 ) { l.StrokeThickness = 2 ; l.Y2 = 15 ; var textBlock = new TextBlock { Text = l.ToolTip.ToString ( ) , FontSize = 8 , FontFamily = new FontFamily ( `` Tahoma '' ) , Foreground = new SolidColorBrush ( Color.FromRgb ( 255 , 255 , 255 ) ) } ; Canvas.SetLeft ( textBlock , ( currentX - 22 ) ) ; Canvas.SetTop ( textBlock , 0 ) ; Header.Children.Add ( textBlock ) ; } if ( ( ( ( currentLine % everyXLine100 ) == 0 ) & & currentLine ! = 0 ) & & ( currentLine % majorEveryXLine ) ! = 0 ) { l.Y2 = 20 ; var textBlock = new TextBlock { Text = string.Format ( `` . { 0 } '' , TimeSpan.Parse ( l.ToolTip.ToString ( ) ) .Milliseconds ) , FontSize = 8 , FontFamily = new FontFamily ( `` Tahoma '' ) , Foreground = new SolidColorBrush ( Color.FromRgb ( 192 , 192 , 192 ) ) } ; Canvas.SetLeft ( textBlock , ( currentX - 8 ) ) ; Canvas.SetTop ( textBlock , 8 ) ; Header.Children.Add ( textBlock ) ; } l.Stroke = new SolidColorBrush ( Color.FromRgb ( 255 , 255 , 255 ) ) ; Header.Children.Add ( l ) ; Canvas.SetLeft ( l , currentX ) ; currentX += distanceBetweenLines ; currentLine++ ; currentTime += timeStep ; } }
|
10000's+ UI elements , bind or draw ?
|
C_sharp : In unity3D I am creating and destroying capsule dynamically at run-time . I used space to create capsule and C for destroying.I want create multiple object and destroy multiple object at time . When I pressed Space multiple times object is creating multiple time it fine . But the problem is when I pressed C multiple times only one object is destroying . How I can achieve destroying multiple object ? One by one . <code> using System ; using System.Collections ; using System.Collections.Generic ; using UnityEngine ; public class DynamicCreate : MonoBehaviour { public GameObject caps ; // Update is called once per frame void Update ( ) { if ( Input.GetKeyDown ( KeyCode.Space ) ) { createObject ( ) ; } if ( Input.GetKeyDown ( KeyCode.C ) ) { destroyObject ( ) ; } } private void createObject ( ) { caps = GameObject.CreatePrimitive ( PrimitiveType.Capsule ) ; } public void destroyObject ( ) { Destroy ( caps ) ; } }
|
How to Destroy multiple gameObject at runtime ?
|
C_sharp : This is a question I was asked at my interview recently : Which 'Random ' object ( s ) would get collected during the 'GC.Collect ( ) ' call ? I answered that this is an implementation-specific question and it highly depends on the GC implementation and the corresponding weak reference semantics . As far as I know , C # specification does n't provide exact description of what GC.Collect should do and how should the weak references be handled.However , my interviewer wanted to hear something else . <code> String a = new Random ( ) .Next ( 0 , 1 ) ==1 ? `` Whatever 1 '' : `` Whatever 2 '' ; String b = new WeakReference ( new Random ( ) ) .Target.Next ( 0 , 1 ) == 1 ? `` Whatever 1 '' : `` Whatever 2 '' ; GC.Collect ( ) ;
|
Which of these objects are eligible for garbage collection ?
|
C_sharp : Lets say I have a function that needs to return some integer value . but it can also fail , and I need to know when it does.Which is the better way ? orthis is probably more of a style question , but I 'm still curious which option people would take.Edit : clarification , this code talks to a black box ( lets call it a cloud . no , a black box . no , wait . cloud . yes ) . I dont care why it failed . I would just need to know if I have a valid value or not . <code> public int ? DoSomethingWonderful ( ) public bool DoSomethingWonderful ( out int parameter )
|
which is better , using a nullable or a boolean return+out parameter
|
C_sharp : I have an application that needs to take in several million char* 's as an input parameter ( typically strings less than 512 characters ( in unicode ) ) , and convert and store them as .net strings.It turning out to be a real bottleneck in the performance of my application . I 'm wondering if there 's some design pattern or ideas to make it more effecient . There is a key part that makes me feel like it can be improved : There are a LOT of duplicates . Say 1 million objects are coming in , there might only be like 50 unique char* patterns . For the record , here is the algorithm i 'm using to convert char* to string ( this algorithm is in C++ , but the rest of the project is in C # ) <code> String ^StringTools : :MbCharToStr ( const char *Source ) { String ^str ; if ( ( Source == NULL ) || ( Source [ 0 ] == '\0 ' ) ) { str = gcnew String ( `` '' ) ; } else { // Find the number of UTF-16 characters needed to hold the // converted UTF-8 string , and allocate a buffer for them . const size_t max_strsize = 2048 ; int wstr_size = MultiByteToWideChar ( CP_UTF8 , 0L , Source , -1 , NULL , 0 ) ; if ( wstr_size < max_strsize ) { // Save the malloc/free overhead if it 's a reasonable size . // Plus , KJN was having fits with exceptions within exception logging due // to a corrupted heap . wchar_t wstr [ max_strsize ] ; ( void ) MultiByteToWideChar ( CP_UTF8 , 0L , Source , -1 , wstr , ( int ) wstr_size ) ; str = gcnew String ( wstr ) ; } else { wchar_t *wstr = ( wchar_t * ) calloc ( wstr_size , sizeof ( wchar_t ) ) ; if ( wstr == NULL ) throw gcnew PCSException ( __FILE__ , __LINE__ , PCS_INSUF_MEMORY , MSG_SEVERE ) ; // Convert the UTF-8 string into the UTF-16 buffer , construct the // result String from the UTF-16 buffer , and then free the buffer . ( void ) MultiByteToWideChar ( CP_UTF8 , 0L , Source , -1 , wstr , ( int ) wstr_size ) ; str = gcnew String ( wstr ) ; free ( wstr ) ; } } return str ; }
|
Optimizing several million char* to string conversions
|
C_sharp : I 'm having trouble serialising and de-serialising NodaTime 's LocalTime through a WebAPI.Class definitionTry to serialize the outputI want to time format formatted to a ISO like standard e.g . 12:34:53 , but instead it de-serialisers to the following with local time represented as ticks ; { `` ExampleLocalTime '' : { `` ticks '' : 553800000000 } } What do I need to add to avoid Ticks when de-serialising and serialising ? <code> public class ExampleClass { public LocalTime ExampleLocalTime { get ; set ; } } // create example objectvar exampleclass = new ExampleClass ( ) { ExampleLocalTime = new LocalTime ( DateTime.Now.Hour , DateTime.Now.Minute ) } ; // serialise outputvar jsonsettings = new JsonSerializerSettings ( ) { DateParseHandling = DateParseHandling.None , NullValueHandling = NullValueHandling.Ignore } ; jsonsettings.Converters.Add ( new IsoDateTimeConverter ( ) ) ; string exampleoutput = JsonConvert.SerializeObject ( exampleclass , Formatting.Indented , jsonsettings ) ;
|
Proper serialization of LocalTime through WebAPI
|
C_sharp : Somebody gives me a type t.I 'd like to know if that type is an enumeration or not . <code> public bool IsEnumeration ( Type t ) { // Mystery Code . throw new NotImplementedException ( ) ; } public void IsEnumerationChecker ( ) { Assert.IsTrue ( IsEnumeration ( typeof ( Color ) ) ) ; Assert.IsFalse ( IsEnumeration ( typeof ( float ) ) ) ; }
|
Is there any way to check that a type is a type of enumeration ?
|
C_sharp : I am getting all events , with a certain attribute , and I want to modify these events adding a call to another method.What I want is basically what is commented above . `` Modify '' the subscribed methods of the event . I guess I ca n't subscribe to it , because I need to pass the parameters the method is passing to the big handler ( the new method ) .One more example based on this question . I want to convert this : To something like this : Or this : How can I do it ? The bigger goal : I need to `` detect '' when an event is fired and call a method . I also need to send the parameters it is using.So I can make something like : Then on my handler method I can check if an event from XYZ was fired , check which event was fired , retrieve the parameter and do something . For example : I know it can be achieved using PostSharp , but I ca n't use it . I need another solution.RelatedC # Reflection , changing a method 's bodyHow can I dynamically inject code into event handlers in Delphi ? Update 2010-09-27 I could n't find a solution neither more info on it , I still need help . Added +150 bounty . <code> var type = GetType ( ) ; var events = type.GetEvents ( ) .Where ( e = > e.GetCustomAttributes ( typeof ( ExecuteAttribute ) , false ) .Length > 0 ) ; foreach ( var e in events ) { var fi = type.GetField ( e.Name , BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField ) ; var d = ( Delegate ) fi.GetValue ( this ) ; var methods = d.GetInvocationList ( ) ; foreach ( var m in methods ) { var args = e.EventHandlerType.GetMethod ( `` Invoke '' ) .GetParameters ( ) .Select ( p = > Expression.Parameter ( p.ParameterType , `` p '' ) ) .ToArray ( ) ; var body = m.Method.GetMethodBody ( ) ; /** TODO : Create a new method with the body of the previous and add a call to another method Remove current method Add the new created method **/ } } var e += ( x ) = > { var y = x ; } ; var e += ( x ) = > { var y = x ; BigHandler ( x ) ; // injected code } ; var e += ( x ) = > // new method { previousE ( x ) ; // previous method BigHandler ( x ) ; // additional code } public delegate void OnPostSaved ( Post p ) ; [ Execute ] public event OnPostSaved PostSaved ; public void Save ( ) { /* save stuff */ // assume that there is already an event subscribed PostSaved ( post ) ; } public void BigHandler ( string eventName , params object [ ] p ) { if ( eventName == `` PostSaved '' ) { var post = p [ 0 ] as Post ; MessageBoard.Save ( `` User posted on the blog : `` + post.Content ) ; } }
|
How can I change a method assigned on an event ?
|
C_sharp : I would like to parse an input string that contains either a time , a date and time , or just a date , and I need to know which parts where included in the input string.Parsing the actual values is not a problem : These all successfully parse as you 'd expect.However , if the date element is not provided , DateTime.Parse automatically adds the current date to the time . So if today was 1/1/2014 , then DateTime.Parse ( `` 10pm '' ) actually returns a DateTime object set to 1/1/2014 10:00:00.Also , if I parse an input string with no time element , then DateTime.Parse assumes a time of 00:00:00.So after the parse has occurred , simply by inspecting the resulting DateTime object , I can not determine if the original input string specified the date and time , or the date only or the time only.I could use a simple RegEx to look for the standard time pattern , e.g . ^\d\d : \d\d $ but I do n't want to assume that all cultures use the same pattern to specify time.How can I robustly detect which date and time elements were provided in the original input string regardless of culture , and without using some fuzzy regex that may only work for some cultures ? <code> var dt1 = DateTime.Parse ( `` 10:00:00 '' , CultureInfo.CurrentCulture ) ; var dt2 = DateTime.Parse ( `` 10pm '' , CultureInfo.CurrentCulture ) ; var dt3 = DateTime.Parse ( `` 01/02/2014 '' , CultureInfo.CurrentCulture ) ; var dt4 = DateTime.Parse ( `` 01/02/2014 10:00:00 '' , CultureInfo.CurrentCulture ) ;
|
Parsing Time , Date/Time , or Date
|
C_sharp : EDIT 1 : I know there are alternatives such as telescoping , this was a purely educational question.I know that this is true , but why must it be ? It seems like with something like this : The compiler could change the method to something like this : Why would n't that work , or would it , and it 's just a design decision ? <code> public class Foo { private int bar ; public void SetBar ( int baz = ThatOtherClass.GetBaz ( 3 ) ) { this.bar = baz ; } } public void SetBar ( int baz ) { //if baz was n't passed : baz = ThatOtherClass.GetBaz ( 3 ) ; this.bar = baz ; }
|
Why must default method parameters be compile-time constants in C #
|
C_sharp : I 'm trying to create several enums as such , that gives the syntax of Dropdown.Category.Subcategory . However , I have been reading that this is n't such a good idea . My choice for this was mostly because I could n't think of any other way to select different enum values depending on the choice of the category , and then the choice of the subcategory is subject to the selected enum based on the enum values . Is there a better way to create such functionality ? I would prefer to be able to easily identify both the .Category and .Subcategory names , and it would be a bonus if this code was readable.Just to make it clear , I want to be able to choose the Category , then have an appropriate Subcategory selection . <code> public class Dropdown { public enum Gifts { GreetingCards , VideoGreetings , UnusualGifts , ArtsAndCrafts , HandmadeJewelry , GiftsforGeeks , PostcardsFrom , RecycledCrafts , Other } public enum GraphicsAndDesign { CartoonsAndCaricatures , LogoDesign , Illustration , EbookCoversAndPackages , WebDesignAndUI , PhotographyAndPhotoshopping , PresentationDesign , FlyersAndBrochures , BusinessCards , BannersAndHeaders , Architecture , LandingPages , Other } }
|
Alternative to nesting enums
|
C_sharp : If I have two yield return methods with the same signature , the compiler does not seem to be recognizing them to be similar.I have two yield return methods like this : With this , I would expect the following statement to compile fine : Func < int , IEnumerable < int > > generator = 1 == 0 ? EvenNumbers : OddNumbers ; // Does not compileI get the error message Type of conditional expression can not be determined because there is no implicit conversion between 'method group ' and 'method group'However , an explicit cast works : Func < int , IEnumerable < int > > newGen = 1 == 0 ? ( Func < int , IEnumerable < int > > ) EvenNumbers : ( Func < int , IEnumerable < int > > ) OddNumbers ; // Works fineAm I missing anything or Is this a bug in the C # compiler ( I 'm using VS2010SP1 ) ? Note : I have read this and still believe that the first one should 've compiled fine.EDIT : Removed the usage of var in the code snippets as that was n't what I intended to ask . <code> public static IEnumerable < int > OddNumbers ( int N ) { for ( int i = 0 ; i < N ; i++ ) if ( i % 2 == 1 ) yield return i ; } public static IEnumerable < int > EvenNumbers ( int N ) { for ( int i = 0 ; i < N ; i++ ) if ( i % 2 == 0 ) yield return i ; }
|
C # compiler not recognizing yield return methods as similar ?
|
C_sharp : I 'm trying to create a set of C # classes that I can schedule to run at a future time . The intention is to programmatically schedule these via other parts of my code.This is the current class I 'm trying to call via COM.Here 's how I 'm attempting to schedule the taskMicrosoft.Win32.TaskScheduler is version 2.7.2 of this libraryI can create the scheduled task no problem , but when I attempt to run it , I get a Class not registered ( 0x80040154 ) .In my .csproj I 'm registering the assembly as a COM object.For the PlatformTarget attribute , I 've tried all of AnyCPU , x86 , and x64 with the corresponding regasm.exe.I 'm using the following post-build event to register the .dll.As near as I can tell , it 's properly registered.Procmon.exe seems to report the same . The thing I 'm worried about is the `` NAME NOT FOUND '' for \TreatAs , \InprocHandler and \InprocServer32\InprocServer32 <code> using System ; using System.Linq ; using System.Runtime.InteropServices ; using Microsoft.Win32.TaskScheduler ; namespace SchedulableTasks { [ Guid ( `` F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A '' ) ] public class TaskRegistry : ITaskHandler { private ITaskHandler _taskHandler ; public void Start ( object pHandlerServices , string data ) { var arguments = data.Split ( '| ' ) ; var taskTypeName = arguments.FirstOrDefault ( ) ; var taskArguments = arguments.Skip ( 1 ) .FirstOrDefault ( ) ; var taskType = Type.GetType ( taskTypeName ) ; _taskHandler = ( ITaskHandler ) Activator.CreateInstance ( taskType ) ; _taskHandler.Start ( pHandlerServices , taskArguments ) ; } public void Stop ( out int pRetCode ) { var retCode = 1 ; _taskHandler ? .Stop ( out retCode ) ; pRetCode = retCode ; } public void Pause ( ) { _taskHandler.Pause ( ) ; } public void Resume ( ) { _taskHandler.Resume ( ) ; } } } using System ; using Microsoft.Win32.TaskScheduler ; using Newtonsoft.Json ; using Action = Microsoft.Win32.TaskScheduler.Action ; namespace MyProject.Service { public static class SchedulingService { public enum ScheduledTask { BillingQuery } private static readonly Guid RegistryGUI = new Guid ( `` F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A '' ) ; public static void ScheduleAction ( string name , string description , Trigger trigger , Action action ) { using ( var taskService = new TaskService ( ) ) { var task = taskService.NewTask ( ) ; task.RegistrationInfo.Description = description ; task.Triggers.Add ( trigger ) ; task.Actions.Add ( action ) ; taskService.RootFolder.RegisterTaskDefinition ( name , task ) ; } } public static Action CreateCSharpAction ( ScheduledTask task , object data ) { var taskData = $ '' { task.ToString ( ) } | { JsonConvert.SerializeObject ( data ) } '' ; return new ComHandlerAction ( RegistryGUI , taskData ) ; } } } < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Debug|AnyCPU ' `` > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > bin\Debug\ < /OutputPath > < DefineConstants > DEBUG ; TRACE < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < RegisterForComInterop > true < /RegisterForComInterop > < PlatformTarget > x86 < /PlatformTarget > < /PropertyGroup > powershell C : \Windows\Microsoft.Net\Framework64\v4*\RegAsm.exe /codebase ' $ ( ProjectDir ) $ ( OutDir ) SchedulableTasks.dll '
|
Unable to register a COM object for usage in a scheduled task
|
C_sharp : PreambleI have been investigating a concept and what I am posting below is a cut down version of what I have been trying . If you look at it and think `` That does n't make any sense to do it that way '' then it is probably because I does n't make any sense - there may be more efficient ways of doing this . I just wanted to try this out because it looks interesting.What I am attempting to do it to calculate arbitrary calculations using CLR custom aggregations in SQL using a Reverse-Polish-like implementation . I 'm using the data : The result of the calculation should be 123 ( = ( 100 * 1 ) + ( 10 * 2 ) + ( 1 * 3 ) ) . Using the following SQL ( and the CLR functions ReversePolishAggregate and ToReversePolishArguments* that I have written ) I can get the correct result : The ProblemI want to generalise the solution more by putting the instructions and order in a separate table so that I can create calculations on arbitrary data . For example , I was thinking of a table like this : and joining it to a calculation table like thisto calculated whether each item is over or under budget . The important consideration is that minus is non-commutative so I need to specify the order to ensure that the actual amount is subtracted from the budgeted amount , not the other way around . I expected that I would be able to do this with the ORDER BY clause inside the OVER clause of the aggregation ( and then a little more tweaking that result ) .However I get the error : Incorrect syntax near the keyword 'ORDER'.I have checked the syntax by running the following SQL statementThis works fine ( it parses and runs , although I 'm not sure that the result is meaningful ) , so I am left assuming that this is a problem with custom CLR aggregations or functions.My Questions Is this supposed to work ? Is there any documentation saying explicitly that this is not supported ? Have I got the syntax right ? I 'm using Visual Studio 2012 Premium , SQL Server Management Studio 2012 and .NET framework 4.0 . * I created 2 CLR functions as a work-around to not being able to pass multiple arguments into a single aggregation function - see this article.EDIT : This post looks like it is not supported , but I was hoping for something a little more official . <code> K | Amt | Instruction | Order -- + -- -- -+ -- -- -- -- -- -- -+ -- -- -- A | 100 | Push | 1A | 1 | Multiply | 2A | 10 | Push | 3A | 2 | Multiply | 4A | | Add | 5A | 1 | Push | 6A | 3 | Multiply | 7A | | Add | 8 SELECT K , dbo.ReversePolishAggregate ( dbo.ToReversePolishArguments ( Instruction , Amt ) ) FROM dbo.ReversePolishCalculationGROUP BY K ; Item | Type | Amount -- -- -+ -- -- -- -- -- + -- -- -- - A | Budgeted | 10 A | Actual | 12 B | Actual | 20 B | Budgeted | 18 Type | Instruction | Order -- -- -- -- -+ -- -- -- -- -- -- -+ -- -- -- Budgeted | Push | 1 Actual | Minus | 2 SELECT K , dbo . [ ReversePolishAggregate ] ( dbo . [ ToReversePolishArguments ] ( Instruction , Amt ) ) OVER ( PARTITION BY K ORDER by [ Order ] ) FROM dbo.ReversePolishCalculation ; SELECT K , SUM ( Amt ) OVER ( PARTITION BY K ORDER BY [ Order ] ) FROM dbo.ReversePolishCalculation ;
|
SQL ORDER BY within OVER clause incompatible with CLR aggregation ?
|
C_sharp : Consider the following codeSteps to reproducePut a breakpoint on Console.Read ( ) ; Run to breakpointInspect count++ ( should display 0 ) Inspect values2 and populate the Results ViewInspect count++ ( should display 100 ) ProblemGiven that I have only taken 50 items from values1 , I would expect count++ to display 50 . Why does it display 100 ? Please note , if this is confusing , try running this code instead , it produces the same result ... ExampleInspect count++Inspect values2 ( populate Results View ) Inspect count++Any explanation as to what is happening here , and how to fix it ? NOTEMany of the given answers suggest deferred execution . I know linq uses deferred execution , so unless I 'm missing something , this is not the issue.My point is that when the breakpoint is hit , the CLR has created a state machine for values2 . Then this is iterated over in the debugger , count increments to 100 immediately for what appears to be only 1 iteration . This seems a little odd ! Also , I am aware that subsequent populations of the results view of value2 cause count to increment since this causes further iterations of the state machine . <code> namespace ConsoleApp1 { using System ; using System.Collections.Generic ; using System.Linq ; public class Program { public static void Main ( string [ ] args ) { int count = default ( int ) ; IEnumerable < int > values1 = Enumerable.Range ( 1 , 200 ) .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 100 ) ; IEnumerable < int > values2 = values1 .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 50 ) .Select ( o = > { count++ ; return o ; } ) ; Console.Read ( ) ; } } } namespace ConsoleApp1 { using System ; using System.Collections.Generic ; using System.Linq ; public class Program { public static void Main ( string [ ] args ) { int count = default ( int ) ; IEnumerable < int > values1 = Enumerable.Range ( 1 , 100 ) .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 50 ) ; IEnumerable < int > values2 = values1 .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 50 ) .Select ( o = > { count++ ; return o ; } ) ; Console.Read ( ) ; } } }
|
LINQ projection ( Select ) returning an odd result
|
C_sharp : I 've read that it is usually bad practice to extend System.Object , which I do agree with.I am curious , however , if the following would be considered a useful extension method , or is it still bad practice ? It is similar to extending System.Object but not exactly , This essentially allows any object to invoke any function that takes that object as a parameter and returns R , whether that function belongs to the object or not . I think this could facilitate some interesting 'inversion of control ' , but not sure about it overall . Thoughts ? <code> public static R InvokeFunc < T , R > ( this T input , Func < T , R > func ) { return func.Invoke ( input ) ; }
|
Extension method that extends T - bad practice ?
|
C_sharp : When I bump my mousewheel , my WPF application crashes sometimes , with an OverflowException . Here 's the start of the stack trace : From that , I 've traced it down to the WindowChrome - I can even reproduce it with just the WindowChrome . But it seems like it has to be fullscreen . What 's going on here ? Is there a workaround ? <code> at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest ( WM uMsg , IntPtr wParam , IntPtr lParam , Boolean & handled )
|
Why does my WPF application crash when I bump my mousewheel ?
|
C_sharp : I 'm having trouble understanding why arrays in C # are covariant and what benefits this covariance can bring . Consider the following trivial code example : This code will compile okay , but will unceremoniously and perhaps unsurprisingly explode at runtime.If I try to attempt this same thing using generics , the compiler would grumble at me and I would realise my stupidity at an early stage , so my question is this : Why does the C # compiler allow this covariance with arrays and furthermore , what are the potential benefits ? <code> object [ ] myArray = new string [ 1 ] ; myArray [ 0 ] = 1 ;
|
Why are C # arrays covariant and what benefits does it bring ?
|
C_sharp : If I have a synchronous method `` GetStrings ( ) '' : ( which itself calls async method `` GetString ( ) '' ) And I call this synchronous `` GetStrings ( ) '' method from an async method : What would be the behavioural difference , if GetStrings ( ) was actually async ? ( and performed an await on the Task.WhenAll ) Would it simply stop Task.WhenAll from blocking the thread ? I 've found some production code which looks like this , so I 've put together this small example to try and understand what 's going . It 's difficult to identify the difference though . <code> private static Task < string [ ] > GetStrings ( IEnumerable < int > ids ) { var tasks = ids.Distinct ( ) .Select ( GetString ) ; return Task.WhenAll ( tasks ) ; } private static async Task < string > GetString ( int stringId ) { await Task.Delay ( 15000 ) ; return `` hello '' + stringId ; } public static async Task Main ( ) { var ids = new List < int > { 1 , 2 , 3 } ; await GetStrings ( ids ) ; Console.WriteLine ( `` all done '' ) ; Console.ReadLine ( ) ; }
|
What happens when you await a synchronous method
|
C_sharp : Hi i have two Writablebitmap , one from jpg and another from png and use this method to mix color in a loop : My problem is in alpha channel , my watermark effect result is bad ( quality ) ! This is the original png.This is the original jpg.Any Help ? <code> private static Color Mix ( Color from , Color to , float percent ) { float amountFrom = 1.0f - percent ; return Color.FromArgb ( ( byte ) ( from.A * amountFrom + to.A * percent ) , ( byte ) ( from.R * amountFrom + to.R * percent ) , ( byte ) ( from.G * amountFrom + to.G * percent ) , ( byte ) ( from.B * amountFrom + to.B * percent ) ) ; }
|
Png over jpeg ( water mark effect ) bad quality ?
|
C_sharp : In C # I have ( saw with Visual Studio watch tool ) : And in C++ : Why are the values not the same ? And how can I get -3.40282347E+38 ( C # value ) in C++ ? <code> float.MinValue = -3.40282347E+38 std : :numeric_limits < float > : :min ( ) = 1.17549435e-038
|
Why is float.min different between C++ and C # ?
|
C_sharp : Given the following code , Resharper will correctly warn me about a possible NullReferenceException on foo.Bar because there could be null elements in the enumerable : One way to satisfy the static analyzer is to explicitly exclude nulls : I find myself typing .Where ( x = > x ! = null ) a lot , so I wrapped it up in an extension method , and now I can do the following : The problem is that Resharper does n't know that NotNull ( ) strips out nulls . Is there a way I can teach Resharper about this fact ? In general , is there a way to tell Resharper that an IEnumerable-returning method will never have nulls in it ( so that I can just annotate GetFoos ( ) directly ) ? I know I can use the NotNullAttribute to tell Resharper that the enumerable itself is not null , but I ca n't find one that speaks about the contents of the enumerable.Edit : The extension method looks exactly as you 'd expect : <code> IEnumerable < Foo > foos = GetFoos ( ) ; var bars = foos.Select ( foo = > foo.Bar ) ; IEnumerable < Foo > foos = GetFoos ( ) .Where ( foo = > foo ! = null ) ; IEnumerable < Foo > foos = GetFoos ( ) .NotNull ( ) ; [ NotNull ] public static IEnumerable < T > NotNull < T > ( this IEnumerable < T > enumerable ) { return enumerable.Where ( x = > x ! = null ) ; }
|
How do I tell Resharper that my IEnumerable method removes nulls ?
|
C_sharp : I recently came across what seems to puzzle my logic of maths in a piece of codeFor some reason , C # is claiming that this is false but if one were to think logically , 0.123 is larger than 0.Is there any reason that it is claiming that 0.123 is smaller than 0 ? I have read that there will be a comparison issue with double that is base 2 and it would be better to use decimal which is base 10.Could someone enlighten me ? <code> if ( ( 123/1000 ) > 0 )
|
if ( ( 123 / 1000 ) > 0 ) returns false
|
C_sharp : There are two Point3D 's ( A and B ) and I want to calculate the points of a cuboid ( a , b , c ... h ) surrounding the line between A and B like a hull : There is one degree of freedom , the angle of the cuboid , because it can rotate around the line AB . I am not sure yet if this is a problem.I tried to calculate a vector normal to AB , D , and then the cross product of AB ⨯ AD = E. In the code , C is A - B so its the offset parallel to AB.I normalized these three vectors ( C , D and E ) and multiplied it with an offset to add / subtract them from A and B . It 's not quite working yet . EDIT : see ja72 's code for solutioni also implemented a way of finding a normal vector : <code> double ax = Vector3D.AngleBetween ( E , new Vector3D ( 1 , 0 , 0 ) ) ; double ay = Vector3D.AngleBetween ( E , new Vector3D ( 0 , 1 , 0 ) ) ; double az = Vector3D.AngleBetween ( E , new Vector3D ( 0 , 0 , 1 ) ) ; ax = Math.Abs ( ax - 90 ) ; ay = Math.Abs ( ay - 90 ) ; az = Math.Abs ( az - 90 ) ; if ( ax < = ay & ax < = az ) { n = Vector3D.CrossProduct ( E , new Vector3D ( 1 , 0 , 0 ) ) ; } else if ( az < = ax & & az < = ay ) { n = Vector3D.CrossProduct ( E , new Vector3D ( 0 , 0 , 1 ) ) ; } else { n = Vector3D.CrossProduct ( E , new Vector3D ( 0 , 1 , 0 ) ) ; } n = normalize ( n ) ;
|
Calculating the Point3Ds of a Cuboid around a Line
|
C_sharp : i use the httpclient from Microsoft.Net.Http ( version 2.2.22 ) to request some of my mvc pages.My page returns a HttpStatusCodeResult like : With the httpclient it is not problem to call the page . But i could n't find a way to access the statusDescription ( `` Blub Blub '' ) . Is there a way to access the description ? And if not , why microsoft does n't make it accessable ? By the way if i call the site from browser ( Chrome ) the description is shown as expected . <code> return new HttpStatusCodeResult ( clientResponse.StatusCode , `` Blub Blub '' ) ;
|
HttpClient StatusDescription is missing
|
C_sharp : I found this explanation and solution for using Dapper to search a VARCHAR field using a string as input : Source : Dapper and varcharsBut is there a way to adapt this to do the DbString conversion for every item in a list ( using an IN clause ) ? The query I am trying to run looks like this : Unfortunately , this query runs slowly because : model.LogEntries contains around 300 items . T_INDEX.CallId is a VARCHAR ( 30 ) field.As I understand , Dapper uses NVarchar with strings in a WHERE clause by default.This causes an implicit conversion of every row in my table in SQL , which slows down the query significantly.How can I tell Dapper to use ansi strings in my IN clause for this query ? <code> Query < Thing > ( `` select * from Thing where Name = @ Name '' , new { Name = new DbString { Value = `` abcde '' , IsFixedLength = true , Length = 10 , IsAnsi = true } ) ; Query < IndexRec > ( `` SELECT * FROM T_INDEX WHERE CallId IN @ callIds '' , new { callIds = model.LogEntries.Select ( x = > x.Id ) } ) ;
|
How do I tell Dapper to use varchar for a list of params in a `` WHERE '' clause that uses `` IN '' ?
|
C_sharp : What are some good ways to handle known errors that occur in a method ? Let 's take a user registration method as an example . When a user is signing up , a method SignUp ( User user ) is called . There are a few known errors that might happen.Email is already registeredUsername is already registeredEtcYou could throw specific exceptions : Now specific exceptions could be caught.This is bad in my opinion , because exceptions are being used for flow control.You could return a boolean stating if it succeeded and pass in an error message that would get set if an error occurs : I do n't like this for a few reasons.A value has to be returned . What if the method needs to return a value ? An error message has to be passed in every time.The consumer of the method should be the one determining what the message is.Let 's just say anything where the actual message set in the method is bad.You could use error codes : The very last one here is the one I like best , but I still do n't like it a whole lot . I do n't like the idea of passing an error code in . I do n't like the idea of returning an code either , for that matter.I like the idea of using custom exceptions because it seems a little cleaner , but I do n't like the idea of using exceptions for flow control . Maybe in specific cases like this example , an email already being in the system SHOULD be an exception , and it 's ok.What have other people done in this situation ? <code> public void SignUp ( User user ) { // Email already exists throw new EmailExistsException ( ) ; } public bool SignUp ( User user , out/ref string errorMessage ) { // Email already exists errorMessage = `` Email already exists . `` ; return false ; } public enum Errors { Successful = 0 , EmailExists , UsernameExists , Etc } public Errors SignUp ( User user ) { // Email already exists return Errors.EmailExists ; } // orpublic void SignUp ( User user , out/ref Errors error ) { // Email already exists error = Errors.EmailExists ; }
|
Handling Known Errors and Error Messages in a Method
|
C_sharp : I 've been having really bad memory problems with an ASP.NET Application . It seems as if every time the page loads , the old previous instance of the page is not removed from memory . If you press F5 ten times , the memory adds 10-20MB to the instance . During Stress and performance testing , this would max out the memory and the web server will crash ... I ran ANTS memory profiling and it confirmed that every time a page is loaded , the old instane remains in memory . All my ASP.NET Web pages uses a Master page as well . Again , if I load the page 10 times , then 10 instances of the web page exists , as well as 10 instances of the master page ... http : //oi51.tinypic.com/21msy2g.jpgLooking at the ants profiler results , you can see that every page reload adds around 320Kb to the memory , and thats just the web page , not even taking the master page into account . My application is a life insurance app that captures applications , so it goes through about 30-40 pages . So you can see why this is a masssive proble.How would I go about finding out whats keeping the page in memory ? I have no idea where to begin ... : \All my pages uses Unity and Dependency injection to register service ... Not sure if I need to unregister these services after during page_onUnload.EDITOkay , I 've managed to track the issue down . The reason why the page is n't disposed ( GCollected ) is because of the Unity service instances that registered but nevered unregistered during the unload of the page . This is how I 'm using Unity on my page : I inject the services through public propertiesThen page init , I do the Unity Buildup : Now obviously when the page goes through its normal lifecycle and calls Unload , it ca n't unload because of the dependency injection reference ... I 'm just not sure how to unregistered the services ( SummaryService , PortfolioService ) I tried calling the following in OnUnload but it does nothing : ApplicationContainer.GetContainer ( Context ) .Teardown ( this ) ; <code> # region Services [ Dependency ] public ReviewReportService SummaryService { get ; set ; } [ Dependency ] public Portfolios.PortfolioService PortfolioService { get ; set ; } # endregion protected override void OnInit ( EventArgs e ) { base.OnInit ( e ) ; ApplicationContainer.BuildUp ( this.Context , this ) ; }
|
ASP.NET Pages not removed from memory
|
C_sharp : I wan na select some records from the informix database via Odbc connection and insert them to a Sql database table.I 've searched regrading that , but they did n't solve my issue . Is it possible to have both connections at one place ? Any help or suggestions would be appreciated . Thanks <code> INSERT INTO SAS.dbo.disconnectiontemp ( meterno ) SELECT DISTINCT met_number FROM Bills.dbadmin.MeterData
|
Odbc & Sql connection in one query
|
C_sharp : I wrote User Control ( yay ! ) . But I want it to behave as a container . But wait ! I know about Trick . The problem is - I do n't want all of my control to behave like container , but only one part . One - de facto - panel ; ) To give wider context : I wrote a control that has Grid , some common buttons , labels and functionalities . But it also has a part where the user is supposed to drop his custom buttons/controls whatever . Only in this particular part of the control , nowhere else . Anyone had any idea ? <code> [ Designer ( `` System.Windows.Forms.Design.ParentControlDesigner , System.Design '' , typeof ( IDesigner ) ) ]
|
UserControl with header and content - Allow dropping controls in content panel and Prevent dropping controls in header at design time
|
C_sharp : I was fiddling around with parsing in C # and found that for every string I tried , string.StartsWith ( `` \u2D2D '' ) will return true . Why is that ? It seems it works with every char . Tried this code with .Net 4.5 the Debugger did not break . <code> for ( char i = char.MinValue ; i < char.MaxValue ; i++ ) { if ( ! i.ToString ( ) .StartsWith ( `` \u2d2d '' ) ) { Debugger.Break ( ) ; } }
|
Why does string.StartsWith ( `` \u2D2D '' ) always return true ?
|
C_sharp : I am currently working on a C # .NET Add-In for Microsoft Outlook.The goal of the Add-In is , to capture the search input from the Outlook Instant Search , and show in a Custom Pane my own search results.It works pretty well , and with subclassing the Outlook Window with a Native Window , I get the search string , and it already passes that into my panel.The problem is now , that when you close the Add-In ( via `` File- > Options- > Add-Ins- > COM Add-Ins '' , but not with the X in the pane ) , the Add-In gets terminated instantly and I ca n't call searchboxWindow.ReleaseHandle ( ) beforehand to restore my WndProc chain . Outlook simply crashes without any visible errors.I already tried to listen to a few Window Messages that should be called when the Add-In gets closed , but these messages only appear when I close the Outlook in a normal way.Also , the events in the main Add-In source file like AppDomain.CurrentDomain.ProcessExit , this.Shutdown , or ( ( Outlook.ApplicationEvents_10_Event ) this.Application ) .Quit do n't get called.What event can I listen on that ( reliably ) gets fired when the Add-In is terminated ? Are there some ? If not , what alternatives to solve my problem do I have ? <code> protected override void WndProc ( ref Message m ) { base.WndProc ( ref m ) ; switch ( ( uint ) m.Msg ) { case WindowMessages.WM_DESTROY : case WindowMessages.WM_QUIT : case WindowMessages.WM_NCDESTROY : this.ReleaseHandle ( ) ; return ; case WindowMessages.WM_KEYUP : case WindowMessages.WM_LBUTTONDOWN : case WindowMessages.WM_RBUTTONDOWN : OnKeyUp ( ) ; break ; case WindowMessages.WM_EXITSIZEMOVE : OnResize ( ) ; break ; } }
|
Native Window : Release Handle On Close
|
C_sharp : This compiles correctly in C # 7.3 ( Framework 4.8 ) : I know that this is syntactic sugar for the following , which also compiles correctly : So , it appears that ValueTuples can be assigned covariantly , which is awesome ! Unfortunately , I do n't understand why : I was under the impression that C # only supported covariance on interfaces and delegates . ValueType is neither.In fact , when I try to duplicate this feature with my own code , I fail : So , why can ValueTuples be assigned covariantly , but MyValueTuples ca n't ? <code> ( string , string ) s = ( `` a '' , `` b '' ) ; ( object , string ) o = s ; ValueTuple < string , string > s = new ValueTuple < string , string > ( `` a '' , `` b '' ) ; ValueTuple < object , string > o = s ; struct MyValueTuple < A , B > { public A Item1 ; public B Item2 ; public MyValueTuple ( A item1 , B item2 ) { Item1 = item1 ; Item2 = item2 ; } } ... MyValueTuple < string , string > s = new MyValueTuple < string , string > ( `` a '' , `` b '' ) ; MyValueTuple < object , string > o = s ; // ^ Can not implicitly convert type 'MyValueTuple < string , string > ' to 'MyValueTuple < object , string > '
|
What makes ValueTuple covariant ?
|
C_sharp : I have encountered a problem while using Invariants with Code Contracts . I want to define an Invariant within my abstract class but it is simply ignored . The code below shows my interface and the abstract class.Afterwards , I implement this interface within my Point class and create an object from it . This should at least fail during runtime . When I move the Invariant to the Point-Class , it works fine . All other pre- or post conditions are working fine too.Is it not possible to have Invariants within an abstract class or am I doing it wrong ? <code> [ ContractClass ( typeof ( IPointContract ) ) ] interface IPoint { int X { get ; } int Y { get ; } } [ ContractClassFor ( typeof ( IPoint ) ) ] abstract class IPointContract : IPoint { public int X { get { return 0 ; } } public int Y { get { return 0 ; } } [ ContractInvariantMethod ] private void PointInvariant ( ) { Contract.Invariant ( X > Y ) ; } } class Point : IPoint { public Point ( int X , int Y ) { this._x = X ; this._y = Y ; } private int _x ; public int X { get { return _x ; } } private int _y ; public int Y { get { return _y ; } } } class Program { static void Main ( string [ ] args ) { Point p = new Point ( 1 , 2 ) ; } }
|
Code Contracts : Invariants in abstract class
|
C_sharp : Would it be considered bad practice to have a viewmodel that has a property of another view model ? ... as in : EDITA little more about my particular situation : I have a view model that currently contains 2 domain classes . I pass this viewmodel to a view that loads 2 partials views ( one for each domain class in the viewmodel ) So with this I end up passing pure domain models directly into the partial views.My thinking is that I can make a view model for each domain model that go to the partials ... and then wrap those 2 in another viewmodel that gets passed to my parent ... or is there a better way to accomplish this ? <code> public class PersonViewModel { public PersonJobViewModel Peron { get ; set ; } //other properties here ... }
|
Is it bad practice to have a ViewModel with a property typed as another ViewModel in ASP.NET MVC
|
C_sharp : I have some code that was recently upgraded from EF 4.2 to EF 5.0 ( actually EF 4.4 since I am running on .Net 4.0 ) . I have discovered that I had to change the syntax of my query , and I 'm curious as to why . Let me start off with the problem.I have an EventLog table that is populated by the client periodically . For each event log an entry is created in a Report table . This is the query that is run periodically to discover any event logs that do not have an entry in the Report table yet . The query I used in EF 4.2 was : Since upgrading to EF 5.0 I get the following error at runtime : System.NotSupportedException : Unable to create a constant value of type 'Namespace.Report ' . Only primitive types or enumeration types are supported in this context.I discovered that rewriting it with the join syntax fixed the issue . The following works in EF 5.0 and is roughly the equivalent : Some people may have mixed opinions about the mixed syntax/style of the first query , but I 'm really more interested in the why of this . It seems odd that the EF 4.2 compiler could generate the SQL for the original query but that the EF 5.0 refuses . Is this a setting I am missing or just a tightening of constraints between the two ? Why is this happening ? <code> from el in _repository.EventLogswhere ! _repository.Reports.Any ( p = > p.EventLogID == el.EventlogID ) from eventLog in _repository.EventLogsjoin report in _repository.Reports on eventLog.EventlogID equals report.EventLogID into alreadyReportedwhere ! alreadyReported.Any ( )
|
Why does EF 5.0 not support this EF 4.x LINQ syntax when compiling to sql ?
|
C_sharp : Let 's say , hypothetically ( read : I do n't think I actually need this , but I am curious as the idea popped into my head ) , one wanted an array of memory set aside locally on the stack , not on the heap . For instance , something like this : I 'm guessing the answer is no . All I 've been able to find is heap based arrays . If someone were to need this , would there be any workarounds ? Is there any way to set aside a certain amount of sequential memory in a `` value type '' way ? Or are structs with named parameters the only way ( like the way the Matrix struct in XNA has 16 named parameters ( M11-M44 ) ) ? <code> private void someFunction ( ) { int [ 20 ] stackArray ; //C style ; I know the size and it 's set in stone }
|
Are stack based arrays possible in C # ?
|
C_sharp : Let 's assume I have a class that has a property of type Dictionary < string , string > , that may be null.This compiles but the call to TryGetValue ( ) could throw at a NullRef exception at runtime : So I 'm adding a null-propagating operator to guard against nulls , but this does n't compile : Is there an actual use case where val will be uninitialized inside the if block , or can the compiler simply not infer this ( and why ) ? Update : The cleanest ( ? ) way to workaround^H^H^H^H^H fix this is : <code> MyClass c = ... ; string val ; if ( c.PossiblyNullDictionary.TryGetValue ( `` someKey '' , out val ) ) { Console.WriteLine ( val ) ; } MyClass c = ... ; string val ; if ( c.PossiblyNullDictionary ? . TryGetValue ( `` someKey '' , out val ) ? ? false ) { Console.WriteLine ( val ) ; // use of unassigned local variable } MyClass c = ... ; string val = null ; //POW ! initialized.if ( c.PossiblyNullDictionary ? . TryGetValue ( `` someKey '' , out val ) ? ? false ) { Console.WriteLine ( val ) ; // no more compiler error }
|
Null propagation operator , out parameters and false compiler errors ?
|
C_sharp : My test code : My problem is : I can not directly declare pictureUrl like this : I 've tried to do that , it threw me error message : 'Task < UserProfileViewModels > ' does not contain a definition for 'PictureUrl ' and no extension method 'PictureUrl ' accepting a first argument of type 'Task < UserProfileViewModels > ' could be found.Can you explain me why ? <code> using ( var db = new MyDbContext ( ) ) { string id = `` '' ; string pictureUrl = db.UserProfile.Single ( x = > x.Id == id ) .PictureUrl ; //valid syntax var user = await db.UserProfile.SingleAsync ( x = > x.Id == id ) ; //valid syntax string _pictureUrl = user.PictureUrl ; //valid syntax } string pictureUrl = await db.UserProfile.SingleAsync ( x = > x.Id == id ) .PictureUrl ;
|
Why can not I directly access property `` .SingleAsync ( ) .Property '' ?
|
C_sharp : I am creating ( then altering ) a bitmap using `` unsafe '' code in a C # winforms project . This is done every 30ms or so . The problem I 'm having is that `` noise '' or random pixels will show up sometimes in the resulting bitmap where I did not specifically change anything.For example , I create a bitmap of 100x100 . Using BitmapData and LockBits , I iterate through the bitmap and change certain pixels to a specific color . Then I UnlockBits and set a picturebox to use the image . All of the pixels I set are correct , but pixels that I did not specifically set are sometimes seemingly random colors.If I set every pixel , the noise disappears . However , for performance reasons , I would prefer only to set the minimum number.Can anyone explain why it does this ? Here is some example code : In this example , I am only setting the left half of the image ( Width/2 in the inner for loop ) . The right half will have random noise on an otherwise black background . <code> // Create new output bitmapBitmap Output_Bitmap = new Bitmap ( 100 , 100 ) ; // Lock the output bitmap 's bitsRectangle Output_Rectangle = new Rectangle ( 0 , 0 , Output_Bitmap.Width , Output_Bitmap.Height ) ; BitmapData Output_Data = Output_Bitmap.LockBits ( Output_Rectangle , ImageLockMode.WriteOnly , PixelFormat.Format32bppRgb ) ; const int PixelSize = 4 ; unsafe { for ( int y = 0 ; y < Output_Bitmap.Height ; y++ ) { for ( int x = 0 ; x < Output_Bitmap.Width/2 ; x++ ) { Byte* Output_Row = ( Byte* ) Output_Data.Scan0 + y * Output_Data.Stride ; Output_Row [ ( x * PixelSize ) + 2 ] = 255 ; Output_Row [ ( x * PixelSize ) + 1 ] = 0 ; Output_Row [ ( x * PixelSize ) + 0 ] = 0 ; } } } // Unlock the bitsOutput_Bitmap.UnlockBits ( Output_Data ) ; // Set picturebox to use bitmappbOutput.Image = Output_Bitmap ;
|
How to avoid `` noise '' when setting pixels of image in unsafe code
|
C_sharp : This is very baffling to me . Somehow the IndexOf ( string ) method of my List < string > object is returning -1 even though the value is CLEARLY in the List.string prefix is `` 01 '' validPrefixes index 0 is `` 01 '' .indexOf is -1 . Umm ... How ? <code> protected readonly List < string > validPrefixes = new List < string > ( ) { `` 01 '' , `` 02 '' , `` 03 '' , `` FE '' , `` E1 '' , `` E2 '' , `` E3 '' } ;
|
List < string > object IndexOf returning -1 . How ?
|
C_sharp : I have a situation where I have a simple , immutable value type : When I box an instance of this value type , I would normally expect that whatever it is that I boxed would come out the same when I do an unbox . To my big suprise this is not the case . Using Reflection someone may easily modify my box 's memory by reinitializing the data contained therein : Sample output : Whats in the box : 013b50a4-451e-4ae8-b0ba-73bdcb0dd612 : : ConsoleApplication1.ImmutableStruct Whats in the box : 176380e4-d8d8-4b8e-a85e-c29d7f09acd0 : : ConsoleApplication1.ImmutableStruct ( There 's actually a small hint in the MSDN that indicates this is the intended behavior ) Why does the CLR allow mutating boxed ( immutable ) value types in this subtle way ? I know that readonly is no guarantee , and I know that using `` traditional '' reflection a value instance can be easily mutated . This behavior becomes an issue , when the reference to the box is copied around and mutations show up in unexpected places . One thing I have though about is that this enables using Reflection on value types at all - since the System.Reflection API works with object only . But Reflection breaks apart when using Nullable < > value types ( they get boxed to null if they do not have a Value ) . Whats the story here ? <code> public struct ImmutableStruct { private readonly string _name ; public ImmutableStruct ( string name ) { _name = name ; } public string Name { get { return _name ; } } } class Program { static void Main ( string [ ] args ) { object a = new ImmutableStruct ( Guid.NewGuid ( ) .ToString ( ) ) ; PrintBox ( a ) ; MutateTheBox ( a ) ; PrintBox ( a ) ; ; } private static void PrintBox ( object a ) { Console.WriteLine ( String.Format ( `` Whats in the box : { 0 } : : { 1 } '' , ( ( ImmutableStruct ) a ) .Name , a.GetType ( ) ) ) ; } private static void MutateTheBox ( object a ) { var ctor = typeof ( ImmutableStruct ) .GetConstructors ( ) .Single ( ) ; ctor.Invoke ( a , new object [ ] { Guid.NewGuid ( ) .ToString ( ) } ) ; } }
|
Why does the CLR allow mutating boxed immutable value types ?
|
C_sharp : Given a set of sixteen letters and an English dictionary file , need to find a solution where those sixteen letters can fit into a 4x4 grid so that a valid word can be read across each row , and down each column.My current solution:1 ) Get a list of all of the possible 4-letter words that can be made with those letters ( anagram generator ) and assign them to an array.2 ) Loop through each word , trying it in every row , while checking that the correct number of each letter is used.3 ) Checking if the word created in each column exists in the anagram array.The logic works , but it 's been running over an hour and I 'm on word 200 of the 400+ array of anagrams . Any suggestions ? Here is an example , as requested : Given the letters `` N , O , O , and T '' find a solution where these letters fit into a 2x2 grid so that when read across and down , English words can be created . The answer would be : Except this problem is for a 4x4 grid.UPDATE : Thanks for your help , but I 'm an idiot . I did n't fix my copy/pasted variables ( which , I suppose , goes back to the guy who suggested I refactor ) . Also , the way I was comparing arrays was faulty . Fixed these issues and ran against known working word list , worked like a charm . Ran again against my original data , took 13 seconds . No results . Thanks again for your help.UPDATE 2 : Since I do n't have enough rep to answer my own question , here is my working code ( ... code deleted ... see dasblinklight 's answer below ) UPDATE 3 : Please see dasblinkenlight 's answer below . Much more elegant , fewer loops . Thanks ! <code> namespace GridWords { class Program { static void Main ( string [ ] args ) { string [ ] words = new string [ ] { `` zoon '' , `` zonk '' , `` zone '' , `` zona '' , `` zoea '' , `` zobo '' , `` zero '' , `` zerk '' , `` zeal '' , `` zack '' , `` rore '' , `` roon '' , `` rook '' , `` rood '' , `` rone '' , `` role '' , `` roke '' , `` roed '' , `` rode '' , `` rock '' , `` roch '' , `` robe '' , `` roar '' , `` roan '' , `` road '' , `` rhea '' , `` rend '' , `` redo '' , `` reck '' , `` rear '' , `` rean '' , `` real '' , `` reak '' , `` read '' , `` raze '' , `` rare '' , `` rank '' , `` rand '' , `` rana '' , `` rale '' , `` rake '' , `` rade '' , `` rack '' , `` rach '' , `` race '' , `` raca '' , `` orzo '' , `` orra '' , `` orle '' , `` ordo '' , `` orca '' , `` oral '' , `` orad '' , `` ooze '' , `` oner '' , `` once '' , `` oleo '' , `` olea '' , `` olde '' , `` okra '' , `` okeh '' , `` ohed '' , `` odor '' , `` odea '' , `` odal '' , `` odah '' , `` oche '' , `` obol '' , `` oboe '' , `` nork '' , `` noob '' , `` nook '' , `` nolo '' , `` nole '' , `` noel '' , `` node '' , `` nock '' , `` nerk '' , `` nerd '' , `` neck '' , `` near '' , `` neal '' , `` naze '' , `` nark '' , `` nare '' , `` nard '' , `` narc '' , `` nala '' , `` nada '' , `` nach '' , `` nabk '' , `` nabe '' , `` lorn '' , `` lore '' , `` lord '' , `` loor '' , `` loon '' , `` look '' , `` lone '' , `` loke '' , `` lode '' , `` loco '' , `` lock '' , `` loch '' , `` loca '' , `` lobo '' , `` lobe '' , `` loan '' , `` load '' , `` leno '' , `` lend '' , `` lehr '' , `` lech '' , `` lear '' , `` lean '' , `` leak '' , `` lead '' , `` lazo '' , `` laze '' , `` larn '' , `` lark '' , `` lare '' , `` lard '' , `` lank '' , `` lane '' , `` land '' , `` lana '' , `` lakh '' , `` lake '' , `` laer '' , `` lade '' , `` lack '' , `` lace '' , `` krab '' , `` kore '' , `` kora '' , `` kond '' , `` kolo '' , `` kola '' , `` kohl '' , `` koel '' , `` kobo '' , `` koan '' , `` knob '' , `` knar '' , `` khor '' , `` khan '' , `` kern '' , `` kerb '' , `` keno '' , `` kbar '' , `` karn '' , `` kara '' , `` kaon '' , `` kane '' , `` kana '' , `` kale '' , `` kaed '' , `` kade '' , `` horn '' , `` hore '' , `` hora '' , `` hoon '' , `` hook '' , `` hood '' , `` honk '' , `` hone '' , `` hond '' , `` holk '' , `` hole '' , `` hold '' , `` hoke '' , `` hoer '' , `` hoed '' , `` hock '' , `` hobo '' , `` hoar '' , `` hero '' , `` hern '' , `` herl '' , `` herd '' , `` herb '' , `` hend '' , `` helo '' , `` held '' , `` heck '' , `` hear '' , `` heal '' , `` head '' , `` haze '' , `` haro '' , `` harn '' , `` harl '' , `` hark '' , `` hare '' , `` hard '' , `` hank '' , `` hand '' , `` halo '' , `` hale '' , `` hake '' , `` haka '' , `` haen '' , `` haed '' , `` hade '' , `` hack '' , `` haar '' , `` eorl '' , `` eoan '' , `` enol '' , `` elan '' , `` ecod '' , `` echo '' , `` ecad '' , `` ebon '' , `` earn '' , `` earl '' , `` eard '' , `` each '' , `` dzho '' , `` drek '' , `` drab '' , `` doze '' , `` dorr '' , `` dork '' , `` dore '' , `` door '' , `` dool '' , `` dook '' , `` doob '' , `` done '' , `` dona '' , `` dole '' , `` doer '' , `` doen '' , `` doek '' , `` dock '' , `` doab '' , `` dhal '' , `` dhak '' , `` dern '' , `` deco '' , `` deck '' , `` dear '' , `` dean '' , `` deal '' , `` daze '' , `` darn '' , `` darl '' , `` dark '' , `` dare '' , `` darb '' , `` dank '' , `` dale '' , `` dahl '' , `` dace '' , `` daal '' , `` czar '' , `` cred '' , `` cran '' , `` crab '' , `` coze '' , `` corn '' , `` cork '' , `` core '' , `` cord '' , `` coon '' , `` cool '' , `` cook '' , `` conk '' , `` cone '' , `` cond '' , `` cole '' , `` cold '' , `` cola '' , `` coke '' , `` coho '' , `` coed '' , `` code '' , `` coda '' , `` coal '' , `` clon '' , `` clod '' , `` clan '' , `` clad '' , `` chon '' , `` chez '' , `` cher '' , `` char '' , `` chao '' , `` chal '' , `` chad '' , `` cero '' , `` carr '' , `` carn '' , `` carl '' , `` cark '' , `` care '' , `` card '' , `` carb '' , `` cane '' , `` calo '' , `` calk '' , `` cake '' , `` cade '' , `` caba '' , `` broo '' , `` brod '' , `` brer '' , `` bren '' , `` bred '' , `` bran '' , `` brae '' , `` brad '' , `` bozo '' , `` born '' , `` bork '' , `` bore '' , `` bord '' , `` bora '' , `` boor '' , `` boon '' , `` bool '' , `` book '' , `` booh '' , `` bonk '' , `` bone '' , `` bond '' , `` bona '' , `` bolo '' , `` bole '' , `` bold '' , `` bola '' , `` boko '' , `` boke '' , `` boho '' , `` bode '' , `` bock '' , `` boar '' , `` boak '' , `` bloc '' , `` bled '' , `` blah '' , `` blae '' , `` blad '' , `` bhel '' , `` berk '' , `` bend '' , `` beck '' , `` bear '' , `` bean '' , `` beak '' , `` bead '' , `` barn '' , `` bark '' , `` bare '' , `` bard '' , `` bank '' , `` bane '' , `` band '' , `` banc '' , `` balk '' , `` bale '' , `` bald '' , `` bake '' , `` bael '' , `` bade '' , `` back '' , `` bach '' , `` baal '' , `` azon '' , `` azan '' , `` arna '' , `` arle '' , `` ared '' , `` area '' , `` arco '' , `` arch '' , `` arba '' , `` arar '' , `` arak '' , `` anoa '' , `` ankh '' , `` ance '' , `` anal '' , `` aloe '' , `` alod '' , `` alec '' , `` albe '' , `` alba '' , `` alar '' , `` alan '' , `` alae '' , `` aked '' , `` ahed '' , `` aero '' , `` aeon '' , `` adze '' , `` acre '' , `` acne '' , `` ache '' , `` acer '' , `` aced '' , `` able '' , `` abed '' , `` abac '' } ; char [ ] letters = new char [ ] { ' a ' , ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' h ' , ' k ' , ' l ' , ' n ' , ' o ' , ' o ' , ' o ' , ' r ' , ' r ' , ' z ' } ; for ( int z = 0 ; z < words.Length ; z++ ) { Console.WriteLine ( z ) ; for ( int y = 0 ; y < words.Length ; y++ ) { bool letterCountCorrect0 = true ; char [ ] wordLetters0 = words [ z ] .ToCharArray ( ) .Concat ( words [ y ] .ToCharArray ( ) ) .ToArray ( ) ; for ( int a = 0 ; a < wordLetters0.Length ; a++ ) { if ( countInstances ( wordLetters0 , wordLetters0 [ a ] ) ! = countInstances ( letters , wordLetters0 [ a ] ) ) { letterCountCorrect0 = false ; break ; } } if ( y ! = z & & letterCountCorrect0 ) { for ( int x = 0 ; x < words.Length ; x++ ) { bool letterCountCorrect1 = true ; char [ ] wordLetters1 = words [ z ] .ToCharArray ( ) .Concat ( words [ y ] .ToCharArray ( ) ) .Concat ( words [ x ] .ToCharArray ( ) ) .ToArray ( ) ; for ( int a = 0 ; a < wordLetters0.Length ; a++ ) { if ( countInstances ( wordLetters0 , wordLetters0 [ a ] ) ! = countInstances ( letters , wordLetters0 [ a ] ) ) { letterCountCorrect1 = false ; break ; } } if ( x ! = y & & x ! = z & & letterCountCorrect1 ) { for ( int w = 0 ; w < words.Length ; w++ ) { bool letterCountCorrect2 = true ; char [ ] wordLetters2 = words [ z ] .ToCharArray ( ) .Concat ( words [ y ] .ToCharArray ( ) ) .Concat ( words [ x ] .ToCharArray ( ) ) .Concat ( words [ w ] .ToCharArray ( ) ) .ToArray ( ) ; for ( int a = 0 ; a < wordLetters0.Length ; a++ ) { if ( countInstances ( wordLetters0 , wordLetters0 [ a ] ) ! = countInstances ( letters , wordLetters0 [ a ] ) ) { letterCountCorrect2 = false ; break ; } } if ( w ! = x & & w ! = y & & w ! = z & & letterCountCorrect2 ) { char [ ] row1 = words [ z ] .ToCharArray ( ) ; char [ ] row2 = words [ y ] .ToCharArray ( ) ; char [ ] row3 = words [ x ] .ToCharArray ( ) ; char [ ] row4 = words [ w ] .ToCharArray ( ) ; char [ ] wordLetterArray = row1.Concat ( row2 ) .Concat ( row3 ) .Concat ( row4 ) .ToArray ( ) ; Array.Sort ( wordLetterArray ) ; if ( wordLetterArray == letters ) { string col1 = new string ( new char [ ] { row1 [ 0 ] , row2 [ 0 ] , row3 [ 0 ] , row4 [ 0 ] } ) ; if ( col1 ! = words [ z ] & & col1 ! = words [ y ] & & col1 ! = words [ x ] & & col1 ! = words [ w ] ) { string col2 = new string ( new char [ ] { row1 [ 1 ] , row2 [ 1 ] , row3 [ 1 ] , row4 [ 1 ] } ) ; if ( col2 ! = words [ z ] & & col2 ! = words [ y ] & & col2 ! = words [ x ] & & col2 ! = words [ w ] ) { string col3 = new string ( new char [ ] { row1 [ 2 ] , row2 [ 2 ] , row3 [ 2 ] , row4 [ 2 ] } ) ; if ( col3 ! = words [ z ] & & col3 ! = words [ y ] & & col3 ! = words [ x ] & & col3 ! = words [ w ] ) { string col4 = new string ( new char [ ] { row1 [ 3 ] , row2 [ 3 ] , row3 [ 3 ] , row4 [ 3 ] } ) ; if ( col4 ! = words [ z ] & & col4 ! = words [ y ] & & col4 ! = words [ x ] & & col4 ! = words [ w ] ) { if ( words.Contains < String > ( col1.ToLower ( ) ) & & words.Contains < String > ( col2.ToLower ( ) ) & & words.Contains < String > ( col3.ToLower ( ) ) & & words.Contains < String > ( col4.ToLower ( ) ) ) { Console.WriteLine ( new string ( row1 ) + `` `` + new string ( row2 ) + `` `` + new string ( row3 ) + `` `` + new string ( row4 ) ) ; //Console.WriteLine ( col1.ToString ( ) + `` `` + col2.ToString ( ) + `` `` + col3.ToString ( ) + `` `` + col4.ToString ( ) ) ; } } } } } } } } } } } } } } private static int countInstances ( char [ ] arrToSearch , char charToFind ) { int count = 0 ; for ( int x = 0 ; x < arrToSearch.Length ; x++ ) { if ( arrToSearch [ x ] == charToFind ) { count++ ; } } return count ; } } } T OO N
|
My iteration is taking forever . Looking for a better way
|
C_sharp : I wrote the following console app to test static properties : As this console app demonstrates , the MyProperty property exists once for all instances of BaseClass . Is there a pattern to use which would allow me to define a static property which will have allocated storage for each sub-class type ? Given the above example , I would like all instances of DerivedAlpha to share the same static property , and all instances of DerivedBeta to share another instance of the static property.Why am I trying to do this ? I am lazily initializing a collection of class property names with certain attributes ( via reflection ) . The property names will be identical for each derived class instance , so it seems wasteful to store this in each class instance . I ca n't make it static in the base class , because different sub-classes will have different properties.I do n't want to replicate the code which populates the collection ( via reflection ) in each derived class . I know that one possible solution is to define the method to populate the collection in the base class , and call it from each derived class , but this is not the most elegant solution.Update - Example of what I 'm doingAt Jon 's request , here 's an example of what I 'm trying to do . Basically , I can optionally decorate properties in my classes with the [ SalesRelationship ( SalesRelationshipRule.DoNotInclude ) ] attribute ( there are other attributes , this is just a simplified example ) .Desired end resultAccessing FooEntity.PropertiesWithDoNotInclude returns a List < string > of : Accessing BarEntity.PropertiesWithDoNotInclude returns a List < string > of : <code> using System ; namespace StaticPropertyTest { public abstract class BaseClass { public static int MyProperty { get ; set ; } } public class DerivedAlpha : BaseClass { } public class DerivedBeta : BaseClass { } class Program { static void Main ( string [ ] args ) { DerivedBeta.MyProperty = 7 ; Console.WriteLine ( DerivedAlpha.MyProperty ) ; // outputs 7 } } } public class BaseEntity { // I want this property to be static but exist once per derived class . public List < string > PropertiesWithDoNotInclude { get ; set ; } public BaseEntity ( ) { // Code here will populate PropertiesWithDoNotInclude with // all properties in class marked with // SalesRelationshipRule.DoNotInclude . // // I want this code to populate this property to run once per // derived class type , and be stored statically but per class type . } } public class FooEntity : BaseEntity { [ SalesRelationship ( SalesRelationshipRule.DoNotInclude ) ] public int ? Property_A { get ; set ; } public int ? Property_B { get ; set ; } [ SalesRelationship ( SalesRelationshipRule.DoNotInclude ) ] public int ? Property_C { get ; set ; } } public class BarEntity : BaseEntity { public int ? Property_D { get ; set ; } [ SalesRelationship ( SalesRelationshipRule.DoNotInclude ) ] public int ? Property_E { get ; set ; } public int ? Property_F { get ; set ; } } { `` Property_A '' , `` Property_C '' } { `` Property_E '' }
|
What is the best way to define a static property which is defined once per sub-class ?
|
C_sharp : I am using application insights sdk for a wpf app I 've been working on to capture some simple telemetry . I am loading the configuration file that looks like thisThe problem is when I run the installed application and am offline the telemetry is captured just fine . Next time I open the app when I 'm online that data eventually gets pushed out to app insights . But when anyone else runs the application offline their data never ends up getting pushed to app insights when they come back online . Is there something wrong here in the way that this is configured ? Why would this work for some users but not others ? edit : Working with a user today I noticed that when they are offline and running the app there is no temporary file that is saved . When I do the same thing on my computer I notice a weird temp file gets created . When I run the app when back online it disappears . <code> < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ApplicationInsights xmlns= '' http : //schemas.microsoft.com/ApplicationInsights/2013/Settings '' > < TelemetryChannel Type= '' Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel , Microsoft.AI.ServerTelemetryChannel '' / > < TelemetryProcessors > < Add Type= '' Microsoft.ApplicationInsights.Extensibility.AutocollectedMetricsExtractor , Microsoft.ApplicationInsights '' / > < Add Type= '' Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor , Microsoft.AI.ServerTelemetryChannel '' > < MaxTelemetryItemsPerSecond > 5 < /MaxTelemetryItemsPerSecond > < ExcludedTypes > Event < /ExcludedTypes > < /Add > < Add Type= '' Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.AdaptiveSamplingTelemetryProcessor , Microsoft.AI.ServerTelemetryChannel '' > < MaxTelemetryItemsPerSecond > 5 < /MaxTelemetryItemsPerSecond > < IncludedTypes > Event < /IncludedTypes > < /Add > < /TelemetryProcessors >
|
App Insights Telemetry not sending when offline
|
C_sharp : I am trying to develop an algorithm in C # that can take an array list of URL 's and output them in an outline numbered list.As you can imagine I need some help . Does anyone have any suggestions on the logic to use to generate this list ? Example Output : ... and so on <code> 1 - http : //www.example.com/aboutus1.2 - http : //www.example.com/aboutus/page11.3 - http : //www.example.com/aboutus/page21.3.1 - http : //www.example.com/aboutus/page2/page31.3.1.1 - http : //www.example.com/aboutus/page2/page3/page41.3.2 - http : //www.example.com/aboutus/page5/page61.3.2.1 - http : //www.example.com/aboutus/page5/page7/page91.3.2.2 - http : //www.example.com/aboutus/page5/page8/page101.4 - http : //www.example.com/aboutus/page101.4.1 - http : //www.example.com/aboutus/page10/page111.4.2 - http : //www.example.com/aboutus/page10/page121.1.5 - http : //www.example.com/aboutus/page131.1.6 - http : //www.example.com/aboutus/page141.1.6.1 - http : //www.example.com/aboutus/page14/page151.1.6.2 - http : //www.example.com/aboutus/page14/page161.1.6.3 - http : //www.example.com/aboutus/page14/page17
|
c # outline numbering
|
C_sharp : I have function which serialize objects . It is working fine in every case except when I run with specific object . This is object of class which contains Tasks . But I do n't see why would this be problem.In debug mode code is just stuck without any error , or any exception . Just stop and waiting for ever.Also to mention that this serialization is called in running Task , but also I am not sure why would this be problem.I have also set attribute [ NonSerialized ] to all Task properties but still nothing.This is my function : This is object I try to serialize : <code> [ NonSerialized ] private Task < bool > isConnected ; public Task < bool > IsConnected { get { return isConnected ; } set { isConnected = value ; } } public static string ToJson ( this object obj ) { try { var res = JsonConvert.SerializeObject ( obj , Formatting.Indented , new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore } ) ; return res ; } catch { return $ '' Object { obj.ToString ( ) } is not serializable . `` ; } }
|
SerializeObject is waiting for ever
|
C_sharp : I have this code ( the unimportant details are that it runs on EC2 instances in AWS , processing messages on an SQS queue ) .The first statement in the method gets some data over http , the second statement saves state to a local dynamo data store.The performance characteristics are that the http round trip takes 100-200 milliseconds , and the dynamo write takes around 10 milliseconds . Both of these operations have async versions . We could write it as follows : So the guidance is that since the first operation `` could take longer than 50 milliseconds to execute '' it should make use of async and await . ( 1 ) But what about the second , fast operation ? Which of these two arguments is correct : Do not make it async : It does not meet the 50ms criterion and it 's not worth the overhead.Do make it async : The overhead has already been paid by the previous operation . There is already task-based asynchrony happening and it 's worth using it.1 ) http : //blog.stephencleary.com/2013/04/ui-guidelines-for-async.html <code> public bool HandleMessage ( OrderAcceptedMessage message ) { var order = _orderHttpClient.GetById ( message.OrderId ) ; _localDynamoRepo.SaveAcceptedOrder ( message , order ) ; return true ; } public async Task < bool > HandleMessage ( OrderAcceptedMessage message ) { var order = await _orderHttpClient.GetByIdAsync ( message.OrderId ) ; await _localDynamoRepo.SaveAcceptedOrderAsync ( message , order ) ; return true ; }
|
Should I make a fast operation async if the method is already async
|
C_sharp : Our code base has a lot of StringBuilder.AppendFormats that have strings that end with newline characters . I 've made an extension method called AppendLineFormat and would like to use Resharper 's Custom Patterns feature to identify and fix those old calls to use the new extension method ( and to suggest this new extension method to others in the future ) .intoIs there a way to use regex ( with replacement ) to identify strings that match ? I do n't want to turn every AppendFormat into an AppendLineFormat - only the ones with strings that end in \r\n . Here 's what I 've got so far.Search Pattern : Replace Pattern : Where $ sb $ is an expression of type System.Text.StringBuilder $ newLineString $ is an identifier matching `` ( . * ) \\r\\n '' ( totally wrong , I know ) $ args $ is any number of arguments <code> StringBuilder sb = new StringBuilder ( ) ; int i = 1 ; sb.AppendFormat ( `` i is { 0 } \r\n '' , i ) ; sb.AppendLineFormat ( `` i is { 0 } '' , i ) ; $ sb $ .AppendFormat ( $ newLineString $ , $ args $ ) $ sb $ .AppendLineFormat ( $ newLineString $ , $ args $ )
|
Can I use regex to find strings in Resharper 's Custom Patterns ?
|
C_sharp : I have a VC++ COM component with a type library . The type library of this component declares an interface and a co-class : In order to consume the component from a C # application I add a reference to the C # project and an interop assembly is generated.In the Object Browser of Visual Studio 2003 I see that the interop contains : It 's clear that that for some reason the name of the class and the interface differ in capitalization . This does n't happen for other 20+ interfaces declared in the same type library - for them ISomething corresponds to Something and SomethingClass.I 've looked through the .idl files of the project - the identifier Workflow is not used anywhere else.What 's the reason of this strange behaviour and how can it be worked around ? <code> [ object , uuid ( ActualUuidHere ) , dual , nonextensible , oleautomation , hidden , helpstring ( ActualHelpStringHere ) ] interface IWorkflow : IDispatch { //irrelevant properties here } [ uuid ( ActualClassIdHere ) , noncreatable ] coclass Workflow { [ default ] interface IWorkflow ; } ; public abstract interface IWorkflow ; public abstract interface workflow : IWorkflow ; public class workflowClass : System.Object ;
|
Names in the interop assembly have wrong capitalization
|
C_sharp : My Application can perform 5 business functions . I now have a requirement to build this into the licensing model for the application.My idea is to ship a `` keyfile '' with the application . The file should contain some encrypted data about which functions are enabled in the application and which are not . I want it semi hack proof too , so that not just any idiot can figure out the logic and `` crack '' it.The decrypted version of this file should contain for example : Please can you give me some ideas on how to do this ? <code> BUSINESS FUNCTION 1 = ENABLED BUSINESS FUNCTION 2 = DISABLED ... . etc
|
How can I secure an `` enabled functions '' license file for my program ?
|
C_sharp : Good day ! I allow my content editors to store CSS as very basic components ( usually containing a single , multi-line field called `` code '' that they paste into ) , and these are then added as Component Presentations into a Page with a .css file extension . When creating the page , users are able to set a few configuration values : minify output ( bool ) , file name prefix , and file name suffix . The intent of those last two is that if the user has selected to minify the CSS on its way out the door , the file name can be different sitting on the presentation server.I 've got everything working except the modification of the file name . I do n't want to change the file name in the CM ; only as it resides out on the presentation server . I assume this can be done in a TBB placed into the CSS Page Template . I took a crack at it , but want to be sure that there 's not something I 'm missing . The following example is just the shorthand with some configurable values hard-coded for brevity . <code> // Create a reference to the Page object in the package.Page page = this.GetPage ( ) ; // Retrieve a reference to the page 's file name.string currentFileName = Utilities.GetFilename ( page.FileName ) ; // Set the published file name on its way out the door.page.FileName = currentFileName + `` _min '' ; // ? ? ? // Profit .
|
Tridion 2011 : Changing a page 's file name as it 's being published
|
C_sharp : I found this bit of code that computes Levenshtein 's distance between an answer and a guess : But I need a way to do a count for the amount of times each error occurs . Is there an easy way to implement that ? <code> int CheckErrors ( string Answer , string Guess ) { int [ , ] d = new int [ Answer.Length + 1 , Guess.Length + 1 ] ; for ( int i = 0 ; i < = Answer.Length ; i++ ) d [ i , 0 ] = i ; for ( int j = 0 ; j < = Guess.Length ; j++ ) d [ 0 , j ] = j ; for ( int j = 1 ; j < = Guess.Length ; j++ ) for ( int i = 1 ; i < = Answer.Length ; i++ ) if ( Answer [ i - 1 ] == Guess [ j - 1 ] ) d [ i , j ] = d [ i - 1 , j - 1 ] ; //no operation else d [ i , j ] = Math.Min ( Math.Min ( d [ i - 1 , j ] + 1 , //a deletion d [ i , j - 1 ] + 1 ) , //an insertion d [ i - 1 , j - 1 ] + 1 //a substitution ) ; return d [ Answer.Length , Guess.Length ] ; }
|
Levenshtein distance c # count error type
|
C_sharp : I have the following code : I want to write one function that will properly trim the fields , something like : Of course , this is not permitted in C # .One option I have is to write a helper and use reflection.Is there another way I can achieve this ( reflecting on so many properties will deffinitely have a performance hit on that particular scenario and I ca n't afford that ) ? <code> class SearchCriteria { public string Name { get ; set ; } public string Email { get ; set ; } public string Company { get ; set ; } // ... around 20 fields follow public void Trim ( ) { if ( ! String.IsNullOrEmpty ( Name ) ) { Name = Name.Trim ( ) ; } if ( ! String.IsNullOrEmpty ( Email ) ) { Email = Email.Trim ( ) ; } // ... repeat for all 20 fields in the class . } } public void Trim ( ) { Trim ( Name ) ; Trim ( Email ) ; // ... } private static void Trim ( ref string field ) { if ( ! String.IsNullOrEmpty ( field ) ) { field = field.Trim ( ) ; } }
|
Modify multiple string fields
|
C_sharp : I was writing some code today and was mid line when I alt-tabbed away to a screen on my other monitor to check something . When I looked back , ReSharper had colored the 3rd line below grey with the note `` Value assigned is not used in any execution path '' . I was confused ; surely this code ca n't compile . But it does , and it runs too . The line `` name += '' has no effect ( that I could tell ) on the string . What 's going on here ? ( Visual Studio 2008 , .NET 3.5 ) <code> var ltlName = ( Literal ) e.Item.FindControl ( `` ltlName '' ) ; string name = item.FirstName ; name += ltlName.Text = name ;
|
Why is `` someString += AnotherString = someString ; '' valid in C #
|
C_sharp : If JavaScript 's Number and C # 's double are specified the same ( IEEE 754 ) , why are numbers with many significant digits handled differently ? I am not concerned with the fact that IEEE 754 can not represent the number 1234123412341234123 . I am concerned with the fact that the two implementations do not act the same for numbers that can not be represented with full precision . This may be because IEEE 754 is under specified , one or both implementations are faulty or that they implement different variants of IEEE 754 . This problem is not related to problems with floating point output formatting in C # . I 'm outputting 64-bit integers . Consider the following : long x = 1234123412341234123 ; Console.WriteLine ( x ) ; // Prints 1234123412341234123 double y = 1234123412341234123 ; x = Convert.ToInt64 ( y ) ; Console.WriteLine ( x ) ; // Prints 1234123412341234176The same variable prints different strings because the values are different . <code> var x = ( long ) 1234123412341234123.0 ; // 1234123412341234176 - C # var x = 1234123412341234123.0 ; // 1234123412341234200 - JavaScript
|
Why are numbers with many significant digits handled differently in C # and JavaScript ?
|
C_sharp : I need to replace some parts of a string with each other using C # .I could find only one similar question about how to achive this here but it was PHP.My situation involves a Dictionary [ string , string ] which holds pairs to replace like : dog , cat cat , mouse , mouse , raptorAnd I have a string with the value of : I need a function to get this : If I enumerate the dictionary and call string.Replace by order , I get this : It 's weird if this has n't been asked before , ( Is it common knowledge ? ) but I could n't find any . So I 'm sorry if it has and I missed it . <code> `` My dog ate a cat which once ate a mouse got eaten by a raptor '' `` My cat ate a mouse which once ate a raptor got eaten by a raptor '' `` My raptor ate a raptor which once ate a raptor got eaten by a raptor ''
|
How to replace two or more strings with each other ?
|
C_sharp : The following code finds instances of the word `` Family '' in a Word document . It selects and deletes the instances . The code works fine , but I want to find all instances of only highlighted words . <code> public void FindHighlightedText ( ) { const string filePath = `` D : \\COM16_Duke Energy.doc '' ; var word = new Microsoft.Office.Interop.Word.Application { Visible = true } ; var doc = word.Documents.Open ( filePath ) ; var range = doc.Range ( ) ; range.Find.ClearFormatting ( ) ; range.Find.Text = `` Family '' ; while ( range.Find.Execute ( ) ) { range.Select ( ) ; range.Delete ( ) ; } doc.Close ( ) ; word.Quit ( true , Type.Missing , Type.Missing ) ; }
|
Find highlighted text
|
C_sharp : I have an int array in one dimension : and I want to convert it to two dimensions , such as : How do I achieve this with C # ? <code> var intArray=new [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ; var intArray2D=new [ , ] { { 1 , 2 } , { 3 , 4 } , { 5 , 6 } } ;
|
How to Convert int [ ] to int [ , ] - C #
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.