lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Current ASAX code ( simplified ) : QuestionIs it safe to pull routes from the DB at this point ? For example : Additional InformationThis question is born out of a lack of knowledge concerning routing as well as a general unfamiliarity with global.asax . In the past , I 've only used global.asax for extremely simple ta...
void Application_Start ( object sender , EventArgs e ) { // Enable routing RegisterRoutes ( RouteTable.Routes ) ; } void RegisterRoutes ( RouteCollection routes ) { routes.Add ( `` ContactUsRoute '' , new Route ( `` contact-us '' , new PageRouteHandler ( `` ~/contactus.aspx '' ) ) ) ; } void RegisterRoutes ( RouteColle...
Creating routes from DB records
C#
I 'm using JSON.NET to deserialize a JSON file to a dynamic object in C # .Inside a method , I would like to pass in a string and refer to that specified attribute in the dynamic object.For example : Where File is the dynamic object , and Key is the string that gets passed in . Say I 'd like to pass in the key `` foo '...
public void Update ( string Key , string Value ) { File.Key = Value ; } { `` Key '' : '' bar '' } { `` foo '' : '' bar '' }
Referring to dynamic members of C # 'dynamic ' object
C#
I am trying to convert a C # Dependency Property that limits the maximum length of text entered into a ComboBox to F # . The program is a MVVM program that uses F # for the model and viewmodel , and C # for the view . the working C # code is this : The F # code is this : The problem I am having is that the XAML error I...
public class myComboBoxProperties { public static int GetMaxLength ( DependencyObject obj ) { return ( int ) obj.GetValue ( MaxLengthProperty ) ; } public static void SetMaxLength ( DependencyObject obj , int value ) { obj.SetValue ( MaxLengthProperty , value ) ; } // Using a DependencyProperty as the backing store for...
Dependency Property in F # Default Value does not match
C#
Suppose I do something like Does MyList.OrderBy ( x = > x.prop1 ) return the filtered list , and then does it further filter that list by ThenBy ( x = > x.prop2 ) ? In other words , is it equivalent to ? ? ? Because obviously it 's possible to optimize this by running a sorting algorithm with a comparator : If it does ...
var Ordered = MyList.OrderBy ( x = > x.prop1 ) .ThenBy ( x = > x.prop2 ) ; var OrderedByProp1 = MyList.OrderBy ( x = > x.prop1 ) ; var Ordered = OrderedByProp1.OrderBy ( x = > x.prop2 ) ; var Ordered = MyList.Sort ( ( x , y ) = > x.prop1 ! = y.prop1 ? x.prop1 < y.prop1 : ( x.prop2 < y.prop2 ) ) ;
Does LINQ know how to optimize `` queries '' ?
C#
I have a large array of primitive value-types . The array is in fact one dimentional , but logically represents a 2-dimensional field . As you read from left to right , the values need to become ( the original value of the current cell ) + ( the result calculated in the cell to the left ) . Obviously with the exception...
0 0 1 0 02 0 0 0 30 4 1 1 00 1 0 4 1 0 0 1 1 12 2 2 2 50 4 5 6 60 1 1 5 6
Segmented Aggregation within an Array
C#
I have this kind of code : Foo is a base class and therefor other classes might inherit from it.I would like the OnBar event to always be fired when Bar ( ) is called even if it 's not called explicitly inside Bar.How can it be done ?
public class Foo { public SomeHandler OnBar ; public virtual void Bar ( ) { } }
How to invoke an event automatically when a function is called ?
C#
I 'm checking the sort parameter and building a bunch of if statements : How do I make this better ?
if ( sortDirection == `` ASC '' ) { if ( sortBy == `` Id '' ) return customerList.OrderBy ( x = > x.Id ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` FirstName '' ) return customerList.OrderBy ( x = > x.FirstName ) .Skip ( startIndex ) .Take ( pageSize ) .ToList ( ) ; if ( sortBy == `` City '...
How can I improve this sorting code ?
C#
We have created a lot of NuGet packages . One of them is a tool , and it contains a special compiler and it is installed like a dotnet tool . The name of the command is `` PolyGen '' .We used a similar mechanism to what Grpc.Tools uses , that means we have defined .targets file inside our NugetPackage . And it works we...
Executing nuget actions took 181,36 ms
Execute an action after my nuget package is installed
C#
I have the need to construct a LINQ To SQL statement at runtime based on input from a user and I ca n't seem to figure out how to dynamically build the WHERE clause.I have no problem with the following : But what I really need is to make the entire WHERE clause dynamic . This way I can add multiple conditions at runtim...
string Filters = `` < value > FOO < /value > '' ; Where ( `` FormattedMessage.Contains ( @ 0 ) '' , Filters ) foreach ( Filter filter in filterlist ) { whereclause = whereclause + `` & & formattedmessage.contains ( filter ) '' ; }
How dynamic can I make my LINQ To SQL Statements ?
C#
I have a list of work items . Each work item has a start and an end time.So , basically it looks like this : Now I want to get the total time that was worked . Again , basically this is easy : It 's just the sum.But now it gets difficult : How do I calculcate this sum if I want to extract parallel times ? E.g. , is 6.5...
List < Work > works = new List < Work > ( ) ; works.Add ( new Work ( new DateTime ( 2013 , 4 , 30 , 9 , 0 , 0 ) , new DateTime ( 2013 , 4 , 30 , 11 , 0 , 0 ) ) ; 09:00-11:00 = > 2 hours13:00-17:00 = > 4 hours -- -- 06:00 hours 09:00-11:00 = > 2 hours10:00-11:30 = > 1.5 hours13:00-17:00 = > 4 hours -- -- 06:30 hours
Get breaks from a list of times
C#
I 'm a bit of a novice with Reflection . I 'm hoping that it 's possible to do what I 'd like it to . I 've been working through ProjectEuler to learn the language , and I have a base class called Problem . Every individual PE problem is a separate class , i.e . Problem16 . To run my calculations , I use the following ...
using System ; using Euler.Problems ; using Euler.Library ; namespace Euler { static class Program { [ STAThread ] static void Main ( ) { Problem prob = new Problem27 ( ) ; } } } for ( int i = 1 ; i < = 50 ; i++ ) { string statement = `` Problem prob = new Problem '' + i + `` ( ) ; '' ; // Execute statement }
How can I use reflection or alternative to create function calls programatically ?
C#
I 'm getting a null exception , but the field was initialized as an empty list . So how could it be null ? The error occurs on the second line in this method ( on _hydratedProperties ) : And this is how the field is declared : This is how it 's set : This is the full class ( with the comments and non-relevant parts rem...
protected virtual void NotifyPropertyChanged < T > ( Expression < Func < T > > expression ) { string propertyName = GetPropertyName ( expression ) ; if ( ! this._hydratedProperties.Contains ( propertyName ) ) { this._hydratedProperties.Add ( propertyName ) ; } } public abstract class EntityBase < TSubclass > : INotifyP...
How is this field null ?
C#
According to https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods It is possible to explicitly invoke an interface base implementation with the following syntax.But this does n't seem to be implemented yet.Is there a workaround ( e.g reflection ) to achieve ...
base ( IInterfaceType ) .Method ( ) ; interface IA { void M ( ) { Console.WriteLine ( `` IA.M '' ) ; } } interface IB : IA { void IA.M ( ) { Console.WriteLine ( `` IB.M '' ) ; } } interface IC : IA { void IA.M ( ) { Console.WriteLine ( `` IC.M '' ) ; } } class D : IA , IB , IC { public void M ( ) { // base ( IB ) .M ( ...
C # 8 base interface 's default method invocation workaround
C#
Since the release of C # 8.0 , I 've really been enjoying the 'void safety ' with nullable reference types . However , while tweaking a library of mine to support the new feature , I stumbled upon a 'problem ' to which I really could n't find an answer anywhere . I 've looked at Microsoft 's release notes and the .NET ...
public class WebSocketClientEnumerator < TWebSocketClient > : IEnumerator < TWebSocketClient > where TWebSocketClient : WebSocketClient { private WebSocketRoom < TWebSocketClient > room ; private int curIndex ; private TWebSocketClient ? curCli ; public WebSocketClientEnumerator ( WebSocketRoom < TWebSocketClient > roo...
.NET Implement IEnumerator with nullable reference types
C#
C # 8 introduced nullable reference types , which is a very cool feature . Now if you expect to get nullable values you have to write so-called guards : These can be a bit repetitive . What I am wondering is if it is possible to avoid writing this type of code for every variable , but instead have a guard-type static v...
object ? value = null ; if ( value is null ) { throw new ArgumentNullException ( ) ; } …
Possibility of external functions as nullable guards ?
C#
I have a class MyClassof which I want to store several instances in a collection . I will often need to check if an instance with a certain name exists , and if it does , retrieve that instance . Since iterating through the whole collection is not an option ( performance ! ) , I thought of a using a collection of key-v...
class MyClass { public string Name { get ; set ; } // is unique among all instances public SomeClass Data { get ; set ; } ... }
collection of key-value pairs where key depends on value
C#
I want to integrate SimpleModal in My ListView edit action so when the user click edit , the modal popup loaded with data through ajax to edit the form .My simple listview : My Bind Code : From FireBug :
< asp : ListView ID= '' lv_familyrelation '' runat= '' server '' ItemPlaceholderID= '' RelationContainer '' > < LayoutTemplate > < fieldset id= '' FieldSet1 '' > < legend > Relations < /legend > < div class= '' container-fluid '' > < div class= '' row '' > < div class= '' col-lg-4 '' > Code < /div > < div class= '' col...
How to use SimpleModal in listView edit action
C#
I 'm using the RestSharp library to access a REST API.I want all the API requests to go through the same method , so I can add headers , handle errors and do other stuff in a central place.So I made a method that accepts a generic Func < > and that solves most of my problems , but I do n't know how to handle the case w...
private T PerformApiCall < T > ( RestRequest restRequest , Func < RestRequest , IRestResponse < T > > restMethod ) { var response = restMethod.Invoke ( restRequest ) ; //handle errors ... . return response.Data ; } var apples = PerformApiCall ( new RestRequest ( '/api/apples ' ) , req = > Client.Execute < List < Apple ...
C # Generics and using the non-generic version from typed method
C#
I wrote the code : and I expect to see in ouput : only short namesor only long namesor names that occur first , after sorting in alphabetical order , which in this case coincides with `` only short names '' .But I did not expect to see what the program showed up : Short name at the end of the output . ¿ Why ? I tried t...
enum FlipRotate2dEnum : byte { NO = 0 , None = 0 , R2 = 1 , RotateTwice = 1 , FX = 2 , FlipX = 2 , FY = 3 , FlipY = 3 , D1 = 4 , ReflectDiagonal1 = 4 , D2 = 5 , ReflectDiagonal2 = 5 , RC = 6 , RotateClockwise = 6 , RN = 7 , RotateNonClockwise = 7 } class EnumTest { public static void Main ( ) { for ( byte i = 0 ; i < 8...
How to convert primitive type value to enum value , when enum contains elements with the same values ?
C#
I hope this is a simple question : How can you change 2 connection strings at runtime in the Global.asax under Application_Start ( ) Web.configGlobal.asaxDetailsBefore I start getting questions as to why I 'm doing this or reasons I should n't , please refer to the following post Azure Key Vault Connection Strings and ...
< connectionStrings > < add connectionString= '' DB1 '' value= '' '' / > < add connectionString= '' DB2 '' value= '' '' / > < /connectionStrings > protected void Application_Start ( ) { AreaRegistration.RegisterAllAreas ( ) ; GlobalConfiguration.Configure ( WebApiConfig.Register ) ; FilterConfig.RegisterGlobalFilters (...
How to Change ConnectionStrings at Runtime for a Web API
C#
I 'm playing with cqs a little bit and I 'm trying to implement this in a class library ( so there 's no IOC , IServiceProvider , etc ) . Here is some code that I wrote : And this si how I am calling my code : But the problem is that inside the dispatcher , I do n't know why the variable handler can not be casted as IQ...
public interface IQuery < TResult > { } public interface IQueryHandler < TQuery , TResult > where TQuery : IQuery < TResult > { TResult Handle ( TQuery query ) ; } public class Query : IQuery < bool > { public int Value { get ; set ; } } public class QueryHandler : IQueryHandler < Query , bool > { public bool Handle ( ...
some confusion with generic types in c #
C#
Consider we have a class with event declared : Despite of `` publicness '' of the event , we can not call FooBarEvent.Invoke from outside.This is overcame by modyfing a class with the following approach : Why accessing public events outside is limited by adding and removing listeners only ?
public class FooBar { public event EventHandler FooBarEvent ; } public class FooBar { public event EventHandler FooBarEvent ; public void RaiseFooBarEvent ( object sender , EventArgs eventArguments ) { FooBarEvent.Invoke ( sender , eventArguments ) ; } }
Why public event can not be invoked outside directly ?
C#
I 'm new to Stack Overflow , but tried to put as much informationI have following class structureI am trying to group list of ItemEntity into MasterEntity . Grouping fileds are Field1 , Field2 and Field3.I have done the grouping so far like belowWith in this group , I want to further split this by actual ItemDate and D...
public class ItemEntity { public int ItemId { get ; set ; } public int GroupId { get ; set ; } public string GroupName { get ; set ; } public DateTime ItemDate { get ; set ; } public string Field1 { get ; set ; } public string Filed2 { get ; set ; } public string Field3 { get ; set ; } public string Field4 { get ; set ...
Complex Linq Grouping
C#
I want to translate keys used in JSON to different languages.I 'm aware this seems like nonsense from a technical perspective when designing interfaces , APIs and so on . Why not use English only in the first place ? Well , I did n't write this requirement ; ) The easiest way to achieve this is probably an attribute : ...
/// < summary > serialization language < /summary > public enum Language { /// < summary > English < /summary > EN , /// < summary > German < /summary > DE // some more ... } /// < summary > An Attribute to add different `` translations '' < /summary > public class TranslatedFieldName : Attribute { public string Name {...
Different `` translated '' JsonProperty names
C#
So , I currently have a Board class that is composed of Pieces . Each Piece has a color and a string that describes the kind of piece . It also has a 2d matrix with bits either set on or off , that allows me to know which pixels to paint with the desired color or not.My question is , which class should have the respons...
Boolean [ , ] IsPixelSet ( int x , int y ) void DrawPieceOnBoard ( ) { for ( int y = 0 ; y < height ; ++y ) { for ( int x = 0 ; x < width ; ++x ) { if ( piece.IsPixelSet ( x , y ) { board.DrawPixelAt ( x , y , piece.GetColor ( ) ) ; } } } }
Which class has the responsibility of setting Piece 's pixels on a Board ( 2d matrix ) ? The Piece or the Board ?
C#
I am working on a framework that uses some Attribute markup . This will be used in an MVC project and will occur roughly every time I view a specific record in a view ( eg /Details/5 ) I was wondering if there is a better/more efficient way to do this or a good best practices example.At any rate , I have an a couple of...
[ Foo ( `` someValueHere '' ) ] String Name { get ; set ; } [ Bar ( `` SomeOtherValue '' ] String Address { get ; set ; } [ System.AttributeUsage ( AttributeTargets.Property ) ] class FooAttribute : Attribute { public string Target { get ; set ; } public FooAttribute ( string target ) { Target = target ; } } public sta...
Best way to access attributes
C#
I 've got a code In .net 3.5 expression evaluates as false , but in 4.0 it evaluates as true . My question is why ? and how can i check all of my old ( .net 3.5 ) code to prevent this behaviour ?
byte [ ] bytes = new byte [ ] { 0x80 , 1 , 192 , 33 , 0 } ; if ( bytes [ 0 ] ! = 0x80 || ( ( bytes [ 1 ] & ~1 ) ! = 0 ) || bytes [ 4 ] ! = 0 ) { //signature wrong ( .net 4.0 result ) } else { //signture okay ( .net 3.5 result ) }
Strange difference between .net 3.5 and .net 4.0
C#
Is there a way to make the analyzer understand that the variable Bar has a value for the following case ? There is the warning `` Nullable value type may be null . '' for Bar.Value but it obviously ca n't be.I am aware of two ways to avoid the warning . Both have disadvantages : Using Bar.HasValue directly instead of t...
# nullable enable class Foo { bool GenerateArray = > Bar.HasValue ; int ? Bar { get ; set ; } void FooBar ( ) { var data = ( GenerateArray ) ? new int [ Bar.Value ] : null ; } }
How to avoid irrelevant nullable warning ( without explicit suppression )
C#
Is there a way that I can track and intercept calls to values in properties that are auto implemented ? I 'd like to have code that looks a bit like this : Ideally the attribute would be able to intercept changes to the property values . Is this possible ? What I do n't want it to have a second piece of code spin over ...
[ Tracked ] public int SomeProperty { get ; set ; }
Track calls to auto implemented properties
C#
I am very new to EWS and Exchange in general , so not really sure what is the best approach.BackgroundI am trying to set configuration information about a room . I was hoping that the EWS API provided me with a Room object that I can add ExtendedProperties on , however , it appears that rooms are just an email address....
var folderId = new FolderId ( WellKnownFolderName.Calendar , new Mailbox ( roomEmail.Address ) ) ; var myCalendar = CalendarFolder.Bind ( service , folderId , PropertySet.FirstClassProperties ) ; myCalendar.DisplayName += `` Updated '' ; myCalendar.Update ( ) ; FindFoldersResults root = service.FindFolders ( WellKnownF...
Setting ExtendedProperties related to a Room
C#
Why the following codeprints `` msg '' and this onedoes n't print anything ?
class ClassA { public delegate void WriteLog ( string msg ) ; private WriteLog m_WriteLogDelegate ; public ClassA ( WriteLog writelog ) { m_WriteLogDelegate = writelog ; Thread thread = new Thread ( new ThreadStart ( Search ) ) ; thread.Start ( ) ; } public void Search ( ) { /* ... */ m_WriteLogDelegate ( `` msg '' ) ;...
A Question About C # Delegates
C#
Given code similar to the following ( with implementations in the real use case ) : Everything works great with a plain foreach ... e.g . the following compiles fine : We can also compile code to feed all the hungry animals : ... but if we try to use similar code changes to make only the hungry dogs bark , we get a com...
class Animal { public bool IsHungry { get ; } public void Feed ( ) { } } class Dog : Animal { public void Bark ( ) { } } class AnimalGroup : IEnumerable < Animal > { public IEnumerator < Animal > GetEnumerator ( ) { throw new NotImplementedException ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { throw new NotImple...
Linq functions give strange compile error when ambiguous use of IEnumerable - possible workarounds ?
C#
I have a small class called Tank has one public member called Location which is a Rectangle ( a struct ) . When I write : everything works fine , and the tank moves.But after I changed the member to be a property , I can no longer use this syntax . It does n't compile , because the t.Location is now a property ( which ...
Tank t = new Tank ( ) ; t.Location.X+=10 ; k = t.Location k.X +=10 ; t.Location = k ;
How to work with value types in c # using properties ?
C#
I 'm trying to port Java code to C # and I 'm running into odd bugs related to the unsigned shift right operator > > > normally the code : Would be the equivalent of Java 's : However for the case of -2147483648L which you might recognized as Integer.MIN_VALUE this returns a different number than it would in Java since...
long l = ( long ) ( ( ulong ) number ) > > 2 ; long l = number > > > 2 ;
Unsigned shift right in C # Using Java semantics for negative numbers
C#
I noticed that some enumerations have `` None '' as a enumeration member.For example what I meanWhy do they use it ? In what cases solution with a none member is more preferable ( less preferable ) ?
enum Mode { Mode1 = 1 , Mode2 = 2 , Mode3 = 3 , None = 4 }
Why do some people use `` None '' as enumeration member ?
C#
I have a jagged double [ ] [ ] array that may be modified concurrently by multiple threads . I should like to make it thread-safe , but if possible , without locks . The threads may well target the same element in the array , that is why the whole problem arises . I have found code to increment double values atomically...
public class Example { double [ ] [ ] items ; public void AddToItem ( int i , int j , double addendum ) { double newCurrentValue = items [ i ] [ j ] ; double currentValue ; double newValue ; SpinWait spin = new SpinWait ( ) ; while ( true ) { currentValue = newCurrentValue ; newValue = currentValue + addendum ; // This...
Concurrent modification of double [ ] [ ] elements without locking
C#
In c # 7.0 , you can use discards . What is the difference between using a discard and simply not assigning a variable ? Is there any difference ?
public List < string > DoSomething ( List < string > aList ) { //does something and return the same list } _ = DoSomething ( myList ) ; DoSomething ( myList ) ;
What is the difference between discard and not assigning a variable ?
C#
Normally , with value ( struct ) types , comparison with null ( or object types ) will result in a compiler error.However , if I add equality operator overloads on the struct , the comparison with null no longer produces a compiler error : I believe this has something to do with implicit conversion to Nullable < Value ...
struct Value { } class Program { static void Main ( ) { object o = new object ( ) ; Value v = default ; // Error CS0019 Operator '== ' can not be applied to operands of type 'Value ' and ' < null > ' var a = v == null ; // Error CS0019 Operator '== ' can not be applied to operands of type 'Value ' and 'object ' var b =...
Is it possible to suppress implicit conversion from null on a struct with operator overloads ?
C#
I 'd like your opinion on the following subject : Imagine we have a method that is responsible of achieving one specific purpose , but to do so , it needs the support of an important number of locally scoped objects , many of them implementing IDisposable.MS coding standards say that when using local IDisposable object...
using ( var disposableA = new DisposableObjectA ( ) ) { using ( var disposableB = new DisposableObjectB ( ) ) { using ( var disposableC = new DisposableObjectC ( ) ) { //And so on , you get the idea . } } } using ( var disposableA = new DisposableObjectA ( ) ) { using ( DisposableBaseObject disposableB = new Disposable...
Using block galore ?
C#
I try to load JPEG file and delete all black and white pixels from imageC # Code : After that I try to find unique colors in List by this codeAnd this code produces different results on different machines on same image ! For example , on this image it produces:43198 unique colors on XP SP3 with .NET version 443168 uniq...
... m_SrcImage = new Bitmap ( imagePath ) ; Rectangle r = new Rectangle ( 0 , 0 , m_SrcImage.Width , m_SrcImage.Height ) ; BitmapData bd = m_SrcImage.LockBits ( r , ImageLockMode.ReadWrite , PixelFormat.Format32bppArgb ) ; //Load Colors int [ ] colours = new int [ m_SrcImage.Width * m_SrcImage.Height ] ; Marshal.Copy (...
.NET Bitmap.Load method produce different result on different computers
C#
Assuming a method with the following signatureWhat is it acceptable for toReturn to be if TryXxxx returns false ? In that it 's infered that toReturn should never be used if TryXxxx fails does it matter ? If toReturn was a nulable type , then it would make sense to return null . But int is n't nullable and I do n't wan...
bool TryXxxx ( object something , out int toReturn )
What 's the standard behaviour for an out parameter when a TryXxxx method returns false ?
C#
I 've tried to name Button like that : But I 've seen the error : The token `` - Delete '' is unexpectedHow to include < sign in the Content property of Button ?
< Button Content= '' < -Delete '' / >
Can I use sign `` < - '' in Content property of Control ?
C#
Why does the following output provide incorrect result , Output is { N } rather then { 95.00 } as expected . Am I misunderstanding the concept of escaping { } or doing something wrong with Number format ?
int myNumber = 95 ; Console.WriteLine ( String.Format ( `` { { { 0 : N } } } '' , myNumber ) ) ;
String.Format does not provide correct result for number format
C#
Whats the best way to darken a color until it is readable ? I have a series of titles are have an associated color , but some of these colors are very light and any text drawn in them is unreadable . I 've been messing around with HSB and I ca n't seem to get an algorithm down that darkens the color without making it l...
Color c = FromHSB ( orig.A , orig.GetHue ( ) , orig.GetSaturation ( ) , orig.GetBrightness ( ) > .9 ? orig.GetBrightness ( ) - MyClass.Random ( .5 , .10 ) : orig.GetBrightness ( ) ) ;
C # Best Way to Darken a Color Until Its Readable
C#
I seemed to have stumbled upon something unusual within C # that I do n't fully understand . Say I have the following enum defined : If I declare an array of Foo or retrieve one through Enum.GetValues , I 'm able to successfully cast it to both IEnumerable < short > and IEnumerable < ushort > . For example : This happe...
public enum Foo : short { // The values are n't really important A , B } Foo [ ] values = Enum.GetValues ( typeof ( Foo ) ) ; // This cast succeeds as expected.var asShorts = ( IEnumerable < short > ) values ; // This cast also succeeds , which was n't expected.var asUShorts = ( IEnumerable < ushort > ) values ; // Thi...
Why can enum arrays be cast to two different IEnumerable < T > types ?
C#
I 'm writing Android application that connect with ASP.net web service ( C # ,3.5 ) android Application send `` Sign in '' information of the user to web service to verify that if the user is registered or not.here is the [ WebMethod ] which receive the request : SigninPerson is a class which hold user information like...
[ WebMethod ] public SigninPerson signin ( SigninPerson SIPerson ) { SigninPerson Temp = new SigninPerson ( 0 , `` '' , `` '' , `` '' , `` '' ) ; LinqToSQLDataContext DataBase = new LinqToSQLDataContext ( ) ; var Person = ( from a in DataBase.Persons where a.Email == SIPerson.E_Mail & & a.Password.Equals ( SIPerson.Pas...
String Comparsion in ASP.net ( C # )
C#
We have to use api from 3rd party vendor ( perforce ) . Till today , we were able to reference and use that API in .net framework application . But , now we are refactoring our product and of course we decided to use new .net environment , which is .net core 2.2 . As , Perforce did n't publish that library for .net cor...
FailFast : A callback was made on a garbage collected delegate of type 'p4netapi ! Perforce.P4.P4CallBacks+LogMessageDelegate : :Invoke ' . at Perforce.P4.P4Bridge.RunCommandW ( IntPtr , System.String , UInt32 , Boolean , IntPtr [ ] , Int32 ) at Perforce.P4.P4Bridge.RunCommandW ( IntPtr , System.String , UInt32 , Boole...
.net standard library fails in .net core but not in framework
C#
I wrote some code today and It was changed by another developer who said it was more safe . I am not sure this is right as I can not see the advantage of what was done here are some code examplesthis was changed toI am quite new to c # should the stream not be closed when you are finished with it ?
public byte [ ] ReadFile ( Stream stream ) { byte [ ] result = null ; try { // do something with stream result = < result of operation > } finally { stream.Close ( ) ; } return result ; } public byte [ ] ReadFile ( Stream stream ) { byte [ ] result = null ; // do something with stream result = < result of operation > r...
Closing a stream in function , a bad idea ?
C#
I have a propertygrid which I need to create a combobox inside the propertygrid and display int value ( 1 to 9 ) , I found using enum is the easiest way , but enum could n't display int value , even I try to cast it to int , but I do not know how to return all the value . Any other way to do this ? Thanks in Advance . ...
public class StepMode { private TotalSteps totalSteps ; public TotalSteps totalsteps { get { return totalSteps ; } set { value = totalSteps ; } } public enum TotalSteps { First = 1 , Second = 2 , Three = 3 , Four = 4 , Five = 5 , Six = 6 , Seven = 7 , Eight = 8 , Nine = 9 } }
display int value from enum
C#
I have an issue looping the if-statement in my code . I looked at other threads on stackoverflow but I could n't get it to work multiple times . The program I 'm trying to create is a basic converter for a casting company . What I tried to do is make it so that the user can input the type of conversion needed then the ...
static void Main ( string [ ] args ) { double waxWeight , bronzeWeight , silverWeight , fourteenkGoldWeight , eighteenkGoldWeight , twentytwokGoldWeight , platinumWeight ; string wW ; bool doesUserWantToLeave = false ; Console.WriteLine ( `` Please specify the type of conversion you would like to accomplish : '' + `` \...
How to loop an if-statement with many else if conditions
C#
I 'm learning C # generics and making some dummy code for testing purposes . So , I 'm testing the in Generic Modifier , which specifies that the type parameter is contravariant.Given the below interface : When compiling , I 'm getting the error message : [ CS1961 ] Invalid variance : The type parameter 'T ' must be in...
public interface IInterfaceTest < in T > { void Method ( T value ) ; void Method ( IList < T > values ) ; void Method ( IEnumerable < T > values ) ; }
Using generic contravariant with IList and IEnumerable
C#
I got two sets of numbers , with SET2 having more items in it usually . It 's guaranteed that the count of SET2 is equal or greater than the count of SET1 . Acutally , since the order matters the input are rather lists than sets.My goal is to combine ( sum up ) / reorder the numbers from SET2 to make it as similar to S...
SET1 = { 272370 , 194560 , 233430 } ; SET2 = { 53407.13 , 100000 , 365634.03 , 181319.07 } 272370 | 194560 | 233430 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - 365634.03 | 100000 + 53407.13 | 181319.07 ( best match ) 365634.03 | 181319.07 | 100000 + 53407.13 (...
Finding a good match of two lists of numbers
C#
I have couple of classes that are identified by some ID ( which is unique integer for every class ) . Next I need a method which takes an integer ( ID ) as argument and return corresponding class type . So far I have come to this : For now it seems that it works , but for some reason I do n't like that I have to instan...
public static Type GetById ( int id ) { switch ( id ) { case 1 : return ( new ClassA ( ) ) .GetType ( ) ; case 2 : return ( new ClassB ( ) ) .GetType ( ) ; case 3 : return ( new ClassC ( ) ) .GetType ( ) ; // ... and so on } }
C # method to return a type
C#
I was reading a C # book in which the author ( some dude named Jon Skeet ) implements a Where function like Now , I fully understand how this works and that it 's equivalent to which brings up the question of why would one separate these into 2 functions given that there would be memory/time overhead and of course more...
public static IEnumerable < T > Where < T > ( this IEnumerable < T > source , Funct < T , bool > predicate ) { if ( source == null || predicate == null ) { throw new ArgumentNullException ( ) ; } return WhereImpl ( source , predicate ) ; } public static IEnumerable < T > WhereImpl < T > ( IEnumerable < T > source , Fun...
Separate functions into validation and implementation ? Why ?
C#
I need to continuously read a log file to detect certain patterns . How can do so without interfering with file operations that the log writer operation needs to perform ? The log writer process , in addition to writing logs , periodically moves the file to another location ( one it reaches certain size ) .With the way...
using ( FileStream stream = new FileStream ( @ '' C : \temp\in.txt '' , FileMode.Open , FileAccess.Read , FileShare.Delete ) ) { TextReader tr = new StreamReader ( stream ) ; while ( true ) { Console.WriteLine ( `` .. `` + tr.ReadLine ( ) ) ; Thread.Sleep ( 1000 ) ; } }
Read a file in such a way that other processes are not prevented from modifying it
C#
My colleague and I came across this when looking into getting the invocation list of a delegate . If you create an event in say class X , then you can access the public methods of the event fine from within that class . But ( and please ignore stuff like why you 'd have public access to class members , this is n't what...
public class X { public delegate void TestMethod ( ) ; public event TestMethod testMethod ; private void rubbish ( ) { // can access testMethod.GetInvocationList ( ) fine here testMethod.GetInvocationList ( ) ; } } public class Y { public Y ( ) { X x = new X ( ) ; x.testMethod += this.test ; // here it says testMethod ...
How to make public methods only visible in class itself and class owning the object in C # ?
C#
Boxed nullable underlying type can be cast to enum but boxed enum type ca n't be cast to nullable type.And similarly , Boxed nullable enum can be cast to underlying type but boxed underlying type ca n't be cast to nullable enum.Ok , I know `` boxed nullable type '' is not the best way to describe it , but it 's for the...
enum Sex { Male , Female } int ? i = 1 ; object o = i ; Sex e = ( Sex ) o ; //success//butSex e = Sex.Male ; object o = e ; int ? i = ( int ? ) o ; //invalid cast Sex ? e = Sex.Male ; object o = e ; int i = ( int ) o ; //success//butint i = 1 ; object o = i ; Sex ? e = ( Sex ? ) o ; //invalid cast ( enum ) int ? - > su...
Boxed nullable underlying type can be cast to enum but boxed enum type ca n't be cast to nullable type
C#
This code after compilation looks like this in ILSpy : Why does it happen and can it be the reason of regex not matching in .Net 3.5 ? On 4.5 it works .
Regex regex = new Regex ( `` blah '' , RegexOptions.Singleline & RegexOptions.IgnoreCase ) ; Regex regex = new Regex ( `` blah '' , RegexOptions.None ) ;
Why RegexOptions are compiled to RegexOptions.None in MSIL ?
C#
I have the following simple codeWhen I ran this code the line Test ( ( Int32 ) 1 ) causes stack overflow due to infinite recursion . The only possible way to correctly call proper method ( with integer parameter ) I found isBut this is not appropriate for me , because both methods Test are public and I am willing the u...
abstract class A { public abstract void Test ( Int32 value ) ; } class B : A { public override void Test ( Int32 value ) { Console.WriteLine ( `` Int32 '' ) ; } public void Test ( Double value ) { Test ( ( Int32 ) 1 ) ; } } ( this as A ) .Test ( 1 ) ;
How to call overridden method which have overloads ?
C#
I want to generate triangles from points and optional relations between them . Not all points form triangles , but many of them do.In the initial structure , I 've got a database with the following tables : Nodes ( id , value ) Relations ( id , nodeA , nodeB , value ) Triangles ( id , relation1_id , relation2_id , rela...
INSERT INTO TrianglesSELECT t1.id , t2.id , t3.id , FROM Relations t1 , Relations t2 , Relations t3WHERE t1.id < t2.id AND t3.id > t1.id AND ( t1.nodeA = t2.nodeA AND ( t3.nodeA = t1.nodeB AND t3.nodeB = t2.nodeBOR t3.nodeA = t2.nodeB AND t3.nodeB = t1.nodeB ) OR t1.nodeA = t2.nodeBAND ( t3.nodeA = t1.nodeB AND t3.node...
Forming triangles from points and relations
C#
I 'm processing lots of data in a 3D grid so I wanted to implement a simple iterator instead of three nested loops . However , I encountered a performance problem : first , I implemented a simple loop using only int x , y and z variables . Then I implemented a Vector3I structure and used that - and the calculation time...
using BenchmarkDotNet.Attributes ; using BenchmarkDotNet.Running ; using System.Runtime.CompilerServices ; public struct Vector2I { public int X ; public int Y ; public int Z ; [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public Vector2I ( int x , int y , int z ) { this.X = x ; this.Y = y ; this.Z = z ; } } ...
Why is using structure Vector3I instead of three ints much slower in C # ?
C#
I know that we can use a format specifier for string interpolation in C # 6However I am using the same format in the same method over and over again so would like to soft code it , but not sure how to do it , or even if its possible , Can someone tell me how to do it , or confirm to me its impossible as I have done som...
var someString = $ '' the date was ... { _criteria.DateFrom : dd-MMM-yyyy } '' ; DateTime favourite ; DateTime dreaded ; ... ... const string myFormat = `` dd-MMM-yyyy '' ; var aBigVerbatimString = $ @ '' my favorite day is { favourite : $ myFormat } but my least favourite is { dreaded : $ myFormat } blah blah `` ;
Soft coding format specifier for Interpolated strings c # 6.0
C#
I 've got some code that has an awful lot of duplication . The problem comes from the fact that I 'm dealing with nested IDisposable types . Today I have something that looks like : The whole nested using block is the same for each of these methods ( two are shown , but there are about ten of them ) . The only thing th...
public void UpdateFromXml ( Guid innerId , XDocument someXml ) { using ( var a = SomeFactory.GetA ( _uri ) ) using ( var b = a.GetB ( _id ) ) using ( var c = b.GetC ( innerId ) ) { var cWrapper = new SomeWrapper ( c ) ; cWrapper.Update ( someXml ) ; } } public bool GetSomeValueById ( Guid innerId ) { using ( var a = So...
How could one refactor code involved in nested usings ?
C#
I work with resharper and when I clean my code I get this layout : I 'd rather have : is this possible ?
mock.Setup ( m = > m.Products ) .Returns ( new List < Product > { new Product { Name = `` Football '' , Price = 25 } , new Product { Name = `` Surf board '' , Price = 179 } , new Product { Name = `` Running Shoes '' , Price = 95 } } .AsQueryable ( ) ) ; mock.Setup ( m = > m.Products ) .Returns ( new List < Product > { ...
resharper inline object initialisation
C#
I want to perform the updation of the existing record.. the way that i have paste my code here i have successfully achieved my task but i dont want to do the updation by that way actually.. i want to do such that i get the id of the customer..
private void btnUpdate_Click ( object sender , EventArgs e ) { SqlConnection cn = new SqlConnection ( @ '' Data Source=COMPAQ-PC-PC\SQLEXPRESS ; Initial Catalog=Gym ; Integrated Security=True '' ) ; if ( cn.State == ConnectionState.Closed ) { cn.Open ( ) ; } int result = new SqlCommand ( `` Update Customer set Customer...
A question regarding C # and SQL
C#
consider the variable ob4 as shown in figurenow : how can i reach ob4 [ 0 ] - > [ 0,2 ] the line ( double [ , ] p= ( double [ , ] ) o [ 0,0 ] ; ) gives the following error : Can not apply indexing with [ ] to an expression of type 'object '
var o=ob4 [ 0 ] ; double [ , ] p= ( double [ , ] ) o [ 0,0 ] ;
Working with object
C#
I have a WinForms project which is several years old and has been retro-fitted with async event-handlers : Inside this method is an async call : When the program runs on a normal resolution screen , it runs as expected . However , when run on a high-DPI screen the window 's dimensions - as well as those of all child co...
private async void dgvNewOrders_CellClick ( object sender , DataGridViewCellEventArgs e ) var projectTemplate = await GetProjectTemplateFile ( companyId , sourceLang , targetLang ) ; private async Task < ProjectTemplateFile > GetProjectTemplateFile ( long companyId , string sourceLanguage , string targetLanguage ) { re...
WinForms window changes dimensions when it encounters an async call
C#
I got a little problem with reading information from an xml file ... The file passed to me has thousands of lines . Im interested in only 300 - 400 of those lines . I do n't need to write any data back to xml when the user is finished with his operation and the data to read can be stored in a List < string > .I found s...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ProjectConfiguration xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < ProjectLists xmlns= '' ... '' > < ProjectList > ... // not interested in this data < /ProjectList > < ProjectList > < ListNode > < ...
Read xml from file
C#
I 've got a number of classes designed to handle objects of specific types.e.g. , where the handler interface might be defined something like this : Now , I 'd like to be able to use a dictionary of these handlers : However , C # does n't appear to allow me to use the Handler interface without specifying a type . C # a...
class FooHandler : Handler < Foo > { void ProcessMessage ( Foo foo ) ; } interface Handler < T > { void ProcessMessage ( T obj ) ; } Dictionary < Type , Handler > handlers ; void ProcessMessage ( object message ) { var handler = handlers [ message.GetType ( ) ] ; handler.ProcessMessage ( handler ) ; } Dictionary < Type...
Is it possible to do an unsafe covariant invocation of a generic method ?
C#
I 've been experimenting with Linq to see what it can do - and I 'm really loving it so far : ) I wrote some queries for an algorithm , but I did n't get the results I expected ... the Enumeration always returned empty : case # 1I changed the query declaration to be inline like this , and it worked fine : case # 2Does ...
List < some_object > next = new List < some_object > ( ) ; some_object current = null ; var valid_next_links = from candidate in next where ( current.toTime + TimeSpan.FromMinutes ( 5 ) < = candidate.fromTime ) orderby candidate.fromTime select candidate ; current = something ; next = some_list_of_things ; foreach ( so...
Linq deferred execution with local values
C#
Why does the following not compile ? The compiler complains that `` The name 'FooMethod ' does not exist in the current context '' . However , if the Foo method is changed to : this compiles just fine.I do n't understand why one works and the other does not .
interface IFoo { void Foo ( ) ; } class FooClass : IFoo { void IFoo.Foo ( ) { return ; } void Another ( ) { Foo ( ) ; // ERROR } } public void Foo ( ) { return ; }
Why does a method prefixed with the interface name not compile in C # ?
C#
I am looking for a way to generate N pieces of question marks joined with comma.EDIT 1 I am looking in a simple way . Probably using 1-2 line of code . In c++ there are array fill ( ) and joins.EDIT 2I need this for Compact Framework
string element= '' ? `` ; string sep= '' , '' ; int n=4 ; // code to run and create ? , ? , ? , ?
How can create N items of a specific element in c # ?
C#
The code below works for me however , I would like to add a condition before it is added to the table . What I need is - if the `` Scan Time '' is between two dates , then it should be added to the `` table '' if not , then it should be disregarded.This is for selecting the file.. This is for reading the file then addi...
private void btnSelectFile_Click ( object sender , EventArgs e ) { OpenFileDialog ofd = new OpenFileDialog ( ) { Title = `` Select the file to open . `` , Filter = `` DAT ( *.dat ) |*.dat|TXT ( *.txt ) |*.txt|All Files ( *.* ) |* . * '' , InitialDirectory = Environment.GetFolderPath ( Environment.SpecialFolder.MyDocume...
Exploding a lambda expression
C#
I have an interface with a covariant type parameter : Additionally , I have a non-generic base class and another deriving from it : Covariance says that an I < Derived > can be assigned to an I < Base > , and indeed I < Base > ib = default ( I < Derived > ) ; compiles just fine.However , this behavior apparently change...
interface I < out T > { T Value { get ; } } class Base { } class Derived : Base { } class Foo < TDerived , TBase > where TDerived : TBase { void Bar ( ) { I < Base > ib = default ( I < Derived > ) ; // Compiles fine I < TBase > itb = default ( I < TDerived > ) ; // Compiler error : Can not implicitly convert type ' I <...
Covariance error in generically constrained class
C#
Can anyone shed light on why contravariance does not work with C # value types ? The below does not work
private delegate Asset AssetDelegate ( int m ) ; internal string DoMe ( ) { AssetDelegate aw = new AssetDelegate ( DelegateMethod ) ; aw ( 32 ) ; return `` Class1 '' ; } private static House DelegateMethod ( object m ) { return null ; }
Contravariant Delegates Value Types
C#
VB.Net code that I need to translate to C # : Same equation in C # Why is there a different ? Is Mod different between the two ? EDIT : I am translating code from VB to C # , so I need to get the same result as the VB code in my C # code .
Dim s = 27 / 15 Mod 1 //result is 0.8 var s = 27 / 15 % 1 //result is 0
C # and VB.Net give different results for the same equation
C#
I need to download from FTP over 5000 files being .html and .php files . I need to read each file and remove some stuff that was put there by virus and save it back to FTP.I 'm using following code : I downloaded some files by hand and some have < meta http-equiv= '' Content-Type '' content= '' text/html ; charset=wind...
string content ; using ( StreamReader sr = new StreamReader ( fileName , System.Text.Encoding.UTF8 , true ) ) { content = sr.ReadToEnd ( ) ; sr.Close ( ) ; } using ( StreamWriter sw = new StreamWriter ( fileName + `` 1 '' + file.Extension , false , System.Text.Encoding.UTF8 ) ) { sw.WriteLine ( content ) ; sw.Close ( )...
Can a file be read and written right back with small changes without knowing its encoding in C # ?
C#
This is minor , I know , but let 's say that I have a class Character and a class Ability ( mostly because that 's what I 'm working on ) . Class Character has six abilities ( so typical D & D ... ) . basically : andWhen actually using these ability properties in future code , I 'd like to be able to default to just th...
public class Character { public Character ( ) { this.Str = new Ability ( `` Strength '' , `` Str '' ) ; this.Dex = new Ability ( `` Dexterity '' , `` Dex '' ) ; this.Con = new Ability ( `` Constitution '' , `` Con '' ) ; this.Int = new Ability ( `` Intelligence '' , `` Int '' ) ; this.Wis = new Ability ( `` Wisdom '' ,...
How to create a simplified assignment or default property for a class in C #
C#
I noticed the following code from our foreign programmers : It 's not exactly proper code but I was wondering what exactly this will do . Will this lock on a new object each time this method is called ?
private Client [ ] clients = new Client [ 0 ] ; public CreateClients ( int count ) { lock ( clients ) { clients = new Client [ count ] ; for ( int i=0 ; i < count ; i++ ) { Client [ i ] = new Client ( ) ; //Stripped } } }
New inside a lock
C#
I have the follow button click event : Effectively , it does a few checks and then starts some directory recursion looking for specific files . However , the very first line of code to make the label visible does not occur until after the directories have been recursed ? Anybody know why this would be ? Thanks .
private void btnRun_Click ( object sender , EventArgs e ) { label1.Visible = true ; if ( SelectDatabase ( ) ) { if ( string.IsNullOrEmpty ( txtFolderAddress.Text ) ) MessageBox.Show ( `` Please select a folder to begin the search . `` ) ; else { if ( cbRecurse.Checked == false || Directory.GetDirectories ( initialDirec...
C # - Code processing order - strange behaviour
C#
LINQ to NHibernate removes parenthesis in where clause : This results in the following query ( note the missing parenthesis ) : This is a huge problem , because it changes the query condition significantly.Is this a known problem or am I doing something wrong ?
session.Query < MyEntity > ( ) .Where ( x = > ( x.MyProp1 < end & & x.MyProp1 > start ) || ( x.MyProp2 < end & & x.MyProp2 > start ) ) ; select < columns > from MY_ENTITY where MY_PROP1 < : p0 and MY_PROP1 > : p1 or MY_PROP2 < : p2 and MY_PROP2 > : p3 ;
Grouping in condition is being dropped
C#
I have simplified my code to thisThe issue is that this calls although I am calling it with an int and it should be using Using the parent returns the expected result.Update : Thanks to @ Jan and @ azyberezovsky for pointing me to the specification . I have added a virtual empty method to the base class to get around t...
internal class Program { private static void Main ( string [ ] args ) { Child d = new Child ( ) ; int i = 100 ; d.AddToTotal ( i ) ; Console.ReadKey ( ) ; } private class Parent { public virtual void AddToTotal ( int x ) { Console.WriteLine ( `` Parent.AddToTotal ( int ) '' ) ; } } private class Child : Parent { public...
Derived class using the wrong method
C#
Any ideas ? I marked it as static but it 's not working !
class ExtensionMethods { public static int Add ( this int number , int increment ) { return number + increment ; } }
I can not get my extension method to work ( C # )
C#
This question relates to DocumentClient from Microsoft.Azure.DocumentDB.Core v2.11.2 . ( Update : the bug also exists in Microsoft.Azure.Cosmos . ) There seems to be a bug in the LINQ Provider for Cosmos DB when the query contains DateTime values with trailing zeros . Consider the following piece of code : The result o...
string dateTimeWithTrailingZero = `` 2000-01-01T00:00:00.1234560Z '' ; // trailing zero will be truncated by LINQ provider : - ( DateTime datetime = DateTime.Parse ( dateTimeWithTrailingZero , CultureInfo.InvariantCulture , DateTimeStyles.AdjustToUniversal ) ; IQueryable < Dictionary < string , object > > query = clien...
Bug in DateTime handling of Cosmos DB DocumentClient
C#
Example code : Code at line C wo n't compile , but line A compiles fine . Is there something special about an enum with 0 value that gets it special treatment in cases like this ?
public enum Foods { Burger , Pizza , Cake } private void button1_Click ( object sender , EventArgs e ) { Eat ( 0 ) ; // A Eat ( ( Foods ) 0 ) ; // B //Eat ( 1 ) ; // C : wo n't compile : can not convert from 'int ' to 'Foods ' Eat ( ( Foods ) 1 ) ; // D } private void Eat ( Foods food ) { MessageBox.Show ( `` eating : ...
Enum 0 value inconsistency
C#
I have seen some form of this some time ago , but I can not recall what it was called , and therefore have no clue on how to implement something like this : Which calls some overload function that can parse the string into a SomeMoneyFormat object .
SomeMoneyFormat f = `` € 5,00 '' ;
What 's this syntax called ? SomeMoneyFormat f = `` € 5,00 '' ;
C#
So I am trying to Unit test/Integration test my code responsible for sharing a directory.So I create my share drive and then I check if the directory exists . First locally and then via it 's share name.After this I of course want to clean up after myself by removing the directory I just created . However this does not...
Assert.IsTrue ( Directory.Exists ( testSharePath ) ) ; Assert.IsTrue ( Directory.Exists ( String.Format ( @ '' \\ { 0 } \ { 0 } '' , System.Environment : MachineName , testShareName ) ) ;
Directory.Exists hold directory handle for several seconds
C#
Let 's say I have this text input.I want to extract the ff output : Currently , I can only extract what 's inside the { } groups using balanced group approach as found in msdn . Here 's the pattern : Does anyone know how to include the R { } and D { } in the output ?
tes { } tR { R { abc } aD { mnoR { xyz } } } R { abc } R { xyz } D { mnoR { xyz } } R { R { abc } aD { mnoR { xyz } } } ^ [ ^ { } ] * ( ( ( ? 'Open ' { ) [ ^ { } ] * ) + ( ( ? 'Target-Open ' } ) [ ^ { } ] * ) + ) * ( ? ( Open ) ( ? ! ) ) $
How to make balancing group capturing ?
C#
I 'm need to convert some string comparisons from vb to c # . The vb code uses > and < operators . I am looking to replace this with standard framework string comparison methods . But , there 's a behaviour I do n't understand . To replicate this , I have this testCould someone explain why b is returning 1 . My current...
[ TestMethod ] public void TestMethod2 ( ) { string originalCulture = CultureInfo.CurrentCulture.Name ; // en-GB var a = `` d '' .CompareTo ( `` t '' ) ; // returns -1 var b = `` T '' .CompareTo ( `` t '' ) ; // returns 1 Assert.IsTrue ( a < 0 , `` Case 1 '' ) ; Assert.IsTrue ( b < = 0 , `` Case 2 '' ) ; }
Understanding String Comparison behaviour
C#
In the below piece of C # code , why does the first set of prints produce an output of C C C but the LINQ equivalent of that produces an output of A B C I understand the first set of outputs - it takes last value when it exits the loop , but seems to me that there should be consistency between the traditional loop and ...
public static void Main ( string [ ] str ) { List < string > names = new List < string > ( ) { `` A '' , `` B '' , `` C '' } ; List < Action > actions = new List < Action > ( ) ; foreach ( var name in names ) { actions.Add ( ( ) = > Console.WriteLine ( name ) ) ; } foreach ( var action in actions ) { action.Invoke ( ) ...
Traditional loop versus LINQ - different outputs
C#
Possible Duplicate : Why are private fields private to the type , not the instance ? Consider the following class : In my constructor I 'm calling private or protected stuff of the otherObject . Why is this possible ? I always thought private was really private ( implying only the object could call that method / variab...
public class Test { protected string name ; private DateTime dateTime ; public Test ( string name ) { this.name = name ; this.dateTime = DateTime.Now ; } public Test ( Test otherObject ) { this.name = otherObject.name ; this.dateTime = otherObject.GetDateTime ( ) ; } private DateTime GetDateTime ( ) { return dateTime ;...
Why is calling a protected or private CSharp method / variable possible ?
C#
I am creating a save game manager for Skyrim and have run into an issue . When I create a SaveGame object by itself , the bitmap portion of the save works correctly . When I call that method in a loop , however , the bitmap takes on an erroneous value , mainly one that is similar to that of another save game.TL ; DR - ...
public string Name { get ; private set ; } public int SaveNumber { get ; private set ; } public int PictureWidth { get ; private set ; } public int PictureHeight { get ; private set ; } public Bitmap Picture { get ; private set ; } public DateTime SaveDate { get ; private set ; } public string FileName { get ; private ...
Why does the data in a bitmap go out of scope ?
C#
I 'm building an application that saves named regular expressions into a database . Looks like this : I 'm using Asp.Net forms . How can I validate the entered regex ? It would like the user to know if the entered regex is not a valid .Net regular expression.The field should reject values like :
^Wrong ( R [ g [ x ) ] ] $ Invalid\Q & \A
How to validate if the input contains a valid .Net regular expression ?
C#
I am trying to generating the usps label with 4x6 but I am facing this issue . Can any one help me out for generating 4x6Label.Also I tried changing the version from DeliveryConfirmationV3 to DeliveryConfirmationV4 but still it is not generating 4x6Label.My xml request is passing as but I am receiving error as Initiall...
https : //secure.shippingapis.com/ShippingAPI.dll ? API=DeliveryConfirmationV3 & XML= < DeliveryConfirmationV3.0Request USERID= '' xxxxx '' PASSWORD= '' xxxxxx '' > < Option > 1 < /Option > < ImageParameters > < ImageParameter > 4X6LABEL < /ImageParameter > < /ImageParameters > < FromName > Mitesh1 Jain1 < /FromName > ...
Issue as The element 'ImageParameters ' can not contain child element 'ImageParameter '
C#
I salted and hashed my logins according to this Code Project articleWhen I did this , my password and salt fields in the database were just varchar columns . The data was displayed in SQL Server Management Studio as question marks.A friend then came and changed the columns to nvarchar data type and now the data appears...
public User Login ( ) // returns an instance of its own class { // get the salt value for the user var auser = ie.users.FirstOrDefault ( u = > String.Compare ( u.emailaddress , emailaddress , false ) == 0 ) ; if ( auser == null ) { throw new ValidationException ( `` User not found '' ) ; } // hash the login for compari...
Password hashing used to work , now I ca n't get into my software
C#
I 'm consuming a SOAP web service . The web service designates a separate service URL for each of its customers . I do n't know why they do that . All their functions and parameters are technically the same . But if I want to write a program for the service I have to know for each company is it intended . That means fo...
using DMDelivery.apple ; using DMDelivery.orange ;
`` using '' of two different libraries with almost identical functions
C#
Why must we specify the parameter name x as followswhen declaring a delegate type ? For me , the parameter name x is unused so it will be simpler if we can rewrite as follows : Please let me know why the C # designer `` forced '' us to specify the parameter names.Edit1 : Is public delegate TResult Func < T1 , TResult >...
public delegate void XXX ( int x ) ; public delegate void XXX ( int ) ;
By design why is it mandatory to specify parameter names when declaring delegate type ?
C#
I 'm working on an algorithm which calculates a similarity coefficient between restaurants . Before we 're able to calculate said similarity , I need 3 users who rated both restaurants . Here is a table with a possible scenario as example : Here does X stand for no review , and the ratings are reviews from a user for t...
| Restaurant 1 | Restaurant 2User 1 | X | 2User 2 | 1 | 5User 3 | 4 | 3User 4 | 2 | 1User 5 | X | 5 for ( int i = 0 ; i < allRestaurants.Count ; i++ ) for ( int j = 0 ; j < allRestaurants.Count ; j++ ) if ( i < j ) matrix.Add ( new Similarity ( ) { Id = Guid.NewGuid ( ) , FirstRest = allRestaurants [ i ] , SecondRest =...
Matching users who reviewed the same restaurants
C#
The output of the below code is as following : not equalequal Note the difference in type of x and xx and that == operator overload is only executed in the second case and not in the first.Is there a way I can overload the == operator so that its always executed when a comparison is done on between MyDataObejct instanc...
class Program { static void Main ( string [ ] args ) { // CASE 1 Object x = new MyDataClass ( ) ; Object y = new MyDataClass ( ) ; if ( x == y ) { Console.WriteLine ( `` equal '' ) ; } else { Console.WriteLine ( `` not equal '' ) ; } // CASE 2 MyDataClass xx = new MyDataClass ( ) ; MyDataClass yy = new MyDataClass ( ) ...
== operator overloading when object is boxed
C#
Both the strings s5 and s6 have same value as s1 ( `` test '' ) . Based on string interning concept , both the statements must have evaluated to true . Can someone please explain why s5 did n't have the same reference as s1 ?
string s1 = `` test '' ; string s5 = s1.Substring ( 0 , 3 ) + '' t '' ; string s6 = s1.Substring ( 0,4 ) + '' '' ; Console.WriteLine ( `` { 0 } `` , object.ReferenceEquals ( s1 , s5 ) ) ; //FalseConsole.WriteLine ( `` { 0 } `` , object.ReferenceEquals ( s1 , s6 ) ) ; //True
Why some identical strings are not interned in .NET ?