lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
C# | I think it was in .net 2.0 , microsoft introduced an accessor that was abbreviated to something likepublic string Name { get ; set ; } But is there any real difference between the above code , and simply : | public string Name ; | Public accessor .net |
C# | I need to display a PieChart , I 'm currently using Modern UI ( Metro ) Charts . I did copy the code in the documentation and the problem is that i 'm always having the border and the title in the screen but no chart.XAMLCS | < UserControl x : Class= '' Projet.Recources0.Statistique.Ad_Aj '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.micro... | PieChart Does Not Show Up |
C# | In my ASP.NET MVC 4 / EF 5 web application 's database I have a table with a Comments column that I want to concat new comments to . In traditional T-SQL , I 'd write : I find with method linq for EF ( uow + repository pattern -- which I regret ) , I have to first query the current value of Comments and prepend my new ... | UPDATE MyTable SET Comments = 'Hi ' + CHAR ( 13 ) +CHAR ( 10 ) + Comments WHERE ID = 2 StringBuilder displayComment = new StringBuilder ( ) ; var item = uow.MyRepos.Where ( i = > i.ID == 2 ) ; item.Comments = displayComment.Append ( `` Hi '' ) .Append ( Environment.NewLine ) .Append ( item.Comments ) .ToString ( ) ; uo... | How to cause EF to build update SQL with string concat ? |
C# | New to Unity and C # This is actually just a small issue that I 'm curious about ... I ran into it while tweaking this code in a ( failed ) attempt to make it work . I have been trying to get this code to work for a few hours now . Anyway , when this code is executed , there is only one error , but it appears 3 times .... | using System.Collections ; using System.Collections.Generic ; using UnityEngine ; public class PlatformGenerator : MonoBehaviour { public GameObject Single ; private GameObject NewPillar ; private int PillarCount ; private bool run ; private int px ; private int py ; private int pz ; void Start ( ) { px = 0 ; py = 0 ; ... | Instantiating a GameObject causes said object to have its Transform destroyed ? |
C# | According to .NET MemoryStream - Should I set the capacity ? , it 's preferred to set the initial capacity of a MemoryStream if you know it beforehand.In my code , I 'm receiving ( from a third party library ) a Stream object . This Stream is wrapped around a GetObjectResponse class.Since this class will be disposed af... | Stream destination = new MemoryStream ( response.ResponseStream.Length ) ; | Why does MemoryStream not offer a constructor taking a `` long '' capacity ? |
C# | Suppose I have the following class structure : PageThe Page , StaticPage and DynamicPage interfaces are to be implemented by the clients . They provide various data depending on the page type ( static or dynamic ) , which is used to render the page by the Renderer . There might be many implementations of these interfac... | void render ( Page page , Renderer renderer ) { if ( page is StaticPage ) { renderer.renderStaticPage ( page ) ; } else if ( page is DynamicPage ) { renderer.renderDynamicPage ( page ) ; } else { throw new Exception ( `` page type not supported '' ) ; } } | How to do multiple dispatch on interface in C # ? |
C# | Why databinding TwoWay do n't work on the text property of a combobox in .net 4.0 ( it 's working in .net 3.5 ) ? My code : I have an xml file like this : and I have a ListItem control like that : Here is the code behind : I do like that because I can have a ComboBox with auto-completion with the different custom optio... | < xml > < combobox option= '' '' obs= '' tralala '' > < option value= '' here '' / > < option value= '' there '' / > < /combobox > < combobox option= '' blue '' obs= '' '' > < option value= '' one '' / > < option value= '' two '' / > < option value= '' three '' / > < /combobox > < /xml > < ListBox DataContext= '' { Bin... | XAML - Why databinding TwoWay do n't work on the text property of a combobox in .net 4.0 ? |
C# | I 've run into a bit on an Anomaly where for the first time ever , using the var keyword bit me.Take this very simple methodNow we can call this method with a dynamic parameter and everything will work as expected.However , by declaring shouldBeNullableInt32 using implicit typing , the results are far from what I would... | public static Int32 ? GetNullableInt32 ( Int32 num ) { return new Nullable < Int32 > ( num ) ; } public static void WorksAsAdvertised ( ) { dynamic thisIsAnInt32 = 42 ; //Explicitly defined type ( no problems ) Int32 ? shouldBeNullableInt32 = GetNullableInt32 ( thisIsAnInt32 ) ; Console.Write ( shouldBeNullableInt32.Ha... | Anomaly when using 'var ' and 'dynamic ' |
C# | I have a search application that takes some time ( 10 to 15 seconds ) to return results for some requests . It 's not uncommon to have multiple concurrent requests for the same information . As it stands , I have to process those independently , which makes for quite a bit of unnecessary processing.I 've come up with a... | class SearchRequest : IDisposable { public readonly string RequestKey ; public string Results { get ; set ; } public ManualResetEvent WaitEvent { get ; private set ; } public SearchRequest ( string key ) { RequestKey = key ; WaitEvent = new ManualResetEvent ( false ) ; } public void Dispose ( ) { WaitEvent.Dispose ( ) ... | How do I know when it 's safe to call Dispose ? |
C# | This question is about the threshold at which Math.Floor ( double ) and Math.Ceiling ( double ) decide to give you the previous or next integer value . I was disturbed to find that the threshold seems to have nothing to do with Double.Epsilon , which is the smallest value that can be represented with a double . For exa... | double x = 3.0 ; Console.WriteLine ( Math.Floor ( x - Double.Epsilon ) ) ; // expected 2 , got 3Console.WriteLine ( Math.Ceiling ( x + Double.Epsilon ) ) ; // expected 4 , got 3 Console.WriteLine ( Math.Floor ( x - Double.Epsilon*1000 ) ) ; // expected 2 , got 3Console.WriteLine ( Math.Ceiling ( x + Double.Epsilon*1000... | Unexpected Behavior of Math.Floor ( double ) and Math.Ceiling ( double ) |
C# | I 'm using Mono.Cecil 0.9.5.3 , and after installing VS2012 RC ( which causes the .NET 4.0 System.XML.DLL to be replaced with its .NET 4.5 counterpart ) , I get an System.ArugmentException in some code that iterates each methods ' custom attributes . It appears the cause is that in certain cases , the AsyncStateMachine... | string path = Assembly.Load ( `` System.Xml , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' ) .Location ; AssemblyDefinition systemXmlAssembly = AssemblyDefinition.ReadAssembly ( path ) ; var query = from ModuleDefinition module in systemXmlAssembly.Modules from TypeDefinition td in module.Type... | Mono.Cecil Exception thrown when analyzing .NET 4.5 version of System.Xml DLL , why ? |
C# | I am trying to deserialize my packages.config file in C # but the Collection i get back is always null . Is there something special that is needed if my xml file consists of a single collection of attributes ? where my packages.config looks like | [ Serializable ( ) ] [ System.Xml.Serialization.XmlTypeAttribute ( ) ] public class Package { [ System.Xml.Serialization.XmlAttribute ( `` id '' ) ] public string Id { get ; set ; } [ System.Xml.Serialization.XmlAttribute ( `` version '' ) ] public string Version { get ; set ; } } [ Serializable ( ) ] [ System.Xml.Seri... | Why does deserializing my packages.config in c # return null values ? |
C# | I have the following string : I want to split it according to 1 . 2 . 3. and so on : Is there any way I can do it C # ? | string text = `` 1 . This is first sentence . 2 . This is the second sentence . 3 . This is the third sentence . 4 . This is the fourth sentence . '' result [ 0 ] == `` This is first sentence . `` result [ 1 ] == `` This is the second sentence . `` result [ 2 ] == `` This is the third sentence . `` result [ 3 ] == `` T... | String split using C # |
C# | I got hit by a strange `` asymmetry '' in C # that I do not really understand . See the following code : It might be obvious for all you .NET gurus , but the 2nd assert fails.In Java I have learnt that == is a synonym for something called Object.ReferenceEquals here . In C # , I thought that Object.operator== uses Obje... | using System ; using System.Diagnostics ; namespace EqualsExperiment { class Program { static void Main ( string [ ] args ) { object apple = `` apple '' ; object orange = string.Format ( `` { 0 } { 1 } '' , `` ap '' , `` ple '' ) ; Console.WriteLine ( `` 1 '' ) ; Debug.Assert ( apple.Equals ( orange ) ) ; Console.Write... | Object.Equals is virtual , but Object.operator== does not use it in C # ? |
C# | I am a C++ developer and recently started working on WPF . Well I am using Array.Copy ( ) in my app and looks like I am not able to completely get the desired result . I had done in my C++ app as follows : I did the similar operation in my WPF ( C # ) app as follows : But it throws me an error at Array.Copy ( sendBuf +... | static const signed char version [ 40 ] = { ' A ' , ' U ' , 'D ' , ' I ' , ' E ' , ' N ' , ' C ' , ' E ' , // name 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // reserved , firmware size 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // board number 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // variant , version , serial 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 // da... | Failing to use Array.Copy ( ) in my WPF App |
C# | I 'm fairly experienced in .NET development but today I was forced to wrap my head around something I 'd never thought about before : How do the installed .NET Framework , the .NET Framework target in Visual Studio and the C # compiler work together ? Concrete example : The System.dll contains the enum System.Net.Secur... | var p = SecurityProtocolType.SystemDefault ; | .NET target framework compatibility and the compiler - on .NET 4.5 or higher |
C# | My MVC webapp allows users to add and delete images . The UI calls ImageService.SaveImage ( ... ) in my business layer which internally uses a flag that tells the method to save to either Azure or the file system . I might eventually add S3 to I figure an interface here would work great . This is what I would imaging t... | // Service the UI usespublic static class ImageService { public static void SaveImage ( byte [ ] data , IImageProvider imageProvider ) { string fileName = `` some_generated_name.jpg '' imageProvider.Save ( fileName , data ) ; } } public interface IImageProvider { void Save ( string filename , byte [ ] imageData ) ; byt... | How to implement interface with additional parameters/info per implementation |
C# | The text `` lblDate.Content '' disappears when I use the sleep timer to close the window . How do I get that text to display ? The rest of the window/text is shown . I 'm open to other ways to autoclose a window . | public void DisplayErrorMessage ( string message ) { // Error Message TextBox textBox1.Text = message ; Show ( ) ; // Show date and logged message lblDate.Content = `` This error has been logged and an administrator contacted : `` + DateTime.Now ; // Auto close window System.Threading.Thread.Sleep ( 3000 ) ; this.Close... | c # autoclose window with sleep but text disappears |
C# | This is the c # codeThis is the IL of M1 methodMy question is : Why twice ldarg.0 ? | class SimpleIL { private int f = 2 ; public void M1 ( ) { M2 ( f ) ; } public void M2 ( Object p ) { Console.WriteLine ( p ) ; } } IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.0 IL_0003 : ldfld int32 ConsoleApplication1.SimpleIL : :f IL_0008 : box [ mscorlib ] System.Int32 IL_000d : call instance void ConsoleApplica... | IL code , Someone get me explain why ldarg.0 appear twice ? |
C# | I have a Class that retrieves some data and images does some stuff to them and them uploads them to a third party app using web services.The object needs to perform some specific steps in order.My question is should I be explicitly exposing each method publicly like so . or should all of these methods be private and en... | myObject obj = new myObject ( ) ; obj.RetrieveImages ( ) ; obj.RetrieveAssociatedData ( ) ; obj.LogIntoThirdPartyWebService ( ) ; obj.UploadStuffToWebService ( ) ; public class myObject ( ) { private void RetrieveImages ( ) { } ; private void RetrieveAssociatedData ( ) { } ; private void LogIntoThirdPartyWebService ( )... | Should methods that are required to be executed in a specific order be private ? |
C# | I have a WCF service that has a few different responsibilities , but it provides one entry point for anyone interacting with my code . To keep it simple , let 's say there are 2 methodsBecause consumers will only call the service for one reason , MethodA or MethodB , is it a problem that the IOC container will be needl... | private IMethodAHelper _methodA ; private IMethodBHelper _methodB ; public MyService ( IMethodAHelper methodA , IMethodBHelper methodB ) { _methodA = methodA ; _methodB = methodB ; } public void MethodA ( ) { _methodA.CallThis ( ) ; } public void MethodB ( ) { _methodB.CallThis ( ) ; } public void MethodA ( ) { var met... | IOC Container - WCF Service - Should I instantiate all dependencies via constructor ? |
C# | To reduce redundant code , I have some throw helper methods : Usage : Problem : Because the operator + must always return a value , I fixed this by making ThrowInvalidOperation return a value and call it with returnThrowInvalidOperation ( `` + '' , a , b ) ; There a many disadvatages - one is because I ca n't call it f... | protected static X ThrowInvalidOperation ( string operation , X a , X b ) { throw new InvalidOperationException ( `` Invalid operation : `` + a.type.ToString ( ) + `` `` + operation + `` `` + b.type.ToString ( ) ) ; } public static X operator + ( X a , X b ) { if ( ... ) { return new X ( ... ) ; } return ThrowInvalidOp... | Thoughts on throw helpers |
C# | I want a function that I can call as an alternative to .ToString ( ) , that will show the contents of collections.I 've tried this : but the second overload never gets called . For example : I 'm expecting this output : What actually happens is this : dict is correctly interpreted as an IEnumerable < KeyValuePair < int... | public static string dump ( Object o ) { if ( o == null ) return `` null '' ; return o.ToString ( ) ; } public static string dump < K , V > ( KeyValuePair < K , V > kv ) { return dump ( kv.Key ) + `` = > '' + dump ( kv.Value ) ; } public static string dump < T > ( IEnumerable < T > list ) { StringBuilder result = new S... | How do I convert IEnumerable < T > to string , recursively ? |
C# | 15 years ago , while programming with Pascal , I understood why to use power of two 's for memory allocation . But this still seems to be state-of-the-art.C # Examples : I still see this thousands of times , I use this myself and I 'm still questioning : Do we need this in modern programming languages and modern hardwa... | new StringBuilder ( 256 ) ; new byte [ 1024 ] ; int bufferSize = 1 < < 12 ; | Why does everyone use 2^n numbers for allocation ? - > new StringBuilder ( 256 ) |
C# | I have created a controller with an Index action . All of my other Actions return the views just fine ... but for some reason I have to specify the full url to have the Index view return . It 's almost like my Routes are n't working correctly.For instance , to go to the properties page , you have to go to /Properties/I... | routes.MapRoute ( name : `` Index '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; | MVC4 Index Action Not Working Correctly |
C# | I have implemented the following benchmark using BenchmarkDotNet : The results are : Originally I guessed the Array.Fill does some optimizations which make it perform better than for-loop , but then I checked the .NET Core source code to see that the Array.Fill implementation is pretty straightforward : The performance... | public class ForVsFillVsEnumerable { private bool [ ] data ; [ Params ( 10 , 100 , 1000 ) ] public int N ; [ GlobalSetup ] public void Setup ( ) { data = new bool [ N ] ; } [ Benchmark ] public void Fill ( ) { Array.Fill ( data , true ) ; } [ Benchmark ] public void For ( ) { for ( int i = 0 ; i < data.Length ; i++ ) {... | Performance difference between C # for-loop and Array.Fill |
C# | I am working on implementing AutoMapper in our service and am seeing a very confusing issue in our unit tests.First off this issue involves the following objects and their respective maps : It also involves these objects , though I have n't mapped these with AutoMapper at this point : These classes are converted using ... | public class DbAccount : ActiveRecordBase < DbAccount > { // this is the ORM entity } public class Account { // this is the primary full valued Dto } public class LazyAccount : Account { // this class as it is named does n't load the majority of the properties of account } Mapper.CreateMap < DbAccount , Account > ( ) ;... | How to stop Automapper from mapping to parent class when child class was requested |
C# | So I 've been tinkering with Linq.Expressions ( and if anyone can suggest a more proper or more elegant way to do what I 'm doing please feel free to chime in ) and have hit a wall in trying to do something . Let 's imagine we have a simple math class : I decide I want to convert our AddNumbers method to a simple Func ... | public class SimpleMath { public int AddNumbers ( int number1 , int number2 ) { return number1 + number2 ; } } // Two collections , one for Type Object paramaters and one for converting to Type int.List < ParameterExpression > parameters = new List < ParameterExpression > ( ) ; List < Expression > convertedParameters =... | Linq.Expression TryCatch - Pass exception to Catch Block ? |
C# | I have about 100k Outlook mail items that have about 500-600 chars per Body . I have a list of 580 keywords that must search through each body , then append the words at the bottom.I believe I 've increased the efficiency of the majority of the function , but it still takes a lot of time . Even for 100 emails it takes ... | public List < string > Keyword_Search ( HtmlNode nSearch ) { var wordFound = new List < string > ( ) ; foreach ( string currWord in _keywordList ) { bool isMatch = Regex.IsMatch ( nSearch.InnerHtml , `` \\b '' + @ currWord + `` \\b '' , RegexOptions.IgnoreCase ) ; if ( isMatch ) { wordFound.Add ( currWord ) ; } } retur... | Increasing Regex Efficiency |
C# | Suppose I have a list of strings , like this : Now I 'd like to verify that another List < String > , let 's call it list1 , contains each of those candidates exactly once . How can I do that , succintly ? I think I can use Intersect ( ) . I also want to get the missing candidates . Order does n't matter . | var candidates = new List < String > { `` Peter '' , `` Chris '' , `` Maggie '' , `` Virginia '' } ; private bool ContainsAllCandidatesOnce ( List < String > list1 ) { ? ? ? ? } private IEnumerable < String > MissingCandidates ( List < String > list1 ) { ? ? ? ? } | how to ensure a List < String > contains each string in a sequence exactly once |
C# | This is asked more out of curiosity than with regards to any real-world problem . Consider the following code : In the synchronous world , this would ultimately cause a stackoverflow.In the async world , this simply consumes a lot of memory ( which I assume is related to something that I might loosely call the `` async... | void Main ( ) { FAsync ( ) .Wait ( ) ; } async Task FAsync ( ) { await Task.Yield ( ) ; await FAsync ( ) ; } | Async recursion . Where is my memory actually going ? |
C# | I have a WCF service hosted in a consol application ( that also acts as the Windows Service installer ) , pleas see more here : http : //msdn.microsoft.com/en-us/library/ms733069.aspxThis is how the class in the consol application looks like : This is made for running in a Windows Service , how do I make so I can run t... | public class MyAppWindowsService : ServiceBase { public ServiceHost _MyAppClientServiceHost = null ; public ServiceHost _MyAppIntegrationServiceHost = null ; public ServiceHost _MyAppserviceHost = null ; public MyAppWindowsService ( ) { // Name the Windows Service ServiceName = `` MyApp Service '' ; } public static voi... | Running consol application in debug mode with WCF selfhosting ? |
C# | While doing some fancy code generation , I 've encountered a stack overflow that I do n't understand.My code is basically like this : If you use small numbers like here ( 100 ) everything works fine . If the numbers are large , strange things happens . In my case , I tried emitting approximately 10K lines of code like ... | static Tuple < string , int > [ ] DoWork ( ) { // [ call some methods ] Tuple < string , int > [ ] tmp = new Tuple < string , int > [ 100 ] ; tmp [ 0 ] = new Tuple < string , int > ( `` blah 1 '' , 0 ) ; tmp [ 1 ] = new Tuple < string , int > ( `` blah 2 '' , 1 ) ; tmp [ 2 ] = new Tuple < string , int > ( `` blah 3 '' ... | Weird stackoverflow in c # when allocating reference types |
C# | I 'm getting an odd response from a site that I was looking to parse with FiddlerCore . In chrome developer tools if I inspect the response it looks completely normal , in fiddler it does n't . Code snippet as follows ( which used to work fine ) Returns the following , which is n't html , note this is a sample rather t... | String html = oSession.GetResponseBodyAsString ( ) ; JRHwJNeR\0���\0\0\u0001��D\0�2�\b\0�\u0016�7 ] < ! DOCTYPE html > \n win\ '' > \n\n\n\n\n \n < meta name=\ '' treeID\ '' content=\ '' dwedxE+pgRQAWIHiFSsAAA==\ '' > \n Cache-Control : no-cache , no-storeConnection : keep-aliveContent-Encoding : sdch , gzipContent-Lan... | FiddlerCore decoding an sdch response |
C# | I have a C # method that looks a bit like this : In F # this ends up looking quite a bit uglier because of the mandatory else branches : What would be a cleaner way of writing this in F # ? | bool Eval ( ) { // do some work if ( conditionA ) { // do some work if ( conditionB ) { // do some work if ( conditionC ) { // do some work return true ; } } } return false ; } let eval ( ) = // do some work if conditionA then // do some work if conditionB then // do some work if conditionC then // do some work true el... | How can I refactor out the required else clause ? |
C# | The following example shows Type.GetType failing in a specific scenario.GetType succeeds when I provide it the class name string ( including namespace ) in a lambda expression , but fails when I specify the call to GetType as a method group.Fails : Succeeds : Both methods succeed when the class path includes the assemb... | collectionOfClassNames.Select ( GetType ) collectionOfClassNames.Select ( s = > GetType ( s ) ) using System ; using System.Linq ; using System.Reflection ; namespace GetTypeTest { public class FindMe { } class Program { static void Main ( string [ ] args ) { var assemblyName = Assembly.GetExecutingAssembly ( ) .FullNa... | Type.GetType fails when invoked as method group but not in lambda expression |
C# | I 'm trying to find a way to loop through all the controls of type 'Checkbox ' in a ASP Placeholder , and then do something with the control in the loop.Problem is I ca n't access the controls ... here is what I have so far ... But I 'm getting the error - `` Foreach can not operate on a method group '' .Any help would... | string selections = `` '' ; foreach ( CheckBox ctrl in phProductLines.Controls.OfType < CheckBox > ) { selections += ctrl.Text + `` , `` ; } | Loop through Checkboxes in Placholder |
C# | public class Item { ... } Now , using LINQ I need to get all items that a customer bought . How can I ? I tried something like var items = from o in cust.Orders select o.Items ; but result is IEnuberable < List < Item > > and I wan na just one IEnumerable < Item > .I 'm asking here to try to avoid coding 2 loops . | public class Order { public List < Item > Items ... } public class Customer { public List < Order > Orders ... } | Get a IEnumerable < T > from a IEnumerable < IEnumerable < T > > |
C# | I have this C # method which I 'm trying to optimize : The function basically compares two int arrays . For each pair of matching elements , the method compares each individual byte value and takes the larger of the two . The element in the first array is then assigned a new int value constructed from the 4 largest byt... | // assume arrays are same dimensionsprivate void DoSomething ( int [ ] bigArray1 , int [ ] bigArray2 ) { int data1 ; byte A1 , B1 , C1 , D1 ; int data2 ; byte A2 , B2 , C2 , D2 ; for ( int i = 0 ; i < bigArray1.Length ; i++ ) { data1 = bigArray1 [ i ] ; data2 = bigArray2 [ i ] ; A1 = ( byte ) ( data1 > > 0 ) ; B1 = ( b... | Help with optimizing C # function via C and/or Assembly |
C# | So I 'm writing tests for our MVC4 application and I 'm testing Controller actions specifically . As I mention in the title , the test still hits the service ( WCF ) instead of returning test data . I have this controller : And it uses this DAO object : And this is my test using JustMock , the mock on GetForms ( ) retu... | public class FormController : Controller { public SurveyServiceClient Service { get ; set ; } public SurveyDao Dao { get ; set ; } public FormController ( SurveyServiceClient service = null , SurveyDao dao = null ) { this.Service = service ? ? new SurveyServiceClient ( ) ; this.Dao = dao ? ? new SurveyDao ( Service ) ;... | Mocked Object Still Making Calls to Service |
C# | I have an interface : I 'd like to configure Ninject ( v3 ) bindings so that I can have a `` dispatcher '' shuffle method calls out to multiple instances of IService , like so : However , my bindings , that look like this , wind up throwing an exception at runtime indicating a cyclic dependency : Is this possible ? If ... | public interface IService { void DoStuff ( int parm1 , string parm2 , Guid gimmeABreakItsAnExampleK ) ; } public sealed class DispatcherService : IService { private IEnumerable < IService > _children ; public DispatcherService ( IEnumerable < IService > children ) { this._children = children.ToList ( ) ; } public void ... | Ninject bindings for a dispatcher implementation of an interface |
C# | Could someone explain what this C # code is doing ? I know that CameraCaptureTask is a class and has a public method Show ( ) . What kind of event is this ? what is ( s , e ) ? | // launch the camera capture when the user touch the screenthis.MouseLeftButtonUp += ( s , e ) = > new CameraCaptureTask ( ) .Show ( ) ; // this static event is raised when a task completes its jobChooserListener.ChooserCompleted += ( s , e ) = > { //some code here } ; | What is this event ? |
C# | I am going through a LitJSON library . In the code there are lots of segments likeFor a method I know how overriding/overloading works but in the example above the code reads : int ICollection.CountI 'm not familiar with that format for a method signature . Is the coder trying to explicitly state its the ICollection.Co... | public class JsonData : IJsonWrapper , IEquatable < JsonData > # region ICollection Properties int ICollection.Count { get { return Count ; } } # end region | What is it called when you edit an interface ? |
C# | In VS2012 's C # the following code : results in a printed to console output window . The spaces are separated by 0xFFFD yet it matches two consecutive spaces . Is that an expected result/feature or a ( known ) bug ? | string test = `` [ `` + ( char ) 0xFFFD + `` ] '' ; System.Console.WriteLine ( `` { 0 } '' , test.IndexOf ( `` `` ) == 1 ) ; True | IndexOf matching when Unicode 0xFFFD is in the string - bug or feature ? |
C# | I am currently trying to add an order by to a LINQ query that will order by a datetime field in an EF object : When the SortingDirection is set to desc it works fine . But when set to asc I get no records ! Upon looking at SQL Server Profiler , it turns out that DateTime objects are being formatted differently ! For DE... | return this.SortingDirection.Equals ( `` asc '' , StringComparison.InvariantCultureIgnoreCase ) ? entities.OrderBy ( e = > e.ProcessStartTime ) : entities.OrderByDescending ( e = > e.ProcessStartTime ) ; ORDER BY [ Project1 ] . [ StartTime ] DESC ' , N ' ... @ p__linq__22='2015-01-07 09:00:23 ' , @ p__linq__23='2015-01... | Order by ( asc|desc ) in linq to SQL Server handles DateTime differently |
C# | I have an issue with ListBoxItems . I am trying to make all controls in the ListBoxItem select it as well , so clicking on a TextBox , Label , etc will select the ListBoxItem . Pretty simple so far . I am also changing the ListBoxItem Template to change the selection visualization from highlighting the background to ju... | < Window x : Class= '' ListBoxClickThroughTest.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Width= '' 525 '' Height= '' 350 '' > < Grid > < ListBox ItemsSource= '' { Binding Items } '' Selec... | WPF ListBoxItem ControlTemplate breaks some MouseDown/Selection |
C# | I have an ASP.Net web page that currently works on the iOS4 but not on the iOS5 . On the parent web page I have a button that opens a child window . And I do a setTimeout refresh thing in the parent window right after the open window call.I noticed on the iPhone iOS5 that when it opens the child window , the setTimeout... | WindowManager.OpenWindow ( ' ... ' ) t = setTimeout ( function ( ) { handles [ 0 ] .testfx ( ) ; } , 1000 ) ; | JavaScript setTimeout not firing after Window.Open |
C# | I am trying run a Datastore query to get a list of names and prices . However , I keep getting this error message : Can not implicitly convert type 'Google.Cloud.Datastore.V1.DatastoreQueryResults ' to 'System.Collections.Generic.List < TestApp.Models.AllSportsStore > 'This is the code I am using : AllSportsStore.cs Pa... | public DatastoreDb _db ; [ BindProperty ] public List < AllSportsStore > SportsStoreList { get ; set ; } public void OnGet ( ) { Environment.SetEnvironmentVariable ( `` GOOGLE_APPLICATION_CREDENTIALS '' , Path.Combine ( AppDomain.CurrentDomain.BaseDirectory , `` xxxxx.json '' ) ) ; _db = DatastoreDb.Create ( `` project... | Datastore Query Array |
C# | I 've got an app that has to do the following type of things , preferably on the GUI thread since that 's where most of the action is taking place and there 's no long-running ops : I realize I could use a timer with a state-machine style OnTick function , but that seems cumbersome : Plus I 'd like to be able to make i... | Wait 1000FuncA ( ) Wait 2000FuncB ( ) Wait 1000FuncC ( ) int _state ; void OnTick ( object sender , EventArgs e ) { switch ( _state ) { case 0 : FuncA ( ) ; _timer.Interval = TimeSpan.FromSeconds ( 2 ) ; _state = 1 ; break ; case 1 : FuncB ( ) ; _timer.Interval = TimeSpan.FromSeconds ( 1 ) ; _state = 2 ; break ; case 2... | How does one kick off a timed sequence of events on the GUI thread in C # ? |
C# | I am using .Net Core 3.1 Framework in WPF Application . I have a button event in which I am trying to redirect to Instagram url on click . but its giving me the following error . Exception thrown : 'System.ComponentModel.Win32Exception ' in System.Diagnostics.Process.dll . | private void Insta_Click ( object sender , RoutedEventArgs e ) { try { string targetURL = `` https : //www.instagram.com/xyz/ '' ; Process.Start ( targetURL ) ; } catch { } } | .Net Core 3.1 Process.Start ( `` www.website.com '' ) not working in WPF |
C# | I 've been playing with RavenDB recently and there is something that is annoying me a little . I have an entity object with a series of value objects , e.g . There are a number of times when I want to pass an object of type Bar into a method/class but at some point want to reference back to the parent entity . In the w... | class Foo { IList < Bar > Bars { get ; set ; } } class Bar { Foo Foo { get ; set ; } } void DoSomething ( Foo foo , Bar bar ) { Console.WriteLine ( foo ) ; Console.WriteLine ( bar ) ; } void DoSomething ( Bar bar ) { Console.WriteLine ( bar.Foo ) ; Console.WriteLine ( bar ) ; } | Reference a value objects parent entity object in RavenDb |
C# | Is it necessary to protect access to a single variable of a reference type in a multi-threaded application ? I currently lock that variable like this : But I 'm wondering if this is really necessary ? Is n't assignment of a value to a field atomic ? Can anything go wrong if I do n't lock in this case ? P.S . : MyType i... | private readonly object _lock = new object ( ) ; private MyType _value ; public MyType Value { get { lock ( _lock ) return _value ; } set { lock ( _lock ) _value = value ; } } | Is a lock necessary in this situation ? |
C# | I ran into a weird issue and I 'm wondering what I should do about it.I have this class that return a IEnumerable < MyClass > and it is a deferred execution . Right now , there are two possible consumers . One of them sorts the result.See the following example : Consumers call the deferred execution only once , but if ... | public class SomeClass { public IEnumerable < MyClass > GetMyStuff ( Param givenParam ) { double culmulativeSum = 0 ; return myStuff.Where ( ... ) .OrderBy ( ... ) .TakeWhile ( o = > { bool returnValue = culmulativeSum < givenParam.Maximum ; culmulativeSum += o.SomeNumericValue ; return returnValue ; } ; } } return myS... | Ensure deferred execution will be executed only once or else |
C# | Should I worry about the order of Entity Framework linq query clauses in terms of performance ? In the example below could changing the order of the two where clauses have an performance impact on the DB lookup ? | using ( var context = new ModelContext ( ) ) { var fetchedImages = ( from images in context.Images.Include ( `` ImageSource '' ) where images.Type.Equals ( `` jpg '' ) where images.ImageSource.Id == 5 select images ) .ToArray ( ) ; } | Does the order of EF linq query clauses influence performance ? |
C# | Currently in my code I have a method like this : What Im trying to do is selecting the interface method using lambda expression and then get the name of method inside AddMethod . So the result would be : I have tried this : But the problem is some of the interface methods have input parameters which I 'm trying to igno... | .AddMethod ( nameof ( IRoleService.GetRoles ) ) .AddMethod < IRoleService > ( x= > x.GetRoles ) AddMethod < T > ( Expression < Func < T , Action > > expression ) ; | Selecting a class method name using Lambda Expression |
C# | Suppose I have a method like so : Would this still dispose the 'ms ' object ? I 'm having doubts , maybe because something is returned before the statement block is finished.Thanks , AJ . | public byte [ ] GetThoseBytes ( ) { using ( System.IO.MemoryStream ms = new System.IO.MemoryStream ( ) ) { ms.WriteByte ( 1 ) ; ms.WriteByte ( 2 ) ; return ms.ToArray ( ) ; } } | .NET/C # - Disposing an object with the 'using ' statement |
C# | Why does conditional if in VB require not handle the direct cast of the conditions . For example in C # this is just fine ... But if I wanted the same thing in VB I would have to cast it I do n't understand why C # will do the transform and why VB does not . Should I be casting on my C # conditionals eg Also , Yes I am... | bool i = false ; i = ( 1 < 2 ) ? true : false ; int x = i ? 5:6 ; Dim i as Boolean = CBool ( IIF ( 1 < 2 , True , False ) ) Dim x as Integer = CInt ( IIF ( i , 5 , 6 ) ) bool i = Convert.ToBoolean ( ( 1 < 2 ) ? True : False ) ; int x = Convert.ToInt32 ( i ? 5:6 ) ; | Condition if differences in C # and VB |
C# | I have a system that compiles C # code at runtime . I would like the generated assemblies to be linked to the system itself . Here 's some example code that I am using : What I would like to do is also add a reference to the main compiler program as well , so the newly compiled extension can use library routines from t... | CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < String , String > { { `` CompilerVersion '' , `` v3.5 '' } } ) ; CompilerParameters compilerparams = new CompilerParameters ( ) ; compilerparams.GenerateExecutable = false ; compilerparams.GenerateInMemory = true ; foreach ( string name in linkedre... | Compile C # code extension at runtime |
C# | What 's the best practice to check if a collection has items ? Here 's an example of what I have : The GetAllTerminals ( ) method will execute a stored procedure and , if we return a result , ( Any ( ) is true ) , SyncTerminals ( ) will loop through the elements ; thus enumerating it again and executing the stored proc... | var terminalsToSync = TerminalAction.GetAllTerminals ( ) ; if ( terminalsToSync.Any ( ) ) SyncTerminals ( terminalsToSync ) ; else GatewayLogAction.WriteLogInfo ( Messages.NoTerminalsForSync ) ; | How to properly check IEnumerable for existing results |
C# | I work with a codebase where several classes implement an indexer : When I stumble over code like foo [ 1,2 ] = 3 in visual Studio 2008 , I frequently want toright-click / `` go to definition '' , i.e . show the above definition in the visual studio editor window.For normal properties or methods this works without prob... | public double this [ int i , int j ] { get { return ... ; } set { ... ; } } | How do I `` go to definition '' for the indexer ` this [ ] ` in Visual Studio |
C# | I have a piece of code that throws a NullReferenceException : It throws because dataSource is null . GetView returns a DataTable.However , when run on the one computer ( 64 bits ) , the program continues without any problems . The Exception does happen , because when I step , I end up completely somewhere else . The de... | dataSource.DataSource = GetView ( ) ; | 32 bit program on 64 bit computer does n't crash on NullReferenceException |
C# | I am trying to understand the below code trying to use reactive extensionsIf I enter SEARC in the input box , the output looks OnNext SE OnNext SEA OnNext SEAOnNext SEAROnNext SEAR OnNext SEAROnNext SEARCOnNext SEARC OnNext SEARC OnNext SEARCWhy is `` S '' not triggering an OnNext ? Why is OnCompleted never called ? Wh... | IObservable < string > textChangedObservable = Observable.FromEventPattern < TextChangedEventArgs > ( searchScrip , `` TextChanged '' ) .Select ( evt = > ( ( TextBox ) sender ) .Text ) ; textChangedObservable.Subscribe ( OnNext , OnCompleted ) ; private void OnNext ( string s ) { System.Diagnostics.Debug.Print ( `` OnN... | Observable pattern on reactive extension |
C# | why is it , that in the following code , n does n't end up being 0 , it 's some random number with a magnitude less than 1000000 each time , somtimes even a negative number ? Does n't up.Join ( ) force both for loops to finish before WriteLine is called ? I understand that the local variable is actually part of a class... | static void Main ( string [ ] args ) { int n = 0 ; var up = new Thread ( ( ) = > { for ( int i = 0 ; i < 1000000 ; i++ ) { n++ ; } } ) ; up.Start ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { n -- ; } up.Join ( ) ; Console.WriteLine ( n ) ; Console.ReadLine ( ) ; } | Conflicting threads on a local variable |
C# | I have a system that is performing lots of calculations using decimals , occasionally it will add up the same numbers , but return different results , +/- 0.000000000000000000000000001Here is a short example : That outputs : The differences are so small that there is no practical effect , but has anyone seen something ... | decimal a = 2.016879990455473621256359079m ; decimal b = 0.8401819425625631128956517177m ; decimal c = 0.4507062854741283043456903406m ; decimal d = 6.7922317815078349615022988627m ; decimal result1 = a + b + c + d ; decimal result2 = a + d + c + b ; Console.WriteLine ( ( result1 == result2 ) ? `` Same '' : `` DIFFEREN... | Decimal order of addition affects results |
C# | I 'm trying to learn how to do Unit Testing and Mocking . I understand some of the principles of TDD and basic testing . However , I 'm looking at refactoring the below code that was written without tests and am trying to understand how it needs to change in order to make it testable . These two methods are in a single... | public class AgentRepository { public Agent Select ( int agentId ) { Agent tmp = null ; using ( IDataReader agentInformation = GetAgentFromDatabase ( agentId ) ) { if ( agentInformation.Read ( ) ) { tmp = new Agent ( ) ; tmp.AgentId = int.Parse ( agentInformation [ `` AgentId '' ] .ToString ( ) ) ; tmp.FirstName = agen... | How could I refactor this factory-type method and database call to be testable ? |
C# | Consider these two controller methods : Let 's say on the client side we do n't care about the response . We might wait for it to complete , we might abandon it half-way due user refreshing the page -- but it does n't matter that DoWithTaskRunAndReturnEarly returns earlier.Is there an important server-side difference b... | public async Task DoAsync ( ) { await TaskThatRunsFor10MinutesAsync ( ) .ConfigureAwait ( false ) ; } public void DoWithTaskRunAndReturnEarly ( ) { Task.Run ( ( ) = > TaskThatRunsFor10MinutesAsync ( ) ) ; } | What are possible issues if we await a long async operation in ASP.NET Core ? |
C# | I am using windows azure blob storage service . I want to protect my blobs from public access ( except my users ) .For this i used Shared Access Signature ( SAS ) and it works fine . But my issue is that i have a Container which contains blob in a directory structure , like : Now my requirement is that i want to give p... | https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob1 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob2 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob3 https : //xxxxxxx.blob.core.windows.net/myContainer/directory1/blob4 https : //xxxxxxx.blob.core.windows.net/myCo... | How to secure azure blobs |
C# | Is there any automated way to verify that all commits in a Git repo are in a compilable state ? I need this to verify I have n't broken anything after rewriting history . Since I 'm rewriting history , this excludes a build server - a commit that worked at the time it was committed might be broken after rewriting histo... | git filter-branch -- tree-filter msbuild | Verify that all Git commits of a C # project compile after rewriting history |
C# | System.ObjectDisposedException when the button style is set to FlatStyle.System in WinForms applicationI 've a child form which shows up on clicking a button in parent . And the code goes like below.The child form has in turn a button that closes itself.Steps to get exception : In debug mode , put a break point on Me.C... | Public Class Parent Private Sub Form1_Load ( sender As Object , e As EventArgs ) Handles MyBase.Load End Sub Private Sub btnOpenChild_Click ( sender As Object , e As EventArgs ) Handles btnOpenChild.Click Child.Show ( ) End SubEnd Class Public Class Child Private Sub btnCloseMe_Click ( sender As Object , e As EventArgs... | System.ObjectDisposedException when the button style is set to FlatStyle.System in WinForms application |
C# | Searching Effort : Google : custom c # syntaxc # floating pointStackoverflow : custom c # syntaxc # floating pointAnd some more I do not remember ... Preconception : Every `` built-in type '' in c # ( such as int , float , charetc . ) is a class , and every class in C # inherits from the Object class . Therefore , ever... | double number = new double ( ) ; number.leftSide= 5 ; number.rightSide = 23 ; Console.Write ( number ) ; // Output : // 5.23 double number = 5.23 ; Time time = 10:25 ; | How to create a custom syntax for describing an object in c # ? |
C# | I have tried to implement Read write operation using File IO operations and encapsulated those operations into TransformBlock so as to make these operation thread safe instead of using locking mechanism . But the problem is that when I try to write even 5 files parallely there is a memory out of exception and on using ... | public static readonly IsolatedStorageFile _isolatedStore = IsolatedStorageFile.GetUserStoreForApplication ( ) ; public static readonly FileIO _file = new FileIO ( ) ; public static readonly ConcurrentExclusiveSchedulerPair taskSchedulerPair = new ConcurrentExclusiveSchedulerPair ( ) ; public static readonly ExecutionD... | Memory issue in TPL Dataflow implementation of IO read write operation |
C# | I am new to WPF programming and not a professional in C # coding.So I have the following problem : I have a lot of different comboboxes and textboxes.I want to bind them to a variable in the background , because I want to fill the comboboxes with Data from a Database.So I created the following in the fileliste.xaml.cs ... | private Dictionary < string , Filter > _ctrlFilter ; public Dictionary < string , Filter > ctrlFilter { get { return _ctrlFilter ; } set { _ctrlFilter = value ; } } ctrlFilter = new Dictionary < string , Filter > { //ComboBox { `` hersteller '' , new Filter ( `` Hersteller '' , typeof ( ComboBox ) ) } , { `` fahrzeugar... | WPF Binding to dictionary with classes |
C# | I have a block of code that attempts to query some simple configuration parameters from a database . However , using the code below , as soon as I enumerate the result I get the first value for each item in the result : If I print the results ( before attempting to add them to a new dictionary ) I get something like : ... | var db = new ConfigurationServiceDataContext ( `` Server=vsdcs022.aridev.lcl ; Database=ConfigurationService ; Trusted_Connection=True ; '' ) ; var parameters = from configContents in db.ConfigurationContents where configContents.ConfigurationContextsTable.ConfigurationContextName == contextName & & configContents.Conf... | Why does iterating over IQueryable give the first value for each item in the result ? |
C# | What is the default behavior of violating the Authorize attribute in ASP.NET Core ? It seems that it redirects to the /Account/AccessDenied if the user does n't have enough rights and /Account/Login if the user did n't login yet.Am I right ? I do n't see anything about it in the docs . | [ Authorize ( Roles = `` Administrator '' ) ] public ActionResult ShutDown ( ) { } | What is the default behavior of violating the Authorize attribute in ASP.NET Core |
C# | Update : This is no longer an issue from C # 6 , which has introduced the nameof operator to address such scenarios ( see MSDN ) . Note : Refer to “ Getting names of local variables ( and parameters ) at run-time through lambda expressions ” for a generalization of this question , as well as some answers.I like the ide... | public static void CheckNotNull < T > ( Expression < Func < T > > parameterAccessExpression ) { Func < T > parameterAccess = parameterAccessExpression.Compile ( ) ; T parameterValue = parameterAccess ( ) ; CheckNotNull ( parameterValue , parameterAccessExpression ) ; } public static void CheckNotNull < T > ( T paramete... | Lambda expressions for refactor-safe ArgumentException |
C# | Curious about the reputed performance gains in xobotos , I checked out the binary tree benchmark code.The Java version of the binary tree node is : The C # version is : I 'm wondering what the benefit of using a struct here is , since the Next and Previous pointers are still encapsulated in a class . Well , there is on... | private static class TreeNode { private TreeNode left , right ; private int item ; } struct TreeNode { class Next { public TreeNode left , right ; } private Next next ; private int item ; } | XobotOS : Why does the C # binary tree benchmark use a struct ? |
C# | First of all sorry for the long question , but I could n't write it any shorter : ) Real world example : we have large roll of paper , which contains small 'stickers ' printed on them . Each sticker has a code . First two letters of the code tells us what kind of a sticker this is ( sticker that represents new roll , s... | public void AddSticker ( StickerBase sticker ) { if ( sticker.GetType ( ) .Equals ( typeof ( StickerNewRoll ) ) ) { // Next 9999 sticker should be in the form of NN0001 to NN9999 } if ( sticker.GetType ( ) .Equals ( typeof ( EnumeratedSticker ) ) ) { // Add 9999 stickers to the list , other business logic ... } if ( st... | Polymorphism design question |
C# | Here 's the deal . Have a functioning web app using ASP.NET WebForms with a C # backend . The thing works fine , but I 'm always looking to improve , as a beginner at this stuff . Right now , to deal with a user 's search coming back with no results , I utilize the following , and was wondering if there was any cleaner... | DataClass data = new DataClass ( ) ; var searchresults = data.GetData ( searchBox.Text ) ; int datanumber = searchresults.Count ( ) ; if ( datanumber == 0 ) { ClientScript.RegisterStartupScript ( this.GetType ( ) , `` alert '' , `` javascript : alert ( 'There were no records found to match your search ' ) ; '' , true )... | Throwing a popup when search yields no results |
C# | Consider the following scenario.Document - > Section - > Body - > ItemsDocument has sections , a section contains a body . A body has some text and a list of items . The items is what the question is about . Sometimes the items is a basic list of string , but sometimes the items contain a list of a custom datatype . So... | public class Document { public Section [ ] Sections { get ; set ; } } public class Section { public SectionType Type { get ; set ; } public Body { get ; set ; } } public class Body { //I want the items to be depending on the section type . //If e.g . the sectiontype is experience , I want the Items to be created with t... | polymorphism , generics and anonymous types C # |
C# | I have created a Rectangle inside of a ScrollViewer like thisDuring the use of the app , the size of MusicBg changes , sometimes to something around 3,000 pixels width.However , while scrolling the scrollViewer , it allows me to scroll the rectangle all the way off the screen.For example this line of code gives me the ... | < ScrollViewer ManipulationMode= '' Control '' x : Name= '' songScrollViewer '' HorizontalScrollBarVisibility= '' Visible '' VerticalScrollBarVisibility= '' Disabled '' Height= '' 270 '' VerticalAlignment= '' Center '' Width= '' 728 '' Canvas.Top= '' 20 '' d : LayoutOverrides= '' HorizontalMargin '' > < Rectangle x : N... | How do I get a ScrollViewer with a Rectangle inside to stop scrolling when it reaches the end of the rectangle ? |
C# | The following code demonstrates my question : The question is , why is there a difference for the compiler between casting the type inline to the extension method call and moving that cast out into a separate method ? | public class DynamicExample { public void DoSomething ( ) { var x = new ExpandoObject ( ) ; dynamic d = x ; d.GetString = ( Func < string > ) ( ( ) = > `` Some Value '' ) ; d.GetString ( ) .SomeStringExtension ( ) ; // Does n't work - expected ( ( string ) d.GetString ( ) ) .SomeStringExtension ( ) ; // Works - expecte... | Explicit cast of dynamic method return value within a method does n't allow an extension method to be called |
C# | So I 'm using a webclient to send some data from my C # application to my PHP script , which is located on a remote server . The problem that I 'm having is that the NameValueCollection I 'm using to store my data in works , But whenever my PHP script hits the object switch then it says that the type is invalid , this ... | private static void send_it ( string jobj ) { // this is where I encode my JSON object to base_64 var b64bytes = System.Text.Encoding.UTF8.GetBytes ( json ) ; b64encode = System.Convert.ToBase64String ( b64bytes ) ; var data = new NameValueCollection ( ) ; // this is where I add the data data [ `` b64string '' ] = b64e... | PHP not processing data from C # webclient correctly |
C# | Consider the TranslateAllCoords static function : Then , later in code , you have : But , by calling TranslateAllCoords you are in effect modifying value types ( i.e. , the integer coords ) and generally values types should be immutable . Are some rules broken here or is this a perfectly valid construct that gets aroun... | static class CoordinateTransformation { public static void TranslateAllCoords ( ref int x , ref int y , ref int z , int amount ) { x+=amount ; y+=amount ; z+=amount ; } } int x=0 , y=0 , z=0 ; ... CoordinateTransformation.TranslateAllCoords ( ref x , ref y , ref z , 5 ) ; ... | Mutability of value types |
C# | So , I 've written a small and , from what I initially thought , easy method in C # .This static method is meant to be used as a simple password suggestion generator , and the code looks like this : I call this function like this : Now , this method almost always return random strings like `` AAAAAA '' , `` BBBBBB '' ,... | public static string CreateRandomPassword ( int outputLength , string source = `` '' ) { var output = string.Empty ; for ( var i = 0 ; i < outputLength ; i++ ) { var randomObj = new Random ( ) ; output += source.Substring ( randomObj.Next ( source.Length ) , 1 ) ; } return output ; } var randomPassword = StringHelper.C... | My static C # function is playing games with me ... totaly weird ! |
C# | I understand that AspNetCore 2.1 is still in release candidate form and that new testing model with Microsoft.AspNetCore.Mvc.Testing is not stabilized.But I 'm trying to follow examples and use WebApplicationTestFixture class for testing . Here is code I have so far : However , I ca n't find WebApplicationTestFixture c... | public class UnitTest1 : IClassFixture < WebApplicationTestFixture < Startup > > { public UnitTest1 ( WebApplicationTestFixture < Startup > fixture ) { Client = fixture.CreateClient ( ) ; } public HttpClient Client { get ; } [ Fact ] public async void Test1 ( ) { var response = await Client.GetAsync ( `` api/values '' ... | AspNetCore testing with TestHost , WebApplicationTestFixture class not found |
C# | I 've noticed that when using Contains in EFThe generated SQL looks like this Since the values are not parameterized , is n't it possible to inject some SQL ? | .Where ( i = > myListOfStrings.Contains ( i.Value ) ) IN ( 'Value1 ' , 'Value2 ' ) | Possible SQL Injection when using contains with EF ? |
C# | During reflection , is it possible in C # to check whether one constructor calls another ? I would like to determine for each ConstructorInfo whether or not it 's at the end of chain of invocation . | class Test { public Test ( ) : this ( false ) { } public Test ( bool inner ) { } } | Check whether a constructor calls another constructor |
C# | I used SHA1 for hashing passwords on my site . I 'm trying to move to ASP.NET Identity . I found how I can verify the old passwords ( ASP.NET Identity default Password Hasher , how does it work and is it secure ? ) : In my custom ApplicationUserManager , I set the PasswordHasher property : Now , I would like delete the... | public class CustomPasswordHasher : IPasswordHasher { // ... . public static bool VerifyHashedPassword ( string hashedPassword , string password ) { byte [ ] buffer4 ; if ( hashedPassword == null ) { return false ; } if ( password == null ) { throw new ArgumentNullException ( `` password '' ) ; } // Old hash verificati... | How can I rewrite password hash made by SHA1 ( in ASP.NET Identity ) ? |
C# | From a long time i am trying to generate graph like this Codes i tried.Please help which chart type i should use or i am making any mistake . AAfter changing chart type , it works perfectly fine but its not working for last row text . As shown in image below . | Excel.Range chartRange1 ; Excel.ChartObjects xlCharts1 = ( Excel.ChartObjects ) worksheet.ChartObjects ( Type.Missing ) ; Excel.ChartObject myChart1 = ( Excel.ChartObject ) xlCharts1.Add ( 350 , 500 , 500 , 350 ) ; Excel.Chart chartPage1 = myChart1.Chart ; chartRange1 = worksheet.get_Range ( `` A33 '' , `` b56 '' ) ; c... | Excel Chart Type vertical value |
C# | I have following program to add the values.When I am comenting Add method call in main method and looking into ILDASM.EXE Maxstack size is 2 . And after uncommenting maxstack size becomes 4.Why in the case of Main method all variables are not going into stack as stack size remains 2 only , While in case of Add method c... | static void Main ( string [ ] args ) { int x = 2 ; int y = 3 ; int a = 4 ; int b = 5 ; int c = 6 ; Console.WriteLine ( x + y + a + b + c ) ; Console.WriteLine ( Add ( 10 , 20 , 30 , 40 ) ) ; Console.ReadLine ( ) ; } static int Add ( int x , int y , int z , int a ) { return x + y + z + a ; } | Calculation of maxstack value in IL code |
C# | I 'm trying to create a request with IP address SAN . This is the function that is responsible for creating the CAlternativeName : The problem is that I 'm getting the next error : What am I doing wrong ? | public static CAlternativeNameClass GetCurrentIpName ( ) { //get current machine IP address IPAddress ip = GetCurrentIp ( ) ; if ( ip == null ) { return null ; } try { CAlternativeNameClass nameClass = new CAlternativeNameClass ( ) ; nameClass.InitializeFromString ( AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS , ip... | Create a Computer Request Including IP address Subject Alternative Name |
C# | https : //msdn.microsoft.com/en-us/magazine/jj883956.aspx Consider the polling loop pattern : In this case , the .NET 4.5 JIT compiler might rewrite the loop like this : In the single-threaded case , this transformation is entirely legal and , in general , hoisting a read out of a loop is an excellent optimization . Ho... | private bool _flag = true ; public void Run ( ) { // Set _flag to false on another thread new Thread ( ( ) = > { _flag = false ; } ) .Start ( ) ; // Poll the _flag field until it is set to false while ( _flag ) ; // The loop might never terminate ! } if ( _flag ) { while ( true ) ; } | .NET JIT compiler volatile optimizations |
C# | Consider the following code : Assuming I 'm calling MyMethod ( `` mystring '' ) from different threads concurrently.Would it be possible for more than one thread ( we 'll just take it as two ) enter the if ( ! list.Contains ( a ) ) statement in the same time ( with a few CPU cycles differences ) , both threads get eval... | Dictionary < string , string > list = new Dictionary < string , string > ( ) ; object lockObj = new object ( ) ; public void MyMethod ( string a ) { if ( list.Contains ( a ) ) return ; lock ( lockObj ) { list.Add ( a , '' someothervalue '' ) ; } } | C # Is this method thread safe ? |
C# | I am using a pre-built third party class library ( think .NET Framework ... ) that contains a class Foo with the following members : Foo does not contain a public _state setter.In a specific scenario , I want to set the state of a Foo object to the object itself . This will NOT compile : Given the above prerequisites ,... | public sealed class Foo { private object _state ; public Foo ( object state ) { _state = state ; } } Foo f ; f = new Foo ( f ) ; // Compilation error : Use of unassigned local variable ' f ' | Can I set the state of an object to the object itself in the constructor call ? |
C# | What are the implications or unperceived consequences of throwing an exception inside of a delegate that is used during an unmanaged callback ? Here is my situation : Unmanaged C : Managed C # : | int return_callback_val ( int ( *callback ) ( void ) ) { return callback ( ) ; } [ DllImport ( `` MyDll.dll '' ) ] static extern int return_callback_val ( IntPtr callback ) ; [ UnmanagedFunctionPointer ( CallingConvention.Cdecl ) ] delegate int CallbackDelegate ( ) ; int Callback ( ) { throw new Exception ( ) ; } void ... | Implications of throwing exception in delegate of unmanaged callback |
C# | I have four consumer when error occured message publishing to default EasyNetQ_Default_Error_Queue is it possible to each queue consumer write own error exchangeFor example ; | Queue Name : A ErrorExchange : A_ErrorExchangeQueue Name : B ErrorExchange : B_ErrorExchange bus.Advanced.Conventions.ErrorExchangeNamingConvention = new ErrorExchangeNameConvention ( info = > `` A_DeadLetter '' ) ; bus.Advanced.Conventions.ErrorExchangeNamingConvention = new ErrorExchangeNameConvention ( info2 = > `` ... | How to declare custom error exchange for each consumer in EasyNetQ ? |
C# | Today , when I write a piece of code like this : I suddenly realize that thestatement is so much like a function declaration . And I vaguely remembered that the exception handling involves some kind of stack walking/manipulation.So , what exactly is the above exception handling code compiled into ? I have the feeling t... | try { ... } catch ( Exception e ) { ... } catch ( Exception e ) { ... } | The internal implementation of exception handling |
C# | I am trying to create a .NET Object from a JObject but I am getting all properties of the Object as defaults ( null for string , 0 for int etc . ) I am creating a simple Jobject : The car class is : The deserialization is here : But the result in run time is default values : Run time pictureI would like to know why it ... | var jsonObject = new JObject ( ) ; jsonObject.Add ( `` type '' , `` Fiat '' ) ; jsonObject.Add ( `` model '' , 500 ) ; jsonObject.Add ( `` color '' , `` white '' ) ; public class Car { string type { get ; set ; } int model { get ; set ; } string color { get ; set ; } } Car myCar = jsonObject.ToObject < Car > ( ) ; | Deserialize Json using ToObject method results in default properties values |
C# | I am trying to export an excel and make it password protected . My code is given below.But i am getting error : Excel completed file level validation and repair . Some parts of this workbook may have been repaired or discarded.I DO N'T KNOW WHAT I AM DOING WRONG .In-case i do it without the save As line for package the... | [ HttpGet ] public FileStreamResult ExportToExcel ( ) { _objService = new ServiceBAL ( ) ; List < ReconcilationEntity > Objmodel = new List < ReconcilationEntity > ( ) ; Objmodel = _objService.GetCreditsudharLeads ( ) ; String URL = string.Empty ; if ( ! Directory.Exists ( Server.MapPath ( `` ~/TempExcel '' ) ) ) { Sys... | I am trying to export an excel and make it password protected . My code is given below.But i am getting error |
C# | Can optimizations done by the C # compiler or the JITter have visible side effects ? One example I 've though off.When calling A ( x ) x is guaranteed to be kept alive to the end of A - because B uses the same parameter . But if B is defined asThen the B ( x ) can be eliminated by the optimizer and then a GC.KeepAlive ... | var x = new Something ( ) ; A ( x ) ; B ( x ) ; public void B ( Something x ) { } | C # optimizations and side effects |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.