lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Suppose I have var lst = List < Foobar > that I populated in loop . I can not modify the Foobar object.What would be the best way to effectively do an OrderBy on one property in an IEnumerable , but preserve the original order in case they are equal ? For example , if I had this : I would want to ensure I 'd get back t...
var lst = new List < Foobar > { new Foobar { Foo = `` b '' , Bar=3 } , new Foobar { Foo = `` b '' , Bar=1 } , new Foobar { Foo = `` a '' , Bar=2 } } List < Foobar > { new Foobar { Foo = `` a '' , Bar=2 } new Foobar { Foo = `` b '' , Bar=3 } , new Foobar { Foo = `` b '' , Bar=1 } , }
Linq order by property , then by original order
C#
I have two extension methods : Now I write some code which uses it : Second overload is chosen only if I explicitly specify IEnumerable type . Is there any way to make second overload to be chosen in both cases ?
public static IPropertyAssertions < T > ShouldHave < T > ( this T subject ) { return new PropertyAssertions < T > ( subject ) ; } public static IPropertyAssertions < T > ShouldHave < T > ( this IEnumerable < T > subject ) { return new CollectionPropertyAssertions < T > ( subject ) ; } List < Customer > collection2 = ne...
Extension methods overload choice
C#
I have this project , and one of the tasks I need to do is find what page a specific object appears on . The object has a predefined ID , and the ID 's appear in order from 0 to N , but they could potentially skip values.Which means , obviously , that using the ID of the element I 'm looking for wo n't work , as if it ...
int itemsPerPage = Convert.ToInt32 ( masterDbContext.Settings.First ( x = > x.Name == `` ItemsPerPage '' ) .Value ) ; int itemCount = masterDbContext.Items.OrderBy ( x = > x.Id ) .TakeWhile ( x = > x.Id < currentItemId ) .Count ( ) ; int pageNumber = ( int ) Math.Ceiling ( ( double ) itemCount / itemsPerPage ) ; Respon...
Count how many items appear before an item with a specific ID
C#
I have an OWIN-based ASP.NET Web API hosted in a Windows Service . Most of my ApiController actions are async , and accept CancellationToken parameters : Using the built-in request-cancellation features of Web API , if the client cancels the request , token is signaled and _dataSource handles it appropriately and throw...
[ Route ( `` data/ { id } '' ) ] public async Task < IHttpActionResult > GetSomeDataAsync ( int id , CancellationToken token ) { try { using ( var _dataSource = ... ) { return Ok ( await _dataSource.GetDataAsync ( id , token ) ) ; } } catch ( OperationCanceledException ex ) { return StatusCode ( HttpStatusCode.NoConten...
How can I signal cancellation to Web API actions when the self-hosted OWIN server shuts down ?
C#
I have a TCP server windows service developed in .net 4.0 with asynchronous server sockets.It works , but about 90 % of the time I simply can not stop it : after pressing stop button in Windows Service console , it hangs and stops after about a minute , but its process goes on and TCP communication continues . It hangs...
public class DeviceTCPServer { public readonly IPAddress IPAddress ; public readonly int Port ; public readonly int InputBufferSize ; public readonly ConcurrentDictionary < Guid , StateObject > Connections ; public event EventHandler OnStarted ; public event EventHandler OnStopped ; public event ServerEventHandler OnCo...
Can not stop async TCP sever Windows service
C#
I have a UserScope class which functions similarly to TransactionScope , i.e. , it stores the current state in a thread local . This of course does n't work across calls to await , and neither did TransactionScope until TransactionScopeAsyncFlowOption was added in .NET 4.5.1 . What alternative to thread local can I use...
class User { readonly string name ; public User ( string name ) { this.name = name ; } public string Name { get { return this.name ; } } } class UserScope : IDisposable { readonly User user ; [ ThreadStatic ] static UserScope currentScope ; public UserScope ( User user ) { this.user = user ; currentScope = this ; } pub...
Sharing scope across awaits
C#
I have a following situation . Some .Net runtime method does n't work very well and I need to craft a workaround . Like there 's SqlCommand.ExecuteReader ( ) which sometimes returns a closed reader object and I want to have code like this : This would be just fine except I now need to change all the code that calls Exe...
SqlDataReader MyExecuteReader ( this SqlCommand command ) { var reader = command.ExecuteReader ( ) ; if ( reader.IsClosed ( ) ) { throw new ClosedReaderReturnedException ( ) ; } return reader ; }
Can I replace a C # method with another with the same name and signature ?
C#
Perhaps I am missing something trivial . I have a couple of List < T > s and I need one big list from them which is a union of all the other lists . But I do want their references in that big list and not just the values/copies ( unlike many questions I typically find on SO ) .For example I have this , Suppose I get th...
List < string > list1 = new List < string > { `` a '' , `` b '' , `` c '' } ; List < string > list2 = new List < string > { `` 1 '' , `` 2 '' , `` 3 '' } ; var unionList = GetThatList ( list1 , list2 ) ; unionList.Remove ( `` a '' ) ; = > list1.Remove ( `` a '' ) ; unionList.Remove ( `` 1 '' ) ; = > list2.Remove ( `` 1...
How to copy a List < T > without cloning
C#
I was reading about the ValueType class and I am wondering if , when something gets casted to a ValueType , whether it is getting boxed ? Example : Did the int represented by the literal 5 get boxed when received by DoSomething method ?
void DoSomething ( ValueType valueType ) { } DoSomething ( 5 ) ;
C # boxing when casting to ValueType
C#
I have exceptionI 'm using unit tests to test class Parser which on specific input should throw exception above . I 'm using code like this : Is there any smart simple way to check if SyntaxError.line == 1 ? Best I come up with is : I do n't like it very much , is there better way ?
class SyntaxError : Exception { public SyntaxError ( int l ) { line = l ; } public int line ; } [ TestMethod ] [ ExpectedException ( typeof ( Parser.SyntaxError ) ) ] public void eolSyntaxError ( ) { parser.reader = new StringReader ( `` ; alfa\n ; beta\n\n\n\na '' ) ; parser.eol ( ) ; } [ TestMethod ] public void eolS...
Unit testing exception property
C#
For purposes of automatically translating code from C++ to C # , I would like to have a C # class ( psuedo-code ) This would be useful in cases such asFor certain reasons , programmatically disambiguating the above type is not in general possible . E.g.But if I had the Null class above , I could programmatically add in...
class Null { public static implicit operator T ( Null unused ) { return null ; } } foo ( T1 x ) { ... } foo ( T2 x ) { ... } foo ( null ) ; // ambiguous foo ( ( T1 ) null ) ; // Discovering T1 over T2 is not possible or really hard to do foo ( Null x ) { ... } foo ( new Null ( ) ) ; // not ambiguous T1 x = new Null ( )...
C # generic implicit operator return type
C#
I have the SQL queryand I want to convert it to LINQ to SQL , yet my LINQ skills are not there yet . Could someone please help me convert this . It 's the with and union statements that are making this a bit more complex for me.Any help appreciated .
with c as ( select categoryId , parentId , name,0 as [ level ] from task_Category b where b.parentId is null union all select b.categoryId , b.parentId , b.name , [ level ] + 1 from task_Category b join c on b.parentId = c.categoryId ) select name , [ level ] , categoryId , parentId as item from c
Convert SQL to LINQ to SQL
C#
Possible Duplicate : C # if/then directives for debug vs release I am working on a C # project and I like to know how to add special cases while I am running the program in the debugger in the Debug Mode I have access to certain resources that I would not normally have in the release version.Here is what keeps happenin...
rpg_Admin.Visible = true ; rpg_Admin.Visible = false ; if Debug Mode rpg_Admin.Visible = true rpg_Admin.Visible = true rpg_Admin.Visible = false
In Visual Studio how to add special cases for debug and release versions ?
C#
Possible Duplicate : Cast int to Enum in C # I fetch a int value from the database and want to cast the value to an enum variable . In 99.9 % of the cases , the int will match one of the values in the enum declarationIn the edge case , the value will not match ( whether it 's corruption of data or someone manually goin...
public enum eOrderType { Submitted = 1 , Ordered = 2 , InReview = 3 , Sold = 4 , ... } eOrderType orderType = ( eOrderType ) FetchIntFromDb ( ) ;
The correct way of casting an int to an enum
C#
Is there an Android preprocessor macros that Mono for Android defines ? I mean very useful things for cross-platform development like : and
# if WINDOWS ... # endif # if WINDOWS_PHONE ... # endif
Mono for Android preprocessor macros
C#
I have a Windows form with a datagridview.The ideal situation : User clicks on any of the nine columns , and the program sorts all the data , if the clicked column contains numbers , I would like the lowest number on the top . If the clicked column contains a string I would like it to be sorted Alphabetically ( A-Z ) ....
dataGridView2.DataSource = listPlayers.Select ( s = > new { voornaam = s.Voornaam , Achternaam = s.Achternaam , positie = s.Positie , Nationaltieit = s.Nationaliteit , Leeftijd = s.Age , Aanval = s.Aanval , Verdediging = s.Verdediging , Gemiddeld = s.Gemiddeld , waarde = s.TransferWaarde } ) .OrderBy ( s = > s.Achterna...
Make all datagridview columns sortable
C#
Tough question but I could use any help on it.I 'm using System.Security.Cryptography.Xml on my end to encrypt an XML SAML blob.The encryption is working fine , however when it hits the java library on the other side they are getting error : How can I continue to use my encryption method : While getting around this err...
java.lang.ArrayIndexOutOfBoundsException : too much data for RSA block at org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal ( Unknown Source ) at org.bouncycastle.jce.provider.WrapCipherSpi.engineUnwrap ( Unknown Source ) at javax.crypto.Cipher.unwrap ( Unknown Source ) at org.apache.xml.security.encryption.XMLC...
.NET System Encryption to Bouncy Castle Java Decryption Throws Error
C#
I am trying to use the ActionTypes.OpenUrl type on a CardAction in a hero card on kik . all it does is echo back the message . It does not actually open a URL . I have the same code working on multiple channels , but can not get it working on kik . Has anyone been able to find a work around for this ? Here is the code ...
Activity reply = activity.CreateReply ( ) ; var card = new HeroCard { Title = `` title '' , Text = `` text '' , Buttons = new List < CardAction > { new CardAction ( ActionTypes.OpenUrl , '' url 1 '' , text : `` open url 1 '' , value : @ '' https : //www.google.com/ '' ) , new CardAction ( ActionTypes.OpenUrl , title : ...
Bot Framework : How to make an OpenUrl button on a herocard in Kik
C#
I am working on a math library for my DirectX 3D engine in C # . I am using SlimDX , which is a wonderfuly put together and powerful library . SlimDX provides quite a few math classes , but they are actually wrappers around native D3DX objects , so while the objects themselves are very , very fast , the interop is not ...
float Epsilon = 1.0e-6f ; bool FloatEq ( float a , float b ) { return Math.Abs ( a - b ) < Epsilon }
Inline expansion in C #
C#
Regex.Replace says : In a specified input string , replaces all strings that match a specified regular expression with a specified replacement string.In my case : Output : but I was expectingWhy is it replacing my non-matching groups ( group 1 and 3 ) ? And how do I fix this in order to get the expected output ? Demo
string w_name = `` 0x010102_default_prg_L2_E2_LDep1_LLC '' ; string regex_exp = @ '' ( ? : E\d ) ( [ \w\d_ ] + ) ( ? : _LLC ) '' ; w_name = Regex.Replace ( w_name , regex_exp , string.Empty ) ; 0x010102_default_prg_L2_ 0x010102_default_prg_L2_E2_LLC
Regex replace only matching groups and ignore non-matching groups ?
C#
i 've got this structnow i 'm failing this : with System.InvalidCastException : Specified cast is not valid . at System.Linq.Enumerable.d__aa ` 1.MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) ...
[ Serializable ] public struct Foo : IConvertible , IXmlSerializable , IComparable , IComparable < Foo > { private readonly int _value ; private Foo ( int id ) { this._value = id ; } private IConvertible ConvertibleValue { get { return this._value ; } } public int CompareTo ( object obj ) { if ( obj is Foo ) { var foo ...
Why does this cast-operation fail
C#
In the code below , I 'm checking the equality of object references.Here : x and z refers to same object ; I can say that x is interned and z is used taht version . Well , I 'm not sure about this ; Please correct me , if I am wrong.I changed the value of y by assigning it the same value as x. I thought it is going to ...
string x = `` Some Text '' ; string y = `` Some Other Text '' ; string z = `` Some Text '' ; Console.WriteLine ( object.ReferenceEquals ( x , y ) ) ; // FalseConsole.WriteLine ( object.ReferenceEquals ( x , z ) ) ; // TrueConsole.WriteLine ( object.ReferenceEquals ( y , z ) ) ; // Falsey = `` Some Text '' ; Console.Wri...
String Interning
C#
I have an ASP.NET application that is accessed by 120-140 users at the same time on average . I use Session to get and set user specific info . To make things easy I 've got a static a class called CurrentSession and it has a property called UserInfo : And whenever I needed current user 's info I just used to do : Rece...
public static class CurrentSession { public static UserInfo { get { return HttpContext.Current.Session [ `` userInfo '' ] ! =null ? ( UserInfo ) HttpContext.Current.Session [ `` userInfo '' ] : null ; } set { HttpContext.Current.Session [ `` userInfo '' ] =value ; } } //And other properties } CurrentSession.UserInfo ;
Can Sessions conflict when encapsulated in a static class static property ?
C#
I know how to force a type parameter to be a subtype of another type : Is there a way to force a type parameter to be a supertype of another type ? Currently , I 'm having to compare T1 and T2 at runtime using IsSubclassOf inside IncludeMappingOf . A compile-safe solution would be preferable . Any ideas ? EDIT : Change...
public interface IMapping < T2 > { public void Serialize < T3 > ( T3 obj ) where T3 : T2 ; } ... var mapping = MapManager.Find < Truck > ( ) ; mapping.Serialize ( new TonkaTruck ( ) ) ; public interface IMapping < T2 > { public void IncludeMappingOf < T1 > ( ) where T2 : T1 ; // < == does n't work } ... var mapping = M...
Constrain type parameter to a base type
C#
What will happen if two threads read this property at the same time ? My object is read only and it 's not critical if two instances are created . Should I add locks in any case ?
public static HugeType HugeType { get { if ( tenderCache == null ) { tenderCache = Config.Get < HugeType > ( `` HugeType '' , null ) ; } return tenderCache ; } }
Lazy loading without locks in multithread application
C#
I wanted to know how to word-wrap in C # when I came across a very good solution to my problem on word-wrapping text in a line in this URL . Unfortunately , I do not have enough reputations to ask the OP directly about one specific problem I am having ( and most likely people dealing with this will be having indefinite...
Graphics PAddress = e.Graphics ; SizeF PAddressLength = PAddress.MeasureString ( `` Residential Address : `` + RAddressTextBox.Text , new Font ( fontface , fontsize , FontStyle.Regular ) ,700 ) ; PAddress.DrawString ( `` Residential Address : `` +PAddressLength + RAddressTextBox.Text , new Font ( fontface , fontsize , ...
How to detect a string-overflow from a line in C # ?
C#
Somehow I can not believe that I am the first one to run into that problem ( and I do n't want to believe that I am the only one stupid enough not to see a solution directly ) , but my search-fu was not strong enough.I regularly run into a situation , when I need to do a few time-consuming steps one after the other . T...
var data = DataGetter.GetData ( ) ; var processedData = DataProcessor.Process ( data ) ; var userDecision = DialogService.AskUserAbout ( processedData ) ; // ... DataGetter.Finished += ( data ) = > { DataProcessor.Finished += ( processedData ) = > { DialogService.Finished ( userDecision ) = > { // ... . } DialogService...
How to avoid spaghetti code when using completion events ?
C#
Imagine I have a function calledMy C # declaration could beIs this functionally and technically equivalent toOr will there be a difference in how they are marshalled.I 'm asking this because the library I 'm calling is all void * , typedef 'd to other names , and in C # I 'd like to get type safety , for what it 's wor...
Myfunction ( const void * x ) ; MyFunction ( IntPtr x ) ; struct MyStruct { IntPtr P ; } MyFunction ( MyStruct x ) ;
PInvoke with a void * versus a struct with an IntPtr
C#
I 'm trying to use SOAP headers to allow for SQL Authentication while accessing a webservice published on my SQL 2005 box via HTTP Endpoint . On the endpoint , I 've set Authentication = ( Basic ) , Ports = ( SSL ) , and LOGIN_TYPE = MIXED . I 'm able to generate the WSDL and consume it just fine in VS utilizing domain...
namespace ConsoleApplication.WebService { class Program { static void Main ( string [ ] args ) { //Prevents error due to self signed cert ServicePointManager.ServerCertificateValidationCallback = delegate { return true ; } ; Stuff stuff = new Stuff ( ) ; stuff.DoSomthing ( ) ; } } public class Stuff { [ System.Web.Serv...
Adding SOAP Headers for SQL 2005 HTTP Endpoint web service in Visual Studio 2008
C#
Context : There 2 main classes that look something like this : And the sub / collection / Enum types : Currently my Map looks like this : Where MapAttribute gets the item from the Dictionary and using the AttributeType I 've provided , adds it to the target collection as a ( name & value ) object ( using a try get and ...
public class Source { public Dictionary < AttributeType , object > Attributes { get ; set ; } } public class Target { public string Title { get ; set ; } public string Description { get ; set ; } public List < Attribute > Attributes { get ; set ; } } public class Attribute { public string Name { get ; set ; } public st...
AutoMapper : Ignore specific dictionary item ( s ) during mapping
C#
In c # I can use default ( T ) to get the default value of a type . I need to get the default type at run time from a System.Type . How can I do this ? E.g . Something along the lines of this ( which does n't work )
var type = typeof ( int ) ; var defaultValue = default ( type ) ;
How can I call default ( T ) with a type ?
C#
The application I am working on is relying on Autofac as DI container and one of the reasons that made me decide to use it , among others , was the delegate factory feature ( see here ) This works fine for all cases where I need to recreate the same elements several times as is the case of some reports and related scre...
var myTaskA = _taskFactoryConcreteTaskA ( ) ; var myTaskB = _taskFactoryConcreteTaskB ( ) ; var myTaskC = _taskFactoryConcreteTaskC ( ) ; ... var myTaskZZ = = _taskFactoryConcreteTaskZZ ( ) ; var myTaskA = _taskFactory.Create < ConcreteTaskA > ( ) ; var myTaskB = _taskFactory.Create < ConcreteTaskB > ( ) ; var myTaskC ...
Service Locator easier to use than dependency Injection ?
C#
I 'm testing what sort of speedup I can get from using SIMD instructions with RyuJIT and I 'm seeing some disassembly instructions that I do n't expect . I 'm basing the code on this blog post from the RyuJIT team 's Kevin Frei , and a related post here . Here 's the function : The section of disassembly I 'm querying ...
static void AddPointwiseSimd ( float [ ] a , float [ ] b ) { int simdLength = Vector < float > .Count ; int i = 0 ; for ( i = 0 ; i < a.Length - simdLength ; i += simdLength ) { Vector < float > va = new Vector < float > ( a , i ) ; Vector < float > vb = new Vector < float > ( b , i ) ; va += vb ; va.CopyTo ( a , i ) ;...
What are these extra disassembly instructions when using SIMD intrinsics ?
C#
I 'm reading Clean Code : A Handbook of Agile Software Craftsmanship and one of the examples involves a Portfolio class and a TokyoStockExchange class . However , Portfolio is not very testable because it depends on TokyoStockExchange as an external API to determine the value of the portfolio and such is quite a volati...
public class PortfolioTest { private DummyStockExchange exchange ; private Portfolio portfolio ; protected void setUp ( ) { exchange = new DummyStockExchange ( ) ; exchange.fix ( `` MSFT '' , 100 ) ; portfolio = new Portfolio ( exchange ) ; } public void GivenFiveMSFTTotalShouldBe500 ( ) { portfolio.add ( 5 , `` MSFT '...
Confused about why it 's useful to unit test dummy objects
C#
Creating a simple list ( UniqueList ) of items with a Name property that must only contains unique items ( defined as having different Names ) . The constraint on the UniqueList type can be an interface : or an abstract class : So the UniqueList can be : orThe class function , AddUnique : If the class type constraint i...
interface INamed { string Name { get ; } } public abstract class NamedItem { public abstract string Name { get ; } } class UniqueList < T > : List < T > where T : INamed class UniqueList < T > : List < T > where T : NamedItem public T AddUnique ( T item ) { T result = Find ( x = > x.Name == item.Name ) ; if ( result ==...
Constraints on type parameters : interface vs. abstract class
C#
I 've noticed a performance hit of iterating over a primitive collection ( T [ ] ) that has been cast to a generic interface collection ( IList or IEnumberable ) .For example : The above code executes significantly faster than the code below , where the parameter is changed to type IList ( or IEnumerable ) : The perfor...
private static int Sum ( int [ ] array ) { int sum = 0 ; foreach ( int i in array ) sum += i ; return sum ; } private static int Sum ( IList < int > array ) { int sum = 0 ; foreach ( int i in array ) sum += i ; return sum ; } private static int Sum ( IList < int > array ) { int sum = 0 ; if ( array is int [ ] ) foreach...
Overhead of Iterating T [ ] cast to IList < T >
C#
I 'm working on a WordSearch puzzle program ( also called WordFind ) where you have to find certain words in a mass of letters . I 'm using C # WinForms.My problem is when I want to click and hold 1 letter ( Label ) , then drag over to other letters to change their ForeColor . I 've tried googling but to no avail.Here ...
foreach ( Letter a in game.GetLetters ( ) ) { this.Controls.Add ( a ) ; a.MouseDown += ( s , e2 ) = > { isDown = true ; a.ForeColor = Color.Yellow ; } ; a.MouseUp += ( s , e2 ) = > { isDown = false ; } ; a.MouseHover += ( s , e2 ) = > { if ( isDown ) a.ForeColor = Color.Yellow ; } ; } private void frmMain_MouseHover ( ...
MouseHover not firing when mouse is down
C#
Possible Duplicate : Can ’ t operator == be applied to generic types in C # ? I have a DatabaseLookup { } class where the parameter T will be used by the lookup methods in the class . Before lookup , I want to see if T was already looked up with something likeThis does n't compile at all . What is preventing me from ma...
if ( T == previousLookupObject ) ...
Applying '== ' operator to generic parameter
C#
I have a dynamic COM object as a private field in my class . I 'm not sure whether it is considered managed resource ( GC cleans it up ) , or not ... .When implementing IDispose , should I clean it up as a managed resource ( only when Dispose ( ) is called explicitly ) , or as a native resource ( when Dispose ( false )...
private dynamic _comConnector = null ; _comConnector = Activator.CreateInstance ( Type.GetTypeFromProgID ( `` SomeProgId '' ) ) ; private void Dispose ( bool disposing ) { if ( disposing ) { // Free managed resources // // -- > Should I call Marshal.FinalReleaseComObject ( _comConnector ) here ? } // Free unmanaged res...
Are dynamic COM objects considered managed resources ?
C#
I have a method like so : However , I 'm wanting to write another method , very similar but it calls WriteAsync instead , such as : However I do n't like having two methods with practically duplicate code . How can I avoid this ? The right approach feels like I should use an Action/Delegate , but the signatures are dif...
public void Encrypt ( IFile file ) { if ( file == null ) throw new ArgumentNullException ( nameof ( file ) ) ; string tempFilename = GetFilename ( file ) ; using ( var stream = new FileStream ( tempFilename , FileMode.OpenOrCreate ) ) { this.EncryptToStream ( file , stream ) ; file.Write ( stream ) ; } File.Delete ( te...
Refactoring a library to be async , how can I avoid repeating myself ?
C#
I have a native DLL , written in Delphi , actively using callback mechanism : a callback function is `` registered '' and later called from inside of the DLL : Most of the callback functions are passing plain structures by reference , like the following : where PStructType is declared asThis DLL is consumed by a .NET a...
function RegisterCallback ( CallbackProc : TCallbackProc ) : Integer ; stdcall ; TCallbackProc = procedure ( Struct : PStructType ) ; stdcall ; TStructType = packed record Parameter1 : array [ 0..9 ] of AnsiChar ; Parameter2 : array [ 0..19 ] of AnsiChar ; Parameter3 : array [ 0..29 ] of AnsiChar ; end ; PStructType = ...
Marshalling plain structures : does C # copy them onto heap ?
C#
I have two text boxes and I want skip a block of code only when both are empty : If either of the text boxes has something , I want the //Do something part to execute . Only when both are empty do I want to skip.However the above code fragment does n't work . Why ?
if ( txtBox1.Text.Trim ( ) ! = string.Empty & & txtBox2.Text.Trim ( ) ! = string.Empty ) { // Do something }
Why does this IF statement return false ?
C#
I have a string like this : When I parse it to JObject like thatMy jObject looks like this : I need to get rid of scientific notation so that resulting JObject would look like original json.I managed to do that using later version of Newtonsoft.Json like that : But I need to achieve the same result using Newtonsoft.Jso...
var str = `` { 'data ' : { 'someProperty ' : 0.00001 } } '' ; var jObject = JObject.Parse ( str ) ; { `` data '' : { `` someProperty '' : 1E-05 } } var serializer = new JsonSerializer { FloatParseHandling = FloatParseHandling.Decimal } ; using ( System.IO.TextReader tr = new System.IO.StringReader ( str ) using ( var j...
How to deserialize string to JObject without scientific notation in C #
C#
I contribute to an open source library that currently supports MVC 2 - MVC 5 , and I would like to support MVC 6 ( and beyond ) as well . To support each version of MVC , we take advantage of the Condition feature of MSBuild to include the correct version of MVC and its dependencies when doing a build ( depending on th...
< ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC2 ' ) ) `` > < Reference Include= '' System.Web.Mvc , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=MSIL '' / > < /ItemGroup > < ItemGroup Condition= '' $ ( DefineConstants.Contains ( 'MVC3 ' ) ) `` > < ! -- Due t...
Supporting Multiple Versions of a Compilation Dependency ( vNext )
C#
The autofac documentation states : when Autofac is injecting a constructor parameter of type IEnumerable < ITask > it will not look for a component that supplies IEnumerable < ITask > . Instead , the container will find all implementations of ITask and inject all of them.But actually , it adds each registered type as m...
builder.RegisterType < A > ( ) ; builder.RegisterType < A > ( ) ;
Autofac Enumeration not working with multiple registrations of types or modules
C#
How does Skip ( ) and Take ( ) work in Entity Framework when calling a stored procedure ? I ca n't access sql profiler to check , but I want to make sure I optimize the amount of data sent between servers.Say I have the following code , where MyStoredProcedure returns 1000+ rows . Will the Take ( 10 ) make sure that on...
List < MyComplex_Result > myComplexList = db.MyStoredProcedure ( ) .Skip ( 50 ) .Take ( 10 ) ;
EF using skip and take on stored procedure
C#
I already searched the forum but no asked question fits to my problem I think ... I use a BackgroundWorker to handle a very time consuming operation . After this operation finishes a button should be set to enabled so that the user can perform another operation . I 'm using WPF and I 'm following the MVVM pattern , so ...
void fileLoadBackgroundWorker_RunWorkerCompleted ( object sender , RunWorkerCompletedEventArgs e ) { SetButtonToEnabled ( ) ; } < Button Name= '' btnLoadTargetFile '' Command= '' { Binding Path=LoadTargetCommand } '' ... / > public RelayCommand LoadTargetCommand { get { if ( loadTargetCommand == null ) { loadTargetComm...
Why does BackgroundWorker_RunWorkerCompleted not update GUI ?
C#
I 'm making a sound synthesis program in which the user can create his own sounds doing node-base compositing , creating oscillators , filters , etc.The program compiles the nodes onto an intermediary language which is then converted onto an MSIL via the ILGenerator and DynamicMethod.It works with an array in which all...
//Testing delegateunsafe delegate float TestDelegate ( float* data ) ; //Inside the test method ( which is marked as unsafe ) Type ReturnType = typeof ( float ) ; Type [ ] Args = new Type [ ] { typeof ( float* ) } ; //Ca n't use UnamangedExport as method attribute : DynamicMethod M = new DynamicMethod ( `` HiThere '' ,...
ILGenerator : How to use unmanaged pointers ? ( I get a VerificationException )
C#
If you forward to approximately 13 minutes into this video by Eric Lippert he describes a change that was made to the C # compiler that renders the following code invalid ( Apparently prior to and including .NET 2 this code would have compiled ) .Now I understand that clearly any execution of the above code actually ev...
int y ; int x = 10 ; if ( x * 0 == 0 ) y = 123 ; Console.Write ( y ) ; int y ; int x = 10 ; y = 123 ; Console.Write ( y ) ;
Constants and compile time evaluation - Why change this behaviour
C#
I 've already looked around , and since i 'm no security or encryption expert , I am still confused on how to implement encryption in my program . I need a server to login to its gitHub account to update code files with special headers . The only hang-up I have right now is how to store/retrieve the server 's credentia...
PushOptions push = new PushOptions { Credentials = new UsernamePasswordCredentials { Password = `` password '' , Username = `` Username '' } } ;
Storing credentials for automated use
C#
Why does the following code : render as : Where is that `` Length=4 '' coming from ? UpdateIf I remove the new { @ class = `` more '' } , I do n't get that Length=4 parameter .
< % = Html.ActionLink ( `` [ Click Here For More + ] '' , `` Work '' , `` Home '' , new { @ class = `` more '' } ) % > < a class= '' more '' href= '' /Home/Work ? Length=4 '' > [ Click Here For More + ] < /a >
Puzzling ... why do most of my links , in ASP.NET MVC , have Length=4 appended to them ?
C#
I have this code : When I try to compile it I get an error : A deconstruction can not mix declarations and expressions on the left I do n't understand why . Any suggestions ?
public static ( int a , int b ) f12 ( ) { return ( 1 , 2 ) ; } public static void test ( ) { int a ; ( a , int b ) = f12 ( ) ; //here is the error }
Why a deconstruction can not mix declarations and expressions on the left
C#
I have a rather simple problem , but there seems to be no solution within C # .I have around 100 Foo classes where each implement a static FromBytes ( ) method . There are also some generic classes which shall use these methods for its own FromBytes ( ) . BUT the generic classes can not use the static FromBytes ( ) met...
public class Foo1 { public static Foo1 FromBytes ( byte [ ] bytes , ref int index ) { // build Foo1 instance return new Foo1 ( ) { Property1 = bytes [ index++ ] , Property2 = bytes [ index++ ] , // [ ... ] Property10 = bytes [ index++ ] } ; } public int Property1 { get ; set ; } public int Property2 { get ; set ; } // ...
Is there a workaround to use static methods by a generic class ?
C#
In ASP.NET MVC 2 asynchronous controllers , we can do something like this : My question is , does the action filter `` Blurb '' in this case execute asynchronously ? In other words , is its synchronous nature automatically wrapped into an asynchronous call ?
public class SomeController : AsyncController { [ Blurb ] public void FooAsync ( ) { this.AsyncManager.OutstandingOperations.Increment ( ) ; Task.Factory.StartNew ( ( ) = > { this.AsyncManager.Parameters [ `` result '' ] = new BazResult ( ) ; this.AsyncManager.OutstandingOperations.Decrement ( ) ; } ) ; } public Action...
In ASP.NET MVC 2 asynchronous controllers , do Action Filters execute asynchronously ?
C#
I am looking at the Roslyn September 2012 CTP with Reflector , and I noticed that the SlidingTextWindow class has the following : I believe the purpose of this class is to provide fast access to substrings of the input text , by using char [ ] characterWindow , starting with 2048 characters at a time ( although the cha...
internal sealed class SlidingTextWindow : IDisposable { private static readonly ConcurrentQueue < char [ ] > arrayPool = new ConcurrentQueue < char [ ] > ( ) ; private int basis ; private readonly LexerBaseCache cache ; private char [ ] characterWindow ; private int characterWindowCount ; private int characterWindowSta...
Why use a ConcurrentQueue in this case ?
C#
So I have a client who is going to upgrade to ssl , but they currently use just plain http.I want to change the endpoint for the service . To use https.The question is will their connection to the web service using http still work until they change the address to https ? Do I need two endpoints to pull this off ?
< binding name= '' basicHttpSSLBinding '' closeTimeout= '' 00:02:00 '' openTimeout= '' 00:02:00 '' receiveTimeout= '' 00:20:00 '' sendTimeout= '' 00:20:00 '' > < security mode= '' Transport '' > < /security > < /binding >
Can I use normal http and https for the same endpoint
C#
Trying to do some business logic in C # by overriding the EF SaveChanges method.The idea is to have some advanced calculations on things like if this field has changed update this field . And this field is the sum of the subclass minus some other fields , you know advanced business junk . Since it 's really complicated...
void Update ( object entity , DbPropertyValues currentValues , DbPropertyValues originalValues ) ; public override int SaveChanges ( ) { var added = ChangeTracker.Entries ( ) .Where ( p = > p.State == EntityState.Added ) .Select ( p = > p.Entity ) ; var updated = ChangeTracker.Entries ( ) .Where ( p = > p.State == Enti...
Testing EF Save Changes Modifiers . Passing in DbPropertyValues
C#
I am aware that Linq provides capability to determine if a collection has any items . Such asThis is very efficient because if it finds at least one item then the iteration stops . Now what if I want to know if a collection has at least 2 items . Here is the code i have currently : This one will go through the whole co...
var anyCategories= categories.Any ( ) ; var atLeastTwoCategories= categories.Count ( ) > 1 ;
Efficient way to determine collection has at least 2 items
C#
I 'd like to create a method that returns a type ( or IEnumerable of types ) that implement a specific interface that takes a type parameter -- however I want to search by that generic type parameter itself . This is easier demonstrated as an example : Method signature that I want : And then if I have the below objects...
public IEnumerable < Type > GetByInterfaceAndGeneric ( Type interfaceWithParam , Type specificTypeParameter ) public interface IRepository < T > { } ; public class FooRepo : IRepository < Foo > { } ; public class DifferentFooRepo : IRepository < Foo > { } ; var repos = GetByInterfaceAndGeneric ( typeof ( IRepository < ...
Get type that implements generic interface by searching for a specific generic interface parameter
C#
In the projects I worked on I have classes that query/update database , like this one , as I keep creating more and more classes of this sort , I realize that maybe I should make this type of class static . By doing so the obvious benefit is avoid the need to create class instances every time I need to query the databa...
public class CompanyInfoManager { public List < string > GetCompanyNames ( ) { //Query database and return list of company names } }
should I make this class static ?
C#
I 'm experimenting with parsing expression trees and have written the following code : The idea of the code is to parse the expression tree and write details about the nodes into the string variable output . However , when this variable is written to the page ( using the Output ( ) method ) , I 'm finding it 's empty.W...
private void TestExpressionTree ( ) { Expression < Func < int , bool > > expression = x = > x == 1 || x == 2 ; string output = String.Empty ; HandleExpression ( expression.Body , output ) ; Output ( `` Output '' , output ) ; } private void HandleExpression ( Expression expression , string output ) { switch ( expression...
C # : String parameter being mysteriously reset to empty - please help !
C#
In my codebehind file I call this function : Then in webservice I do this : What I want to do now is when an exception is thrown , show a messagebox . And when I got a status 200 I navigate to the next page in de code behind file.My question is now , how do i 'm going to know this in my code behind file ? Many thanks i...
private void loginAction ( object sender , TappedRoutedEventArgs e ) { Webservice webservice = new Webservice ( ) ; webservice.getUser ( txtLogin.Text , txtPass.Text ) ; } public void getUser ( String user , String password ) { String strUrl = String.Format ( `` http : //*******/nl/webservice/abc123/members/login ? ema...
returning a false when got 400 status of webservice in JSON
C#
In a C # 8 project with nullable reference types enabled , I have the following code which I think should give me a warning about a possible null dereference , but does n't : When instance is initialized with the default constructor , instance.Member is set to the default value of ExampleClassMember , which is null . T...
public class ExampleClassMember { public int Value { get ; } } public struct ExampleStruct { public ExampleClassMember Member { get ; } } public class Program { public static void Main ( string [ ] args ) { var instance = new ExampleStruct ( ) ; Console.WriteLine ( instance.Member.Value ) ; // expected warning here abo...
Why do n't I get a warning about possible dereference of a null in C # 8 with a class member of a struct ?
C#
I 'm trying to bring a listing to frontEnd.I 'm using mongoDb . My mongodb has a colletion called Employee . Employee has the following attributeIn this Model , I have an attribute called : public List < DocumentsImagesViewModel > DependentsDocuments { get ; set ; } : I 'm trying to bring benefits that contain the depe...
public class EmployeeViewModel { [ BsonId ( IdGenerator = typeof ( StringObjectIdGenerator ) ) ] public string ownerId { get ; set ; } public string atributeChange { get ; set ; } public PersonalDataViewModel personalData { get ; set ; } public AddressViewModel address { get ; set ; } public List < EmailsViewModel > em...
Can not convert type IEnumerable to List C #
C#
I am working with asp.net mvc and creating a form . I want to add a class attribute to the form tag.I found an example here of adding a enctype attribute and tried to swap out with class . I got a compile error when accessing the view.I then found an example of someone adding a @ symbol to the beginning of the property...
< % Html.BeginForm ( `` Results '' , `` Search '' , FormMethod.Get , new { class= '' search_form '' } ) ; % > < % Html.BeginForm ( `` Results '' , `` Search '' , FormMethod.Get , new { @ class= '' search_form '' } ) ; % >
Why does adding the @ symbol make this work ?
C#
Given the following code : Is it possible that the cast from char to int could fail ( and under what circumstances ) ?
string source = `` Some Unicode String '' ; foreach ( char value in source ) { int y = ( int ) value ; }
Is casting char to int a safe operation in C # ?
C#
I have a controller running on Azure App Service - Mobile . The trace shows that the below code runs fine until db.SaveChanges ( ) this fails.The stacktrace from the diagnostic on the appservice ( which I unfortunately do not understand ) gives : UpdateSo I will be trying this , which will give more detailed error mess...
var telemetry = new Microsoft.ApplicationInsights.TelemetryClient ( ) ; telemetry.TrackTrace ( `` Create User '' ) ; using ( BCMobileAppContext db = new BCMobileAppContext ( ) ) { string Username_NoSpaces = username.Username.Replace ( `` `` , `` '' ) ; var user = db.Users.FirstOrDefault ( u = > u.Username_NoSpaces == U...
Db context on azure app service ( mobile ) fails
C#
Just Asking : Why 'withOffset ' variable is inferred as dynamic as Parse method returns Struct ? and after explicit cast its back to Struct ? since the return type of DateTimeOffset.Parse is DateTimeOffset , and the compiler must know that . keeping that in mind , what ever method it invoke at runtime , the return is a...
dynamic str = `` 22/11/2013 10:31:45 +00:01 '' ; var withOffset = DateTimeOffset.Parse ( str ) ; dynamic str = `` 22/11/2013 10:31:45 +00:01 '' ; var withOffset = DateTimeOffset.Parse ( ( string ) str ) ;
C # DLR , Datatype inference with Dynamic keyword
C#
I am trying to query data from Azure WadPerformanceCountersTable.I am trying to get the last 5 minutes of data.The problem is that I only get data from instances nr . 4,5 and 6 , but not from 0,1,2 and 3.The script I am using to pull de data is this : My diagnostics.wadcfg file is this : EDIT : Also , I have this code ...
Microsoft.WindowsAzure.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.CloudStorageAccount.Parse ( AppDefs.CloudStorageAccountConnectionString ) ; CloudTableClient cloudTableClient = storageAccount.CreateCloudTableClient ( ) ; TableServiceContext serviceContext = cloudTableClient.GetDataServiceContext ( ) ;...
Azure instances from 0 to 3 not writing diagnostics data in WadPerformanceCountersTable
C#
Basically I just want to check if one time period overlaps with another.Null end date means till infinity . Can anyone shorten this for me as its quite hard to read at times . Cheers
public class TimePeriod { public DateTime StartDate { get ; set ; } public DateTime ? EndDate { get ; set ; } public bool Overlaps ( TimePeriod other ) { // Means it overlaps if ( other.StartDate == this.StartDate || other.EndDate == this.StartDate || other.StartDate == this.EndDate || other.EndDate == this.EndDate ) r...
Can anyone simplify this Algorithm for me ?
C#
Ok , So I have the following situation . I originally had some code like this : Now , I decided to refactor that code so the classes ' dependencies are injected , instead : My question is what to do about Board Size ? I mean , in the first case , I just passed the class the desired board size , and it would do everythi...
public class MainBoard { private BoardType1 bt1 ; private BoardType2 bt2 ; private BoardType3 bt3 ; ... private readonly Size boardSize ; public MainBoard ( Size boardSize ) { this.boardSize = boardSize ; bt1 = new BoardType1 ( boardSize ) ; bt2 = new BoardType2 ( boardSize ) ; bt3 = new BoardType3 ( boardSize ) ; } } ...
How to convert this code so it now uses the Dependency Injection pattern ?
C#
I have a python script : It 's so easy to achieve multiple return values in python.And now I want to achieve the same result in C # . I tried several ways , like return int [ ] or KeyValuePair . But both ways looked not elegant . I wonder a exciting solution . thanks a lot .
def f ( ) : a = None b = None return ( a , b ) a , b = f ( )
How to achieve multiple return values in C # like python style
C#
I 've created an website available in three languages : english , portuguese and spanish.It 's everything working fine except for one thing : it was not updating a BoundField when an accentuated word is loaded into it.Below is the field which does n't update in the gridview at MEMGridView.ascx : At App_LocalResources a...
< asp : BoundField DataField= '' Ocupacao '' HeaderText= '' Ocupação '' SortExpression= '' Ocupação '' meta : resourcekey= '' BoundFieldResource9 '' > < ItemStyle HorizontalAlign= '' Center '' / > < /asp : BoundField > public partial class MEMGridView : UserControl { ... protected override void FrameworkInitialize ( ) ...
Globalization issue on asp.net : it 's not updating accentuated words
C#
I 've been looking for a way to extract slices from a 2D matrix without having to actually reallocate-copy the contents , and I 've checked this method with this simple Unit tests and apparently it works : This does n't seem right to me though . I mean , I 'd like to understand what 's exactly happening behind the scen...
public static Span < float > Slice ( [ NotNull ] this float [ , ] m , int row ) { if ( row < 0 || row > m.GetLength ( 0 ) - 1 ) throw new ArgumentOutOfRangeException ( nameof ( row ) , `` The row index is n't valid '' ) ; return Span < float > .DangerousCreate ( m , ref m [ row , 0 ] , m.GetLength ( 1 ) ) ; } [ TestMet...
Slicing a Span < T > row from a 2D matrix - not sure why this works
C#
I got an old solution and I am trying to build a newer one using the current projects in it . One of the projects is SQLUtils that contains only .cs files and the Target framework of it is .NET Framework 2.0.In the old solution it is a regular C # Class Library project but when I add it to my new solution it becomes .s...
Microsoft Visual Studio Solution File , Format Version 12.00 # Visual Studio 14VisualStudioVersion = 14.0.25420.1MinimumVisualStudioVersion = 10.0.40219.1Project ( `` { E24C65DC-7377-472B-9ABA-BC803B73C61A } '' ) = `` BO 25.7.17 '' , `` BO 25.7.17 '' , `` { 5C12D821-9F39-4C47-A888-DD65E5CD6464 } '' ProjectSection ( Web...
How to stop VS2015 from converting my.csproj into .sqlproj ?
C#
The following simple code will yield an `` invariant unproven '' warning by the static checker of Code Contracts , although there is no way _foo can be null . The warning is for the return statement inside UncalledMethod.Apart from the fact , that the warning is simply invalid , it only occures in certain specific circ...
public class Node { public Node ( string s1 , string s2 , string s3 , string s4 , object o , string s5 ) { } } public class Bar { private readonly string _foo ; public Bar ( ) { _foo = `` foo '' ; } private object UncalledMethod ( ) { return new Node ( string.Empty , string.Empty , string.Empty , string.Empty , GetNode...
`` Invariant unproven '' when using method that creates a specific new object in its return statement
C#
I have a themed page whereby the theme is chosen inside a http module.Now when I request the elmah.axd the following exception is thrown : Using themed css files requires a header control on the page . ( e.g . ) .When I disable the http theme module everything is fine and elmah.axd page is shown . I think this is a sma...
public void context_PreRequestHandlerExecute ( object sender , EventArgs e ) { Page p = HttpContext.Current.Handler as Page ; if ( p ! = null ) { //get theme string theme = GetTheme ( HttpContext.Current.Request.Url.Host ) ; Debug.WriteLine ( String.Format ( `` Loading theme { 0 } '' , theme ) ) ; //set theme of page p...
ELMAH within a themed page error
C#
When I trying to define a class which inherits from System.ValueType or System.Enum class , I 'm getting an error : I understand that error but what I could n't understand is what makes ValueType class special ? I mean there is no keyword ( like sealed ) or attribute to specify that this class can not be inherited.Valu...
Can not derive from special class System.ValueType
What makes ValueType class Special ?
C#
Im having some trouble getting this generic constraint to work.I have two interfaces below . I want to be able to constrain the ICommandHandlers TResult type to only use types that implement ICommandResult , but ICommandResult has its own constraints that need to be supplied . ICommandResult could potentially return a ...
public interface ICommandResult < out TResult > { TResult Result { get ; } } public interface ICommandHandler < in TCommand , TResult > where TCommand : ICommand where TResult : ICommandResult < ? ? ? ? > { TResult Execute ( TCommand command ) ; }
Defining generic interface type constraint for value and reference types
C#
Is it possible to write methods , which are only callable by unit tests ? My problem is that our framework contains a lot of Singleton classes , which makes unit testing quite hard some time . My idea was to create a simple interface like this : This method will be called for `` resetting '' singleton instances for bet...
public interface IUnitTestClearable { void ClearForUnitTest ( ) ; }
Make method only callable from unit test
C#
I 'm using an AutoFixture customization to test a repository which access to a SQL Compact DB.Would be very helpful to me to delete this database as soon as the test is completed . Because the db is created in the customization constructor I think that the best place to delete it is in the dispose method.The code which...
internal class ProjectRepositoryCustomization : ICustomization { private readonly String _dbLocation ; public ProjectRepositoryCustomization ( ) { var tempDbLocation = Path.Combine ( Path.GetTempPath ( ) , `` TempDbToDelete '' ) ; if ( ! Directory.Exists ( tempDbLocation ) ) { Directory.CreateDirectory ( tempDbLocation...
Invoke Dispose method on AutoFixture customization
C#
I am just starting to learn about the code contracts library that comes standard with VS2010 . One thing I am running into right away is what some of the contract clauses really mean.For example , how are these two statements different ? In other words , what does Contract.Exists do in practical purposes , either for a...
Contract.Requires ( ! mycollection.Any ( a = > a.ID == newID ) ) ; Contract.Requires ( ! Contract.Exists ( mycollection , a = > a.ID == newID ) ) ;
How does Contract.Exists add value ?
C#
I have a list of Button , and I add an event handler for each button : Then I clear the list :
List < Button > buttons = new List < Button > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { Button btn = new Button ( ) ; btn.Click = new RoutedEventHandler ( OnbtnClick ) ; buttons.Add ( btn ) ; } /* Have I to remove all events here ( before cleaning the list ) , or not ? foreach ( Button btn in buttons ) btn.Click -= new ...
Should I remove an event handler ?
C#
I know various questions have been asked that resembles this question , but as far as I can tell ( and test ) , none of the provided solutions seems to fit , so here goes.I am wondering if it is possible to flatten/denormalise an object hierarchy so that an instance with a list of nested properties is mapped to a list ...
public class DistributionInformation { public string Streetname ; public RouteInformation [ ] Routes ; } public class RouteInformation { public int RouteNumber ; public string RouteDescription ; } public class DenormDistributionInfo { public string Streetname ; public int RouteNumber ; public string RouteDescription ; ...
Denormalise object hierarchy with automapper
C#
I seem to be having a problem with retrieving XML values with C # , which I know it is due to my very limited knowledge of C # and .XML.I was given the following XML fileI am to process the XML file and make sure that each of the files in the exist in the folder ( that 's the easy part ) . It 's the processing of the X...
< PowerBuilderRunTimes > < PowerBuilderRunTime > < Version > 12 < /Version > < Files > < File > EasySoap110.dll < /File > < File > exPat110.dll < /File > < File > pbacc110.dll < /File > < /File > < /PowerBuilderRunTime > < /PowerBuilderRunTimes > var runtimeXml = File.ReadAllText ( string.Format ( `` { 0 } \\ { 1 } '' ...
Retrieving Data From XML File
C#
I 've set up a little example where I loaded an assembly into a new AppDomain without any Permission . This works fine , the assembly ca n't access the file system and ca n't listen to sockets.But there is another thing i want to prevent : Thread creation . Why ? Cause theoreticly this assembly can create a thread whic...
Thread t = new Thread ( this.DoWork ) ; t.Start ( ) ; PermissionSet set = new PermissionSet ( PermissionState.None ) ; set.AddPermission ( new SecurityPermission ( SecurityPermissionFlag.Execution ) ) ; set.AddPermission ( new FileIOPermission ( FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery , this....
Prevent thread creation in AppDomain
C#
The question is very straightforward , if I have a following class : and change it to : can it break a legay client dll ?
public class ExportReservationsToFtpRequestOld { public int A { get ; set ; } public long B { get ; set ; } } public class ExportReservationsToFtpRequestOld { public virtual int A { get ; set ; } public virtual long B { get ; set ; } }
Does adding virtual to a C # method may break legacy clients ?
C#
In the following WPF code , once button is clicked , a new foreground thread is started . Then I close the WPF window , I could see that in Windows task manager , the process wo n't be terminated until Thread.Sleep ( 100000 ) ends . I could understand it because foreground threads could prevent process from terminating...
public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private void Button_Click ( object sender , RoutedEventArgs e ) { new Thread ( Go ) .Start ( ) ; } private void Go ( object obj ) { Thread.Sleep ( 100000 ) ; } } class Program { static void Main ( string [ ] args ) { new Thre...
Foreground thread do n't stop a console process from terminating ?
C#
I wonder if it is possible to get MatchCollection with all matches even if there 's intersection among them.This code returns 1 , but I want it to return 2 . How to achive it ? Thank you for your help .
string input = `` a a a '' ; Regex regex = new Regex ( `` a a '' ) ; MatchCollection matches = regex.Matches ( input ) ; Console.WriteLine ( matches.Count ) ;
regex matches with intersection in C #
C#
I have two interfaces : An example of a closed implementation of IQueryHandler : I can register and resolve closed generic implementations of IQueryHandler < , > with this component registration : However what I would like to do is resolve an open generic implementation that is `` half closed '' ( ie specifies a generi...
public interface IQuery < TResult > { } public interface IQueryHandler < in TQuery , out TResult > where TQuery : IQuery < TResult > { TResult Handle ( TQuery q ) ; } public class EventBookingsHandler : IQueryHandler < EventBookings , IEnumerable < EventBooking > > { private readonly DbContext _context ; public EventBo...
Registering 'half-closed ' generic component
C#
Currently trying to create a wrapper for an iOS framework on Unity.I made a .bundle , containing basic objective-c code : sample.h : sample.mm : The SDK is included in the bundle as a .framework ( references in `` Linked Frameworks and libraries '' ) . The bundle target is iOS.The bundle builds successfully.The bundle ...
# import < Foundation/Foundation.h > extern `` C '' { void SampleFunction ( ) ; // this is going to call already bridged swift or objc code } # import `` Sample.h '' # import < SDK/SDKFunctions.h > void SampleFunction ( ) { // my sweet functions calls } public class BundleImportSample : MonoBehaviour { # if UNITY_IOS [...
Unity iOS - Can not import functions from .Bundle
C#
If I 'm explaining the following ForEach feature to someone , is it accurate to say that # 2 is the `` LINQ foreach approach '' or is it simply a `` List < T > extension method '' that is not officially associated with LINQ ?
var youngCustomers = from c in customers where c.Age < 30 select c ; //1 . traditional foreach approachforeach ( var c in youngCustomers ) { Console.WriteLine ( c.Display ( ) ) ; } //2 . LINQ foreach approach ? youngCustomers.ToList ( ) .ForEach ( c = > Console.WriteLine ( c.Display ( ) ) ) ;
What part of the C # language is .ForEach ( ) ?
C#
Possible Duplicate : Collection < T > versus List < T > what should you use on your interfaces ? Consider this method—the returned variable myVar is a List < T > , but the return type of the method MyMethod ( ) is an IEnumerable < T > : Essentially , what I want to know is if returning myVar as a different type is OK.S...
public IEnumerable < T > MyMethod ( string stuff ) { var myVar = new List < T > ( ) ; //do stuff return myVar ; }
OK to return an internal List < T > as an IEnumerable < T > or ICollection < T > ?
C#
A control can only be accessed by the thread that created it - this much I know . I have a DataGridView with aDataSource based on a BindingList < > .I have a worker thread ( non-GUI ) that runs some fancycalculations/comparisons/etc andthen adds/edits an object to/in the BindingList < > .On a timer , the GUI thread ref...
An Exception has occurredEXCEPTION : Cross-thread operation not valid : Control `` accessed from a thread other than the thread it was created on.IN METHOD : get_HandleAT LINE : 0CLASS : System.Windows.Forms.Control
Cross-Thread Exception - Environment Only
C#
Consider the following code : With the following output : Why is it false and null ? A has n't been collected yet.EDIT : Oh ye of little faith.I added the following lines : See the updated output .
class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; CreateB ( a ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Console.WriteLine ( `` And here 's : '' + a ) ; GC.KeepAlive ( a ) ; } private static void CreateB ( A a ) { B b = new B ( a ) ; } } class A { } class B { private WeakReference a ;...
Why is a WeakReference useless in a destructor ?
C#
As shown here , attribute constructors are not called until you reflect to get the attribute values . However , as you may also know , you can only pass compile-time constant values to attribute constructors . Why is this ? I think many people would much prefer to do something like this : than passing a string ( causin...
[ MyAttribute ( new MyClass ( foo , bar , baz , jQuery ) ]
If attributes are only constructed when they are reflected into , why are attribute constructors so limited ?
C#
In the Microsoft.VisualStudio.TestTools.UnitTesting namespace , there is the handy static class Assert to handle the assertions going on in your tests.Something that has got me bugged is that most methods are extremely overloaded , and on top of that , they have a generic version . One specific example is Assert.AreEqu...
Assert.AreEqual < T > ( T t1 , T t2 ) Assert.AreEqual < T > ( T t1 , T t2 ) where T : IEquatable < T >
Microsoft.VisualStudio.TestTools.UnitTesting.Assert generic method overloads behavior
C#
I am trying to build an interface for a game . The game runs for 1 minute . The GetStop method stops after 60 sec game . The play method starts the game and the quit method quit the game . Now ideally what I want is when I quit the game after 30 seconds , the timer should get reset and on click of the Play button , the...
private async Task GetStop ( CancellationToken token ) { await Task.Run ( async ( ) = > { token.ThrowIfCancellationRequested ( ) ; await Task.Delay ( TimeSpan.FromSeconds ( 60 ) , token ) ; token.ThrowIfCancellationRequested ( ) ; if ( ! token.IsCancellationRequested ) { sendMessage ( ( byte ) ACMessage.AC_ESCAPE ) ; }...
Task.Delay didn ’ t get canceled ?
C#
The code below shows a generic class with a type constraint ( Pub < T > ) . The class has an event that it can raise allowing us to pass a message to subscribers . The constraint is that the message must implement IMsg ( or inherit from IMsg when it 's is an abstract class ) .Pub < T > also provides a Subscribe method ...
public interface IMsg { } // Does n't work//public abstract class IMsg { } // Does workpublic class Msg : IMsg { } public class Pub < T > where T : IMsg { public event Action < T > notify ; public void Subscribe ( object subscriber ) { // Subscriber subscribes if it implements IHandler of the exact same type as T // Th...
Why does n't an interface work but an abstract class does with a generic class constraint ?
C#
According to MSDN the .NET XmlDocument.Load ( String ) method requires write access to the underlying file . The exceptions list saysMy question boils down toIs it even true that read-write access is needed , or is this just a documentation error ? Does it mean that the file is kept open during the lifetime of the obje...
UnauthorizedAccessException : filename specified a file that is read-only ... .
Why does XmlDocument.Load ( String ) seem to want read-write access ?