lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
During switching to the new .NET Core 3 's IAsynsDisposable , I 've stumbled upon the following problem.The core of the problem : if DisposeAsync throws an exception , this exception hides any exceptions thrown inside await using-block.What is getting caught is the AsyncDispose-exception if it 's thrown , and the excep...
class Program { static async Task Main ( ) { try { await using ( var d = new D ( ) ) { throw new ArgumentException ( `` I 'm inside using '' ) ; } } catch ( Exception e ) { Console.WriteLine ( e.Message ) ; // prints I 'm inside dispose } } } class D : IAsyncDisposable { public async ValueTask DisposeAsync ( ) { await ...
Proper way to deal with exceptions in AsyncDispose
C#
I have been chasing this issue for a day now and am stumped , so thought I would put it out to you folks for some inspiration . I 'm a bit of a novice when it comes to deadlocks and SQL Server lock modes , I rarely need to delve into this.The short story : When a user logs into our application , we want to update a SQL...
< deadlock-list > < deadlock victim= '' process4785288 '' > < process-list > < process id= '' process4785288 '' taskpriority= '' 0 '' logused= '' 0 '' waitresource= '' OBJECT : 7:617365564:0 `` waittime= '' 13040 '' ownerId= '' 3133391 '' transactionname= '' SELECT '' lasttranstarted= '' 2013-01-07T15:16:24.680 '' XDES...
Deadlocks during logon to ASP app caused by dropping/creating SQL Server views
C#
I have the following code attaching event handler : Can I unsubscribe that lambda expression from the vent ?
this.btnOK.Click += ( s , e ) = > { MessageBox.Show ( `` test '' ) ; } ;
Unsubscribe lambda expression from event c #
C#
Would appreciate any kind of help here . A brief description about scenario -There is a COM+ running on server ( written in C # ) . The task of this COM is to take a file name , page number of a multi-paged tiff file and the resolution to convert it to a gif file image . This COM is called from a web application using ...
EventType clr20r3 , P1 imageCOM.exe , P2 1.0.0.0 , P3 4fd65854 , P4 prod.web.imaging , P5 1.0.0.0 , P6 4fd65853 , P7 1a , P8 21 , P9 system.outofmemoryexception , P10 NIL.Here is the error ( s ) on the web server ( these continuously appear every minute ) ….System.Net.WebException : Unable to connect to the remote serv...
Possibly memory leak OR ?
C#
I researched this subject but I could n't find any duplicate . I am wondering why you can use a struct in an array without creating an instance of it.For example , I have a class and a struct : When ClassAPI is used in an array , it has to be initialized with the new keyword before being able to use its properties and ...
public class ClassAPI { public Mesh mesh { get ; set ; } } public struct StructAPI { public Mesh mesh { get ; set ; } } ClassAPI [ ] cAPI = new ClassAPI [ 1 ] ; cAPI [ 0 ] = new ClassAPI ( ) ; //MUST DO THIS ! cAPI [ 0 ] .mesh = new Mesh ( ) ; StructAPI [ ] sAPI = new StructAPI [ 1 ] ; sAPI [ 0 ] .mesh = new Mesh ( ) ;...
Why does n't a struct in an array have to be initialized ?
C#
I reviewed a colleagues code and told him to reorder the boolean comparisons in the following Linq Any predicate for performance reasons . So givenandI suggested changing the following : to becomeMy reasoning was that most of the jobs in jobsList fail the test for JobType , only a few will fail the test for Running and...
public class JobResult { public JobResult ( ) ; public string Id { get ; set ; } public StatusEnum Status { get ; set ; } public string JobType { get ; set ; } } IList < JobResult > jobsList = _jobRepository.FetchJobs ( ) //Exit if there is already a job of type `` PurgeData '' runningif ( jobsList.Any ( job = > job.St...
Order of evaluation c #
C#
I was reading this page , which is officially referenced in the release notes of Visual Studio 17 RC , it states the following : For the purpose of Overloading Overriding Hiding , tuples of the same types and lengths as well as their underlying ValueTuple types are considered equivalent . All other differences are imma...
public abstract class Foo { public abstract void AbstractTuple ( ( int a , string b ) tuple ) ; public virtual void OverrideTuple ( ( int a , string b ) tuple ) { Console.WriteLine ( $ '' First= { tuple.a } Second = { tuple.b } '' ) ; } } public class Bar : Foo { public override void AbstractTuple ( ( int c , string d ...
Overriding Methods with Tuples and Field Name Rules in C # 7.0
C#
I 'm trying to implement a search function in a custom ListView and as such I am hiding Items with a custom ObservableCollection which allows AddRange , similar to the one defined on damonpayne.com ( for the tl ; dr-ers out there basically it suppresses firing OnCollectionChanged event while adding multiple items then ...
public new MyCollection < ListViewItem > Items { get ; protected set ; } this.BeginUpdate ( ) ; base.Items.Clear ( ) ; base.Items.AddRange ( this.Items.ToArray ( ) ) ; this.EndUpdate ( ) ; var item0 = new ListViewItem ( ) ; var item0.Group = this.Groups [ `` foo '' ] ; //here this.Items.Count = 0this.Items.Add ( item0 ...
ListViewItem 's group not being preserved through another collection
C#
I 've been trying to shift myself into a more test driven methodology when writing my .net MVC based app . I 'm doing all my dependency injection using constructor-based injection . Thus far it 's going well , but I 've found myself doing something repeatedly and I 'm wondering if there is a better practice out there.L...
'MyProject.Web.Api.Controllers.MyExampleController ' does not contain a constructor that takes 3 arguments var controllerToTest = new MyExampleController ( mockUOW.Object ) ; var controllerToTest = new MyExampleController ( mockUOW.Object , null , null ) ;
Unit tests break when I add new dependency to controller
C#
I was debugging resource leaks in my application and created a test app to test GDI object leaks . In OnPaint I create new icons and new bitmaps without disposing them . After that I check the increase of GDi objects in task manager for each of the cases . However , if I keep repainting the main window of my app , the ...
public partial class MainForm : Form { public MainForm ( ) { InitializeComponent ( ) ; } protected override void OnPaint ( PaintEventArgs e ) { base.OnPaint ( e ) ; // 1. icon increases number of GDI objects used by this app during repaint . //var icon = Resources.TestIcon ; //e.Graphics.DrawIcon ( icon , 0 , 0 ) ; // ...
Is there a difference in disposing Icon and Bitmap ?
C#
I am really confused , take the following code : And yes I know that I could directly cast the integer to the given Enum , but this is a simplified version of my actual code which includes the work with generic extensions.Anyhow I ran a few performance tests , because I was curious which one is faster . I am using Benc...
[ Benchmark ] public TEnum DynamicCast ( ) { return ( TEnum ) ( dynamic ) 0 ; } [ Benchmark ] public TEnum ObjectCast ( ) { return ( TEnum ) ( object ) 0 ; } [ Benchmark ] public TEnum DirectCast ( ) { return ( TEnum ) 0 ; } public enum TEnum { Foo , Bar } BenchmarkDotNet=v0.12.0 , OS=Windows 10.0.18362Intel Core i7-67...
Why is casting with dynamic faster than with object
C#
How can I change items in my double variable based on a simple condition ? Check this example : After executing the function setDouble ( ) , these values did n't change . No errors found . How can I fix this ?
public partial class Form1 : Form { double [ ] vk = new double [ 11 ] { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; ... ... void setDouble ( ) { if ( bunifuDropdown1.selectedIndex == 0 ) { double [ ] vk = new double [ 11 ] { 2 , 4.86 , 11.81 , 28.68 , 69.64 , 169.13 , 410.75 , 997.55 , 2422.61 , 5883.49 , 21000 } ; }...
How can I change items inside a double array ?
C#
My company is on a Unit Testing kick , and I 'm having a little trouble with refactoring Service Layer code . Here is an example of some code I wrote : In this simplified case ( it is reduced from a 1,000 line class that has 1 public method and ~30 private ones ) , my boss says I should be able to test my CalculateInvo...
public class InvoiceCalculator : IInvoiceCalculator { public CalculateInvoice ( Invoice invoice ) { foreach ( InvoiceLine il in invoice.Lines ) { UpdateLine ( il ) ; } //do a ton of other stuff here } private UpdateLine ( InvoiceLine line ) { line.Amount = line.Qty * line.Rate ; //do a bunch of other stuff , including ...
Refactoring Service Layer classes
C#
I have an object called Page , with an instance called p that has a custom property called AssociatedAttributes . If I do the following : numMatchingAttributes ends up equaling 0 even though p has 6 AssociatedAttributes . Why does it not equal 6 ? AssociatedAttributes is of Type List < Attribute > ( Attribute is my own...
int numMatchingAttributes = p.AssociatedAttributes.Intersect ( p.AssociatedAttributes ) .Distinct ( ) .Count ( ) ; public int CompareTo ( Attribute other ) { return Id.CompareTo ( other.Id ) ; } public List < Attribute > AssociatedAttributes { get { List < Attribute > list = new List < Attribute > ( ) ; using ( Predict...
Can someone explain LINQ 's intersect properly to me ? I do n't understand why this does n't work
C#
Do the following 2 code snippets achieve the same thing ? My original code : What ReSharper thought was a better idea : I think the above code is much easier to read , any compelling reason to change it ? Would it execute faster , and most importantly , will the code do the exact same thing ? Also if you look at the : ...
if ( safeFileNames ! = null ) { this.SafeFileNames = Convert.ToBoolean ( safeFileNames.Value ) ; } else { this.SafeFileNames = false ; } this.SafeFileNames = safeFileNames ! = null & & Convert.ToBoolean ( safeFileNames.Value ) ; this.SafeFileNames = bool public class Configuration { public string Name { get ; set ; } p...
Are these 2 statements identical ?
C#
I have a sorted array of strings.Given a string that identifies a prefix , I perform two binary searches to find the first and last positions in the array that contain words that start with that prefix : Running this code I get firstPosition and lastPosition both equal to 1 , while the right answer is to have lastPosit...
string [ ] words = { `` aaa '' , '' abc '' , '' abcd '' , '' acd '' } ; string prefix = `` abc '' ; int firstPosition = Array.BinarySearch < string > ( words , prefix ) ; int lastPosition = Array.BinarySearch < string > ( words , prefix + char.MaxValue ) ; if ( firstPosition < 0 ) firstPosition = ~firstPosition ; if ( ...
Why ( `` abc '' +char.MaxValue ) .CompareTo ( `` abc '' ) ==0 ?
C#
I have a list of objects that looks like this : now , I 'd like to browse ( traverse ) it with a for each . But I want to traverse it starting from the same ID . So , first a foreach for the single/unique ID ( 2000 , 3000 , 4000 , so 3 steps ) . Than , for each `` ID '' step , each Title/Description : so 2 steps for th...
ID:2000Title : '' Title 1 '' Description : '' My name is Marco '' ID:2000Title : '' Title 2 '' Description : '' My name is Luca '' ID:3000Title : '' Title 3 '' Description : '' My name is Paul '' ID:4000Title : '' Title 4 '' Description : '' My name is Anthony '' ID:4000Title : '' Title 5 '' Description : '' My name is...
How can I traverse this list in this manner ?
C#
Is calling Array.Resize on an array that is being used as a buffer for SAEA threadsafe ? different threads all write to their own assigned part of the array , I just want to make the array bigger without locking once the initialized size runs out as connected users increase .
byte [ ] buffer ; //Accessedobject expand_Lock = new object ( ) ; public void AsyncAccept ( ) { //Lock here so we do n't resize the buffer twice at once lock ( expand_Lock ) { if ( bufferFull ) { Array.Resize ( buffer , buffer.Length + 2048 * 100 ) ; //Add space for 100 more args //Is Array.Resize threadsafe if buffer ...
Is Array.Resize ( .. ) threadsafe ?
C#
I need to be able to say something like myString.IndexOf ( c = > ! Char.IsDigit ( c ) ) , but I ca n't find any such method in the .NET framework . Did I miss something ? The following works , but rolling my own seems a little tedious here :
using System ; class Program { static void Main ( ) { string text = `` 555ttt555 '' ; int nonDigitIndex = text.IndexOf ( c = > ! Char.IsDigit ( c ) ) ; Console.WriteLine ( nonDigitIndex ) ; } } static class StringExtensions { public static int IndexOf ( this string self , Predicate < char > predicate ) { for ( int inde...
Is there a String.IndexOf that takes a predicate ?
C#
I have a base class : And a class which stores the DomainEventSubscriber references : Even though the Subscribe method type is constrained , I can not convert from DomainEventSubscriber < T > subscriber where T : DomainEvent to DomainEventSubscriber < DomainEvent > : How would I go about performing this conversion , or...
public abstract class DomainEventSubscriber < T > where T : DomainEvent { public abstract void HandleEvent ( T domainEvent ) ; public Type SubscribedToEventType ( ) { return typeof ( T ) ; } } public class DomainEventPublisher { private List < DomainEventSubscriber < DomainEvent > > subscribers ; public void Subscribe ...
Convert generic parameter with 'where ' type constraint not possible ?
C#
I created a SqlDependency so that an event would fire when the results of a particular query change.When this code executes , a stored procedure is automatically created with a name like SqlQueryNotificationStoredProcedure-82ae1b92-21c5-46ae-a2a1-511c4f849f76This procedure is unencrypted , which violates requirements I...
// Create a commandSqlConnection conn = new SqlConnection ( connectionString ) ; string query = `` SELECT MyColumn FROM MyTable ; '' ; SqlCommand cmd = new SqlCommand ( query , conn ) cmd.CommandType = CommandType.Text ; // Register a dependencySqlDependency dependency = new SqlDependency ( cmd ) ; dependency.OnChange ...
Encrypt the stored procedure created by SqlDependency
C#
Visual Studio C # compiler warns about accidentally assigning a variable to itself , but this warning does not apply to C # properties , only variables . As described in this other question.However , I would really like something similar that can warn me at compile time if I assign a property to itself.I 'm currently u...
public class Foo { public ILogger Logger { get ; private set ; } public Foo ( ILogger logger ) { if ( logger == null ) throw new ArgumentNullException ( `` logger '' ) ; this.Logger = logger ; } } public class Foo { public ILogger Logger { get ; private set ; } public Foo ( ILogger logger ) { if ( logger == null ) thro...
Compile-time detection of accidentally assign a C # property to itself
C#
Here 's a bit of a tricky one . Perhaps someone 's C # -fu is superior to mine , as I could n't find a solution.I have a method that takes a parameter that holds either an enum or a string indicating the value of an Enum and returns an instance of that enum . It 's basically an implementation of Enum.Parse but implemen...
public static T Parse < T > ( object value ) where T : struct { if ( ! typeof ( T ) .IsEnum ) throw new ArgumentException ( `` T must be an Enum type . `` ) ; if ( value == null || value == DBNull.Value ) { throw new ArgumentException ( `` Can not parse enum , value is null . `` ) ; } if ( value is String ) { return ( ...
Is there any way to combine these two methods into one method , or overloaded methods ?
C#
It is conventional to name namespaces in a C # solution such that they match the default namespace for the project plus the name of any sub-directories for the containing file.For example , a file called Haddock.cs is in a directory called Fish and the default namespace ( in the first tab of the project 's properties i...
namespace Lakes.Fish { public class Haddock { } }
Can an analyzer validate that namespaces properly match the file location
C#
I 'm looking to retrieve the last row of a table by the table 's ID column . What I am currently using works : Is there any way to get the same result with more efficient speed ?
var x = db.MyTable.OrderByDescending ( d = > d.ID ) .FirstOrDefault ( ) ;
What 's the most efficient way to get only the final row of a SQL table using EF4 ?
C#
I 'm writing a small data structures library in C # , and I 'm running into an architectural problem . Essentially I have a class which implements the visitor pattern , and there are many possible implementations of visitors : Anytime I want to pass in a visitor , I have to create a visitor class , implement the interf...
public interface ITreeVisitor < T , U > { U Visit ( Nil < T > s ) ; U Visit ( Node < T > s ) ; } public abstract class Tree < T > : IEnumerable < T > { public readonly static Tree < T > empty = new Nil < T > ( ) ; public abstract U Accept < U > ( ITreeVisitor < T , U > visitor ) ; } public sealed class Nil < T > : Tree...
How do I simulate anonymous classes in C #
C#
I am trying to create text that looks like this in WPF : Notice that it is yellow text , with a black stroke , then a yellow stroke , then another ( very thin ) black stroke . Now , I can create a single stroke with little difficult by following How to : Create Outlined Text . Note that the properties not shown are all...
protected override void OnRender ( System.Windows.Media.DrawingContext drawingContext ) { // Draw the outline based on the properties that are set . drawingContext.DrawGeometry ( Fill , new System.Windows.Media.Pen ( Stroke , StrokeThickness ) , _textGeometry ) ; } /// < summary > /// Create the outline geometry based ...
How do you create multiple strokes on text in WPF ?
C#
I have a set of classes with the same functions but with different logic . However , each class function can return a number of objects . It is safe to set the return type as the interface ? Each class ( all using the same interface ) is doing this with different business logic.Are there any pitfalls with unit testing ...
protected IMessage validateReturnType ; < -- This is in an abstract classpublic bool IsValid ( ) < -- This is in an abstract class { return ( validateReturnType.GetType ( ) == typeof ( Success ) ) ; } public IMessage Validate ( ) { if ( name.Length < 5 ) { validateReturnType = new Error ( `` Name must be 5 characters o...
Is it advisable to have an interface as the return type ?
C#
Which one is better to use ? ORint xyz= default ( int ) ;
int xyz = 0 ;
Which one is better to use and why in c #
C#
I have a file that looks something like this : I need to break the file up into multiple files based on the first 6 characters starting in position 2.File 1 named 29923c.asc : File 2 named 47422K.asc : File 3 named 9875D.asc : I do n't know what will be in the file before the program gets it , just the format . The 6 d...
|29923C|SomeGuy , NameHere1 |00039252|042311|Some Address Info Here ||47422K|SomeGuy , NameHere2 |00039252|042311|Some Address Info Here ||98753D|SomeGuy , NameHere3 |00039252|042311|Some Address Info Here ||29923C|SomeGuy , NameHere4 |00039252|042311|Some Address Info Here ||47422K|SomeGuy , NameHere5 |00039252|042311...
C # Text File Input Multi-File Output
C#
For those who are not sure what is meant by 'constrained non-determinism ' I recommend Mark Seeman 's post.The essence of the idea is the test having deterministic values only for data affecting SUT behavior . Not 'relevant ' data can be to some extent 'random'.I like this approach . The more data is abstract the more ...
[ TestMethod ] public void DoSomethig_RetunrsValueIncreasedByTen ( ) { // Arrange ver input = 1 ; ver expectedOutput = input+10 ; var sut = new MyClass ( ) ; // Act var actualOuptut = sut.DoeSomething ( input ) ; // Assert Assert.AreEqual ( expectedOutput , actualOutput , '' Unexpected return value . `` ) ; } /// Here ...
Detecting 'dead ' tests and hardcoded data vs constrained non-determinism
C#
can anyone explain why the TextBlock inside my DataTemplate does not apply the style defined in my UserControl.Resources element , but the second TextBlock ( 'Test B ' ) does ? I think it may have to do with a dependency property somewhere set to not inherit , but I ca n't be sure .
< UserControl.Resources > < Style TargetType= '' { x : Type TextBlock } '' > < Setter Property= '' Padding '' Value= '' 8 2 '' / > < /Style > < /UserControl.Resources > < StackPanel > < ItemsControl ItemsSource= '' { Binding } '' > < ItemsControl.ItemTemplate > < DataTemplate > < ! -- Padding does not apply -- > < Text...
No Style Inheritance Inside ItemsControl / DataTemplate in WPF ?
C#
I am trying to get into C # generics and have created a state machine with the state pattern and now I try to refactor.I have a state , which has a reference to the object it 's working on.and I have the object which has states , this should have a reference to its current state.But it does not work ( `` the type can n...
public abstract class AbstractState < T > where T : StatefulObject { protected T statefulObject ; public AbstractState ( T statefulObject ) { this.statefulObject = statefulObject ; } } public abstract class StatefulObject < T > : MonoBehaviour where T : AbstractState < StatefulObject < T > > { public T state ; } public...
C # generics , cross referencing classes for state pattern
C#
Consider the following attribute.When I try to use the attribute [ Nice ( Stuff = `` test '' ) ] the compiler gives the following error . 'Stuff ' is not a valid named attribute argument . Named attribute arguments must be fields which are not readonly , static , or const , or read-write properties which are public and...
internal class NiceAttribute : Attribute { private string _stuff ; public string Stuff { set { _stuff = value ; } } } interface ISettingsBuilder { Settings GetSettings ( ) ; } class SettingsAttribute : Attribute , ISettingsBuilder { private readonly IDictionary < string , object > _settings = new Dictionary < string , ...
Why do properties of attributes have to be readable ?
C#
I 'm working my way through this ASP MVC tutorial . This page of the tutorial deals with writing a simple `` search '' page . The controller contains this method : According to MSDN , String.Contains is case-sensitive . But when I navigate to [ website url ] /Movies/SearchIndex ? searchString=mel , it returns a movie w...
public ActionResult SearchIndex ( string searchString ) { var movies = from m in db.Movies select m ; if ( ! String.IsNullOrEmpty ( searchString ) ) { movies = movies.Where ( s = > s.Title.Contains ( searchString ) ) ; } return View ( movies ) ; }
Why is String.Contains case-insensitive in this query ?
C#
I have a Json string : I 'm using James Newton-King 's Json.NET parser and calling : Where my classes are defined as follows : This all works , but the original list might have different JackFactions rather than B , P , N and H. Ideally what I 'd like to get is : Without changing the Json string , how can I get the Jac...
{ `` B '' : { `` JackID '' : `` 1 '' , `` Faction '' : `` B '' , `` Regard '' : `` 24 '' , `` Currency '' : `` 1340 '' , `` factionName '' : `` Buccaneer '' , `` factionKing '' : `` 22 '' , `` Tcurrency '' : `` 0 '' , `` currencyname '' : `` Pieces of Eight '' , `` textcolor '' : `` # FFFFFF '' , `` bgcolor '' : `` # 0...
Deserialize Json when number of objects is unknown
C#
I am trying to create a method for ( at runtime ) creating wrappers for delegates of all types . This to create a flexible way of injecting additional logging ( in this case ) . In this first step i tried to create a try-catch wrap around the given input-argument.I am using a generic method call CreateWrapper2 ( see be...
try { Console.WriteLine ( ... . ) ; // Here the original call Console.WriteLine ( ... . ) ; } catch ( Exception ex ) { Console.WriteLine ( ... .. ) ; } private static readonly MethodInfo ConsoleWriteLine = typeof ( Console ) .GetMethod ( `` WriteLine '' , new [ ] { typeof ( string ) , typeof ( object [ ] ) } ) ; privat...
`` variable `` of type 'System.Boolean ' referenced from scope `` , but it is not defined '' in Expression
C#
I know this code does not work ( and have no problems writing it in a way that will work ) . I was wondering how the compiler can build with out any errors . And you get run time errors if you where to run it ? ( assuming data was not null )
using System ; using System.Collections.Generic ; public class Class1 { public void Main ( ) { IEnumerable < IEnumerable < Foo > > data = null ; foreach ( Foo foo in data ) { foo.Bar ( ) ; } } } public class Foo { public void Bar ( ) { } }
Why is the C # compiler happy with double IEnumerable < T > and foreach T ?
C#
I 'm doing a component to format a list , it is an Extension , I wrote the following code , but , when in execution time , it gives me the error : Can not convert lambda expression to type 'System.Web.WebPages.HelperResult ' because it is not a delegate typeThis is the extension : View calling : I already tried to chan...
public static MvcHtmlString FormatMyList < TModel , TValue > ( this HtmlHelper < TModel > htmlHelper , IEnumerable < TValue > list , Expression < Func < TValue , System.Web.WebPages.HelperResult > > formatExp = null ) { foreach ( var item in list ) { var itemFormated = formatExp.Compile ( ) .Invoke ( item ) .ToString (...
Expression of HelperResult to format item from a list
C#
I have a collection of nullable ints . Why does compiler allows to iteration variable be of type int not int ? ? Of course I should pay attention to what I iterate through but it would be nice if compiler reprimanded me : ) Like here :
List < int ? > nullableInts = new List < int ? > { 1,2,3 , null } ; List < int > normalInts = new List < int > ( ) ; //Runtime exception when encounter null value //Why not compilation exception ? foreach ( int i in nullableInts ) { //do sth } foreach ( bool i in collection ) { // do sth } //Error 1 Can not convert typ...
Iteration variable of different type than collection ?
C#
After all the fuss about non-generic classes being obsolete ( well almost ) why are .NET collection classes still non-generic ? For instance , Control.ControlCollection does n't implement IList < T > but only IList , or FormCollection implements only upto ICollection and not ICollection < T > . Everytime I have to do s...
this.Controls.OfType < Control > ( ) ;
Why are collections classes in .NET not generic ?
C#
How flexible is DataBinding in WPF ? I am new to WPF and would like to have a clear idea . Can I Bind a string variable with a Slider value ? Does it always have to be a control ? Is it at all possible to bind a string value with a Slider control so that it updates in real time ? How far up the Logical tree does the up...
URLQuery.Append ( `` & zoom= '' + zoomFactor + `` & size=600x500 & format=jpg & sensor=false '' ) ;
How flexible is DataBinding in WPF ?
C#
I am trying to convert a 10,000 by 10,000 int array to double array with the following method ( I found in this website ) and the way I call isit gives me this error , The machine has 32GB RAM , OS is MAC OS 10.6.8
public double [ , ] intarraytodoublearray ( int [ , ] val ) { int rows= val.GetLength ( 0 ) ; int cols = val.GetLength ( 1 ) ; var ret = new double [ rows , cols ] ; for ( int i = 0 ; i < rows ; i++ ) { for ( int j = 0 ; j < cols ; j++ ) { ret [ i , j ] = ( double ) val [ i , j ] ; } } return ret ; } int bound0 = myInt...
intArray to doubleArray , Out Of Memory Exception C #
C#
I am using ArangoDB and I am querying a collection named movies . Its data structure is such that categories is a List of strings . Here is the query statement : id is passed as a param and I need to retrieve all the movies that has the category matched by the id.However , above code does n't work as result gives me AL...
public class movies { [ DocumentProperty ( Identifier = IdentifierType.Key ) ] public string Key ; public List < string > categories ; public string desc ; public string img ; public List < vod_stream > streams ; public string title ; } ; var result = db.Query < movies > ( ) .Where ( p = > p.categories.Contains ( id ) ...
Linq List Contains
C#
I 'm having an issue trying to create indexes on RavenDB 3.5When creating more than 3 indexes the application just dies , getting a Unable to connect to the remote server Status Code : ConnectFailureThe index creation code is farely straight forward : But the same happens if the IndexCreation.CreateIndexes ( typeof ( M...
private static void CreateIndexes ( IDocumentStore documentStore ) { new PurchaseOrder_QueryByExternalReference ( ) .Execute ( documentStore ) ; new SupplierDocument_QueryBySupplierName ( ) .Execute ( documentStore ) ; new ProductDocument_QueryByProductIdAndName ( ) .Execute ( documentStore ) ; new PurchaseOrderLine_Qu...
Task Canceled exception on RavenDB when creating indexes
C#
Unfortunatly , i ca n't find the original project which led me to this question . That would have perhaps given this question a bit more context.EDIT : I found the original project i 've seen this in : http : //mews.codeplex.com/SourceControl/changeset/view/63120 # 1054567 with a concrete implementation at : http : //m...
abstract class AbstractClass { public virtual int ConvertNumber ( string number ) { string preparedNumber = Prepare ( number ) ; int result = StringToInt32 ( number ) ; return result ; } protected abstract string Prepare ( string number ) ; protected virtual int StringToInt32 ( string number ) { return Convert.ToInt32 ...
Abstract class inheriting the most derived type
C#
I have been using javascript and I made a lot of use of functions inside of functions . I tried this in C # but it seems they do n't exist . If I have the following : How can I code a method d ( ) that can only be calledfrom inside the method the method abc ( ) ?
public abc ( ) { }
Does C # have a concept of methods inside of methods ?
C#
The following Delphi program calls method upon nil reference and runs fine . However , in a structurally similar C # program , System.NullReferenceException will be raised , which seems to be the right thing to do.Because TObject.Free uses such style , it seems to be `` supported '' to call method on nil reference in D...
program Project1 ; { $ APPTYPE CONSOLE } type TX = class function Str : string ; end ; function TX.Str : string ; begin if Self = nil then begin Result : = 'nil ' end else begin Result : = 'not nil ' end ; end ; begin Writeln ( TX ( nil ) .Str ) ; Readln ; end . namespace ConsoleApplication1 { class TX { public string ...
Is it `` supported '' to call method on nil reference in Delphi ?
C#
In wpf , I have a textbox , the content of it coming from a txt file.in code behine it looks like : The thing is that the txt file content is changing during the runtime , is it possible to be synchronized with those changes ? I mean that the textbox content would be change if the txt file is changed . if It 's possibl...
public MyWindow ( ) { InitializeComponent ( ) ; ReadFromTxt ( ) ; } void Refresh ( object sender , RoutedEventArgs e ) { ReadFromTxt ( ) ; } void ReadFromTxt ( ) { string [ ] lines = System.IO.File.ReadAllLines ( @ '' D : \Log.txt '' ) ; foreach ( string line in lines ) { MyTextBox.AppendText ( line + Environment.NewLi...
Update textbox from txt file during runtime without clicking `` refresh ''
C#
It is important to me that my syntax does not make other developers confused.In this example , I need to know if a parameter is a certain type . I have hit this before ; what 's the most elegant , clear approach to test `` not is '' ? Method 1 : Method 2 : Method 3 : Method 4 : [ EDIT ] Method 5 : Which is the most str...
void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { if ( ! ( e.parameter is MyClass ) ) { /* do something */ } } void MyBinding_Executed ( object sender , ExecutedRoutedEventArgs e ) { if ( e.parameter is MyClass ) { } else { /* do something */ } } void MyBinding_Executed ( object sender , ExecutedR...
Best `` not is '' syntax in C #
C#
I 'm trying to debug a crash that happens in our application during garbage collection and looking at the code I found two related pieces of code that , if not the cause of the problem , are at least suspicious to me : Note that from my understanding the struct is actually at least 98 bytes in size but is declared as 9...
[ StructLayout ( LayoutKind.Sequential , Size = 96 , CharSet = CharSet.Ansi , Pack=1 ) ] public class MilbusData { public System.Int64 TimeStamp ; public System.Int16 Lane ; public System.Int16 TerminalAddress ; public System.Int16 TerminalSubAddress ; public System.Int16 Direction ; public System.Int64 ErrorCounter ; ...
Can this code cause a managed heap corruption ?
C#
After reading this question ASP.NET MVC : Nesting ViewModels within each other , antipattern or no ? and Derick Bailey 's comment i think the `` consider what your viewmodel would look like as xml or json '' bit is probably the most important point , here . i often use that perspective to help me understand what the vi...
public class SearchViewModel { public int ? page { get ; set ; } public int ? size { get ; set ; } //Land Related search criteria [ IgnoreDataMember ] public SelectList LocationSelection { get ; set ; }
Do SelectLists belong in viewModels ?
C#
I understand how to get the names of parameters passed to a method , but let 's say I have a method declaration as follows : and I want to use object/property names in my template for substitution with real property values in any of the objects in my ` objects ' parameter . Let 's then say I call this method with : I w...
static void ParamsTest ( string template , params object [ ] objects ) ParamsTest ( `` Congrats '' , customer , purchase ) ;
How can I pass a variable number of named parameters to a method ?
C#
I have this code : The variable p is always null . How is this posible ? Here is a print screen of what I am talking about : I also try with immediate windows I got this : p CAN NOT BE NULL since im creating a new instance of it while all of its properties are not null . I tried clean the project , restart windows , op...
public ObjectModel.Path GetPath ( int pathid ) { var path = this.DbContext.Paths.Find ( pathid ) ; var app = GetApplicationById ( path.ApplicationId.GetValueOrDefault ( ) ) ; var p = new Path { ApplicationId = path.ApplicationId , Id = path.Id , Password = path.Password , UserName = path.UserName , LocalUrl = string.Is...
new operator returning null - C #
C#
I 'm attempting to convert the following method ( simplified example ) to be asynchronous , as the cacheMissResolver call may be expensive in terms of time ( database lookup , network call ) : There are plenty of materials on-line about consuming async methods , but the advice I have found on producing them seems less ...
// Synchronous versionpublic class ThingCache { private static readonly object _lockObj ; // ... other stuff public Thing Get ( string key , Func < Thing > cacheMissResolver ) { if ( cache.Contains ( key ) ) return cache [ key ] ; Thing item ; lock ( _lockObj ) { if ( cache.Contains ( key ) ) return cache [ key ] ; ite...
Correct way to convert method to async in C # ?
C#
I just started using mock objects ( using Java 's mockito ) in my tests recently . Needless to say , they simplified the set-up part of the tests , and along with Dependency Injection , I would argue it made the code even more robust.However , I have found myself tripping in testing against implementation rather than s...
Element e = mock ( Element.class ) ; when ( e.getAttribute ( `` attribute '' ) ) .thenReturn ( `` what '' ) ; when ( e.getAttribute ( `` other '' ) ) .thenReturn ( null ) ; assertEquals ( attributeWithDefault ( e , `` attribute '' , `` default '' ) , `` what '' ) ; assertEquals ( attributeWithDefault ( e , `` other '' ...
Use of Mocks in Tests
C#
The requirement used to be that the window is CenterScreen but the client has recently asked that the window is now slightly to the right of its current position.The current definition of the window is : I was hoping that doing the following would work : But the window is still in the same position when it appears on s...
public MyWindow ( ) { InitializeComponent ( ) ; // change the position after the component is initialized this.Left = this.Left + this.Width ; }
Is it possible to offset the window position by a value when WindowStartupLocation= '' CenterScreen '' ?
C#
I add a MenuStrip to my form and I would like to add other controls below it like usual Point ( 0 , 0 ) is the top left corner of empty form space . After I add the menu to my form and add more controls they overlap each other . So I want to take away some height of the client rect for the menu and a button with Locati...
MenuStrip menu = new MenuStrip ( ) ; menu.Items.Add ( `` File '' ) ; menu.AutoSize = false ; menu.Height = 50 ; menu.Dock = DockStyle.Top ; MainMenuStrip = menu ; Controls.Add ( menu ) ; Button b = new Button ( ) ; b.Text = `` hello world '' ; b.SetBounds ( 0 , 25 , 128 , 50 ) ; Controls.Add ( b ) ; Menu = new MainMenu...
How to take away vertical space for programmatically added menu ?
C#
Given that all controls in a WebForm are destroyed ( by my understanding ) at the end of each postback do you need to `` unwire '' any event handlers you may have wired up ? ( Assuming you want to stop handling the events and allow GC ) So for example :
public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load ( object sender , EventArgs e ) { //Do I need to remove this handler ? btnSubmit.ServerClick += btnSubmit_ServerClick ; } }
Do you need to `` unwire '' event handlers in ASP.NET webforms
C#
In .NET Thread class has static method Yield.I see that method in coreclr implementation of Thread.But documentation does n't contain that Method description.Also .NET CLI ( dotnet build ) cant compile code with that method invocation.Why ? updruntime : 1.0.0-rc1-update1 coreclr x64 darwin project.jsonupd2I 'm not goin...
{ `` version '' : `` 1.0.0-* '' , `` compilationOptions '' : { `` emitEntryPoint '' : true } , `` dependencies '' : { `` NETStandard.Library '' : `` 1.0.0-rc2-* '' , `` System.Threading '' : `` 4.0.11-rc3-* '' } , `` frameworks '' : { `` dnxcore50 '' : { } } }
Thread.Yield ( ) in coreclr
C#
I want to do the followingHowever I ca n't because you ca n't have static abstract members.I understand why I ca n't do this - any recommendations for a design that will achieve much the same result ? ( For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a...
public abstract class MyAbstractClass { public static abstract int MagicId { get ; } public static void DoSomeMagic ( ) { // Need to get the MagicId value defined in the concrete implementation } } public class MyConcreteClass : MyAbstractClass { public static override int MagicId { get { return 123 ; } } }
C # class design - what can I use instead of `` static abstract '' ?
C#
i was wondering if there is a way to restrict a value in construction . Here is my code : and when i make a new Student i want to restrict the Grade between > = 2.00 and < = 6.00 , like compile error or excepion on runtime . Is there a way ? ( Do n't worry about other fields FirstName , and LastName )
class Student : Human { private double Grade ; public Student ( string FirstName , string LastName , double Grade ) : base ( FirstName , LastName ) { this.FirstName = FirstName ; this.LastName = LastName ; this.Grade = Grade ; } }
Constructor restrictions
C#
Sometimes when using the miniprofiler , there 's just some requests that you does n't care about . In my case I do n't care much about signalr , umbraco pings , and some requests made when I wan na know if the user is idle or not.To avoid the miniprofiler using energy on ( and providing results for ) these types of req...
protected void Application_BeginRequest ( ) { if ( ( Request.IsLocal || Request.UserHostAddress == `` 37.49.143.197 '' ) & & ! ( Request.RawUrl.Contains ( `` /signalr/ '' ) || Request.RawUrl.Contains ( `` /idle/verify '' ) || Request.RawUrl.Contains ( `` /idle/interaction '' ) || Request.RawUrl.Contains ( `` /umbraco/p...
How to remove specific URL 's from profiling when using MiniProfiler
C#
I have the following code in my C # application.ReSharper 7.1.1 is highlighting the fact that the DateTimeFormatInfo.CurrentInfo could cause a null reference exception.Under what circumstances would this occur ? Or is this just a mistake on ReSharper 's part believing that any object whose property you access should be...
DateTimeFormatInfo.CurrentInfo.DayNames
How can DateTimeFormatInfo.CurrentInfo be null
C#
I think this looks like a bug in the C # compiler.Consider this code ( inside a method ) : It compiles with no errors ( or warnings ) . Seems like a bug . When run , prints 0 on console.Then without the const , the code : When this is run , it correctly results in an OverflowException being thrown.The C # Language Spec...
const long dividend = long.MinValue ; const long divisor = -1L ; Console.WriteLine ( dividend % divisor ) ; long dividend = long.MinValue ; long divisor = -1L ; Console.WriteLine ( dividend % divisor ) ;
Why does the compiler evaluate remainder MinValue % -1 different than runtime ?
C#
I 'm currently migrating a Windows Azure application to Amazon AWS . In Windows Azure we used Lokad.Clout to get strongly typed access to Azure Blob Storage . For instance like this : For more detailed examples see their wiki.In the AWS SDK for .NET you do n't get strongly typed access . For instance in order to achive...
foreach ( var name in storage.List ( CustomerBlobName.Prefix ( country ) ) { var customer = storage.GetBlob ( name ) ; // strong type , no cast ! // do something with 'customer ' , snipped }
Strongly typed access to Amazon S3 using C #
C#
I 'm using Rob Conery 's Massive for database access . I want to wrap a transaction around a couple of inserts but the second insert uses the identity returned from the first insert . It 's not obvious to me how to do this in a transaction . Some assistance would be appreciated .
var commandList = new List < DbCommand > { contactTbl.CreateInsertCommand ( new { newContact.Name , newContact.Contact , newContact.Phone , newContact.ForceChargeThreshold , newContact.MeterReadingMethodId , LastModifiedBy = userId , LastModifiedDate = modifiedDate , } ) , branchContactTbl.CreateInsertCommand ( new { n...
Want to use identity returned from insert in subsequent insert in a transaction
C#
My question is different with the one identified . Obviously I have called `` BeginErrorReadLine '' method ( I mark it in the code below ) .I want to parse the result produced by HandleCommand lineWhen run in a command line environment , it will output something like : > handle64 -p [ PID ] Nthandle v4.11 - Handle view...
Stream streamOut , streamErr ; var p = Process.Start ( new ProcessStartInfo { FileName = `` handle64.exe '' , Arguments = `` -p [ PID ] '' , CreateNoWindow = true , UseShellExecute = false , RedirectStandardOutput = true , RedirectStandardError = true , } ) ; p.OutputDataReceived += ( sender , e ) = > { streamOut.Write...
When run a program in C # , all the messages go to the standard output , but the standard error contains nothing
C#
Is there anyway to know this ? I found one post that asked a very similar question at How to check if an object is nullable ? The answer explains how to determine if an object is nullable if there is access to a Generic Type Parameter . This is accomplished by using Nullabe.GetUnderlyingType ( typeof ( T ) ) . However ...
void Main ( ) { Console.WriteLine ( Code.IsNullableStruct ( Code.BoxedNullable ) ) ; } public static class Code { private static readonly int ? _nullableInteger = 43 ; public static bool IsNullableStruct ( object obj ) { if ( obj == null ) throw new ArgumentNullException ( `` obj '' ) ; if ( ! obj.GetType ( ) .IsValueT...
How to determine if a non-null object is a Nullable struct ?
C#
Is there a way how to decorate property of datacontract object , so the generated xsd will contain MaxLenght restriction ? E.g . I can imagine I need something like this : and something like this should be included in the output from xsd.exe : Is there a way to do it ? To define the restrictions in C # class in such wa...
[ XmlElement ( MaxLengthAttribute = `` 12 '' ) ] public string Name ; < xs : element name= '' name '' > < xs : simpleType > < xs : restriction base= '' xs : string '' > < xs : maxLength value = `` 12 '' / > < /xs : restriction > < /xs : simpleType > < /xs : element >
How to generate XSD from Class with restrictions
C#
I want to do a foreach loop while taking out members of that foreach loop , but that 's throwing errors . My only idea is to create another list inside of this loop to find which Slices to remove , and loop through the new list to remove items from Pizza .
foreach ( var Slice in Pizza ) { if ( Slice.Flavor == `` Sausage '' ) { Me.Eat ( Slice ) ; //This removes an item from the list : `` Pizza '' } }
Going Through A Foreach When It Can Get Modified ?
C#
Lets say we have the folowing code.What is actually happening ? Cast the obj to a string and then calls the ToString Method ? Calls the ToString method on obj which is the override of string without casting ? Something else ? Witch one is better to do ? var bar = obj.ToString ( ) ; var bar = ( string ) obj ;
var foo = `` I am a string '' ; Object obj = foo ; var bar = obj.ToString ( ) ;
What happens when calling Object.ToString when the actual type is String
C#
In C # I 've enabled tracing and a net tracing source.But longer messages get truncated ( long like 12Kb/30 lines , not long like 1GB ! ) so I end up in a situation where only part of web reqiest headers are logged.How to fix that ? Or do you know a book or some resource that explains .Net tracing and debugging in grea...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5 '' / > < /startup > < system.diagnostics > < sources > < source name= '' System.Net '' tracemode= '' includehex '' maxdatasize= '' 1024 '' > < listeners > < add ...
C # Tracing truncate long messages
C#
This is a very specific problem . Not quite sure how to even word it . Basically I am implementing the unit of work and repository pattern , I have a dynamic object that I convert to an int , but if I use var it will throw an exception when trying to call the method.I tried to remove all the trivial variables to this p...
class BlackMagic { static void Main ( string [ ] args ) { dynamic obj = new ExpandoObject ( ) ; obj.I = 69 ; UnitOfWork uow = new UnitOfWork ( ) ; int i1 = Convert.ToInt32 ( obj.I ) ; var i2 = Convert.ToInt32 ( obj.I ) ; if ( i1.Equals ( i2 ) ) { uow.TacoRepo.DoStuff ( i1 ) ; // Works fine uow.TacoRepo.DoStuff ( i2 ) ;...
Casting Dynamic Object and Passing Into UnitOfWork and Repository Pattern . Throws Exception
C#
I 'm building a generic flat file reader which looks something like this.It could be consumed like so.Here are the classes used.Is there a way how I could remove or encapsulate that generic type information in the GenericReader ? I 'm looking for an extra pair of eyes to show me something what I 've been missing . We a...
public class GenericReader < TComposite , THeader , TData , TTrailer > where TComposite : GenericComposite < THeader , TData , TTrailer > , new ( ) where THeader : new ( ) where TData : new ( ) where TTrailer : new ( ) { public TComposite Read ( ) { var composite = new TComposite ( ) ; composite.Header = new THeader ( ...
Can I somehow tidy up this ( overuse ? ) of generics ?
C#
This is my mapping class : This works fine for the Table ( [ mySchema ] . [ MyTable ] ) in my first database.But this table ( `` MyTable '' ) exists in ( actually a lot of ) different databases , but for any reason the schema is always named different ( this I dont have any control of ) : So in the Database `` OtherDB ...
class MyTableMap : ClassMap < MyTable > { public MyTableMap ( ) { Schema ( `` mySchema '' ) ; Id ( x = > x.id ) ; Map ( x = > x.SomeString ) ; } }
Fluent nHibernate : Use the same mapping files for tables with the same structure in different schemas
C#
I 'm using this code to print a PDF file on a local printer with C # within a windows service.Everything works fine when I set a user to run the windows service.Whenever I run this code under the LocalSystem credential , I get the error `` there are no application associated to this operation '' which usually indicates...
Process process = new Process ( ) ; PrinterSettings printerSettings = new PrinterSettings ( ) ; if ( ! string.IsNullOrWhiteSpace ( basePrint ) ) printerSettings.PrinterName = basePrint ; process.StartInfo.FileName = fileName ; process.StartInfo.Verb = `` printto '' ; process.StartInfo.Arguments = `` \ '' '' + printerSe...
PDF Print Through Windows Service with C #
C#
What is the order of implicit conversions done in Console.WriteLine ( x ) when x is an object from user-defined class : Why I get 42 , and not 3.14 or `` 12 '' ? Why I can not add an additional implicit conversion to string /there is Compiler error on the ambiguity between CW ( int ) and CW ( string ) / : I know I shou...
class Vector { public int x = 12 ; public static implicit operator double ( Vector v1 ) { return 3.14 ; } public static implicit operator int ( Vector v1 ) { return 42 ; } public override string ToString ( ) { return this.x.ToString ( ) ; } } static void Main ( string [ ] args ) { Vector v11 = new Vector ( ) ; Console....
Order of implicit conversions in c #
C#
I am having problems figuring out the Linq syntax for a left outer join within multiple joins . I want to do a left join on RunLogEntry Table so I get records which match from this table as well as all of the Service Entries . Can some one please correct my snytax ?
var list = ( from se in db.ServiceEntry join u in db.User on se.TechnicianID equals u.ID join s in db.System1 on se.SystemID equals s.ID join r in db.RunLogEntry on se.RunLogEntryID equals r.ID where se.ClosedDate.HasValue == false where se.ClosedDate.HasValue == false & & se.Reconciled == false orderby se.ID descendin...
Linq left join syntax correction needed
C#
As a newcomer to TDD I 'm stuggling with writing unit tests that deal with collections . For example at the moment I 'm trying to come up with some test scearios to essentially test the following methodWhere the method should return the index of the first item in the list list that matches the predicate predicate . So ...
int Find ( List < T > list , Predicate < T > predicate ) ;
TDD - writing tests for a method that iterates / works with collections
C#
I have a generic methodThis method is used quite a lot throughout the code , and I want to find where it is used with T being a specific type.I can text-search for but most often the type argument has been omitted from the call ( inferred ) . Is there any way I can find these method invocations in VS2010 or perhaps ReS...
public void Foo < T > ( T arg ) where T : ISomeInterface `` Foo < TheType > ( ``
How can I find generic invocations with a specific type argument in my source ?
C#
How do I do that ? And , what do I take on the left side of the assignment expression , assuming this is C # 2.0 . I do n't have the var keyword .
sTypeName = ... //do some string stuff here to get the name of the type/*The Assembly.CreateInstance function returns a typeof System.object . I want to type cast it to the type whose name is sTypeName.assembly.CreateInstance ( sTypeName ) So , in effect I want to do something like : */assembly.CreateInstance ( sTypeNa...
Typecast to a type from just the string representation of the type name
C#
We 're running our Win8 Metro unit tests from powershell using vstest.console.exe , which is included with Visual Studio 2012 . The way the process uses the unit test appx-package created by msbuild , and runs it : \install\location\vstest.console.exe path\to\unittest.appx /InIsolationFrom time to time the execution fa...
Starting test execution , please wait ... Error : Installation of package '\absolute\path\to\unittest.appx ' failed with Error : ( 0x5B4 ) Operation timed out . Unable to install Windows app package in 15 sec.For more details look into Event Viewer under Applications and Services Logs - > Microsoft - > Windows - > AppX...
Windows 8 Appx installation timeout during unit test execution
C#
I have written the following SQL CLR function in order to hash string values larger then 8000 bytes ( the limit of input value of the T-SQL built-it HASHBYTES function ) : It is working fine for Latin strings . For example , the following hashes are the same : The issue is it is not working with Cyrillic strings . For ...
[ SqlFunction ( DataAccess = DataAccessKind.None , IsDeterministic = true ) ] public static SqlBinary HashBytes ( SqlString algorithm , SqlString value ) { HashAlgorithm algorithmType = HashAlgorithm.Create ( algorithm.Value ) ; if ( algorithmType == null || value.IsNull ) { return new SqlBinary ( ) ; } else { byte [ ]...
SQL CLR function based on .net ComputeHash is not working with Cyrrilic
C#
I understand this is a beta ( just checked the new version of EF 4.3 and it does the same thing ) release and some functionality may be missing , but i haven ` t seen anything to explain why ... ... no longer creates a column of type xml when using EF 4.3 ( column is created as nvarchar ( max ) ) , I have tried EF 4.2 ...
[ Column ( TypeName = `` xml '' ) ] public string SomeProperty { get ; set ; }
Entity Framework 4.3 beta [ Column ( TypeName ) ] issue , can not create columns of type xml
C#
Here are two C # classes ... ... and a list of data ( filled somewhere ) ... ... and then this LINQ query : I do not understand the query : What means the `` Any '' function and what does the `` = > '' operator do ? Can someone explain me what 's going on in this code ? Thanks !
public class Address { public string Country ; public string City ; } public class Traveller { public string Name ; public List < Address > TravelRoute ; } List < Traveller > Travellers ; var result = from t in Travellers where t.TravelRoute.Any ( a = > a.Country == `` F '' ) select t ; foreach ( var t in result ) Syst...
What does this LINQ query do ?
C#
I feel like I played buzzword bingo with the title . Here 's a concise example of what I 'm asking . Let 's say I have some inheritance hierarchy for some entities.Now let 's say I have a generic interface for a service with a method that uses the base class : I have some concrete implementations : Assume I 've registe...
class BaseEntity { ... } class ChildAEntity : BaseEntity { ... } class GrandChildAEntity : ChildAEntity { ... } class ChildBEntity : BaseEntity { ... } interface IEntityService < T > where T : BaseEntity { void DoSomething ( BaseEntity entity ) ... } class BaseEntityService : IEntityService < BaseEntity > { ... } class...
Mechanism for Dependency Injection to Provide the Most Specific Implementation of a Generic Service Interface
C#
If the data is on a single line the index=int.Parse ( logDataReader.ReadElementContentAsString ( ) ) ; andvalue=double.Parse ( logDataReader.ReadElementContentAsString ( ) , cause the cursor to move forward . If I take those calls out I see it loop 6 times in debug.In the following only 3 < data > are read ( and they a...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < log > < logData id= '' Alpha '' > < data > < index > 100 < /index > < value > 150 < /value > < /data > < data > < index > 110 < /index > < value > 750 < /value > < /data > < data > < index > 120 < /index > < value > 750 < /value > < /data > < data > < index > 130 <...
XmlReader behaves different with line breaks
C#
I have a Windows store app that draws an image under the system 's cursor . I capture all the cursor movements using : And this is working fine if I use my mouse to move the cursor.However , I have another application - a desktop application - , that changes the position of the system 's cursor . I 'm using this method...
var window = Window.Current .Content ; window .AddHandler ( PointerMovedEvent , new PointerEventHandler ( window_PointerMoved ) , true ) ; [ DllImport ( `` user32 '' ) ] private static extern int SetCursorPos ( int x , int y ) ;
PointerMoved event not firing
C#
So I use Visual Studio 2017 and everything worked ok . But then I updated to 15.6.0 and suddenly nothing is working anymore.All the references like Systme . * or Microsoft . * are with a yellow warning sign ... At every project - even new ones- I keep getting the same type of erros after ( re ) building : I have tried ...
The `` ResolveAssemblyReference '' task could not be initialized with its input parametersThe `` ResolveAssemblyReference '' task could not be initialized with its input parameters The `` FindDependenciesOfExternallyResolvedReferences '' parameter is not supported by the `` ResolveAssemblyReference '' task . Verify the...
Can not find reference System
C#
I 'm developing an assistive technology application ( in C # ) that overlays information on top of the currently open window . It detects clickable elements , and labels them.To do this , I 'm currently creating a borderless , transparent window with TopMost set to `` true '' , and drawing the labels on that . This mea...
public partial class OverlayForm : Form { public OverlayForm ( ) { } protected override void OnPaint ( PaintEventArgs eventArgs ) { base.OnPaint ( eventArgs ) ; Graphics graphics = eventArgs.Graphics ; Brush brush = new SolidBrush ( this.labelColor ) ; foreach ( ClickableElement element in this.elements ) { Region curr...
How to draw on top of the right-click menu in .NET/C # ?
C#
Otherwise I always need to check if the value is null before performing any other validations . It 's kinda annoying if I have many custom checks that are using Must ( ) .I placed NotEmpty ( ) at the very top of it therefore it already returns false , is it possible to stop there ? Example
RuleFor ( x = > x.Name ) .NotEmpty ( ) // Can we not even continue if this fails ? .Length ( 2 , 32 ) .Must ( x = > { var reserved = new [ ] { `` id '' , `` email '' , `` passwordhash '' , `` passwordsalt '' , `` description '' } ; return ! reserved.Contains ( x.ToLowerInvariant ( ) ) ; // Exception , x is null } ) ;
Is it possible to stop checking further validations when the first one fails ?
C#
I have a partial class using an interface because I can ’ t inherit what was an original abstract class due to the other partial class being auto-generated from Entity Framework 4 and therefore already inheriting ObjectContext.I have the following for my partial class : Here ’ s the interface : And the implementation :...
namespace Model { using Microsoft.Practices.EnterpriseLibrary.Validation ; using Microsoft.Practices.EnterpriseLibrary.Validation.Validators ; using Utilities.BusinessRules ; using Utilities.BusinessRules.Rules ; [ HasSelfValidation ] public partial class MyObject : IBusinessObject { private readonly IBusinessObject bu...
Inherited C # Class Losing `` Reference ''
C#
I have several c # structs that give shape to structures in a very large data file . These structs interpret bits in the file 's data words , and convert them to first-class properties . Here is an example of one : I need to do two things , which I think are related . The first is to have the ability to validate the en...
[ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct TimeF1_MsgDayFmt { // Time Data Words public UInt16 TDW1 ; public UInt16 TDW2 ; public UInt16 TDW3 ; /// < summary > /// Tens of milliseconds /// < /summary > public UInt16 Tmn { // Bits.Get is just a helper method in a static class get { return Bits.G...
Auditing and validating changes to C # class and structure properties in a high-performance way
C#
I 've been battling with OAuth and Twitter for 2 weeks now trying to implement it . After many rewrites of my code I 've finally got a library which performs the request as it should be based on the 1.0 spec . I 've verified it by using this verifier on Google Code , and this verifier from Hueniverse.My version , the G...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < hash > < request > /1/statuses/update.xml < /request > < error > Could not authenticate with OAuth. < /error > < /hash >
Is Twitter implemeting OAuth off spec ? ( C # )
C#
I have an Angular front-end app and an ASP.NET Core back-end app . Everything was fine until I decided to migrate from ASP.NET Core 2.2 to 3.0-preview-9.For example , I have a DTO class : And an example JSON request : Before migration , this was a valid request because 123 was parsed as a decimal . But now , after migr...
public class DutyRateDto { public string Code { get ; set ; } public string Name { get ; set ; } public decimal Rate { get ; set ; } } { `` name '' : '' F '' , `` code '' : '' F '' , `` rate '' : '' 123 '' } { `` type '' : `` https : //tools.ietf.org/html/rfc7231 # section-6.5.1 '' , `` title '' : `` One or more valida...
Model binding stopped working after migrating from .NET Core 2.2 to 3.0-preview-9
C#
I wanted to get the projected Balance for the next 12 months from the current month and if the Balance is empty for that month it will get the value from the nearest Month with a Balance of greater than 0.This is what I have tried so far . This would result to : Is it possible to get a result somewhat like this : I ca ...
void Main ( ) { var firstDayMonth = new DateTime ( DateTime.Now.Year , DateTime.Now.Month , 1 ) ; var months = Enumerable.Range ( 0 , 12 ) .Select ( m = > new { Month = firstDayMonth.AddMonths ( m ) } ) ; List < SomeDate > SomeDates = new List < SomeDate > ( ) { new SomeDate { Id = 1 , Month = firstDayMonth.AddMonths (...
How to get the next 12 months with empty months
C#
I have an application that has been working for a while . I tried running it with VS2013 and it hangs on a line where it tries to initialize a DataCacheFactory object . The same code works fine with VS2010 and VS2012.No errors are generated . The code just hangs on the line factory = new DataCacheFactory ( ) . The AppF...
private static DataCacheFactory GetDataCacheFactory ( ) { if ( factory == null ) { lock ( lockObject ) { if ( factory == null ) { factory = new DataCacheFactory ( ) ; //VS2013 hangs on this line } } } return factory ; }
AppFabric DataCacheFactory ( ) initialization hangs in VS2013 , works fine in VS2010 and VS2012
C#
I am trying to figure out how to create an asynchronous call from Application_Error Method in MVC.I have an e-mail dll that I have written which sends out an e-mail via asynchronous call using Smtp Client.The problem is that when I call SendEmail method in my dll I have conflict of needing to await for the call . Now i...
protected async void Application_Error ( ) { var await emailService.SendEmail ( `` Hello World '' ) ; }
Asynchronous call from Application_Error ( )
C#
Browsing some forum I came across this answer in which the answerer refers to the following as the native call stackWhat exactly is the native call stack with regards to the CLR ( here we are looking at the CLR invoking the Main method I think ) and how can I view and come to understand said native call stack on my loc...
00000000 ` 0014ea10 00000642 ` 7f67d4a2 0x642 ` 8015014200000000 ` 0014ea90 00000642 ` 7f5108f5 mscorwks ! CallDescrWorker+0x82 00000000 ` 0014eae0 00000642 ` 7f522ff6 mscorwks ! CallDescrWorkerWithHandler+0xe500000000 ` 0014eb80 00000642 ` 7f49a94b mscorwks ! MethodDesc : :CallDescr+0x306 00000000 ` 0014edb0 00000642 ...
What exactly is the native call stack with regards to the CLR ?