lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Here is the relevant code . Mind you , I did this in Notepad++ instead of copying in my code for my project at work . If I misspelled a class name in it , assume it is not misspelled in my code . No compile errors.Model : Controller : View ( Razor ) : This will `` work '' , but wo n't set values on any of the rendered ...
public class MyViewModel { public int SelectedSomething { get ; set ; } public IList < int > Somethings { get ; set ; } } public class MyController { public ActionResult Index ( ) { var viewModel = new MyViewModel ( ) ; viewModel.Somethings = Enumerable.Range ( 1 , 12 ) .ToList ( ) ; return View ( viewModel ) ; } } @ H...
Correct way to use DropDownListFor with a list of primitive types ?
C#
I have many entities that have the IsActive property . For internal reasons , I need all those fields to be nullable . On the other hand , for every entity I may have to do a double test in tens of places in the application : ( null are treated as true ) If I create a method likeIt still wo n't hide the property ( at l...
if ( language.IsActive == null || language.IsActive.value ) class Language { public bool IsActiveLanguage ( ) { return language.IsActive == null || language.IsActive.value ; } }
Avoiding to repeatedly test for nulls on the same properties
C#
I use dotMemory to profile my application and I noticed the below behavior : inside my code there are some points where I perform garbage collection manually by using Inside dotMemory I see that memory is actually freed in these points but if after that I click 'Force GC ' even more garabage is collected . What is the ...
GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ;
What exactly happens when I ask dotMemory to force garbage collection
C#
Is it possible for a constructor to be pre-empted in C # ? For example , consider the code : Somewhere else in the code two threads have access to a variable of type A , the first thread calls the constructor which is pre-empted at point # 1 . Then the second thread tests for ready and finds it to still be true therefo...
public class A { public bool ready = true ; public A ( ) { ready = false ; // Point # 1 // Other initialization stuff ready = true ; // Point # 2 } }
Can a constructor be pre-empted ?
C#
I wanted to learn more about C # language and a lot of people have recommended digging into the C # specification , so I went and downloaded a copy of it from MSDN and started reading and going through the examples.C # Specification Introducton - Section 1.6.7.5 Operators `` The List class declares two operators , oper...
using System ; class Test { static void Main ( ) { List < int > a = new List < int > ( ) ; a.Add ( 1 ) ; a.Add ( 2 ) ; List < int > b = new List < int > ( ) ; b.Add ( 1 ) ; b.Add ( 2 ) ; Console.WriteLine ( a == b ) ; // Outputs `` True '' b.Add ( 3 ) ; Console.WriteLine ( a == b ) ; // Outputs `` False '' } }
C # Specification - Section 1.6.7.5 can someone please explain this example ?
C#
What is the difference between the following two snippets of code : andI have started using using a lot more but I am curious as to what the actually benefits are as compared to scoping objects.Edit : Useful tidbits I took from this : Jon Skeet : Note that this does not force garbage collection in any way , shape or fo...
using ( Object o = new Object ( ) ) { // Do something } { Object o = new Object ( ) ; // Do something }
Difference between 'using ' and scoping ?
C#
I have function in c++ something like this : And I can use functions in two ways : When I write code in C # I used ref keyword : but compiler said : A ref or out parameter can not have a default value.How can I solve this problem ?
// C++bool Foo ( int* retVal = NULL ) { // ... if ( retVal ! = NULL ) *retVal = 5 ; // ... return true ; } int ret ; Foo ( & ret ) ; Foo ( ) ; // C # bool Foo ( ref int retVal = null ) { // ... if ( retVal ! = null ) { retVal = 5 ; } // ... return true ; }
How to convert optional pointer argument from C++ code to C #
C#
Given the code : Inputting the value 0x300 yields the result 0x69D04700 . This is only the lower 32 bits of the result.Given the result 0x69D04700 and the factor 0x123456D , is it possible to retrieve all numbers such that ( value * 0x123456D ) & 0xFFFFFFFF = 0x69D04700 in a fast way ? Edit : The code I show is pseudoc...
uint Function ( uint value ) { return value * 0x123456D ; }
Reversing multiplication operation that has overflowed
C#
I have the following LINQ query : Which translates to the following when run : Now I 'm pretty sure that the reason there is a sub-select is because I have the base LINQ query surrounded by ( ) and then perform .Distinct ( ) but I do n't know enough about LINQ to be sure of this . If that 's indeed the case is there a ...
var queryGroups = ( from p in db.cl_contact_event select new Groups { inputFileName = p.input_file_name } ) .Distinct ( ) ; SELECT [ Distinct1 ] . [ C1 ] AS [ C1 ] , [ Distinct1 ] . [ input_file_name ] AS [ input_file_name ] FROM ( SELECT DISTINCT [ Extent1 ] . [ input_file_name ] AS [ input_file_name ] , 1 AS [ C1 ] F...
Why does LINQ-to-Entities put this query in a sub-select ?
C#
Can anyone explain , why does the following code produce the error ? ( Compiling in Microsoft Visual Studio 2008 ) the error is The call is ambiguous between the following methods or properties : 'ConsoleApplication1.Program.M1 < ConsoleApplication1.Base1 > ( ConsoleApplication1.Base1 , ConsoleApplication1.I1 ) ' and '...
class Base1 { } ; class Base2 { } interface I1 { } interface I2 { } class C : I1 , I2 { } static class Program { static T M1 < T > ( this T t , I1 x ) where T : Base1 { return t ; } static T M1 < T > ( this T t , I2 x ) where T : Base2 { return t ; } static void Main ( string [ ] args ) { Base1 b1 = new Base1 ( ) ; C c...
Why is this call ambiguous ?
C#
I 'm confused why this compiles : MyDelegate should be a pointer to a method that takes two int parameters and returns another int , right ? Why am I allowed to assign a method that takes no parameters ? Interestingly , these does n't compile ( it complains about the signature mismatches , as I 'd expect ) Thanks for a...
private delegate int MyDelegate ( int p1 , int p2 ) ; private void testDelegate ( ) { MyDelegate imp = delegate { return 1 ; } ; } private void testDelegate ( ) { // Missing param MyDelegate imp = delegate ( int p1 ) { return 1 ; } ; // Wrong return type MyDelegate imp2 = delegate ( int p1 , int p2 ) { return `` String...
Why does a delegate with no parameters compile ?
C#
( Note : I already asked this question , but the answer was specific to Java , and so I am asking the same question for C # and the .NET framework . It is NOT a duplicate . ) I have been using this pattern for a while , but I only recently came to think that it might not be OK to do this . Basically , I use some varian...
public class SampleAsync { public SampleAsync ( ) { } private bool completed ; public void Start ( ) { var worker = new BackgroundWorker ( ) ; worker.DoWork += ( sender , e ) = > { // ... do something on a different thread completed = true ; } ; worker.RunWorkerAsync ( ) ; } public void Update ( ) { if ( ! completed ) ...
Are unresettable `` flags '' threadsafe in C # /.NET ?
C#
I have the following recursive code and i am getting a stackoverflow exception . I ca n't figure out the root cause because once i get the exception , i dont get the full call stack in Visual studio.The idea is that there are org teams that roll up into larger `` Main '' teams.Does anyone see a flaw on this code below ...
private Unit GetUnit ( Unit organisationalUnit ) { if ( organisationalUnit.IsMainUnit ) { return organisationalUnit ; } if ( organisationalUnit.Parent == null ) return null ; return GetUnit ( organisationalUnit.Parent ) ; }
how can i get catch the root of a stackoverflow exception on recursive code
C#
If I have a task running on a worker thread and when it finds something wrong , is it possible to pause and wait for the user to intervene before continuing ? For example , suppose I have something like this : Is it possible to substitute WaitForUserInput ( ) with something that runs on the UI thread , waits for the us...
async void btnStartTask_Click ( object sender , EventArgs e ) { await Task.Run ( ( ) = > LongRunningTask ( ) ) ; } // CPU-boundbool LongRunningTask ( ) { // Establish some connection here . // Do some work here . List < Foo > incorrectValues = GetIncorrectValuesFromAbove ( ) ; if ( incorrectValues.Count > 0 ) { // Here...
How to pause task running on a worker thread and wait for user input ?
C#
Possible Duplicate : C # Captured Variable In Loop I am pretty new to multi-threading programming.When I ran the code below and only the last child got executed.Can some one tell me what happened ? Thank you very much.Output
private void Process ( ) { Dictionary < int , int > dataDict = new Dictionary < int , int > ( ) ; dataDict.Add ( 1 , 2000 ) ; dataDict.Add ( 2 , 1000 ) ; dataDict.Add ( 3 , 4000 ) ; dataDict.Add ( 4 , 3000 ) ; foreach ( KeyValuePair < int , int > kvp in dataDict ) { Console.WriteLine ( `` Ready for [ `` + kvp.Key.ToStr...
Confused about multi-threading in a loop for C #
C#
The loop : It just does a repeated find-and-replace on a bunch of keys . The dictionary is just < string , string > .I can see 2 improvements to this . Every time we do pattern.Replace it searches from the beginning of the string again . It would be better if when it hit the first { , it would just look through the lis...
var pattern = _dict [ key ] ; string before ; do { before = pattern ; foreach ( var pair in _dict ) if ( key ! = pair.Key ) pattern = pattern.Replace ( string.Concat ( `` { `` , pair.Key , `` } '' ) , string.Concat ( `` ( `` , pair.Value , `` ) '' ) ) ; } while ( pattern ! = before ) ; return pattern ; class FlexDict :...
How can I speed this loop up ? Is there a class for replacing multiple terms at at time ?
C#
To follow my previous post here = > Binding SelectedItem of ComboBox in DataGrid with different typeI have now a datagrid containing 2 columns , one with a text , the other with a combobox ( in a datatemplate , written thru the C # code , not the Xaml ) . After having done some choice on the combobox , I now would like...
foreach ( DataRowView row in Datagrid1.Items ) { var firstColumNresult = row.Row.ItemArray [ 0 ] ; // Return correctly a stringvar myrow = row.Row.ItemArray [ 1 ] ; // always empty ... } DataTable tableForDG = new DataTable ( ) ; tableForDG.Columns.Add ( new DataColumn { ColumnName = `` Name '' , Caption = `` Name '' }...
How to get value of a programmatically written combobox in a datagrid in wpf ?
C#
I am trying to understand one thing in this code : And Output is : And the thing that I do n't understand when you pass null to y , I believe it calls public static implicit operator Nullable < T > ( T value ) but the definition of this method initializes a new struct passing value which is assigned null however constr...
Nullable < Int32 > x = 5 ; Nullable < Int32 > y = null ; Console.WriteLine ( `` x : HasValue= { 0 } , Value= { 1 } '' , x.HasValue , x.Value ) ; Console.WriteLine ( `` y : HasValue= { 0 } , Value= { 1 } '' , y.HasValue , y.GetValueOrDefault ( ) ) ; x : HasValue=True , Value=5y : HasValue=False , Value=0
How CLR can bypass throwing error when assigning a null value to the struct ?
C#
I use private and public methods all the time . However , I do not understand why they work.Creating a small Hello World Program : The IL created for the public method : The IL created for the private method : It 's the exact same.How does the JIT differentiate and verify that the private/public rules were followed ?
public class CallPublicHelloWorld { public void CallHelloWorld ( ) { publicHelloWorld ( ) ; privateHelloWorld ( ) ; } private void privateHelloWorld ( ) { Console.WriteLine ( `` Hello World '' ) ; } public void publicHelloWorld ( ) { Console.WriteLine ( `` Hello World '' ) ; } } IL_0000 : nopIL_0001 : ldstr `` Hello Wo...
How does C # verify the C # Private Definition ?
C#
I 'm having a problem . I 'm making a utility to do procedural generated maps.I have a room pool and each rooms are disposed in a table of room . I have a method to connect all the room together which walk in the table and connect adjacent rooms . I have an enum which contains the type of rooms : In the connection meth...
public enum RoomType { Default = 0 , Building , Boss , Item , Standard , Start , } if ( neighbourhood [ 2 , 1 ] ! = null ) { if ( firstLevel.isOn ) { if ( neighbourhood [ 2,1 ] .TypeOfRoom == RoomType.Start ) { roomGrid [ x , y ] .AddConnection ( neighbourhood [ 2 , 1 ] , Location.RIGHT ) } } else if ( neighbourhood [ ...
If statement always true with enum in comparison
C#
I have a C # app . In this app , I have some XML that looks like this : I 'm trying to convert this XML into a C # object . My class looks something like this : When I run var list = List.Deserialize ( xml ) ; I get a List object back . The name of the List is properly set . However , the Items property is null . Why a...
string xml = @ '' < list name= '' '' Groceries '' '' > < add key= '' '' 1 '' '' value= '' '' Milk '' '' / > < add key= '' '' 2 '' '' value= '' '' Eggs '' '' / > < add key= '' '' 3 '' '' value= '' '' Bread '' '' / > < /list > '' ; public class List : ConfigurationElement , IXmlSerializable { [ ConfigurationProperty ( ``...
C # - Xml Deserialization of KeyValueConfigurationCollection
C#
I have been trying to read data from the Twitter stream API using C # , and since sometimes the API will return no data , and I am looking for a near-realtime response , I have been hesitant to use a buffer length of more than 1 byte on the reader in case the stream does n't return any more data for the next day or two...
input.BeginRead ( buffer , 0 , buffer.Length , InputReadComplete , null ) ; //buffer = new byte [ 1 ]
Consuming a HTTP stream without reading one byte at a time
C#
Is there a way to mark a type ( or even better , an interface ) so that no instances of it can be stored in a field ( in a similar way to TypedReference and ArgIterator ) ? In the same way , is there a way to prevent instances from being passed through anonymous methods and -- In general -- To mimic the behavior of the...
using System ; unsafe static class Program { static TypedReference* _tr ; static void Main ( string [ ] args ) { _tr = ( TypedReference* ) IntPtr.Zero ; } }
Make type 's instances non-storable
C#
[ Edit : It looks like the original question involved a double and not an integer . So I think this question stands if we change the integer to a double . ] I have rare issue with reading integer properties from a class used in multiple threads that sometimes returns a zero value . The values are not changed after init...
public class ConfigInfo { private readonly object TimerIntervalLocker = new object ( ) ; private int _TimerInterval ; public int TimerInterval { get { lock ( TimerIntervalLocker ) { return _TimerInterval ; } } } private int _Factor1 ; public int Factor1 { set { lock ( TimerIntervalLocker ) { _Factor1 = value ; _TimerIn...
What is a best practice for making a class 's properties thread safe ?
C#
For example , consider this : The eventStream is a long lived source of events . A short lived client will use this method to subscribe for some period of time , and then unsubscribe by calling Dispose on the returned IDisposable.However , while the eventStream still exists and should be kept in memory , there has been...
public IDisposable Subscribe < T > ( IObserver < T > observer ) { return eventStream.Where ( e = > e is T ) .Cast < T > ( ) .Subscribe ( observer ) ; }
Do 'Intermediate IObservables ' without final subscribers get kept in memory for the lifetime of the root IObservable
C#
The above compiles , but ... Does not.Replacing it with : Will obviously compile though . Is this inconsistancy or am i being stupid , or am i just wrong : S .
private string [ ] GetRoles ( ) { string [ ] foo = { `` Test '' } ; return foo ; } private string [ ] GetRoles ( ) { return { `` Test '' } ; } return new string [ ] { `` Test '' } ;
Inconsistent syntax c # ?
C#
I work for myself , I am a self-employed coder and as a result I do n't have the luxury of code reviews or the ability to improve based upon peer programming . I am going to use this as an exercise to see if the StackOverflow community might help to review a simple method which i 've written ; This is a method that tak...
internal static DateTime CONVERT_To_DateTime ( int binDate ) { // 3/10/2008 = 1822556159 // 2/10/2008 = 1822523391 // 1/10/2008 = 1822490623 // 30/09/2008 = 1822392319 // 29/09/2008 = 1822359551 // September 30th 2008 // 1822392319 = 0x6c9f7fff // 0x6c = 108 = 2008 ( based on 1900 start date ) // 0x9 = 9 = September //...
Refactor for Speed : Convert To a Date
C#
I have the following C # code which initializes a new dictionary with int keys and List < string > values : If I decompile an executable made from this snippet back to C # the corresponding part looks like this : Everything seems normal and is working properly here.But when I have the following code : which again seems...
var dictionary = new Dictionary < int , List < string > > { [ 1 ] = new List < string > { `` str1 '' , `` str2 '' , `` str3 '' } , [ 2 ] = new List < string > { `` str4 '' , `` str5 '' , `` str6 '' } } ; Dictionary < int , List < string > > expr_06 = new Dictionary < int , List < string > > ( ) ; expr_06 [ 1 ] = new Li...
Dictionary initializer has different behavior and raises run-time exception when used in combination of array initializer
C#
Suppose I initialize members of a class like this : Does the compiler generate a default constructor in this situation ? In general , I know that a constructor may initialize the value of class instance variables and may also perform some other initialization operations appropriate for the class . But in the above exam...
class A { public int i=4 ; public double j=6.0 ; }
In C # , is a default constructor generated when class members are initialized ?
C#
I 'm writing a bunch of unit tests for my ASP.NET MVC app using Entity Framework ( against a SQL Server database ) .I 'm using Rowan Miller 's excellent Nuget packages `` EntityFramework.Testing '' and `` EntityFramework.Testing.Moq '' to allow me to unit test EF code ( without actually having a real SQL Server databas...
[ TestFixture ] public class ContactsUseCaseTests : MyUnitTestBase { private Mock < MyModel > _mockDbContext ; private MockDbSet < Contact > _mockDbSetContact ; private IContactsUseCase _usecase ; [ SetUp ] public void InitializeTest ( ) { SetupTestData ( ) ; _usecase = new ContactsUseCase ( _mockDbContext.Object ) ; }...
Unit-testing EF 's state management code
C#
This is a constructor in one of my classes : The Code Contracts static checker flags an error : warning : CodeContracts : ensures is false : PrereleaseVersion ! = nullMaybe < T > is a collection containing zero or one elements.As far as I can see , the only way that can be null is if there 's an exception before it is ...
public SemanticVersion ( string version ) { Contract.Requires < ArgumentException > ( ! string.IsNullOrEmpty ( version ) ) ; Contract.Ensures ( MajorVersion > = 0 ) ; Contract.Ensures ( MinorVersion > = 0 ) ; Contract.Ensures ( PatchVersion > = 0 ) ; Contract.Ensures ( PrereleaseVersion ! = null ) ; Contract.Ensures ( ...
Why does Code Contracts claim that `` Ensures is false '' for this code ?
C#
I 'm trying to convert this C # code to C++ : Pretty clear this calls for std : :function . Since this is a larger project I used a tool to do all the conversion and this is what it came up with : I assumed using std : :function < void ( ) > is a translation error , so I changed them to Action . So , my final version i...
public delegate void Action < in T > ( T obj ) ; public delegate void Action < in T1 , in T2 > ( T1 arg1 , T2 arg2 ) ; public delegate void Action < in T1 , in T2 , in T3 > ( T1 arg1 , T2 arg2 , T3 arg3 ) ; # include < functional > template < typename T > //C # TO C++ CONVERTER TODO TASK : C++ does not allow specifying...
C # to C++11 conversion : delegate templates
C#
I am trying to setup blazor server side but I keep getting this problem when trying to install itfollowing this tutorial from microsoft and I get this error in powershell window
PS D : \blazorTesting > dotnet new blazorserverside -o WebApplicationServerSideUsage : new [ options ] Options : -h , -- help Displays help for this command . -l , -- list Lists templates containing the specified name . If no name is specified , lists all templates . -n , -- name The name for the output being created ....
Unable to determine the desired template from the input template name : blazorserverside
C#
I wrote the following test ( actually used in a wider context ) Why does n't the task manager show any sign of the allocated 100 megabytes before the first key press ? If this is by design , how else can I test the consumption of unmanaged heap memory ?
IntPtr x = Marshal.AllocHGlobal ( 100000000 ) ; Console.Write ( `` Press any key to continue . . . `` ) ; Console.ReadKey ( true ) ; Marshal.FreeHGlobal ( x ) ; Console.ReadKey ( true ) ;
Unmanaged memory not showing up in task manager
C#
I was perusing the .Net Reference Source and found this gem in ButtonBase.cs at line 408 : Question being , what would motivate someone to use the exceptionThrown flag over just writing it as Is it just stylistic or is there some side-effect I am missing ?
bool exceptionThrown = true ; try { OnClick ( ) ; exceptionThrown = false ; } finally { if ( exceptionThrown ) { // Cleanup the buttonbase state SetIsPressed ( false ) ; ReleaseMouseCapture ( ) ; } } try { OnClick ( ) ; } catch { SetIsPressed ( false ) ; ReleaseMouseCapture ( ) ; throw ; }
Is there a reason for using Try/Finally with ExceptionThrown variable over Try/Catch
C#
In C # , will the folloing code throw e containing the additional information up the call stack ?
... catch ( Exception e ) { e.Data.Add ( `` Additional information '' , '' blah blah '' ) ; throw ; }
Exception throwing
C#
I have looked , but could n't find a definitive answer for some of my exception questions , especially regarding C # best practices.Perhaps I will always be confused about the best way to use exceptions , I ran across this article which basically says 'always use exceptions , never use error codes or properties ' http ...
//try to log in and get SomeException catch ( SomeException ex ) { throw new SomeException ( `` Login failed '' , ex ) ; } ... //try to send a file and get SomeExceptioncatch ( SomeException ex ) { throw new SomeException ( `` Sending file failed '' , ex ) : }
Mixing errors and exceptions in C #
C#
I want to make an SS application . But I have problem on this subject . I want user to be able to select a special area to take screenshot . I also want the desktop is live while the user is selecting the area . For example user wants to take an SS of a video 's specific frame . The user must be able to do this while v...
[ DllImport ( `` User32.dll '' ) ] static extern IntPtr GetDC ( IntPtr hwnd ) ; [ DllImport ( `` user32.dll '' ) ] static extern bool InvalidateRect ( IntPtr hWnd , IntPtr lpRect , bool bErase ) ; public Form1 ( ) { InitializeComponent ( ) ; this.Load += Form1_Load ; } void Form1_Load ( object sender , EventArgs e ) { ...
How to do a screenshot area selection by drawing on desktop to take screenshot ?
C#
I have a rather simple LDAP client that works ok when connecting to the 389 port ( LDAP ) but fails with a `` LDAP server unavailable '' when I try to connect to the 636 port ( LDAPS ) .If I add the following at [ CODE MODIFICATION HERE ] to accept all server certificates , it works : The certificate is signed by a sel...
namespace MyNS { class ProgramLdap { private static LdapConnection CreateConnection ( String baseDn , string usuario , string password ) { LdapConnection ldapConnection = new LdapConnection ( new LdapDirectoryIdentifier ( `` myserver.example '' , 636 , true , false ) ) ; ldapConnection.SessionOptions.SecureSocketLayer ...
.Net program does not get validated server certificate
C#
The documentation of constant pattern matching with the is-operator ( expr is constant ) states : The constant expression is evaluated as follows : If expr and constant are integral types , the C # equality operator determines whether the expression returns true ( that is , whether expr == constant ) .Otherwise , the v...
public bool IsZero ( int value ) { return value is 0 ; } .method public hidebysig instance bool IsZero ( int32 'value ' ) cil managed { .maxstack 8 ldarg.1 ldc.i4.0 ceq ret } .method public hidebysig instance bool IsZero ( int32 'value ' ) cil managed { .maxstack 8 ldc.i4.0 box [ mscorlib ] System.Int32 ldarg.1 box [ m...
Why does the is-operator cause unnecessary boxing ?
C#
I have a class of 3 different linked lists ( for saving the entities in a game I 'm working on ) . The lists are all of objects with the same base type , but I keep them separate for processing reasons . Note that IEntity , IObject and IUndead all inherited from IEntity.I have 3 methods for retrieving each of the lists...
public class EntityBucket { public LinkedList < IEntity > undeadEntities ; public LinkedList < IEntity > objects ; public LinkedList < IEntity > livingEntities ; public EntityBucket ( ) { undeadEntities = new LinkedList < IEntity > ( ) ; objects = new LinkedList < IEntity > ( ) ; livingEntities = new LinkedList < IEnti...
C # , generic way to access different lists within a class
C#
We had a bit of an incident today which has got me thinking . We have a project with a pretty standard web.config transform setup for our various configs . There is a section which controls access to our DAO services which looks like this : And a transform like this : Hopefully you will have spotted the error here - th...
< endpoint address= '' http : //myserver/myservice1.svc/basicHttp '' binding= '' basicHttpBinding '' contract= '' MyAssembly.IItem '' name= '' DataAccessEndPoint '' kind= '' '' endpointConfiguration= '' '' / > < endpoint address= '' http : //myserver/myservice2.svc/basicHttp '' binding= '' basicHttpBinding '' contract=...
Failing web.config transform when no value exists for a transform
C#
I 'm working on a project where the MongoDB model will be similar to Facebook . So we all know how FB works , a user `` likes '' a band/company page , and that user will see all the posts from that page.Is the below model how I should design this ? If a Page has million likes , then each Post will have a million sub do...
public class Person { public ObjectId Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } } public class Page { public ObjectId Id { get ; set ; } public string Name { get ; set ; } public List < Like > PersonLikes { get ; set ; } } public class Like { public ObjectId Id { ...
C # mongodb model like Facebook
C#
I 'm attempting to use CryptUnprotectData to read a password protected using CryptProtectData into a SecureString and use that to connect to a database . I can get the correct password out , but trying to create a new SqlConnection after that fails with the following : It 's enough to simply call CryptUnprotectData for...
System.TypeInitializationException was unhandled HResult=-2146233036 Message=The type initializer for 'System.Data.SqlClient.SqlConnection ' threw an exception . Source=System.Data TypeName=System.Data.SqlClient.SqlConnection StackTrace : at System.Data.SqlClient.SqlConnection..ctor ( ) at System.Data.SqlClient.SqlConn...
P/Invoke CryptUnprotectData breaks SqlConnection constructor
C#
IEnumerable does not guarantee that enumerating twice will yield the same result . In fact , it 's quite easy to create an example where myEnumerable.First ( ) returns different values when executed twice : This is not just an academic example : Using the popular from ... in ... select new A ( ... ) will create exactly...
class A { public A ( string value ) { Value = value ; } public string Value { get ; set ; } } static IEnumerable < A > getFixedIEnumerable ( ) { return new A [ ] { new A ( `` Hello '' ) , new A ( `` World '' ) } ; } static IEnumerable < A > getDynamicIEnumerable ( ) { yield return new A ( `` Hello '' ) ; yield return n...
Is there a canonical way to `` fix '' a `` dynamic '' IEnumerable ?
C#
I have a Windows Forms application where I need to make all fonts of all UI elements configurable from a separate file . I.e . I want to be able to specify that a label has a font `` TitleBarBoldFont '' which would resolve to a real font , depending on the current locale . The configuration file may contain a correspon...
< Font fontID= '' TitleBarBoldFont '' > < Display facename= '' Helvetica '' pointSize= '' 12 '' > < Override lang= '' ja '' facename= '' Meiryo Bold '' pointSize= '' 12 '' / > < Override lang= '' zh '' facename= '' SimHei '' pointSize= '' 12 '' / > < Override lang= '' ru '' facename= '' Arial Bold '' pointSize= '' 12 '...
Looking for the optimal way to use custom font definitions in WinForms application
C#
suppose this is my txt file : im reading content of this file with : Now i want to read data in stdList , but read only value every 2 line ( in this case i 've to read `` line2 '' and `` line4 '' ) .can anyone put me in the right way ?
line1line2line3line4line5 string line ; List < string > stdList = new List < string > ( ) ; StreamReader file = new StreamReader ( myfile ) ; while ( ( line = file.ReadLine ( ) ) ! = null ) { stdList.Add ( line ) ; } finally { //need help here }
reading string each number c #
C#
This is a question for a job application : '' A father has two sons and 999 paintings . Each painting has a different value : first is worth 1 , second is worth 2 and so on , until the final painting is worth 999 . He would like to divide all of his paintings to his two sons , so that each son gets equal value . How ma...
StringBuilder sb = new StringBuilder ( ) ; for ( short i = 2 ; i < = 999 ; i++ ) //starts from 2 because 1 is always added to the total for one side { sb.AppendLine ( `` for ( byte i '' + i.ToString ( ) + `` = 0 ; i '' + i.ToString ( ) + `` < 2 ; i '' + i.ToString ( ) + `` ++ ) '' ) ; sb.AppendLine ( `` { `` ) ; } for ...
Father , two sons , 999 paintings
C#
I 'm trying to load some .dll files dynamically . The Files are Plugins ( self-written for now ) which have at least one class that implements MyInterface . For each file I 'm doing the following : Running this causes a cast exception , but I ca n't find a workaround . Anyway I am wondering why this does n't work at al...
Dictionary < MyInterface , bool > _myList ; // ... code Assembly assembly = Assembly.LoadFrom ( currentFile.FullName ) ; foreach ( Type type in assembly.GetTypes ( ) ) { var myI = type.GetInterface ( `` MyInterface '' ) ; if ( myI ! = null ) { if ( ( myI.Name == `` MyInterface '' ) & & ! type.IsAbstract ) { var p = Act...
C # cast a class to an Interface List
C#
I 'm currently working on some C # /C++ code which makes use of invoke . In the C++ side there is a std : :vector full of pointers each identified by index from the C # code , for example a function declaration would look like this : But now I 'm thinking , since I 'm working with pointers could n't I sent to C # the p...
void SetName ( char* name , int idx ) void SetName ( char*name , int ptr ) { ( ( TypeName* ) ptr ) - > name = name ; }
Is it safe to keep C++ pointers in C # ?
C#
I have seven words in the array : the x is generated from another array : that means each x can be either a or b or c or d. It is randomly generated . this could be an example : my question is how can I check if there are five x which has the same value ? This is for a poker app Im working on .
string [ 7 ] = { x , x , x , x , x , x , x } ; string [ 4 ] = { a , b , c , d } ; string [ 7 ] = { a , a , d , a , a , c , a }
Compare 7 words to eachother to see if 5 of them are equal . How ?
C#
I have a C # app that uses a custom section for configuration . I have that section of XML defined as a string . The string looks like this : This XML matches the schema defined by the classes I described here . When I pass the above string to the Departments.Deserialize method , I receive an error . The error says : `...
var xml = @ '' < departments > < department id= '' '' 1 '' '' name= '' '' Sporting Goods '' '' > < products > < product name= '' '' Basketball '' '' price= '' '' 9.99 '' '' > < add key= '' '' Color '' '' value= '' '' Orange '' '' / > < add key= '' '' Brand '' '' value= '' '' [ BrandName ] '' '' / > < /product > < /prod...
Unable to Deserialize XML in C # - Unrecgnized element 'add '
C#
I am developing a windows application using c # . I am loading a file ( html , txt , xhtml ) to the text box . I want to test the occurrence of following cases in my text box.For all the occurrences of the above condition I want to highlight the particular found text in the textbox . I am trying to use the regular expr...
, ( comma ) with closeup text ( ex . text1 , text2 ) . ( dot ) with closeup text ( ex . text1.text2 ) : ( colon ) with closeup text ( ex . text1 : text2 ) , ( comma ) with closeup ' i.e ( left single quotation mark ) '' ( doublequote ) with closeup text ' ( single quote ) with closeup text < /i > with closeup text ( ex...
Multiple occurrence of regular expression in a multiline textbox
C#
I have a strange problem and it 's been frustrating me for the past few hours . I ca n't seem to find anything related ; perhaps I 'm not being specific enough , as I 'm not sure how to word it correctly , or it 's a strangely unique problem.There 's a form a user fills in to update their account information , everythi...
public ActionResult Edit_Information ( long id ) { // Get user info from the database . // Return the view with the user info from the DB etc . } [ HttpPost ] public ActionResult Edit_Information ( long id , UserInfo userInfo ) { if ( ! this.ModelState.IsValid ) { // Invalid return View ( userInfo ) ; } // Update the i...
That text area of nullness
C#
I have the following line of code : Exists on the left hand side is a property of the User class . Its type is just bool , not bool ? . The Exists method on the right hand side is an API method to check if a given entity exists in the repository . It returns Task < bool > . I want to check if the repository is null fir...
user.Exists = await this.repository ? .Exists ( id ) ;
Why can the null conditional operator be used when setting the value of a bool without using a nullable bool ?
C#
Consider the following : The first Write in DoItAsync ( ) executes.SomeLongJobAsync ( ) starts.The WriteLine in DoItAsync ( ) executes.DoItAsync ( ) pauses while SomeLongJobAsync ( ) works away until it 's done.SomeLongJobAsync ( ) completes , so DoItAsync ( ) returns.Meanwhile , the UI is responsive.On what thread doe...
private async void btnSlowPoke_Click ( object sender , EventArgs e ) { await DoItAsync ( ) ; } private async Task < int > SomeLongJobAsync ( ) { for ( int x = 0 ; x < 999999 ; x++ ) { //ponder my existence for one second await Task.Delay ( 1000 ) ; } return 42 ; } public async Task < int > DoItAsync ( ) { Console.Write...
Where do 'awaited ' tasks execute ?
C#
As you probably know in D language we have an ability called Voldemort Types and they are used as internal types that implement particular range function : Here is how the Voldemort type can be used : Now I want to make sure that , Is this the equivalent to delegate in C # ?
auto createVoldemortType ( int value ) { struct TheUnnameable { int getValue ( ) { return value ; } } return TheUnnameable ( ) ; } auto voldemort = createVoldemortType ( 123 ) ; writeln ( voldemort.getValue ( ) ) ; // prints 123 public static void Main ( ) { var voldemort = createVoldemortType ( 123 ) ; Console.WriteLi...
Voldemort types in C #
C#
I 'm currently trying to bulkinsert a datatable into a database . It works fine and fast . The only problem occursif there are any rows that are already in the database ( duplicate key ) . To counter this I have modified my program so that I first check for each new entry if it already exists in the database or not.Whi...
DataTable transactionTable.Columns.Add ( `` DeviceId '' , typeof ( Int32 ) ) ; transactionTable.Columns.Add ( `` LogDate '' , typeof ( DateTime ) ) ; transactionTable.Columns.Add ( `` LogType '' , typeof ( Int32 ) ) ; transactionTable.Columns.Add ( `` LogText '' , typeof ( String ) ) ; transactionTable.PrimaryKey = new...
How to fast reduce a datatable according to existing entries in a DB
C#
This issue has been on/off bugging me and I 've written 4 wrappers now . I 'm certain I 'm doing it wrong and need to figure out where my understanding is branching off.Let 's say I 'm using the Rectangle class to represent bars of metal . ( this works better then animals ) So say the base class is called `` Bar '' .So...
private class Bar { internal Rectangle Area ; } private Bar CreateBar ( ) { Bar1 = new Bar1 ( ) ; Bar1.Area = new Rectangle ( new Point ( 0,0 ) , new Size ( 300,10 ) ) ; return Bar1 ; } private class SteelBar : Bar { string Material ; } private SteelBar CreateSteelBar ( ) { SteelBar SteelB = new SteelB ( ) ; Bar B = Cr...
C # base inheritance
C#
Is there any performance benefit to explicitly calling a method directly from a namespace class library rather than using the namespace ? Here is an example of a situation I 'm referring to : vs .
// usingusing System.Configuration ; public class MyClass { private readonly static string DBConn = ConfigurationManager.ConnectionStrings [ `` DBConn '' ] .ConnectionString ; } //explicitpublic class MyClass { private readonly static string DBConn = System.Configuration.ConfigurationManager.ConnectionStrings [ `` DBCo...
Is there a performance difference between using a namespace vs explicitly calling the class from the namespace ?
C#
Having How can I translate for ( x = 0 ; x < 1ULL < < ( 2*k ) ; ++x ) unsigned long long 1ULL and bitwise to c # ? I was tryingHow to translate that parts of code x < 1ULL < < ( 2*k ) ; and `` ACGT '' [ y & 3 ] ?
int i , k ; unsigned long long x , y ; k = 5 ; for ( x = 0 ; x < 1ULL < < ( 2*k ) ; ++x ) { for ( i = 0 , y = x ; i < k ; ++i , y > > = 2 ) putchar ( `` ACGT '' [ y & 3 ] ) ; putchar ( '\n ' ) ; } public static ulong aux ( int val ) { ulong result = ? ? ? ? ? < < val ; return result ; } public static void main ( ) { in...
translate C unsigned long long and bitwise in for loop to c #
C#
I would like to know if there 's a specific constraint for numerical types that allows casting to work in the following case : I tried boxing and unboxing like : But this only works if T == byte . Otherwise I get an InvalidCastException.T is always a number type ( like short , float , and so on ) .
class MyClass < T > { ... void MyMethod ( ) { ... . byte value = AnotherObject.GetValue ( ) Tvalue = ( T ) value ; ... . } ... } Tvalue = ( T ) ( object ) value ;
Converting numerical concrete type to numerical generic type
C#
After a bit of programming one of my classes used generics in a way I never seen before . I would like some opinions of this , if it 's bad coding or not.is this an OK use of generics or not ? I 'm mostly thinking about the constraint to `` itself '' . I sometimes feel like generics can `` explode '' to other classes w...
abstract class Base < T > : where T : Base < T > { // omitted methods and properties . virtual void CopyTo ( T instance ) { /*code*/ } } class Derived : Base < Derived > { override void CopyTo ( Derived instance ) { base.CopyTo ( instance ) ; // copy remaining stuff here } }
Weird use of generics
C#
I am trying to write documentation comments however I have a problem.When I reach the < T > Visual studio thinks I am trying to add another tag . what is the correct way to add comments like that ( and if I could make them click able in the generated help text that would be a extra bonus )
/// < summary > /// Inserts an element into the System.Collections.Generic.List < T > at the specified/// index./// < /summary >
How to add items enclosed by < > to documentation comments
C#
I am working on a calculation module using C # , and I bumped on this : I know this is a wrong initialization that returns v = 0.0 instead of v = 0.04The c # rules says I must ensure at least one of the member is a double , like this : However , I have many many initializations of that kind that involves integer variab...
double v = 4 / 100 ; double v = ( double ) 4 / 100 ; double v = 4.0 / 100 ;
How to be warned about potential arithmetic errors due to type conversion ?
C#
I 'm using .NET 4.8 and declare a record with a Deconstructor : Then I use the following code which is compiled and it works fine : While this code does n't work an error is generated : '' Error CS0029 Can not implicitly convert type 'ConsoleApp4.Product ' to 'System.Tuple < string , int > ' '' ) : The declaration var ...
public record Product { public string Name { get ; } public int CategoryId { get ; } public Product ( string name , int categoryId ) = > ( Name , CategoryId ) = ( name , categoryId ) ; public void Deconstruct ( out string name , out int categoryId ) = > ( name , categoryId ) = ( Name , CategoryId ) ; } var product = ne...
What is the variable declaration `` var ( name , categoryId ) = object '' called in C # ?
C#
I am trying to make a regex match which is discarding the lookahead completely . This is the match and this is my regex101 test.But when an email starts with - or _ or . it should not match it completely , not just remove the initial symbols . Any ideas are welcome , I 've been searching for the past half an hour , but...
\w+ ( [ -+. ] \w+ ) * @ \w+ ( [ -. ] \w+ ) *\.\w+ ( [ - . ] \w+ ) *
Regex lookahead discard a match
C#
I 'm currently programming my own implementation of priority queue / sorted list and I would like to have it concurrent.In order to have it thread safe I 'm using lock ( someObject ) and I would like to verify some behavior of mutexes in C # .Inner representation of my sorted list is basically linked list with head and...
internal class Slot { internal T Value ; internal Slot Next ; public Slot ( T value , Slot next = null ) { Value = value ; Next = next ; } } public IEnumerator < T > GetEnumerator ( ) { lock ( syncLock ) { var curr = head ; while ( curr ! = null ) { yield return curr.Value ; curr = curr.Next ; } } }
Concurrent collection enumerator
C#
I 'm having a brain fart trying to make the following method more generic such that any List < T > can be passed in for the columnValues parameter . Here 's what I have : I could change it to a List < object > and convert the original list prior to passing it to the method but I 'm sure there is a better option : - ) E...
public static DataRow NewRow ( this DataTable dataTable , List < string > columnValues ) { DataRow returnValue = dataTable.NewRow ( ) ; while ( columnValues.Count > returnValue.Table.Columns.Count ) { returnValue.Table.Columns.Add ( ) ; } returnValue.ItemArray = columnValues.ToArray ( ) ; return returnValue ; }
How can I make this extension method more generic ?
C#
For example , we know that `` int '' type in C # is nothing but a structure which is actually System.Int32 . If that so , then if `` using system ; '' is commented in a program , then int type should not be able to use . But still int type can be used . My question is , from where these types are coming from ?
//using System ; class Program { static void Main ( ) { int x = 0 ; // it still work , though int is under System namespace , why ? ? } }
In C # where does the key words come from if `` using system '' is commented ?
C#
I am building a POC application using the new MIP SDK on C # . One of the requirements is to use username/password stored on the server . All the example applications are using OAuth2 login with a popup window for user credentials input.I believe that properly implementing the IAuthDelegate may help , but in-line docum...
var authDelegate = new AuthDelegateImplementation ( appInfo ) ; //Initialize and instantiate the File Profile //Create the FileProfileSettings object var profileSettings = new FileProfileSettings ( path : `` mip_data '' , useInMemoryStorage : true , authDelegate : authDelegate , consentDelegate : new ConsentDelegateImp...
Microsoft Information Protection SDK : using username/password to login
C#
I 'm new using .NET MVC Web Application . I 'm using the version 4 of Web Application.I 'm developing a page to manage the roles of the simple membership provider , and I want to it be dynamically . To clear what I mean , it would be something like this : Something really simple as that . To do so , I have a complex Vi...
public class UserInRolesModel { public List < string > AllRoleNames { get ; set ; } public List < UserInRoles > UsersInRoles { get ; set ; } public UserInRolesModel ( ) { AllRoleNames = new List < string > ( ) ; UsersInRoles = new List < UserInRoles > ( ) ; } public UserInRolesModel ( List < string > allRoleNames , Lis...
Binding issue in a list at a complex model to an mvc application
C#
The argument to my function f ( ) must implement two different interfaces that are not related to each other by inheritance , IFoo and IBar . I know of two different ways of doing this . The first is to declare an empty interface that inherits from both : This , of course , requires that the classes declare themselves ...
public interface IFooBar : IFoo , IBar { // nothing to see here } public int f ( IFooBar arg ) { // etc . } public int f < T > ( T arg ) where T : IFoo , IBar { // etc . }
C # : Preferred pattern for functions requiring arguments that implement two interfaces
C#
We are trying to use an IEnumerable as a factory that generates different objects each time we iterate over it . Those should be GC'ed as soon as possible . Note however that we keep a reference to the enumerator so we can call it again . So our program basically looks like this : Looking at that code in the debugger :...
public class YieldSpec { public static IEnumerable < string > Strings ( ) { yield return `` AAA '' ; yield return `` BBB '' ; yield return `` CCC '' ; } public void YieldShouldAllowGC ( ) { var e = Strings ( ) ; foreach ( var a in e ) { Console.WriteLine ( a ) ; } } }
When using `` yield '' why does compiler-generated type implement both IEnumerable and IEnumerator
C#
I 've used try and catch statements as an easy way to keep my code running without things crashing ( I would wrap everything in a big try ) . Recently , I 've wanted to start using try and catch statements more correctly . Here as an example I have questions about : In the above Ninja class , the entire contents of my ...
public class Ninja { Ninja ( ) { } public void ThrowShirikin ( int numberOfShirikins ) { try { if ( numberOfShirikins == 0 ) { throw new System.ArgumentException ( `` Invalid number of shirikins '' ) ; } //Throw shirikin } catch ( ArgumentException e ) { MessageBox.Show ( e.Message ) ; } } } public class Ninja { Ninja ...
Question About Where To Position Try And Catch statements
C#
Is there such a thing as a LINQ Query Provider for querying C # files ? I have a Winforms app that I use to assist me in generating code as well as to supplement Visual Studio 's editing capabilities for existing code . One thing I would like to be able to do is to query a given class to see if a method exists . Or que...
static List < string > GetMethodList ( string filename , string className ) { var syntaxTree = SyntaxTree.ParseFile ( filename ) ; var root = syntaxTree.GetRoot ( ) ; var @ class = root.DescendantNodes ( ) .OfType < ClassDeclarationSyntax > ( ) .FirstOrDefault ( md = > md.Identifier.ValueText.Equals ( className ) ) ; r...
Is there a LINQ Query Provider for querying C # files ?
C#
I have two IQueryable collections having this kind of type Collection 1 , with the following Name values : Collection 2 , with the following Name values : What I would like to get is a third collection having Name values from Collections 1 and 2 matched , and if there is no match , than null ( empty ) , so as follows :...
public class Property { public string Name { get ; set ; } } A A A B A B B Result Collection : A AA null A null B B null B
C # Linq full outer join on repetitive values
C#
I 'm trying to generate a certificate self-signed by a KeyPair stored in Azure KeyVault.My end result is a certificate with an invalid signature : Generating the certificate parameters : Fetching a reference to the Azure KeyVault stored key ( HSM like service ) : The key is successfully retrieved.I then try to generate...
DateTime startDate = DateTime.Now.AddDays ( -30 ) ; DateTime expiryDate = startDate.AddYears ( 100 ) ; BigInteger serialNumber = new BigInteger ( 32 , new Random ( ) ) ; X509V1CertificateGenerator certGen = new X509V1CertificateGenerator ( ) ; X509Name selfSignedCA = new X509Name ( `` CN=Test Root CA '' ) ; certGen.Set...
Invalid signature when creating a certificate using BouncyCastle with an external Azure KeyVault ( HSM ) Key
C#
Suppose I want to be able to write queries likeWhere < Product > ( t= > t.Version > new Version ( 1,2,0,0 ) ) In Product table I store only Int64 NumVersion field , so Version property is mapped as component , and currently I query it like Where < Product > ( t= > t.Version.NumVersion > new Version ( 1,2,0,0 ) .NumVers...
public class Version { public byte Major { get ; set ; } public byte Minor { get ; set ; } public short Build { get ; set ; } public int Revision { get ; set ; } private long NumVersion { //get { } //set { } //Some logic that make Int64 number that represents this verion } } public static implicit operator long ( Versi...
NHibernate and operator overloading
C#
I 'm using Tridion 2011 's Event System to perform some additional actions when un-publishing components . I 'm using code found here to publish a related component.I 'm registering my event handler as follows : ... and my handler method is as follows : My problem is that the UnPublishEventArgs.Targets property is an I...
EventSystem.Subscribe < Component , UnPublishEventArgs > ( RemoveAndRepublish , EventPhases.Initiated ) ; public void RemoveAndRepublish ( Component cmp , UnPublishEventArgs args , EventPhases phase ) { // ... code to locate related component , and perform required actions ... var instruction = new PublishInstruction (...
How to get the ( un- ) PublicationTarget for component UnPublish event in Tridion 2011 ?
C#
This may be a rather long and involved question . Let me start by saying that I 'm developing in C # and XAML . I want to create a control that stacks the following template : for a sequence of items , in two columns , like so : Notice that they are ordered first by height and then left to right.This is relatively simp...
_____________| || Text || Image || More Text ||___________| ______ ______| | | || 1 | | 2 ||____| | || | |____|| 3 | | || | | 4 || | |____||____| | || | | 5 || 6 | | || |
Create two-column , vertically-stacked columns control for Windows Phone 8
C#
Can the compiler or processor reorder the following instructions so that another Thread sees a == 0 and b == 1 ? Assuming int a = 0 , b = 0 ; somewhere .
System.Threading.Interlocked.CompareExchange < int > ( ref a , 1 , 0 ) ; System.Threading.Interlocked.CompareExchange < int > ( ref b , 1 , 0 ) ;
.Net CompareExchange reordering
C#
Sanity-check here . Suppose I start a task but I do n't await it and I do n't store a reference to it . In other words , I just run : Clearly , without keeping a reference to the Task returned by PerformLongOperation ( ) , I have no way of knowing if and when it completes . But suppose that that 's not necessary in cer...
async Task PerformLongOperation ( ) { await Task.Delay ( 10 * 1000 ) ; Debug.WriteLine ( `` All done ! `` ) ; } void DoSomething ( ) { // Kick off the operation and allow it to complete when it does . PerformLongOperation ( ) ; }
Will a task ever be interrupted by garbage collection if there are no references to it ?
C#
I 'm a bit confused about the following.Given this class : Why is an InvalidCastException thrown when I try to do the following ?
public class SomeClassToBeCasted { public static implicit operator string ( SomeClassToBeCasted rightSide ) { return rightSide.ToString ( ) ; } } IList < SomeClassToBeCasted > someClassToBeCastedList = new List < SomeClassToBeCasted > { new SomeClassToBeCasted ( ) } ; IEnumerable < string > results = someClassToBeCaste...
C # .net casting question
C#
Recentelly I found an issue that at the beginning did n't appeared so dubious . Let me start by describing the big picture of my environment : I have a domain model respecting the Table Module architecture that consumes a data access layer written using Entity Framework 6.x . My application is a windows forms applicati...
public class PersonsModule { public List < Person > GetAllByCityId ( int cityId ) { using ( var ctx = new Container ( ) ) { return ( from p in ctx.Persons join addr in ctx.Addresses on p.AddressId equals addr.Id where addr.CityId == cityId select p ) .ToList ( ) ; } } } public class Determinator < TCollectionTypePerson...
Caching domain model data
C#
In Visual Studio Professional 2010 whenever I type the following : It automatically changes to : Is there a way to make it not do this ? `` Object '' does not have the properties of the object I want to anonymously create .
new { new object {
Visual Studio Professional 2010 : Stop `` new { `` from autocompleting into `` new object { `` ( C # )
C#
I have a C # program that has a list that does writes and reads in separate threads . The write is user initiated and can change the data at any random point in time . The read runs in a constant loop . It does n't matter if the read is missing data in any given loop , as long as the data it does receive is valid and i...
static List < string > constants = new List < string > ( ) ; //Thread Apublic void UserInputHandler ( List < string > userProvidedConstants ) { lock ( items ) { items.Clear ( ) ; foreach ( var constant in userProvidedConstants ) { constants.Add ( constant ) ; } } } //Thread Bpublic void DoStuff ( ) { lock ( items ) { /...
Thread Safety : Lock vs Reference
C#
When I use asp-controller and asp-action in a < a > tag for another Action than the current , in a View called by a Controller Method with a [ Route ] attribute , the generated link have an empty href attribute.In the Controller : In the View : Generated html : As you can see , the first link is not generated correctly...
public class ForumController : Controller { [ Route ( `` [ action ] / { sectionId : int } '' ) ] public async Task < IActionResult > ShowSection ( int sectionId ) { //some code } } < a asp-controller= '' Forum '' asp-action= '' Index '' > Index < /a > < a asp-controller= '' Forum '' asp-action= '' ShowSection '' asp-ro...
Strange behaviour between tag-helpers and Route attribute in asp.net 5 MVC6
C#
I am facing a problem in which I need to transform dates in a given input format into a target one . Is there any standard way to do this in C # ? As an example say we have yyyy.MM.dd as the source format and the target format is MM/dd/yyy ( current culture ) .The problem arises since I am using a parsing strategy that...
DateTime.Convert ( 2015.12.9 , 'yyyy/MM/dd ' , CultureInfo.CurrentCulture ) . DateTime.ParseExact ( `` 2015.12.9 '' , `` yyyy.MM.dd '' , CultureInfo.CurrentCulture )
Transform between datetime formats
C#
I have some classes in C # which I would like to use them in pipelines , I 've seen articles about it but I have n't been able to do it yet.Here 's how I am using it right now : And I want to be able to use it like this with pipelines : Here are my C # classes : And I am struggling to make these function available to c...
$ suite = [ MyProject.SuiteBuilder ] : :CreateSuite ( 'my house ' ) $ houseSet = $ suite.AddSet ( 'doors ' , 'These represents doors ' ) $ houseSet.AddOption ( 'blue ' , 'kitchen ' ) $ houseSet.AddOption ( 'black ' , 'bedreoom ' ) $ houseSet.AddOption ( 'white ' , 'toilet ' ) $ suite = [ MyProject.SuiteBuilder ] : :Cre...
Create PowerShell Cmdlets in C # - Pipeline chaining
C#
Can someone tell me the difference the following two LINQ statements please ? andChkUnique ! = null returns false for the top one when a match can not be found and true for the latter and I ca n't figure out why this is happening.I 'm new to LINQ so I could have missed something really basic but its driving me nuts at ...
var ChkUnique = DB.BusinessFile.FirstOrDefault ( c = > c.ROCNo == txtBoxID.Text ) ; var ChkUnique = from c in DB.BusinessFile where c.ROCNo == ( string ) txtBoxID.Text select c ;
LINQ - Different syntax style , different result ?
C#
Recently , in a book i read this code . Can you define the means of this code and how this code works .
int i = 0 ; for ( ; i ! = 10 ; ) { Console.WriteLine ( i ) ; i++ ; }
How this looping works in c #
C#
Why does System.Convert has ToDateTime that accepts DateTime ? The method documentation states the value remain unchanged .
//// Summary : // Returns the specified System.DateTime object ; no actual conversion is performed.//// Parameters : // value : // A date and time value.//// Returns : // value is returned unchanged.public static DateTime ToDateTime ( DateTime value ) ;
Why does System.Convert has ToDateTime that accepts DateTime ?
C#
There are a lot of questions on SO lamenting the fact that Code Analysis rule CA2000 is being applied possibly too rigorously by VS2010 , but I seem to have run into a case where it should be applied , but isn't.Consider the following code : Now if I run Code Analysis in Visual Studio 2010 on this , it will complain ab...
Image srcImage = Image.FromFile ( source ) ; Bitmap newImage = new Bitmap ( newWidth , newHeight ) ; using ( Graphics gr = Graphics.FromImage ( newImage ) ) { gr.DrawImage ( srcImage , new Rectangle ( 0 , 0 , newWidth , newHeight ) ) ; } newImage.Save ( destination , ImageFormat.Jpeg ) ;
Why does Bitmap cause rule CA2000 , but Image does not ?
C#
I have a method that takes a generic parameter T. Internally , to decide what other methods to call , I need to know ( without constraining it ) if that parameter is a List or just something.How do I do that ? I 've been using but that feels like a dirty approach . What 's cleaner ?
var isList = typeof ( T ) .Name.ToLower ( ) .Contains ( `` list ` 1 '' ) ;
Is my generic type a list , or just an item ?
C#
After reading this article & that article - I got confused.It says : If there are two methods at different levels of the hierarchy , the `` deeper '' one will be chosen first , even if it is n't a `` better function member '' for the call.Also - It turns out that if you override a base class method in a child class , t...
public class Base { public virtual void Foo ( int x ) { `` 1 '' .Dump ( ) ; } } public class Child : Base { public void Foo ( object x ) { `` 3 '' .Dump ( ) ; } public override void Foo ( int x ) { `` 2 '' .Dump ( ) ; } } void Main ( ) { Child c = new Child ( ) ; c.Foo ( 10 ) ; //emits 3 } public class Base { public vi...
Overloading across inheritance boundaries in c # ?
C#
We are using BasicHttpBinding in a service and also we have set the concurrency mode to multiple and instance context mode to single like belowWe have consumed this service in console through reference . We are having an issue that after some time we are seeing messages are pilled in IIS worker process.For example - > ...
[ ServiceBehavior ( InstanceContextMode=InstanceContextMode.Single , ConcurrencyMode =ConcurrencyMode.Multiple ) ] public class Service1 : IService1 < binding name= '' BasicHttpBinding_Common '' closeTimeout= '' 00:10:00 '' openTimeout= '' 00:10:00 '' receiveTimeout= '' 00:10:00 '' sendTimeout= '' 00:10:00 '' allowCook...
Requests are piling up in WCF IIS server
C#
Are there any way to turn of the autoformatting of C # code that is inlined inside HTML when making a MVC application ? It seems that it use the C # Text Editor settings for the inline code as well , but I do n't want to use the same formatting inside the HTML file as the normal code files.For example , if I write < % ...
< % using ( Html.BeginForm ( ) ) { % > ... < % } % > < % using ( Html.BeginForm ( ) ) { % > ... < % } % >
Autoformating of inline code in MVC
C#
Ok , I must be doing something dumb , but should n't this work ? I have following three lists : Each list has the proper values and count . I can return any one of these lists : And I can return a any two of these lists : However , when I try to return all three : I get the exception : Unable to create a constant value...
var commonViews = ( from v in context.TPM_VIEWS where v.VIEWID < 0 select v ) ; // IQueryable < TPM_VIEWS > var ownedViews = ( from v in context.TPM_VIEWS where v.OWNERID == userId & & v.VIEWID > 0 select v ) ; // IQueryable < TPM_VIEWS > var sharedViews = ( from v in context.TPM_USER.Include ( `` TPM_VIEWS2 '' ) where...
Concatenating three lists into one with LINQ throws an exception
C#
I 'm reading some examples and i keep seeing code with [ SOMETHING ] before methods and I 'd like to know what that 's called and how it 's used . Can you define you own [ SOMETHING ] or is there a defined list of these things ? Here 's some code examples I found that use this thing but do n't explain anything about it...
[ HandleError ] public class HomeController : Controller { public ActionResult Index ( ) { ViewData [ `` Message '' ] = `` Welcome to ASP.NET MVC ! `` ; return View ( ) ; } public ActionResult About ( ) { return View ( ) ; } }
.NET MVC 3 semantics