text stringlengths 46 37.3k | title stringlengths 12 162 |
|---|---|
C_sharp : When I remove Ldstr `` a '' and Call Console.WriteLine ( before Ret ) , the code runs fine , otherwise an InvalidProgramException is thrown upon invocation . Does this mean that an empty evaluation stack is required ? <code> class Program { delegate void Del ( ) ; static void Main ( string [ ] args ) { DynamicMethod dynamicMethod = new DynamicMethod ( `` '' , null , Type.EmptyTypes ) ; ILGenerator ilGen = dynamicMethod.GetILGenerator ( ) ; ilGen.Emit ( OpCodes.Ldstr , `` a '' ) ; ilGen.BeginExceptionBlock ( ) ; ilGen.Emit ( OpCodes.Ldstr , `` b '' ) ; ilGen.Emit ( OpCodes.Call , typeof ( Console ) .GetMethod ( `` WriteLine '' , BindingFlags.Static | BindingFlags.Public , null , new Type [ ] { typeof ( string ) } , null ) ) ; ilGen.BeginCatchBlock ( typeof ( Exception ) ) ; ilGen.EndExceptionBlock ( ) ; ilGen.Emit ( OpCodes.Call , typeof ( Console ) .GetMethod ( `` WriteLine '' , BindingFlags.Static | BindingFlags.Public , null , new Type [ ] { typeof ( string ) } , null ) ) ; ilGen.Emit ( OpCodes.Ret ) ; ( ( Del ) dynamicMethod.CreateDelegate ( typeof ( Del ) ) ) .Invoke ( ) ; } } | Is an empty evaluation stack required before an exception block ? |
C_sharp : or <code> db.Albums.FirstOrDefault ( x = > x.OrderId == orderId ) db.Albums.FirstOrDefault ( x = > x.OrderId.Equals ( orderId ) ) | Linq to SQL - what 's better ? |
C_sharp : I have the next function : I inserted the print function for analysis.If I call the function : It return true since 5^2 equals 25.But , if I call 16807 , which is 7^5 , the next way : In this case , it prints ' 7 ' but a == ( int ) a return false.Can you help ? Thanks ! <code> static bool isPowerOf ( int num , int power ) { double b = 1.0 / power ; double a = Math.Pow ( num , b ) ; Console.WriteLine ( a ) ; return a == ( int ) a ; } isPowerOf ( 25 , 2 ) isPowerOf ( 16807 , 5 ) | C # isPowerOf function |
C_sharp : Can someone explain the following piece of codeIt assigns 32 to y <code> int x = 45 ; int y = x & = 34 ; | How does this C # code snippet work ? |
C_sharp : While testing an application , I ran a into strange behaviour . Some of the tests use impersonation to run code as a different user , but they would always hang , never complete.After some investigation , the problem was narrowed down to the use of mutexes . Originally , we used our own impersonation code based on the MSDN documentation , but even when using the SimpleImpersonation library the problem still remains . Here is a minimal example to reproduce the problem : This never finishes , it 's stuck on the line with the mutex creation . The documentation states that it should either throw an exception or return something , but does not mention blocking.Some other observations , which might or might not be related : if we `` impersonate '' the current user , it returns immediatelyif we run the actual application and start another instance as adifferent user , everything works as intendedProbably there 's something going on with underlying system resources , but we could n't figure it out . How to make this work ? UPDATE : As per Hans ' comment , I tried disabling Windows Defender , it did n't help . Here 's a stacktrace of the place where it 's hanging : <code> using ( Impersonation.LogonUser ( DOMAIN , USER , PASSWORD , LogonType.Interactive ) ) { Console.WriteLine ( `` Impersonated '' ) ; bool mine ; using ( new Mutex ( true , `` Mutex '' , out mine ) ) { if ( ! mine ) throw new Exception ( `` Could n't get mutex '' ) ; Console.WriteLine ( `` Got mutex '' ) ; } } Console.WriteLine ( `` Finished '' ) ; ntdll.dll ! _NtWaitForSingleObject @ 12 ( ) KernelBase.dll ! _WaitForSingleObjectEx @ 12 ( ) mscorlib.ni.dll ! 719c1867 ( ) [ Frames below may be incorrect and/or missing , native debugger attempting to walk managed call stack ] mscorlib.ni.dll ! 719c1852 ( ) [ Managed to Native Transition ] mscorlib.dll ! System.Threading.Mutex.CreateMutexHandle ( bool initiallyOwned , string name , Microsoft.Win32.Win32Native.SECURITY_ATTRIBUTES securityAttribute , out Microsoft.Win32.SafeHandles.SafeWaitHandle mutexHandle ) mscorlib.dll ! System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode ( object userData ) [ Native to Managed Transition ] [ Managed to Native Transition ] mscorlib.dll ! System.Threading.Mutex.CreateMutexWithGuaranteedCleanup ( bool initiallyOwned , string name , out bool createdNew , Microsoft.Win32.Win32Native.SECURITY_ATTRIBUTES secAttrs ) mscorlib.dll ! System.Threading.Mutex.Mutex ( bool initiallyOwned , string name , out bool createdNew , System.Security.AccessControl.MutexSecurity mutexSecurity ) mscorlib.dll ! System.Threading.Mutex.Mutex ( bool initiallyOwned , string name , out bool createdNew ) MutexImpersonationTest.exe ! MutexImpersonationTest.Program.Main ( string [ ] args ) Line 16 | Mutex creation hangs while using impersonation |
C_sharp : I have a LINQ statement which is adding up the values of multiple columns , each beginning with 'HH ' although there are other columns available : Is there any way to tidy this up ? I have to do lots of variations of this ( in different methods ) so it would clear out a lot of 'fluff ' if it could be.Also I 'd like to call .GetValueOrDefault ( ) on each column , but currently I 've taken this out due to the mess except for the last two columns.Suggestions much appreciated ! <code> //TODO Clean up this messvar query1 = ( from e in Data where e.SD == date select e ) .Select ( x = > x.HH01 + x.HH16 + x.HH17 + x.HH18 + x.HH19 + x.HH20 + x.HH21 + x.HH22 + x.HH23 + x.HH24 + x.HH25 + x.HH26 + x.HH27 + x.HH28 + x.HH29 + x.HH30 + x.HH31 + x.HH32 + x.HH33 + x.HH34 + x.HH35 + x.HH36 + x.HH37 + x.HH38 + x.HH39 + x.HH40 + x.HH41 + x.HH42 + x.HH43 + x.HH44 +x.HH45 + x.HH46 + x.HH47 + x.HH48 + x.HH49.GetValueOrDefault ( ) + x.HH50.GetValueOrDefault ( ) ) ; return query1.FirstOrDefault ( ) ; | Ugly LINQ statement , a better way ? |
C_sharp : While looking at the Implementation of List.AddRange i found something odd i do not understand.Sourcecode , see line 727 ( AddRange calls InsertRange ) Why doest it Copy the collection into a `` temp-array '' ( itemsToInsert ) first and then copies the temp array into the actual _items-array ? Is there any reason behind this , or is this just some leftover from copying ArrayList 's source , because the same thing happens there . <code> T [ ] itemsToInsert = new T [ count ] ; c.CopyTo ( itemsToInsert , 0 ) ; itemsToInsert.CopyTo ( _items , index ) ; | List < T > .AddRange / InsertRange creating temporary array |
C_sharp : I have an overload method - the first implementation always returns a single object , the second implementation always returns an enumeration.I 'd like to make the methods generic and overloaded , and restrict the compiler from attempting to bind to the non-enumeration method when the generic type is enumerable ... To be used with ... Is this just plain bad code-smell that I 'm infringing on here , or is it possible to disambiguate the above methods so that the compiler will always get the calling code right ? Up votes for anyone who can produce any answer other than `` rename one of the methods '' . <code> class Cache { T GetOrAdd < T > ( string cachekey , Func < T > fnGetItem ) where T : { is not IEnumerable } { } T [ ] GetOrAdd < T > ( string cachekey , Func < IEnumerable < T > > fnGetItem ) { } } { // The compile should choose the 1st overload var customer = Cache.GetOrAdd ( `` FirstCustomer '' , ( ) = > context.Customers.First ( ) ) ; // The compile should choose the 2nd overload var customers = Cache.GetOrAdd ( `` AllCustomers '' , ( ) = > context.Customers.ToArray ( ) ) ; } | an I prevent a specific type using generic restrictions |
C_sharp : I always thought it worked fine both ways . Then did this test and realized it 's not allowed on re-assignments : works fine but not : Any technical reason for this ? I thought I would ask about it here , because this behavior was what I expected intuitively . <code> int [ ] a = { 0 , 2 , 4 , 6 , 8 } ; int [ ] a ; a = { 0 , 2 , 4 , 6 , 8 } ; | Why are collection initializers on re-assignments not allowed ? |
C_sharp : I am wondering if there is some way to optimize the using statement to declare and assign its output together ( when it is a single value ) .For instance , something similar to the new way to inline declare the result variable of an out parameter.Thanks for your input . <code> //What I am currently doing : string myResult ; using ( var disposableInstance = new myDisposableType ( ) ) { myResult = disposableInstance.GetResult ( ) ; } //That would be idealvar myResult = using ( var disposableInstance = new myDisposableType ( ) ) { return disposableInstance.GetResult ( ) ; } //That would be great toousing ( var disposableInstance = new myDisposableType ( ) , out var myResult ) { myResult = disposableInstance.GetResult ( ) ; } | C # using statement with return value or inline declared out result variable |
C_sharp : The following VB.NET code works : The following C # code fails to compile : The LearnerLogbookReportRequest is declared as : Error : Why is the C # version failing to compile ? <code> Dim request As Model.LearnerLogbookReportRequest = New Model.LearnerLogbookReportRequestrequest.LearnerIdentityID = Convert.ToInt32 ( Session ( `` identityID '' ) ) request.EntryVersion = LearnerLogbookEntryVersion.FullDim reportRequestService As IReportRequestService = ServiceFactory.GetReportRequestService ( ServiceInvoker.LearnerLogbook ) reportRequestservice.SaveRequest ( request ) LearnerLogbookReportRequest request = new LearnerLogbookReportRequest ( ) ; request.LearnerIdentityID = theLearner.ID ; request.EntryVersion = LearnerLogbookEntryVersion.Full ; IReportRequestService reportRequestService = ServiceFactory.GetReportRequestService ( ServiceInvoker.LearnerLogbook ) ; reportRequestService.SaveRequest ( ref request ) ; Public Class LearnerLogbookReportRequest Inherits AbstractReportRequest Error 11 Argument 1 : can not convert from 'ref RACQ.ReportService.Common.Model.LearnerLogbookReportRequest ' to 'ref RACQ.ReportService.Common.Model.AbstractReportRequest ' C : \p4projects\WEB_DEVELOPMENT\SECURE_ASPX\main-dev-codelines\LogbookSolution-DR6535\RACQ.Logbook.Web\Restful\SendLogbook.cs 64 50 RACQ.Logbook.Web | Why does my code compile in VB.NET but the equivalent in C # fails |
C_sharp : Hi my head is boiling now for 3 days ! I want to get all DNA encodings for a peptide : a peptide is a sequence of amino acids i.e . amino acid M and amino acid Q can form peptide MQ or QMDNA encoding means there is a DNA code ( called codon ) for each amino acid ( for some there are more than one code i.e . amino acid T has 4 different codes / codons ) The last function in the following code is not working so I want some one to make it work for me and please no query integrated language ( I forgot its acronym ! ) ` <code> private string [ ] CODONS = { `` TTT '' , `` TTC '' , `` TTA '' , `` TTG '' , `` TCT '' , `` TCC '' , `` TCA '' , `` TCG '' , `` TAT '' , `` TAC '' , `` TGT '' , `` TGC '' , `` TGG '' , `` CTT '' , `` CTC '' , `` CTA '' , `` CTG '' , `` CCT '' , `` CCC '' , `` CCA '' , `` CCG '' , `` CAT '' , `` CAC '' , `` CAA '' , `` CAG '' , `` CGT '' , `` CGC '' , `` CGA '' , `` CGG '' , `` ATT '' , `` ATC '' , `` ATA '' , `` ATG '' , `` ACT '' , `` ACC '' , `` ACA '' , `` ACG '' , `` AAT '' , `` AAC '' , `` AAA '' , `` AAG '' , `` AGT '' , `` AGC '' , `` AGA '' , `` AGG '' , `` GTT '' , `` GTC '' , `` GTA '' , `` GTG '' , `` GCT '' , `` GCC '' , `` GCA '' , `` GCG '' , `` GAT '' , `` GAC '' , `` GAA '' , `` GAG '' , `` GGT '' , `` GGC '' , `` GGA '' , `` GGG '' , } ; private string [ ] AMINOS_PER_CODON = { `` F '' , `` F '' , `` L '' , `` L '' , `` S '' , `` S '' , `` S '' , `` S '' , `` Y '' , `` Y '' , `` C '' , `` C '' , `` W '' , `` L '' , `` L '' , `` L '' , `` L '' , `` P '' , `` P '' , `` P '' , `` P '' , `` H '' , `` H '' , `` Q '' , `` Q '' , `` R '' , `` R '' , `` R '' , `` R '' , `` I '' , `` I '' , `` I '' , `` M '' , `` T '' , `` T '' , `` T '' , `` T '' , `` N '' , `` N '' , `` K '' , `` K '' , `` S '' , `` S '' , `` R '' , `` R '' , `` V '' , `` V '' , `` V '' , `` V '' , `` A '' , `` A '' , `` A '' , `` A '' , `` D '' , `` D '' , `` E '' , `` E '' , `` G '' , `` G '' , `` G '' , `` G '' , } ; public string codonToAminoAcid ( String codon ) { for ( int k = 0 ; k < CODONS.Length ; k++ ) { if ( CODONS [ k ] .Equals ( codon ) ) { return AMINOS_PER_CODON [ k ] ; } } // never reach here with valid codon return `` X '' ; } public string AminoAcidToCodon ( String aminoAcid ) { for ( int k = 0 ; k < AMINOS_PER_CODON .Length ; k++ ) { if ( AMINOS_PER_CODON [ k ] .Equals ( aminoAcid ) ) { return CODONS [ k ] ; } } // never reach here with valid codon return `` X '' ; } public string GetCodonsforPeptide ( string pep ) { string result = `` '' ; for ( int i = 0 ; i < pep.Length ; i++ ) { result = AminoAcidToCodon ( pep.Substring ( i,1 ) ) ; for ( int q = 0 ; q < pep.Length ; q++ ) { result += AminoAcidToCodon ( pep.Substring ( q , 1 ) ) ; } } return result ; } | how to get all dna encoding for peptide in c # |
C_sharp : I want to prohibit reentrancy for large set of methods.for the single method works this code : This is tedious to do it for every method.So I 've used StackTrace class : It works fine but looks more like a hack.Does .NET Framework have special API to detect reentrancy ? <code> bool _isInMyMethod ; void MyMethod ( ) { if ( _isInMethod ) throw new ReentrancyException ( ) ; _isInMethod = true ; try { ... do something ... } finally { _isInMethod = false ; } } public static void ThrowIfReentrant ( ) { var stackTrace = new StackTrace ( false ) ; var frames = stackTrace.GetFrames ( ) ; var callingMethod = frames [ 1 ] .GetMethod ( ) ; if ( frames.Skip ( 2 ) .Any ( frame = > EqualityComparer < MethodBase > .Default.Equals ( callingMethod , frame.GetMethod ( ) ) ) ) throw new ReentrancyException ( ) ; } | Does framework have dedicated api to detect reentrancy ? |
C_sharp : I 'm newer to C # and have just discovered how to use yield return to create a custom IEnumerable enumeration . I 'm trying to use MVVM to create a wizard , but I was having trouble figuring out how to control the flow from one page to the next . In some cases I might want a certain step to appear , in others , it does n't apply.Anyway , my issue is that I 'm using an IEnumerable to return each subsequent page , which works really great , but I know I 'm probably doing something improper/unintended with the language . The child class only has to override the abstract Steps IEnumerable accessor : The parent class contains the navigation logic using the Steps attributes ' enumerator : And here is the WizardStep abstract class which each wizard page implements : As I said , this works wonderfully because I navigate the list with the Enumerator . Navigation logic is in an abstract parent class and all the child has to do is to override the Steps attribute . The WizardSteps themselves contain logic so that they know when they are valid and the user can continue . I 'm using MVVM so the next button is bound to the CanMoveToNextPage ( ) and MoveToNextPage ( ) functions through a Command.I guess my question is : how wrong is it to abuse the enumeration model in this case ? Is there a better way ? I really need to define the control flow somehow , and it just fit really well with the yield return ability so that I can have flow logic return to the Steps accessor to get the next page . <code> public class HPLDTWizardViewModel : WizardBase { protected override IEnumerable < WizardStep > Steps { get { WizardStep currentStep ; // 1.a start with assay selection currentStep = new AssaySelectionViewModel ( ) ; yield return currentStep ; // 1.b return the selected assay . SigaDataSet.Assay assay = ( ( AssaySelectionViewModel ) currentStep ) .SelectedAssay ; sigaDataSet = ( SigaDataSet ) assay.Table.DataSet ; // 2.a get the number of plates currentStep = new NumPlatesViewModel ( sigaDataSet ) ; yield return currentStep ; ... } } } public abstract class WizardBase : ViewModelBase { private ICommand _moveNextCommand ; private ICommand _cancelCommand ; private IEnumerator < WizardStep > _currentStepEnumerator ; # region Events /// < summary > /// Raised when the wizard window should be closed . /// < /summary > public event EventHandler RequestClose ; # endregion // Events # region Public Properties /// < summary > /// Gets the steps . /// < /summary > /// < value > The steps. < /value > protected abstract IEnumerable < WizardStep > Steps { get ; } /// < summary > /// Gets the current step . /// < /summary > /// < value > The current step. < /value > public WizardStep CurrentStep { get { if ( _currentStepEnumerator == null ) { _currentStepEnumerator = Steps.GetEnumerator ( ) ; _currentStepEnumerator.MoveNext ( ) ; } return _currentStepEnumerator.Current ; } } # endregion //Public Properties # region Commands public ICommand MoveNextCommand { get { if ( _moveNextCommand == null ) _moveNextCommand = new RelayCommand ( ( ) = > this.MoveToNextPage ( ) , ( ) = > this.CanMoveToNextPage ( ) ) ; return _moveNextCommand ; } } public ICommand CancelCommand { get { if ( _cancelCommand == null ) _cancelCommand = new RelayCommand ( ( ) = > OnRequestClose ( ) ) ; return _cancelCommand ; } } # endregion //Commands # region Private Helpers /// < summary > /// Determines whether this instance [ can move to next page ] . /// < /summary > /// < returns > /// < c > true < /c > if this instance [ can move to next page ] ; otherwise , < c > false < /c > . /// < /returns > bool CanMoveToNextPage ( ) { if ( CurrentStep == null ) return false ; else return CurrentStep.IsValid ( ) ; } /// < summary > /// Moves to next page . /// < /summary > void MoveToNextPage ( ) { _currentStepEnumerator.MoveNext ( ) ; if ( _currentStepEnumerator.Current == null ) OnRequestClose ( ) ; else OnPropertyChanged ( `` CurrentStep '' ) ; } /// < summary > /// Called when [ request close ] . /// < /summary > void OnRequestClose ( ) { EventHandler handler = this.RequestClose ; if ( handler ! = null ) handler ( this , EventArgs.Empty ) ; } # endregion //Private Helpers } public abstract class WizardStep : ViewModelBase { public abstract string DisplayName { get ; } public abstract bool IsValid ( ) ; public abstract List < string > GetValidationErrors ( ) ; } | Wizard navigation with IEnumerable / yield return |
C_sharp : Ok , this is a little weird . Ignore what I am trying to do , and look at the result of what happens in this situation.The Code : The Situation : The line numbers = rawNumbers.Split ( ' , ' ) .Cast < int > ( ) ; appears to work , and no exception is thrown . However , when I iterate over the collection , and InvalidCastException is thrown . Now , drill down into the source and look at CastIterator < TResult > . This seems to be getting called at for ( int i = 0 ; i < numbers.Count ( ) ; i++ ) ... specifically numbers.Count ( ) The error is happening on the cast , and when I look at the data in the source varaible it is a string [ ] .I would have thought that since the line where I call the cast to an int executed successfully everything was fine . What is going on behind the curtain ? Is the string array really just being stored somewhere , and not being casted to T until it is called for ? Lazy casting perhaps ? I know I cant do : ( int ) '' 42 '' . My questions is n't how to make the cast work , but what is going on . Deferred execution of the cast ? It seems weird the line where I call out Cast < int > ( ) seems to work , but really does n't . <code> static string rawNumbers= '' 1,4,6,20,21,22,30,34 '' ; static IEnumerable < int > numbers = null ; static void Main ( string [ ] args ) { numbers = rawNumbers.Split ( ' , ' ) .Cast < int > ( ) ; for ( int i = 0 ; i < numbers.Count ( ) ; i++ ) { //do something } } static IEnumerable < TResult > CastIterator < TResult > ( IEnumerable source ) { foreach ( object obj in source ) yield return ( TResult ) obj ; } | Did I really just put a string data type into an IEnumerable < int > |
C_sharp : I migrated an WebAPI from FullDotnet ( 4.6 ) to .Net Core 2.0 and I 'm having this issue in my Data Layer using Dapper.My code : Strange Behavior : The solution Builds and WORKThe `` error '' who VisualStudio highlight is : Argument type 'lambda expression ' is not assignable to parameter type 'System.Func ` 5 ' I have another classes with the same behavior and same error , but , again , the code compile and work , but this `` error highlight '' is annoying ! This highlight I do n't have in my old solution running .NET Framework 4.6 Usefull info : Class Library : .Net Standard 2.0 Visual Studio 2017 v15.4.1Resharper 2017.2 <code> public List < Doctor > GetList ( ) { List < Doctor > ret ; using ( var db = GetMySqlConnection ( ) ) { const string sql = @ '' SELECT D.Id , D.Bio , D.CRMState , D.CRMNumber , U.Id , U.Email , U.CreatedOn , U.LastLogon , U.Login , U.Name , U.Phone , U.Surname , U.Id , U.Birth , U.CPF , S.Id , S.Name from Doctor D inner join User U on U.Id = D.UserId inner join Speciality S on S.Id = D.IDEspeciality order by D.Id DESC '' ; ret = db.Query < Doctor , User , Speciality , Doctor > ( sql , ( doctor , user , speciality ) = > { doctor.User = user ; doctor.Speciality = speciality ; return doctor ; } , splitOn : `` Id , Id '' , commandType : CommandType.Text ) .ToList ( ) ; } return ret ; } | Why does Visual Studio report a lambda error in a working WebAPI code on .Net Core ? |
C_sharp : I 've read this answer and understood from it the specific case it highlights , which is when you have a lambda inside another lambda and you do n't want to accidentally have the inner lambda also compile with the outer one . When the outer one is compiled , you want the inner lambda expression to remain an expression tree . There , yes , it makes sense quoting the inner lambda expression.But that 's about it , I believe . Is there any other use case for quoting a lambda expression ? And if there is n't , why do all the LINQ operators , i.e . the extensions on IQueryable < T > that are declared in the Queryable class quote the predicates or lambdas they receive as arguments when they package that information in the MethodCallExpression.I tried an example ( and a few others over the last couple of days ) and it does n't seem to make any sense to quote a lambda in this case.Here 's a method call expression to a method that expects a lambda expression ( and not a delegate instance ) as its only parameter.I then compile the MethodCallExpression by wrapping it inside a lambda.But that does n't compile the inner LambdaExpression ( the argument to the GimmeExpression method ) as well . It leaves the inner lambda expression as an expression tree and does not make a delegate instance of it.In fact , it works well without quoting it.And if I do quote the argument , it breaks and gives me an error indicating that I am passing in the wrong type of argument to the GimmeExpression method.What 's the deal ? What 's this quoting all about ? <code> private static void TestMethodCallCompilation ( ) { var methodInfo = typeof ( Program ) .GetMethod ( `` GimmeExpression '' , BindingFlags.NonPublic | BindingFlags.Static ) ; var lambdaExpression = Expression.Lambda < Func < bool > > ( Expression.Constant ( true ) ) ; var methodCallExpression = Expression.Call ( null , methodInfo , lambdaExpression ) ; var wrapperLambda = Expression.Lambda ( methodCallExpression ) ; wrapperLambda.Compile ( ) .DynamicInvoke ( ) ; } private static void GimmeExpression ( Expression < Func < bool > > exp ) { Console.WriteLine ( exp.GetType ( ) ) ; Console.WriteLine ( `` Compiling and executing expression ... '' ) ; Console.WriteLine ( exp.Compile ( ) .Invoke ( ) ) ; } | Why would you quote a LambdaExpression ? |
C_sharp : We have a web api with the following resource url.now there are some books which contains names with ampersand ' & ' and when a request is made for such names , we are receiving below errorURL used : Error : A potentially dangerous Request.Path value was detected from the client ( & ) We tried passing or using encoded value for & i.e . % 26 and getting same error.URL used : Error : A potentially dangerous Request.Path value was detected from the client ( & ) Now , when I added requestPathInvalidCharacters= '' '' property in the web.config in httpruntime element , it started working fine for both the above urls . But , when I read different articles , it is said that it is not a good practice to use requestPathInvalidCharacters= '' '' property . Also , since there are lot of book names in production with `` & '' and different special characters , we can not avoid sending `` & '' ampersand for book names , is there a good way to handle this ? <code> http : //www.example.com/book/bookid/name/bookname http : //www.example.com/book/123/name/ban & ban http : //www.example.com/book/123/name/ban % 26ban | error when url resource contains ampersand |
C_sharp : I have a RGB image ( RGB 4:4:4 colorspace , 24-bit per pixel ) , captured from camera . I use Gorgon 2D library ( build base on SharpDX ) to display this image as a texture so i have to convert it to ARGB . I use this code ( not my code ) to convert from RGB camera image to RGBA.Then convert RGB to RGBA like this : And I use rgba as data of Gorgon texture : But the color of texture image is not like the color of camera image . so I think I have to convert camera image to ARGB , ( not RGBA ) so that it can display with Gorgon texture but i dont know how to do it with the code above . Can you guys please point me some hints ? Thanks ! Below are the links to types of Gorgon Library i used in the code aboveGorgonTexture2DGorgonNativeBufferGorgonImageBuffer <code> [ StructLayout ( LayoutKind.Sequential ) ] public struct RGBA { public byte r ; public byte g ; public byte b ; public byte a ; } [ StructLayout ( LayoutKind.Sequential ) ] public struct RGB { public byte r ; public byte g ; public byte b ; } unsafe void internalCvt ( long pixelCount , byte* rgbP , byte* rgbaP ) { for ( long i = 0 , offsetRgb = 0 ; i < pixelCount ; i += 4 , offsetRgb += 12 ) { uint c1 = * ( uint* ) ( rgbP + offsetRgb ) ; uint c2 = * ( uint* ) ( rgbP + offsetRgb + 3 ) ; uint c3 = * ( uint* ) ( rgbP + offsetRgb + 6 ) ; uint c4 = * ( uint* ) ( rgbP + offsetRgb + 9 ) ; ( ( uint* ) rgbaP ) [ i ] = c1 | 0xff000000 ; ( ( uint* ) rgbaP ) [ i + 1 ] = c2 | 0xff000000 ; ( ( uint* ) rgbaP ) [ i + 2 ] = c3 | 0xff000000 ; ( ( uint* ) rgbaP ) [ i + 3 ] = c4 | 0xff000000 ; } } public unsafe void RGB2RGBA ( int pixelCount , byte [ ] rgbData , byte [ ] rgbaData ) { if ( ( pixelCount & 3 ) ! = 0 ) throw new ArgumentException ( ) ; fixed ( byte* rgbP = & rgbData [ 0 ] , rgbaP = & rgbaData [ 0 ] ) { internalCvt ( pixelCount , rgbP , rgbaP ) ; } } byte [ ] rgb = new byte [ 800*600*3 ] ; //Stored databyte [ ] rgba = new byte [ 800 * 600 * 4 ] ; RGB2RGBA ( 800*600 , rgb , rgba ) unsafe { fixed ( void* rgbaPtr = rgba ) { var buff = new GorgonNativeBuffer < byte > ( rgbaPtr , 800*600*4 ) ; GorgonImageBuffer imb = new GorgonImageBuffer ( buff , 800 , 600 , BufferFormat.R8G8B8A8_UNorm ) ; //Set Texture data GorgonTexture2D Texture.SetData ( imb , new SharpDX.Rectangle ( 0 , 0 , 800 , 600 ) , 0 , 0 , CopyMode.NoOverwrite ) ; } } | How to convert RGB camera image to ARGB format of SharpDX ? |
C_sharp : Anyone can elaborate some details on this code or even give a non-Linq version of this algorithm : <code> public static IEnumerable < IEnumerable < T > > Combinations < T > ( this IEnumerable < T > elements , int k ) { return k == 0 ? new [ ] { new T [ 0 ] } : elements.SelectMany ( ( e , i ) = > elements .Skip ( i + 1 ) .Combinations ( k - 1 ) .Select ( c = > ( new [ ] { e } ) .Concat ( c ) ) ) ; } | How to understand the following C # linq code of implementing the algorithm to return all combinations of k elements from n |
C_sharp : I have seen people use a couple of different way of initializing arrays : or another way , also called initializing is : What is the best way , and what is the major difference between both ways ( including memory allocation ) ? <code> string [ ] Meal = new string [ ] { `` Roast beef '' , `` Salami '' , `` Turkey '' , `` Ham '' , `` Pastrami '' } ; string [ ] Meats = { `` Roast beef '' , `` Salami '' , `` Turkey '' , `` Ham '' , `` Pastrami '' } ; | Whats the difference between Declaring a variable ( as new ) and then initializing it and direct initializing it ? |
C_sharp : I 'm looking to implement some algorithm to help me match imperfect sequences.Say I have a stored sequence of ABBABABBA and I want to find something that 'looks like ' that in a large stream of characters.If I give my algorithm the allowance to have 2 wildcards ( differences ) , how can I use Regex to match something like : where ( and ) mark the differences : My Dilemma is that I am looking to find these potential target matches ( with imperfections ) in a big string of characters.So in something like : I must be able to search for these 'near enough ' matches . Where brackets denote : ( The Good enough Match with the ( Differences ) ) Edit : To be more formal in this example , A match of Length N can be accepted if N-2 characters are the same as the original ( 2 Differences ) I 've used Regex before , but only to find perfect sequences - not for something that 'looks like ' one.Hope this is clear enough to get some advice on.Thanks for reading and any help ! <code> A ( A ) BABAB ( A ) A or ( B ) BBA ( A ) ABBA ABBDBABDBCBDBABDB ( A ( A ) BABAB ( A ) A ) DBDBABDBCBDBABADBDBABDBDBDBCBDBABCBDBABCBDBABCBDBABABBBDBABABBCDDBABCBDABDBABCBCBDBABABDABDBABCBDBABABDDABCBDBABAB | Regex to find 'good enough ' sequences |
C_sharp : I 'm working on my final year project . In which : I have Login and Signup forms on one page ( WebForm ) : When user click on anchor Sign Up the DropDown ddlType ( hides ) and TextBoxes - txtCustName , txtEmail and txtConfirmPassword ( Displays ) in Javascript client side : Login Form : -And when user click on anchor Login the DropDown ddlType ( Displays ) and TextBoxes - txtCustName , txtEmail and txtConfirmPassword ( Hides ) in Javascript client side : Sign Up Form : -The .aspx code of anchors and buttons is : Question : When user click on button Sign Up the DropDown ddlType ( Displays ) and TextBoxes - txtCustName , txtEmail and txtConfirmPassword ( Hides ) but I want to prevent this condition and the sign up form should be shown : How I can stop it on the Sign Up Form ? Updated : My problem is when click on Sign Up button it sets to the Login form as like : <code> function signupClick ( ) { document.getElementById ( 'divType ' ) .style.display = 'block ' ? 'none ' : 'block ' ; document.getElementById ( ' < % =txtCustName.ClientID % > ' ) .style.display = 'inherit ' ; document.getElementById ( ' < % =txtConfirmPassword.ClientID % > ' ) .style.display = 'inherit ' ; document.getElementById ( ' < % =btnLogin.ClientID % > ' ) .style.display = 'none ' ; document.getElementById ( ' < % =btnSignUp.ClientID % > ' ) .style.display = 'inherit ' ; document.getElementById ( 'lblLogin ' ) .style.display = 'inherit ' ; document.getElementById ( 'lblSignup ' ) .style.display = 'none ' ; } function loginClick ( ) { document.getElementById ( 'divType ' ) .style.display = 'none ' ? 'block ' : 'none ' ; document.getElementById ( ' < % =txtCustName.ClientID % > ' ) .style.display = 'none ' ; document.getElementById ( ' < % =txtConfirmPassword.ClientID % > ' ) .style.display = 'none ' ; document.getElementById ( ' < % =btnLogin.ClientID % > ' ) .style.display = 'inherit ' ; document.getElementById ( ' < % =btnSignUp.ClientID % > ' ) .style.display = 'none ' ; document.getElementById ( 'lblLogin ' ) .style.display = 'none ' ; document.getElementById ( 'lblSignup ' ) .style.display = 'inherit ' ; } < label id= '' lblSignup '' style= '' float : right '' > For new account ? < a href= '' javascript : ; '' id= '' signup '' onclick= '' signupClick ( ) '' > Sign Up < /a > < /label > < label id= '' lblLogin '' style= '' float : right ; display : none '' > For existing account ? < a href= '' javascript : ; '' id= '' login '' onclick= '' loginClick ( ) '' > Login < /a > < /label > < /div > < label style= '' width : 28 % '' > < asp : HyperLink ID= '' hlHome '' NavigateUrl= '' Index.aspx '' Text= '' Home '' CssClass= '' btn btn-default '' Width= '' 100 % '' runat= '' server '' / > < /label > < label style= '' width : 70 % ; float : right '' > < asp : Button ID= '' btnLogin '' OnClick= '' btnLogin_Click '' CssClass= '' btn btn-success '' Width= '' 100 % '' runat= '' server '' Text= '' Login '' / > < asp : Button ID= '' btnSignUp '' OnClick= '' btnSignUp_Click '' Style= '' display : none '' Width= '' 100 % '' CssClass= '' btn btn-primary '' runat= '' server '' Text= '' Sign Up '' / > < /label > private void ShowMessage ( string msg ) { ScriptManager.RegisterStartupScript ( this , GetType ( ) , null , `` AutoHideAlert ( ' '' + msg + `` ' ) ; '' , true ) ; } protected void btnSignUp_Click ( object sender , EventArgs e ) { string cusname = txtCustName.Text ; string email = txtEmail.Text ; string pass = txtPassword.Text ; string confirm = txtConfirmPassword.Text ; if ( string.IsNullOrEmpty ( cusname ) || string.IsNullOrEmpty ( email ) || string.IsNullOrEmpty ( pass ) || string.IsNullOrEmpty ( confirm ) ) { ShowMessage ( `` Fill all cradentials of customer . `` ) ; } else { //.. Register user Response.Redirect ( `` ~/CustomerPanel/Dashboard.aspx '' ) ; } } -- - JavaScript Function -- -function AutoHideAlert ( msg ) { // lblAlert is an asp : Label for displaying alert message var al = document.getElementById ( ' < % =lblAlert.ClientID % > ' ) ; al.innerText = msg ; // alert is a DIV to show message $ ( `` # alert '' ) .fadeTo ( 3500 , 500 ) .slideUp ( 1500 , function ( ) { $ ( `` # alert '' ) .slideUp ( 500 ) ; } ) ; } | How to stop on the Sign Up Form when web page performs Postback ? |
C_sharp : I 'm having problem with finding most common group of integers among int [ x,6 ] array , where x < = 100000 . Numbers are between 0 and 50.eg input . ( N = 2 ) output : Attached code I tried . Now I understand it does n't work , but I was asked me to post it . I 'm not just asking help without even trying . <code> 14 24 44 36 37 45 - here01 02 06 24 33 4410 17 34 40 44 45 - here12 13 28 31 37 4701 06 07 09 40 4501 05 06 19 35 4413 19 20 26 31 4744 20 30 31 45 46 - here02 04 14 23 30 3427 30 41 42 44 4903 06 15 27 37 48 44 , 45 ( 3 ) // appeared 3 times using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.IO ; namespace TotoLotek { class Program { static void Main ( string [ ] args ) { StreamReader czytnik = new StreamReader ( `` dane_wejsciowe.txt '' ) ; List < int [ ] > lista = new List < int [ ] > ( ) ; string linia = `` '' ; while ( ( linia = czytnik.ReadLine ( ) ) ! = null ) { string [ ] numery = linia.Split ( ' ' ) ; int [ ] tablica_intow = new int [ 6 ] ; for ( int i = 0 ; i < 6 ; i++ ) { tablica_intow [ i ] = int.Parse ( numery [ i ] ) ; } lista.Add ( tablica_intow ) ; } czytnik.Close ( ) ; int [ ] tablica = new int [ 50 ] ; for ( int i = 0 ; i < lista.Count ( ) ; i++ ) { for ( int j = 0 ; j < 6 ; j++ ) { tablica [ lista [ i ] [ j ] ] ++ ; } } int maks = tablica [ 0 ] ; int maks_indeks = 0 ; for ( int i = 0 ; i < 50 ; i++ ) { if ( tablica [ i ] > maks ) { maks = tablica [ i ] ; maks_indeks = i ; } } Console.Write ( `` { 0 } ( { 1 } ) `` , maks_indeks , maks ) ; List < int [ ] > lista2 = new List < int [ ] > ( ) ; for ( int i = 0 ; i < lista.Count ( ) ; i++ ) { for ( int j = 0 ; j < 6 ; j++ ) { if ( lista [ i ] [ j ] == maks_indeks ) lista2.Add ( lista [ i ] ) ; break ; } } int [ ] tablica2 = new int [ 50 ] ; for ( int i = 0 ; i < lista2.Count ( ) ; i++ ) { for ( int j = 0 ; j < 6 ; j++ ) { tablica2 [ lista2 [ i ] [ j ] ] ++ ; } } int maks2 = tablica2 [ 0 ] ; int maks_indeks2 = 0 ; for ( int i = 0 ; i < 50 ; i++ ) { if ( tablica2 [ i ] > maks2 & & i ! = maks_indeks ) { maks2 = tablica2 [ i ] ; maks_indeks2 = i ; } } Console.Write ( `` { 0 } ( { 1 } ) `` , maks_indeks2 , maks2 ) ; int xdddd = 2 ; } } } | How to find a group of integers ( N ) amongst records , that contains 6 integers |
C_sharp : I found this code snippet on SO ( sorry I do n't have the link to the question/answer combo ) This confuses me because FileAttributes.Directory is on both sides of the ==.What does the & do in this case ? I 'm not sure how to read this line of code . I 'm trying to evaluate whether a path string is a file or a directory . <code> bool isDir = ( File.GetAttributes ( source ) & FileAttributes.Directory ) == FileAttributes.Directory ; | How does this C # operator work in this code snippet ? |
C_sharp : I 've got a controller method : Now , I 'd like to test this.This throws a RuntimeBinderException saying that Calculated is not defined . Is there any way to achieve this ? UPDATEFollowing Jons ' advice , I used InternalsVisibleTo to befriend my test assembly . Everything works fine . Thank you Jon . <code> public JsonResult CalculateStuff ( int coolArg ) { if ( calculatePossible ) return Json ( CoolMethod ( coolArg ) ) ; else return Json ( new { Calculated = false } ) ; } public void MyTest { var controller = GetControllerInstance ( ) ; var result = controller.CalculateStuff ( ) .Data as dynamic ; Assert.IsTrue ( result.Calculated == false ) ; } | Using dynamic in C # to access field of anonymous type - possible ? |
C_sharp : Is there a more efficient way of doing the following , something just feels wrong about it ? I 'm looking for the most time efficient way of logging logarithmically.Update : Here are my micro benchmark tests.Method1 : Übercoder 's way with keep up with stateMethod2 : My way with the big switch statementMethod3 : Markus Weninger 's way with the nice Math FunctionSince for me 100,000,000 records being read without logging takes around 20 minutes then an extra 4 seconds is nothing . I 'm going with the beautiful Math way of doing things . Mathod3 wins in my scenario . <code> public bool Read ( ) { long count = Interlocked.Increment ( ref _count ) ; switch ( count ) { case 1L : case 10L : case 100L : case 1000L : case 10000L : case 100000L : case 1000000L : case 10000000L : case 100000000L : case 1000000000L : case 10000000000L : case 100000000000L : case 1000000000000L : case 10000000000000L : case 100000000000000L : case 10000000000000000L : case 100000000000000000L : case 1000000000000000000L : _logger.LogFormattable ( LogLevel.Debug , $ '' { count } Rows Read '' ) ; break ; } return _reader.Read ( ) ; } Run time for 100,000,000 iterations averaged over 100 attemptsMethod1 Max : 00:00:00.3253789Method1 Min : 00:00:00.2261253Method1 Avg : 00:00:00.2417223Method2 Max : 00:00:00.5295368Method2 Min : 00:00:00.3618406Method2 Avg : 00:00:00.3904475Method3 Max : 00:00:04.0637217Method3 Min : 00:00:03.2023237Method3 Avg : 00:00:03.3979303 | Logging logarithmically 1 , 10 , 100 , 1000 , etc |
C_sharp : I want to find the closest transaction amount which is closest ( which should be > = transaction amount ) or equal to single transaction amount of the given number , but it should be minimum amount . there will be many combination of data which is > = given number but out of those combination I want minimum transaction number.Let 's say I have given amount is 100 and given transaction amount numbers are as belowScenario 1 : 85 , 35 , 25 , 45 , 16 , 100Scenario 2 : 55 , 75 , 26 , 55 , 99Scenario 3 : 99 , 15 , 66 , 75 , 85 , 88 , 5the expected output of above scenarios are as belowScenario 1 : 100 Scenario 2 : 75 , 26 ( i.e . 75+26=101 ) Scenario 3 : 85 , 15 ( i.e . 85+15=100 ) My current code is given output as belowScenario 1 : 85 , 25Scenario 2 : 55 , 26 , 55Scenario 3 : 99 , 5Here is my code <code> class Program { static void Main ( string [ ] args ) { string input ; decimal transactionAmount ; decimal element ; do { Console.WriteLine ( `` Please enter the transaction amount : '' ) ; input = Console.ReadLine ( ) ; } while ( ! decimal.TryParse ( input , out transactionAmount ) ) ; Console.WriteLine ( `` Please enter the claim amount ( separated by spaces ) '' ) ; input = Console.ReadLine ( ) ; string [ ] elementsText = input.Split ( ' ' ) ; List < decimal > claimAmountList = new List < decimal > ( ) ; foreach ( string elementText in elementsText ) { if ( decimal.TryParse ( elementText , out element ) ) { claimAmountList.Add ( element ) ; } } Solver solver = new Solver ( ) ; List < List < decimal > > results = solver.Solve ( transactionAmount , claimAmountList.ToArray ( ) ) ; foreach ( List < decimal > result in results ) { foreach ( decimal value in result ) { Console.Write ( `` { 0 } \t '' , value ) ; } Console.WriteLine ( ) ; } Console.ReadLine ( ) ; } public class Solver { private List < List < decimal > > mResults ; private decimal minimumTransactionAmount = 0 ; public List < List < decimal > > Solve ( decimal transactionAmount , decimal [ ] elements ) { mResults = new List < List < decimal > > ( ) ; RecursiveSolve ( transactionAmount , 0.0m , new List < decimal > ( ) , new List < decimal > ( elements ) , 0 ) ; return mResults ; } private void RecursiveSolve ( decimal transactionAmount , decimal currentSum , List < decimal > included , List < decimal > notIncluded , int startIndex ) { decimal a = 0 ; for ( int index = startIndex ; index < notIncluded.Count ; index++ ) { decimal nextValue = notIncluded [ index ] ; if ( currentSum + nextValue > = transactionAmount ) { if ( a > = currentSum + nextValue ) { if ( minimumTransactionAmount < currentSum + nextValue ) { minimumTransactionAmount = currentSum + nextValue ; List < decimal > newResult = new List < decimal > ( included ) ; newResult.Add ( nextValue ) ; mResults.Add ( newResult ) ; } a = currentSum + nextValue ; } if ( a == 0 ) { a = currentSum + nextValue ; } } else if ( currentSum + nextValue < transactionAmount ) { List < decimal > nextIncluded = new List < decimal > ( included ) ; nextIncluded.Add ( nextValue ) ; List < decimal > nextNotIncluded = new List < decimal > ( notIncluded ) ; nextNotIncluded.Remove ( nextValue ) ; RecursiveSolve ( transactionAmount , currentSum + nextValue , nextIncluded , nextNotIncluded , startIndex++ ) ; } } } } } | Get closest value from list by summation or exact single value using C # |
C_sharp : I have a method that is defined like such : I would like to do something like : My challenge is , I 'm not sure how to detect whether my propertyValue is a nullable bool or not . Can someone tell me how to do this ? Thank you ! <code> public bool IsValid ( string propertyName , object propertyValue ) { bool isValid = true ; // Validate property based on type here return isValid ; } if ( propertyValue is bool ? ) { // Ensure that the property is true } | Detecting nullable types in C # |
C_sharp : I have started to understand that I do not understand what is going on . There is the following behavior in C # : It will print public void Method ( B a ) instead of public void Method ( D a ) It 's surprising . I suppose that the reason of this behavior is implementation of methods table . CLR does not search methods in the base class if it finds the corresponding method in the current type . I think they were trying to improve performance.But I was completely disappointed with the following code : and it will print public void Method ( B a ) instead of public override void Method ( D a ) It 's awful and very unpredictable.Can anyone explain it ? I suppose that the method table has methods that have been implemented in the current type only ( excluding overriding methods ) and CLR stops looking for the corresponding method as soon as any method that can be called is found . Am I right ? <code> public class Base { public void Method ( D a ) { Console.WriteLine ( `` public void Method ( D a ) '' ) ; } } public class Derived : Base { public void Method ( B a ) { Console.WriteLine ( `` public void Method ( B a ) '' ) ; } } public class B { } public class D : B { } class Program { static void Main ( string [ ] args ) { Derived derived = new Derived ( ) ; D d = new D ( ) ; derived.Method ( d ) ; } } public class Base { public virtual void Method ( D a ) { Console.WriteLine ( `` public void Method ( D a ) '' ) ; } } public class Derived : Base { public override void Method ( D a ) { Console.WriteLine ( `` public override void Method ( D a ) '' ) ; } public void Method ( B a ) { Console.WriteLine ( `` public void Method ( B a ) '' ) ; } } public class B { } public class D : B { } class Program { static void Main ( string [ ] args ) { Derived derived = new Derived ( ) ; D d = new D ( ) ; derived.Method ( d ) ; } } | Overloading methods in inherited classes |
C_sharp : My code below finds all prime numbers below number by creating a list of primes and checking to see if the next potential prime is evenly divisible by any primes in the list.I 'm trying to learn the ins and outs of yield return . Right now I have a List < int > primes that I use inside the function . But I 'm returning the same data via yield return . So my question is Can I access the IEnumerable < int > from inside the function as I am creating it ? So I can remove the List < int > primes altogether . <code> /// < summary > /// Finds all primes below < paramref name= '' number '' / > /// < /summary > /// < param name= '' number '' > The number to stop at < /param > /// < returns > All primes below < paramref name= '' number '' / > < /returns > private static IEnumerable < long > PrimeNumbers ( long number ) { yield return 2 ; List < long > primes = new List < long > ( 2 ) ; for ( long num = 3 ; num < number ; num += 2 ) { //if any prime lower then num divides evenly into num , it is n't a prime //what I 'm doing now if ( ! primes.TakeWhile ( x = > x < num ) .Any ( x = > num % x == 0 ) ) { primes.Add ( num ) ; yield return num ; } //made-up syntax for what I 'd like to do if ( ! this.IEnumerable < long > .TakeWhile ( x = > x < num ) .Any ( x = > num % x == 0 ) ) { yield return num ; } } } | Can you access the IEnumerable as you are yield returning it ? |
C_sharp : I am trying to understand how async/await keywords works . I have a textblock on a WPF window bind to a TextBlockContent string property and a button which trigger on click ChangeText ( ) .Here is my code : From my readings , I understood that ConfigureAwait set to false would allow me to specify that I do not want to save the Current context for the `` rest '' of the Task that needs to be executed after the await keyword.After debugging i realize that when i have this code , sometime the code is running on the Main thread after the line : await GetSomeString ( ) .ConfigureAwait ( false ) ; while i specifically added the configure await.I would have expected it to always run on a different thread that the one it was in before it entered the Task.Can someone help me understand why ? Thank you very much <code> public async void ChangeText ( ) { string mystring = await TestAsync ( ) ; this.TextBlockContent= mystring ; } private async Task < string > TestAsync ( ) { var mystring = await GetSomeString ( ) .ConfigureAwait ( false ) ; mystring = mystring + `` defg '' ; return mystring ; } private Task < string > GetSomeString ( ) { return Task.Run ( ( ) = > { return `` abc '' ; } ) ; } | Why am I still on the Main Thread when I specified ConfigureAwait ( false ) ? |
C_sharp : I 'm attempting to grab a device handle on the Synaptics Touchpad using the Synaptics SDK , specifically using methods in the SYNCTRLLib . However , the SYNCTRL method failed to find it , returning -1.Syn.cs : Program.cs <code> using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using SYNCOMLib ; using SYNCTRLLib ; namespace TP_Test1 { class Syn { SynAPICtrl SynTP_API = new SynAPICtrl ( ) ; SynDeviceCtrl SynTP_Dev = new SynDeviceCtrl ( ) ; SynPacketCtrl SynTP_Pack = new SynPacketCtrl ( ) ; int DeviceHandle ; //Constructor public Syn ( ) { SynTP_API.Initialize ( ) ; SynTP_API.Activate ( ) ; //DeviceHandle == -1 ? Ca n't find device ? DeviceHandle = SynTP_API.FindDevice ( new SynConnectionType ( ) , new SynDeviceType ( ) , 0 ) ; //Below line causing Unhandled Exception SynTP_Dev.Select ( DeviceHandle ) ; SynTP_Dev.Activate ( ) ; SynTP_Dev.OnPacket += SynTP_Dev_OnPacket ; } public void SynTP_Dev_OnPacket ( ) { Console.WriteLine ( SynTP_Pack.FingerState ) ; Console.WriteLine ( SynTP_Pack.X ) ; Console.WriteLine ( SynTP_Pack.Y ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using SYNCOMLib ; using SYNCTRLLib ; namespace TP_Test1 { class Program { static void Main ( string [ ] args ) { Syn mySyn = new Syn ( ) ; mySyn.SynTP_Dev_OnPacket ( ) ; } } } | Synaptics SDK ca n't find device |
C_sharp : I 'm in a little bit of a bind . I 'm working with a legacy system that contains a bunch of delimited strings which I need to parse . Unfortunately , the strings need to be ordered based on the first part of the string . The array looks something likeSo I 'd like the array to order to look likeI thought about doing a 2 dimensional array to grab the first part and leave the string in the second part , but can I mix types in a two dimensional array like that ? I 'm not sure how to handle this situation , can anyone help ? Thanks ! <code> array [ 0 ] = `` 10|JohnSmith|82 '' ; array [ 1 ] = `` 1|MaryJane|62 '' ; array [ 2 ] = `` 3|TomJones|77 '' ; array [ 0 ] = `` 1|MaryJane|62 '' ; array [ 1 ] = `` 3|TomJones|77 '' ; array [ 2 ] = `` 10|JohnSmith|82 '' ; | How to numerically order array of delimited strings in C # |
C_sharp : I 'm facing a deadlock-issue in a piece of code of mine . Thankfully , I 've been able to reproduce the problem in the below example . Run as a normal .Net Core 2.0 Console application.What I 'd expect is the complete sequence as follows : However , the actual sequence stalls on the Thread.Join call : Finally , if I insert a small delay in the MainAsync body , everything goes fine.Why ( where ) the deadlock happens ? NOTE : in the original code I solved using a SemaphoreSlim instead of a TaskCompletionSource , and there 's no problems at all . I only would like to understand where the problem is . <code> class Class2 { static void Main ( string [ ] args ) { Task.Run ( MainAsync ) ; Console.WriteLine ( `` Press any key ... '' ) ; Console.ReadKey ( ) ; } static async Task MainAsync ( ) { await StartAsync ( ) ; //await Task.Delay ( 1 ) ; //a little delay makes it working Stop ( ) ; } static async Task StartAsync ( ) { var tcs = new TaskCompletionSource < object > ( ) ; StartCore ( tcs ) ; await tcs.Task ; } static void StartCore ( TaskCompletionSource < object > tcs ) { _cts = new CancellationTokenSource ( ) ; _thread = new Thread ( Worker ) ; _thread.Start ( tcs ) ; } static Thread _thread ; static CancellationTokenSource _cts ; static void Worker ( object state ) { Console.WriteLine ( `` entering worker '' ) ; Thread.Sleep ( 100 ) ; //some work var tcs = ( TaskCompletionSource < object > ) state ; tcs.SetResult ( null ) ; Console.WriteLine ( `` entering loop '' ) ; while ( _cts.IsCancellationRequested == false ) { Thread.Sleep ( 100 ) ; //some work } Console.WriteLine ( `` exiting worker '' ) ; } static void Stop ( ) { Console.WriteLine ( `` entering stop '' ) ; _cts.Cancel ( ) ; _thread.Join ( ) ; Console.WriteLine ( `` exiting stop '' ) ; } } Press any key ... entering workerentering loopentering stopexiting workerexiting stop Press any key ... entering workerentering stop | What 's causing a deadlock ? |
C_sharp : I have a class Player that implements ICollidable . For debugging purposes I 'm just trying to pass a bunch of ICollidables to this method and do some special stuff when it 's the player . However when I try to do the cast to Player of the ICollidable I get an error telling me that ICollidable does n't have a Color property.Am I not able to make a cast this way or am I doing something wrong ? <code> private Vector2 ResolveCollision ( ICollidable moving , ICollidable stationary ) { if ( moving.Bounds.Intersects ( stationary.Bounds ) ) { if ( moving is Player ) { ( Player ) moving.Color = Color.Red ; } } // ... } | Why is this cast from interface to class failing ? |
C_sharp : I have simple ASP.NET Core WebApi with modeland endpointWhen I make a POST request with bodyorthen model.Value == trueHow to avoid this ? I need some error in this case , because 7676 is not the Boolean value.I found this question and this , but solution is not fit for me , because I have a many models in different projects ( so , it will hard to add JsonConverter attribute , from answer , to all properties ) Also , I 'm looking for any docs that describes this behavior . <code> public class Model { public bool ? Value { get ; set ; } } [ HttpPost ] public async Task < IActionResult > Create ( [ FromBody ] Model model ) { `` Value '' : 7676 } { `` Value '' : 2955454545645645645645645645654534534540 } | Avoid bind any number to bool property |
C_sharp : I recently ran into an interesting issue with changing CASE statements to ISNULL functions in TSQL . The query I was working with is used to get some user attributes and permissions for a website I work on . Previously the query had a number of CASE statements similar to the following : NOTE : a.column1 in the example is of type bit in the table . Also note that the [ CanDoSomething ] result column is sometimes used as a string in the website.The DBA replaced these CASE statements with the ISNULL function : This seems like a fine change , but it caused something unexpected when retrieving the data in C # . With the previous query , the value of the [ CanDoSomething ] column when accessed from a DataTable in C # was 1 or 0 . When we changed to using ISNULL , the value in C # was then changed to true or false which , when treated as a string , are obviously not the same as 1 or 0.The errors this caused have already been addressed . I 'm just curious why ISNULL returns a different value than an equivalent CASE statement and I ca n't seem to find any answers on Google . <code> SELECT ... CASE WHEN a.column1 IS NULL THEN 0 ELSE a.column1 END [ CanDoSomething ] ... FROM a SELECT ... ISNULL ( a.column1 , 0 ) [ CanDoSomething ] ... FROM a | ISNULL vs CASE Return Type |
C_sharp : All C # beginners know that class is a reference type and struct is a value one.Structures are recommended for using as simple storage.They also can implement interfaces , but can not derive from classes and can not play a role of base classes because of rather `` value '' nature.Assume we shed some light on main differences , but there is one haunting me . Have a look at the following code : That is clear as hell - of course we are n't permitted to change object 's own pointer , despite of doing it in C++ is a simple practice . But : Why does it work ? It does look like struct this is not a pointer . If it is true , how does the assignment above work ? Is there a mechanism of automatic cloning ? What happens if there are class inside a struct ? What are the main differences of class and struct this and why it behaves in such way ? <code> public class SampleClass { public void AssignThis ( SampleClass data ) { this = data ; //Will not work as `` this '' is read-only } } public struct SampleStruct { public void AssignThis ( SampleStruct data ) { this = data ; //Works fine } } | C # hack : assignment to `` this '' |
C_sharp : I have a condition with two value . if the condition equal to 0 it return Absent and if equal to 1 it returns present.now I want to add the third value into my condition . if the condition equal to 3 it returns Unacceptable absent.this is my conditions with two value : how can I change the condition ? <code> ( status > = 1 ? `` Present '' : `` Absent '' ) | how can I change this condition to that I want |
C_sharp : Description : I am modifying the ASP.NET Core Web API service ( hosted in Windows Service ) that supports resumable file uploads . This works fine and resumes file uploads in many failure conditions except one described below.Problem : When the service is on ther other computer and the client is on mine and I unplug the cable on my computer , the client detects the absence of network while the service hangs on fileSection.FileStream.Read ( ) . Sometimes the service detects the failure in 8 min , sometimes in 20 , sometimes never.I also noticed that after I unplug cable and stop the client , the service becomes stuck at Read ( ) function and the file size is x KB , but when the service finally detects the exception some time later , it writes additional 4 KB to the file . This is weird because I turned off buffering and the buffer size is 2 KB.Question : How to properly detect the absence of network on the service , or timeout properly , or cancel the requestThe service code : The client code : What I tried : I added these in into config files : Tried to set timeout on the servervar host = new WebHostBuilder ( ) .UseKestrel ( o = > { o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes ( 2 ) ; } ) Used async and non-async Read ( ) Tried with keep alive and withoutTried to abort the request when network was restored : request ? .Abort ( ) ; Tried to set formDataStream.ReadTimeout = 60000 ; <code> public static async Task < List < ( Guid , string ) > > StreamFileAsync ( this HttpRequest request , DeviceId deviceId , FileTransferInfo transferInfo ) { var boundary = GetBoundary ( MediaTypeHeaderValue.Parse ( request.ContentType ) , DefaultFormOptions.MultipartBoundaryLengthLimit ) ; var reader = new MultipartReader ( boundary , request.Body ) ; var section = await reader.ReadNextSectionAsync ( _cancellationToken ) ; if ( section ! = null ) { var fileSection = section.AsFileSection ( ) ; var targetPath = transferInfo.FileTempPath ; try { using ( var outfile = new FileStream ( transferInfo.FileTempPath , FileMode.Append , FileAccess.Write , FileShare.None ) ) { var buffer = new byte [ DefaultCopyBufferSize ] ; int read ; while ( ( read = fileSection.FileStream.Read ( buffer , 0 , buffer.Length ) ) > 0 ) // HANGS HERE { outfile.Write ( buffer , 0 , read ) ; transferInfo.BytesSaved = read + transferInfo.BytesSaved ; } } } catch ( Exception e ) { ... } } } var request = CreateRequest ( fileTransferId , boundary , header , footer , filePath , offset , headers , null ) ; using ( Stream formDataStream = request.GetRequestStream ( ) ) { formDataStream.ReadTimeout = 60000 ; formDataStream.Write ( Encoding.UTF8.GetBytes ( header ) , 0 , header.Length ) ; byte [ ] buffer = new byte [ 2048 ] ; using ( FileStream fs = new FileStream ( filePath , FileMode.Open , FileAccess.Read , FileShare.Read ) ) { fs.Seek ( offset , SeekOrigin.Begin ) ; for ( int i = 0 ; i < fs.Length - offset ; ) { int k = await fs.ReadAsync ( buffer , 0 , buffer.Length ) ; if ( k > 0 ) { await Task.Delay ( 100 ) ; await formDataStream.WriteAsync ( buffer , 0 , k ) ; } i = i + k ; } } formDataStream.Write ( footer , 0 , footer.Length ) ; } var uploadingResult = request.GetResponse ( ) as HttpWebResponse ; private static HttpWebRequest CreateRequest ( Guid fileTransferId , string boundary , string header , byte [ ] footer , string filePath , long offset , NameValueCollection headers , Dictionary < string , string > postParameters ) { var url = $ '' { _BaseAddress } v1/ResumableUpload ? fileTransferId= { fileTransferId } '' ; HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( url ) ; request.Method = `` POST '' ; request.ContentType = `` multipart/form-data ; boundary=\ '' '' + boundary + `` \ '' '' ; request.UserAgent = `` Agent 1.0 '' ; request.Headers.Add ( headers ) ; // custom headers request.Timeout = 120000 ; request.KeepAlive = true ; request.AllowReadStreamBuffering = false ; request.ReadWriteTimeout = 120000 ; request.AllowWriteStreamBuffering = false ; request.ContentLength = CalculateContentLength ( filePath , offset , header , footer , postParameters , boundary ) ; return request ; } | Web API service hangs on reading the stream |
C_sharp : I have the following code : Why does n't the marked line compile ? Does it have something to do with return type not being part of the signature ? But the third line does compile , which makes me guess the compiler turns it into something similiar to the second line ... <code> public static class X { public static C Test < A , B , C > ( this A a , Func < B , C > f ) where C : class { return null ; } } public class Bar { public Bar ( ) { this.Test ( foo ) ; //this does n't compile this.Test ( ( Func < int , string > ) foo ) ; this.Test ( ( int q ) = > `` xxx '' ) ; } string foo ( int a ) { return `` '' ; } } | C # Infer generic type based on passing a delegate |
C_sharp : In my templates I 've got these repeating blocks of content which I want to abstract to a single component : Normally I would use a razor partial view for this , and pass it some variables . However in this case that would mean passing big chunks of html as variables , which does n't seem wise.I 've found this article : http : //www.growingwiththeweb.com/2012/09/custom-helper-for-surrounding-block-in.html , which explains how to create block helpers . It 's a little closer to what I 'm trying to do , but it still requires me to define the html as a string , which is not what I want ( as the amount of html is sizeable enough for it to become unmaintainable ) .From what I understand I ca n't use layouts for this either , because the components occur multiple times on one page . So my question is : how can I abstract the pattern above to a single reusable component , which I can reuse on a page , which accepts multiple areas of html and accepts variables ? <code> < header class= '' Component-header '' > < ! -- Some content here is always the same -- > < ! -- And some content is different for each use -- > < /header > < div class= '' Component-body '' > < ! -- Some content here is always the same -- > < ! -- And some content is different for each use -- > < /div > < footer class= '' Component-footer '' > < ! -- Some content here is always the same -- > < ! -- And some content is different for each use -- > < /footer > | How can I abstract this repeating pattern in ASP.NET MVC 5 ? |
C_sharp : I get an exception System.ArrayTypeMismatchException : Source array type can not be assigned to destination array type for this code snippet : Then I resort to Jon 's answer in Why does `` int [ ] is uint [ ] == true '' in C # , it told me that because of GetArray ( ) returns an Array , the conversion was postponed in runtime , and CLR allows this kind of int [ ] to uint [ ] ( vice versa ) cast . And it actually works fine if I check values after conversion : I would get : However I kind of get confused why it would fail when calling ToList ( ) , as this code below will work fine ? <code> var uints = GetArray ( ) ; if ( uints is int [ ] ) { var list = ( ( int [ ] ) uints ) .ToList ( ) ; // fails when call ToList ( ) } private Array GetArray ( ) { var result = new uint [ ] { uint.MaxValue , 2 , 3 , 4 , 5 } ; return result ; } foreach ( var i in ( ( int [ ] ) units ) ) { System.Console.WriteLine ( i.GetType ( ) ) ; System.Console.WriteLine ( i ) ; } System.Int32-1System.Int322//skipped ... internal class Animal { } internal class Cat : Animal { } var cats = new Cat [ ] { new Cat ( ) , new Cat ( ) } ; List < Animal > animals = ( ( Animal [ ] ) cats ) .ToList ( ) ; //no exception | Exception for calling ToList ( ) after conversion from uint [ ] to int [ ] in C # |
C_sharp : I ran across this issue today and I 'm not understanding what 's going on : Output : I know Cast ( ) is going to result in deferred execution , but it looks like casting it to IEnumerable results in the deferred execution getting lost , and only if the actual implementing collection is an array.Why is the enumeration of the values in the Print method result in the enum being cast to an int for the List < Foo > collection , but not the Foo [ ] ? <code> enum Foo { Zero , One , Two } void Main ( ) { IEnumerable < Foo > a = new Foo [ ] { Foo.Zero , Foo.One , Foo.Two } ; IEnumerable < Foo > b = a.ToList ( ) ; PrintGeneric ( a.Cast < int > ( ) ) ; PrintGeneric ( b.Cast < int > ( ) ) ; Print ( a.Cast < int > ( ) ) ; Print ( b.Cast < int > ( ) ) ; } public static void PrintGeneric < T > ( IEnumerable < T > values ) { foreach ( T value in values ) { Console.WriteLine ( value ) ; } } public static void Print ( IEnumerable values ) { foreach ( object value in values ) { Console.WriteLine ( value ) ; } } 012012ZeroOneTwo012 | Why Does an Array Cast as IEnumerable Ignore Deferred Execution ? |
C_sharp : I do n't understand why the following compiles : My knowledge says that a is assignable to b only if a is of type b or a extends/implements b . But looking at the docs it does n't look like StringValues extends string ( string is a sealed class , therefore it should n't be even possible ) .So I assume this is some implicit conversion going on here , but I ca n't find any info on it . <code> StringValues sv = httpContext.Request.Query [ `` param '' ] ; string s = sv ; | Why is StringValues assignable to String |
C_sharp : In C # I am working with large arrays of value types . I want to be able to cast arrays of compatible value types , for example : I want bitmap2 to share memory with bitmap1 ( they have the same bit representations ) . I do n't want to make a copy.Is there a way to do it ? <code> struct Color { public byte R , G , B , A ; } Color [ ] bitmap1 = ... ; uint [ ] bitmap2 = MagicCast ( bitmap1 ) ; | Casting of arrays in C # |
C_sharp : The following code is illegal : The way things should be done is obviously : But the following is also allowed ( I did n't know this and stumbled upon it by accident ) : I guess the compiler verifies that all fields of the struct have been initialized and therefore allows this code to compile . Still I find it confusing with how the rest of the language works . After all , you are basically using an unassigned variable in the C # way of seeing things.Things get even more confusing if you consider the following code : The following code is illegal becuase in this case we have n't assigned all visible fields : Visible is the key word here , because if MyStruct were to be defined in a referenced assembly then c is not visible and the compiler will not complain and the previous code would be perfectly valid . Confusing again.Can somebdoy please explain why its allowed to initialize a struct in C # in such manner ? Why not disallow it completely so there is a more unified experience when dealing with any type of value in the language ? EDIT 1 : I made a mistake in the last example . The compiler will be happy only if the not visible field is of reference type . Even more confusing . Is this last case a known bug in the compiler or is there a sane reason for it to work the way it does ? Changed last example to a valid case.EDIT 2 : I 'm still a litte befuddled with how value-type initialization works . Why is n't the following allowed for instance : The way I see it , there is little doubt that all fields MyStruct are initialized . I can see the reasoning of why this would n't be allowed if properties were not auto-implemented as it is arguably possible that the setters do not garantee that all fields are set . But in auto-implemented properties the compiler knows with 100 % certainty that the fields will be set if the properties are ( after all its code that the compiler generates for you ) .Finally , a small theoretical case with evidently no practical use : Then why is n't this allowed : I find both cases similar in concept and I 'd expect them both to work the same way in C # . I still do n't understand why this seemingly useless differentiation in the way value-type variables can be initialized and what is it 's practical use ( on top of the inconsistencies I explained in the first part of my question ) <code> public struct MyStruct { public MyStruct ( int a , int b ) { this.a = a ; this.b = b ; } public int a ; public int b ; } //now I want to cache for whatever reason the default value of MyStructMyStruct defaultValue ; ... if ( foo ! = defaultValue ) //use of unassigned variable ... MyStruct defaultValue = default ( MyStruct ) //or new MyStruct ( ) ; ... if ( foo ! = defaultValue ) //compiler is happy MyStruct defaultValue ; defaultValue.a = 0 ; defaultValue.b = 0 ; ... if ( foo ! = defaultValue ) //legal public struct MyStruct { public MyStruct ( int a , int b ) { this.a = a ; this.b = b ; this.c = ( a + b ) .ToString ( ) ; } public int a ; public int b ; internal string c ; } MyStruct defaultValue ; defaultValue.a = 0 ; defaultValue.b = 0 ; ... if ( foo ! = defaultValue ) //use of unassigned variable ... struct MyStruct { public int A { get ; set ; } //Auto-implemented property public int B { get ; set ; } //Auto-implemented property } MyStruct defaultValue ; defaultValue.A = 0 ; //use of unassigned variable ... defaultValue.B = 0 ; struct MyUselessStruct { } MyUselessStruct defaultValue ; Console.WriteLine ( defaultValue.ToString ( ) ) ; //hehe did I get away with using an unassigned variable ? Object object ; if ( object == null ) ... . //use of unassigned variable | Confused with little used Value Type initialization |
C_sharp : I 've read the answers for Class with indexer and property named `` Item '' , but they do not explain why can I have a class with multiple indexers , all of them creating Item property and get_Item/set_Item methods ( of course working well , as they are different overloads ) , but I can not have an explicit Item property.Consider the code : For two indexers there are four methods created : I 'd expect my property to createThese overloads are generally acceptable , but somehow the compiler wo n't let me create such a property.Please note that I do n't need a way to rename the indexer etc , this is known - I need an explanation . This answer : https : //stackoverflow.com/a/5110449/882200 does n't explain why I can have multiple indexers . <code> namespace Test { class Program { static void Main ( string [ ] args ) { } public int this [ string val ] { get { return 0 ; } set { } } public string this [ int val ] //this is valid { get { return string.Empty ; } set { } } public int Item { get ; set ; } //this is not valid } } Int32 get_Item ( String val ) Void set_Item ( String val , Int32 value ) String get_Item ( Int32 val ) Void set_Item ( Int32 val , String value ) Int32 get_Item ( ) Void set_Item ( Int32 value ) | `` Item '' property along with indexer |
C_sharp : Given this example code : Which returns : -1What does the first arrow operator mean ? By specification it does not look like an expression body or a lambda operator.Is there any reference in the C # language specification about this usage ? <code> enum op { add , remove } Func < op , int > combo ( string head , double tail ) = > ( op op ) = > op == op.add ? Int32.Parse ( head ) + Convert.ToInt32 ( tail ) : Int32.Parse ( head ) - Convert.ToInt32 ( tail ) ; Console.WriteLine ( combo ( `` 1 '' , 2.5 ) ( op.remove ) ) ; | What does the first arrow operator in this Func < T , TReturn > mean ? |
C_sharp : In Haskell , we have the filterM function . The source code for it is : Translating from do notation : To the best of my understanding , > > = on lists in Haskell and SelectMany on IEnumerablein C # are the same operation and so , this code should work just fine : But it does n't work . Can anyone point me to what 's wrong here ? <code> filterM : : ( Monad m ) = > ( a - > m Bool ) - > [ a ] - > m [ a ] filterM _ [ ] = return [ ] filterM p ( x : xs ) = doflg < - p xys < - filterM p xsreturn ( if flg then x : ys else ys ) filterM : : ( Monad m ) = > ( a - > m Bool ) - > [ a ] - > m [ a ] filterM _ [ ] = return [ ] filterM p ( x : xs ) = p x > > = \flg - > filterM p xs > > = \ys - > return ( if flg then x : ys else ys ) public static IEnumerable < IEnumerable < A > > WhereM < A > ( this IEnumerable < A > list , Func < A , IEnumerable < bool > > predicate ) { // Like Haskells null if ( list.Null ( ) ) { return new List < List < A > > { new List < A > ( ) } ; } else { var x = list.First ( ) ; var xs = list.Tail ( ) ; // Like Haskells tail return new List < IEnumerable < A > > { predicate ( x ) .SelectMany ( flg = > xs.WhereM ( predicate ) .SelectMany ( ys = > { if ( flg ) { return ( new List < A > { x } ) .Concat ( ys ) ; } else { return ys ; } } ) ) } ; } } | Monadic Programming in C # |
C_sharp : I have just noticed that the following code returns true : I have read the Mathf.Approximately Documentation and it states that : Approximately ( ) compares two floats and returns true if they are within a small value ( Epsilon ) of each other.And Mathf.Epsilon Documentation states that : anyValue + Epsilon = anyValue anyValue - Epsilon = anyValue 0 + Epsilon = Epsilon 0 - Epsilon = -Epsilon As a result , I ran the following code , expecting it to be false , but it also returns true.By the way : Q : Based on that evidence , can I safely say that Mathf.Approximately is not correctly implemented according to its documentation* ? ( * and as a result , I should move to different solutions , such as the one in Floating point comparison functions for C # ) <code> Mathf.Approximately ( 0.0f , float.Epsilon ) ; // true Mathf.Approximately ( 0.0f , 2.0f * float.Epsilon ) ; // true Mathf.Approximately ( 0.0f , 2.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 3.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 4.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 5.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 6.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 7.0f * float.Epsilon ) ; // trueMathf.Approximately ( 0.0f , 8.0f * float.Epsilon ) ; // falseMathf.Approximately ( 0.0f , 9.0f * float.Epsilon ) ; // false | Is Mathf.Approximately ( 0.0f , float.Epsilon ) == true its correct behavior ? |
C_sharp : I have a mock being created like this : The intellisense for the Setup method says this : `` Specifies a setup on the mocked type for a call to a void returning method . `` But the mocked method p.GetBytes ( ) does not return void , it returns a byte array . Alternatively another Setup method is defined as Setup < > , and I can create my mock like this : The intellisense of this Setup method states : `` Specifies a setup on the mocked type for a call to a value returning method . `` ..Whichever method I choose , it compiles and tests OK . So , I 'm confused as to which way I should be doing this . What is the difference between .Setup ( ) and .Setup < > ( ) , and am I doing it right ? The docs for Moq are somewhat lacking , shall we say . : ) <code> var mock = new Mock < IPacket > ( MockBehavior.Strict ) ; mock.Setup ( p = > p.GetBytes ( ) ) .Returns ( new byte [ ] { } ) .Verifiable ( ) ; var mock = new Mock < IPacket > ( MockBehavior.Strict ) ; mock.Setup < byte [ ] > ( p = > p.GetBytes ( ) ) .Returns ( new byte [ ] { } ) .Verifiable ( ) ; | Moq confusion - Setup ( ) v Setup < > ( ) |
C_sharp : I 'm trying to deserialize a part of a json file that represents this class . where two properties are optional : Text and Parameters . I 'd like them to be populated with default values.The problem is that I can not figure out how to make it work for both of them . If I use the DefaultValueHandling.Populate option then Text will be populated but Parameters remains null . If I use DefaultValueHandling.Ignore then it 'll be the other way around . If I set [ DefaultValue ( typeof ( Dictionary < string , string > ) ) ] on the Parameters property it 'll crash.Quesiton : Is there a way to make it work for all properties ? I 'd like to have it not-null so that I do n't have to check it in other part of the code.Demo of what I have tried : <code> public class Command { [ JsonRequired ] public string Name { get ; set ; } [ DefaultValue ( `` Json ! '' ) ] public string Text { get ; set ; } // [ DefaultValue ( typeof ( Dictionary < string , string > ) ) ] public Dictionary < string , string > Parameters { get ; set ; } = new Dictionary < string , string > ( ) ; } void Main ( ) { var json = @ '' [ { `` '' Name '' '' : `` '' Hallo '' '' , `` '' Text '' '' : `` '' Json ! '' '' } , { `` '' Name '' '' : `` '' Hallo '' '' , } ] '' ; var result = JsonConvert.DeserializeObject < Command [ ] > ( json , new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate , ObjectCreationHandling = ObjectCreationHandling.Reuse } ) ; result.Dump ( ) ; // LINQPad } | How can I populate an optional collection property with a default value ? |
C_sharp : I am writing a helper method for conveniently setting the Name of a Thread : It 's working as intended . ReSharper , however , claims that the condition is always false and the corresponding code is heuristically unreachable . That 's wrong . A Thread.Name is always null until a string is assigned.So , why does ReSharper think it is ? And is there some way to tell ReSharper it is n't ( other than // ReSharper disable ... ) ? I 'm using ReSharper 5.1.3 . <code> public static bool TrySetName ( this Thread thread , string name ) { try { if ( thread.Name == null ) { thread.Name = name ; return true ; } return false ; } catch ( InvalidOperationException ) { return false ; } } | Why does ReSharper think that `` thread.Name == null '' is always false ? |
C_sharp : Imagine that I have a several Viewer component that are used for displaying text and they have few modes that user can switch ( different font presets for viewing text/binary/hex ) . What would be the best approach for managing shared objects - for example fonts , find dialog , etc ? I figured that static class with lazily initialized objects would be OK , but this might be the wrong idea . <code> static class ViewerStatic { private static Font monospaceFont ; public static Font MonospaceFont { get { if ( monospaceFont == null ) //TODO read font settings from configuration monospaceFont = new Font ( FontFamily.GenericMonospace , 9 , FontStyle.Bold ) ; return monospaceFont ; } } private static Font sansFont ; public static Font SansFont { get { if ( sansFont == null ) //TODO read font settings from configuration sansFont = new Font ( FontFamily.GenericSansSerif , 9 , FontStyle.Bold ) ; return sansFont ; } } } | Managing of shared resources between classes ? |
C_sharp : When you were a kid , did you ever ask your parents how to spell something and they told you to go look it up ? My first impression was always , `` well if could look it up I wouldnt need help spelling it '' . ( yeah yeah I know phonetics ) ... anyway , I was just looking at some code and I found an example like : I can figure out what this operation does , but obviously , I cant google for ? or : and I cant find them when searching for `` c # operators '' , LINQ , Lambda expressions , etc . So I have to ask this silly question so I can go start reading about it.What are these operators ? <code> txtbx.CharacterCasing = ( checkbox.Checked ) ? CharacterCasing.Upper : CharacterCasing.Normal ; | Learning by example - terminology ( ? , : , etc ) |
C_sharp : I have a problem with some overloaded methods and I will try to give a simple implementation of it.So here is a class contains two methods below : and this my entity : Here is where I 'm utilizing it : The problem is that I just have two methods with same name and different arguments so , based on OOP polymorphism concepts , I expect .NET to understand my desired method.But it 's obvious .NET can not understand it because the instance form of Expression < Func < TEntity , Boolean > > and Func < TEntity , Boolean > are the same and this the compile-time error which .NET raises : The question is : how can I prevent this compile-time error ? My preference is to do not touch the way I 'm calling GetData ( ) at this line : <code> public class MyRepo < TEntity > { public List < TEntity > GetData ( Expression < Func < TEntity , Boolean > > expression ) { //Do something } public List < TEntity > GetData ( Func < TEntity , Boolean > whereClause ) { //Do something } } public class MyEntity { public int Id { get ; set ; } public string Name { get ; set ; } } { ... MyRepo < MyEntity > myRepo = new MyRepo < MyEntity > ( ) ; myRepo.GetData ( x = > x.Id == 1 ) ; // The ambiguity point ... } The call is ambiguous between the following methods or properties : 'Program.MyRepo < TEntity > .GetData ( Expression < Func < TEntity , bool > > ) ' and 'Program.MyRepo < TEntity > .GetData ( Func < TEntity , bool > ) ' myRepo.GetData ( x = > x.Id == 1 ) ; | Misunderstanding of .NET on overloaded methods with different parameters ( Call Ambiguous ) |
C_sharp : I have an optimization problem where I have 5 variables : A , B1 , B2 , C1 , C2 . I am trying to optimize these 5 variables to get the smallest root sum square value I can . I have a few optimization techniques that are working ok , but this one in particular is giving me some trouble.I want to explore all 32 options of changing the variables and pick the smallest RSS value . What I mean by this is each variable can either be +/- an increment . And each choice leads to 2 more choices , with 5 variables thats 32 choices . ( 2^5 ) To clarify , I am not adding my variables : A , B1 , B2 etc to each other , I am incrementing / decrementing them by an arbitrary amount . A +/- X , B1+/- X2 , etc . And I am trying to figure out which combination of incrementation/ decrementation of my 5 variables will return the lowest Root sum square value.So on and so forth till all 5 levels are complete . I am not sure even where to start to attempt to solve this . What kind of data structure would be best for storing this ? Is it an iterative , or a recursive solution . I do n't need the answer to the problem , rather somewhere to look or somewhere to start . Thank you again for taking the time to look at this.To clarify further confusion this is my optimization method . I ahve 5 variables , and 5 increments , each increment matches to a variable . ( a , b , c , d , e , f ) -- - > ( incA , incB , incC , indD , incE , incF ) I want to find the best combination of +/- incX to X ( x being one of the 5 variables ) ie : the solution might be something like : a+incA , B-incB , c+incC , d+incD , e+incE , f-incF.There are 32 possibilities of combinations , after reading through all the answers below I have settled on this possible algorithm . ( see my answer below ) make edits and questions as necessary . This is not a perfect algorithm , it is for clarification and ease of understanding , i know it can be condensed . <code> A +/ \- B1 B1 +/\- +/\- B2 B2 B2 B2 //Settign all possible solutions to be iterated through later.double [ ] levelA = new double [ 2 ] ; double [ ] levelB = new double [ 2 ] ; double [ ] levelC = new double [ 2 ] ; double [ ] levelD = new double [ 2 ] ; double [ ] levelE = new double [ 2 ] ; levelA [ 0 ] = a + incA ; levelA [ 1 ] = a - incA ; levelB [ 0 ] = b + incB ; levelB [ 1 ] = b - incB ; levelC [ 0 ] = c + incC ; levelC [ 1 ] = c - incC ; levelD [ 0 ] = d + incD ; levelD [ 1 ] = d - incD ; levelE [ 0 ] = e + incE ; levelE [ 1 ] = e - incE ; double [ ] rootSumAnswers = new double [ 32 ] ; int count = 0 ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( int k = 0 ; k < 2 ; k++ ) { for ( int j = 0 ; j < 2 ; j ++ ) { for ( int n = 0 ; n < 2 ; n++ ) { for ( int m = 0 ; m < 2 ; m++ ) { rootSumAnswers [ count++ ] = calcRootSum ( levelA [ i ] , levelB [ k ] , levelC [ j ] , levelD [ n ] , levelE [ m ] ) ; } } } } } //Finally , i find the minimum of my root sum squares and make that change permanent , and do this again . | How do I iterate between 32 binary options ? |
C_sharp : During an research the purpose of this reassignment possibility with structs I ran into following puzzle : Why it is needed to do this = default ( ... ) at the beginning of some struct constructor . It 's actually zeroes already zeroed memory , is n't it ? See an example from .NET core : <code> public CancellationToken ( bool canceled ) { this = default ( CancellationToken ) ; if ( canceled ) { this.m_source = CancellationTokenSource.InternalGetStaticSource ( canceled ) ; } } | What the purpose of this = default ( ... ) in struct constructor ? |
C_sharp : I understand that the following C # code : compiles to : But what does it mean that it compiles to that ? I was under the impression that C # code compiles directly into CIL ? <code> var evens = from n in nums where n % 2 == 0 select n ; var evens = nums.Where ( n = > n % 2 == 0 ) ; | C # Compiled to CIL |
C_sharp : Here is the code extracted of the SingleOrDefault function : I 'm wondering to know if there is any reason why after finding more than one element in the loop , there is no break statement to prevent looping the rest of the list . In anyways , an error will occurs . For a big list where more than one item is found at the beginning , I think it would make a uge difference . <code> public static TSource SingleOrDefault < TSource > ( this IEnumerable < TSource > source , Func < TSource , bool > predicate ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; if ( predicate == null ) throw Error.ArgumentNull ( `` predicate '' ) ; TSource result = default ( TSource ) ; long count = 0 ; foreach ( TSource element in source ) { if ( predicate ( element ) ) { result = element ; checked { count++ ; } } } switch ( count ) { case 0 : return default ( TSource ) ; case 1 : return result ; } throw Error.MoreThanOneMatch ( ) ; } | Optimization in the SingleOrDefault function of Linq |
C_sharp : Just out of curiosity , why does the compiler treat an unconstrained generic type any differently than it would typeof ( object ) ? In the above , casting `` T thing '' to Bar results in a compiler error . Casting `` object thing '' to Bar however is something the compiler lets me do , at my own risk of course.What I do n't see is why . In .net object after all is a catch-all and the run-time type could be a boxed value or an object of any type . So I do n't see what logical reason there is for the compiler to differentiate between the two cases . The best I can do is something like `` the programmer would expect the compiler to do type checking with generic types , but not with object '' . : ) Is that all there is to it ? Btw , I am aware that I can still get my cast done in the Foo case , by simply writingI just want to understand why the compiler does this ... <code> class Bar { } class Foo { void foo ( object thing ) { ( ( Bar ) thing ) .ToString ( ) ; } } class Foo < T > { void foo ( T thing ) { ( ( Bar ) thing ) .ToString ( ) ; } } ( ( Bar ) ( object ) thing ) .ToString ( ) ; | The rules of generics and type constraints |
C_sharp : I have a question regarding await/async and using async methods in slightly different scenarios than expected , for example not directly awaiting them . For example , Lets say I have two routines I need to complete in parallel where both are async methods ( they have awaits inside ) . I am using await TAsk.WhenAll ( ... ) which in turn expects some sort of list of tasks to wait for . What I did is something like this : This seems overly elaborate to me , in the sense that I am creating async tasks whose sole purpose is to invoke another task . Ca n't I just use tasks which are returned from the async method state engine ? Yet , I am failing to do that since compiler treats every direct mention of async method as an invocation point : If its like this , it seems to synchronously calls one after another , and if I place await in front of methods , it is no longer a Task . Is there some rule book on how async methods should be handled outside plain await ? <code> await Task.WhenAll ( new Task [ ] { Task.Run ( async ( ) = > await internalLoadAllEmailTargets ( ) ) , Task.Run ( async ( ) = > await internalEnumerateInvoices ( ) ) } ) ; // this does n't seem to work ok await Task.WhenAll ( new Task [ ] { internalLoadAllEmailTargets ( ) , internalEnumerateInvoices ( ) } ) ; | await/async and going outside the box |
C_sharp : I have the following enum defined . I have used underscores as this enum is used in logging and i do n't want to incur the overhead of reflection by using custom attribute.We use very heavy logging . Now requirement is to change `` LoginFailed_InvalidAttempt1 '' to `` LoginFailed Attempt1 '' . If i change this enum , i will have to change its value across application . I can replace underscore by a space inside logging SP . Is there any way by which i can change this without affecting whole application.Please suggest . <code> public enum ActionType { None , Created , Modified , Activated , Inactivated , Deleted , Login , Logout , ChangePassword , ResetPassword , InvalidPassword , LoginFailed_LockedAccount , LoginFailed_InActiveAccount , LoginFailed_ExpiredAccount , ForgotPassword , LoginFailed_LockedAccount_InvalidAttempts , LoginFailed_InvalidAttempt1 , LoginFailed_InvalidAttempt2 , LoginFailed_InvalidAttempt3 , ForgotPassword_InvalidAttempt1 , ForgotPassword_InvalidAttempt2 , ForgotPassword_InvalidAttempt3 , SessionTimeOut , ForgotPassword_LockedAccount , LockedAccount , ReLogin , ChangePassword_Due_To_Expiration , ChangePassword_AutoExpired } | How to change enum definition without impacting clients using it in C # |
C_sharp : I am looking to setup something very similar to transaction scope which creates a version on a service and will delete/commit at the end of scope . Every SQL statement ran inside the transaction scope internally looks at some connection pool / transaction storage to determine if its in the scope and reacts appropriately . The caller does n't need to pass in the transaction to every call . I am looking for this functionality.Here is a little more about it : https : //blogs.msdn.microsoft.com/florinlazar/2005/04/19/transaction-current-and-ambient-transactions/ Here is the basic disposable class : I want the ability for all the code I 've written thus far to not have any concept of being in a version . I just want to include a simpleVersion = GetCurrentVersionWithinScope ( ) at the lowest level of the code.What is the safest way of implementing something like this with little risk of using the wrong version if there are multiple instances in memory simultaneously running.My very naive approach would be find if there is a unique identifier for a block of memory a process is running in . Then store the current working version to a global array or concurrent dictionary . Then in the code where I need the current version , I use its block of memory identifier and it maps to the version that was created.Edit : Example of usage : <code> public sealed class VersionScope : IDisposable { private readonly GeodatabaseVersion _version ; private readonly VersionManager _versionManager ; public VersionScope ( Configuration config ) { _versionManager = new VersionManager ( config ) ; _version = _versionManager.GenerateTempVersion ( ) ; _versionManager.Create ( _version ) ; _versionManager.VerifyValidVersion ( _version ) ; _versionManager.ServiceReconcilePull ( ) ; _versionManager.ReconcilePull ( _version ) ; } public void Dispose ( ) { _versionManager.Delete ( _version ) ; } public void Complete ( ) { _versionManager.ReconcilePush ( _version ) ; } } using ( var scope = new VersionScope ( _config ) ) { AddFeature ( ) ; // This has no concept of scope passed to it , and could error out forcing a dispose ( ) without a complete ( ) scope.Complete ( ) ; } | Transaction scope similar functionality |
C_sharp : I get a red line under my await in my code saying : The type arguments for method 'TaskAwaiter < TResult > System.WindowsRuntimeSystemExtensions.GetAwaiter < TResult > ( this Windows.Foundation.IAsyncOperation 1 ) ' can not be inferred from the usage . Try specifying the type arguments explicitlyThough the code compiles and seems to work fine , I just wonder what this means ? ( English is not my first language , so I might just not understand the message ) <code> private async void Init ( ) { var settings = new I2cConnectionSettings ( I2CAddress ) ; settings.BusSpeed = I2cBusSpeed.StandardMode ; var aqs = I2cDevice.GetDeviceSelector ( I2CControllerName ) ; var dis = await DeviceInformation.FindAllAsync ( aqs ) ; _device = await I2cDevice.FromIdAsync ( dis [ 0 ] .Id , settings ) ; _isInited = true ; } | TaskAwaiter can not be inferred from the usage |
C_sharp : I have an Azure Function with a service bus trigger : In 99.9 % of the invocations , the trigger successfully resolves to a subscription on Azure Service Bus . But sometimes , I see the following error in my log : It seems that the service bus trigger can not resolve the connection variable from settings.I tried to add a debugging filter to my function , in order to find out what is going on : When an error is logged in my function , the properties added to FunctionExecutionContext are automatically added to the log message . The weird thing here is that in the scenario where Azure Functions throw this exception , the property values are resolved and shown in the log message.What could be the cause of this ? I 've experienced multiple problems with resolving settings from Azure Functions , so maybe it 's a general problem ? <code> public static async Task Run ( [ ServiceBusTrigger ( `` % inputTopicName % '' , `` % subscriptionName % '' , AccessRights.Manage , Connection = `` connection '' ) ] string mySbMsg ) Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function : UptimeChecker -- - > System.ArgumentException : The argument connectionString is null or white space.Parameter name : connectionString at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.FunctionInvocationFilterInvoker.d__9.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__24.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__23.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__22.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd ( Task task ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__16.MoveNext ( ) -- - End of inner exception stack trace -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__16.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__13.MoveNext ( ) public class DebuggingFilter : FunctionInvocationFilterAttribute { public override Task OnExecutingAsync ( FunctionExecutingContext executingContext , CancellationToken cancellationToken ) { executingContext.Properties.Add ( `` connection '' , ConfigurationManager.AppSettings [ `` connection '' ] ) ; executingContext.Properties.Add ( `` inputTopicName '' , ConfigurationManager.AppSettings [ `` inputTopicName '' ] ) ; executingContext.Properties.Add ( `` subscriptionName '' , ConfigurationManager.AppSettings [ `` subscriptionName '' ] ) ; return base.OnExecutingAsync ( executingContext , cancellationToken ) ; } } | Connection string is sometimes not available in ServiceBusTrigger |
C_sharp : Why can´t we raise an event with a custom implementation , while it is possible without them ? See this code : You see both events are declared within my class . While target.AnotherEvent ( ... ) compiles just fine , target.MyEvent ( ... ) does not : The Event MyEvent can only appear on the left hand side of += or -=.I Know an event is just a delegate with an add- and remove-method . So AnotherEvent is translated by the compiler to an add- and a remove-method : So I assume the call to AnotherEvent is replaced by the compiler to a call to the private delegate , which was _AnotherEvent ( ... ) .Did I get this right ? Are there any docs about why the second call works while the former does not ? Or at least any description about what the compiler does here ? <code> public class Program { private EventHandler myEvent ; public event EventHandler MyEvent { add { myEvent += value ; } remove { myEvent -= value ; } } public event EventHandler AnotherEvent ; public static void Main ( ) { var target = new Program ( ) ; target.MyEvent ( null , null ) ; // ERROR CS0079 target.AnotherEvent ( null , null ) ; // compiles } } private EventHandler _AnotherEvent ; public event EventHandler AnotherEvent { add { _AnotherEvent += value ; } remove { _AnotherEvent -= value ; } } | Why can´t we raise event with accessors ? |
C_sharp : I 'm having hard time understanding the following C # code . This code was taken from Pro ASP.NET MVC 2 Framework by Steven Sanderson . The code esentially creates URLs based on a list of categories . Here 's the code : A lot of stuff is going on here . I 'm guessing it 's defining a function that expects two parameters of type string , and NavLink . Then I see the Lambda categoryName = > new NavLink etc ... . I think all it 's doing is creating an instance of NavLink.The function is then called in the same Controller action : I can tell that it 's making a list of NavLink . I do n't understand why Steven Sanderson wrote it this way though . Could n't he have written something like : Is there an advantage to doing it Steven 's way versus my way ? <code> Func < string , NavLink > makeLink = categoryName = > new NavLink { Text = categoryName ? ? `` Home '' , RouteValues = new RouteValueDictionary ( new { controller = `` Products '' , action = `` List '' , category = categoryName , page = 1 } ) , IsSelected = ( categoryName == currentCategory ) // Place home link on top List < NavLink > navLinks = new List < NavLink > ( ) ; navLinks.Add ( makeLink ( null ) ) ; // Add link for each distinct category var categories = productsRepository.Products.Select ( x = > x.Category.Name ) ; foreach ( string categoryName in categories.Distinct ( ) .OrderBy ( x = > x ) ) navLinks.Add ( makeLink ( categoryName ) ) ; var categories = productsRepository.Products.Select ( x = > x.Category.Name ) ; foreach ( string categoryName in categories.Distinct ( ) .OrderBy ( x = > x ) ) { var newlink = new Navlink { text = categoryName , RouteValues = new RouteValueDictionary ( new { controller = `` Products '' , action = `` List '' , category = categoryName , page = 1 } ) , IsSelected = ( categoryName == currentCategory ) } navLinks.Add ( newlink ) ; } | Why did they use this C # syntax to create a list of links in ASP.NET MVC 2 ? |
C_sharp : I have following code : and use it as following : Is there any way to define something like this : I used Expression < Func < T , bool > > to use it as where clause in my linq to entities query ( EF code first ) . <code> public class MyClass < T > { Expression < Func < T , bool > > Criteria { get ; set ; } } public class Customer { //.. public string Name { get ; set ; } } var c = new MyClass < Customer > ( ) ; c.Criteria = x.Name.StartWith ( `` SomeTexts '' ) ; ? p = x= > x.Customer.Name ; var c = new MyClass < Customer > ( ) ; c.Criteria = p = > p.StartWith ( `` SomeTexts '' ) ; | Define part of an Expression as a variable in c # |
C_sharp : Can a static function in a static class which uses yield return to return an IEnumerable safely be called from multiple threads ? Will each thread that calls this always receive a reference to each object in the collection ? In my situation listOfFooClassWrappers is written to once at the beginning of the program , so I do n't need to worry about it changing during a call to this function . I wrote a simple program to test this , and I did n't see any indication of problems , but threading issues can be difficult to suss out and it 's possible that the issue simply did n't show up during the runs that I did.EDIT : Is yield return in C # thread-safe ? is similar but addresses the situation where the collection is modified while being iterated over . My concern has more to do with multiple threads each getting only part of the collection due to a hidden shared iterator given that the class and method are both static . <code> public static IEnumerable < FooClass > FooClassObjects ( ) { foreach ( FooClassWrapper obj in listOfFooClassWrappers ) { yield return obj.fooClassInst ; } } | Is yield return reentrant ? |
C_sharp : Recently I decided to investigate the degree of randomness of a globally unique identifier generated with the Guid.NewGuid method ( which is also the scope of this question ) . I documented myself about pseudorandom numbers , pseudorandomness and I was dazzled to find out that there are even random numbers generated by radioactive decay . Anyway , I 'll let you discover by yourselves more details about such interesting lectures.To continue to my question , another important thing to know about GUID 's is : V1 GUIDs which contain a MAC address and time can be identified by the digit `` 1 '' in the first position of the third group of digits , for example { 2F1E4FC0-81FD-11DA-9156-00036A0F876A } . V4 GUIDs use the later algorithm , which is a pseudo-random number . These have a `` 4 '' in the same position , for example { 38A52BE4-9352-453E-AF97-5C3B448652F0 } .To put it in a sentence , a Guid will always have the digit 4 ( or 1 , but out of our scope ) as one of its components.For my GUID randomness tests I decided to count the number of digits inside some increasingly large collection of GUIDs and compare it with the statistical probability of digit occurrence , expectedOccurrence . Or at least I hope I did ( please excuse any statistical formula mistakes , I only tried my best guesses to calculate the values ) . I used a small C # console application which is listed below.The output for the above program is : So , even if the theoretical occurrence is expected to be 63.671875 % , the actual values are somewhere around ~63.2 % .How can this difference be explained ? Is there any error in my formulas ? Is there any other `` obscure '' rule in the Guid algorithm ? <code> class Program { static char [ ] digitsChar = `` 0123456789 '' .ToCharArray ( ) ; static decimal expectedOccurrence = ( 10M * 100 / 16 ) * 31 / 32 + ( 100M / 32 ) ; static void Main ( string [ ] args ) { for ( int i = 1 ; i < = 10 ; i++ ) { CalculateOccurrence ( i ) ; } } private static void CalculateOccurrence ( int counter ) { decimal sum = 0 ; var sBuilder = new StringBuilder ( ) ; int localCounter = counter * 20000 ; for ( int i = 0 ; i < localCounter ; i++ ) { sBuilder.Append ( Guid.NewGuid ( ) ) ; } sum = ( sBuilder.ToString ( ) ) .ToCharArray ( ) .Count ( j = > digitsChar.Contains ( j ) ) ; decimal actualLocalOccurrence = sum * 100 / ( localCounter * 32 ) ; Console.WriteLine ( String.Format ( `` { 0 } \t { 1 } '' , expectedOccurrence , Math.Round ( actualLocalOccurrence,3 ) ) ) ; } } 63.671875 63.27363.671875 63.30063.671875 63.33163.671875 63.24263.671875 63.29263.671875 63.26963.671875 63.29263.671875 63.26663.671875 63.25463.671875 63.279 | Estimating the digits occurrence probability inside a GUID |
C_sharp : i 'm trying to print `` p '' to the screen every second.when I run this : it does n't print at all.But when I run this : Its printing without waiting at all . Can somebody please explain this to me and suggest a fix ? <code> while ( true ) Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` p '' ) ; while ( true ) Console.WriteLine ( `` p '' ) ; Thread.Sleep ( 1000 ) ; | waiting for a second every time in a loop in c # using Thread.Sleep |
C_sharp : I have been playing with WPF for a while and I came across an interesting thing . When I bind DateTime object to the Label 's content then I see locally formatted representation of the date . However , when I bind to the TextBlock 's Text property then I actually see English one.It seems that TextBlock is using some sort of converter whereas Label is just calling ToString method but I am not sure about it.If so , why does n't the Label use the converter too ? Is there any reason it works this way ? I provide a short sample to let you guys inspect what 's going on : <code> // MainWindow.xaml < Window x : Class= '' BindConversion.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < StackPanel HorizontalAlignment= '' Center '' Margin= '' 3 '' > < StackPanel > < Label Content= '' { Binding Dt } '' / > < TextBlock Text= '' { Binding Dt } '' / > < /StackPanel > < /StackPanel > < /Window > // MainWindow.xaml.csusing System ; using System.Windows ; namespace BindConversion { /// < summary > /// Interaction logic for MainWindow.xaml /// < /summary > public partial class MainWindow : Window { public DateTime Dt { get ; set ; } public MainWindow ( ) { InitializeComponent ( ) ; DataContext = this ; Dt = DateTime.Now ; } } } | Culture difference between Label and TextBlock |
C_sharp : I have a method I used in MvvmCross 4.x that was used with the NotificationCompat.Builder to set a PendingIntent of a notification to display a ViewModel when the notification is clicked by the user . I 'm trying to convert this method to use the MvvmCross 5.x IMvxNavigationService but ca n't see how to setup the presentation parameters , and get a PendingIntent using the new navigation API.The RouteNotificationViewModel does appear when I click the notification but Prepare and Initialize are not being called . What is necessary to convert this method from MvvmCross 4.x style of navigation to MvvmCross 5.x style of navigation ? <code> private PendingIntent RouteNotificationViewModelPendingIntent ( int controlNumber , RouteNotificationContext notificationContext , string stopType ) { var request = MvxViewModelRequest < RouteNotificationViewModel > .GetDefaultRequest ( ) ; request.ParameterValues = new Dictionary < string , string > { { `` controlNumber '' , controlNumber.ToString ( ) } , { `` notificationContext '' , notificationContext.ToString ( ) } , { `` stopType '' , stopType } } ; var translator = Mvx.Resolve < IMvxAndroidViewModelRequestTranslator > ( ) ; var intent = translator.GetIntentFor ( request ) ; intent.SetFlags ( ActivityFlags.NewTask | ActivityFlags.ClearTask ) ; return PendingIntent.GetActivity ( Application.Context , _notificationId , intent , PendingIntentFlags.UpdateCurrent ) ; } | How do I get PendingIntent using the MvvmCross 5 IMvxNavigationService ? |
C_sharp : I 'm making a jquery clone for C # . Right now I 've got it set up so that every method is an extension method on IEnumerable < HtmlNode > so it works well with existing projects that are already using HtmlAgilityPack . I thought I could get away without preserving state ... however , then I noticed jQuery has two methods .andSelf and .end which `` pop '' the most recently matched elements off an internal stack . I can mimic this functionality if I change my class so that it always operates on SharpQuery objects instead of enumerables , but there 's still a problem.With JavaScript , you 're given the Html document automatically , but when working in C # you have to explicitly load it , and you could use more than one document if you wanted . It appears that when you call $ ( 'xxx ' ) you 're essentially creating a new jQuery object and starting fresh with an empty stack . In C # , you would n't want to do that , because you do n't want to reload/refetch the document from the web . So instead , you load it once either into a SharpQuery object , or into an list of HtmlNodes ( you just need the DocumentNode to get started ) .In the jQuery docs , they give this exampleI do n't have an initializer method because I ca n't overload the ( ) operator , so you just start with sq.Find ( ) instead , which operates on the root of the document , essentially doing the same thing . But then people are going to try and write sq.Find ( ) on one line , and then sq.Find ( ) somewhere down the road , and ( rightfully ) expect it to operate on the root of the document again ... but if I 'm maintaining state , then you 've just modified the context after the first call.So ... how should I design my API ? Do I add another Init method that all queries should begin with that resets the stack ( but then how do I force them to start with that ? ) , or add a Reset ( ) that they have to call at the end of their line ? Do I overload the [ ] instead and tell them to start with that ? Do I say `` forget it , no one uses those state-preserved functions anyway ? `` Basically , how would you like that jQuery example to be written in C # ? sq [ `` ul.first '' ] .Find ( `` .foo '' ) ... Downfalls : Abuses the [ ] property.sq.Init ( `` ul.first '' ) .Find ( `` .foo '' ) ... Downfalls : Nothing really forces the programmer to start with Init , unless I add some weird `` initialized '' mechanism ; user might try starting with .Find and not get the result he was expecting . Also , Init and Find are pretty much identical anyway , except the former resets the stack too.sq.Find ( `` ul.first '' ) .Find ( `` .foo '' ) ... .ClearStack ( ) Downfalls : programmer may forget to clear the stack.Ca n't do it.end ( ) not implemented.Use two different objects.Perhaps use HtmlDocument as the base that all queries should begin with , and then every method thereafter returns a SharpQuery object that can be chained . That way the HtmlDocument always maintains the initial state , but the SharpQuery objects may have different states . This unfortunately means I have to implement a bunch of stuff twice ( once for HtmlDocument , once for the SharpQuery object ) .new SharpQuery ( sq ) .Find ( `` ul.first '' ) .Find ( `` .foo '' ) ... The constructor copies a reference to the document , but resets the stack . <code> $ ( 'ul.first ' ) .find ( '.foo ' ) .css ( 'background-color ' , 'red ' ) .end ( ) .find ( '.bar ' ) .css ( 'background-color ' , 'green ' ) .end ( ) ; | How to design my C # jQuery API such that it is n't confusing to use ? |
C_sharp : I 'm quite new to Linq . I have something like this : This works fine but for obvious reasons I do n't want the split ( ) method to be called twice.How can I do that ? Thanks for all your responses : ) , but I can only choose one . <code> dict = fullGatewayResponse.Split ( ' , ' ) .ToDictionary ( key = > key.Split ( '= ' ) [ 0 ] , value = > value.Split ( '= ' ) [ 1 ] ) | Linq call a function only once in one statement |
C_sharp : Let 's say there are these generic types in C # : and these concrete types : Now the definition of PersonRepository is redundant : the fact that the KeyType of Person is int is stated explicitly , although it can be deduced from the fact that Person is a subtype of Entity < int > .It would be nice to be able to define IPersonRepository like this : and let the compiler figure out that the KeyType is int . Is it possible ? <code> class Entity < KeyType > { public KeyType Id { get ; private set ; } ... } interface IRepository < KeyType , EntityType > where EntityType : Entity < KeyType > { EntityType Get ( KeyType id ) ; ... } class Person : Entity < int > { ... } interface IPersonRepository : IRepository < int , Person > { ... } interface IPersonRepository : IRepository < Person > { ... } | Generic Type Inference in C # |
C_sharp : I have the following sample code.According to MSDN : Exists property : true if the file or directory exists ; otherwise , false.Why Exists returns false after directory has been created ? Am I missing something ? <code> private DirectoryInfo PathDirectoryInfo { get { if ( _directoryInfo == null ) { // Some logic to create the path // var path = ... _directoryInfo = new DirectoryInfo ( path ) ; } return _directoryInfo ; } } public voide SaveFile ( string filename ) { if ( ! PathDirectoryInfo.Exists ) { PathDirectoryInfo.Create ( ) ; } // PathDirectoryInfo.Exists returns false despite the folder has been created . bool folderCreated = PathDirectoryInfo.Exists ; // folderCreated == false // Save the file // ... } | Creating Directory does n't update the Exists property to true |
C_sharp : This is mostly academic - but I was looking at the implementation of Equals ( ) for ValueTypes . The source code is here : http : //referencesource.microsoft.com/ # mscorlib/system/valuetype.cs # 38The code that caught my eye was this : FastEqualsCheck ( ) is declared as follows : My understanding is that the ' [ MethodImplAttribute ( MethodImplOptions.InternalCall ) ] ' indicates that this is implemented in the CLR ( source not available ) , but I thought I would be able to call it directly from my code . When I try , I get a SecurityExceptionECall methods must be packaged into a system module.Can I make these calls myself ( or are they meant for internal consumption only ) ? If I can call them directly , what is the appropriate way of doing so ? <code> // if there are no GC references in this object we can avoid reflection // and do a fast memcmp if ( CanCompareBits ( this ) ) return FastEqualsCheck ( thisObj , obj ) ; [ System.Security.SecuritySafeCritical ] [ ResourceExposure ( ResourceScope.None ) ] [ MethodImplAttribute ( MethodImplOptions.InternalCall ) ] private static extern bool FastEqualsCheck ( Object a , Object b ) ; | How Can I Call FastEqualsCheck ( ) ? |
C_sharp : I wanted to add a nice shadow to my borderless form , and the best way I found to do it with minimal performance loss is to use DwmExtendFrameIntoClientArea . However , this seems to be causing Windows to draw a classic title bar over the window , but it is non-functional ( ie . the glitch is merely graphical ) .This is the code I am using : I have tried setting ALLOW_NCPAINT to 1 , and I even tried returning 0 when the window receives WM_NCPAINT without calling DefWndProc , but it made no difference.Is there a way to resolve this weird issue while still using DwmExtendFrameIntoClientArea ? <code> int v = ( int ) DWMNCRENDERINGPOLICY.DWMNCRP_ENABLED ; NativeApi.DwmSetWindowAttribute ( Handle , DwmWindowAttribute.NCRENDERING_POLICY , ref v , sizeof ( int ) ) ; int enable = 0 ; NativeApi.DwmSetWindowAttribute ( Handle , DwmWindowAttribute.ALLOW_NCPAINT , ref enable , sizeof ( int ) ) ; MARGINS margins = new MARGINS ( ) { leftWidth = 0 , topHeight = 0 , rightWidth = 0 , bottomHeight = 1 } ; NativeApi.DwmExtendFrameIntoClientArea ( Handle , ref margins ) ; | Prevent Win32 from drawing classic title bar |
C_sharp : I find myself creating loads of the properties following the pattern : Is there an easy way to automate creating of these properties ? Usually I : type the field , including the readonly keywordSelect `` initialize from constructor parametersSelect `` encapsulate '' Is it possible to make it quicker ? <code> private readonly MyType sth ; public MyClass ( MyType sth ) //class constructor { this.sth = sth ; } public MyType Sth { get { return sth ; } } | How can I automate creating immutable properties with ReSharper ? |
C_sharp : I just came across this weird 'behavior ' of the Garbage Collector concerning System.Threading.ThreadLocal < T > that I ca n't explain . In normal circumstances , ThreadLocal < T > instances will be garbage collected when they go out of scope , even if they are n't disposed properly , except in the situation where they are part of a cyclic object graph.The following example demonstrates the problem : Although not calling Dispose is not good practice , but it 's the CLR 's design to clean up resources ( by calling the finalizer ) eventually , even if Dispose is not called.Why does ThreadLocal behave differently in this regard and can cause memory leaks when not disposed properly in case of a cyclic graph ? Is this by design ? And if so , where is this documented ? Or is this a bug in the CLR 's GC ? ( Tested under .NET 4.5 ) . <code> public class Program { public class B { public A A ; } public class A { public ThreadLocal < B > LocalB ; } private static List < WeakReference > references = new List < WeakReference > ( ) ; static void Main ( string [ ] args ) { for ( var i = 0 ; i < 1000 ; i++ ) CreateGraph ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; // Expecting to print 0 , but it prints 1000 Console.WriteLine ( references.Count ( c = > c.IsAlive ) ) ; } static void CreateGraph ( ) { var a = new A { LocalB = new ThreadLocal < B > ( ) } ; a.LocalB.Value = new B { A = a } ; references.Add ( new WeakReference ( a ) ) ; // If either one of the following lines is uncommented , the cyclic // graph is broken , and the programs output will become 0 . // a.LocalB = null ; // a.LocalB.Value = null ; // a.LocalB.Value.A = null ; // a.LocalB.Dispose ( ) ; } } | Memory leak when ThreadLocal < T > is used in cyclic graph |
C_sharp : I know there 's a couple similarly worded questions on SO about permutation listing , but they do n't seem to be quite addressing really what I 'm looking for . I know there 's a way to do this but I 'm drawing a blank . I have a flat file that resembles this format : Now here 's the trick : I want to create a list of all possible permutations of these rows , where a comma-separated list in the row represents possible values . For example , I should be able to take an IEnumerable < string > representing the above to rows as such : This should generate the following collection of string data : This to me seems like it would elegantly fit into a recursive method , but apparently I have a bad case of the Mondays and I ca n't quite wrap my brain around how to approach it . Some help would be greatly appreciated . What should GetPermutations ( IEnumerable < string > , string ) look like ? <code> Col1|Col2|Col3|Col4|Col5|Col6a|b , c , d|e|f|g , h|i . . . IEnumerable < string > row = new string [ ] { `` a '' , `` b , c , d '' , `` e '' , `` f '' , `` g , h '' , `` i '' } ; IEnumerable < string > permutations = GetPermutations ( row , delimiter : `` / '' ) ; a/b/e/f/g/ia/b/e/f/h/ia/c/e/f/g/ia/c/e/f/h/ia/d/e/f/g/ia/d/e/f/h/i | Split and join multiple logical `` branches '' of string data |
C_sharp : To declare float numbers we need to put ' f ' for floats and 'd ' for doubles . Example : It is said that C # defaults to double if a floating point literal is omitted.My question , is what prevents a modern language like ' C # ' to 'DEFAULTS ' to the left hand side variable type ? After all , the compiler can see the entire line of code.Is this for historic reasons in compiler design ? or Is there something I 'm not getting . <code> float num1 = 1.23f ; // float stored as floatfloat num2 = 1.23 ; // double stored as float . The code wo n't compile in C # . | C # floating point literals : Why compiler does not DEFAULTS to the left hand side variable type |
C_sharp : I was doing a refactoring of class and thought of moving 100 lines in a separate method . Like this : At calling method of Compiler throws exception : Readonly local variable can not be used as an assignment target for doc and mem.Edit : here only i adding content in pdf document in another method . so i need to pass same doc object , right ? so why ca n't i use ref or out param.Technically using defies the purpose of ref param here . Tried to look on MSDN : How the objects become read only at calling of Method ? Within the scope object is alive and you can do whatever you want . <code> using iTextSharp.text ; using iTextSharp.text.pdf ; class Program { private static void Main ( string [ ] args ) { Document doc = new Document ( iTextSharp.text.PageSize.LETTER , 10 , 10 , 42 , 35 ) ; using ( var mem = new MemoryStream ( ) ) { using ( PdfWriter wri = PdfWriter.GetInstance ( doc , mem ) ) { doc.Open ( ) ; AddContent ( ref doc , ref wri ) ; doc.Close ( ) ; File.WriteAllBytes ( @ '' C : \testpdf.pdf '' , mem.ToArray ( ) ) ; } } } public static void AddContent ( ref Document doc , ref PdfWriter writer ) { var header = new Paragraph ( `` My Document '' ) { Alignment = Element.ALIGN_CENTER } ; var paragraph = new Paragraph ( `` Testing the iText pdf . `` ) ; var phrase = new Phrase ( `` This is a phrase but testing some formatting also . \nNew line here . `` ) ; var chunk = new Chunk ( `` This is a chunk . `` ) ; doc.Add ( header ) ; doc.Add ( paragraph ) ; doc.Add ( phrase ) ; doc.Add ( chunk ) ; } } A ReadOnly property has been found in a context that assigns a value to it . Only writable variables , properties , and array elements can have values assignedto them during execution . | IDisposable objects as ref param to method |
C_sharp : Very short question but I could n't find a solution on the web right now.Will 1 + 2 be performed during run- or compile-time ? Reason for asking : I think most people sometimes use a literal without specifying why it has been used or what it means because they do not want to waste a bit performance by running the calculation and I believe the calculate happens during compiletime and has no effect on performance : instead of <code> int test = 1 + 2 ; int nbr = 31536000 ; //What the heck is that ? int nbr = 365 * 24 * 60 * 60 ; //I guess you know what nbr is supposed to be now ... | Are arithmetic operations on literals in C # evaluated at compile time ? |
C_sharp : I have a WPF application with a number of comboboxes that tie together . When I switch comboboxx # 1 , combobox # 2 switches , etc.Here is the xaml for the 2 comboboxes : CboDivision gets populated at the beginning and doesnt need a reset . HEre is the code that calls the change in division , which should trigger a change in customer : When I do an index change it calls a backgroundworker which calls the following code : The problem is that i am unable to switch selections on CboDivision and have CboCustomerList clear and reload new values into it . Is it the way I 'm binding the values in the xaml ? How can I have a change in CboDivision cause a clearing of CboCustomerList items , then the execution of the filling routine ? i am currently resetting the combobox with : but this just appends the new cbocustomerlist query to the endI also tried but that just returns a null reference error after the box is refilled and the user selects an item . <code> < ComboBox Grid.Row= '' 1 '' Height= '' 23 '' HorizontalAlignment= '' Right '' Margin= '' 0,12,286,0 '' ItemsSource= '' { Binding } '' Name= '' CboDivision '' VerticalAlignment= '' Top '' Width= '' 120 '' SelectionChanged= '' CboDivision_SelectionChanged '' / > < ComboBox Height= '' 23 '' HorizontalAlignment= '' Right '' Margin= '' 0,9,32,0 '' Name= '' CboCustomerList '' ItemsSource= '' { Binding } '' VerticalAlignment= '' Top '' Width= '' 120 '' SelectionChanged= '' CboCustomerList_SelectionChanged '' Grid.Row= '' 1 '' / > private void CboDivision_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { division = CboDivision.SelectedValue.ToString ( ) ; CboCustomerList.ItemsSource = null ; BackgroundWorker customerWorker = new BackgroundWorker ( ) ; customerWorker.DoWork += new DoWorkEventHandler ( FillCustomers ) ; customerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler ( customerWorker_RunWorkerCompleted ) ; FillCustomers ( null , null ) ; } private void FillCustomers ( object sender , DoWorkEventArgs e ) { string connectionString = Settings.Default.ProdConnectionString ; SqlConnection connection = new SqlConnection ( connectionString ) ; SqlCommand SqlCmd = new SqlCommand ( ) ; Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait ; SqlCmd.CommandType = CommandType.StoredProcedure ; SqlCmd.Parameters.Add ( `` @ division '' , SqlDbType.NVarChar ) .Value = division ; SqlCmd.Connection = connection ; SqlCmd.CommandText = `` sp_GetCustomers '' ; SqlDataReader reader = null ; connection.Open ( ) ; reader = SqlCmd.ExecuteReader ( ) ; List < string > result = new List < string > ( ) ; while ( reader.Read ( ) ) { result.Add ( reader [ `` NAME '' ] .ToString ( ) ) ; } e.Result = result ; } CboCustomerList.SelectedIndex = -1 ; CboCustomerList.Items.Clear ( ) | Clearing and refilling a bound combo box |
C_sharp : The Stackoverflow API is returning an unexpected response when C # to create a HTTP GET request.If I paste http : //api.stackoverflow.com/1.1/users/882993 into the browsers address bar I get the correct JSON response : If I attempt to perform the same action in code : I get the response : <code> { `` total '' : 1 , `` page '' : 1 , `` pagesize '' : 30 , `` users '' : [ { `` user_id '' : 882993 , `` user_type '' : `` registered '' , `` creation_date '' : 1312739131 , `` display_name '' : `` Jack '' , `` reputation '' : 1926 , `` email_hash '' : `` 69243d90e50d9e0b3e025517fd23d1da '' , `` age '' : 23 , `` last_access_date '' : 1358087009 , `` website_url '' : `` http : //jtbrown.me.uk '' , `` location '' : `` Birmingham , United Kingdom '' , `` about_me '' : `` < p > Student. < /p > \n '' , `` question_count '' : 68 , `` answer_count '' : 79 , `` view_count '' : 115 , `` up_vote_count '' : 98 , `` down_vote_count '' : 3 , `` accept_rate '' : 94 , `` association_id '' : `` d64187a3-bf66-4a4d-8e87-6ef18f0397e3 '' , `` user_questions_url '' : `` /users/882993/questions '' , `` user_answers_url '' : `` /users/882993/answers '' , `` user_favorites_url '' : `` /users/882993/favorites '' , `` user_tags_url '' : `` /users/882993/tags '' , `` user_badges_url '' : `` /users/882993/badges '' , `` user_timeline_url '' : `` /users/882993/timeline '' , `` user_mentioned_url '' : `` /users/882993/mentioned '' , `` user_comments_url '' : `` /users/882993/comments '' , `` user_reputation_url '' : `` /users/882993/reputation '' , `` badge_counts '' : { `` gold '' : 0 , `` silver '' : 7 , `` bronze '' : 34 } } ] } HttpWebRequest Request = WebRequest.Create ( `` http : //api.stackoverflow.com/1.1/users/882993 '' ) as HttpWebRequest ; using ( HttpWebResponse Response = Request.GetResponse ( ) as HttpWebResponse ) { // Get the response stream StreamReader Reader = new StreamReader ( Response.GetResponseStream ( ) ) ; // Console application output StackWidget.Text = Reader.ReadToEnd ( ) ; } �\b\0\0\0\0\0\0u�Ms�0��� ` 8��Ӏ2�rl���� # ���J4��^\t # �p�g���j�����|�n�G/ڎ�7p���� $ �5\r���f�y�v�����\ '' F ( ���֛0���J� ? { �������� $ ���e� ! T�-~+�� @ _p���j\fb� ( �f�my��dt�ӄ� ! AV\t����G ' $ \ '' ؉i { ; ��X��5H9�z ( �\ '' GQ < � ] ��TA9\b�Z��T��U % ��� ; �n�-����* : ʚ��w�c��yU|P�m�S��M\r�� ? ��O��� @ �m������\n'\b� } /�ь�.7E\a�*���uaDN @ �k��N�L�zU\n�3� : DJ^S { ���� $ K�\ '' �ɮ : f�.� ) �P�\f�Qq\f�C�/�k*UN=�A\r�,7���.���p�9�3�jVT7�� ) ܬH\fYzW�4kGX�_|�AK��q�KU�GGw��^�j����D���7�\\��Ƴr , �N�yzno�F\ro�̄ [ � & i { afڵ��ٗ , ���c\\~=l > 6�\0U�F\0\0 | Stackoverflow API response format |
C_sharp : Why does the OR operator in vb and C # give different results.http : //dotnetfiddle.net/wC9AgGhttp : //dotnetfiddle.net/g4tLQ9 <code> Console.WriteLine ( 0x2 | 0x80000000 ) ; output 2147483650 Console.WriteLine ( & H2 Or & H80000000 ) output -2147483646 | C # vs VB.NET bitwise OR |
C_sharp : There 's far too much code to paste into a question here so I have linked to a public gist.https : //gist.github.com/JimBobSquarePants/cac72c4e7d9f05f13ac9I have an animated gif encoder as part of an image library that I maintain and there is something wrong with it.If I attempt to upload any gif that have been output by the class to twitter I get an internal server error , though if I pass them through http : //ezgif.com/ resizing to the same dimensions first they upload properly.If I upload the image to http : //www.smiliegenerator.us/ to analyse I get the following error which indicates to me that I have some sort of buffer offset error though I do n't know where.Would anyone here be able to tell me what has gone wrong ? The full library is hosted on Github here https : //github.com/JimBobSquarePants/ImageProcessor/tree/V2 <code> unknown block type 0 at *different position each time* | Animated gif encoder error |
C_sharp : Given the output of query : What would you consider the neatest way to detect if a file is in the queryResult ? Here is my lame try with LINQ : There must be an more elegant way to figure out the result . <code> var queryResult = from o in objects where ... select new { FileName = o.File , Size = o.Size } string searchedFileName = `` hello.txt '' ; var hitlist = from file in queryResult where file.FileName == searchedFileName select file ; var contains = hitlist.Count ( ) > 0 ; | Writing 'CONTAINS ' query using LINQ |
C_sharp : According to the Constraints on Type Parameters ( C # Programming Guide ) documentation it says , and I quote : When applying the where T : class constraint , avoid the == and ! = operators on the type parameter because these operators will test for reference identity only , not for value equality . This is the case even if these operators are overloaded in a type that is used as an argument . The following code illustrates this point ; the output is false even though the String class overloads the == operator.With the following example : However , ReSharper ( I 've just started using the demo/trial version to see if it is any worth to me ) gives a hint/tip to do null-checking of parameters like so : ( T is constrained with where T : class , new ( ) ) Can I safely follow ReSharper without running into problems that the C # documentation is trying to tell me to avoid ? <code> public static void OpTest < T > ( T s , T t ) where T : class { System.Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` target '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( `` target '' ) ; string s2 = sb.ToString ( ) ; OpTest < string > ( s1 , s2 ) ; } public Node ( T type , Index2D index2D , int f , Node < T > parent ) { if ( type == null ) throw new ArgumentNullException ( `` type '' ) ; if ( index2D == null ) throw new ArgumentNullException ( `` index2D '' ) ; if ( parent == null ) throw new ArgumentNullException ( `` parent '' ) ; } | Avoid == and ! = operators on generic type parameters , but can it compare with null ? |
C_sharp : I have this simple code : This interface should be covariant on T , and i 'm using it this way : Note the constraint for T to implement IComposite.The synchronization method takes an IReader < IComposite > in input : The compiler tells me it can not convert from IReader < T > to IReader < IComposite > despite the constraint on T and the covariance of IReader.Is there something i 'm doing wrong here ? The compiler should be able to verify the constraint and the covariance should let me use my IReader < T > as an IReader < Icomposite > , is n't it ? Thanks . <code> public interface IReader < out T > { IEnumerable < T > GetData ( ) ; } private static Func < bool > MakeSynchroFunc < T > ( IReader < T > reader ) where T : IComposite { return ( ) = > Synchronize ( reader ) ; } private static bool Synchronize ( IReader < IComposite > reader ) { // ... ... } | .NET Covariance |
C_sharp : I happen to see a code something like this.When and why do we need this kind of dynamic type casting for parameters ? <code> function ( ( dynamic ) param1 , param2 ) ; | dynamic type casting in parameter in c # |
C_sharp : Sometimes I want to add more typesafety around raw doubles . One idea that comes up a lot would be adding unit information with the types . For example , In the case like above , where there is only a single field , will the JIT be able to optimize away this abstraction in all cases ? What situations , if any , will result in extra generated machine instructions compared to similar code using an unwrapped double ? Any mention of premature optimization will be downvoted . I 'm interested in knowing the ground truth.Edit : To narrow the scope of the question , here are a couple of scenarios of particular interest ... These are some of the things I can think of off the top of my head . Of course , an excellent language designer like @ EricLippert will likely think of more scenarios . So , even if these typical use cases are zero-cost , I still think it would be good to know if there is any case where the JIT does n't treat a struct holding one value , and the unwrapped value as equivalent , without listing each possible code snippet as it 's own question <code> struct AngleRadians { public readonly double Value ; /* Constructor , casting operator to AngleDegrees , etc omitted for brevity ... */ } // 1 . Is the value-copy constructor zero cost ? // Is ... var angleRadians = new AngleRadians ( myDouble ) ; // The same as ... var myDouble2 = myDouble ; // 2 . Is field access zero cost ? // Is ... var myDouble2 = angleRadians.Value ; // The same as ... var myDouble2 = myDouble ; // 3 . Is function passing zero cost ? // Is calling ... static void DoNaught ( AngleRadians angle ) { } // The same as ... static void DoNaught ( double angle ) { } // ( disregarding inlining reducing this to a noop | Is a struct wrapping a primitive value type a zero cost abstraction in C # ? |
C_sharp : Basically , I have keywords like sin ( and cos ( in a textbox , which I want to have behave like a single character.When I mention the entire string below it is referring to the group of characters ( for example `` sin ( `` ) Using sin ( as an example : If the caret was in this position ( behind the s ) : If you pressed del , it would remove the entire string . If the right arrow key was pressed the caret would jump to after the ( .If the caret was in this position ( after the ( ) : If backspace was pressed , the entire string would be removed . If the left arrow key was pressed , the caret would jump to behind the s.EDIT : Thanks to John Skeet who pointed this out.Selecting any substring of the group of characters ( for example si from sin ( ) should select the entire string.Sorry if it is difficult to understand , what I have in mind is a bit difficult to put into words.EDIT 2 : Thanks to Darksheao for providing me the answer for the backspace and delete keys . I relocated the delete segment to the PreviewKeyDown event , as it does not work with the KeyPress Event.EDIT 3 : Using the charCombinations way of doing things , here is how I did the implementation for the left and right keys : All that remains is the mouse implementation . Anyone ? I also realised that the user may use the mouse to place the caret in the middle of one of these strings , so when that happens the mouse needs to be moved to the start of the string . <code> # region Rightcase Keys.Right : { s = txt.Substring ( caretLocation ) ; foreach ( string combo in charCombinations ) { if ( s.StartsWith ( combo ) ) { textBox1.SelectionStart = caretLocation + combo.Length - 1 ; break ; } } break ; } # endregion # region Leftcase Keys.Left : { s = txt.Substring ( 0 , caretLocation ) ; foreach ( string combo in charCombinations ) { if ( s.EndsWith ( combo ) ) { textBox1.SelectionStart = caretLocation - combo.Length + 1 ; break ; } } break ; } # endregion | C # Make a group of characters in a textbox behave like one character |
C_sharp : When using C # Strongnames on DLLs and using the InternalsVisibleTo tags andwhen the public key uses SHA256 ( or SHA512 ) We 're noticing that the compile process fails as if the InternalsVisibleTo tags were never even declared . The error we get is MyInternalClass is inaccessible due to its protection level < snip > When the public key uses sha1 ( in step # 3 above ) , the compile process works perfectly with no issues and the internals are exposed properly to the test project . The way we 're creating the strongname keys isAnd the way we 're exposing the project 's internals to it 's test project is : which we stick inside the Properties\AssemblyInfo.cs of the MyProject project.Question : How to use SHA256 or better in the strongname process ? EDIT : Or is this a bug in the VS2012 tools ? Platform , Tools : VS2012 ( Update 3 ) , .NET 4.5 , Windows 8 x64 <code> sn -k 4096 SignKey.snksn -p SignKey.snk SignKeyPublic.snk sha256sn -tp SignKeyPublic.snk [ assembly : InternalsVisibleTo ( `` MyProjectTest , PublicKey=LongPublicKeyHere '' ) ] | StrongNaming with InternalsVisibleTo tag fails when SHA256 used |
C_sharp : I have a frustrating problem with a bit of code and do n't know why this problem occurs . When running without Code optimization then the result is as expected . _cursorLeft and left as far as _cursorTop and top are equal.But when I run it with Code optimization both values _cursorLeft and _cursorTop become bizzare : I found out 2 workarounds : set _cursorLeft and _cursorTop to 0 instead of -1let Interlocked.Exchange take the value from left resp . topBecause workaround # 1 does not match my needs I ended up with workaround # 2 : But where does this bizarre behavior comes from ? And is there a better workaround/solution ? [ Edit by Matthew Watson : Adding simplified repro : ] [ Edit by me : ] I figured out another even shorter example : Unless you do n't use Optimization or set _intToExchange to a value in the range of ushort you would not recognize the problem . <code> //// .NET FRAMEWORK v4.6.2 Console Appstatic void Main ( string [ ] args ) { var list = new List < string > { `` aa '' , `` bbb '' , `` cccccc '' , `` dddddddd '' , `` eeeeeeeeeeeeeeee '' , `` fffff '' , `` gg '' } ; foreach ( var item in list ) { Progress ( item ) ; } } private static int _cursorLeft = -1 ; private static int _cursorTop = -1 ; public static void Progress ( string value = null ) { lock ( Console.Out ) { if ( ! string.IsNullOrEmpty ( value ) ) { Console.Write ( value ) ; var left = Console.CursorLeft ; var top = Console.CursorTop ; Interlocked.Exchange ( ref _cursorLeft , Console.CursorLeft ) ; Interlocked.Exchange ( ref _cursorTop , Console.CursorTop ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Left : { 0 } _ { 1 } '' , _cursorLeft , left ) ; Console.WriteLine ( `` Top : { 0 } _ { 1 } '' , _cursorTop , top ) ; } } } aaLeft : 2 _ 2Top : 0 _ 0bbbLeft : 3 _ 3Top : 3 _ 3 aaLeft : -65534 _ 2Top : -65536 _ 0bbLeft : -65533 _ 3Top : -65533 _ 3 private static int _cursorLeft = -1 ; private static int _cursorTop = -1 ; public static void Progress ( string value = null ) { lock ( Console.Out ) { if ( ! string.IsNullOrEmpty ( value ) ) { Console.Write ( value ) ; // OLD - does NOT work ! //Interlocked.Exchange ( ref _cursorLeft , Console.CursorLeft ) ; //Interlocked.Exchange ( ref _cursorTop , Console.CursorTop ) ; // NEW - works great ! var left = Console.CursorLeft ; var top = Console.CursorTop ; Interlocked.Exchange ( ref _cursorLeft , left ) ; // new Interlocked.Exchange ( ref _cursorTop , top ) ; // new } } } class Program { static void Main ( ) { int actual = -1 ; Interlocked.Exchange ( ref actual , Test.AlwaysReturnsZero ) ; Console.WriteLine ( `` Actual value : { 0 } , Expected 0 '' , actual ) ; } } static class Test { static short zero ; public static int AlwaysReturnsZero = > zero ; } class Program { private static int _intToExchange = -1 ; private static short _innerShort = 2 ; // [ MethodImpl ( MethodImplOptions.NoOptimization ) ] static void Main ( string [ ] args ) { var oldValue = Interlocked.Exchange ( ref _intToExchange , _innerShort ) ; Console.WriteLine ( `` It was : { 0 } '' , oldValue ) ; Console.WriteLine ( `` It is : { 0 } '' , _intToExchange ) ; Console.WriteLine ( `` Expected : { 0 } '' , _innerShort ) ; } } | C # Code optimization causes problems with Interlocked.Exchange ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.