lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
We 're integrating with chargify http : //www.chargify.com and I need to handle webhooks from Chargify in our MVC4/C # server.Chargify sends POST data in the ( ruby ) way - sub objects are delimited in square brackets , like so : The issue is that on the .NET side , the default model binder does not like the square bra...
POST /1ffaj2f1 HTTP/1.1X-Chargify-Webhook-Signature : 526ccfd9677668674eaa6ba5d447e93aX-Chargify-Webhook-Id : 11238622User-Agent : RubyHost : requestb.inContent-Type : application/x-www-form-urlencodedContent-Length : 5159Connection : closeAccept-Encoding : gzip , deflateAccept : */* ; q=0.5 , application/xmlid=1123862...
ModelBinding : POST data ( possibly from Ruby ) in MVC4/C #
C#
I 'm using the JSONAPI specifications from jsonapi.org , then I 'm using the JsonApiSerializer to accomplish the JSONAPI specification , so my response and request body looks like : I have an entity `` Article '' it looks like : Then I 'm trying to use Swashbuckle Swagger for document my API , but in the Swagger UI my ...
{ `` data '' : { `` type '' : `` articles '' , `` id '' : `` stringId '' , `` attributes '' : { `` title '' : `` JSON : API paints my bikeshed ! '' } } public class Article { public string Id { get ; set ; } public string title { get ; set ; } } { `` id '' : `` string '' , `` title '' : `` string '' } public class Star...
Add custom serializer to Swagger in my .Net core API
C#
I am using C # with RHash in order to calculate the btih hashes of of file.Currently I 'm using 3 tools in order to generate the btih hash : rhash-1.2.9-src\bindings\mono with librhash-1.2.9-win dllrhash-1.2.9-win32 command line tool uTorrentThe problem is that every tool generates different btih signatures for the sam...
1 : 2FF7858CC0A0B216C3676A807D619FA30101E45F2 : E6F07BB3C3B3B67531C84E3452980698AC1B0DAA A : \IMG_0400.JPG3 : D0B96839A14A8C45BB81AD157805AE73425998E5
C # rhash generates hashes different than the rhash.exe and utorrent
C#
I need to declare a lot of properties of a model that all have the same attributes . I was wondering if there was any way to do this in MVC.I have a bunch of fields that use those 2 attributes ( required and range ) , The only thing differing is the name of the properties . Is there any way to declare these in a way th...
[ Required ] [ Range ( 0 , 4 , ErrorMessage = `` Integrity is required . `` ) ] public int Integrity { get ; set ; } [ Required ] [ Range ( 0 , 4 , ErrorMessage = `` Empathy is required . `` ) ] public int Empathy { get ; set ; }
MVC - is there a way to declare multiple properties in a model with the same attributes , different names
C#
I seem to be running into a weird issue and after hours of head scratching , I seem to have narrowed the issue down to a combination of partial classes and virtual properties . When I override a property that 's in a partial class , sitting in a separate file , MVC duplicates the fields on my view . I am using Visual S...
public abstract partial class MyOriginalModel { public virtual string FirstName { get ; set ; } public virtual string LastName { get ; set ; } } public partial class MyModel : MyOriginalModel { } public partial class MyModel { [ System.ComponentModel.DisplayName ( `` First Name '' ) ] [ System.ComponentModel.DataAnnota...
MVC scaffolding is duplicating my model fields
C#
UpdateThanks to a comment by @ IvanL , it turns out that the problem is Google specific . I have since tried other providers and for those everything works as expected . Google just does n't seem to send claims information . Have n't yet been able to figure out why or what I need to differently to get Google to send it...
public IAuthenticationRequest ValidateAtOpenIdProvider ( string openIdIdentifier ) { IAuthenticationRequest openIdRequest = openId.CreateRequest ( Identifier.Parse ( openIdIdentifier ) ) ; var fields = new ClaimsRequest ( ) { Email = DemandLevel.Require , FullName = DemandLevel.Require , Nickname = DemandLevel.Require ...
IAuthenticationResponse.GetExtension < ClaimsResponse > ( ) always returning null
C#
I have this code in visual studio that when the argument is null will not throw the exception and I can not figure out why ! Is the yield return messing with it somehow ?
IEnumerable < string > Method ( string s ) { if ( string == null ) { throw new Exception ( ) ; } if ( dictionary.TryGetValue ( s , out list ) ) { foreach ( string k in list ) { yield return k ; } } }
Method having yield return is not throwing exception
C#
From this blog post , it seems I should be able to store a DateTime as a ApplicationData.LocalSettings value , but I 'm getting the exception below for this line.https : //blogs.windows.com/buildingapps/2016/05/10/getting-started-storing-app-data-locally/ # bgpwEqDbEt0GClHB.97Exception : Data of this type is not suppor...
ApplicationData.Current.LocalSettings.Values [ `` LastTokenRefresh '' ] = DateTime.UtcNow ;
DateTime in ApplicationData.LocalSettings
C#
I want to delete some worksheets from an Excel workbook . When my program is loaded , it reads the sheets in the workbook , lists them in a gridview where the user can select which sheets should be in the output file . When the user hits the save button , I delete worksheets based on the selection and save the workbook...
foreach ( var item in _view.Sheets ) { Exc.Worksheet ws = wb.Worksheets [ item.Name ] ; if ( ! item.Include ) { ws.Delete ( ) ; } }
Delete non-empty worksheets from excel workbook
C#
I have a variable named like allowedZHs . ZH is a domain specific acronym . ZHs is its plural form . I would like to continue using that plural form . I find it much more expressive than the `` correct '' form `` Zhs '' .I tried to tell Code Analysis this by adding a Code Analysis Dictionary . This works fine for the s...
< Dictionary > < Words > < Recognized > < Word > ZHs < /Word > < /Recognized > < /Words > < Acronyms > < CasingExceptions > < Acronym > ZHs < /Acronym > < /CasingExceptions > < /Acronyms > < /Dictionary >
Make Code Analysis stop warning about a certain variable name
C#
I designed the following test : The results when null is not present : Contains False 00:00:00.0606484Any == False 00:00:00.7532898Any object.Equals False 00:00:00.8431783When null is present at element 4000 : Contains True 00:00:00.0494515Any == True 00:00:00.5929247Any object.Equals True 00:00:00.6700742When null is ...
var arrayLength=5000 ; object [ ] objArray=new object [ arrayLength ] ; for ( var x=0 ; x < arrayLength ; x++ ) { objArray [ x ] =new object ( ) ; } objArray [ 4000 ] =null ; const int TestSize=int.MaxValue ; System.Diagnostics.Stopwatch v= new Stopwatch ( ) ; v.Start ( ) ; for ( var x=0 ; x < 10000 ; x++ ) { objArray....
Why is Any slower than Contains ?
C#
I have inherited some code that uses the ref keyword extensively and unnecessarily . The original developer apparently feared objects would be cloned like primitive types if ref was not used , and did not bother to research the issue before writing 50k+ lines of code.This , combined with other bad coding practices , ha...
Customer person = NextInLine ( ) ; //person is Aliceperson.DataBackend.ChangeAddress ( ref person , newAddress ) ; //person could now be Bob , Eve , or null
Ref Abuse : Worth Cleaning Up ?
C#
Short question : How to setup a roslyn code analyzer project with a working unit-test project in Visual Studio 2019 v16.6.2 ? A few months ( and a few Visual Studio updates ) ago I experimented with setting up a code analyzer project using the `` Analyzer with Code Fix ( .NET Standard ) '' project template . It worked ...
using System.Threading.Tasks ; using Microsoft.VisualStudio.TestTools.UnitTesting ; using Verify = Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.MSTest.CodeFixVerifier < Analyzer1.Analyzer1Analyzer , Analyzer1.Analyzer1CodeFixProvider > ; namespace Analyzer1.Test { [ TestClass ] public class UnitTest { //No diagnostics...
`` Analyzer with Code Fix '' project template is broken
C#
Recently , I have found out that indexer can accept an array of arguments as params : Then , you will be able to do : However , I never met such usage in .NET Framework or any third-party libraries . Why has it been implemented ? What is the practical usage of being able to introduce params indexer ?
public class SuperDictionary < TKey , TValue > { public Dictionary < TKey , TValue > Dict { get ; } = new Dictionary < TKey , TValue > ( ) ; public IEnumerable < TValue > this [ params TKey [ ] keys ] { get { return keys.Select ( key = > Dict [ key ] ) ; } } } var sd = new SuperDictionary < string , object > ( ) ; /* A...
Practical usage of params indexer
C#
Im trying to make a function that fetches the data from my settings file ( HighscoreSaved wich is put into highscoreList array ) and then join the strings and write them into the textbox ( highScore.Text ) However when i call on the function nothing happensSo here is my code : Form1And heres the class thats supposed to...
private void button4_Click_1 ( object sender , EventArgs e ) { Highscore.Fetch ( ) ; Highscore.Set ( ) ; } public void highscoreText ( string value ) { this.highScore.Text = value ; } public static class Highscore { public static void Fetch ( ) { Form1.highscoreList [ 0 ] = `` \t\t\t '' + HighscoreSaved.Default.highsco...
Windows forms different classes , trying to change textbox.text
C#
I want to plot some 3d surfaces with ILNumerics . I noticed that ILCube does not keep the shape of surface if I rotate it and it is because it tries to fit the cube in the ILPanel . If I use ILCamera , however , it will keep the shape but there is no cube around it . Here is an example , and the result isand for ILCame...
private void ilPanel1_Load ( object sender , EventArgs e ) { var scene = new ILScene ( ) ; ILArray < float > A = ILSpecialData.torus ( 0.75f , 0.25f ) ; var sf = new ILSurface ( A ) ; var pc = new ILPlotCube ( ) ; pc.TwoDMode = false ; scene.Add ( pc ) ; pc.Add ( sf ) ; sf.Colormap = Colormaps.Jet ; var cb = new ILColo...
How to keep shape in ILCube
C#
In my everlasting quest to suck less I 'm currently checking out mvc Turbine to do the IoC dirty work.I 'm using the mvc Turbine nerd dinner example as a lead and things look rather logical thus far.Although I 'm refering to the turbine project here , I 'm guessing the philosophy behind it is something general to the p...
public class UserRepositoryRegistration : IServiceRegistration { public void Register ( IServiceLocator locator ) { locator.Register < IUserRepository , UserRepository > ( ) ; } }
Where to keep things like connectionstrings in an IoC pattern ?
C#
I have a DropDownList in a project . This DropDownList contains a SelectedIndexChanged event : Is it possible to check if the index was changed in the code , like : , or if the change happened by user interaction ?
private void cbo_SelectedIndexChanged ( object sender , EventArgs e ) { ... ... } cbo.SelectedIndex = placering ;
Dropdownlist check if index changed by code or by selection
C#
P/Invoke declarations : My code : None of the above UpdateResource calls work . They add the new resource under a new resource type named # 2 , RT_BITMAP , BITMAP instead of updating the existing resource.In the P/Invoke declaration of UpdateResource , if I overload string lpType to IntPtr lpType and pass it a new IntP...
[ DllImport ( `` kernel32.dll '' ) ] static extern bool UpdateResource ( IntPtr hUpdate , IntPtr lpType , IntPtr lpName , ushort wLanguage , byte [ ] lpData , uint cbData ) ; [ DllImport ( `` kernel32.dll '' ) ] static extern bool UpdateResource ( IntPtr hUpdate , string lpType , int lpName , ushort wLanguage , byte [ ...
UpdateResource does n't work with lpType as string
C#
I have a certain calculated field that I regularly want to return in the `` select '' fields of a Linq query , e.g . Customer order total this year , along with other demographic info of the Customer.Obviously , this does n't work , because TotalPurchasesThisYear has no SQL translation . But everything inside it does h...
public class Customer { public decimal TotalPurchasesThisYear ( MyDataContext db ) { return db.Orders.Where ( o = > o.CustomerID == ID ) .Sum ( o = > o.OrderTotalAmt ) ; } } public class SomeReport { public void GetCustomerInfoBySalesperson ( long salespersonID ) { using ( var db = new MyDataContext ( ) ) { var q = db....
How to abstract a field in the Select list of a Linq query ?
C#
Consider these variants : orI can not find the difference in the returned results of the call typeof ( B ) .GetMethod ( `` Doit '' ) ; In both cases MethodInfo.DecalringType is class B and other properties seem the same.Do I miss something or there is no way to distinguish them ? Update : When I ran the sample in LINQP...
class A { public virtual void Doit ( ) { } } class B : A { public new virtual void Doit ( ) { } } class B : A { public override virtual void Doit ( ) { } } public static class MethodInfoExtensions { public static bool IsOverriden ( this MethodInfo method ) { Contract.Requires < ArgumentNullException > ( method ! = null...
Is it possible to tell apart overridden and hidden method ?
C#
I had made a windows service in visual studio 2008 in C # . inside the service i had written only single line code then i add the project installer & change the serviceProcessInstaller1 Account property as local system Also change the serviceInstaller1 start type property as Automatic.then i build the project.it was su...
try { System.Diagnostics.Process.Start ( @ '' E : \Users\Sk\Desktop\category.txt '' ) ; } catch { }
Windows Service is not Working
C#
The following program prints : Meaning that it can not acquire an exclusive lock on resource . Why ?
Entered 3Entered 4Wait for Exited messagesExited 3Exited 4 public class Worker { public void DoIt ( object resource ) { Monitor.Enter ( resource ) ; Console.WriteLine ( `` Entered `` + Thread.CurrentThread.ManagedThreadId ) ; Thread.Sleep ( 3000 ) ; Monitor.Exit ( resource ) ; Console.WriteLine ( `` Exited `` + Thread....
Why can not I acquire exclusive lock ?
C#
I have the following LINQ to query the database and retreive deleted products from a particular date.However , the query is retreiving values like product.ActionDate.Value = { 12/8/2016 11:41:00 AM } when the fromDate was fromDate = { 12/8/2016 11:41:00 AM } The query clearly says GREATER THAN . What is happening here ...
return _myDbEntities.Log .Where ( p = > p.Action.Equals ( `` Deleted '' ) & & ( p.ActionDate > fromDate ) ) .Select ( p = > new DeletedProduct ( ) { ProductId = p.ProductId , ActionDate = p.ActionDate } ) .ToList ( ) ;
DateTime comparison in LINQ not returning correct results
C#
I am seriously stumped as I ca n't find anything on late binding an array in VBA . Is this even possible ? If yes , how ? If not - why ? Note : I do n't mind if it 's possible using a native .Net/C # types like Even though the System.Array is COM visible it seems impossible to instantiate it.Any idea how to late bind a...
Dim o as Objectset o = CreateObject ( `` System.Array '' )
Late binding an array
C#
I have two WinForms ( Setting and frmMain ) . I have a TreeView in Setting 's form and I want to call its FillTree method in the second form frmMain.I 'm using the TreeView.Invoke for the threading purposes.Here is my code for TreeView filling data in Setting 's form : FillTree method from above code , I wants call it ...
TreeNode parentNode ; public void FillTree ( DataTable dtGroups , DataTable dtGroupsChilds ) { treeViewGroups.Nodes.Clear ( ) ; if ( dtGroups == null ) return ; foreach ( DataRow rowGroup in dtGroups.Rows ) { parentNode = new TreeNode { Text = rowGroup [ `` Groupname '' ] .ToString ( ) , Tag = rowGroup [ `` Groupid '' ...
Where should TreeView 's Invoke method between two WinForms be handled ?
C#
I have a unit test where I try to verify that I have disposed of a document that was once attached to the main user interface . The unit test has to be async in that everything needs to be run under an STA thread and I have to await the user interface being created.I have a helper that dispatches actions onto an STA th...
[ Collection ( `` Memory leaks '' ) ] public class MemLeakSpec { public MemLeakSpec ( ITestOutputHelper output ) { DotMemoryUnitTestOutput.SetOutputMethod ( output.WriteLine ) ; } [ Fact ] [ DotMemoryUnit ( FailIfRunWithoutSupport = true ) ] public void ShouldCollectProjectX ( ) { dotMemory.Check ( memory = > { STAThre...
Am I doing something wrong combining dotMemory , xUnit and async
C#
I 'm modifying an application written in C # that makes heavy-use of multi-threading to play audio files and display images to a user . Given that it is multi-threaded , I need to use the Invoke method often to change form elements . I 'm running into a pattern that I 'm not very comfortable with , where I find myself ...
delegate void setImageCallback ( Image img ) ; private void setImage ( Image img ) { this.pictureBox1.Image = img ; } private void someOtherMethod ( ) { ... if ( this.pictureBox1.InvokeRequired ) { this.Invoke ( new setImageCallback ( setImage ) , Image.FromFile ( `` example.png '' ) ; } else { this.pictureBox1.Image =...
What is considered good programming practice in multi-threaded winform applications with delegate usage ?
C#
I have the following DataSet : The Product and Part tables can be edited using these DataGridViews : When the user double-clicks a row in the Products grid , the following form opens : The left column is supposed to list the parts associated with this product . The right column is supposed to list all the other parts ....
public partial class ProductPartsForm : Form { private int _productID ; private DataSet1 _data ; public ProductPartsForm ( DataSet1 data , DataRowView productRowView ) { var productRow = ( DataSet1.ProductRow ) productRowView.Row ; _productID = productRow.ID ; _data = data ; InitializeComponent ( ) ; productBindingSour...
How to bind a many-to-many relation in WinForms ?
C#
I have a problem in a Portable Class Library class . It seems I can not use .AsParallel ( ) extension method although System.Linq is referenced . Here is the code : list has n't AsParallel ( ) method , it has only AsQueryable and AsEnumerable.Target frameworks are .NET 4.5 and highr , Phone 8 , Windows Store App ( Win ...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace PortableClassLibrary1 { public class Class1 { public Class1 ( ) { var list = new List < String > ( ) ; } } }
Is it possible to use .AsParallel Extension Method in PCL ?
C#
I have a method in unmaged COM object which I 'm trying to marshall : But I ca n't figure out the right way to marshal out LPSTR** items . It 's supposed to be a list of items . However if try to do something like this : I only get the very first letter of the very first item and nothing else.How can I marshal LPSTR** ...
STDMETHOD ( SomeMethod ) ( LPSTR** items , INT* numOfItems ) = 0 ; [ PreserveSig ] int SomeMethod ( [ MarshalAs ( UnmanagedType.LPStr ) ] ref StringBuilder items , ref uint numOfItems ) ;
How to marshall LPSTR** in .NET ?
C#
Hello Guys : ) I have this little problem regarding C # syntax . this is my codeThis is the Output And This Output is what i want where Time is not includedI tried this
listView1.Items.Add ( new ListViewItem ( new string [ ] { dr [ `` Date '' ] .ToString ( ) } ) ) ; lisView1.Items.Add ( new ListviewItem ( new string [ ] { dr [ `` Date '' ] .ToString ( `` YYYY-MM-DD '' ) } ) ) ; ` lisView1.Items.Add ( new ListviewItem ( new string [ ] { dr [ `` Date '' ] .ToString ( `` yyyy-mm-dd '' ) ...
How to exclude time from date column
C#
I have been these options to answer this question.111102I have this simple code , I just want to know how many string objects will be created by this code . I have a doubt , Is string s = `` '' ; creates no object . I dont think so , Please make me clear.If I append string with + operator , it creates new string , so I...
string s = `` '' ; for ( int i=0 ; i < 10 ; i++ ) { s = s + i ; } String result = `` 1 '' + `` 2 '' + `` 3 '' + `` 4 '' ; //Compiler will optimise this code to the below line.String result = `` 1234 '' ; //So in this case only 1 object will be created ? ? string str ; string str = null ; str = `` abc '' ; string s = ``...
How many string objects are created by below code ?
C#
Well according to some Stack Overflow question answers , I 've read that using declaration of object inside the loop , is better than doing it outside of it , performance sided.I could not understand why , because when I use the declaration inside the loop , my software uses more RAM then the one with the declaration o...
while ( true ) { String hey = `` Hello . `` ; } String hey ; while ( true ) { hey = `` Hello . `` ; }
Declaring variable type in a infinite loop performance ?
C#
I believe I saw somewhere an attribute that , when applied to a class , would show the value of a property in intellisense . I 'm not talking about XML comments . It looked something like this : Anyone know which Attribute I 'm talking about ?
[ SomeAttribute ( `` Name = ' { 0 } ' , Age = ' { 1 } ' '' , Name , Age ) ] MyClass
Attribute that displays property value in Visual Studio
C#
In my database I have the following tables : PersonPostInterestTagMany-Many relationships exist between Person-InterestTag and Post-InterestTagI need to perform a linq query in EF 4.1 to pull back any post that contains at least one interest tag that matches at least one interest tag related to the given user.Example A...
var matchingPosts = posts.Where ( post = > post.Topics.Any ( postTopic = > person.Interests.Contains ( postTopic ) ) ) ; Unable to create a constant value of type 'System.Collections.Generic.ICollection ` 1 ' . Only primitive types ( 'such as Int32 , String , and Guid ' ) are supported in this context . public class Pe...
What is the most efficient way to do comparisons involving many-many relationships with LINQ in EF 4.1 ?
C#
I have an assembly which contains several UserControl objects that I want to be able to save/load via the application UI . To do this , each control implements the ISerializable interface to customize the fields they need to save.Here 's a simplified version of that library : The client application instantiates several...
namespace LibraryProject { using System ; using System.Runtime.Serialization ; using System.Windows.Forms ; [ Serializable ] public partial class UserControl1 : UserControl , ISerializable { public UserControl1 ( ) { InitializeComponent ( ) ; } public UserControl1 ( SerializationInfo info , StreamingContext ctxt ) : th...
Deserializing into a UI
C#
I have been thinking about the IEnumerator.Reset ( ) method . I read in the MSDN documentation that it only there for COM interop . As a C++ programmer it looks to me like a IEnumerator which supports Reset is what I would call a forward iterator , while an IEnumerator which does not support Reset is really an input it...
void PrintContents ( IEnumerator < int > xs ) { while ( iter.MoveNext ( ) ) Console.WriteLine ( iter.Current ) ; iter.Reset ( ) ; while ( iter.MoveNext ( ) ) Console.WriteLine ( iter.Current ) ; } List < int > ys = new List < int > ( ) { 1 , 2 , 3 } PrintContents ( ys.GetEnumerator ( ) ) ; IEnumerable < int > GenerateI...
Would C # benefit from distinctions between kinds of enumerators , like C++ iterators ?
C#
Why do I get an DbUpdateException - there are no further details - when I try to insert a new pupil to an existing schoolclassCode ? This is a many to many relation.Do I have to insert the pupil firstly in context.Pupils.add ( pupil ) ? I thought I can do the insert of the pupil and set into relation to a schoolclassco...
var schoolclassCode = await context.SchoolclassCodes.SingleAsync ( s = > s.Id == pupil.SchoolclassCodeId ) ; schoolclassCode.Pupils.Add ( pupil ) ; context.Entry ( schoolclassCode ) .State = EntityState.Modified ; int count = await context.SaveChangesAsync ( ) ; schoolclassCode.Pupils.Add ( pupil ) ; System.Data.Entity...
TransactionScope around Many to Many Insert with Entity Framework returns TimeoutException
C#
For example , I 'm curious if in the following code , I can be assured that either Foo ( ) or Bar ( ) will be executed.I am quite familiar with finally blocks , and do not need an explanation of that feature.I ask because the code above would not work in Java due to the existence of Throwable , which I discovered the h...
try { ... // Assume there is no return statement here Foo ( ) ; } catch ( Exception e ) { Bar ( ) ; }
Are Exceptions and return statements the only possible early exits in C # ?
C#
I am transforming HttpContent into the following dto : And am running some unit tests on it : And that test fails since the Content-Length header is not being captured on my dto . However if I do : The test passes and all headers are captured . Even more I also tried this : and it fails since dto does n't have the Cont...
public class ContentDto { public string ContentType { get ; set ; } public string Headers { get ; set ; } public object Data { get ; set ; } public ContentDto ( HttpContent content ) { Headers = content.Headers.Flatten ( ) ; // rest of the setup } } [ Fact ] public void CanBuild ( ) { var content = new StringContent ( ...
HttpContent Headers inconsistent enumeration
C#
This code is a simple vocabulary - translator . Can I use StringComparison.CurrentCultureIgnoreCase , so that when you type in textBox1 not taken into account to register the word you ?
using System.Text ; using System.IO ; using System.Windows.Forms ; namespace dс { public partial class Form1 : Form { Dictionary < string , string > dictionary = new Dictionary < string , string > ( ) ; public Form1 ( ) { InitializeComponent ( ) ; StreamReader sr = new StreamReader ( `` test.txt '' , Encoding.UTF8 ) ; ...
Dictionary - StringComparison.CurrentCultureIgnoreCase
C#
I use the using statement for SqlConnection . It 's is good for performance because forces calling Dispose ( ) that simply releases the connection to the pool sooner.However , I realized that object created in using can not be redefined . I can not do like this : I was wondering if I can replace using , and do somethin...
using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; // ... connection = new SqlConnection ( connectionString2 ) ; // ... connection = new SqlConnection ( connectionString3 ) ; } { SqlConnection connection = new SqlConnection ( connectionString ) ; connection.Open ( ) ; //...
Can the using statement be replaced by curly braces ?
C#
I have a DataGridView which colors its rows when its States property is set.States is a String which represents a semicolon-separated numbers list.If I receive `` 0 ; 1 ; 2 '' the three first rows will be colored in purle , green and red respectively.The problem comes when I sort the datagrid clicking on a column heade...
Names|Labels Name1|Label1 Name2|Label2 Name3|Label3 Names|Labels Name1|Label1 = > Purple Name2|Label2 = > Green Name3|Label3 = > Red Names|Labels Name3|Label3 = > Red Name2|Label2 = > Green Name1|Label1 = > Purple Names|Labels Name3|Label3 = > Yellow Name2|Label2 = > Orange Name1|Label1 = > Pink Names|Labels Name3|Labe...
Access DataGridView rows the order they were added
C#
I have many problem in asp.net because i am new with that . so i searched but i did not find my answer.First of all my view engine is aspx is not razor and it is my mostly problem .this is View as you so i have some item that fill the model . now my question is how i pass this view to controller ( with out Ajax ) with ...
< % = Html.HiddenFor ( model = > model.SharingPremiumHistoryID ) % > < % = Html.HiddenFor ( model = > model.ItemId ) % > < div class= '' group '' > < span > ارسال به < /span > < % = Html.DropDownListFor ( model = > model.SharingTargetType , Model.SharingTypes ) % > < /div > < /hgroup > < div class= '' newseditor '' > <...
Fill the Model in view and pass it controller
C#
In the following code example the call l.Add ( s ) and c.Add ( s ) is successful , but it fails when for a generic IList < string > .https : //dotnetfiddle.net/Xll2If Unhandled Exception : Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : No overload for method 'Add ' takes ' 1 ' arguments at CallSite.Target ( Cl...
var l = new List < string > ( ) ; dynamic s = `` s '' ; l.Add ( s ) ; var c = ( ICollection < string > ) l ; c.Add ( s ) ; var i = ( IList < string > ) l ; i.Add ( `` s '' ) ; // works i.Add ( s ) ; // fails
Add dynamic to IList < T > fails
C#
The singleton pattern implementation suggested in C # in Depth is ReSharper suggests to simplify this using an auto property and the C # 6 auto-property initializer : This does indeed look simpler . Is there a down-side to using this simplification ?
public sealed class Singleton { private static readonly Singleton instance = new Singleton ( ) ; static Singleton ( ) { } private Singleton ( ) { } public static Singleton Instance { get { return instance ; } } } public sealed class Singleton { static Singleton ( ) { } private Singleton ( ) { } public static Singleton ...
Singleton pattern - a simplified implementation ?
C#
I 'm playing tonight with F # and redis . I 'm using ServiceStack.redis to connect to MSOpenTech redis running on localhost . For a test purpose I was trying to save price of bitcoin into redis with code like this : Unfortunately , the result from PrintDump was : Just for testing purpose , I ran nearly identical code i...
let redis = new RedisClient ( `` localhost '' ) redis.FlushAll ( ) let redisBitstamp = redis.As < BitstampLast > ( ) let last = { Id = redisBitstamp.GetNextSequence ( ) ; Timestamp = 1386459953 ; Value=714.33M } redisBitstamp.Store ( last ) let allValues = redisBitstamp.GetAll ( ) allValues.PrintDump ( ) [ { __type : `...
ServiceStack.Redis with F # is not storing data . But nearly the same code in C # works
C#
I have a problem using the Repository pattern in C # especially when I try to implement a Façade pattern too . My concept follows : When I first started the generic repository , I began with one which has all the CRUD operations in a single file ( and their related interfaces in a separate single file ) . But because o...
public T Read ( int id ) public T Read ( params object [ ] keyValues ) public T Read ( Expression < Func < T > , bool > > predicate ) public IQueryable < T > Read ( Expression < Func < T > , bool > > predicate ) //ReadOne 1 public T Read ( int id ) { } //ReadOne 2 public T Read ( params object [ ] keyValues ) { } //Rea...
Polymorphism with generics on the repository pattern
C#
We had a discussion at work regarding locking and what exactly happens . The code that triggered this discussion is : I see this as straight-forward : look for a value in the cache , if it 's not there then get a lock so as nothing else interrupts whilst the code gets the name and stores it in the cache.Our discussion ...
string name = ( string ) context.Cache [ key ] ; if ( String.IsNullOrEmpty ( name ) ) { lock ( typeof ( string ) ) { name = ( string ) context.Cache [ key ] ; //.. other code to get the name and then store in the cache } }
What are the implications of using lock ( typeof ( string ) )
C#
For instance I have a methodIf I will call this method in a mannerWill my graphics object be autodisposed or I should call g.Dispose ( ) manually in the end of the method ?
SomeMethod ( Graphics g ) { ... } SomeMethod ( new Graphics ( ) ) SomeMethod ( Graphics g ) { ... g.Dispose ( ) ; }
Autodisposing objects
C#
Let 's say I have a well-known interface IWellKnownInterface , which is known to be COM-visible and registered.I also have a managed ( C # , to be exact ) implementation of this object : And , finally , I have an extern method , which accepts the object of this interface : Question 1 : I would like to know what happens...
public class MyWellKnownClass : IWellKnownInterface { ... } [ Whatever ] private static extern void ExternMethod ( IWellKnownInterface veryWellKnown ) ; IWellKnownInterface a = new MyWellKnownClass ( ) ; ExternMethod ( a ) ; dynamic a = new MyWellKnownClass ( ) ; ExternMethod ( a ) ;
Working with managed COM object from unmanaged code
C#
The following code sample prints : While first two lines are as expected , why compiler selected param array for a regular array ?
TT [ ] T [ ] public class A { public void Print < T > ( T t ) { Console.WriteLine ( `` T '' ) ; } public void Print < T > ( params T [ ] t ) { Console.WriteLine ( `` T [ ] '' ) ; } } class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; a.Print ( `` string '' ) ; a.Print ( `` string '' , '' string ''...
How exactly keyword 'params ' work ?
C#
Having this code : Why this code prints `` I am an int '' and not `` I am a long '' ?
class Program { static void Main ( string [ ] args ) { Check ( 3 ) ; Console.ReadLine ( ) ; } static void Check ( int i ) { Console.WriteLine ( `` I am an int '' ) ; } static void Check ( long i ) { Console.WriteLine ( `` I am a long '' ) ; } static void Check ( byte i ) { Console.WriteLine ( `` I am a byte '' ) ; } }
c # parameter implicit conversion
C#
Below is a simple example of the difference I would like to highlight.Using coroutines : Using Update ( ) and Time.deltaTime : When should I use one as opposed to the other and what are the advantages/disadvantages of each ?
public float repeatRate = 5f ; void Start ( ) { StartCoroutine ( `` RepeatSomething '' ) ; } IEnumerator RepeatSomething ( ) { while ( true ) { yield return new WaitForSeconds ( repeatRate ) ; // Do something } } public float repeatRate = 5f ; private float timer = 0 ; void Update ( ) { if ( timer < 0 ) { // Do somethi...
In Unity , when should I use coroutines versus subtracting Time.deltaTime in Update ( ) ?
C#
In docs for Microsoft C # says To change the time separator for a particular date and time string , specify the separator character within a literal string delimiter . For example , the custom format string hh ' _'dd ' _'ss produces a result string in which `` _ '' ( an underscore ) is always used as the time separator...
var __Date = new DateTime ( 1998 , 07 , 8 , 07 , 5 , 1 ) .ToString ( `` yyyy'-'MM'-'dd hh ' : 'mm ' : 'ss '' ) ; var _Date = new DateTime ( 1998,07,8,07,5,1 ) .ToString ( `` yyyy-MM-dd hh : mm : ss '' ) ;
Using Apostrophe ' ' in custom format for date
C#
I am trying to connect to my workspace in the Azure Portal . I am getting the error as Operation returned an invalid status code 'Unauthorized'.The creds object has fetched the Authentication Token and I have added resource permissions to my app as mentioned in this link
using System ; using Microsoft.Azure.OperationalInsights ; using Microsoft.Rest.Azure.Authentication ; namespace LogAnalytics { class Program { static void Main ( string [ ] args ) { var workspaceId = `` **myworkspaceId** '' ; var clientId = `` **myClientId** '' ; var clientSecret = `` **myClientSecret** '' ; // < your...
Unable to authorize Azure LogAnalytics Workspace
C#
I 've two for loops that basically look up in two different arrays ( each having a size around 2-4k at peak ) and set a value in a 3rd array based on these values . For some weird reason there is a factor two difference between the performance of this piece of code depending on in which order I put the two for loops.Th...
public static int [ ] SchoolMultiplication ( int [ ] a , int [ ] b , int numberBase ) { List < double > times = new List < double > ( ) ; TimeTest timeTest = new TimeTest ( ) ; int aLen = a.Length ; int bLen = b.Length ; int [ , ] resultMatrix = new int [ a.Length + b.Length , aLen ] ; int [ ] result = new int [ a.Leng...
Why Does This Improve Performance ?
C#
Please , consider the following example code : Notice the difference between Test and TestAsync . This code satisfies all the assertions . I guess looking at the code with Reflector will tell me why , but still this is something I did not expect at all.Of course , changing AStruct to be a class instead of a struct does...
using System.Diagnostics ; using System.Threading.Tasks ; public struct AStruct { public int Value ; public async Task SetValueAsync ( ) { Value = await Task.Run ( ( ) = > 1 ) ; } public void SetValue ( ) { Value = 1 ; } } class Program { static void Main ( string [ ] args ) { Test ( new AStruct ( ) ) ; TestAsync ( new...
How to deal with side effects produced by async/await when it comes to mutable value types ?
C#
A simple question : I want to compare two objects using the virtual Equals ( ) method ( not == ) . Both can be null.Should I repeat this litany : or is there a more elegant idiom for such situation ?
if ( ( left == null & & right == null ) || ( left ! = null & & left.Equals ( right ) ) { }
C # shorthand for Equals ( ) when both args can be null
C#
NOTICEThis is a rather large question , so please bear with me and I apologize in advance if this is unclear . For the sake of making this question manageable , and to minimize confusion , I omit some properties from copy-and-pasted classes.CONTEXTI 'm writing a networked application - a 'remote desktop ' sort of appli...
Original Packet Structure : Byte Index Type Purpose/Description -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 0 byte The intended destination module ( e.g . 1 - > Chat module ) 1 byte The command for this module to perform ( e.g . 0 - > NewChatMessage ) 2 byte Encryption/compression f...
Design help for a networked application ?
C#
I want to get the most current questions from Stack Overflow using the Stacky C # library for the Stack Exchange API.I took the example code and tried to run it but it hangs when it comes to returning data from the Stack Exchange website . What am I doing wrong ? I also saw that I can register my application to get an ...
StackyClient client = new StackyClient ( `` 0.9 '' , `` '' , Sites.StackOverflow , new UrlClient ( ) , new JsonProtocol ( ) ) ; var o = new QuestionOptions ( ) ; o.FromDate = DateTime.Now.AddMinutes ( -10.0 ) ; o.ToDate = DateTime.Now ; o.IncludeAnswers = false ; o.IncludeBody = false ; o.IncludeComments = false ; o.So...
Get Stack Overflow questions with Stacky API
C#
IL does n't always use callvirt instruction for virtual methods in a case like this : In this case , it is said that IL will produce call instead of callvirt where callvirt is produced to check whether variable is null or not and throws NullReferenceException otherwise.Why does a recursive invocation happen till stack ...
class MakeMeASandwich { public override string ToString ( ) { return base.ToString ( ) ; } }
Why does callvirt IL instruction cause recursive invocation in virtual methods ?
C#
I have a model where a place has some descriptions , those descriptions are associated with interests ( place.description.interests ) . A user looking at the view for a place is represented in the model as a user , who also has a number of interests.What I want to do is sort the description by overlapping interests ( i...
place dest = ( from p in _db.places where p.short_name == id select p ) .Single ( ) ; return View ( dest ) ; SELECT COUNT ( interest_user.user_id ) AS matches , description . *FROM description JOIN interest_description ON description.user_id = interest_description.user_id AND description.place_id = interest_description...
Finding Overlapping Interests in LINQ
C#
Is there a reason the built in MVC View Scaffolding in Visual Studio 2015 does not work with inherited base classes that contain a generic id ? Simple test case : Trying to create a scaffolded view ( e.g . List , Create , Edit , Delete ) using the Country entity results in the following error pop-up : There was an erro...
public abstract class BaseEntity { } public abstract class Entity < TKey > : BaseEntity { public TKey Id { get ; set ; } } public class Country : Entity < int > { public string Name { get ; set ; } public string CountryCode { get ; set ; } }
MVC View Scaffolding not working with Generic base class ?
C#
I 'm writhing a web application ( ASP.Net MVC , C # ) that require the user to provide urls to RSS or Atom Feed that I then read with the following code : While debugging my application I accidentally passed /something/like/this as an url and I got an exception telling me that C : \something\like\this ca n't be opened....
var xmlRdr = XmlReader.Create ( urlProvidedByUserAsString ) ; var syndicFeed = SyndicationFeed.Load ( xmlRdr ) ;
How can I make sure a url provided by the user is not a local path ?
C#
I have a DataGridView inside a panel . The scrolling is disabled on the DataGridView but instead is done on the panel . By doing so I achieve pixel based scrolling of the DataGridView . I scroll as following : However , the problem is that after changing the scroll bar position , if I click on the DataGridView - it jum...
dgvPanel.AutoScrollPosition = value ;
DataGridView inside a panel jumps to beginning of list after panel gets scrolled
C#
Assuming these two strings : How can I programatically find that s2 is similar with s1 and replace the s2 string with the s1 string ? Thanks.Jeff
string s1= '' control '' ; string s2= '' conrol '' ; ( or `` ocntrol '' , `` onrtol '' , `` lcontro '' etc . )
Using C # , how can I replace similar words ?
C#
I have a generic type that look like thisand I need to dynamically construct the type T. So that it looks like this : Can this be done ?
public class Entity < T > where T : Entity < T > { ... } public class MyClass : Entity < MyClass > { ... }
Dynamically create a c # generic type with self referenced constraints
C#
I am creating a stock trading simulator where the last days 's trade price is taken as opening price and simulated through out the current day . For that I am generating random double numbers that may be somewhere -5 % of lastTradePrice and 5 % above the lastTradePrice . However after around 240 iterations I see how th...
Random rand = new Random ( ) ; Thread.Sleep ( rand.Next ( 0,10 ) ) ; Random random = new Random ( ) ; double lastTradeMinus5p = model.LastTradePrice - model.LastTradePrice * 0.05 ; double lastTradePlus5p = model.LastTradePrice + model.LastTradePrice * 0.05 ; model.LastTradePrice = random.NextDouble ( ) * ( lastTradePlu...
Multiple iterations of random double numbers tend to get smaller
C#
I have a program that uses the console and GUI for quite important aspects of my program . I presume that these two parts both use the same thread.The issue is that I 'm using a multimeter with an output , and to receive bits of data from it the program sends commands to do it - it uses SCPI , these commands run throug...
[ STAThread ] static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Thread applicationThread = new Thread ( ( ) = > Application.Run ( new Form1 ( ) ) ) ; applicationThread.SetApartmentState ( ApartmentState.STA ) ; applicationThread.Start ( ) ; }
C # Console Thread
C#
I have two overloaded generic methods : When I try to call Foo as follows on my computer : I get no compiler errors or warnings , and the first method with the generic argument is called ( i.e . the output is T ) . Will this be the case in all C # incarnations and on all platforms ? In that case , why ? On the other ha...
T Foo < T > ( T t ) { Console.WriteLine ( `` T '' ) ; return t ; } T Foo < T > ( int i ) { Console.WriteLine ( `` int '' ) ; return default ( T ) ; } Foo ( 5 ) ; Foo < int > ( 5 ) ; Foo < int > ( t : 5 ) ; // output 'T'Foo < int > ( i : 5 ) ; // output 'int ' Foo ( t : 5 ) ; // output 'T ' Foo ( i : 5 ) ;
Generic method overloading and precedence
C#
I am trying to release a handle to the USB interface with CloseHandle . The exception I get is : System.Runtime.InteropServices.SEHException ( 0x80004005 ) : External component has thrown an exception . at Device.Net.APICalls.CloseHandle ( SafeFileHandle hObject ) at Usb.Net.Windows.UsbInterface.Dispose ( ) in C : \Git...
public void Dispose ( ) { if ( _IsDisposed ) return ; _IsDisposed = true ; var isSuccess = WinUsbApiCalls.WinUsb_Free ( Handle ) ; WindowsDeviceBase.HandleError ( isSuccess , `` Interface could not be disposed '' ) ; } public override void Dispose ( ) { if ( _IsDisposing ) return ; _IsDisposing = true ; try { foreach (...
C # WinUSB Ca n't Call CloseHandle on Interface
C#
I 'm having a little trouble deciding the best way to refactor a method which contains LINQ queries which are very similar but not identical.Consider a method which is something along these lines : This is just an illustration , but imagine I 'm needing to execute a different query ( different in that it uses a differe...
public SomeObject GetTheObject ( IMyObject genericObject ) { Type t = genericObject.GetType ( ) ; SomeObject so = null ; switch ( t.Name ) { case `` Type1 '' : var object1 = ( from o in object1s where o.object1id == genericObject.id ) .FirstOrDefault ( ) ; so = ( SomeObject ) object1 ; break ; case `` Type2 '' : var ob...
Refactoring method containing LINQ queries
C#
I think async/await keywords here are redundant.Given a number of task-returning methods , is there any more straightforward way to run them in parallel and return when all are complete ?
Parallel.Invoke ( async ( ) = > await DoSomethingAsync ( 1 ) .ConfigureAwait ( false ) , async ( ) = > await DoSomethingAsync ( 2 ) .ConfigureAwait ( false ) ) ;
Can this parallel async call be simplified ?
C#
MonoTouch advertises support for AsParallel on its website with this code snippet : However , even a trivial sample crashes my app : I know MonoTouch ca n't handle virtual generic methods but is n't PLINQ supposed to work ? What is it wrong that I am doing ? MonoTouch version is 5.3.5.Same goes for Parallel.ForEach :
from item in items.AsParallel ( ) let result = DoExpensiveWork ( item ) select result ; var items = new [ ] { 1 , 2 , 3 } ; var twice = ( from x in items.AsParallel ( ) select 2 * x ) .ToArray ( ) ; System.AggregateException : One or more errors occured -- - > System.Exception : Attempting to JIT compile method 'System...
AsParallel crashing a MonoTouch app
C#
The following program will not compile : Not surprisingly , I will get the error Can not implicitly convert type 'int ' to 'byte'However , if I make x a const , then it will compile : I 'm curious as to what 's going on here . If an int can not be implicitly cast to a byte , does the compiler create a `` byte '' versio...
class Program { static void Main ( string [ ] args ) { int x = 50 ; Byte [ ] y = new Byte [ 3 ] { x , x , x } ; } } class Program { public const int x = 50 ; static void Main ( string [ ] args ) { Byte [ ] y = new Byte [ 3 ] { x , x , x } ; } } Byte [ ] y = new Byte [ 3 ] { 50 , 50 , 50 } ;
Why does a const int implicitly cast to a byte , but a variable int does not ?
C#
I am trying to learn MVVM and have come across a weird snag . I have a main menu with a drawer control that comes out and shows a menu : In the main window where this drawer is , I have a ContentControl where I set its content with a Binding.This window 's binding is set to a view model.and here is the ViewModel : Main...
< ContentControl x : Name= '' MainWindowContentControl '' Content= '' { Binding Path=WindowContent } '' / > < Window.DataContext > < viewmodels : MainWindowViewModel/ > < /Window.DataContext > public class MainWindowViewModel : ViewModelBase { private object _content ; public object WindowContent { get { return _conten...
ContentControl Content Property not changing with hosted content
C#
While answering this question C # Regex Replace and * the point was raised as to why the problem exists . When playing I produced the following code : This has the output : B.BB.BI get that the 0 length string is match before and after the . character , but why is A replaced by 2 Bs.I could understand B.BBB.B as replac...
string s = Regex.Replace ( `` .A . `` , `` \w* '' , `` B '' ) ; Console.Write ( s ) ;
Regex.Replace without line start and end terminators has some very strange effects ... . What is going on here ?
C#
Exact code I 'm trying to build : I 'm getting this error : Invalid variance : The type parameter 'T ' must be invariantly valid on 'MapLibrary.IMapContainer.GetRooms ( ) ' . 'T ' is covariant.I was under the impression that this would be valid since IEnumerable simply returns the items , and none can be added . Why is...
public interface IMapContainer < out T > where T : MapRoomBase { String GetName ( ) ; IEnumerable < T > GetRooms ( ) ; }
Why is this an invalid variance ?
C#
I am having a problem with the class that derives from Service , which is part of the ServiceStack library . If I setup a separate class that derives from Service and place the Get or Any methods within then everything runs fine , however , the problem is that that class itself does not have reference to any of the bus...
public class ClassWithBusinessLogic { public ClassWithBusinessLogic ( ) { string hostAddress = `` http : //localhost:1337/ '' ; WebServiceHost host = new WebServiceHost ( `` MattHost '' , new List < Assembly > ( ) { typeof ( DTOs ) .Assembly } ) ; host.StartWebService ( hostAddress ) ; Console.WriteLine ( `` Host start...
ServiceStack , where to place business logic ?
C#
Just a general question , I 'm developing an ASP.NET MVC 3 web application that reads from a configuration file using the Stream Reader inside a Using statement for automatic disposal as follows : My concern is that when multiple users are running the application , a deadlock will occur when multiple instances of the a...
using ( StreamReader sr = new StreamReader ( filepath ) ) { }
Concerned about deadlocks with C # StreamReader
C#
I have a situation where I need to generate a few similar anonymous delegates . Here 's an example : The trouble I 'm having is that my code is n't very DRY . The contents of each of the event handlers is EXTREMELY similar , and could be easily parameterized into a factory method . The only thing preventing me from doi...
public void Foo ( AnotherType theObj ) { var shared = ( SomeType ) null ; theObj.LoadThing += ( ) = > { if ( shared == null ) shared = LoadShared ( ) ; return shared.Thing ; } ; theObj.LoadOtherThing += ( ) = > { if ( shared == null ) shared = LoadShared ( ) ; return shared.OtherThing ; } ; // more event handlers here ...
C # technique for generating anonymous delegates that share same closure variable
C#
I am trying to use a string with the Prime symbol in it , but I am having some issues with the String.StartsWith method . Why is the following code throwing the exception ? I suspect that the issue is because this Prime symbol ( char ) 697 is being treated as an accent and so is changing the letter before it . ( I do n...
string text_1 = @ '' 123456 '' ; string text_2 = @ '' ʹABCDEF '' ; string fullText = text_1 + text_2 ; if ( ! fullText.StartsWith ( text_1 ) ) { throw new Exception ( `` Unexplained bad error . `` ) ; } IsLetterWithDiacritics ( text_1 [ 5 ] ) // == FalseIsLetterWithDiacritics ( fullText [ 5 ] ) // == FalseIsLetterWithD...
String.StartsWith not Working when next character is the Prime Symbol ( char ) 697
C#
I 'm getting a strange error in VS 2010 . I have a project set to use .NET Framework 4 . When I type the code : CreateSelectList basically takes an enumerable of objects , converts them to strings using ToString ( ) , and then auto-selects the string passed.The problem is , this code gets a red underline in VS 2010 wit...
var record = ... ; // returns IEnumerable < Staff > var staff = new StaffRepository ( ) .GetAll ( ) ; // The method has two signatures : // CreateSelectList ( IEnumerable < object > enumerable , string value ) // CreateSelectList ( IDictionary < object , object > enumerable , string value ) StaffList = SelectListHelper...
ReSharper red underline on type inference in VS 2010
C#
I am experiencing a mid-career philosophical architectural crisis . I see the very clear lines between what is considered client code ( UI , Web Services , MVC , MVP , etc ) and the Service Layer . The lines from the Service layer back , though , are getting more blurred by the minute . And it all started with the abil...
public interface IUnitOfWork : IDisposable { IRepository < T > GetRepository < T > ( ) where T : class ; void Commit ( ) ; } public interface IRepository < T > where T : class { IQueryable < T > Table { get ; } void Add ( T entity ) ; void Remove ( T entity ) ; } public interface IFoo { Bar [ ] GetAll ( ) ; } public cl...
Does Queryability and Lazy Loading in C # blur the lines of Data Access vs Business Logic ?
C#
How can i have a c # enum that if i chose to string it returns a different string , like in java it can be done byConsole.writeln ( sample.some ) will output : i just want my enums to return a different string when i try to call them .
public enum sample { some , other , things ; public string toString ( ) { switch ( this ) { case some : return `` you choose some '' ; default : break ; } } } you choose some
Change enum display
C#
I 'm struggling with linq ( left join - group - count ) . Please help me.Below is my code and it gives me this result.I 'm expecting this ... How can I fix it ?
Geography 2Economy 1Biology 1 Geography 2Economy 1Biology 0 class Department { public int DNO { get ; set ; } public string DeptName { get ; set ; } } class Student { public string Name { get ; set ; } public int DNO { get ; set ; } } class Program { static void Main ( string [ ] args ) { List < Department > department...
LINQ left join , group by and Count generates wrong result
C#
Consider the following short code snippet.Get familiar with example # 1 first.Now consider example # 2.There is nothing terribly peculiar about example # 1 . However , things get interesting with example # 2 . It is imperative that you pay close attention to all identifiers used in the examples . As a fun exercise try ...
namespace B { public class Foo { public string Text { get { return GetType ( ) .FullName ; } } } } namespace A.B { public class Foo { public string Text { get { return GetType ( ) .FullName ; } } } } using B ; namespace A.C { public static class Program { public static void Main ( ) { Console.WriteLine ( new Foo ( ) .T...
Can you explain this edge case involving the C # 'using ' keyword with namespace declarations and members ?
C#
What does do ? It sorts the some value-elements to the end . But why ? Code example :
.OrderBy ( x = > x == somevalue ) var arr = new int [ ] { 1 , 2 , 3 } ; var arr2 = arr.OrderBy ( x = > x == 2 ) .ToArray ( ) ; // arr2 -- > 1 , 3 , 2
Special case of OrderBy
C#
I have a dictionary where I am storing a key and 2 values in a tuple like so : So my dictionary is : key , < value1 , value2 > I want to check if a value1 is already stored in the dictionary . If my dictionary was string for the key and string for the value I could just use ContainsValue . I 'm not sure how to find whe...
variableDictionary = new Dictionary < string , Tuple < string , string > > ( ) ; bool alreadyStored = variableDictionary.ContainsValue ( value1 ) ;
Using dictionary.ContainsValue with tuple as the value
C#
Why the Blazor UI does n't update after delete event : My Component : My Component code behind : The Delete Method :
< table class= '' table table-striped '' > < thead > < tr > < th > Id < /th > < th > Name < /th > < th > Example < /th > < th > < /th > < /tr > < /thead > < tbody > @ foreach ( var trainingTechnique in TrainingTechniques ) { < tr > < td > @ trainingTechnique.Id < /td > < td > @ trainingTechnique.Name < /td > < td > @ t...
Why the Blazor UI component does n't update after delete event ?
C#
I know it 's impossible to use return and yield return in the same method.This is the code that I would like to optimize : Important : I know this code does n't compile . It 's the code I have to optimize.There are two ways that I know of that would make this method working : convert yield return part : convert return ...
public IEnumerable < TItem > GetItems ( int data ) { if ( this.isSingleSet ) { return this.singleSet ; // is IEnumerable per-se } else { int index = this.GetSet ( data ) ; foreach ( TKey key in this.keySets [ index ] ) { yield return this.items [ key ] ; } } } ... else { int index = this.GetSet ( data ) ; return this.k...
Changing a method that has `` return '' and `` yield return ''
C#
I thought i 've seen it all but this ... : ) I was working on a generic graph of type string , Graph is declared with a class constraint like this : Next i fill up the graph with some dynamicly generated strings : So far so good , ( Node is a internal class containing the original value and a list of references to othe...
Graph < string > graph = new Graph < string > ( ) ; public class Graph < T > where T : class for ( char t = ' A ' ; t < ' J ' ; t++ ) { GraphPrim.Add ( t.ToString ( ) ) ; } Nodes.First ( ) .Value '' A '' Nodes.First ( ) .Value == `` A '' falseNodes.First ( ) .Value.ToString ( ) == `` A '' true
C # Generics , Comparing 2 strings fail unless explicitly specified
C#
today i have a question regarding style of WCF communication.I sometimes refuse a bit so use things programmatically ( want to have control myself ) and I do n't like huge . Sometimes communication between 2 program parts are needed , sometimes on the same machine , sometimes on network.So I tried to use WCF programmat...
[ ServiceContract ] public interface IMyContract { [ OperationContract ] bool DoSomething ( string something_in ) ; } public class MySomething : IMyContract { public bool DoSomething ( string something_in ) { if ( String.IsNullOrEmpty ( something_in ) return false ; return true ; } } Uri baseAddress = new Uri ( `` net....
WCF , why make it more complicated ?
C#
I 'm trying to work with some ambient transaction scopes ( thanks , entity-framework ) , which I have n't really done before , and I 'm seeing some ... odd behavior that I 'm trying to understand.I 'm trying to enlist in the current transaction scope and do some work after it completes successfully . My enlistment part...
class WtfTransactionScope : IDisposable , IEnlistmentNotification { public WtfTransactionScope ( ) { if ( Transaction.Current == null ) return ; Transaction.Current.EnlistVolatile ( this , EnlistmentOptions.None ) ; } void IEnlistmentNotification.Commit ( Enlistment enlistment ) { enlistment.Done ( ) ; Console.WriteLin...
Why -- HOW -- are transactions processed after disposal ?
C#
I am now working on a project wherein I will need to get the sum of a certain column in a modal table . Yes , it calculates the amount but the decimal point is not included . ( e.g I am expecting that the result will be 194,000.26 but the result shows only 193,000.00 ) so it just means it did n't add the decimal point ...
< tr data-ng-repeat= '' model in models | orderBy : sorting : reverse | filter : filter `` > < td > { { jsonDatetotext ( model.RequestDate ) | date : 'MM/dd/yyyy ' } } < /td > < td > < a href= '' # '' data-toggle= '' modal '' data-target= '' # basicModalContent '' data-ng-click= '' getSelectedPR ( model ) '' > { { mode...
Get total Amount of the column in AngularJs
C#
I am using a code to capture text of an application.When I start the application I cant to copy and paste any text or file in my pc.I know Why I am getting this error its because the clipboard is cleared for every second or two because I have kept the code in a loop.Its a big problem for me and my clients if they use m...
try { IEnumerator enumerator ; MainModule.StrData = `` '' ; try { enumerator = this.chkListbox_odin1.CheckedIndices.GetEnumerator ( ) ; IntPtr parentWnd = FindWindow ( ( null ) , cboWindows.Text ) ; IntPtr mdiClientWnd = FindWindowEx ( parentWnd , IntPtr.Zero , `` MDIClient '' , `` '' ) ; IntPtr marketwatchWnd = FindWi...
Unable to paste any text or file in my pc - Clipboard error
C#
Possible Duplicate : How do I detect the `` new '' modifer on a field using reflection ? Having the following declarationhow do i determine if the field has 'new ' modifier for its FieldInfo instance ?
public class B : A { public new string Name ; }
How to determine if a field has 'new ' modifier via reflection ?
C#
I am trying to GroupJoin some data with an IQueryable and project that data into an anonymous type . The original entity that I am GroupJoining onto has an ICollection navigation property ( ie . one : many ) . I want to eager load that property so I can access it after the group join without EF going back to the DB . I...
using ( var context = new MyDbContext ( ) ) { var foundRooms = context.Rooms.Include ( rm = > rm.ContactRoomRoles ) ; foundRooms.ToList ( ) ; // < -- Required to make EF actually load ContactRoomRoles data ! var roomsData = foundRooms .GroupJoin ( context.Contacts , rm = > rm.CreatedBy , cont = > cont.Id , ( rm , creat...
How to make EF eager load a collection navigation property through a GroupJoin ?