text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : In C # 7.2 , are readonly structs always passed to functions as if the `` in '' parameter is present ? If not , in what case would it be useful to copy the memory given that it 's readonly ? I have a readonly struct : So would there be a performance difference between these two methods when called billions of times : And if so , why does n't the compiler recognize that Vec2 is a readonly struct and just pass it as if `` in '' were present ? Is there an instance where you might want to pass a readonly struct without the `` in '' modifier ? <code> public readonly struct Vec2 { public readonly double X ; public readonly double Y ; } public double Magnitude1 ( Vec2 v ) { return Math.Sqrt ( v.X*v.X + v.Y*v.Y ) ; } public double Magnitude2 ( in Vec2 v ) { return Math.Sqrt ( v.X*v.X + v.Y*v.Y ) ; } | Is it necessary to use the `` in '' modifier with a readonly struct ? |
C_sharp : I recently wrote this and was surprised that it compiles : If I use this class as follows , I get an `` Ambiguous constructor reference '' and an `` Ambiguous invocation '' if I call Add.Obviously , there 's no ambiguity when I use int and double as generic types , except of course when I use both ints , which would also both assign to a double.So then I thought that the following was also allowed , but surprisingly I got an error . Why is the following not allowed to compile ? Regardless if I use implicit or explicit interface implementation , the compiler states that 'MyGeneric < U , V > ' can not implement both 'IMyInterface < U , V > ' and 'IMyInterface < V , U > ' because they may unify for some type parameter substitutionsAnd why is the first allowed to write ? <code> public class MyGeneric < U , V > { MyGeneric ( U u ) { ... } MyGeneric ( V v ) { ... } public void Add ( U u , V v ) { ... } public void Add ( V v , U u ) { ... } } var myVar = new MyGeneric < int , int > ( new MyIntComparer ( ) ) ; var myVar = new MyGeneric < int , double > ( new MyIntComparer ( ) ) ; myVar.Add ( 3 , 5 ) ; public interface IMyInterface < T , S > { void Add ( T t , S s ) ; } public class MyGeneric < U , V > : IMyInterface < U , V > , IMyInterface < V , U > { public MyGeneric ( U u ) { } public MyGeneric ( V v ) { } void IMyInterface < U , V > .Add ( U u , V v ) { ... } void IMyInterface < V , U > .Add ( V v , U u ) { ... } } | Generics in C # with multiple generic types leads to allowed and disallowed ambiguity |
C_sharp : I 'm developing a class library which should be licensed to specific developer computers . There are no components so that the design time licensing checks ca n't be done . This check is in fact unavailable for pure class libraries : One has suggested to use Debugger.IsAttached to check if the lib is used on the developer machine : Design-Time validation of libraryBut I 'm looking after a solution on the build stage , so that the program wo n't build if the license is invalid ( e.G . this machine is not licensed ) . Any suggestions ? <code> if ( LicenseContext.UsageMode == LicenseUsageMode.Designtime ) ... | execute method from referenced class library before build .NET application for license checking |
C_sharp : just messing around with the unsafe side of c # Is it possible to assign a string literal to a char pointer just like in C or do I have to do it as in the above snippet ? <code> unsafe { char* m = stackalloc char [ 3+1 ] ; m [ 0 ] = ' A ' ; m [ 1 ] = ' B ' ; m [ 2 ] = ' C ' ; m [ 3 ] = '\0 ' ; for ( char* c = m ; *c ! = '\0 ' ; c++ ) { Console.WriteLine ( *c ) ; } Console.ReadLine ( ) ; } | Assign a string literal to a char* |
C_sharp : I have the following -Problem being that the value of i passed into ProcessResult seems to be the value when it starts , not the value of the iteration when it is created.What is the best way to protect against this ? <code> for ( int i = 0 ; i < N ; ++i ) { var firstTask = DoSomething ( ... ) ; var task = anotherTask.ContinueWith ( ( t ) = > ProcessResult ( i , t.Result ) ) ; } | Using anonymous methods inside of a delayed task inside of a loop |
C_sharp : I 'm using Microsoft 's Entity Framework as an ORM and am wondering how to solve the following problem.I want to get a number of Product objects from the Products collection where the Product.StartDate is greater than today . ( This is a simplified version of the whole problem . ) I currently use : When this is executed , after using ToList ( ) for example on query , it works and the SQL created is effectively : However , I want to move the predicate to a function for better maintainability , so I tried this : This also works from a code point of view insofar as it returns the same Product set but this time the SQL created is analogous to : The filter is moved from the SQL Server to the client making it much less efficient.So my questions are : Why is this happening , why does the LINQ parser treat these two formats so differently ? What can I do to take advantage of having the filter separate but having it executed on the server ? <code> var query = dbContext.Products.Where ( p = > p.StartDate > DateTime.Now ) ; SELECT * FROM Product WHERE StartDate > ( GetDate ( ) ) ; private Func < Product , bool > GetFilter ( ) { Func < Product , bool > filter = p = > p.StartDate > DateTime.Now ; return filter ; } var query = dbContext.Products.Where ( GetFilter ( ) ) ; SELECT * FROM Product ; | Why does EntityFramework 's LINQ parser handle an externally defined predicate differently ? |
C_sharp : I 'm trying to convert this long JS regex to C # .The JS code below gives 29 items in an array starting from [ `` '' , '' 常 '' , '' '' , '' に '' , '' '' , '' 最新 '' , '' 、 '' , '' 最高 '' ... ] But the C # code below gives a non-splitted single item in string [ ] .Many questions in Stack Overflow are covering relatively simple expressions only , so I can not find my mistakes.What am I missing ? <code> var keywords = / ( \ & nbsp ; | [ a-zA-Z0-9 ] +\ . [ a-z ] { 2 , } | [ 一-龠々〆ヵヶゝ ] +| [ ぁ-んゝ ] +| [ ァ-ヴー ] +| [ a-zA-Z0-9 ] +| [ a-zA-Z0-9 ] + ) /g ; var source = '常に最新、最高のモバイル。Androidを開発した同じチームから。 ' ; var result = source.split ( keywords ) ; var keywords = @ '' / ( \ & nbsp ; | [ a-zA-Z0-9 ] +\ . [ a-z ] { 2 , } | [ 一-龠々〆ヵヶゝ ] +| [ ぁ-んゝ ] +| [ ァ-ヴー ] +| [ a-zA-Z0-9 ] +| [ a-zA-Z0-9 ] + ) /g '' ; var source = @ '' 常に最新、最高のモバイル。Androidを開発した同じチームから。 '' ; var result = Regex.Split ( source , keywords ) ; | C # Regex.Split is working differently than JavaScript |
C_sharp : Just curious , is changing the size of a struct/value type a breaking change in C # ? Structs tend to be more sensitive in terms of memory layout since altering them directly affects the size of arrays/other structs . Are there any examples of code that breaks , either binary-wise or source-wise , after the layout of a struct in a library it uses is changed ? NOTE : By `` breaks , '' I mean it fails to compile at all or the IL is invalidated . So for example I would n't consider this a breaking change : because it still runs . <code> // My.Library v1public struct MyStruct { } // My.Library v2public struct MyStruct { int _field ; } // App codeusing My.Library ; using System.Runtime.InteropServices ; Console.WriteLine ( Marshal.SizeOf < MyStruct > ( ) ) ; // before printed 1 , now prints 4 | Is changing the size of a struct a breaking change in C # ? |
C_sharp : I have a string : Apple1231|C : \asfae\drqw\qwer|2342|1.txtI have the following code : What I want to be able to do is replace every | after the first | with \So i want to write out Apple1231|C : \asfae\drqw\qwer\2342\1.txt <code> Regex line2parse = Regex.Match ( line , @ '' ( \| ) ( \| ) ( \| ) ( \d ) '' ) ; if ( line2parse < 2 ) { File.AppendAllText ( workingdirform2 + `` configuration.txt '' , | C # Regex replace help |
C_sharp : I have the following statement : I want to check and see if card.Details is null or empty ... if not , write the value . Is there any syntax that allows me to leave out the else conditional ? <code> serverCard.Details = ! String.IsNullOrEmpty ( card.Details ) ? card.Details : serverCard.Details ; | How to simplify this C # if/else syntax |
C_sharp : I 've read a fair amount of posts on the subject , and I think I finally understand how the volatile keyword works in C # . Still I wanted to ask here just to make sure I understand the concepts properly . Consider the following code : From what I understand , if another thread were to set Enabled=false , the original thread may not actually see this change right away ( or perhaps ever ? ) . To make sure the compiler does n't optimize access to the Enabled property and rely on cached values , changing the code as follows should fix things.Now whenever the Enabled value is read , it is guaranteed to get its most current value , correct ? If so , I should be able to use it as a simple signal or flag ( like I have above ) .As another example , consider the following : For simple inter-thread communication like this , is volatile satisfactory here ? I understand that i++ is n't an atomic operation , but if one thread is doing all the incrementing and another simply wants to read it to see if it reaches a certain threshold , we 're okay right ? Edit : I course I found another similar question with detailed answers after the fact . <code> class ThreadWrapper { public bool Enabled { get ; set ; } private void ThreadMethod ( ) { while ( Enabled ) { // ... Do work } } } public bool Enabled { get { return mEnabled ; } set { mEnabled=value ; } } private volatile bool mEnabled ; class C { private volatile int i ; private volatile bool enabledA ; private volatile bool enabledB ; void ThreadA ( ) { i = 0 ; // Reset counter while ( enabledA ) { // .. Do some other repeated work if ( i > 100 ) { // .. Handle threshold case } } } void ThreadB ( ) { while ( enabledB ) { // .. Do work if ( condition ) // Some condition occurs that we want to count { i++ ; } } } } | Using volatile for one-way communication between threads in .NET |
C_sharp : I have been looking in to you some code was n't working . Everything looks fine except for the following line.Before that line is executed Transport is null . I see the GetMock executed and that it returns a non null object . After that line Transport is still null ; I looked at the IL that was generated an it looks fine to me . We see the function get called and stfld should take the return value and set the field.So I then looked at the assembly I see the call get made but it looks like the return in RAX gets blown away by the next call and is lost . if I use an if statement or a ? : operator everyting works fine . Visual Studio 2013 EDITI have create a psudo minimal reproduction . If you set a breakpoint on the indicated line and look at the value of MyA in the debugger it will still be null ( only if building in x64 ) . if you execute the next line it will set the value . I have not been able to reproduce the assessment not happening at all . Its very clear in the disassembly the execution for the next line has begun before the assignment takes place.Edit 2Here is a link to the ms connect site <code> Transport = Transport ? ? MockITransportUtil.GetMock ( true ) ; IL_0002 : ldarg.0 IL_0003 : ldfld class [ Moq ] Moq.Mock ` 1 < class [ CommLibNet ] CommLibNET.ITransport > Curex.Services.Common.UnitTests.Messaging.TestIGuaranteedSubscriptionBase : :Transport IL_0008 : dup IL_0009 : brtrue.s IL_0012 IL_000b : pop IL_000c : ldc.i4.1 IL_000d : call class [ Moq ] Moq.Mock ` 1 < class [ CommLibNet ] CommLibNET.ITransport > Curex.Services.Common.UnitTests.Mocking.MockITransportUtil : :GetMock ( bool ) IL_0012 : stfld class [ Moq ] Moq.Mock ` 1 < class [ CommLibNet ] CommLibNET.ITransport > Curex.Services.Common.UnitTests.Messaging.TestIGuaranteedSubscriptionBase : :Transport Transport = Transport ? ? MockITransportUtil.GetMock ( true ) ; 000007FE9236F776 mov rax , qword ptr [ rbp+0B0h ] 000007FE9236F77D mov rax , qword ptr [ rax+20h ] 000007FE9236F781 mov qword ptr [ rbp+20h ] , rax 000007FE9236F785 mov rcx , qword ptr [ rbp+20h ] 000007FE9236F789 mov rax , qword ptr [ rbp+0B0h ] 000007FE9236F790 mov qword ptr [ rbp+28h ] , rax 000007FE9236F794 test rcx , rcx 000007FE9236F797 jne 000007FE9236F7AC 000007FE9236F799 mov cl,1 000007FE9236F79B call 000007FE92290608 //var x = ReferenceEquals ( null , Transport ) ? MockITransportUtil.GetMock ( true ) : Transport ; ListerFactory = ListerFactory ? ? MockIListenerUtil.GetMockSetupWithAction ( ( a ) = > invokingAction = a ) ; 000007FE9236F7A0 mov qword ptr [ rbp+30h ] , rax 000007FE9236F7A4 mov rax , qword ptr [ rbp+30h ] 000007FE9236F7A8 mov qword ptr [ rbp+20h ] , rax 000007FE9236F7AC mov rcx , qword ptr [ rbp+28h ] class simple { public A MyA = null ; public B MyB = null ; public void SetUp ( ) { MyA = MyA ? ? new A ( ) ; MyB = new B ( ) ; // Put breakpoint here } } | Is the JIT generating the wrong code |
C_sharp : I have an abstract class called EntityTypeTransform with a single abstract method designed to hold a Func delegate that converts an IDataRecord into an instance of T.An implementation of that class might look like ( does look like ) this : Now I want to keep an instance of each of these classes in a generic Dictionary , something like : But this does n't work because ( for example ) an instance of EntityTypeTransform Of Task is not the same as an instance of EntityTypeTransform Of TaskParameter.Can anyone help me out ? Edit : I should add that the Type key = typeof ( T ) <code> public abstract class EntityTypeTransform < TEntityType > where TEntityType : class { public abstract Func < IDataRecord , TEntityType > GetDataTransform ( ) ; } public class TaskParameterEntityTypeTransform : EntityTypeTransform < TaskParameter > { public override Func < IDataRecord , TaskParameter > GetDataTransform ( ) { return dataRecord = > new TaskParameter ( ) { TaskId = ( int ) dataRecord [ `` task_id '' ] , Name = ( string ) dataRecord [ `` p_name '' ] , Value = ( string ) dataRecord [ `` p_value '' ] } ; } } Dictionary < Type , EntityTypeTransform < T > > | Keep a Dictionary < Type , MyClass < T > > where elements are referenceable by type |
C_sharp : Is there a make_tuple equivalent for C # /.NET ? I want to do something like thisC # seems to support it when i create my own functionBut msdn tuple shows not using itIs there or is n't there ? I can use 4.5 <code> mylist.Add ( new Tuple < string , int > ( `` '' , 1 ) ) ; Tuple < T , U > make_tuple < T , U > ( T t , U u ) { return new Tuple < T , U > ( t , u ) ; } ... var a = make_tuple ( 1 , `` '' ) ; //compiles ! Tuple < string , Nullable < int > > [ ] scores = { new Tuple < string , Nullable < int > > ( `` Jack '' , 78 ) , new Tuple < string , Nullable < int > > ( `` Abbey '' , 92 ) , ... | Is there a make_tuple for C # ? |
C_sharp : I have this string : '' B82V16814133260 '' what would be the most efficient way to get two strings out of it : left part String : `` B82V '' rigth part string : `` 16814133260 '' The rule is this : take all numbers on the right side and create string out of them , then take the reminder and place it into another string.This is my solution , but it is too bulky ! How to do it short and efficient ? <code> String leftString = `` '' ; String rightString= '' '' ; foreach ( char A in textBox13.Text.Reverse ( ) ) { if ( Char.IsNumber ( A ) ) { rightString += A ; } else { break ; } } char [ ] arr = rightString.ToArray ( ) ; Array.Reverse ( arr ) ; rightString=new string ( arr ) ; leftString = textBox13.Text.Replace ( rightString , `` '' ) ; | the most efficient way to separate string |
C_sharp : String interpolation is great and snippets are great , but they do n't play nice together . I have a snippet that looks ( in part ) like this : The locationfield part is supposed to be the replacement , but of course it will see as ' '' { e [ `` being a replacement . So when you try to use the snippet , that part is messed up : And the rest of the code following is gone ( because it ca n't match another $ presumably ) .Is there a way around that ? Or can you just not use string interpolation in your snippets ? <code> job.Location = $ '' { e [ `` $ locationfield $ '' ] } '' ; return true ; job.Location = locationfield | How to escape string interpolation in snippet |
C_sharp : Here 's a simple application that prints the method signature of a MethodCallExpression : I would expect the program to print out : But it instead prints out : When getting the Method property for the inherited MethodCallExpression , it always returns As MethodInfo ( the root class ) .However , in Visual Studio and I `` Go To Definition '' of each of the Foo ( ) calls , I 'm taken to each of the overridden methods as expected.Why does the MethodCallExpression.Method behave this way ? Is there anything in the spec about this ? Why is there a discrepancy between VS and the Method property ? I 've tested with .NET 4.0 and 4.5 . <code> using System ; using System.Linq ; using System.Linq.Expressions ; class A { public virtual void Foo ( ) { } } class B : A { public override void Foo ( ) { } } class C : B { public override void Foo ( ) { } } class Program { static void Main ( string [ ] args ) { PrintMethod < A > ( a = > a.Foo ( ) ) ; PrintMethod < B > ( b = > b.Foo ( ) ) ; PrintMethod < C > ( c = > c.Foo ( ) ) ; Console.Read ( ) ; } static void PrintMethod < T > ( Expression < Action < T > > expression ) { var body = ( MethodCallExpression ) expression.Body ; var method1 = body.Method ; var method2 = typeof ( T ) .GetMethod ( body.Method.Name , body.Method.GetParameters ( ) .Select ( p = > p.ParameterType ) .ToArray ( ) ) ; Console.WriteLine ( `` body.Method - > `` + method1.DeclaringType.ToString ( ) + `` - `` + method1.ToString ( ) ) ; Console.WriteLine ( `` typeof ( T ) .GetMethod - > `` + method2.DeclaringType.ToString ( ) + `` - `` + method2.ToString ( ) ) ; } } body.Method - > A - Void Foo ( ) typeof ( T ) .GetMethod - > A - Void Foo ( ) body.Method - > B - Void Foo ( ) *typeof ( T ) .GetMethod - > B - Void Foo ( ) body.Method - > C - Void Foo ( ) *typeof ( T ) .GetMethod - > C - Void Foo ( ) body.Method - > A - Void Foo ( ) typeof ( T ) .GetMethod - > A - Void Foo ( ) body.Method - > A - Void Foo ( ) *typeof ( T ) .GetMethod - > B - Void Foo ( ) body.Method - > A - Void Foo ( ) *typeof ( T ) .GetMethod - > C - Void Foo ( ) | MethodCallExpression.Method always returns the root base class 's MethodInfo |
C_sharp : I noticed most of the developers are using event for callback and I 'm not sure whether I 'm doing in a right way.I noticed most of developers ' codes look like this : While the way I do `` event '' look like this : I hope someone could explain to me what 's the differences between both codes ? Which way of doing delegate is a better practice ? Is it better to set it as a static ? <code> public delegate void SampleDelegate ( ) ; public static event SampleDelegate SampleEvent ; public delegate void SampleDelegate ( ) ; public SampleDelegate SampleEvent ; // notice that I did n't set to static and not an event type | Which is the correct/better way of Delegate declaration |
C_sharp : I 'm trying to insert some data into my DB ( Microsoft SQL Server ) My connection does not open and I get this message : Can not open database \ '' [ Sales and Inventory System ] \ '' requested by the login . The login failed.\r\nLogin failed for user 'Mostafa-PC\Mostafa'.here is my code : I 've done everything and I 've searched everywhere . I can not figure out why . <code> public void InsertProduct ( List < string > _myName , List < int > _myAmount , List < int > _myPrice , string _date ) { string connectionString = @ '' Data Source=MOSTAFA-PC ; Initial Catalog= [ Sales and Inventory System ] ; Integrated Security=True '' ; string query = @ '' INSERT INTO dbo.product ( Name , Amount , Price , [ date ] ) VALUES ( @ Name , @ Amount , @ Price , @ Date ) ; '' ; using ( SqlConnection Con = new SqlConnection ( connectionString ) ) using ( SqlCommand Cmd = new SqlCommand ( query , Con ) ) { Cmd.Parameters.Add ( `` @ Name '' , SqlDbType.NVarChar ) ; Cmd.Parameters.Add ( `` @ Amount '' , SqlDbType.Int ) ; Cmd.Parameters.Add ( `` @ Price '' , SqlDbType.Int ) ; Cmd.Parameters.Add ( `` @ Date '' , SqlDbType.DateTime ) .Value = Convert.ToDateTime ( _date ) ; Cmd.Connection = Con ; Con.Open ( ) ; int recordsToAdd = _myName.Count ( ) ; for ( int x = 0 ; x < recordsToAdd ; x++ ) { Cmd.Parameters [ `` @ Name '' ] .Value = _myName [ x ] ; Cmd.Parameters [ `` @ Amount '' ] .Value = _myAmount [ x ] ; Cmd.Parameters [ `` @ Price '' ] .Value = _myPrice [ x ] ; Cmd.ExecuteNonQuery ( ) ; } } | can not open database - requested by the login - why ca n't I connect to my DB ? |
C_sharp : The following code is very repetitive : However , my attempt to use generics does not compile : The error message is as follows : Error 2 Operator '- ' can not be applied to operands of type 'T ' and 'T ' C : \Git ... \LinearInterpolator.cs How should I reuse my code ? Edit : fast runtime is important for this modules . <code> public static double Interpolate ( double x1 , double y1 , double x2 , double y2 , double x ) { return y1 + ( x - x1 ) * ( y2 - y1 ) / ( x2 - x1 ) ; } public static decimal Interpolate ( decimal x1 , decimal y1 , decimal x2 , decimal y2 , decimal x ) { return y1 + ( x - x1 ) * ( y2 - y1 ) / ( x2 - x1 ) ; } public static T Interpolate < T > ( T x1 , T y1 , T x2 , T y2 , T x ) { return y1 + ( x - x1 ) * ( y2 - y1 ) / ( x2 - x1 ) ; } | How to use generics to develop code that works for doubles and decimals |
C_sharp : Could someone explain to me why this piece of code is doing well when I execute it on a x86 platform and why it fail on x64 ? Results : x86 Debug : 12345678910x64 Debug : 12345678910x86 Release : 12345678910x64 Release : 1111111111If I change something , like removing one of the unused variables , or if I remove the useless for-loop after p_lFirstId++ , the strange behavior disappear.I found that changing `` pdb-only '' to `` full '' in my release configuration , it 's work again.If you run the code directly from visual studio , it 's doing well too.Is this a JIT Compiler bug ? Thank you in advance . <code> class Program { static void Main ( string [ ] args ) { Test ( null , null , null , 0 , 1 ) ; } public static void Test ( List < string > liste , List < string > unused1 , string unused2 , int unused3 , long p_lFirstId ) { liste = new List < string > ( ) ; StringBuilder sbSql = new StringBuilder ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { sbSql.Append ( p_lFirstId ) ; p_lFirstId++ ; foreach ( string sColonne in liste ) { } } System.Console.WriteLine ( sbSql.ToString ( ) ) ; } } | Variable is not incrementing in C # Release x64 |
C_sharp : Everybody knows that asynchrony gives you `` better throughput '' , `` scalability '' , and more efficient in terms of resources consumption . I also thought this ( simplistic ) way before doing an experiment below . It basically tells that if we take into account all the overhead for asynchronous code and compare it against properly configured synchronous code it yields little to no performance/throughput/resource consumption advantages.The question : Does asynchronous code actually perform so much better comparing to the synchronous code with correctly configured thread pool ? May be my performance tests are flawed in some dramatic way ? Test setup : Two ASP.NET Web API methods with JMeter trying to call them with 200 threads thread group ( 30 seconds rump up time ) .Here is response time ( log scale ) . Notice how synchronous code becomes faster when Thread Pool injected enough threads . If we were to set up Thread Pool beforehand ( via SetMinThreads ) it would outperform async right from the start.What about resources consumption you would ask . `` Thread has big cost in terms of CPU time scheduling , context switching and RAM footprint '' . Not so fast . Threads scheduling and context switching is efficient . As far as the stack usage goes thread does not instantly consume the RAM , but rather just reserve virtual address space and commit only a tiny fraction which is actually needed.Let 's look at what the data says . Even with bigger amount threads sync version has smaller memory footprint ( working set which maps into the physical memory ) .UPDATE . I want to post the results of follow-up experiment which should be more representational since avoids some biases of the first one.First of all , the results of the first experiment are taken using IIS Express , which is basically dev time server , so I needed to move away from that . Also , considering the feedback I 've isolated load generation machine from the server ( two Azure VMs in the same network ) . I 've also discovered that some IIS threading limits are from hard to impossible to violate and ended up switching to ASP.NET WebAPI self-hosting to eliminate IIS from the variables as well . Note that memory footprints/CPU times are radically different with this test , please do not compare numbers across the different test runs as setups are totally different ( hosting , hardware , machines setup ) . Additionally , when I moved to another machines and another hosting solution the Thread Pool strategy changed ( it is dynamic ) and injection rate increased.Settings : Delay 100ms , 200 JMeter `` users '' , 30 sec ramp-up time.I want to conclude these experiments with the following : Yes , under some specific ( more laboratory like ) circumstances it 's possible to get comparable results for sync vs. async , but in real world cases where workload can not be 100 % predictable and workload is uneven we inevitably will hit some kind of threading limits : either server side limits , or Thread Pool grow limits ( and bear in mind that thread pool management is automatic mechanism with not always easily predictable properties ) . Additionally , sync version does have a bigger memory footprint ( both working set , and way bigger virtual memory size ) . As far as CPU consumption is concerned async also wins ( CPU time per request metric ) .On IIS with default settings the situation is even more dramatic : synchronous version is order ( s ) of magnitude slower ( and smaller throughput ) due to quite tight limit on threads count - 20 per CPU.PS . Do use asynchronous pipelines for IO ! [ ... sigh of relief ... ] <code> [ HttpGet ] [ Route ( `` async '' ) ] public async Task < string > AsyncTest ( ) { await Task.Delay ( _delayMs ) ; return `` ok '' ; } [ HttpGet ] [ Route ( `` sync '' ) ] public string SyncTest ( ) { Thread.Sleep ( _delayMs ) ; return `` ok '' ; } | Does asynchronous model really give benefits in throughput against properly configured synchronous ? |
C_sharp : I have a Window with few controls on it . One of them is a DataGrid . I want to implement some non-default focus traversal . Namely : DataGrid is a single stop as a whole , not each row.When DataGrid is focused , user can navigate through rows using up and down keys.Navigating through columns using left and right keys is not allowed.First column ( and the only relevant for navigation ) is of type DataGridHyperlinkColumn . When user hits Space or Enter key , it executes the hyperlink.At the moment I have the following code : Unfortunately , it does not reach my expectations.Could you , please , explain how to achieve this ? <code> < DataGrid x : Name= '' DocumentTemplatesGrid '' Grid.Row= '' 2 '' ItemsSource= '' { Binding Source= { StaticResource DocumentTemplatesView } } '' IsReadOnly= '' True '' AutoGenerateColumns= '' False '' SelectionUnit= '' FullRow '' SelectionMode= '' Single '' TabIndex= '' 1 '' IsTabStop= '' True '' > < DataGrid.CellStyle > < Style TargetType= '' DataGridCell '' > < Setter Property= '' IsTabStop '' Value= '' False '' / > < /Style > < /DataGrid.CellStyle > < DataGrid.RowStyle > < Style TargetType= '' DataGridRow '' > < Setter Property= '' IsTabStop '' Value= '' False '' / > < /Style > < /DataGrid.RowStyle > < DataGrid.Columns > < DataGridHyperlinkColumn Header= '' Name '' Width= '' 2* '' Binding= '' { Binding Name } '' / > < DataGridTextColumn Header= '' Description '' Width= '' 5* '' Binding= '' { Binding Description } '' / > < DataGridTextColumn Header= '' Type '' Width= '' * '' Binding= '' { Binding Type } '' / > < /DataGrid.Columns > < /DataGrid > | How to make DataGrid a single stop as a whole on focus traversal with arrow keys row selection ? |
C_sharp : I 'm creating project in ASP.NET ( Framework 4.0 ) . I have used Asp LinkButton in Master Page & it has 2 page linked with it ( Home.aspx & service.aspx ) .Question As follows : That LinkButton1 works on Home.aspx and does n't work on service.aspx.User.master code as followUser.master.cs code for LinkButton1 ClickWhile inspect element ( using Chrome Browser ) on Home.aspx page i found below codeand while on service.aspx ( Chrome Browser inspect element ) Why their is difference between Home.aspx & service.aspx ( while inspect element through chrome browser ) ? <code> < ul class= '' nav navbar-nav navbar-right '' > < li > < asp : LinkButton ID= '' LinkButton1 '' runat= '' server '' onclick= '' LinkButton1_Click '' AutoPostBack= '' true '' > Signout < i class= '' glyphicon glyphicon-off '' > < /i > < /asp : LinkButton > < /li > < li class= '' dropdown '' > < a href= '' # '' class= '' dropdown-toggle '' data-toggle= '' dropdown '' > < span > < asp : Label ID= '' lblName '' runat= '' server '' Text= '' '' > < /asp : Label > < /span > < i class= '' icon-user fa '' > < /i > < i class= '' icon-down-open-big fa '' > < /i > < /a > < ul class= '' dropdown-menu user-menu '' > < li class= '' active '' > < a href= '' frmUserHome.aspx '' > < i class= '' icon-home '' > < /i > My Account < /a > < /li > < li > < a href= '' frmUserHome.aspx '' > < i class= '' icon-home '' > < /i > Personal Home < /a > < /li > < li > < a href= '' # '' > < i class= '' icon-hourglass '' > < /i > Pending approval < /a > < /li > < /ul > < /li > < /ul > protected void LinkButton1_Click ( object sender , EventArgs e ) { if ( Request.Cookies [ `` ASP.NET_SessionId '' ] ! = null ) { Response.Cookies [ `` ASP.NET_SessionId '' ] .Value = string.Empty ; Response.Cookies [ `` ASP.NET_SessionId '' ] .Expires = DateTime.Now.AddMonths ( -20 ) ; } FormsAuthentication.SignOut ( ) ; Session.Abandon ( ) ; Response.Redirect ( `` ~/Default.aspx '' ) ; } < li > < a id= '' ctl00_LinkButton1 '' autopostback= '' true '' href= '' javascript : __doPostBack ( 'ctl00 $ LinkButton1 ' , '' ) '' > Signout < i class= '' glyphicon glyphicon-off '' > < /i > < /a > < /li > < li > < a id= '' ctl00_LinkButton1 '' autopostback= '' true '' href='javascript : WebForm_DoPostBackWithOptions ( new WebForm_PostBackOptions ( `` ctl00 $ LinkButton1 '' , `` '' , true , `` '' , `` '' , false , true ) ) ' > Signout < i class= '' glyphicon glyphicon-off '' > < /i > < /a > < /li > | LinkButton on Master Page does n't fire on Second Child Page in ASP.NET |
C_sharp : How to document the classes & properties & functions that are generated automatically using LINQ to SQL DBML ? I managed to provide documentation to the datacontext class by defining the same partial class in another file with < summary > so it wo n't be removed if the DBML got refreshed This would work for table mapping class with one downside is having to manually maintain the separate class for added/removed tables . another thing..I have comments-like-documentation ( author , date and description ) in the stored procedure , should n't be also extracted into the code file as the function 's documentation ? is it acceptable to exclude the DBML form C # documentation and have separate database documentation instead ? <code> /// < summary > /// Linq to SQL datacontext /// < /summary > public partial class LinqDBDataContext { } -- ============================================= -- Author : < Katia Aleid > -- Create date : < 2015-04-01 > -- Description : < Performs search for the users > -- =============================================ALTER PROCEDURE [ dbo ] . [ SearchUsers ] ... . | C # XML documentation of Linq to SQL |
C_sharp : I 'm making a pong game . I 've been using a simple 44 x 44 .png of a red square as my ball while I 've been debugging . The game works fine with this square.When I try to replace the texture with anything other than a square , I do n't see the ball drawn on screen , and I ca n't figure out why . I 'm making my images the exact same size in photoshop , and using either .PNG or .JPG and having the same result , but I ca n't figure it out for the life of me . What do you think could be causing this issue ? I 've left the code for my ball in the text below . My ball 's update and draw methods are being called by the GameplayScreen ( using MS ' GSM sample ) . <code> public class Ball : IGameEntity { # region Fields private Random rand ; // Random var private Texture2D texture ; // Texture for the ball private double direction ; // Directon the ball is traveling in private bool isVisible ; private bool hasHitLeftBat ; // Checked to see if the ball and bat have just collided private bool hasHitRightBat ; // Checked to see if the ball and bat have just collided private Vector2 ballPosition , resetBallPos , oldBallPos ; private Rectangle ballRect ; public float Speed ; private SpriteBatch spriteBatch ; // Spritebatch private bool isBallStopped ; private Vector2 origin ; // Locate the mid-point of the ball public float RotationAngle ; private AIBat rightBat ; // Player 's Bad private Bat leftBat ; // AI Bat private float ballRelativePos ; private Rectangle rectangle3 ; // Used to draw the collison rectangle private Texture2D blank ; // Texture to be drawn on the collision rectangle GameplayScreen gameplayScreen ; // Creates an instance of the GameplayScreen Game1 gameInstance ; // Creates an instance of the Game1 class int selectedStage ; // Pass this into GameplayScreen for selecting easy , medium , or hard # endregion # region Constructors and Destructors /// < summary > /// Constructor for the ball /// < /summary > public Ball ( ContentManager contentManager , Vector2 ScreenSize , Bat bat , AIBat aiBat ) { Speed = 15f ; texture = contentManager.Load < Texture2D > ( @ '' gfx/balls/redBall '' ) ; direction = 0 ; ballRect = new Rectangle ( 0 , 0 , texture.Width /2 , texture.Height /2 ) ; resetBallPos = new Vector2 ( ScreenSize.X / 2 + origin.X , ScreenSize.Y / 2 + origin.Y ) ; ballPosition = resetBallPos ; rand = new Random ( ) ; isVisible = true ; origin = new Vector2 ( texture.Width / 2 , texture.Height / 2 ) ; leftBat = bat ; // Creates a new instance of leftBat so that I can access Position.X/Y for LeftBatPatcicles ( ) rightBat = aiBat ; // Creates a new instance of leftBat so that can access Position.X/Y for RightBatPatcicles ( ) gameplayScreen = new GameplayScreen ( null , selectedStage ) ; gameInstance = new Game1 ( ) ; Rectangle rectangle3 = new Rectangle ( ) ; blank = contentManager.Load < Texture2D > ( @ '' gfx/blank '' ) ; // pes = new ParticleEmitterService ( game ) ; } public Ball ( Bat myBat ) { leftBat = myBat ; // this assigns and instantiates the member bat // with myBat which was passed from the constructor } # endregion # region Methods /// < summary > /// Draws the ball on the screen /// < /summary > public void Draw ( SpriteBatch spriteBatch ) { if ( isVisible ) { // Draws the rotaing ball spriteBatch.Draw ( texture , ballPosition , ballRect , Color.White , RotationAngle , origin , .0f , SpriteEffects.None , 0 ) ; spriteBatch.Draw ( blank , rectangle3 , Color.LightCoral ) ; } } /// < summary > /// Updates position of the ball . Used in Update ( ) for GameplayScreen . /// < /summary > public void UpdatePosition ( GameTime gameTime ) { ballRect.X = ( int ) ballPosition.X ; ballRect.Y = ( int ) ballPosition.Y ; oldBallPos.X = ballPosition.X ; oldBallPos.Y = ballPosition.Y ; ballPosition.X += Speed * ( ( float ) Math.Cos ( direction ) ) ; ballPosition.Y += Speed * ( ( float ) Math.Sin ( direction ) ) ; bool collided = CheckWallHit ( ) ; // Stops the issue where ball was oscillating on the ceiling or floor if ( collided ) { ballPosition.X = oldBallPos.X + Speed * ( float ) 1.5 * ( float ) Math.Cos ( direction ) ; ballPosition.Y = oldBallPos.Y + Speed * ( float ) Math.Sin ( direction ) ; } // As long as the ball is to the right of the back , check for an update if ( ballPosition.X > leftBat.BatPosition.X ) { // When the ball and bat collide , draw the rectangle where they intersect BatCollisionRectLeft ( ) ; } // As longas the ball is to the left of the back , check for an update if ( ballPosition.X < rightBat.BatPosition.X ) { // When the ball and bat collide , draw the rectangle where they intersec BatCollisionRectRight ( ) ; } // The time since Update was called last . float elapsed = ( float ) gameTime.ElapsedGameTime.TotalSeconds ; // Rotation for the ball RotationAngle += elapsed ; float circle = MathHelper.Pi * 2 ; RotationAngle = RotationAngle % circle ; // base.Update ( gameTime ) ; gameInstance.update ( ) ; } /// < summary > /// Checks for the current direction of the ball /// < /summary > public double GetDirection ( ) { return direction ; } /// < summary > /// Checks for the current position of the ball /// < /summary > public Vector2 GetPosition ( ) { return ballPosition ; } /// < summary > /// Checks for the current size of the ball ( for the powerups ) /// < /summary > public Rectangle GetSize ( ) { return ballRect ; } /// < summary > /// Checks to see if ball went out of bounds , and triggers warp sfx . Used in GameplayScreen . /// < /summary > public void OutOfBounds ( ) { AudioManager.Instance.PlaySoundEffect ( `` Muzzle_shot '' ) ; } /// < summary > /// Speed for the ball when Speedball powerup is activated /// < /summary > public void PowerupSpeed ( ) { Speed += 20.0f ; } /// < summary > /// Check for where to reset the ball after each point is scored /// < /summary > public void Reset ( bool left ) { if ( left ) { direction = 0 ; } else { direction = Math.PI ; } ballPosition = resetBallPos ; // Resets the ball to the center of the screen isVisible = true ; Speed = 15f ; // Returns the ball back to the default speed , in case the speedBall was active if ( rand.Next ( 2 ) == 0 ) { direction += MathHelper.ToRadians ( rand.Next ( 30 ) ) ; } else { direction -= MathHelper.ToRadians ( rand.Next ( 30 ) ) ; } } /// < summary > /// Shrinks the ball when the ShrinkBall powerup is activated /// < /summary > public void ShrinkBall ( ) { ballRect = new Rectangle ( 0 , 0 , texture.Width / 2 , texture.Height / 2 ) ; } /// < summary > /// Stops the ball each time it is reset . Ex : Between points / rounds /// < /summary > public void Stop ( ) { isVisible = true ; Speed = 0 ; isBallStopped = true ; } /// < summary > /// Checks for collision with the ceiling or floor . 2*Math.pi = 360 degrees /// < /summary > private bool CheckWallHit ( ) { while ( direction > 2 * Math.PI ) { direction -= 2 * Math.PI ; return true ; } while ( direction < 0 ) { direction += 2 * Math.PI ; return true ; } if ( ballPosition.Y < = 0 || ( ballPosition.Y > resetBallPos.Y * 2 - ballRect.Height ) ) { direction = 2 * Math.PI - direction ; return true ; } return true ; } /// < summary > /// Used to determine the location where the particles will initialize when the ball and bat collide /// < /summary > private void BatCollisionRectLeft ( ) { // For the left bat if ( ballRect.Intersects ( leftBat.batRect ) ) { rectangle3 = Rectangle.Intersect ( ballRect , leftBat.batRect ) ; } } /// < summary > ///Checks for collision of Right Bat /// < /summary > private void BatCollisionRectRight ( ) { // for the right bat if ( ballRect.Intersects ( rightBat.batRect ) ) { rectangle3 = Rectangle.Intersect ( ballRect , rightBat.batRect ) ; ; } } | Can not draw image over than square in XNA |
C_sharp : I have the following ugly code : Is there a way to chain check for null values in C # , so that I do n't have to check each individual level ? <code> if ( msg == null || msg.Content == null || msg.Content.AccountMarketMessage == null || msg.Content.AccountMarketMessage.Account == null || msg.Content.AccountMarketMessage.Account.sObject == null ) return ; | Is there such a thing as a chained NULL check ? |
C_sharp : Why does url decode not get an error when it decodes % 22 . This is a double quote . When a programmer enters a double quote in a string syntactically they must use two double quotes `` '' to represent a double quote.For ExampleOutputIt '' s nice to meet youBut when url decodes a double quotes why does it not break . After the string is passed through the url decoder there is only a single quote `` . Why does this not break the code ? For ExampleOutputIt '' s nice to meet you <code> string myString = `` It\ '' s nice to meet you '' ; console.write ( myString ) ; string myString = `` It % 22s nice to meet you '' ; myString = HttpUtility.UrlDecode ( myString ) ; console.Write ( myString ) ; | What is the logic behind url decoder when using double quotes ? |
C_sharp : I 'm working in a code base which has a lot of first class collections.In order to ease using these collections with LINQ , there is an extension method per collection that looks like : With the accompanying constructors : This winds up being a bunch of boilerplate so I attempted to write a generic IEnumerable < U > .To < T > ( ) so that we would n't have to keep generating these specific ToXCollection ( ) methods.I got as far as : Which has to be called like customCollectionInstance.OrderBy ( i = > i.Property ) .To < CustomCollection , CustomItem > ( ) Is there a way to avoid having to specify the CustomItem type so we can instead use customCollectionInstance.OrderBy ( i = > i.Property ) .To < CustomCollection > ( ) or is this not something that can be done generically ? <code> public static class CustomCollectionExtensions { public static CustomCollection ToCustomCollection ( this IEnumerable < CustomItem > enumerable ) { return new CustomCollection ( enumerable ) ; } } public class CustomCollection : List < CustomItem > { public CustomCollection ( IEnumerable < CustomItem > enumerable ) : base ( enumerable ) { } } public static class GenericCollectionExtensions { public static T To < T , U > ( this IEnumerable < U > enumerable ) where T : ICollection < U > , new ( ) { T collection = new T ( ) ; foreach ( U u in enumerable ) { collection.Add ( u ) ; } return collection ; } } | Generic extension method to convert from one collection to another |
C_sharp : I want to chunk a credit card number ( in my case I always have 16 digits ) into 4 chunks of 4 digits.I 've succeeded doing it via positive look ahead : But I do n't understand why the result is with two padded empty cells : I already know that I can use `` Remove Empty Entries '' flag , But I 'm not after that.However - If I change the regex to ( ? = ( ? : ... . ) + $ ) , then I get this result : QuestionWhy does the regex emit empty cells ? and how can I fix my regex so it produce 4 chunks at first place ( without having to 'trim ' those empty entries ) <code> var s= '' 4581458245834584 '' ; var t=Regex.Split ( s , '' ( ? = ( ? : ... . ) * $ ) '' ) ; Console.WriteLine ( t ) ; | Split credit card number into 4 chunks using Regex lookahead ? |
C_sharp : I usually use many EF Core async methods in my web application like this : As we know , initial number of threads in ThreadPool by default is limited to number of CPU logical cores . Also user requests are handled by threads in ThreadPool . Should I worry about handling user requests or performance issues due to many async calls in my application ? <code> await db.Parents.FirstOrDefaultAsync ( p = > p.Id == id ) ; | Do Entity Framework async methods consume ThreadPool threads ? |
C_sharp : The following code produces a syntax error : However , the following alternatives both work : Why is this so ? ( foo.a ) is an Action ; why ca n't I call it ? <code> class Foo { public Action a = ( ) = > { } ; } void doSomething ( ) { var foo = new Foo ( ) ; ( foo.a ) ( ) ; // error CS1525 : Invalid expression term ' ) ' } foo.a ( ) ; // worksAction a = foo.a ; a ( ) ; // works | Why is it invalid syntax to call an Action member in this way ? |
C_sharp : I have to do a search to return a value , I have to do is the sum of multiplying two fields.I have the following code : It is giving the following error : the variable 'acct ' type 'tem ' is referenced in scope `` , but it is not setHow can i return this value ? <code> internal double TotalRes ( long Id ) { double total = 0 ; Reserve rAlias = null ; var query = Session.QueryOver < Item > ( ) ; query = query.JoinAlias ( e = > e.Reserve , ( ) = > rAlias ) ; query = query.Where ( ( ) = > rAlias.Id == Id ) ; query = query.Select ( Projections.Sum < Item > ( acct = > acct.Ammount * acct.Wight ) ) ; object result = query.UnderlyingCriteria.UniqueResult ( ) ; if ( result ! = null ) total = Convert.ToDouble ( result ) ; return total ; } | Make a multiplication in a SQL |
C_sharp : I 'm trying to write the following method using generics . ( My actual method is more complex than this . ) My goal is to return something like null if the item is not in the dictionary.The problem is that I do n't know what type T is . If T was an integer , for example , then I should return the type T ? . However , if T is a class , then it is already nullable . And I wo n't know this until run time.Can anyone see a clean way to return a special value in this method to indicate the item is invalid ? I 'm open to returning something other than null , but it has to be a special value . ( 0 is not a special value for integers . ) <code> public T ParseDictionaryItem < T > ( string s , Dictionary < string , T > dictionary ) { T result ; if ( dictionary.TryGetValue ( s , out result ) ) return result ; // TODO : Return special value such as null to indicate invalid item } | Returning Null Value for Unknown Type |
C_sharp : I have some code that when called calls a webservice , queries a database and fetches a value from local cache . It then combines the return values from these three actions to produce its result . Rather than perform these actions sequentially I want to perform them asynchronously in parallel . Here 's some dummy/example code : The problem is that the last line throws an error because dbResult is still null when it gets executed . As soon as queryDB.EndInvoke is called the WaitHandle is signalled and execution continues BEFORE the result of queryDB.EndInvoke is assigned to dbResult . Is there a neat/elegant way round this ? Note : I should add that this affects dbResult simply because the queryDB is the last wait handle to be signalled.Update : While I accepted Philip 's answer which is great , following Andrey 's comments , I should add that this also works : <code> var waitHandles = new List < WaitHandle > ( ) ; var wsResult = 0 ; Func < int > callWebService = CallWebService ; var wsAsyncResult = callWebService.BeginInvoke ( res = > { wsResult = callWebService.EndInvoke ( res ) ; } , null ) ; waitHandles.Add ( wsAsyncResult.AsyncWaitHandle ) ; string dbResult = null ; Func < string > queryDB = QueryDB ; var dbAsyncResult = queryDB.BeginInvoke ( res = > { dbResult = queryDB.EndInvoke ( res ) ; } , null ) ; waitHandles.Add ( dbAsyncResult.AsyncWaitHandle ) ; var cacheResult = `` '' ; Func < string > queryLocalCache = QueryLocalCache ; var cacheAsyncResult = queryLocalCache.BeginInvoke ( res = > { cacheResult = queryLocalCache.EndInvoke ( res ) ; } , null ) ; waitHandles.Add ( cacheAsyncResult.AsyncWaitHandle ) ; WaitHandle.WaitAll ( waitHandles.ToArray ( ) ) ; Console.WriteLine ( string.Format ( dbResult , wsResult , cacheResult ) ) ; var waitHandles = new List < WaitHandle > ( ) ; var wsResult = 0 ; Func < int > callWebService = CallWebService ; var wsAsyncResult = callWebService.BeginInvoke ( null , null ) ; waitHandles.Add ( wsAsyncResult.AsyncWaitHandle ) ; string dbResult = null ; Func < string > queryDB = QueryDB ; var dbAsyncResult = queryDB.BeginInvoke ( null , null ) ; waitHandles.Add ( dbAsyncResult.AsyncWaitHandle ) ; var cacheResult = `` '' ; Func < string > queryLocalCache = QueryLocalCache ; var cacheAsyncResult = queryLocalCache.BeginInvoke ( null , null ) ; waitHandles.Add ( cacheAsyncResult.AsyncWaitHandle ) ; WaitHandle.WaitAll ( waitHandles.ToArray ( ) ) ; var wsResult = callWebService.EndInvoke ( wsAsyncResult ) ; var dbResult = queryDB.EndInvoke ( dbAsyncResult ) ; var cacheResult = queryLocalCache.EndInvoke ( cacheAsyncResult ) ; Console.WriteLine ( string.Format ( dbResult , wsResult , cacheResult ) ) ; | c # threading async problem |
C_sharp : I tried to convert the default template for `` Service Fabric Applicatoin '' with `` Actor Service '' from C # to F # . Here is the github repo.I can compile everything but when I deploy it to the local cluster I get System.ArgumentNullException . Does anyoune know what is wrong here ? Here is the stack trace ( it 's in german , sorry ) : <code> bei System.Reflection.Emit.FieldBuilder..ctor ( TypeBuilder typeBuilder , String fieldName , Type type , Type [ ] requiredCustomModifiers , Type [ ] optionalCustomModifiers , FieldAttributes attributes ) bei System.Reflection.Emit.TypeBuilder.DefineFieldNoLock ( String fieldName , Type type , Type [ ] requiredCustomModifiers , Type [ ] optionalCustomModifiers , FieldAttributes attributes ) bei System.Reflection.Emit.TypeBuilder.DefineField ( String fieldName , Type type , Type [ ] requiredCustomModifiers , Type [ ] optionalCustomModifiers , FieldAttributes attributes ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.BuildRequestBodyType ( ICodeBuilderNames codeBuilderNames , CodeBuilderContext context , MethodDescription methodDescription ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.Build ( ICodeBuilderNames codeBuilderNames , CodeBuilderContext context , MethodDescription methodDescription ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.MethodBodyTypesBuilder.Build ( InterfaceDescription interfaceDescription ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.CodeBuilder.Microsoft.ServiceFabric.Services.Remoting.Builder.ICodeBuilder.GetOrBuildMethodBodyTypes ( Type interfaceType ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.MethodDispatcherBuilder ` 1.Build ( InterfaceDescription interfaceDescription ) bei Microsoft.ServiceFabric.Services.Remoting.Builder.CodeBuilder.Microsoft.ServiceFabric.Services.Remoting.Builder.ICodeBuilder.GetOrBuilderMethodDispatcher ( Type interfaceType ) bei Microsoft.ServiceFabric.Actors.Remoting.Builder.ActorCodeBuilder.GetOrCreateMethodDispatcher ( Type actorInterfaceType ) bei Microsoft.ServiceFabric.Actors.Remoting.Runtime.ActorMethodDispatcherMap..ctor ( ActorTypeInformation actorTypeInformation ) bei Microsoft.ServiceFabric.Actors.Runtime.ActorRuntime. < RegisterActorAsync > d__7 ` 1.MoveNext ( ) -- - Ende der Stapelüberwachung vom vorhergehenden Ort , an dem die Ausnahme ausgelöst wurde -- -bei System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) bei System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) bei System.Runtime.CompilerServices.TaskAwaiter.GetResult ( ) bei Program.main ( String [ ] argv ) in C : \Users\tomas\Projects\playground\MyServiceFabricApp\MyActor\Program.fs : Zeile 18 . | Service Fabric with F # not working |
C_sharp : I have a class containing a collection of items . For convenience I 've provided GetCurrentItem which is implemented bywhich will throw an exception if there are no items in the list . Should I let the exception be thrown or should I return null ? If this was an API I handed to you , what would you expect ? The exception or null ? Is there a better way to handle this ? <code> public Type GetCurrentItem { get { return this.items [ this.items.Count - 1 ] ; } } | Creating property which may throw IndexOutOfRangeException |
C_sharp : I 'm sure I 've seen this in various exception messages in the framework . I checked the following pages from the MSDN library but could not find much guidance for the message contents : Exception ThrowingError Message DesignException.Message PropertyThe only part in the first page that could explain it is this text : Do not disclose security-sensitive information in exception messages without demanding appropriate permissions.It 's the the ArgumentException thrown by Dictionary < TKey , TValue > .Add method that reminded me of this issue . It looks like this : Why does it not look something like this ? This assumes 123 is the TKey value , basically any format with the TKey value is what I would thing would be useful to track down an error while debugging.Is there a known reason why this is not included ? Would it be considered bad practice to re-thrown the argument exception with the key in the message ? I had considered making my own exception subclass but I think this is a case where using a built in exception class seems like a better option . <code> System.ArgumentException : An item with the same key has already been added . System.ArgumentException : An item with the same key ( 123 ) has already been added . | Why do built in exception messages tend to not have specific details ? ( e.g . key from a dictionary ) |
C_sharp : Code contracts simply treats Tasks as it would with any other variable , instead of waiting for the result asynchronously . So , the following scenario will not work , and cause a Contracts exception since at the time the method returns , its an incomplete task , and the results would n't be set at that point in time . Is there any reasonable workaround for the following scenario ? Any suggestions would be appreciated . : ) I 'd rather not break the contract patterns . <code> public Task LoadAppModel ( ) { Contract.Ensures ( app.User ! = null ) ; Contract.Ensures ( app.Security ! = null ) ; Contract.Ensures ( app.LocalSettings ! = null ) ; return Task.WhenAll ( store.GetUserAsync ( ) .ContinueWith ( t = > { app.User = t.Result ; } ) , store.GetSecurityAsync ( ) .ContinueWith ( t = > { app.Security = t.Result ; } ) , store.GetLocalSettingsAsync ( ) .ContinueWith ( t = > { app.LocalSettings = t.Result ; } ) ) ; } | Code Contracts and Tasks |
C_sharp : I have wrote the following code : resharper shows me a warning : Possible duplicate enumeration of IEnumerableWhat does this mean ? Why is this a warning ? <code> IEnumerable < string > blackListCountriesCodes = pair.Criterion.CountriesExceptions.Select ( countryItem = > countryItem.CountryCode ) ; IEnumerable < string > whiteListCountriesCodes = pair.Criterion.Countries.Select ( countryItem = > countryItem.CountryCode ) ; return ( ! blackListCountriesCodes.Contains ( Consts.ALL.ToString ( ) ) & & ! blackListCountriesCodes.Contains ( country ) & & ( whiteListCountriesCodes.Contains ( Consts.ALL.ToString ( ) ) || whiteListCountriesCodes.Contains ( country ) ) ) ; | Possible duplicate enumeration of IEnumerable |
C_sharp : I have a class which has been steadily growing over time . It 's called LayoutManager . It started as a way for me to keep track of which dynamically created controls were on my page . So , for instance , I have this : In this way , during the beginning stages of the Page Lifecycle , controls would be re-created and they would add themselves to their respective control 's list . A while later I found myself passing the 'Page ' object between methods . This was for the sole purpose of being able to access controls found on Page . I thought to myself -- well , I already have a Layout Manager , I 'll just treat the static controls in the same way.As such , my Page_Init method now looks like this mess : I 'm looking at that and saying no , no , no . That is all wrong . Yet , there are controls on my page which are very dependent on each other , but do not have access to each other . This is what seems to make this so necessary.I think a good example of this in practice would be using UpdatePanels . So , for instance , DashboardUpdatePanel is being given to the LayoutManager . There are controls on the page which , conditionally , should cause the entire contents of the dashboard to update.Now , in my eyes , I believe I have two options : Inside the object wanting to call UpdatePanel.Update ( ) , I recurse up through parent objects , checking type and ID until I find the appropriate UpdatePanel.I ask LayoutManager for the UpdatePanel.Clearly the second one sounds cleaner in this scenario ... but I find myself using that same logic in many instances . This has resulted in a manager class which looks like this : Am I on a bad path ? What steps are generally taken at this point ? EDIT1 : I have decided to start down the path of improvement by finding the controls which are least-integrated into LayoutManager and finding ways of breaking them down into separate objects . So , for instance , instead of assigning the HistoricalReportsContainer and CustomReportsContainer objects to LayoutManager ( which is then used in RegenerationManager.RegenerateReportMenu ) I have moved the code to RadListBox `` Load '' event . There , I check the ID of the control which is loading and react accordingly . A strong first improvement , and has removed 2 controls and a method from LayoutManager ! <code> public CormantRadDockZone ( ) { ID = String.Format ( `` RadDockZone_ { 0 } '' , Guid.NewGuid ( ) .ToString ( ) .Replace ( '- ' , ' a ' ) ) ; MinHeight = Unit.Percentage ( 100 ) ; BorderWidth = 0 ; HighlightedCssClass = `` zoneDropOk '' ; CssClass = `` rightRoundedCorners '' ; LayoutManager.Instance.RegisteredDockZones.Add ( this ) ; } protected void Page_Init ( object sender , EventArgs e ) { SessionRepository.Instance.EnsureAuthorized ( ) ; LayoutManager.Instance.RegisteredPanes.Clear ( ) ; LayoutManager.Instance.RegisteredDocks.Clear ( ) ; LayoutManager.Instance.RegisteredDockZones.Clear ( ) ; LayoutManager.Instance.RegisteredSplitters.Clear ( ) ; LayoutManager.Instance.RegisteredSplitBars.Clear ( ) ; LayoutManager.Instance.RegisteredPageViews.Clear ( ) ; LayoutManager.Instance.CheckBox1 = CheckBox1 ; LayoutManager.Instance.CheckBox4 = CheckBox4 ; LayoutManager.Instance.StartEditButton = StartEditButton ; LayoutManager.Instance.FinishEditButton = FinishEditButton ; LayoutManager.Instance.RadNumericTextBox1 = RadNumericTextBox1 ; LayoutManager.Instance.RadNumericTextBox2 = RadNumericTextBox2 ; LayoutManager.Instance.LeftPane = LeftPane ; LayoutManager.Instance.DashboardUpdatePanel = DashboardUpdatePanel ; LayoutManager.Instance.CustomReportsContainer = CustomReportsContainer ; LayoutManager.Instance.HistoricalReportsContainer = HistoricalReportsContainer ; RegenerationManager.Instance.RegenerateReportMenu ( ) ; LayoutManager.Instance.MultiPage = DashboardMultiPage ; LayoutManager.Instance.MultiPageUpdatePanel = MultiPageUpdatePanel ; LayoutManager.Instance.TabStrip = DashboardTabStrip ; RegenerationManager.Instance.RegenerateTabs ( DashboardTabStrip ) ; RegenerationManager.Instance.RegeneratePageViews ( ) ; LayoutManager.Instance.Timer = RefreshAndCycleTimer ; LayoutManager.Instance.Timer.TimerEvent += DashboardTabStrip.DoTimerCycleTick ; RegenerationManager.Instance.RegeneratePageState ( ) ; } public class LayoutManager { private static readonly ILog _logger = LogManager.GetLogger ( MethodBase.GetCurrentMethod ( ) .DeclaringType ) ; private static readonly LayoutManager _instance = new LayoutManager ( ) ; private LayoutManager ( ) { } public static LayoutManager Instance { get { return _instance ; } } private IList < CormantRadDock > _registeredDocks ; private IList < CormantRadDockZone > _registeredDockZones ; private IList < CormantRadPane > _registeredPanes ; private IList < CormantRadSplitter > _registeredSplitters ; private IList < CormantRadSplitBar > _registeredSplitBars ; private Dictionary < string , StyledUpdatePanel > _registeredUpdatePanels ; private IList < CormantRadPageView > _registeredPageViews ; public RadMultiPage MultiPage { get ; set ; } public CormantTimer Timer { get ; set ; } public CormantRadListBox HistoricalReportsContainer { get ; set ; } public CormantRadListBox CustomReportsContainer { get ; set ; } public StyledUpdatePanel MultiPageUpdatePanel { get ; set ; } public CormantRadTabStrip TabStrip { get ; set ; } public RadPane LeftPane { get ; set ; } public StyledUpdatePanel DashboardUpdatePanel { get ; set ; } public RadButton ToggleEditButton { get ; set ; } public CheckBox CheckBox1 { get ; set ; } public CheckBox CheckBox4 { get ; set ; } public RadNumericTextBox RadNumericTextBox1 { get ; set ; } public RadNumericTextBox RadNumericTextBox2 { get ; set ; } public RadButton StartEditButton { get ; set ; } public RadButton FinishEditButton { get ; set ; } public IList < CormantRadDock > RegisteredDocks { get { if ( Equals ( _registeredDocks , null ) ) { _registeredDocks = new List < CormantRadDock > ( ) ; } return _registeredDocks ; } } public IList < CormantRadDockZone > RegisteredDockZones { get { if ( Equals ( _registeredDockZones , null ) ) { _registeredDockZones = new List < CormantRadDockZone > ( ) ; } return _registeredDockZones ; } } public IList < CormantRadPane > RegisteredPanes { get { if ( Equals ( _registeredPanes , null ) ) { _registeredPanes = new List < CormantRadPane > ( ) ; } return _registeredPanes ; } } public IList < CormantRadSplitter > RegisteredSplitters { get { if ( Equals ( _registeredSplitters , null ) ) { _registeredSplitters = new List < CormantRadSplitter > ( ) ; } return _registeredSplitters ; } } public IList < CormantRadSplitBar > RegisteredSplitBars { get { if ( Equals ( _registeredSplitBars , null ) ) { _registeredSplitBars = new List < CormantRadSplitBar > ( ) ; } return _registeredSplitBars ; } } public Dictionary < string , StyledUpdatePanel > RegisteredUpdatePanels { get { if ( Equals ( _registeredUpdatePanels , null ) ) { _registeredUpdatePanels = new Dictionary < string , StyledUpdatePanel > ( ) ; } return _registeredUpdatePanels ; } } public IList < CormantRadPageView > RegisteredPageViews { get { if ( Equals ( _registeredPageViews , null ) ) { _registeredPageViews = new List < CormantRadPageView > ( ) ; } return _registeredPageViews ; } } public StyledUpdatePanel GetBaseUpdatePanel ( ) { string key = MultiPage.PageViews.Cast < CormantRadPageView > ( ) .Where ( pageView = > pageView.Selected ) .First ( ) .ID ; return RegisteredUpdatePanels [ key ] ; } public CormantRadDockZone GetDockZoneByID ( string dockZoneID ) { CormantRadDockZone dockZone = RegisteredDockZones.Where ( registeredZone = > dockZoneID.Contains ( registeredZone.ID ) ) .FirstOrDefault ( ) ; if ( Equals ( dockZone , null ) ) { _logger.ErrorFormat ( `` Did not find dockZone : { 0 } '' , dockZoneID ) ; } else { _logger.DebugFormat ( `` Found dockZone : { 0 } '' , dockZoneID ) ; } return dockZone ; } public CormantRadPane GetPaneByID ( string paneID ) { CormantRadPane pane = RegisteredPanes.Where ( registeredZone = > paneID.Contains ( registeredZone.ID ) ) .FirstOrDefault ( ) ; if ( Equals ( pane , null ) ) { _logger.ErrorFormat ( `` Did not find pane : { 0 } '' , paneID ) ; } else { _logger.DebugFormat ( `` Found pane : { 0 } '' , paneID ) ; } return pane ; } public CormantRadDock GetDockByID ( string dockID ) { CormantRadDock dock = RegisteredDocks.Where ( registeredZone = > dockID.Contains ( registeredZone.ID ) ) .FirstOrDefault ( ) ; if ( Equals ( dock , null ) ) { _logger.ErrorFormat ( `` Did not find dock : { 0 } '' , dockID ) ; } else { _logger.DebugFormat ( `` Found dock : { 0 } '' , dockID ) ; } return dock ; } } | Trying to shy away from a singleton/god/manager class . Not sure how I am supposed to sustain functionality , though |
C_sharp : Few Days back , I faced a test where I was asked to answer the following question : Though it seems basic , I 've some doubt and my own opinionA publication center publishes books . A writer can write many books and a book has a authorThere were four options and among them , I omitted two options that were n't close . So left two options as follows : One Option With List : Another Option With Array : In the same time , I looked into this link to understand about the difference : List Vs ArrayUpon that , Firstly , I chose the first option ( My answer was this ) and believe , List has more functionality and would be a better choice . Another reason is that , I use EF in projects and when work with relationship with tables specifically for One-To-Many , then classes created , has a collection of List like this : Secondly , I was thinking , if arrays could be used for the same , but what I learned array data structure is perfect for fixed data . I hope , I am on the right track . Finally I was unable to understand two things from the link provided:1 ) As a counter - List < T > is one-dimensional ; where-as you have have rectangular ( etc ) arrays like int [ , ] or string [ , , ] - but there are other ways of modelling such data ( if you need ) in an object modelMy views - One dimensional means is List a one-dimensional array or something related.2 ) Little bit confused I mean in what case should we use the following with Array ? Though it explains but need some more clarification : it does a lot of bit-shifting , so a byte [ ] is pretty much essentialfor encoding ; I use a local rolling byte [ ] buffer which I fill before sending down to the underlying stream ( and v.v . ) ; quicker than BufferedStreametc ; it internally uses an array-based model of objects ( Foo [ ] rather than List ) , since the size is fixed once built , and needs to bevery fast . <code> public class Publisher { public int PublisherId { get ; set ; } public string PublisherName { get ; set ; } public string Address { get ; set ; } public List < Author > Authors { get ; set ; } public List < Book > Books { get ; set ; } } public class Author { public int AuthorId { get ; set ; } public string AuthorName { get ; set ; } public string AuthorAddress { get ; set ; } public List < Book > Books { get ; set ; } } public class Book { public int BookId { get ; set ; } public string BookName { get ; set ; } public Author Author { get ; set ; } } public class Publisher { public int PublisherId { get ; set ; } public string PublisherName { get ; set ; } public string Address { get ; set ; } public Author [ ] Authors { get ; set ; } public Book [ ] Books { get ; set ; } } public class Author { public int AuthorId { get ; set ; } public string AuthorName { get ; set ; } public string AuthorAddress { get ; set ; } public Book [ ] Books { get ; set ; } } public class Book { public int BookId { get ; set ; } public string BookName { get ; set ; } public Author Author { get ; set ; } } public List < Book > Books { get ; set ; } | List Vs Array : One-To-Many and Has-A Relationship |
C_sharp : I 've come across the problem regarding asynchronous tasks in a dictionary in a couple programs now , and I ca n't wrap my head around how to solve it.I have an asynchronous task that looks like this : MessageEventArgs is a class from a 3rd party library that I declare statically at the start of my program : The program listens for events in an IRC channel and does actions based on text commands . Rather than have a giant switch statement for each command , I wanted to make a dictionary that matched the string to the method . Not all are simply sending messages , so I ca n't just store the string to send . It looks like this : In Main ( ) , I call : What I 've come to realize is that when the dictionary is instantiated , it tries to call SendMessage , as it is an async task . MessageEventArgs is n't instantiated until after , so it throws an exception . Is there a way to go about storing a reference to these functions in a dictionary ? I found solutions using delegates , but they did n't seem to work with void methods , and async methods ( to my knowledge ) can only return void or Task.Thanks in advance ! <code> MessageEventArgs.Channel.SendMessage ( `` somestring '' ) ; public static MessageEventArgs meargs ; public static Dictionary < string , Task > myDict= new Dictionary < string , Task > ( ) { { `` ! example '' , MessageEventArgs.Channel.SendMessage ( `` HelloWorld '' ) } } MessageReceived += async ( s , e ) = > { meargs = e ; await myDict [ e.Message.Text ] ; } | Referencing asynchronous tasks in a c # dictionary |
C_sharp : I am working on a `` learning program '' and using the Code Rush refactoring tool with my learning . With the latest update of Code Rush it has been recommending implementing IDisposable to my programs . I know what MSDN says about IDisposable and I have a real basic understanding of what it does but because I do n't know all the implications of implementing it I have been ignoring the recommendation . Today I decided to learn more about it and went along with the recommendation . This is what it added to my program.So my questions is this . Does that do everything I need to do to get the advantage of IDisposable or do I need to do something in code to make it work ? I put a break points on that and never reached it through the debugger so either it was not needed or I am not using it the way it was intended . Can someone please shed some light on what this is doing for me or how I should use it so it does do something for me ? <code> class Program : IDisposable { static Service _proxy ; public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } protected virtual void Dispose ( bool disposing ) { if ( disposing ) if ( _proxy ! = null ) { _proxy.Dispose ( ) ; _proxy = null ; } } ~Program ( ) { Dispose ( false ) ; } | What is this IDisposable doing for me ? |
C_sharp : I ca n't understand how to solve the problem that the teacher gave me . Given a number N ( 0 < = N < = 100 ) , find its first digit . For example : It seemed easy at first , but ( as the teacher said ) it should be done using ONLY integer data types ( in other words , using + , - , * , / and % operators ) . Is it even possible to do it this way ? I just ca n't realize how to extract the first digit from a variable-length number without using things like log10 , conditions , `` while '' loop or string conversion . <code> input : 100result : 1input : 46result : 4input : 3result : 3 | Find first digit of a number using ONLY integer operations |
C_sharp : I am unsure of whether what I am doing is completely invalid or merely poor practice , but I have a class , let 's call it Bar , which is a field of some parent class , let 's call Foo , and one of Bar 's methods requires that I pass the instance of the parent Foo as an argument . This seems like a terrible and messy idea , but I ca n't think of a better way to do it . Foo effectively stores a number of List < Bar > , Bar , ConcurrentDictionary < string , Bar > , or similar and is used to allow me to build up all of my Bar instances without a duplication of data.The principle of the code is something like this : I thought about making each List < BarX > ( where X is a number ) a static field of BarX but this does n't work as everything is multithreaded and I would want multiple instances of List < BarX > ; I thought about accessing the parent object using the standard methods but I do n't see how that does n't get messy if I have two parents for one List < BarX > . Any ideas/hints ? I do n't want to move the DoSomething method out of Bar.EDIT FOR DESCRIPTION OF ACTUAL PROBLEM : As mentioned before , Foo functions as a repository of all of the various Bar instances ; all of the Bar instances are interweaved so Bar1 might contain a List < Bar > . One family of Bars , for example List < Bar1 > is prescribed as the program input ; the rest of the BarX Lists , etc etc are then created from this List , as the required , using a wholo load of config files and logic . There are , in total , 9 flavours of Bar , arranged in a non-linear manner e.g . my first Bar1 instance might require a Bar7 instance , which in turn requires another Bar1 instance ( which was n't present in the initial List < Bar1 > ) and so on . Each BarX flavour has a Generate ( ) method which takes the place of DoSomething ( ) to determine how to build it . This arrangement lends itself to thread very nicely , hence the need for a Concurrent place to hold all of these instances , where the basic idea is IfExists , return it and assign to field/List/whatever ; otherwise build it and add it to the ConcurrentDictionary . <code> public class Foo { public List < Bar1 > bar1List { get ; set ; } public List < Bar2 > bar2List { get ; set ; } } public abstract class Bar { //EDITED TO IMPROVE EXAMPLE public int Value { get ; set ; } public void DoSomething ( Foo parentFoo ) { } } public class Bar1 : Bar { public override void DoSomething ( Foo parentFoo ) { //EDITED TO GIVE AN EXAMPLE OF DoSomething ( ) this.Value = this.Value + parentFoo.bar2List [ 0 ] .Value : } } public class Bar2 : Bar { public override void DoSomething ( Foo parentFoo ) { //some other code } } Foo foo = new Foo ( ) //populate foo somehowfoo.bar1List [ 0 ] .DoSomething ( foo ) ; //this is what looks very odd to me and feels kind of like a circular reference . The code will never be circular in that if I want to change bar1List within DoSomething ( ) I will do it by `` this '' , not foo.bar1List . | How to deal with passing a parent object as an argument ? |
C_sharp : So I see that Assert has dozens of methods that seem to do essentially the same thing . Why ? Is it just to be more explicit ? When should the various methods be used ? Is there an offical best practices document ? <code> Assert.IsFalse ( a == b ) ; Assert.IsTrue ( a ! = b ) ; Assert.AreNotEqual ( a , b ) ; | Why does the `` Assert '' class have so many seemingly redundant methods ? When should each be used ? |
C_sharp : I am trying to load some BitmapImages from files held on the file system . I have a dictionary of keys and relative filepaths . Unfortunately the Uri constructor seems non deterministic in the way that it will load the images.Here is my code : Unfortunately sometimes the Uris get loaded as relative file Uris and sometimes they get loaded as relative Pack Uris . There does n't seem to be any rhyme or reason as to which will get loaded which way . Sometimes I get all the Uris loading one way , or just a couple , or most of them , and it will change each time I run the code.Any ideas what is going on here ? <code> foreach ( KeyValuePair < string , string > imageLocation in _imageLocations ) { try { BitmapImage img = new BitmapImage ( ) ; img.BeginInit ( ) ; img.UriSource = new Uri ( @ imageLocation.Value , UriKind.Relative ) ; img.EndInit ( ) ; _images.Add ( imageLocation.Key , img ) ; } catch ( Exception ex ) { logger.Error ( `` Error attempting to load image '' , ex ) ; } } | c # Uri loading non deterministic ? |
C_sharp : I have the following scenario when grouping a collection : where data variable is of type ObservableCollection < Data > When I check forit throws an IndexOutOfRangeExceptionof course this happens because the string split operation throws an exception.The question is : is there a way to check if the result of the grouping is not null and avoiding the exception ? <code> var result = data.GroupBy ( x = > x.Name.Split ( new char [ ] { '- ' } ) [ 1 ] .Trim ( ) ) ; if ( result.Count ( ) > 0 ) | C # IEnumerable.Count ( ) throws IndexOutOfRangeException |
C_sharp : What are the differences between this two methods that seems to do the same thing ? Can it be done even with async/await ? <code> public Task < int > TaskMaxAsync1 ( Task < int > [ ] my_ints ) { return Task.WhenAll ( my_ints ) .ContinueWith ( x = > x.Result.Where ( i = > i % 2 ! = 0 ) .Max ( ) ) ; } public Task < int > TaskMaxAsync2 ( Task < int > [ ] my_ints ) { var numbers = Task.WhenAll ( my_ints ) .Result ; return Task.FromResult ( numbers.Where ( i = > i % 2 ! = 0 ) .Max ( ) ) ; } | C # Differences between Result and ContinueWith |
C_sharp : I have a list of strings which holds file paths . I have another list which holds a subset of files – but it has only the file name ; not the path.Now I need to get files from allFilesWithPathList that is not present in excludeList . Currently I am doing the following , using EXCEPT , after creating another list with file names only.What is the best way in LINQ to get this logic working without introducing another list like the above ? Note : I am using .Net 4.5Complete code <code> List < string > allFilesWithPathList = new List < string > ( ) ; allFilesWithPathList.Add ( @ '' G : \Test\A.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\B.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\C.sql '' ) ; return allFilesWithPathList ; List < string > excludeList = new List < string > ( ) ; excludeList.Add ( `` B.sql '' ) ; List < string > allFileNamesOnlyList = new List < string > ( ) ; foreach ( string fileNameWithPath in allFilesWithPathList ) { //Remove path and get only file name int pos = fileNameWithPath.LastIndexOf ( @ '' \ '' ) + 1 ; string value = fileNameWithPath.Substring ( pos , fileNameWithPath.Length - pos ) ; allFileNamesOnlyList.Add ( value ) ; } //EXCEPT logicList < string > eligibleListToProcess = allFileNamesOnlyList.Except ( excludeList ) .ToList ( ) ; class Program { static void Main ( string [ ] args ) { List < string > allFilesWithPathList = GetAllFilesWithPath ( ) ; List < string > excludeList = new List < string > ( ) ; excludeList.Add ( `` B.sql '' ) ; List < string > allFileNamesOnlyList = new List < string > ( ) ; foreach ( string fileNameWithPath in allFilesWithPathList ) { //Remove path and get only file name int pos = fileNameWithPath.LastIndexOf ( @ '' \ '' ) + 1 ; string value = fileNameWithPath.Substring ( pos , fileNameWithPath.Length - pos ) ; allFileNamesOnlyList.Add ( value ) ; } //EXCEPT logic List < string > eligibleListToProcess = allFileNamesOnlyList.Except ( excludeList ) .ToList ( ) ; //Print all eligible files foreach ( string s in eligibleListToProcess ) { Console.WriteLine ( s ) ; } Console.ReadLine ( ) ; } public static List < string > GetAllFilesWithPath ( ) { List < string > allFilesWithPathList = new List < string > ( ) ; allFilesWithPathList.Add ( @ '' G : \Test\A.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\B.sql '' ) ; allFilesWithPathList.Add ( @ '' G : \Test\C.sql '' ) ; return allFilesWithPathList ; } } | Except with LIKE condition in LINQ |
C_sharp : The reason I am asking is because I wrote an extension method to use in Silverlight only to find out that feature magically started working for silver light . Example Why is there a special System dll in the framework for Silverlight that does the comparsion as case insenstive ? I have run into this for tons of methods , it 's kind of annoying that they either act different or are just missing in general . <code> string sentence = `` I am a sentence that has some words '' ; sentence.Contains ( `` N '' ) ; //would return false , silverlight truesentence.Contains ( `` n '' ) ; //would return true , silverlight true | Is there a reason why System dll is different in Silverlight and other C # Libraries |
C_sharp : In VB you can have this : But in C # , you ca n't do this : Because you get an error `` Keyword 'this ' is not available in the current context '' .I found this question/answer which quotes the C # language specification section 7.6.7:7.6.7 This accessA this-access is permitted only in the block of an instance constructor , an instancemethod , or an instance accessor . ... ( specifics omitted ) ... Use of this in a primary-expression in a context other than the ones listed above is a compile-time error . Inparticular , it is not possible to refer to this in a static method , a static propertyaccessor , or in a variable-initializer of a field declaration.Furthermore , this question covers it ( although , in my option , does not sufficiently answer it ) , and Oblivious Sage 's answer to my question here explains why -- because it 's bug-preventing feature.Why was this feature left out of VB ? <code> Class One Private myTwo As Two = New Two ( Me ) End ClassClass Two Sub New ( withOne As One ) End SubEnd Class class One { private Two myTwo = new Two ( this ) ; } class Two { public Two ( One withOne ) { } } | Why does VB not prevent the use of `` Me '' in field initialization like C # does with `` this '' ? |
C_sharp : I have a HashSet < int > and a List < int > ( Hashset has approximately 3 Million items , List has approximately 300k items ) .I currently intersect them usingand I wonder if there is any faster way to do so . Maybe in parallel ? <code> var intersected = hashset.Intersect ( list ) .ToArray ( ) ; | Fast intersection of HashSet < int > and List < int > |
C_sharp : I have a situation where , for testing , I only want my timer method ( FooMethod ) to run one at a time . In the example below , FooMethod is passed as the delegate to a timer . There are many concrete instances of this class . I thought that by making _locker static , only one instance of FooMethod ( ) would process at a time . But when I run the app , multiple threads are getting past the TryEnter ( ) line at a time.This is how I 'm adding each class to a new timer . This is done , in a loop , for each foo instance : And this is the class that has that method : Note : Normally , _locker is n't static ; I do n't want the same thread entering the method before it got a chance to complete . I changed it to static here for testing.My first thought is that maybe this is n't working because the class is generic ? And that each concrete class is actually its own class and they do n't share the _locker variable ? Is that true ? If that 's true how should I have the concrete classes share a _locker variable ? Do I need to add a static _locker variable to some other class to which the Foos have access ? <code> _timers.Add ( new Timer ( foo.FooMethod , null , 0 , 10000 ) ) ; public class Foo < T > { private static readonly object _locker = new object ( ) ; public void FooMethod ( object stateInfo ) { // Do n't let threads back up ; just get out if ( ! Monitor.TryEnter ( _locker ) ) { return ; } try { // Logic here } finally { Monitor.Exit ( _locker ) ; } } } | Monitor.TryEnter with Generic Class |
C_sharp : I have a ten element array of integers . I want to sum the elements by group , so for instance I want to add the value at element 0 with the value at element 1 , then with the value at element 2 , then 3 , and so on through to element 9 , then add the value at element 1 with the value at 2,3 , through to 9 until every group of 2 values has been added together and stored in a variable . I then want to repeat the process with groups of 3 , groups of 4 , of 5 , all the way through to group of 10 . Each resultant total being stored in a separate variable . Thus far the only way I can figure out how to do it is thus : -The above is an example of summing groups of 4.I was wondering if anyone could be kind enough to show me a less verbose and more elegant way of achieving what I want . Many thanks . <code> int i = 0 ; int p = 1 ; int q = 2 ; int r = 3 ; while ( i < NumArray.Length - 3 ) { while ( p < NumArray.Length - 2 ) { while ( q < NumArray.Length-1 ) { while ( r < NumArray.Length ) { foursRet += NumArray [ i ] + NumArray [ p ] + NumArray [ q ] + NumArray [ r ] ; r++ ; } q++ ; r = q + 1 ; } p++ ; q = p + 1 ; r = q + 1 ; } i++ ; p = i + 1 ; q = i + 2 ; r = i + 3 ; } | Adding elements of an array |
C_sharp : I am testing my run ( ) function to make sure it has all the correct things populated by the end of the method . I populate 4 fields from our databases , two strings , and two IEnumerable ( string ) 's . The idea is to print them all out for all the people I am pulling from the database.When I only print the string fields , everything works fine . However , when I try to add the Enumerables as well , nothing prints at all . I am also printing a counter so I know the program is still running and working . Does Console ever decide to not print anything at all due to space or something else ? Here 's the code that does it : So , as my output , whenever I run the code above , I get an output like this : Problem is , only two people out of the total ( ~425 ) show up , the rest of the lines are just numbers . Should n't I at least get the strings `` Email '' , and `` , correspondence '' ? It seems like Console is just deciding not to do anything . And I know that the code must reach it because it prints out the integer i just before I call that Console.WriteLine ( ) .On the other hand , whenever I just ask for the two string fields to be printed , the Console displays both fields for all 425 users , right after their corresponding integer . Does anyone know what 's happening here ? TIA <code> int i = 0 ; foreach ( Contact contact in Contact.LoadWithPredicate ( getAll ) ) { -- -- -- -other code to populate fields -- -- -- -- - i ++ ; Console.WriteLine ( i ) ; //Turn the Enumerables into strings for printing string firstEnumAsString = String.Join ( `` , `` , firstEnumerable.ToArray ( ) ) ; string secondEnumAsString = String.Join ( `` , `` , secondEnumerable.ToArray ( ) ) ; Console.WriteLine ( `` Email : `` + firstString+ `` , correspondance : `` + secondString+ `` , PAM addresses : `` + firstEnumAsString+ `` , famousPeople : `` + secondEnumAsString ) ; } 12Email : foo @ bar.com , correspondance : John , PAM addresses : bar @ foo.com , famousPeople : foo , bar , foo34etc | Does Console.Write ever fail ? |
C_sharp : ( All of the below are simplified for brevity ) I have a static reference to a processing object.The Processor contains a function to which I can pass an object Package , which is the info to be processed.The Package comes from a list of lots of packages which should be processed . These packages are unqique ; there are not multiple references to the same object here.I start many threads so that I can process the packages in toProcess in parallell . The threads Pop ( ) an available Package from the toProcess stack until the stack is empty.My question is now : Can I risk that package in Check is overwritten by another thread , or will the other thread `` create a copy '' of Check ? <code> static class Program { static Processor processor = new Processor ( ) ; static Stack < Package > toProcess ; static Object sync = new Object ( ) ; static void RunThreads ( ) { toProcess = GetPackages ( ) ; //start many threads using the Work delegate } static void Work ( ) { while ( true ) { Package p ; lock ( sync ) { if ( toProcess.Count == 0 ) break ; p = toProcess.Pop ( ) ; } processor.Check ( p ) ; } } } class Processor { public void Check ( Package package ) { //do many analyses on p and report results of p 's analysis to elsewhere } } class Package { //properties } | Will parameter of a static object 's non-static method be shared from multiple threads ? |
C_sharp : I 'm trying to download a composition media file into my hard drive using the following code : But every time I get an exception with this message : `` The remote server returned an error : ( 302 ) FOUND . `` Note that this method is called after Twilio calls my StatusCallback method which I 've set when creating a new composition using CompositionResource.CreateAsync method . <code> try { var uri = `` https : //video.twilio.com/v1/Compositions/ '' + sid + `` /Media ? Ttl=6000 '' ; var request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; request.Headers.Add ( `` Authorization '' , `` Basic `` + Convert.ToBase64String ( Encoding.ASCII.GetBytes ( _apiKeySid + `` : '' + _apiKeySecret ) ) ) ; request.AllowAutoRedirect = false ; var responseBody = new StreamReader ( request.GetResponse ( ) .GetResponseStream ( ) ) .ReadToEnd ( ) ; var mediaLocation = JsonConvert.DeserializeObject < Dictionary < string , string > > ( responseBody ) [ `` redirect_to '' ] ; new WebClient ( ) .DownloadFile ( mediaLocation , `` D : \\test.mp4 '' ) ; } catch ( Exception ex ) { var temp = ex.Message ; } | C # Twilio retrieve composition media |
C_sharp : I need to analyze some extension method . For example Enumerable.ToList.Code sample to analyze : Diagnostic : However symbolInfo.Symbol is null and there are no any candidates . If I change the code sample like that : then symbolInfo has a candidate but still does n't have Symbol . How to get a symbol info of extension method invocation ? <code> var test = @ '' using System.Linq ; namespace Test { public class TestType { void TestMethod ( ) { var empty = new [ ] { 0 } ; var test = empty.ToList ( ) ; } } } '' ; public override void Initialize ( AnalysisContext context ) { context.RegisterSyntaxNodeAction ( AnalyzeSymbol , SyntaxKind.InvocationExpression ) ; } private static void AnalyzeSymbol ( SyntaxNodeAnalysisContext context ) { var symbolInfo = context.SemanticModel.GetSymbolInfo ( context.Node ) ; } var test = @ '' using System.Linq ; namespace Test { public class TestType { void TestMethod ( ) { var empty = new [ ] { 0 } ; var test = Enumerable.ToList ( empty ) ; } } } '' ; | SymbolInfo of extension method |
C_sharp : Currently in my game i want trying to move my object towards both x axis and y axis.As I also wanted to put it into center , I have put a camera.Here is my Camera code-and in Game1.cs file as usual in begin statement i am putting this-Here ba is the object of ball , its just have moving x and y functionalities.In a separate begin , end statement , I am drawing rest all of the objects-Here Have applied globaltransformation to acheive independent screen resolution ( similar codes like in Camera.cs ) .Rest of the objects are working as expected , But intersections of camera object and rest of the objects is not working as expected.I guess this is due to resolution independency is not applied to Camera object ( I am not sure ) .I have tried lot of codes after searching internet , but none of them is working as expected.In a simple words-I want to clone this game-https : //play.google.com/store/apps/details ? id=com.BitDimensions.BlockyJumpIf you see main player is moving along x and y axis , but due to camera its in constant position , but the obstacles are not in camera , How to acheive the intersection between obejct which is in camera draw and objects which are not in camera in this caseRequest all to help , I am stuck here from long time ... <code> public class Camera { public Matrix transform ; public Viewport view ; public Vector2 origin ; Vector2 baseScreenSize = new Vector2 ( 1136 , 720 ) ; float horScaling ; float verScaling ; Vector3 screenScalingFactor ; public Camera ( Viewport newView ) { view = newView ; horScaling = view.Width / baseScreenSize.X ; verScaling = view.Height / baseScreenSize.Y ; screenScalingFactor = new Vector3 ( horScaling , verScaling , 1 ) ; } public void update ( GameTime gt , ball pl ) { origin = new Vector2 ( pl.Position.X + ( pl.ballRectangle.Width / 2 ) - 400 , 0 ) ; transform = Matrix.CreateScale ( 1,1,0 ) * Matrix.CreateTranslation ( new Vector3 ( -origin.X , -origin.Y , 0 ) ) ; } } spriteBatch.Begin ( SpriteSortMode.Deferred , BlendState.AlphaBlend , null , null , null , null , cm.transform*globalTransformation ) ; ba.Draw ( spriteBatch , Color.White ) ; spriteBatch.End ( ) ; spriteBatch.Begin ( SpriteSortMode.Immediate , null , null , null , null , null , globalTransformation ) ; spriteBatch.Draw ( mainMenu , new Vector2 ( 0 , 0 ) , Color.White ) ; spriteBatch.Draw ( mainMenu1 , new Vector2 ( 450 , 100 ) , Color.White ) ; spriteBatch.End ( ) ; | Need help on monogame screen resolution and intersection |
C_sharp : Hi I see following code : Why using Action and then invoke action here ? Why not just using txtMessage.Text = message to replace the code in function body ? UpdateA fuller version of the code , presented in a comment , reproduced below with syntax highlighting , indentation etc . <code> void UpdateMessage ( string message ) { Action action = ( ) = > txtMessage.Text = message ; this.Invoke ( action ) ; } public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; new Thread ( Work ) .Start ( ) ; } void Work ( ) { Thread.Sleep ( 5000 ) ; UpdateMessage ( `` My Garden '' ) ; } void UpdateMessage ( string message ) { Action action = ( ) = > textBox1.Text = message ; this.Invoke ( action ) ; } } | Why using Action in this code ? |
C_sharp : I can not understand why the above code ( modified from the actual codes ) always gives me weird result : '' ZXCV ) '' instead of `` Tom ( ZXCV ) '' .Does anybody knows the reason behind and can provide a reference if possible ? <code> StringBuilder htmlResp=new StringBuilder ( ) ; int ? cuID= 1 ; string cuName= '' Tom '' ; string cuEmpID= '' ZXCV '' ; htmlResp .Append ( `` < option value=\ '' '' + cuID.Value + `` \ '' > '' + cuName+ '' ( `` +cuEmpID== '' '' ? `` - '' : cuEmpID+ '' ) '' + `` < /option > '' ) ; html.Resp.ToString ( ) ; | Why the following Conditional Operator works strangely in StringBuilder containing Nullable type ? in C # ? |
C_sharp : Why does the compiler reject this code with the following error ? ( I am using VS 2017 with C # 7.3 enabled . ) CS0019 Operator '== ' can not be applied to operands of type 'T ' and 'T'The version without generics is of course perfectly valid . <code> public class GenericTest < T > where T : Enum { public bool Compare ( T a , T b ) { return a == b ; } } public enum A { ONE , TWO , THREE } ; public class Test { public bool Compare ( A a , A b ) { return a == b ; } } | C # Enums and Generics |
C_sharp : Lets forgot about why I need this.Can we create a class with name `` class '' .Below code resulted in compilation error as class is a reserve keyword.so is there any hack or a way to fool C # compiler ? : ) This Question was asked by interviewer in my last interview and he told me it is possible . <code> public class class { } | Can we create class with name `` class '' ? |
C_sharp : I have a multi layered project with a web API project and a library project . Both projects rely on AutoMapper ( and AutoMapper extensions for Microsoft.Extensions.DependencyInjection ) . Based on thishttps : //docs.automapper.org/en/latest/Dependency-injection.html # asp-net-corein the Startup file I 'm setting up AutoMapper for all the layersAs you can see here , the API project needs to know about all the referenced library projects by loading them via name . I would prefer a way that every project is able to register itself . Based on this sample codehttps : //github.com/jasontaylordev/CleanArchitecture/blob/master/src/Application/DependencyInjection.csI created such a file in my library projectand in the API project I can now do thisThe code seems to work fine but AddAutoMapper will be called twice . Once for the API assembly and once for the library assembly . Should I stick to the first approach because AutoMapper should only be added once or is it fine to separate it ? <code> Assembly apiAssembly = Assembly.GetExecutingAssembly ( ) ; Assembly myLibraryAssembly = Assembly.Load ( `` MyLibrary '' ) ; services.AddAutoMapper ( apiAssembly , myLibraryAssembly ) ; public static class DependencyInjection { public static IServiceCollection AddMyLibrary ( this IServiceCollection services ) { Assembly executingAssembly = Assembly.GetExecutingAssembly ( ) ; // MyLibrary assembly services.AddAutoMapper ( executingAssembly ) ; // ... setup other services return services ; } } Assembly executingAssembly = Assembly.GetExecutingAssembly ( ) ; services.AddAutoMapper ( executingAssembly ) ; services.AddMyLibrary ( ) ; | calling AddAutoMapper once per assembly instead of passing in multiple assemblies ? |
C_sharp : I have the following if condition param.days is a string.This works fine , but if I saythen it does not evaluate correctly at runtime . Both statements are not the same in C # .It does say that the value is null but then C # tries to cast it to a bool which is non-nullable.Why did the C # designers choose to do it this way ? Such a statement is valid in C++ , but why is this not considered valid in C # ? <code> if ( param.days ! = null ) If ( param.days ) | Why is n't this allowed in C # ? |
C_sharp : GoalI have a couple of interfaces and some dlls that provide implementations for these interfaces . I want to load the implementation into a new AppDomain ( so I can unload the dll later ) and instatiate the implementation in the new AppDomain and then use a clientside ( here the default AppDomain ) proxy to wrap the actual implementation object . The goal is to create these ClientProxy instances once and change their actual implementations whenever while not loading the implementations assembly into the default AppDomain.ProblemWhen calling a method on the ClientProxy __TransparentProxy object that gets another ClientProxy as argument I get the following Exceptions : System.Runtime.Remoting.RemotingException : 'The argument type 'System.MarshalByRefObject ' can not be converted into parameter type 'IData ' . 'With inner Exception : InvalidCastException : Object must implement IConvertible.When passing the __TransparentProxy obtained directly from the Server AppDomain the ClientProxy works.SetupCloneable from : https : //github.com/mailgerigk/remotingInterfaces : Interface Impl in _impl.dll : Serverside AssemblyLoader : ClientProxy : Main : <code> public interface IData { int Foo { get ; set ; } } public interface ILogic { void Update ( IData data ) ; } public class DataImpl : MarshalByRefObject , IData { public int Foo { get ; set ; } } public class LogicImpl : MarshalByRefObject , ILogic { public void Update ( IData data ) { data.Foo++ ; } } class AssemblyLoader : MarshalByRefObject { public Assembly Assembly { get ; private set ; } public AssemblyLoader ( string assemblyFile ) { Assembly = Assembly.LoadFrom ( assemblyFile ) ; } public object CreateInstance ( string typeName ) { return Activator.CreateInstance ( Assembly.GetType ( typeName ) ) ; } } class ClientProxy : RealProxy { private RealProxy innerProxy ; public ClientProxy ( Type interfaceType , object proxyObject ) : base ( interfaceType ) { SetInnerProxy ( proxyObject ) ; } public void SetInnerProxy ( object proxyObject ) { innerProxy = RemotingServices.GetRealProxy ( proxyObject ) ; } public override IMessage Invoke ( IMessage msg ) { return innerProxy.Invoke ( msg ) ; } } class Program { static void Main ( string [ ] args ) { var app = AppDomain.CreateDomain ( `` ImplDomain '' , null , AppDomain.CurrentDomain.BaseDirectory , AppDomain.CurrentDomain.RelativeSearchPath , true ) ; var assmblyLoader = app.CreateInstanceFromAndUnwrap ( typeof ( AssemblyLoader ) .Assembly.Location , typeof ( AssemblyLoader ) .FullName , false , BindingFlags.CreateInstance , null , new object [ ] { `` _impl.dll '' } , null , null ) as AssemblyLoader ; var dataImpl = assmblyLoader.CreateInstance ( `` DataImpl '' ) as IData ; var logicImpl = assmblyLoader.CreateInstance ( `` LogicImpl '' ) as ILogic ; logicImpl.Update ( dataImpl ) ; // Works Console.WriteLine ( dataImpl.Foo ) ; // prints 1 var clientDataProxy = new ClientProxy ( typeof ( IData ) , dataImpl ) ; var clientDataImpl = clientDataProxy.GetTransparentProxy ( ) as IData ; var clientLogicProxy = new ClientProxy ( typeof ( ILogic ) , logicImpl ) ; var clientLogicImpl = clientLogicProxy.GetTransparentProxy ( ) as ILogic ; clientLogicImpl.Update ( dataImpl ) ; // Works Console.WriteLine ( clientDataImpl.Foo ) ; // prints 2 clientLogicImpl.Update ( clientDataImpl ) ; // throws System.Runtime.Remoting.RemotingException Console.WriteLine ( clientDataImpl.Foo ) ; } } | Wrapping __TransparentProxy of RemotingProxy in another Proxy throws RemotingException |
C_sharp : UPDATE 10:29 MST on 11/7Oddly enough if I move the attribute out of the ComponentModel folder back into the root of the Common project the code works fine . I ca n't imagine what 's possibly referencing the old namespace after all of the references were refactored for the InflowHealth.Common.ComponentModel namespace.It 's almost like there is some reference hiding somewhere that 's not code-based but rather runtime and dynamic , but I sure do n't see it when looking through all find results of InflowHealthErrorContext.UPDATE 19:33 MST on 11/6Of new interest , when I commented out the line to use the custom attribute to inherit routes , and use the default one , it still blew up . Of further interest , the namespace it 's looking for InflowHealth.Common.InflowHealthErrorContextAttribute is actually the old FQN before I refactored it and moved it to a folder ( and namespace ) ComponentModel.UPDATE 07:42 MST on 11/6I believe I 've identified that the issue is related to another custom attribute I 'm using to inherit actions . This attribute is added to the HttpConfiguration like this : The implementation of that attribute is pretty simple : It appears that inheriting this InflowHealthErrorContext attribute is causing issues , but I 'm not sure exactly what the issue is . I 've tried : Removing Inherited = false so that it is inheritable.Removing AllowMultiple = true just because that was misconfigured.Those did not change the error.ORIGINAL POSTI have a very simple attribute in a Common assembly shared by a couple Web API applications . As simple as this is I just ca n't figure out what would cause this exception . I have tried to collect Fusion logs on this , but it 's not logging them.This is the Attribute : This would be used on a route to later provide some extra context to the automated error logging done inside of a filter : Upon loading the application , when Web API Routes are registered , it fails . Here is the line it 's breaking on : It 's throwing this exception : Could not load type 'InflowHealth.Common.InflowHealthErrorContextAttribute ' from assembly 'InflowHealth.Common , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null'.This is the stack trace : <code> public static void MapInheritedAttributeRoutes ( this HttpConfiguration config ) { config.MapHttpAttributeRoutes ( new InheritanceDirectRouteProvider ( ) ) ; } public class InheritanceDirectRouteProvider : DefaultDirectRouteProvider { protected override IReadOnlyList < IDirectRouteFactory > GetActionRouteFactories ( HttpActionDescriptor actionDescriptor ) { return actionDescriptor.GetCustomAttributes < IDirectRouteFactory > ( true ) ; } } using System ; namespace InflowHealth.Common.ComponentModel { [ AttributeUsage ( AttributeTargets.Method , Inherited = false , AllowMultiple = true ) ] public sealed class InflowHealthErrorContextAttribute : Attribute { // This is a positional argument public InflowHealthErrorContextAttribute ( string errorContext ) { ErrorContext = errorContext ; } public string ErrorContext { get ; } } } [ Authorize ( Roles = Roles.ALL_ADMINS ) ] [ Route ( `` api/ControlPanelApi/PayerClassifications '' ) ] [ InflowHealthErrorContext ( `` Error getting payer classifications . `` ) ] public IHttpActionResult GetPayerClassifications ( int clientId , bool showAllRows ) { return Ok ( GetData ( payerClassificationManager , clientId , showAllRows ) ) ; } GlobalConfiguration.Configure ( WebApiConfig.Register ) ; at System.ModuleHandle.ResolveType ( RuntimeModule module , Int32 typeToken , IntPtr* typeInstArgs , Int32 typeInstCount , IntPtr* methodInstArgs , Int32 methodInstCount , ObjectHandleOnStack type ) at System.ModuleHandle.ResolveTypeHandleInternal ( RuntimeModule module , Int32 typeToken , RuntimeTypeHandle [ ] typeInstantiationContext , RuntimeTypeHandle [ ] methodInstantiationContext ) at System.Reflection.RuntimeModule.ResolveType ( Int32 metadataToken , Type [ ] genericTypeArguments , Type [ ] genericMethodArguments ) at System.Reflection.CustomAttribute.FilterCustomAttributeRecord ( CustomAttributeRecord caRecord , MetadataImport scope , Assembly & lastAptcaOkAssembly , RuntimeModule decoratedModule , MetadataToken decoratedToken , RuntimeType attributeFilterType , Boolean mustBeInheritable , Object [ ] attributes , IList derivedAttributes , RuntimeType & attributeType , IRuntimeMethodInfo & ctor , Boolean & ctorHasParameters , Boolean & isVarArg ) at System.Reflection.CustomAttribute.GetCustomAttributes ( RuntimeModule decoratedModule , Int32 decoratedMetadataToken , Int32 pcaCount , RuntimeType attributeFilterType , Boolean mustBeInheritable , IList derivedAttributes , Boolean isDecoratedTargetSecurityTransparent ) at System.Reflection.CustomAttribute.GetCustomAttributes ( RuntimeMethodInfo method , RuntimeType caType , Boolean inherit ) at System.Reflection.RuntimeMethodInfo.GetCustomAttributes ( Type attributeType , Boolean inherit ) at System.Attribute.GetCustomAttributes ( MemberInfo element , Type type , Boolean inherit ) at System.Attribute.GetCustomAttribute ( MemberInfo element , Type attributeType , Boolean inherit ) at System.Reflection.CustomAttributeExtensions.GetCustomAttribute [ T ] ( MemberInfo element ) at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.IsValidActionMethod ( MethodInfo methodInfo ) at System.Array.FindAll [ T ] ( T [ ] array , Predicate ` 1 match ) at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem..ctor ( HttpControllerDescriptor controllerDescriptor ) at System.Web.Http.Controllers.ApiControllerActionSelector.GetInternalSelector ( HttpControllerDescriptor controllerDescriptor ) at System.Web.Http.Controllers.ApiControllerActionSelector.GetActionMapping ( HttpControllerDescriptor controllerDescriptor ) at System.Web.Http.Routing.AttributeRoutingMapper.AddRouteEntries ( SubRouteCollection collector , HttpConfiguration configuration , IInlineConstraintResolver constraintResolver , IDirectRouteProvider directRouteProvider ) at System.Web.Http.Routing.AttributeRoutingMapper. < > c__DisplayClass2. < > c__DisplayClass4. < MapAttributeRoutes > b__1 ( ) at System.Web.Http.Routing.RouteCollectionRoute.EnsureInitialized ( Func ` 1 initializer ) at System.Web.Http.Routing.AttributeRoutingMapper. < > c__DisplayClass2. < MapAttributeRoutes > b__0 ( HttpConfiguration config ) at System.Web.Http.HttpConfiguration.EnsureInitialized ( ) at System.Web.Http.GlobalConfiguration.Configure ( Action ` 1 configurationCallback ) at InflowHealthPortal.MvcApplication.Application_Start ( ) in Global.asax.cs : line 22 | TypeLoadException on Attribute in shared assembly |
C_sharp : I 've always used role authorization in my .net application . However , I 'm building a demo app and want to give claims a try . I 've always decorated my controller like this where either an admin or User with full access can be authorized.However , I ca n't accomplish the same with claims . In my startup , I have these two claims policies . How can I decorate my controller or change these policies to make either claims to be authorize by my controller ? <code> [ [ Authorize ( Roles = `` IsApiUserFullAccess '' , `` IsAdmin '' ) ] ] options.AddPolicy ( `` IsApiUserFullAccess '' , policy = > policy.RequireClaim ( `` apiuser.fullaccess '' , `` true '' ) ) ; options.AddPolicy ( `` IsAdmin '' , policy = > policy.RequireClaim ( `` administrator '' , `` true '' ) ) ; | Is it possible to have a claims authorization with an OR condition like roles ? |
C_sharp : Firstly I need to get all the data from ODBC ( this is working already ) . Then comes the most complicated part that I am not sure yet how it can be done . There are two tables of data in ODBC . I am merging them with my current code and filtering them with certain parameters.Table 1 in database : Table 2 in database : Merged dataTable look like this : However merged output dataTable should look like this ( to have a possibility to work with it further ) : Find duplicates in NAME . Leave only one of them , assign a number from Table 1 to NRO from Table 2 to NRO1 . Table 1 numbers should be in NRO , Table 2 numbers should be in NRO1.After connecting to ODBC I am filling one table with data from Table 1then I am getting data from another Table 2 and merging them by : After that I am performing filtering ( I need to have rows only starting with 4 and 1 in NRO , there are also rows with other starting number ) : Then I am adding one more Column for NRO1 ( this is also adding zeros ( 0 ) I do n't need them in Column NRO1 ) : I can catch duplicates with this codebut how to perform the rest ? This should be performed by a loop with building a new table ? How I can perform joining and removing duplicates to dataTable ? <code> NRO NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR COMPANYN COUNTRY ID ACTIVE123 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1133 Opel Meriva FTG J5 K4 O3 P4 O2 JO 3 1153 MB E200 C25 JN KI OP PY OR JD 5 1183 BMW E64 SE0 JR KE OT PG OL J8 9 1103 Audi S6 700 JP KU OU PN OH J6 11 1 NRO NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR COMPANYN COUNTRY ID ACTIVE423 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1463 BMW E64 SE0 JR KE OT PG OL J8 9 1 NRO NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR COMPANYN COUNTRY ID ACTIVE423 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1463 BMW E64 SE0 JR KE OT PG OL J8 9 1123 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1133 Opel Meriva FTG J5 K4 O3 P4 O2 JO 3 1153 MB E200 C25 JN KI OP PY OR JD 5 1183 BMW E64 SE0 JR KE OT PG OL J8 9 1103 Audi S6 700 JP KU OU PN OH J6 11 1 NRO NRO1 NAME NAMEA NAMEB ADDRESS POSTA POSTN POSTADR COMPANYN COUNTRY ID ACTIVE123 423 Fiat Punto 500 J5 K4 O3 P4 O2 JT 1 1133 Opel Meriva FTG J5 K4 O3 P4 O2 JO 3 1153 MB E200 C25 JN KI OP PY OR JD 5 1183 463 BMW E64 SE0 JR KE OT PG OL J8 9 1103 Audi S6 700 JP KU OU PN OH J6 11 1 DataTable dataTable = new DataTable ( `` COMPANY '' ) ; using ( OdbcConnection dbConnectionSE = new OdbcConnection ( connectionStringSE ) ) { dbConnectionSE.Open ( ) ; OdbcDataAdapter dadapterSE = new OdbcDataAdapter ( ) ; dadapterSE.SelectCommand = new OdbcCommand ( queryStringSE , dbConnectionSE ) ; dadapterSE.Fill ( dataTable ) ; } using ( OdbcConnection dbConnectionFI = new OdbcConnection ( connectionStringFI ) ) { dbConnectionFI.Open ( ) ; OdbcDataAdapter dadapterFI = new OdbcDataAdapter ( ) ; dadapterFI.SelectCommand = new OdbcCommand ( queryStringFI , dbConnectionFI ) ; var newTable = new DataTable ( `` COMPANY '' ) ; dadapterFI.Fill ( newTable ) ; dataTable.Merge ( newTable ) ; } DataTable results = dataTable.Select ( `` ACTIVE = ' 1 ' AND ( NRO Like ' 1 % ' OR NRO Like ' 4 % ' ) '' ) .CopyToDataTable ( ) ; results.Columns.Add ( `` NRO1 '' , typeof ( int ) ) .SetOrdinal ( 1 ) ; foreach ( DataRow row in results.Rows ) { //need to set value to NewColumn column row [ `` NRO1 '' ] = 0 ; // or set it to some other value } var duplicates = results.AsEnumerable ( ) .GroupBy ( r = > r [ 2 ] ) .Where ( gr = > gr.Count ( ) > 1 ) ; | Build one datatable out of two with certain conditions |
C_sharp : QUESTION : How do I apply my personal DocumentationProvider to source tree symbols ? Which is the type of symbol i get when i use the SymbolFinder.FindSymbolAtPosition ( ) Specifically I want to override the GetDocumentationForSymbol ( ) function . I have it overridden for my autocomplete symbols but not the symbols i get from hover over.BACKGROUND : Hi , I am using roslyn to gather intellisense for a text editor i am creating . One of the things i need to make is quick info or tool tips . I have it working for the autocomplete suggestions . by using a snippet that looks like thisthis uses my own personal DotNetDocumentationProvider which parses XML and documentation the way I need it . This works for assembly symbols which are the types of symbols I have when i use Recommender.GetRecommendedSymbolsAtPosition ( ) . EDIT : Just wanted to give more background : ) I get symbols in two different ways . 1 ) One way is when I call I use this when the user asks for auto-complete informationWith these symbols I can go through and for each one call : This eventually calls a function I have overridden from the class DocumentationProvider :2 ) The second way is for when the user hovers over I call the exact same function ( from the same line of code actually , keeping it DRY ) But this does not invoke my overridden GetDocumentationCommentXml ( ) instead the default Roslyn one is called.Thanks ! <code> compilation = CSharpCompilation.Create ( `` MyIntellisense '' , new [ ] { CSharpSyntaxTree.ParseText ( dotNetCode ) } , assemblies .Select ( i = > MetadataReference .CreateFromFile ( i.Location , MetadataReferenceProperties.Assembly , new DotNetDocumentationProvider ( new CSharpCompilationOptions ( OutputKind.DynamicallyLinkedLibrary ) ) ; var symbols = Recommender.GetRecommendedSymbolsAtPosition ( semanticModel , offset , solution.Workspace ) ; var information = symbol.GetDocumentationCommentXml ( ) ; protected override string GetDocumentationForSymbol ( string documentationMemberID , CultureInfo preferredCulture , CancellationToken cancellationToken = default ( CancellationToken ) ) var symbol = SymbolFinder.FindSymbolAtPosition ( semanticModel , offset , workspace , cancellationToken ) ; var information = symbol.GetDocumentationCommentXml ( ) ; | Using roslyn for hover over data for source tree symbols |
C_sharp : Possible Duplicate : Why is Func < T > ambiguous with Func < IEnumerable < T > > ? I noticed a very weird overload resolution issue with generics ... Consider the following methods : ( C # 4 , tested in LINQPad ) If I try to call Foo with a lambda expression as the selector , everything works fine : But if I replace x = > x with Identity , the compiler ca n't decide between the 2 Foo overloads : How can the second overload be a valid candidate ? Type inference correctly determines that TSource is int , so the T parameter for the Identity method has to be int as well , so the return type has to be int too ... Identity could be a Func < int , int > or a Func < double , double > , but not a Func < int , double > ! And it gets worse ! Even if I specify all type parameters explicitly , I still get the same error : How can there be any ambiguity here ? As far as I can tell , there is no way the overload that takes a Func < int , double > can be a candidate . I guess the explanation must be somewhere in the specifications , but I ca n't find the relevant bit ... or it might be a bug in the compiler , but I guess it 's unlikely.Note that it does work if I explicitly create the delegate : So , could someone explain what 's going on here ? Also , why does it work with a lambda but not with a method group ? <code> static void Foo < TSource > ( TSource element , Func < TSource , int > selector ) { `` int '' .Dump ( ) ; } static void Foo < TSource > ( TSource element , Func < TSource , double > selector ) { `` double '' .Dump ( ) ; } static T Identity < T > ( T value ) { return value ; } Foo ( 42 , x = > x ) ; // prints `` int '' Foo ( 42 , Identity ) ; // The call is ambiguous between the following methods or properties : // 'UserQuery.Foo < int > ( int , System.Func < int , int > ) ' and// 'UserQuery.Foo < int > ( int , System.Func < int , double > ) ' Foo < int > ( 42 , Identity < int > ) ; // The call is ambiguous ... Foo ( 42 , new Func < int , int > ( Identity ) ) ; // prints `` int '' | Generics , overload resolution and delegates ( sorry , ca n't find a better title ) |
C_sharp : I 've look in many places including google and SO but I did n't find any relevant answer.I 've made a few changes in my app recently , including updating ZedGraph dll ( from 5.1.4.26270 to 5.1.6.405 ) and since , VS wo n't open my controls throwing this error : Could not load file or assembly 'ZedGraph , Version=5.1.4.26270 , Culture=neutral , PublicKeyToken= ... ' or one of its dependencies . The system can not find the file specified.Which point to the old version . I 've look everywhere , I do n't find any trace of this old version.It also throw this error : The variable 'lineGraphControl1 ' is either undeclared or was never assigned.Whereas I call the constructor : I 've try to : RebootClean and RebluidStart VS in admin modeRemove the reference and re-add itWithout success.How can I erase trace of the old ZedGraph lib and how can I fix this error ? EditHere 's the changes between the old version and the new ( old first ) Edit 2After clearing the cache of VS and rebooting the computer , the error message changed : I am lost.Edit 3I 've search through the whole disk for the string 5.1.4.26270 and the only place found are not in the project.csproj snippet : Edit 4 : ( After Hans Passant anwser ) Here 's the LineGraphControl declaration : The LineGraph ( which use ZedGraph objects ) The Graph : Unfortunately the ZedGraph lib is to deeply linked to the software to change it to another one.I wo n't rollback the changes because I 've adapt the library in a way that make my software graphing 250 % faster.Here 's the callstack of the tentative to open the LineGraphControl in VS : Here 's the activity logError message when I try to create a new LineGraphControl : The ProcMon extract : <code> this.lineGraphControl1 = new Sakura.UI.Graphing.LineGraphControl ( ) ; < Reference Include= '' ZedGraph , Version=5.1.4.26270 , Culture=neutral , PublicKeyToken=02a83cbd123fcd60 , processorArchitecture=MSIL '' > < SpecificVersion > False < /SpecificVersion > < HintPath > ..\..\Lib\ZedGraph.dll < /HintPath > < /Reference > < Reference Include= '' ZedGraph , Version=5.1.6.405 , Culture=neutral , PublicKeyToken=02a83cbd123fcd60 , processorArchitecture=MSIL '' > < SpecificVersion > False < /SpecificVersion > < HintPath > ..\..\Lib\ZedGraph.dll < /HintPath > < /Reference > at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument ( IDesignerSerializationManager manager ) at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad ( IDesignerSerializationManager manager ) at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad ( IDesignerSerializationManager serializationManager ) at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted ( Int32 fReload ) < Reference Include= '' ZedGraph , Version=5.1.6.405 , Culture=neutral , PublicKeyToken=02a83cbd123fcd60 , processorArchitecture=MSIL '' > < SpecificVersion > False < /SpecificVersion > < HintPath > ..\..\Lib\ZedGraph.dll < /HintPath > < /Reference > public class LineGraphControl : GraphControl < Sakura.Graphing.LineGraph > public class LineGraph : Graph , ISerializable [ XmlInclude ( typeof ( StackedGraph ) ) ] [ XmlInclude ( typeof ( LineGraph ) ) ] [ XmlInclude ( typeof ( BubbleGraph ) ) ] [ XmlInclude ( typeof ( BatchGraph ) ) ] [ Serializable ] public abstract class Graph : ISerializable at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.EnsureDocument ( IDesignerSerializationManager manager ) at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad ( IDesignerSerializationManager manager ) at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad ( IDesignerSerializationManager serializationManager ) at System.ComponentModel.Design.Serialization.BasicDesignerLoader.BeginLoad ( IDesignerLoaderHost host ) | VS wo n't open control since dll update |
C_sharp : The following code produces a CA2000 ( `` Dispose objects before losing scope '' ) violation for the first line of Main , but not the second . I would really like the CA2000 violation for the second line , because this is a ( obviously simplified ) pattern often found in a large code base I work on . Does anyone know why the violation is not produced for the second line ? <code> public static void Main ( ) { new Disposable ( ) ; MakeDisposable ( ) ; } private static Disposable MakeDisposable ( ) { return new Disposable ( ) ; } private sealed class Disposable : IDisposable { public void Dispose ( ) { } } | Why does FxCop not report CA2000 for this trivial case of not-disposed class instance ? |
C_sharp : For money I am using a custom value type which holds only one decimal field . Simplified code is as follows.While using this struct in my project sometimes an ambiguity arises . And also sometimes I am setting an object with a constant number which is supposed to be a Money . For now I am initializing the object like , Can I assign a suffix for my custom type Money . I 'd like to initialize the object with the following . <code> public struct Money { private decimal _value ; private Money ( decimal money ) { _value = Math.Round ( money , 2 , MidpointRounding.AwayFromZero ) ; } public static implicit operator Money ( decimal money ) { return new Money ( money ) ; } public static explicit operator decimal ( Money money ) { return money._value ; } } object myObject= ( Money ) 200 ; object myObject=200p ; | Can I assign a suffix to my custom value type ? |
C_sharp : So I 've got these classes that expose a collection of child objects.I do n't want other classes adding or removing objects from collections because I need to wire into events in the child objects , so as they get added or removed I want to be able to do additional processing . But I really love the ease of manipulating generics internally.Did I mention this is a WPF app so I need INotifySupport ? The best I can come up with is something like this.Are there serious flaws with this design that I 'm not seeing ? Every time the Children property is accessed we get the overhead of converting list to an array.Any advice on this would be great . <code> public class foo : INotifyPropertyChanged { protected List < ChildFoo > _Children = new List < ChildFoo > ( ) ; public foo ( ) { } public void AddChild ( ChildFoo newChild ) { DoAttachLogic ( newChild ) ; _Children.Add ( newChild ) ; NotifyPropertyChange ( `` Children '' ) ; } public void RemoveChild ( ChildFoo oldChild ) { DoRemoveLogic ( oldChild ) ; _Children.Remove ( oldChild ) ; NotifyPropertyChange ( `` Children '' ) ; } public ChildFoo [ ] Children { get { return _Children.ToArray ( ) ; } } } | Is there a good pattern for exposing a generic collection as readonly ? |
C_sharp : I have a c # class which looks likeFrom a browser , I submitted a JSON object as followsWhere the value 1 assigned to the ParentNode property representes a database identifier . So , in order to bind properly to my model , i need to write a custom JSON converterBecause i get a `` Current JsonReader item is not an object : Integer . Path ParentNode ' '' , how can adapt the ReadJson method in order to bind the ParentNode property or anything else which needs custom conversion ? UPDATEI have seen JsonPropertyAttribute whose API documentation states Instructs the JsonSerializer to always serialize the member with the specified nameHowever , how can i instruct programatically a JsonSerializer - in my case , in the ReadJson method - to use a given JsonPropertyAttribute ? http : //www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonPropertyAttribute.htm <code> public class Node { public int Id { get ; set ; } /** Properties omitted for sake of brevity **/ public Node ParentNode { get ; set ; } } { `` Id '' :1 , `` ParentNode '' :1 } public class NodeJsonConverter : JsonConverter { public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { if ( reader.TokenType == JsonToken.Null ) { return null ; } /** Load JSON from stream **/ JObject jObject = JObject.Load ( reader ) ; Node node = new Node ( ) ; /** Populate object properties **/ serializer.Populate ( jObject.CreateReader ( ) , node ) ; return node ; } } | How to bind a given property when deserializing a JSON object in c # Web Api ? |
C_sharp : I would like to run this function under mono ( my current version is 4.0.2 ) But it fails with the error : What is the Mono equivalent of ClientConnectionId ? Or how can I fix it ? <code> public Object GetConnectionProperty ( SqlConnection _conn , string prop ) { if ( _conn.State == ConnectionState.Closed & prop == `` ServerVersion '' ) return string.Empty ; if ( prop == `` ClientConnectionId '' ) { Guid guid = _conn.ClientConnectionId ; return guid.ToString ( ) ; } return _conn.GetType ( ) .GetProperty ( prop ) .GetValue ( _conn ) ; } error CS1061 : Type ` System.Data.SqlClient.SqlConnection ' does not contain a definition for ` ClientConnectionId ' and no extension method ` ClientConnectionId ' of type ` System.Data.SqlClient.SqlConnection ' could be found . Are you missing an assembly reference ? | Mono equivalent of ClientConnectionId |
C_sharp : I have a scenario where a class loads objects of one type , due do abstractions I can not use a generic class ( generics tend to spread like cancer : ) but I often want to work with a generic version of the objects once retrieved , which resulted in code like this ( simplified ) : Where LoadItems returns a List < object > , then I realized , why not instead haveNow I can do this insteadWhich should be more efficient . It 's also seems a bit more flexible since I can take an existing List and tack on new items . So my questions are , is this a common pattern or do you have a different/better way of achieving this ? I 'm also a bit curious that you can do this , if you try and add a object of the wrong type you get an exception , but does that mean that generic lists also do a type check ? ( which seems a bit unecessary ) EDITIt might actually be a bit more elegant to modify the pattern to that way you can use the statement fluently and if no list is passed you could simply instantiate a List < object > <code> List < SomeClass > items = Storage.LoadItems ( filename ) .OfType < SomeClass > ( ) .ToList ( ) ; public void LoadItems ( string filename , IList list ) ; List < SomeClass > items = new List < SomeClass > ( ) ; LoadItems ( filename , items ) ; public IList LoadItems ( string filename , IList list=null ) ; | Backdooring Generic Lists through IList |
C_sharp : i am implementing Floyd–Warshall algorithm with c++ , c # and java . in each language i use sequential and parallel implementation after testing the result was : ( Elapsed time is only for main Function and Reading Files , Inti of Variable and ... are not measured . ) download sources here SourceCodesc++IDE : NetbeansCompiler : MinGW-4.8.1sequential time : 9.333000Parallel time : 2.539000using OpenMp for Prallel if NumOfThreads=1 then is Sequential else is Parallel variables javaIDE : NetbeansCompiler : Netbeans defaultsequential time : 11.632Parallel time : 3.089-Xms512m -Xmx1024mimport java.util.concurrent.Callable ; import java.util.concurrent.ExecutionException ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Future ; java variables i did not put java code here because its working right ( i think ) c # IDE : Visual Studio 2012Compiler : Visual Studio 2012 default sequential time : 31.312Parallel time : 8.920using System.Threading.Tasks ; variableparallel codesingle code whats wrong with my c # implementation ? all use the same filenow my question is why it takes more time to solve this algorithm with c # ? java and c++ have nearly the same elapsed time but i think my implementation with c # is wrong because this difference between c # and c++ is strange ! please help me to improve my C # implementation or name some reasons Thank you ! edit 1 i changed my arrays to jagged array and the result changed to : sequential time : 19.22Parallel time : 4.903 still its a huge different between c # and c++ or java ! any idea why ? new variables new codes : <code> # define n 1000 /* Then number of nodes */double dist [ n ] [ n ] ; void floyd_warshall ( int NumOfThreads ) { int i , j , k ; omp_set_num_threads ( NumOfThreads ) ; for ( k = 0 ; k < n ; ++k ) # pragma omp parallel for private ( i , j ) for ( i = 0 ; i < n ; ++i ) for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i ] [ k ] * dist [ k ] [ j ] ! = 0 ) & & ( i ! = j ) ) if ( ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) || ( dist [ i ] [ j ] == 0 ) ) dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } public final int numNodes =1000 ; public final double [ ] [ ] costs= new double [ numNodes ] [ numNodes ] ; const int n = 1000 ; static double [ , ] dist = new double [ n , n ] ; static void floyd_warshall ( ParallelOptions pOp ) { int k ; for ( k = 0 ; k < n ; ++k ) Parallel.For < int > ( 0 , n , pOp , ( ) = > 0 , ( i , loop , j ) = > { for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i , k ] * dist [ k , j ] ! = 0 ) & & ( i ! = j ) ) if ( ( dist [ i , k ] + dist [ k , j ] < dist [ i , j ] ) || ( dist [ i , j ] == 0 ) ) dist [ i , j ] = dist [ i , k ] + dist [ k , j ] ; return 0 ; } , ( j ) = > { } ) ; static void floyd_warshallSingle ( ) { int i , j , k ; for ( k = 0 ; k < n ; ++k ) for ( i = 0 ; i < n ; ++i ) for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i , k ] * dist [ k , j ] ! = 0 ) & & ( i ! = j ) ) if ( ( dist [ i , k ] + dist [ k , j ] < dist [ i , j ] ) || ( dist [ i , j ] == 0 ) ) dist [ i , j ] = dist [ i , k ] + dist [ k , j ] ; } const int n = 1000 ; static double [ ] [ ] dist = new double [ n ] [ ] ; static void floyd_warshallSingle ( ) { int i , j , k ; for ( k = 0 ; k < n ; ++k ) for ( i = 0 ; i < n ; ++i ) for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i ] [ k ] * dist [ k ] [ j ] ! = 0 ) & & ( i ! = j ) ) if ( ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) || ( dist [ i ] [ j ] == 0 ) ) dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } static void floyd_warshall ( ParallelOptions pOp ) { int k ; for ( k = 0 ; k < n ; ++k ) Parallel.For < int > ( 0 , n , pOp , ( ) = > 0 , ( i , loop , j ) = > { for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i ] [ k ] * dist [ k ] [ j ] ! = 0 ) & & ( i ! = j ) ) if ( ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) || ( dist [ i ] [ j ] == 0 ) ) dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; return 0 ; } , ( j ) = > { } ) ; } | Comparing c # , c++ and java performance ( Strange behavior of c # ) |
C_sharp : can I get a hand converting the following into a LINQ statement.Currently I have it down to this : The problem with the LINQ above is that it returns entries that have titles changed . Within the database I keep history of all records ( hence the need for the first on the createdDate order descending . When I change a report from title x to title y , it shows up under both titles when I only want the most recent record which would hence be the one under title y.EDITSorry for the lack of detail . I have a reports table which holds info about the report ( seedlot being an identifier ) . Whenever a report is edited , a new record is inserted ( vs updating the old one ) such that history is kept . In this case then the max entry for the createdDate indicates that the report is the most recent record to be displayed . Reports are then grouped into titles or ReportItems . These report items hold the title and associated reports . These reportItems are held in a ReportList such that I can print out the JSON in a desired format and just contains a status column and id linked to by the ReportItems . In the event that a report is moved from title a to title b , a new record is entered with the title foreign key linking up to the title it was changed to . When this happens the above given LINQ returns the record under each individual ReportItem when it should only return the newest entry for title b ( from the example above ) . Other than this the LINQ statement only returns the most recent record for the createdDate . Here are my class structures ( which mimic the DB structure as well ) Thanks , Dman <code> SELECT reports . * FROM [ dbo ] . [ ReportLists ] rlINNER JOIN [ dbo ] . [ ReportItems ] ri ON rl.Id = ri.ReportListIdINNER JOIN [ dbo ] . [ Reports ] reports ON ri.Id = reports.ReportItemIdWHERE reports.createdDateIN ( SELECT MAX ( report_max_dates.createdDate ) FROM [ dbo ] . [ Reports ] report_max_dates GROUP BY report_max_dates.seedLot ) db.ReportLists.Select ( rl = > db.ReportItems .Where ( ri = > ri.ReportListId == rl.Id ) .Select ( ri = > db.Reports .Where ( r = > r.ReportItemId == ri.Id ) .GroupBy ( r = > new { r.seedLot } ) .Select ( g = > g.OrderByDescending ( x = > x.createdDate ) .FirstOrDefault ( ) ) ) ) ; public class ReportList { public int Id { get ; set ; } public string status { get ; set ; } public List < ReportItem > { get ; set ; } } public class ReportItem { public int Id { get ; set } public string title { get ; set ; } public List < Report > { get ; set ; } } public class Report { public int Id { get ; set ; } public string Lot { get ; set ; } ... Other data ... public DateTime createdDate { get ; set ; } } | Convert an SQL statement into LINQ-To-SQL |
C_sharp : I would like to call one method 3 times Using LINQ , the method returns an object , with that object I want to add it into a List , How do i do it ? <code> List < News > lstNews = new List < News > ( ) ; lstNews.Add ( CollectNews ) [ x 3 times ] < -- Using Linq private static News CollectNews ( ) { ... } | Call method x times using linq |
C_sharp : I am getting the following error in an editor template of mine , ApplicantAddressMode : error CS0019 : Operator ' ! = ' can not be applied to operands of type 'Comair.RI.ViewModels.ApplicantAddressType ' and 'Comair.RI.Models.ApplicantTypesOfAddress ' '' } The type Comair.RI.ViewModels.ApplicantAddressType is nowhere to be found . A global solution search of all files for just the ApplicantAddressType returns no results . I changed the name of the enum in Comair.RI.Models from ApplicantAddressType to ApplicantTypesOfAddress to try and avoid an unintentional match , and cleaned out both 32 bit and 64 bit Temporary ASP Internet Files , and yet the error still persists on this line of the editor template : Model.AddressType is declared as : I am at my wits end about to start throwing flaming , pointed flags around , like IsResidentialStreetNumber and IsPostalSuburb . I do n't think the ambulances will arrive long after that and take me away to peace.The enum declaration is like this : <code> @ using Comair.RI.Models @ model Comair.RI.ViewModels.ApplicantAddressModel @ Html.ValidationSummary ( true ) < fieldset > < legend > @ Model.AddressTypeDescription < /legend > < ul class= '' form-column '' > @ if ( Model.AddressType ! = ApplicantTypesOfAddress.Residential ) { [ ScaffoldColumn ( false ) ] public ApplicantTypesOfAddress AddressType { get ; set ; } namespace Comair.RI.Models { public enum ApplicantTypesOfAddress { Residential , Postal } } | Why am I getting a type mismatch error with a type I can not see anywhere in my solution ? |
C_sharp : I understand why GUI controls have thread affinity.But why do n't the controls use the invoke internally in their methods and properties ? Now you have to do stuff like this just to update TextBox value : While using just textBox.Text = `` newValue '' ; would be enough to represent the same logic . All that would have to be done is change textBox.Text logic from this ( pseudocode ) : To this : The same goes for getters and methods.I 'm certainly not proposing to remove Invoke/BeginInvoke , I 'm just asking why the controls do n't do the necessary thread switch themselves instead of throwing exception . <code> this.Invoke ( new MethodInvoker ( delegate ( ) { textBox.Text = `` newValue '' ; } public string Text { set { if ( ! this.InvokeRequired ) // do the change logic else throw new BadThreadException ( ) ; } } public string Text { set { if ( ! this.InvokeRequired ) // do the change logic else this.Invoke ( new MethodInvoker ( delegate ( ) { // do the change logic } } } | Why do n't WinForms/WPF controls use Invoke internally ? |
C_sharp : Have a collection of objects . Schematically : Need : Is it possible to LINQ such ? Note : Ordering is important . So Bs = [ 5 ] ca n't be merged with Bs = [ 1 , 2 ] <code> [ { A = 1 , B = 1 } { A = 1 , B = 2 } { A = 2 , B = 3 } { A = 2 , B = 4 } { A = 1 , B = 5 } { A = 3 , B = 6 } ] [ { A = 1 , Bs = [ 1 , 2 ] } { A = 2 , Bs = [ 3 , 4 ] } { A = 1 , Bs = [ 5 ] } { A = 3 , Bs = [ 6 ] } ] | Transform a collection |
C_sharp : I have an object that looks something like this ( obviously simplified ) What I would like is for ETag to be a hash of the json serialization of the object omitting the ETag property ( to prevent a recursive loop ) . However , I can not just use a [ JsonIgnore ] attribute since at other times I want to be able to json serialize the entire thing.So what I want is something like thiswhich is unfortunately not an API that exists . How would I achieve something similar ? <code> public class Person { public string Name { get ; set ; } public int Age { get ; set ; } public string ETag { get { return ... } } } public string ETag { get { return Hash ( JsonConvert.Serialize ( this , p = > p.Ignore ( x= > x.ETag ) ) ) ; } } | How to serialize all but a specific property in one specific serialization |
C_sharp : How can I wait for n number of pulses ? I want the above thread to wait until being notified n times ( by n different threads or n times by the same thread ) .I believe there is a type of counter to do this , but I ca n't find it . <code> … // do somethingwaiter.WaitForNotifications ( ) ; | Let a thread wait for n number of pulses |
C_sharp : I have written some test code for comparing the performance of using direct property access or reflection or reflection by using delegates . But the results that I get are baffling , since it is showing that reflection is not much slower ( ~4 % ) than direct property access , which I do not believe to be true . Could someone tell me if I am doing something wrong here ? for 5000 items I am getting the below resultsdirect access : 32.2609 secsreflection : 33.623 secs reflection byusing delegates : 31.7981 secsCode : <code> private static Random random = new Random ( ( int ) DateTime.Now.Ticks ) ; Private Dictionary < string , Delegate > delegateList = new Dictionary < string , Delegate > ( ) ; private List < ReflectClass1 > dataList = new List < ReflectClass1 > ( ) ; private void TestMethod2 < T > ( ) { foreach ( var propertyInfo in typeof ( T ) .GetProperties ( BindingFlags.Public | BindingFlags.Instance ) ) { if ( propertyInfo.PropertyType.BaseType ! = typeof ( ValueType ) ) { Func < T , object > getPropDelegate = ( Func < T , object > ) Delegate.CreateDelegate ( typeof ( Func < T , object > ) , null , propertyInfo.GetGetMethod ( ) ) ; delegateList.Add ( propertyInfo.Name , getPropDelegate ) ; } //else // { // Type propertyType = propertyInfo.PropertyType.GetType ( ) ; // delegateList.Add ( propertyInfo.Name , // Delegate.CreateDelegate ( typeof ( Func < T , TResult > ) , null , propertyInfo.GetGetMethod ( ) ) ) ; // } } } //http : _//stackoverflow.com/questions/1122483/c-random-string-generator private string RandomString ( int size ) { StringBuilder builder = new StringBuilder ( ) ; char ch ; for ( int i = 0 ; i < size ; i++ ) { ch = Convert.ToChar ( Convert.ToInt32 ( Math.Floor ( 26 * random.NextDouble ( ) + 65 ) ) ) ; builder.Append ( ch ) ; } return builder.ToString ( ) ; } private void SetUpReflectObjList ( ) { for ( int i = 0 ; i < 5000 ; i++ ) { ReflectClass1 reflectClass1 = new ReflectClass1 ( ) ; reflectClass1.Prop1 = RandomString ( 15 ) ; reflectClass1.Prop2 = RandomString ( 10 ) ; reflectClass1.Prop3 = RandomString ( 10 ) ; reflectClass1.Prop4 = RandomString ( 10 ) ; reflectClass1.Prop5 = RandomString ( 10 ) ; reflectClass1.Prop6 = RandomString ( 10 ) ; reflectClass1.Prop7 = RandomString ( 10 ) ; reflectClass1.Prop8 = RandomString ( 10 ) ; reflectClass1.Prop9 = RandomString ( 10 ) ; reflectClass1.Prop10 = RandomString ( 10 ) ; dataList.Add ( reflectClass1 ) ; } } private void UseDelegateList ( ) { Debug.WriteLine ( string.Format ( `` Begin delegate performance test . item count = { 0 } start time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; for ( int i = 0 ; i < dataList.Count ; i++ ) { foreach ( PropertyInfo propertyInfo in typeof ( ReflectClass1 ) .GetProperties ( ) ) { if ( delegateList.ContainsKey ( propertyInfo.Name ) ) { Func < ReflectClass1 , object > getPropDelegate = ( Func < ReflectClass1 , object > ) delegateList [ propertyInfo.Name ] ; Debug.Write ( string.Format ( `` By delegates Object : { 0 } Property : { 1 } Value : { 2 } '' , i , propertyInfo.Name , getPropDelegate ( dataList [ i ] ) ) ) ; } } } Debug.WriteLine ( `` '' ) ; Debug.WriteLine ( string.Format ( `` End delegate performance test . item count = { 0 } end time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; } private void UseDirectReflection ( ) { Debug.WriteLine ( string.Format ( `` Begin direct reflection performance test . item count = { 0 } start time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; for ( int i = 0 ; i < dataList.Count ; i++ ) { foreach ( PropertyInfo propertyInfo in typeof ( ReflectClass1 ) .GetProperties ( ) ) { if ( propertyInfo == null ) continue ; { Debug.Write ( string.Format ( `` By reflection Object : { 0 } Property : { 1 } Value : { 2 } '' , i , propertyInfo.Name , propertyInfo.GetValue ( dataList [ i ] , null ) ) ) ; } } } Debug.WriteLine ( `` '' ) ; Debug.WriteLine ( string.Format ( `` End direct reflection performance test . item count = { 0 } end time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; } private void DirectOutputTest ( ) { Debug.WriteLine ( string.Format ( `` Begin direct output benchmark . item count = { 0 } start time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; for ( int i = 0 ; i < dataList.Count ; i++ ) { Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop1 '' , dataList [ i ] .Prop1 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop2 '' , dataList [ i ] .Prop2 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop3 '' , dataList [ i ] .Prop3 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop4 '' , dataList [ i ] .Prop4 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop5 '' , dataList [ i ] .Prop5 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop6 '' , dataList [ i ] .Prop6 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop7 '' , dataList [ i ] .Prop7 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop8 '' , dataList [ i ] .Prop8 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop9 '' , dataList [ i ] .Prop9 ) ) ; Debug.Write ( string.Format ( `` direct output benchmark Object : { 0 } Property : { 1 } Value : { 2 } '' , i , `` Prop10 '' , dataList [ i ] .Prop10 ) ) ; } Debug.WriteLine ( `` '' ) ; Debug.WriteLine ( string.Format ( `` End direct output benchmark . item count = { 0 } end time : { 1 } '' , dataList.Count , DateTime.Now.ToLongTimeString ( ) ) ) ; } | Reflection test does not show expected numbers |
C_sharp : I 'll try to make this as clear as possible . A Plugin architecture using reflection and 2 Attributes and an abstract class : PluginEntryAttribute ( Targets.Assembly , typeof ( MyPlugin ) ) PluginImplAttribute ( Targets.Class , ... ) abstract class Plugin Commands are routed to a plugin via an interface and a delegate : Ex : public delegate TTarget Command < TTarget > ( object obj ) ; Using extension methods with Command < > as the target , a CommandRouter executes the delegate on the correct target interface : Ex : Putting this together , I have a class hard-coded with the command delegates like so : When an object wants to query from the repository , practical execution looks like this : My question is this : how can I create such a class as Repositories dynamically from the plugins ? I can see the possibility that another attribute might be necessary . Something along the lines of : This is just an idea , but I 'm at a loss as to how I 'd still create a dynamic menu of sorts like the Repositories class . For completeness , the CommandRouter.Execute ( ... ) method and related Dictionary < , > : <code> public static TResult Execute < TTarget , TResult > ( this Command < TTarget > target , Func < TTarget , TResult > func ) { return CommandRouter.Default.Execute ( func ) ; } public class Repositories { public static Command < IDispatchingRepository > Dispatching = ( o ) = > { return ( IDispatchingRepository ) o ; } ; public static Command < IPositioningRepository > Positioning = ( o ) = > { return ( IPositioningRepository ) o ; } ; public static Command < ISchedulingRepository > Scheduling = ( o ) = > { return ( ISchedulingRepository ) o ; } ; public static Command < IHistographyRepository > Histography = ( o ) = > { return ( IHistographyRepository ) o ; } ; } var expBob = Dispatching.Execute ( repo = > repo.AddCustomer ( `` Bob '' ) ) ; var actBob = Dispatching.Execute ( repo = > repo.GetCustomer ( `` Bob '' ) ) ; [ RoutedCommand ( `` Dispatching '' , typeof ( IDispatchingRepository ) '' ) ] public Command < IDispatchingRepository > Dispatching = ( o ) = > { return ( IDispatchingRepository ) o ; } ; private readonly Dictionary < Type , object > commandTargets ; internal TResult Execute < TTarget , TResult > ( Func < TTarget , TResult > func ) { var result = default ( TResult ) ; if ( commandTargets.TryGetValue ( typeof ( TTarget ) , out object target ) ) { result = func ( ( TTarget ) target ) ; } return result ; } | How to build a dynamic command object ? |
C_sharp : I need to parse DateTime in `` Myy '' format , so : the first number is a month without leading zero ( 1 to 12 ) , andthe second number is a year with two digits.Examples : When using DateTime.ParseExact with `` Myy '' as a format , DateTime throws an exception when month is without leading zero.This code throws an exception : While this works fine : MSDN Documentation clearly defines format specifiers : `` M '' – The month , from 1 through 12 . `` MM '' – The month , from 01 through 12 . `` yy '' – The year , from 00 to 99 . Is there any format which would resolve the above case , i.e . `` Myy '' date time format in which month is without leading zeros ? EDITJust to precise : The question is about using format in ParseExact specifically and not about how to parse it itself by using string manipulation . <code> 115 - > January 20151016 - > October 2016 var date = DateTime.ParseExact ( `` 115 '' , `` Myy '' , CultureInfo.InvariantCulture ) ; // throws FormatException var date = DateTime.ParseExact ( `` 1016 '' , `` Myy '' , CultureInfo.InvariantCulture ) ; // works fine | Parsing DateTime in a `` Myy '' format |
C_sharp : This is more of an academic question about performance than a realistic 'what should I use ' but I 'm curious as I do n't dabble much in IL at all to see what 's constructed and I do n't have a large dataset on hand to profile against.So which is faster : or : Keep in mind that I do n't really want to know the performance impact of the string.Add ( s ) ( as whatever operation needs to be done ca n't really be changed ) , just the performance difference between setting s each iteration ( let 's say that s can be any primitive type or string ) verses calling the getter on the object each iteration . <code> List < myObject > objs = SomeHowGetList ( ) ; List < string > strings = new List < string > ( ) ; foreach ( MyObject o in objs ) { if ( o.Field == `` something '' ) strings.Add ( o.Field ) ; } List < myObject > objs = SomeHowGetList ( ) ; List < string > strings = new List < string > ( ) ; string s ; foreach ( MyObject o in objs ) { s = o.Field ; if ( s == `` something '' ) strings.Add ( s ) ; } | Which is faster in a loop : calling a property twice , or storing the property once ? |
C_sharp : We build software that audits fees charged by banks to merchants that accept credit and debit cards . Our customers want us to tell them if the card processor is overcharging them . Per-transaction credit card fees are calculated like this : A `` fee scheme '' is the pair of ( fixed , variable ) used by a group of credit cards , e.g . `` MasterCard business debit gold cards issued by First National Bank of Hollywood '' . We believe there are fewer than 10 different fee schemes in use at any time , but we are n't getting a complete nor current list of fee schemes from our partners . ( yes , I know that some `` fee schemes '' are more complicated than the equation above because of caps and other gotchas , but our transactions are known to have only a + bx schemes in use ) . Here 's the problem we 're trying to solve : we want to use per-transaction data about fees to derive the fee schemes in use . Then we can compare that list to the fee schemes that each customer should be using according to their bank . The data we get about each transaction is a data tuple : ( card_id , transaction_price , fee ) . transaction_price and fee are in integer cents . The bank rolls over fractional cents for each transation until the cumulative is greater than one cent , and then a `` rounding cent '' will be attached to the fees of that transaction . We can not predict which transaction the `` rounding cent '' will be attached to . card_id identifies a group of cards that share the same fee scheme . In a typical day of 10,000 transactions , there may be several hundred unique card_id 's . Multiple card_id 's will share a fee scheme . The data we get looks like this , and what we want to figure out is the last two columns.The end result we want is a short list like this with 10 or fewer entries showing the fee schemes that best fit our data . Like this : The average fee is about 8 cents . This means the rounding cents have a huge impact and the derivation above requires a lot of data . The average transaction is 125 cents . Transaction prices are always on 5-cent boundaries . We want a short list of fee schemes that `` fit '' 98 % + of the 3,000+ transactions each customer gets each day . If that 's not enough data to achieve 98 % confidence , we can use multiple days ' of data . Because of the rounding cents applied somewhat arbitrarily to each transaction , this is n't a simple algebra problem . Instead , it 's a kind of statistical clustering exercise that I 'm not sure how to solve . Any suggestions for how to approach this problem ? The implementation can be in C # or T-SQL , whichever makes the most sense given the algorithm . <code> fee = fixed + variable*transaction_price card_id transaction_price fee fixed variable=======================================================================12345 200 22 ? ? 67890 300 21 ? ? 56789 150 8 ? ? 34567 150 8 ? ? 34567 150 `` rounding cent '' - > 9 ? ? 34567 150 8 ? ? fee_scheme_id fixed variable======================================1 22 02 21 03 ? ? 4 ? ? ... | given 10 functions y=a+bx and 1000 's of ( x , y ) data points rounded to ints , how to derive 10 best ( a , b ) tuples ? |
C_sharp : I migrated to a Table Azure Provider for managing Microsoft bot framework state.In my telemetry , I see dependencies call being made to my new Table Azure Storage however I still see a lot of calls being made to state.botframework.com and some have the usual random slow response time . This does not seem normal as I would have expect all calls to be directed to my new private state provider : Example : https : //state.botframework.com/v3/botstate/facebook/users/999999999999Example of call to new private state provider : https : //xxxxxxxxxx.table.core.windows.net:443/botdata ( PartitionKey='facebook : private ' , RowKey='XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXOther potential relevant information : The application was live for a while using Microsoft State provider before switching to a table azure storageI do not persist any mission critical information in the bot state only the state of a dialog with a user ; and I can loose that without significant impact.The bot sends notification using a resumption cookie saved in a custom SQL database.This is how the Table Azure Provider is registered in a Autofac Module : I have the following method that check for saved state version compared to the running service version . This code was introduced because sometimes a user would have a serialized dialog state that was not compatible with the changes made in a dialog with a new release . <code> protected override void Load ( ContainerBuilder builder ) { base.Load ( builder ) ; //Register custom datastore builder .RegisterKeyedType < TableBotDataStore , IBotDataStore < BotData > > ( ) .Keyed < IBotDataStore < BotData > > ( AzureModule.Key_DataStore ) .WithParameter ( ( pi , c ) = > pi.Name == `` connectionString '' , ( pi , c ) = > ConfigurationManager.ConnectionStrings [ `` X '' ] .ConnectionString ) .SingleInstance ( ) ; builder.RegisterAdapterChain < IBotDataStore < BotData > > ( typeof ( TableBotDataStore ) , typeof ( CachingBotDataStore ) ) .InstancePerLifetimeScope ( ) ; } public static async Task CheckClientVersion ( Activity activity ) { StateClient stateClient = activity.GetStateClient ( ) ; BotData userData = stateClient.BotState.GetUserData ( activity.ChannelId , activity.From.Id ) ; if ( userData ? .GetProperty < string > ( `` version '' ) ? .CompareTo ( Assembly.GetExecutingAssembly ( ) .GetName ( ) .Version.ToString ( ) ) ! = 0 ) { string [ ] result = await stateClient.BotState.DeleteStateForUserAsync ( activity.ChannelId , activity.From.Id , CancellationToken.None ) ; userData = stateClient.BotState.GetUserData ( activity.ChannelId , activity.From.Id ) ; userData.SetProperty < string > ( `` version '' , Assembly.GetExecutingAssembly ( ) .GetName ( ) .Version.ToString ( ) ) ; await stateClient.BotState.SetUserDataAsync ( activity.ChannelId , activity.From.Id , userData ) ; } } | Migrated bot state provider but calls to state.botframework.com are still being made |
C_sharp : I have some kind of a job scheduling implemented which calls a function ProcessJob . Now inside this method I need to generate url to one of my pages i.e DoanloadPage.aspx ? some_params . That url is sent to user via email and when user clicks that link , it will take to the page . The problem here is that I am not generating url in a web request method or I do n't have access to the Request object . URL need to be generated in a custom class which is threaded i.e not in a web request.So I ca n't go with these solutions : None of these works because I think they all rely on current request or session somehow . So how do I generate urls for my app inside my code so I can use them anyway I want . <code> HostingEnvironment.MapPath ( `` test.aspx '' ) ; VirtualPathUtility.ToAbsolute ( `` 123.aspx '' ) ; HttpContext.Current.Request.Url.Authority ; | Making relative urls in asp.net webform custom classes without Request |
C_sharp : In this code , is it safe to not await the CopyToAsync or the stream could be disposed before the actual copy is done ? <code> public Task SaveAsync ( Stream source , string filepath ) { using ( var file = File.OpenWrite ( filepath ) ) { return source.CopyToAsync ( file ) ; } } | Is safe to not await inside a using block ? |
C_sharp : I am building an expression of type Expression < Func < Project , bool > > which returns the correct IQueryable < Project > from the database . IQueryable < Project > has a nested collection of SubProjects that I would like to filter as well . It looks something like thisCan this be done with one call to the database ? For example : This is what I would like to do : The GetProjectsByOrganization is as followsHow can I add an Expression < Func < SubProject , bool > > to the filter ? If not what alternatives do I have ? <code> Expression < Func < Project , bool > > projectFilter = FilterEnabled ( ) ; projectFilter = projectFilter.And ( GetProjectsByOrganization ( ) ) ; var projectData = GetProjectsAsQueryable ( projectFilter ) ; //returns correct projects Expression < Func < Project , bool > > projectFilter = FilterEnabled ( ) ; projectFilter = projectFilter.And ( GetProjectsByOrganization ( ) ) .And ( GetSubProjectsByStartDate ( ) ) ; var projectData = GetProjectsAsQueryable ( projectFilter ) ; //returns correct projects and the filtered sub projects by start date public Expression < Func < Project , bool > > GetProjectByOrganization ( ) { var organizationIDs = new List < Guid > ( ) ; if ( FilterCriteria.OrganiazaitonId ! = null ) organizationIDs = OrganizationRepository.GetParentAndChildrenOrganizationIds ( FilterCriteria.OrganiazaitonId.Value ) .ToList ( ) ; // ... return prj = > FilterCriteria.OrganiazaitonId == null || organizationIDs.Contains ( prj.OrganizationID.Value ) ; } | How can I filter nested items of IQueryable < T > ? |
C_sharp : Do I have to do this to ensure the MemoryStream is disposed of properly ? or is it OK to inline the MemoryStream so that it simply goes out of scope ? Like this ? <code> using ( MemoryStream stream = new MemoryStream ( bytes ) ) using ( XmlReader reader = XmlReader.Create ( stream ) ) { return new XmlDocument ( ) .Load ( reader ) ; } using ( XmlReader reader = XmlReader.Create ( new MemoryStream ( bytes ) ) ) { return new XmlDocument ( ) .Load ( reader ) ; } | Can I `` inline '' a variable if it 's IDisposable ? |
C_sharp : I was stepping through .Net Framework source code to find a tricky bug ( HttpApplication.cs ) , and I noticed lines like these in the code ( these are copy/pastes , I did n't edit anything ) : andI 'm wondering if this is obfuscated code , or is this some sort of c # convention I 've never seen before ? VS 2012 seems to think its not real code.Can anyone enlighten me ? <code> _ [ ... . ] = true ; _ [ ... . ] = false ; | Weird variable name ( _ [ ... . ] ) in .Net Source Code ( HttpApplication.cs ) |
C_sharp : While attempting to create a .NET Core class library for PowerShell I 'm seeing some strange differences between .NET Standard and .NET Core.Following this guidance , I 've created a simple .NET Standard 2.0 class library and have been able to successfully load it in PowerShell 5.1 and PowerShell 6.0.1 using Add-Type -Path [ path ] .I can call the .Bark ( ) method and see an output in PowerShell 5.1 and PowerShell Core 6.0.1.When I use the .NET Core 2.2 template to build the same class I ca n't use it in either PowerShell instance . Code is almost identical : PowerShell 5.1 : Add-Type : Unable to load one or more of the requested types . Retrieve the LoaderExceptions property for more information.PowerShell Core 6.0.1 Unable to find type [ AnimalCore.Dog ] I could happily go on using the .NET Standard template to build my assembly but I 'm wondering what the difference is here and how it would be possible to compile this class library for use on .NET Core ? <code> namespace Animal { public class Dog { public string Bark ( ) { return `` Woof ! `` ; } } } namespace AnimalCore { public class Dog { public string Bark ( ) { return `` Woof ! `` ; } } } | Ca n't call/load .NET Core assembly but .NET Standard works fine using Add-Type in PowerShell |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.