lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I am rendering some simple text to a PDF in C # using Telerik : This works great locally.I 've set up an Azure app service , and I am getting the following error when I run reportProcessor.RenderReport ( ) : I feel like this might be an issue with the way I 've configured my Azure app service . Here is my configuration... | using Telerik.Reporting ; using Telerik.Reporting.Processing ... ReportProcessor reportProcessor = new ReportProcessor ( ) ; InstanceReportSource instanceReportSource = new InstanceReportSource ( ) ; instanceReportSource.ReportDocument = new MyReport ( ) ; RenderingResult result = reportProcessor.RenderReport ( `` PDF ... | Telerik Reporting produces pdf locally , but not on Azure |
C# | I am currently working with .Net 2.0 and have an interface whose generic type is used to define a method 's return type . Something likeMy problem is that some classes that implement this interface do not really need to return anything.In Java you can use java.lang.Void for this purpose , but after quite a bit of searc... | interface IExecutor < T > { T Execute ( ) { ... } } | java.lang.Void in C # ? |
C# | We have a legacy .NET Remoting-based app . Our client client libary currently supports only synchronous operations . I would like to add asynchronous operations with TPL-based async Task < > methods.As proof of concept , I have set up a basic remoting server/client solution based a modified version of these instruction... | public class Client : MarshalByRefObject { private IServiceClass service ; public delegate double TimeConsumingCallDelegate ( ) ; public void Configure ( ) { RemotingConfiguration.Configure ( `` client.exe.config '' , false ) ; var wellKnownClientTypeEntry = RemotingConfiguration.GetRegisteredWellKnownClientTypes ( ) .... | Wrap .NET Remoting async method in TPL Task |
C# | I was looking at the IL code of a valid method with Reflector and I 've run into this : Instructions with the suffix .s are supposed to take an int8 operand , and sure enough this should be the case with Leave_S as well . However , 0x0103 is 259 , which exceeds the capacity of an int8 . The method somehow works , but w... | L_00a5 : leave.s L_0103 L_00a5 : leave.s L_0003 switch ( instruction.OpCode.OperandType ) { ... case OperandType.ShortInlineBrTarget : instruction.Operand = ( sbyte ) ( il.ReadByte ( ) + il.position ) ; break ; ... } switch ( instruction.OpCode.OperandType ) { ... case OperandType.ShortInlineBrTarget : instruction.Oper... | IL short-form instructions are n't short ? |
C# | I started a UWP app on a laptop running Visual Studio 2015 Update 3 . All was well and good , able to run and test it on both my laptop and my phone with no issues at all.I added the project to Source Control ( private Git server ) and pulled the repo on my home PC . The project opens in VS2015 Update 3 on my PC and I ... | An unhandled exception of type 'System.UnauthorizedAccessException ' occurred in MyUwpApp.exeAdditional information : Access is denied . ( Exception from HRESULT : 0x80070005 ( E_ACCESSDENIED ) ) at Windows.UI.Xaml.Application.Start ( ApplicationInitializationCallback callback ) at MyUwpApp.Program.Main ( String [ ] ar... | UWP app wo n't launch on second machine |
C# | I created a method to abstract try/catch functionality . I have about 30 methods that have this exact same try/catch scenario . So I put it in one method : Now , most of the methods call it like this : My issue is that I have just a couple of methods that call it without needing to return a value : However , I ca n't u... | private T Invoke < T > ( Func < T > func ) { try { return func.Invoke ( ) ; } catch ( Exception ex ) { throw LogAndThrowFaultException ( ex ) ; } } public IEnumerable < PingResponse > GetAllForPingRequest ( PingRequest pingRequest ) { return Invoke ( ( ) = > PingResponseLogic.GetAllForPingRequest ( pingRequest ) ) ; } ... | Use func method for an action also ? |
C# | So , I just hate using true/false as method arguments for `` enabled '' / '' disabled '' . To freely quote Jeff : `` I dislike it on a fundamental level '' .I repeatedly find myself defining my own enums on every new project in different namespaces all over the place , like these : Is there a generic enum I can use for... | public enum Clickability { Disabled , Enabled } public enum Editability { Disabled , Enabled } public enum Serializability { Disabled , Enabled } | Is there a ( well hidden ) generic enum anywhere in the BCL for Enabled/Disabled ? |
C# | Help me settle an argument here . Is this : treated exactly the same as this : Ie . does it make a difference if I state specifically that the string s is a const.And , if it is not treated in the same way , why not ? | SqlCommand cmd = new SqlCommand ( `` sql cmd '' , conn ) ; const string s = `` sql cmd '' ; SqlCommand cmd = new SqlCommand ( s , conn ) ; | C # - Is this declared string treated as a const ? |
C# | In the code below , I am assigning a string to text box . The text box text is wrapped , so words will be shifted to the next line if they can not fit in same line.C # : XAML : Now , with the example above , it may happen that on the last line in the text box the word `` Eyes '' is the only word due to wrapping . If th... | textbox.Text = `` Norma went to bed . It was eleven o'clock . She turned out the light . She lay in bed . It was dark . It was quiet . She could n't sleep . She closed her eyes . `` ; < TextBox SelectionBrush= '' # FF54FF50 '' x : Name= '' textbox '' Margin= '' 10,53,0,0 '' FontSize= '' 24 '' HorizontalAlignment= '' Le... | How to check if the last line in a text box has only one word ? |
C# | I 've noticed something odd about using the bitwise XOR operator on bytes in C # . Odd to my mind , at least.I also see this issue using short , but not int or long.I thought the last two lines were equivalent , but that does n't seem to be the case . What 's going on here ? | byte a = 0x11 ; byte b = 0xAA ; a ^= b ; // worksa = a ^ b ; // compiler error : Can not implicitly convert type `` int '' to `` byte '' | C # XOR operators : ^ vs ^= and implicit type conversion |
C# | I always saw people always talking about using framework like Ninject , Unity , Windsor to do the dependency resolver and injection . Take following code for example : My question is : why ca n't we simply write as : In that case seems we do n't need any framework , even for the unit test we can easily mock.So what 's ... | public class ProductsController : ApiController { private IProductRepository _repository ; public ProductsController ( IProductRepository repository ) { _repository = repository ; } } public class ProductsController : ApiController { private IProductRepository _repository ; public ProductsController ( ) : this ( null )... | Why we need framework to do the Dependency Resolver ? |
C# | Given two implementations of Comparison methods : Why would n't the following conditional operator code block compile : Compiler error : `` Type of conditional expression can not be determined because there is no implicit conversion between 'method group ' and 'method group ' '' However , the equivalent code block usin... | // compares by Key ... private static int CompareByKey ( KeyValuePair < int , string > x , KeyValuePair < int , string > y ) { return x.Key.CompareTo ( y.Key ) ; } // compares by Value ... private static int CompareByValue ( KeyValuePair < int , string > x , KeyValuePair < int , string > y ) { return x.Value.CompareTo ... | Conditional operator and Comparison Delegate |
C# | I want to retrive the number sequence which is at the end of string . for e.g . gives me result 56 but I want the result as 1234 . How should I do this ? | string contentDbIndex = Regex.Match ( `` ab56cd1234 '' , @ '' \d+ '' ) .Value ; | How to get number at the end of string ? |
C# | I am building a little 2048 WinForms game just for fun.Note that this is not about a 2048 AI . I am just trying to make a 2048 game that can be played by humans.I first decided to use 0-17 to represent the tiles . 0 represents an empty tile . 1 represents a 2 tile . 2 represents a 4 tile . 3 represents a 8 tile , and s... | aa `` `` `` `` ` b `` cb int [ ] EvaluateRow ( int [ ] row ) { // RowToString converts an int [ ] to a string like I said above StringBuilder rowString = new StringBuilder ( RowToString ( row ) ) ; rowString.Replace ( `` ` `` , `` '' ) ; var regex = new Regex ( `` ( [ a-p ] ) \\1 '' ) ; int lastIndex = -1 ; while ( tru... | How can I figure out which tiles move and merge in my implementation of 2048 ? |
C# | I am in the process of converting a Classic ASP/VBScript application to C # /ASP.Net . The VBScript part of the application is a series of individual scripts performed each month on a specific date with each individual task set up in Windows Scheduler . There are about 35 tasks which include database inserts ( saving m... | p.DoTask1 ( ) ; Thread.Sleep ( 60000 ) ; p.DoTask2 ( ) ; Thread.Sleep ( 60000 ) ; p.DoTask3 ( ) ; Thread.Sleep ( 60000 ) ; etc ... | C # Scheduled Series Of Tasks |
C# | I 'm converting a VB.Net app into C # , and have noticed that in the VB.Net code , there is a private member variable , which is initialised using Me like this : When I convert this to C # code like this : I have the error Argument is value while parameter type is ref.If I put ref in front of the parameter this , I get... | Private m_ClassA As New MyCollection ( Of ClassA ) ( Me ) private MyCollection < ClassA > _classA = new MyCollection < ClassA > ( this ) ; | Why in C # this is not allowed in member initializer , but in VB.Net Me is allowed |
C# | I have two ServiceStack servers X and Y. Server X has functionality to register and authenticate users . It has RegistrationFeature , CredentialsAuthProvider , MemoryCacheClient and MongoDbAuthRepository features to handle the authentication.Recently , I introduced server Y and GUI forms that talk to server Y to handle... | public override bool TryAuthenticate ( IServiceBase authService , string userName , string password ) { // authenticate through server X try { var client = new JsonServiceClient ( `` http : //localhost:8088 '' ) ; var createRequest = new Authenticate { UserName = userName , Password = password , provider = Name , } ; v... | Passthrough Authentication in ServiceStack |
C# | I see several StackOverflow questions on this already but not of them seem to match my scenario . I promise I looked.I have some queries against my database that I 'm using linq to do and I ca n't figure out why the incorrect SQL is being generated . This is happening in several places in my code . I 'm hoping we 're j... | var testing = ( from i in context.TableName1 where i.Param1 == object1.GuidParam select i ) .ToList ( ) ; { SELECT [ Extent1 ] . [ RecordId ] AS [ RecordId ] , [ Extent1 ] . [ AnotherId ] AS [ AnotherId ] , [ Extent1 ] . [ YetAnotherId ] AS [ YetAnotherId ] , [ Extent1 ] . [ WeLikeIds ] AS [ WeLikeIds ] , [ Extent1 ] .... | Why does Linq ignore my where clause ? |
C# | I am new to C # , so please bear with me as I have inherited a script that I 'm attempting to tweak.I want to get the output of SQL PRINT/RAISERROR statements to show up in a log file that has been declared in another part of the script.This is my method I 'm calling : This is the info handler method : Instead of outpu... | public void ProcessData ( string StoredProcedure , int StartDate , int EndDate , string Directory , string LogFileNameAndPath ) { SqlConnection sqlConnection = null ; SqlCommand sqlCommand = null ; SqlParameter sqlParameter = null ; // String outputText = null ; try { sqlConnection = new SqlConnection ( _ConnectionStri... | C # output SQL Server Messages to text file |
C# | At the risk of asking a question that has already been asked butis there a counterpart in Java for the Type type available in C # ? What I want to do is filling an array with elements which reflect several primitive types such as int , byte etc.In C # it would be the following code : | Type [ ] types = new Type [ ] { typeof ( int ) , typeof ( byte ) , typeof ( short ) } ; | type of types in Java |
C# | I am working on some code to use HttpWebRequest asynchronously . If any of you have ever done this before , then you know that error handling can be a bit of a pain because if an exception is thrown in one of the callback methods , it ca n't be passed back to the calling code via a try/catch block.What I want to do is ... | public class HttpPostClientAsyncModel { public HttpResponseSnapshot Response { get ; set ; } public HttpPostClientAsyncStatus Status { get ; set ; } public Exception Exception { get ; set ; } public WebRequest Request { get ; set ; } } | What 's the best way to handle asynchronous HttpWebRequest exceptions in C # ? |
C# | Given the following setup in TPL dataflow.i am wondering how I can mark this to complete because of the cycle . A directory is posted to the dirBroadcast broadcaster which posts to the dirfinder that might post back new dirs to the broadcaster , so i cant simply mark it as complete because it would block any directorie... | var directory = new DirectoryInfo ( @ '' C : \dev\kortforsyningen_dsm\tiles '' ) ; var dirBroadcast=new BroadcastBlock < DirectoryInfo > ( dir= > dir ) ; var dirfinder = new TransformManyBlock < DirectoryInfo , DirectoryInfo > ( ( dir ) = > { return directory.GetDirectories ( ) ; } ) ; var tileFilder = new TransformMan... | How to mark a TPL dataflow cycle to complete ? |
C# | Compiles but shouldn'tErrors but shouldn'tCompiler Error Text : -2147483648 can not be converted to a ulongQuestion : I would expect the opposite to occur . Can anyone explain why this is ? Also how I can print this flags attribute to a byte [ ] for inspection ? | [ Flags ] enum TransactionData : long // 64 bits . Last bit is sign bit , but I 'm putting data there { None = 0 , Color1 = 1 < < 63 , } [ Flags ] enum TransactionData : ulong // 64 bits . No sign bit . Not allowed to put data there { None = 0 , Color1 = 1 < < 63 , } var eee = TransactionData.None | TransactionData.Col... | Unexpected behavior between [ Flags ] enum : long vs [ Flags ] enum : ulong |
C# | I 've been struggling with a problem when downloading very big files ( > 2GB ) on Silverlight . My application is an out-of-browser Download Manager running with elevated permissions.When the file reaches a certain ammount of data ( 2GB ) , it throws the following exception : The only clue I have is this site , who sho... | System.ArgumentOutOfRangeException was caught Message=Specified argument was out of the range of valid values.Parameter name : count StackTrace : in MS.Internal.InternalNetworkStream.BeginRead ( Byte [ ] buffer , Int32 offset , Int32 count , AsyncCallback callback , Object state ) in MS.Internal.InternalNetworkStream.R... | ArgumentOutOfRangeException when downloading file via Stream.Read |
C# | Is there any way to call write generic programs and algorithms in C # while avoiding the overhead of a dynamic solution ? Consider a simple example : Which you might call as : While seemingly efficient , this benign-looking example performs an indirect ( i.e . virtual ) call for every comparison.Obviously , the process... | static void QuickSort < T > ( T [ ] arr , int left , int right , Comparison < T > compare ) { do { int i = left ; int j = right ; var x = arr [ i + ( ( j - i ) > > 1 ) ] ; do { while ( i < arr.Length & & compare ( x , arr [ i ] ) > 0 ) i++ ; while ( j > = 0 & & compare ( x , arr [ j ] ) < 0 ) j -- ; if ( i > j ) { brea... | How to write generic code while avoiding indirect calls ? |
C# | Whenever I try to upload a large video via Direct Upload using the YouTube API . I get an OutOfMemory Exception . Is there anything I can do to get rid of this ? The YouTube API does not say anything about video size limit using direct upload.I gave up on the Direct Upload . Now I trying the resumable upload way . My c... | YouTubeRequest request ; YouTubeRequestSettings settings = new YouTubeRequestSettings ( `` YouTube Upload '' , Client Key , `` Username '' , `` Password '' ) ; request = new YouTubeRequest ( settings ) ; Video newVideo = new Video ( ) ; ResumableUploader m_ResumableUploader = null ; Authenticator YouTubeAuthenticator ;... | YouTube Direct Upload - OutOfMemory Exception |
C# | I 'm using Facebook as a login provider for my web application ( ASP.NET MVC ) .My login works similar to another StackOverflow post How to securely authorize a user via Facebook 's Javascript SDK . I also share the user 's concerns.The flow for my login is as Follows:1 . The user presses the login button.2 . The user ... | var authResponse = response.authResponse ; { accessToken : `` ... '' , expiresIn : 1234 , signedRequest : `` ... '' , userID : `` 123456789 '' } | How do I use a Facebook signed_request in .NET ? |
C# | How does the is operator work with respect to the DLR ? To make my question a little more explicit , consider the following signature : By default , what conditions are necessary for Is < T > to return true ? Furthermore , does the DLR provide any mechanism to customize this behavior ? | public bool Is < T > ( Func < dynamic > getInstance ) { return getInstance ( ) is T ; } | How does the `` is '' operator work with dynamic objects ? |
C# | I have a simple Parent Child table in a database like soThe data that I have in them isParent TableChild TableThese tables are mapped to Parent and Child C # objects using the Linq-2-SQL designer in Visual Studio with no non standard options.I made a simple test program to query all child with their parentsThe output o... | CREATE TABLE [ Parent ] ( [ Id ] [ int ] IDENTITY ( 1,1 ) NOT NULL , [ Name ] [ nvarchar ] ( 256 ) NOT NULL ) ALTER TABLE [ Parent ] ADD CONSTRAINT [ PK_Parent_Id ] PRIMARY KEY ( [ Id ] ) CREATE TABLE [ Child ] ( [ Id ] [ int ] IDENTITY ( 1,1 ) NOT NULL , [ ParentId ] [ int ] NOT NULL , [ Name ] [ nvarchar ] ( 256 ) NO... | Why does linq-2-sql create extra unnecessary objects ? |
C# | I read that sometimes that calling directly a Task can lead to a deadlock of the main thread.Here 's my async method : I tried a lot of ways to run this task in a sync function . Here 's some examples : I want to know which is better solution to run the async method synchronously in the syncFoo ( ) without causing dead... | public async Task < List < JobsWithSchedules > > fillJobsAsync ( ) { IOlapJobAccess jobAccess = new OlapJobAccess ( _proxy , CentralPointPath ) ; List < OlapJob > jobs = await jobAccess.GetAllJobsAsync ( ) ; List < JobsWithSchedules > quartzJobs = null ; if ( jobs ! = null ) { quartzJobs = fillQuartzJobs ( jobs ) ; } r... | Prevent deadlock by running a Task synchronously - Windows Service |
C# | I have a list of bool , and a list of strings . I want to use IEnumerable.Zip to combine the lists , so if the value at each index of the first list is true , the result contains the corresponding item from the second list . In other words : The simplest solution I could come up with is : ... but I suspect there 's a s... | List < bool > listA = { true , false , true , false } ; List < string > listB = { `` alpha '' , `` beta '' , `` gamma '' , `` delta '' } ; IEnumerable < string > result = listA.Zip ( listB , [ something ] ) ; //result contains `` alpha '' , `` gamma '' listA.Zip ( listB , ( a , b ) = > a ? b : null ) .Where ( a = > a !... | Linq : Exclude results using Zip |
C# | When I use expression trees to replace a method , such as Math.Max , it looks like it successfully replaces it in the expression tree . But when I go to use it in Entity Framework , it throws an exception about not supporting Math.Max for Entity Framework . But I am explicitly replacing it.Does anyone know why ? And a ... | using System ; using System.Collections.Generic ; using System.Linq ; using System.Linq.Expressions ; namespace ConsoleApplication1 { public static class CalculateDatabase { public static void Main ( string [ ] args ) { var calcs = GetCalculateToAmounts ( GetTestItems ( ) , 0.5m ) .ToList ( ) ; } public static IQueryab... | Expression Tree - Math.Max replacement |
C# | Suppose I have three objects : ' a ' , ' b ' and ' c'.Object ' a ' and ' c ' are long-lived , statically referenced service singletons.Object ' b ' is short-lived , i.e . no static references keep it alive.Now suppose object ' a ' creates an instance of object ' b ' in the scope of one of its methods , e.g.Further supp... | B b = new B ( ) ; public B ( ) { C.ActionList.Add ( SomeMethod ) ; } void SomeMethod ( ) { ... } public B ( ) { C.ActionList.Add ( ( ) = > { ... } ) ; } | does passing a method of one object to another object keep the first object alive ? |
C# | I 'm in the process of designing a system that will allow me to represent broad-scope tasks as workflows , which expose their workitems via an IEnumerable method . The intention here is to use C # 's 'yield ' mechanism to allow me to write psuedo-procedural code that the workflow execution system can execute as it sees... | public override IEnumerable < WorkItem > Workflow ( ) { // These would probably be injected from elsewhere var db = new DB ( ) ; var emailServer = new EmailServer ( ) ; // other workitems here var ci = new FindLowInventoryItems ( db ) ; yield return ci ; if ( ci.LowInventoryItems.Any ( ) ) { var email = new SendEmailTo... | Is this good design of a workflow-esque system ? |
C# | I have some working code which produces a correct signature of a string if I load a certificate from a file or from the current user 's store . However , if I load the exact same certificate ( same .p12 and same thumbprint ) from the Machine certificate store , it behaves differently . When loaded from that store , the... | Thumbprint : FBBE05A1C5F2AEF637CDE20A7985CD1011861651Has private key : Truersa.KeySize ( bits ) =2048Signature Length ( bits ) : 2048Signature : kBC2yh0WCo/AU8aVo+VUbRoh67aIJ7SWM4dRMkNvt ... Thumbprint : FBBE05A1C5F2AEF637CDE20A7985CD1011861651Has private key : Truersa.KeySize ( bits ) = 1024Signature Length ( bits ) :... | Cryptography : Why am I getting different RSA signatures depending on which certificate store the certificate was loaded from ? |
C# | With this code for a very basic logger : when I try it from a few threads simultaneously I quickly get the error : Why the lock is not preventing the threads to access the file at the same time ? It does n't matter if the threads call the same instance or different instances to the same file.Also I thought It could be ... | lock ( string.Concat ( `` LogWritter_ '' , this.FileName ) ) { using ( var fileStream = File.Open ( this.FileName , FileMode.Append , FileAccess.Write , FileShare.Read ) ) { using ( var w = new StreamWriter ( fileStream ) ) { w.Write ( message ) ; } } } The process ca n't access the file because its being used by anoth... | Why the lock in this code is not working ? |
C# | Really curious for the below program ( yes run in release mode without debugger attached ) , the first loop assigns a new object to each element of the array , and takes about a second to run . So I was wondering which part was taking the most time -- object creation or assignment . So I created the second loop to test... | static class Program { const int Count = 10000000 ; static void Main ( ) { var objects = new object [ Count ] ; var sw = new Stopwatch ( ) ; sw.Restart ( ) ; for ( var i = 0 ; i < Count ; i++ ) { objects [ i ] = new object ( ) ; } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedMilliseconds ) ; // ~800 ms sw.Restart ( ) ; ... | C # performance curiosity |
C# | I 'm designing an application that will allow me to draw some functions on a graphic . Each function will be drawn from a set of points that I will pass to this graphic class.There are different kinds of points , all inheriting from a MyPoint class . For some kind of points it will be just printing them on the screen a... | class GraphicMaker { ArrayList < Point > points = new ArrayList < Point > ( ) ; public void AddPoint ( Point point ) { points.add ( point ) ; } public void DoDrawing ( ) { foreach ( Point point in points ) { if ( point is PointA ) { //some logic here else if ( point is PointXYZ ) { // ... etc } } } } | Designing a class in such a way that it does n't become a `` God object '' |
C# | Doing an experiment of translating .NET IL to C++ in a human readable fashion.Here is the issue : C # allows you to resolve multiple interfaces with the same method name that only differ in return type . C++ does n't seem to support this however making resolving two interfaces impossible using the vTable ( or am i wron... | template < typename T > class IMyInterface { public : short ( T : :*Foo_IMyInterface ) ( ) = 0 ; } ; template < typename T > class IMyInterface2 { public : int ( T : :*Foo_IMyInterface2 ) ( ) = 0 ; } ; class MyClass : public IMyInterface < MyClass > , public IMyInterface2 < MyClass > { public : MyClass ( ) { Foo_IMyInt... | C++ multiple interfaces that only differ in return type ? |
C# | As you 're developing you often use things like oras a placeholder to remind you to finish something off - but these can be missed and mistakenly end up in the release.You could use something likeso it wo n't compile in Release build - but is there a more elegant way ? | throw new NotImplementedException ( `` Finish this off later '' ) // TODO - Finish this off later # if RELEASE Finish this off later # endif | Elegant way to stop release compilation with error |
C# | So I have a case where the layout has evolved to become more complicated . There 's the usual things like @ section styleIncludes { ... } , then other sections that define all kinds of the things that each page can optionally ( but almost always ) specify like the structure of the current pages breadcrumb . The reason ... | @ { string title = `` Edit Person '' ViewBag.Title = title ; } @ section styles { .someOneOffPageSpecificStyle { width:59px } } @ section javascript { //javascript includes which the layout will place at the bottom ... } @ section breadcrumb { < a ... > Parent Page < /a > & gt ; < a ... > Sub Page < /a > & gt ; @ title... | Hint/Fluent for razor section names ? |
C# | When exposing a set of related functions in Powershell cmdlets , is it possible to share the property names and summary help to normalize these across cmdlets in an assembly ? I know that this can be done with derived classes , but this solution is awkward at best when there are multiple cmdlets with different properti... | namespace FrozCmdlets { using System.Management.Automation ; /// < summary > /// Adds a new froz to the system./// < /summary > [ Cmdlet ( VerbsCommon.Add , `` Froz '' ) ] public class AddFroz : Cmdlet { /// < summary > /// The name of the froz . /// For more information on the froz , see froz help manual . /// < /summ... | Is it possible to share properties and comments between Powershell cmdlets in c # ? |
C# | Given a list of dates in descending order , this code will find the largest date where the date is < = searchDate.How would I write a binary search function to replace this method ? I 'm struggling to implement it for an inexact comparison like this.This method is called frequently , and can contain several thousand re... | List < CurrencyHistoricExchangeRate > history = GetOrderedHistory ( ) ; foreach ( var record in history ) { if ( record.Date < searchDate ) { return record ; } } | Binary search list of dates for largest date where date < = n |
C# | I did a search for an HsbToRgb converter in the docs but did n't find anything containing `` hsb '' or `` hsl '' , so I 'm guessing it just does n't exist . Just to make sure , though , are there any classes that support this conversion ? UpdateI ended up going with this , which is slightly different than 0xA3 's . I a... | public static Color AhsbToArgb ( byte a , double h , double s , double b ) { var color = HsbToRgb ( h , s , b ) ; return Color.FromArgb ( a , color.R , color.G , color.B ) ; } public static Color HsbToRgb ( double h , double s , double b ) { if ( s == 0 ) return RawRgbToRgb ( b , b , b ) ; else { var sector = h / 60 ; ... | Does the .NET Framework 3.5 have an HsbToRgb converter or do I need to roll my own ? |
C# | If I run this test : I get the following result : When I use the regular For : The output is : The last result is a Triangular Distribution and it is the expected output.The purpose of my question is not to discuss the applicability of parallelism . The question is why the Parallel.For behaves that way ? | var r = new Random ( ) ; var ints = new int [ 13 ] ; Parallel.For ( 0 , 2000000 , i = > { var result = r.Next ( 1 , 7 ) + r.Next ( 1 , 7 ) ; ints [ result ] += 1 ; } ) ; 2 : 92,144453 : 0,417654 : 0,622455 : 0,825256 : 1,040357 : 1,252158 : 1,05319 : 0,834110 : 0,633411 : 0,419212 : 0,2109 for ( int i = 0 ; i < 2000000... | Parallel.For and For yield different results |
C# | I have the following function in c # : Since TModel is clear from a function parameter I want some way to not specify its type when calling a function . Ideally I want to call it like : Since this is probably impossible , I came up with the following : So I 'm now calling it like : Are there other possibilities ? Did I... | bool Handle < TCommandHandler , TModel > ( TModel model ) where TCommandHandler : ICommandHandler < TModel > { // ... _container.Resolve < TCommandHandler > ( ) ; // ... } Handle < MyCommandHandler > ( model ) ; HandleTemp < TModel > Handle < TModel > ( TModel model ) { return new HandleTemp < TModel > ( model ) ; } pu... | Syntax sugar for double-generic function |
C# | How to write correct Linq expression used in generic for condition `` where '' Repositor.csbut this with Linq expression will run | public static class ConStr { public static MySqlConnection Conn ( ) { return new MySqlConnection ( ConfigurationManager.ConnectionStrings [ `` DBCN '' ] .ConnectionString ) ; } } private IDbConnection cn ; public IEnumerable < TEntity > FilterBy ( Expression < Func < TEntity , bool > > expression ) { using ( cn = ConSt... | Linq expression IEnumerable < TEntity > does not contain definition of where |
C# | It is second nature for me to whip up some elaborate SQL set processing code to solve various domain model questions . However , the trend is not to touch SQL anymore . Is there some pattern reference or conversion tool out there that helps convert the various SQL patterns to Linq syntax ? I would look-up ways to code ... | SELECT * FROM orders X WHERE ( SELECT COUNT ( * ) FROM orders YWHERE Y.totalOrder > X.totalOrder ) < 6 var differenceQuery = ( from cust in db.Customersselect cust.Country ) .Except ( from emp in db.Employees select emp.Country ) ; SELECT DISTINCT [ t0 ] . [ field ] AS [ Field_Name ] FROM [ left_table ] AS [ t0 ] WHERE... | How to get linq to produce exactly the sql I want ? |
C# | I have a small 3D vector class in C # 3.0 based on struct that uses double as basic unit.An example : One vector 's y-value isI subtract a vector with an y-value ofThe value for y I would expect is Instead I getWhen I 'm doing the whole computation in one single thread , I get ( 1 ) . Also the debugger and VS quick-wat... | -20.0 straight 10.094999999999965 -30.094999999999963 ( 1 ) -30.094999313354492 ( 2 ) public struct Vector3d { private readonly double _x , _y , _z ; ... public static Vector3d operator - ( Vector3d v1 , Vector3d v2 ) { return new Vector3d ( v1._x - v2._x , v1._y - v2._y , v1._z - v2._z ) ; } } Vector3d pos41 = pos4 - ... | Can floating-point precision be thread-dependent ? |
C# | For some reason my stored procedure is executed without any error from the code-behind in C # but it is not deleting anything at all that the stored procedure has written . I have all the correct parameters and everything . I ran the query from SQL Server with all the same parameters from the C # code and it works perf... | string reportType = `` PostClaim '' ; string GRNBRs = `` 925 ' , '926 ' , '927 '' ; string PUNBRs = `` 100 ' , '100 ' , '100 '' ; string beginningDates = `` 20120401 '' ; string endDates= `` 20120430 '' ; try { conn = new SqlConnection ( ConnectionInfo ) ; conn.Open ( ) ; SqlDataAdapter da = new SqlDataAdapter ( `` Rem... | Stored procedure not running correctly with dynamic sql text |
C# | When loading a rtf file into a Windows Forms RichTextBox it loses the background colour of table cells . If we use a WPF RichTextBox and load the same file everything is formatted as it should.Am I missing something when I load the file into the Windows Forms RichTextBox ? Windows Forms RichTextBox code snippet : In th... | private void button1_Click ( object sender , EventArgs e ) { OpenFileDialog fDialog = new System.Windows.Forms.OpenFileDialog ( ) ; fDialog.Filter = `` Rich Text Files ( *.rtf ) |*.rtf '' ; fDialog.Multiselect = false ; fDialog.RestoreDirectory = true ; if ( fDialog.ShowDialog ( ) == System.Windows.Forms.DialogResult.O... | Windows.Forms.RichTextBox Loses table background colours |
C# | This was mentioned in my other question and I thought it might be useful to add it to the record . In the following program , which , if any , of the locally defined delegates are cached between calls to the Work method instead of being created from scratch each time ? | namespace Example { class Dummy { public int age ; } class Program { private int field = 10 ; static void Main ( string [ ] args ) { var p = new Program ( ) ; while ( true ) { p.Work ( ) ; } } void Work ( ) { int local = 20 ; Action a1 = ( ) = > Console.WriteLine ( field ) ; Action a2 = ( ) = > Console.WriteLine ( loca... | Which ( if any ) locally defined delegates are cached between method calls ? |
C# | For each entity that has a one to many relation with other entity when i trying to add a new item it seems like i have to define these list of items that relates to this entity.For example , lets say that i have a ProductType entity that has a list of Products as following : when i try to add a new ProductType like tha... | [ Table ] public class ProductType { [ Column ( IsPrimaryKey = true , IsDbGenerated = true ) ] public int Id { get ; private set ; } [ Column ] public string Name { get ; set ; } private EntitySet < Product > _products ; [ Association ( Storage = `` _products '' , ThisKey = `` Id '' , OtherKey = `` ProductTypeId '' ) ]... | How Can I define Nullable EntitySet < > ? |
C# | I 'm looking for a way to navigate between screens in my app . Basically what I 've seen so far consists of passing a string URI to the NavigationService , complete with query string parameters. , e.g.I 'm not really keen on this though ultimately because it requires magic strings , and they can lead to problems down t... | NavigationService.Navigate ( new Uri ( `` /MainPage.xaml ? selectedItem= '' +bookName.Id , UriKind.Relative ) ) ; | Is there a typesafe way of navigating between screens in Windows Phone ? |
C# | The azure role setting , is very useful since it lets you change values on-the-fly while IIS is running . But the problem is , if you have plenty users , and if it reads every time the config value from file , it is not best practice to use it without putting it in a static variable . The next problem , if you put it i... | RoleEnvironment.GetConfigurationSettingValue ( `` Appname.settingKey '' ) ; ConfigurationManager.ConnectionStrings [ `` SettingKey '' ] .ConnectionString ; | Does RoleEnvironment.GetConfigurationSettingValue read every time from cfg file ? |
C# | Basic C # question here.What is the difference between creating an instance of a class property / field either as you declare it or in the constructor of the object in question . For example : vs | public class MyClass { public MyObject = new MyObject ( ) ; } public class MyClass { public MyObject ; public MyCLass ( ) { MyObject = new MyObject ( ) ; } } | C # - What 's the difference between these two ways of instancing a class property ? |
C# | Silverlight Unit Test Framework has an [ Asynchronous ] attribute ( AsynchronousAttribute ) that causes the tests to only end when EnqueueTestComplete ( ) gets called . This allows for a simple way to write tests that need to wait for an event to occur before they end . Now I am trying to pick a favorite general purpos... | [ TestClass ] public class AsyncTests : SilverlightTest { [ Asynchronous ] [ TestMethod ] public void AsyncAppendStringTest ( ) { var appendStrings = new List < string > ( ) { `` hello '' , `` there '' } ; StringJoiner.AsyncAppendStringsWithDashes ( appendStrings , ( returnString ) = > { Assert.IsTrue ( string.Compare ... | Asynchronous tests in VSUTF , NUnit , xUnit.NET , MbUnit vs. SUTF ? |
C# | I am querying an xml file and returning 3 attributes per selection ( each entry that meets my criteria will return 3 attributes details ) . I need to store these values , and then later look up the first attribute , and return the 2 other stored attributes related to it . The above code returns 3 attributes per item fo... | var items = from item in doc.Descendants ( `` SUM '' ) select new { id = ( string ) item.Attribute ( `` id '' ) , category = ( string ) item.Attribute ( `` cat '' ) , selection = ( string ) item.Attribute ( `` sel '' ) } ; | How to store and lookup data , based on multiple xml attributes ? |
C# | The question seems simple . Although the documentation says it does : the following code gives an error : saying that there is no conversion from KeyCollection < T > to IReadOnlyCollection < T > .Moreover polish documentation ( french too for that matter ) says it does not : Which is it ? And in case it 's the error in... | public sealed class KeyCollection : ICollection < TKey > , IReadOnlyCollection < TKey > , IEnumerable < TKey > , ICollection , IEnumerable class MyKeys < T > { readonly Dictionary < T , T > dict = new Dictionary < T , T > ( ) ; public IReadOnlyCollection < T > Keys { get { return dict.Keys ; } set ; } } [ SerializableA... | Does ` Dictionary < TKey , TValue > .KeyCollection ` implement ` IReadOnlyCollection ` or not ? |
C# | when choosing a character I currently have a base classAnd my characters derive from this classLastly I use this code to select the WarriorSo this way works pretty fine . But when it comes to cooldowns etc . I want to stay with a clean code so I thought about creating a Ability class.My abstract parent classThe Warrior... | abstract class CharacterClass { public abstract void AbilityOne ( ) ; public abstract void AbilityTwo ( ) ; } class Warrior : CharacterClass { public override void AbilityOne ( ) { // implement ability one here } public override void AbilityTwo ( ) { // implement ability two here } } CharacterClass selectedClass = new ... | creating ability objects in Unity |
C# | I have a design problem that I ca n't figure out . Here 's what I 've got : In general , I have two general types of objects Strikes and Options . These have been abstracted into two interfaces IStrike and IOption.Let 's say that IOption has the following fields , in reality there are about 10 times as many , but we ca... | interface IOption { double Bid { get ; set ; } double Ask { get ; set ; } double ImpliedVol { get ; set ; } } interface IStrike { IOption Call { get ; set ; } IOption Put { get ; set ; } } public double SquareImpliedVol ( IOption opt ) { return Math.Pow ( opt.ImpliedVol,2 ) ; } interface IOption : IOptionImpliedVol { d... | Can I combine composition and inheritance with interfaces in C # |
C# | Excel 2016 seems to trigger a programmatically added undo level upon saving , which does not happen in earlier versions of Excel ( 2013 , 2010 , and 2007 ) . To reproduce this apparent bug , open a new workbook and save it as a macro-enabled workbook ( .xlsm file ) . Paste the following code into the ThisWorkbook modul... | Option ExplicitPublic WithEvents App As ApplicationPrivate Sub Workbook_Open ( ) Set App = ApplicationEnd SubPrivate Sub App_SheetChange ( ByVal Sh As Object , ByVal Target As Range ) Application.OnUndo `` foo '' , `` modTest.Undo '' End Sub Public Sub Undo ( ) MsgBox `` This is the Excel 2016 bug . `` End Sub | Excel 2016 triggers undo upon save bug ? |
C# | I 've borrowed the code below from another question ( slightly modified ) , to use in my code : The original author of this code correctly adheres to the warnings given in MSDN 's implicit & explicit documentation , but here 's my question : Is explicit always necessary in potentially exceptional code ? So , I 've got ... | internal class PositiveDouble { private double _value ; public PositiveDouble ( double val ) { if ( val < 0 ) throw new ArgumentOutOfRangeException ( `` Value needs to be positive '' ) ; _value = val ; } // This conversion is safe , we can make it implicit public static implicit operator double ( PositiveDouble d ) { r... | Why/when is it important to specify an operator as explicit ? |
C# | I have an Web API 2 end point where by I want to asynchronously carry out an operation while I retrieve and verify a user . If this user does not exist I want to return a 404 Not Found like so : Could this cause me potential issues if the user was to equal to null and the method returned without awaiting the getCatTask... | public async Task < IHttpActionResult > Get ( ) { var getCatTask = GetCatAsync ( ) ; var user = await GetUserAsync ( ) ; if ( user == null ) { return NotFound ( ) ; } var cat = await getCatTask ; return Ok ( cat ) ; } | Bad practice to return from method before async operation completes ? |
C# | I 'm looking for a way to program a custom authorization filter in ASP.NET 5 as the current implementation relies in Policies/Requirements wich in turn rely solely in the use of Claims , thus on the umpteenth and ever-changing Identity System of wich I 'm really tired of ( I 've tried all it 's flavours ) .I have a lar... | [ Authorize ( Requires = enumPermission.DeleteCustomer ) ] | DI into a Requirement/Policy in ASP.NET MVC 6 |
C# | I was recently attempting to answer a question that a user posted about why the decimal struct does not declare its Min/Max values as const like every other numeric primitive ; rather , the Microsoft documentation states that it is static readonly.In researching that , I dug through the Microsoft source code , and came... | public const Decimal MinValue = new Decimal ( -1 , -1 , -1 , true , ( byte ) 0 ) ; public const Decimal MaxValue = new Decimal ( -1 , -1 , -1 , false , ( byte ) 0 ) ; public Decimal ( int lo , int mid , int hi , bool isNegative , byte scale ) { if ( ( int ) scale > 28 ) throw new ArgumentOutOfRangeException ( `` scale ... | 'Decimal ' source code from Microsoft - will it build ? |
C# | I have a requirement that calls for matching a Sample Set of color values against a Known Set of values to find either an exact match , or matches that are within an acceptable distance . I 'm not entirely sure what algorithm would be best suited for this and I 'm looking for suggestions . I thought about using a SQL q... | Color 1 Color 2 Color 3Sample A : [ 25 , 25 , 25 ] , [ 10 , 10 , 10 ] , [ 100 , 100 , 100 ] Sample B : [ 125 , 125 , 125 ] , [ 10 , 10 , 10 ] , [ 200 , 200 , 200 ] Sample C : [ 13 , 87 , 255 ] , [ 10 , 10 , 10 ] , [ 100 , 100 , 100 ] Sample D : [ 67 , 111 , 0 ] , [ 10 , 10 , 10 ] , [ 200 , 200 , 200 ] Sample E : [ 255 ... | Suggest an algorithm for color pattern matching against a large known set |
C# | In Xamarin google maps for Android using C # you can create polygons like so based on this tutorial : However I have downloaded a CSV file from my Fusion Table Layer from google maps as I think this might be the easiest option to work with polygon/polyline data . The output looks like this : I uploaded a KML file to Go... | public void OnMapReady ( GoogleMap googleMap ) { mMap = googleMap ; PolylineOptions geometry = new PolylineOptions ( ) .Add ( new LatLng ( 37.35 , -37.0123 ) ) .Add ( new LatLng ( 37.35 , -37.0123 ) ) .Add ( new LatLng ( 37.35 , -37.0123 ) ) ; Polyline polyline = mMap.AddPolyline ( geometry ) ; } description , name , l... | Extracting data from CSV file ( fusion table and kml workaround ) |
C# | During development I had a TempTextBlock for testing and I 've removed it now . It builds successfully , but when I try to create a package for store , it gives this error : error CS1061 : 'MainPage ' does not contain a definition for 'TempTextBlock ' and no extension method 'TempTextBlock ' accepting a first argument ... | /// < summary > /// Connect ( ) /// < /summary > [ global : :System.CodeDom.Compiler.GeneratedCodeAttribute ( `` Microsoft.Windows.UI.Xaml.Build.Tasks '' , '' 14.0.0.0 '' ) ] [ global : :System.Diagnostics.DebuggerNonUserCodeAttribute ( ) ] public void Connect ( int connectionId , object target ) { switch ( connectionI... | Page does n't contain a definition for X |
C# | Here 's the simplified case . I have a class that stores a delegate that it will call on completion : I have another utility class that I want to subscribe to various delegates . On construction I want itself to register to the delegate , but other than that it does n't care about the type . The thing is , I do n't kno... | public class Animation { public delegate void AnimationEnd ( ) ; public event AnimationEnd OnEnd ; } public class WaitForDelegate { public delegateFired = false ; // How to express the generic type here ? public WaitForDelegate < F that 's a delegate > ( F trigger ) { trigger += ( ) = > { delegateFired = true ; } ; } }... | Constructor that takes any delegate as a parameter |
C# | My expectation is that AutoMapper ( 3.3.0 ) does not automatically resolve string - > DateTime conversions , even when the string is in a well-understood format . The lack of inclusion of a default string - > DateTime converter is noted ( albeit four years ago ) in a comment by the library author , Jimmy Bogard , on th... | AutoMapper.AutoMapperMappingExceptionMissing type map configuration or unsupported mapping.Mapping types : String - > DateTime System.String - > System.DateTimeDestination path : Bar.ZingSource value : Friday , December 26 , 2014 using System ; using AutoMapper ; public class Program { public static void Main ( ) { var... | AutoMapper inconsistently automatically resolving string - > DateTime |
C# | OK , Custom Policy Based Authorization in ASP.NET Core . I kinda of understood the idea of this new identity framework , but still not 100 % clear what you can achieve with this . Assuming we have an Action in HomeController called List . This action will query and display a list of products from the database . The use... | [ Authorize ( Policy = `` ProductsAccess '' ) ] public IActionResult List ( ) { //do query and return the products view model return View ( ) ; } | ASP.NET Core Custom Policy Based Authorization - unclear |
C# | I 'm launching an external application from a ContextMenu , and I must block the the source application while the target application is running . To achieve this I 'm using Process.WaitForExit ( ) to avoid the source application responding to events.The problem is the context menu is still ahead the target application ... | public MainWindow ( ) { InitializeComponent ( ) ; this.ContextMenu = new ContextMenu ( ) ; MenuItem menuItem1 = new MenuItem ( ) ; menuItem1.Header = `` Launch notepad '' ; menuItem1.Click += MyMenuItem_Click ; this.ContextMenu.Items.Add ( menuItem1 ) ; } void MyMenuItem_Click ( object sender , RoutedEventArgs e ) { Pr... | WPF ContextMenu still visible after launching an external process |
C# | Is there a way I can determine in .NET , for any arbitrary SQL Server result set , if a given column in the result can contain nulls ? For example , if I have the statementsand and I get a datareader like this : can I have a function like this ? I want it to return true for the first statement , and false for the secon... | Select NullableColumn From MyTable Select IsNull ( NullableColumn , ' 5 ' ) as NotNullColumn From MyTable var cmd = new SqlCommand ( statement , connection ) ; var rdr = cmd.ExecuteReader ( ) ; bool ColumnMayHaveNullData ( SqlDataReader rdr , int ordinal ) { // ? ? ? ? } | SqlDataReader find out if a data field is nullable |
C# | I have a List < T > of available times within a 24 hour day , and two TimeSpans , minTime and maxTime.I need to find a time of day within the List < T > that lands between the minTime and maxTime , however due to this being used in multiple timezones , the minTime and maxTime can be on separate days and span something ... | // Make new TimeSpan out of maxTime to eliminate any extra days ( TotalHours > = 24 ) , // then check if time on the MaxTime is earlier than the MinTimeif ( new TimeSpan ( maxTime.Hours , maxTime.Minutes , maxTime.Seconds ) < minTime ) { // If time on MaxTime is earlier than MinTime , the two times span separate days ,... | What am I missing in this algorithm to find a TimeOfDay between two TimeSpans that may span separate days ? |
C# | I was using Dapper and having it return a dynamic IEnumerable , like this : Here , rows is of type IEnumerable < dynamic > . The IntelliSense says FirstOrDefault ( ) is awaitable , and has the usage await FirstOrDefault ( ) . Not all LINQ queries are shown as awaitable , but it seems like especially those that somehow ... | var rows = conn.Query ( `` SELECT * FROM T WHERE ID = @ id '' , new { id = tableId } ) ; var row = rows.FirstOrDefault ( ) ; | Why is First ( ) or ElementAt ( ) on a dynamic IEnumerable awaitable ? |
C# | I have a Control lblDate in User Control MainScreen . I would like to modify it in a method in class Date , which is in another project AoWLibrary . I ca n't reference it because AoWLibrary is a dependent of the first project.I tried to make lblDate static but the compiler kept throwing errors at me , and I have a publ... | public Label LabelDate { get { return lblDate ; } set { lblDate = value ; } } public static void CalculateDate ( ) { GameDate = month.ToString ( ) + `` / '' + displayDay.ToString ( ) + `` / '' + year.ToString ( ) ; // LabelDate.Text = GameDate ; // This is essentially what I need to do } | Modify Windows Forms Control from another Project |
C# | When writing a method chain for LINQ , I can do the Where statements one of two ways : Or Are there any benefits of one over the other ? Do n't worry too much about the datatypes in this example , but if there are issues with datatypes , then that would be good to know too.The obvious one is that the object is already ... | var blackOldCats = cats.Where ( cat = > cat.Age > 7 & & cat.Colour == `` noir '' ) var blackOldCats = cats.Where ( cat = > cat.Age > 7 ) .Where ( cat = > cat.Colour == `` noir '' ) | Linq Where Clauses - Better to stack or combine ? |
C# | I 'm currently working on an emulation server for a flash-client based game , which has a `` pets system '' , and I was wondering if there was a simpler way of going about checking the level of specified pets.Current code : Yes , I 'm aware I 've misspelt Experience , I had made the mistake in a previous function and h... | public int Level { get { if ( Expirience > 100 ) // Level 2 { if ( Expirience > 200 ) // Level 3 { if ( Expirience > 400 ) // Level 4 - Unsure of Goal { if ( Expirience > 600 ) // Level 5 - Unsure of Goal { if ( Expirience > 1000 ) // Level 6 { if ( Expirience > 1300 ) // Level 7 { if ( Expirience > 1800 ) // Level 8 {... | Simpler / more efficient method of nested if ... else flow ? |
C# | I am writing a Cmdlet and need to pass object structures into an API client that may contain PSObjects . Currently , these serialise as a JSON string containing CLIXML . Instead , I need it to be treated like an object ( including the NoteProperties in PSObject.Properties as properties , and recursively serialising the... | public class PSObjectJsonConverter : JsonConverter { public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { if ( value is PSObject ) { JObject obj = new JObject ( ) ; foreach ( var prop in ( ( PSObject ) value ) .Properties ) { obj.Add ( new JProperty ( prop.Name , value ) ) ;... | How can I serialise PSObjects in C # with JSON.NET ? |
C# | I have a method with the following signatureFrom a point in my code I need to move up the stacktrace to find the closest method with the SpecificationAttribute ( performance is not an issue here ) . I find this method but I can not find any custom attributes on it.I do n't think I 've ever seen this happen . What might... | [ Specification ] public void slide_serialization ( ) { | Why can I not find a custom attribute on this MethodInfo |
C# | PreambleI 'm trying to disassemble and reverse-engineer a program whose author is long gone . The program provides some unique features that I have yet to find elsewhere and ... I 'm curious and intrigued by reverse-engineering the program . If you 're just gon na try and help me find another program ... do n't bother.... | dword_131894E = 54264588 ; dword_131894A = 51381002 ; dword_1318946 = 51380998 ; dword_1318942 = 52429571 ; dword_131893E = 52298503 ; runtimeVersion [ 0 ] = 836 ; szIndex = 0 ; do { runtimeVersion [ szIndex ] = ( runtimeVersion [ szIndex ] - 1 ) ^ ( szIndex + 882 ) ^ 0x47 ; ++szIndex ; } while ( szIndex < 11 ) ; ushor... | Ca n't decrypt these strings |
C# | Does anyone know why the last one does n't work ? | object nullObj = null ; short works1 = ( short ) ( nullObj ? ? ( short ) 0 ) ; short works2 = ( short ) ( nullObj ? ? default ( short ) ) ; short works3 = 0 ; short wontWork = ( short ) ( nullObj ? ? 0 ) ; //Throws : Specified cast is not valid | Null coalescing operator giving Specified cast is not valid int to short |
C# | I am trying to get the heart rate from a Microsoft Band . It should be updating whenever the value changes . I am then trying to display that value in a TextBlock . I first create an instance of IBandClient , and set its HeartRate.ReadingChanged method like this : Then I try to update the value like this : HeartRate is... | bandClient.SensorManager.HeartRate.ReadingChanged += HeartRate_ReadingChanged ; private void HeartRate_ReadingChanged ( object sender , Microsoft.Band.Sensors.BandSensorReadingEventArgs < Microsoft.Band.Sensors.IBandHeartRateReading > e ) { HeartRate = e.SensorReading.HeartRate ; } public int HeartRate { get { return (... | Get Heart Rate From Microsoft Band |
C# | Eric Lippert has explained in his blog post at http : //blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx why constraints are not considered for type inference , which makes sense given that methods can not be overloaded by simply changing type constraints . However , I woul... | public interface I < T > { Other < T > CreateOther ( ) ; } public class C : I < string > { public Other < string > CreateOther ( ) { return new Other < string > ( ) ; } } public class Other < T > { } public static class Factory1 { public static Tuple < T , Other < T1 > > Create < T , T1 > ( T o ) where T : I < T1 > { r... | Is there a workaround to C # not being able to infer generic type arguments using type constraints ? |
C# | Is there any difference between the following two statement ? They both work . | if ( ( ( Func < bool > ) ( ( ) = > true ) ) ( ) ) { ... . } ; if ( new Func < bool > ( ( ) = > true ) ( ) ) { ... . } ; | Cast to Func vs new Func ? |
C# | I declared the function Process32FirstW and the structure PROCESSENTRY32W like this : When calling Process32FirstW ( with a 64-bit process ) , I always get a TypeLoadException saying The type ProcessEntry could n't be loaded , because the object field at offset 44 is aligned wrong or is overlapped by another field , wh... | [ DllImport ( `` KERNEL32.DLL '' , CallingConvention = CallingConvention.StdCall , EntryPoint = `` Process32FirstW '' ) ] private static extern bool Process32FirstW ( IntPtr hSnapshot , ref ProcessEntry pProcessEntry ) ; [ StructLayout ( LayoutKind.Explicit , CharSet = CharSet.Unicode , Size = 568 ) ] internal struct P... | ` PROCESSENTRY32W ` in C # ? |
C# | I get file size =0the finilizer should have executed because I derive from CriticalFinalizerObjectI do n't want to use Trace.Close ( ) not in the Finalizer.editafter @ eric Lippert reply : Ive re-edited the code trying to match it to : constrained execution region ( but still no success ) | class Program : CriticalFinalizerObject { static void Main ( string [ ] args ) { Program p = new Program ( ) ; TextWriterTraceListener listener = new TextWriterTraceListener ( @ '' C : \trace.txt '' ) ; Trace.Listeners.Clear ( ) ; // Remove default trace listener Trace.Listeners.Add ( listener ) ; Trace.WriteLine ( `` ... | Why my Close function is n't called ? |
C# | I have been trying to use Deedle F # Library to write an F # batch program . It has worked perfectly . However , I am not sure about the best design for the following 2 tasks : Combine the F # module into a existing ASP.net MVC/Web Api systemCreate a WPF interface to serve as a control panel and visual dependency contr... | type TimeSeriesDataProcessor ( fileName : string ) = let mutable _fileName = fileName let _rawInputData = loadCsvFile _fileName let _pivotedData = _rawInputData | > pivotRawData | > fillPivotedRawData | > calculateExpandingZscore //read and write member this.FileName with get ( ) = _fileName and set ( value ) = _fileNa... | Designing an F # module to be called by C # ( Console/MVC/WPF ) |
C# | I want to Serialize and DeSerialize an object which contains a Lazy Collection of some custom objects . Normally everything works perfectly fine but , if namespaces of classes used for serialization are changed , then this issue occurs . I have written a SerializationBinder to point to right classes while deserializing... | namespace ConsoleApplication14 { [ Serializable ] public class MyInnerClass : ISerializable { private string _stringInInnerClassKey = `` StringInInnerClass '' ; public string StringInInnerClass { get ; set ; } public MyInnerClass ( ) { } private MyInnerClass ( SerializationInfo info , StreamingContext context ) { Strin... | Not able to deserialize Lazy object |
C# | I encountered some interesting behavior in the interaction between Nullable and implicit conversions . I found that providing an implicit conversion for a reference type from a value type it permits the Nullable type to be passed to a function requiring the reference type when I instead expect a compilation error . The... | static void Main ( string [ ] args ) { PrintCatAge ( new Cat ( 13 ) ) ; PrintCatAge ( 12 ) ; int ? cat = null ; PrintCatAge ( cat ) ; } private static void PrintCatAge ( Cat cat ) { if ( cat == null ) System.Console.WriteLine ( `` What cat ? `` ) ; else System.Console.WriteLine ( `` The cat 's age is { 0 } years '' , c... | What is the justification for this Nullable < T > behavior with implicit conversion operators |
C# | In .NET Core and .NET Framework 4.x the following code works as expected : However , in netstandard , the Name property in Group is gone . I 'm wondering if there is a new way of achieving the same thing , or if this is a bug.Edit : I first thought this was a netstandard 2.0 issue , but it looks like the property is mi... | var match = Regex.Match ( src , pattern ) .Groups .Cast < Group > ( ) .Where ( grp = > grp.Name.StartsWith ( `` val '' ) ) ; | netstandard - Regular Expression , Group Name inaccessible |
C# | Take the following code : using those typesCompiled with C # 5 compiler against .NET 4.5.1 ( the behaviour is probably the same using older compiler/framework version ) this generates the following error : Now , I have a pretty good idea what is happening under the covers ( I blogged about it here ) but I ca n't come u... | ICanQuack quack = new Duck ( ) ; var map = ( object ) `` a map '' ; quack.Fly ( ( dynamic ) map ) ; public interface ICanFly { void Fly < T > ( T map ) ; } public interface ICanQuack : ICanFly { void Quack ( ) ; } public class Duck : ICanQuack { public void Fly < T > ( T map ) { Console.WriteLine ( `` Flying using a { ... | C # dynamic fails invoking method from a base interface |
C# | I 'm writing a Tetris-clone and I 'm prototyping in C # . The final code is supposed to run on an embedded system ( using an 8-Bit CPU and very little RAM ) , so I 'm trying to use a naïve algorithm to do line clear.Right now , my playfield is a 2D Array : ( where TetrominoType is an enum to indicate either None or one... | private readonly TetrominoType [ ] [ ] _playfield ; Before After0 # # # # 1 # # # # 2 # # # # 3 # # # # 4 # # # # 5 # xxxxxx # # # 6 # x xx # # # 7 # xxxxxx # # # 8 # xxxxxx # # x xx # 9 # x xxxx # # x xxxx # # # # # # # # # # # # # # # # # for ( int iy = 9 ; iy > = 0 ; iy -- ) { if ( _linesToClear.Contains ( iy ) ) { ... | Naive Gravity for Tetris game using 2D Array for the playfield |
C# | In C++ the compiler knows about primitive data types such as int , but in C # these are basically structures ( e.g . System.Int32 ) . But can I assume that C # knows about these types . I think that it does , because an int literal in C # is basically an instance of System.Int32 . For example this will work : Output : | Console.WriteLine ( ( 12345 ) .GetType ( ) ) ; System.Int32 | Are C # primitive data types part of the language ? |
C# | I have a Windows application that is connecting to a WCF Data Service hosted on the same machine.The first thing that occurs when the application starts is a query that returns 0 to 3 results . Here 's the code : The very next thing I do is check if ( environments.Count ( ) == 0 ) which takes about 10 seconds to evalua... | var environments = ctx.Environments.AddQueryOption ( `` $ filter '' , `` Environment eq ' '' + ConfigurationManager.AppSettings [ `` environment '' ] + `` ' '' ) .AddQueryOption ( `` $ expand '' , `` Departments , SecurityGroups '' ) ; | Why is WCF Data Service performing better while Fiddler is running ? |
C# | I am testing my asp.net core 2.2 web api with Postman . I write the JSON manually like this ( httppatch ) : Now I am thinking how can I build the patch body on the client side.My question is how can I get the equivalent of this code in json to make it look like the one I write manually ? I guess it 's all about seriali... | { `` query '' : `` { \ '' name\ '' : \ '' foo\ '' } '' , `` update '' : [ `` { \ '' $ set\ '' : { \ '' name\ '' : \ '' foo2\ '' } } '' , '' { \ '' $ set\ '' : { \ '' path\ '' : \ '' foo2 path\ '' } } '' ] } var query = Builders < T > .Filter.Eq ( e = > e.name , `` foo '' ) ; var updates = Builders < T > .Update.Set ( e... | Mongodb Bson type to Json |
C# | I have an interesting situation . When I run a query on remote SQL server in Microsoft SQL Server Management Studio it runs fast ( 12 sec ) , but when I run the same query in Entity Framework using DbContext.Database.SqlQuery < EntityType > ( script ) it takes 48 seconds.I tried setting set arithabort on . The setting ... | declare @ t table ( ... ) insert into @ tselect < long query > select top 1 * from @ t using ( var connection = new SqlConnection ( DbContext.Database.Connection.ConnectionString ) ) using ( var cmd = new SqlCommand ( script , connection ) ) { connection.Open ( ) ; cmd.CommandType = CommandType.Text ; using ( SqlDataRe... | Entity Framework data reading performance |
C# | Given this XML ... And this C # code : I know the Xdoc is not empty and contains the right XML.I also implemented some ScottGu code ( http : //weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx ) as a sanity check and it works exactly as expected . | < ListBucketResult xmlns= '' http : //s3.amazonaws.com/doc/2006-03-01/ '' > < Name > public.rpmware.com < /Name > < Prefix > < /Prefix > < Marker > < /Marker > < MaxKeys > 1000 < /MaxKeys > < IsTruncated > false < /IsTruncated > < Contents > < Key > 0.dir < /Key > < LastModified > 2008-06-25T16:09:49.000Z < /LastModifi... | Why is n't this LINQ to XML Query Working ( Amazon S3 ) |
C# | I 've a project where I am extensively using the generic C # dictionary . I require composite keys , so I 've been using tuples as keys . At some point I was wondering whether it would be beneficial to use a custom class which caches the hash code : I used new instead of override because I thought it would not make a d... | public class CompositeKey < T1 , T2 > : Tuple < T1 , T2 > { private readonly int _hashCode ; public CompositeKey ( T1 t1 , T2 t2 ) : base ( t1 , t2 ) { _hashCode = base.GetHashCode ( ) ; } public new int GetHashCode ( ) { return _hashCode ; } } var dict = new Dictionary < CompositeKey < string , int > , int > ( ) ; var... | Why does the C # dictionary not call the hidden GetHashCode method |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.