lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I was experimenting with the const modifier while exploring a plethora of C # tutorials , and placed a bunch of const modifiers in a class like this without actually using them anywhere : With this class , I get the following warning ( using csc ) : ConstTesting.cs ( 3,19 ) : warning CS0414 : The field ‘ ConstTesting.s...
class ConstTesting { const decimal somedecimal = 1 ; const int someint = 2 ; ... }
Confusing warning about a constant decimal field in C #
C#
Could Someone help me to clarify the difference between : I get the same results in both cases without knowing the difference .Does the Eager Loading require using Include ?
var query = awlt.People.Include ( p = > p.EmailAddresses ) .Where ( p = > p.LastName.Equals ( lastName ) ) .SelectMany ( a = > a.EmailAddresses ) .Select ( a = > a.EmailAddress1 ) ; var query = awlt.People .Where ( p = > p.LastName.Equals ( lastName ) ) .SelectMany ( a = > a.EmailAddresses ) .Select ( a = > a.EmailAddr...
Using include does n't change the behavior
C#
I 've been doing some code refactoring in my C # projects.I got a Resharper code analysis warning : `` Redundant string interpolation '' This happens in following scenario : I 've read string interpolation is rewritten to string.Format at compile time . Then I tried following : This time I get : Redundant string.Format...
void someFunction ( string param ) { ... } someFunction ( $ '' some string '' ) ; someFunction ( string.Format ( `` some string '' ) ) ; someFunction ( $ '' some string '' ) someFunction ( `` some string '' ) someFunction ( string.Format ( `` some string '' ) )
Redundant string interpolation and performance
C#
I wrote a test program wherein a single Button is defined in XAML as the content of a Window . Upon the window 's loading , the Button is programmatically replaced as the window 's content , and the field referring to it is also replaced , both by another Button which I created programmatically . I thereafter track bot...
< Window x : Class= '' Test.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Width= '' 300 '' Height= '' 150 '' Loaded= '' Window_Loaded '' > < Button Name= '' btn '' / > < /Window > namespace Test { public partial cla...
XAML Button not garbage collected after eliminating references
C#
If you have a Form that displays data , one thing you can do is reference this.DesignMode in the constructor to avoid populating it in the designer : However , if you decide to re-write that form as a UserControl , keeping the same constructor logic , something unexpected happens - this.DesignMode is always false no ma...
public partial class SetupForm : Form { private SetupItemContainer container = new SetupItemContainer ( ) ; public SetupForm ( ) { InitializeComponent ( ) ; if ( ! this.DesignMode ) { this.bindingSource1.DataSource = this.container ; this.Fill ( ) ; } } } public partial class AffiliateSetup : UserControl { private Affi...
Are there any caveats to swapping out DesignMode for LicenseManager.UsageMode in a WinForms UserControl constructor ?
C#
Here is what I would like to do : Is such a construction possible in .NET ? Edit : The question was not clear enough . Here is what I want to do , expanded : Meaning , I want the constrained type to : - accept a single generic parameter - implement a given single generic parameter interface.Is that possible ? In fact ,...
public interface IRepository < TSet < TElement > > where TSet < TElement > : IEnumerable < TElement > { TSet < TEntity > GetSet < TEntity > ( ) ; } public class DbRepository : IRepository < DbSet < TElement > > { DbSet < TEntity > GetSet < TEntity > ( ) ; } public class ObjectRepository : IRepository < ObjectSet < TEle...
Can one specify on a generic type constraint that it must implement a generic type ?
C#
I may not have it correct , but I saw something like this above a WebMethod : I saw a vb version first and I used a converter to convert it to c # . I have never seen it before . It 's in a vb 6 asmx file .
[ return : ( XmlElement ( `` Class2 '' ) , IsNullable = false ) ] public Class2 MEthod1 ( ) { }
What does this syntax mean in c # ?
C#
I 'm using the Winforms WebBrowser control to collect the links of video clips from the site linked below.LINKBut , when I scroll element by element , I can not find the < video > tag.Soon after using theI already return 0Do I need to call any ajax ?
void webBrowser_DocumentCompleted_2 ( object sender , WebBrowserDocumentCompletedEventArgs e ) { try { HtmlElementCollection pTags = browser.Document.GetElementsByTagName ( `` video '' ) ; int i = 1 ; foreach ( HtmlElement link in links ) { if ( link.Children [ 0 ] .GetAttribute ( `` className '' ) == `` vjs-poster '' ...
How to get an HtmlElement value inside Frames/IFrames ?
C#
I 've just rebuilt my machine with a fresh install of Visual Studio 2015 . I 've also installed the extensions for Web Essentials and Web Compiler but these seem to have caused a problemSay for example , prior to installing Web Essentials and Web Compiler , if I was editing a Razor view , if the current element was for...
< ul > < li > < ! -- press enter here -- > | < ! -- would put cursor here -- > < /li > < /ul > < ul > < li > < ! -- press enter here -- > | < ! -- put 's cursor here -- > < /li > < /ul >
Razor editor formatting not working after installing Web Essentials and Web Compiler
C#
I have a List < Fruit > , and the list above contains 30 Fruit objects of two types : Apple and Orange . 20 apples and 10 oranges.How can I get a list of 10 random fruits ( from the basket of 30 fruits ) , but there should be 3 oranges and 7 apples ?
public class Fruit { public string Name { get ; set ; } public string Type { get ; set ; } } List < Fruit > fruits = new List < Fruit > ( ) ; fruits.Add ( new Fruit ( ) { Name = `` Red Delicious '' , Type = `` Apple '' } ) ; fruits.Add ( new Fruit ( ) { Name = `` Granny Smith '' , Type = `` Apple '' } ) ; fruits.Add ( ...
Get random items with fixed length of different types
C#
Here is a simple C # .NET Core 3.1 program that calls System.Numerics.Vector2.Normalize ( ) in a loop ( with identical input every call ) and prints out the resulting normalized vector : And here is the output of running that program on my computer ( truncated for brevity ) : So my question is , why does the result of ...
using System ; using System.Numerics ; using System.Threading ; namespace NormalizeTest { class Program { static void Main ( ) { Vector2 v = new Vector2 ( 9.856331f , -2.2437377f ) ; for ( int i = 0 ; ; i++ ) { Test ( v , i ) ; Thread.Sleep ( 100 ) ; } } static void Test ( Vector2 v , int i ) { v = Vector2.Normalize ( ...
Why does the result of Vector2.Normalize ( ) change after calling it 34 times with identical inputs ?
C#
I 'm looking into solutions to convert a string into executeable code . My code is extremely slow and executes at 4.7 seconds . Is there any faster way of doing this ? String : `` 5 * 5 '' Output : 25The code :
class Program { static void Main ( string [ ] args ) { var value = `` 5 * 5 '' ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; var test = Execute ( value ) ; sw.Stop ( ) ; Debug.WriteLine ( $ '' Execute string at : { sw.Elapsed } '' ) ; } private static object Execute ( string content ) { var codeProvider = new CSh...
Convert string to executable code performance
C#
One of my fellow developer has a code similar to the following snippetHere the Data class properties fetch the information from DB dynamically . When there is a need to save the Data to a file the developer creates an instance and fills the property using self assignment . Then finally calls a save . I tried arguing th...
class Data { public string Prop1 { get { // return the value stored in the database via a query } set { // Save the data to local variable } } public void SaveData ( ) { // Write all the properties to a file } } class Program { public void SaveData ( ) { Data d = new Data ( ) ; // Fetch the information from database an...
Is it ok to use C # Property like this
C#
I saw this kind of code at work : Any idea what does a static modifier on a constructor mean and why in this case it is required ?
class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component , it has something special about it 's execution { static FooPlugin ( ) { SomeObject.StaticFunction ( ) ; // The guy who wrote it said it 's meaningful to this question but he ca n't remember why . } }
What does a static modifier on a constructor means ?
C#
I 'm using .NET 4.5 in a VSTO addin for outlook 2013 . I 'm having some trouble fully grasping properties and accessors . Auto-implemented accessors which I assume are when you just write get ; set ; rather than get { //code } , etc . are also giving me trouble . I have a dictionary I use internally in my class . Here ...
private Dictionary < string , string > clientDict { get ; set ; } private Dictionary < string , string > clientHistoryDict { get ; set ; } clientDict = new Dictionary < string , string > ( ) ; clientHistoryDict = new Dictionary < string , string > ( ) ; private Dictionary < string , string > _clientDict ; // etc .
Properties and auto-implementations
C#
I 'm trying to resolve CA2225 , which WARNs on ContrainedValue < T > below , with the following message : Provide a method named 'ToXXX ' or 'FromXXX ' as an alternate for operator 'ConstrainedValue < T > .implicit operator T ( ConstrainedValue < T > ) '.I 've also pasted PositiveInteger to illustrate a use-case for Co...
namespace OBeautifulCode.AutoFakeItEasy { using System.Diagnostics ; using Conditions ; /// < summary > /// Represents a constrained value . /// < /summary > /// < typeparam name= '' T '' > The type of the constrained value. < /typeparam > [ DebuggerDisplay ( `` { Value } '' ) ] public abstract class ConstrainedValue <...
How to fix CA2225 ( OperatorOverloadsHaveNamedAlternates ) when using generic class
C#
BackgroundEven though it 's possible to compile C # code at runtime , it 's impossible to include and run the generated code in the current scope . Instead all variables have to be passed as explicit parameters.Compared with dynamic programming languages like Python , one could never truly replicate the complete behavi...
x = 42print ( eval ( `` x + 1 '' ) ) # Prints 43 void Foo ( ) { int x = 42 ; Console.WriteLine ( Bar ( ) ) ; } int Bar ( ) { return ( int ) ( DynamicScope.Resolve ( `` x '' ) ) ; // Will access Foo 's x = 42 }
How to access locals through stack trace ? ( Mimicking dynamic scope )
C#
I 'd like to know if it is possible to use an expression as a variable/parameter in C # . I would like to do something like this : Here 's what I do n't want to do : Really what I 'm getting at is a way to get around using a switch or series of if statements for each of : < > < = > = == ! = . Is there a way to do it ? ...
int x = 0 ; public void g ( ) { bool greaterThan = f ( `` x > 2 '' ) ; bool lessThan = f ( `` x < 2 '' ) ; } public bool f ( Expression expression ) { if ( expression ) return true ; else return false ; } int x = 0 ; public void g ( ) { bool greaterThan = f ( x , ' < ' , 2 ) ; } public bool f ( int x , char c , int y )...
C # : Is there a way to use expressions as a variable/parameter ?
C#
I am using Microsoft Interactivity and Microsoft Interactions to rotate an object based on a Property in my code-behind . To make the rotation more smooth I added in an easing function . It does the animation perfectly fine but when it reaches the end of the animation for 1 split frame the rotation resets to the value ...
< i : Interaction.Triggers > < ie : PropertyChangedTrigger Binding= '' { Binding Rotation } '' > < ie : ChangePropertyAction TargetName= '' RotateTransformer '' PropertyName= '' Angle '' Value= '' { Binding Rotation } '' Duration= '' 0:0:2 '' > < ie : ChangePropertyAction.Ease > < BackEase EasingMode= '' EaseOut '' Amp...
Easing animation 'twitches ' when it finishes
C#
I would like to know the way to make a list of drop down lists in C # class . I have been trying like this : Then I add _ddlCollection to the Asp.NET site like this : But it breaks on line : Can you tell me how to add a few DDL 's to a List ?
List < DropDownList > _ddlCollection ; for ( int i = 0 ; i < 5 ; i++ ) { _ddlCollection.Add ( new DropDownList ( ) ) ; } foreach ( DropDownList ddl in _ddlCollection ) { this.Controls.Add ( ddl ) ; } _ddlCollection.Add ( new DropDownList ( ) ) ;
How to make a list of DDL in C # programatically
C#
In the MSDN Events Tutorial hooking up to events is demonstrated with the example : Where as I have been keeping a reference to the delegate . Example : When I look at the MSDN example code , `` -= new '' just looks wrong to me . Why would this List have a reference to an event handler I just created ? Obviously I must...
// Add `` ListChanged '' to the Changed event on `` List '' : List.Changed += new ChangedEventHandler ( ListChanged ) ; ... // Detach the event and delete the list : List.Changed -= new ChangedEventHandler ( ListChanged ) ; ChangedEventHandler myChangedEvent = new ChangedEventHandler ( ListChanged ) ; List.Changed += m...
How does the removing an event handler with -= work when a `` new '' event is specified
C#
I 'm using Entity Framework 6.1 , code-first . I 'm trying to store/retrieve a decimal from SQL Server , but the correct precision is n't retrieved . I read from a .csv file , process the data , then insert into the DB.Value in the .csv file : 1.1390Value when saved as decimal from the import : 1.1390Value inserted int...
modelBuilder.Entity < ClassA > ( ) .Property ( p = > p.MyDecimal ) .HasPrecision ( 19 , 4 ) ; _poRepository.Table.FirstOrDefault ( p = > p.CompNumberA == compNum & & p.LineNumber == lineNumber ) ; import.MyDecimal ! = dbValue.MyDecimal public class ClassA { // properties public virtual decimal MyDecimal { get ; set ; }...
EF retrieves incorrect decimal precision
C#
I usually find myself doing something like : and I find all this mixup of types/interface a bit confusing and it tickles my potential performance problem antennae ( which I ignore until proven right , of course ) . Is this idiomatic and proper C # or is there a better alternative to avoid casting back and forth to acce...
string [ ] things = arrayReturningMethod ( ) ; int index = things.ToList < string > .FindIndex ( ( s ) = > s.Equals ( `` FOO '' ) ) ; //do something with indexreturn things.Distinct ( ) ; //which returns an IEnumerable < string >
When to use each of T [ ] , List < T > , IEnumerable < T > ?
C#
Recently it seems like Microsoft changed something in the behaviour when people are trying to sign-in with their Microsoft Account through our services.We have a setup where we use IdentityServer4 and Azure AD for the Microsoft Accounts . When people try to sign-in now , they just click sign-in button on our webpage an...
serviceCollection .AddAuthentication ( o = > { o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme ; o.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme ; } ) .AddCookie ( CookieAuthenticationDefaults.AuthenticationScheme ) .AddMicrosoftAccount ( `` Microsoft '' , `` Microsoft '' , o =...
IdentityServer4 and Azure AD auto selects users on sign-in page
C#
For some reason , with the Razor view engine , VS is crashing on me . I copied the CSHTML content over to a VBHTML file and begin reformatting it , and VS has crashed on me twice now as I change a helper or function method syntax from : toIs anyone else getting this ? The whole machine must be rebooted to get intellise...
@ helper SomeHelper ( string text ) @ Helper SomeHelper ( text As String )
VS Crashes with RAZOR VBHTML
C#
Consider the following two alternatives of getting the higher number between currentPrice and 100 ... I raised this question because I was thinking about a context where the currentPrice variable could be edited by other threads.In the first case ... could price obtain a value lower than 100 ? I 'm thinking about the f...
int price = currentPrice > 100 ? currentPrice : 100int price = Math.Max ( currentPrice , 100 ) if ( currentPrice > 100 ) { //currentPrice is edited here . price = currentPrice ; }
Is the ternary operator ( ? : ) thread safe in C # ?
C#
Being new to programming I have only just found out that you can specifically catch certain types of errors and tie code to only that type of error . I 've been researching into the subject and I do n't quite understand the syntax e.g.I understand the InvalidCastException is the type of error being handled , however I ...
catch ( InvalidCastException e ) { }
Being specific with Try / Catch
C#
What happens when a synchronous method is called within an asynchronous callback ? Example : A connection is accepted and the async receive callback is started . When the tcp connection receives data , it calls the receive callback . If the sync Send method is called , does that stop other async callbacks from happenin...
private void AcceptCallback ( IAsyncResult AR ) { tcp.BeginReceive ( ReceiveCallback ) ; } private void ReceiveCallback ( IAsyncResult AR ) { tcp.Send ( data ) ; }
Call Sync method call from Async Callback ?
C#
I want lines as many as the width of the console to simultaneously write downwards one char to the height of the console . I 've done most of it , but it goes from top to bottom to right etc ... If you need help picturing what I mean , think of the matrix code rain .
int w = Console.WindowWidth ; int h = Console.WindowHeight ; int i = 0 ; while ( i < w ) { int j = 0 ; while ( j < h ) { Thread.Sleep ( 1 ) ; Console.SetCursorPosition ( i , j ) ; Console.Write ( `` . `` ) ; j++ ; } i++ ; }
How to write in multiple positions in a console application at the same time ? C #
C#
While working on a upgrade i happened to come across a code like this.My question is : Is there any need/use of 'explicit ' implementation of interface in this piece of code ? Will it create any problem if i remove the method ( explicit implementation of interface ) that i have marked `` redundant '' above ? PS : I und...
interface ICustomization { IMMColumnsDefinition GetColumnsDefinition ( ) ; } class Customization : ICustomization { private readonly ColumnDefinition _columnDefinition ; //More code here . public ColumnsDefinition GetColumnsDefinition ( ) { return _columnDefinition ; } ColumnsDefinition ICustomization.GetColumnsDefinit...
Implicit and Explicit implementation of interface
C#
I 'm trying to post FormData including both a File and a Collection.This is my Model : This is my action : My FormData in JavaScript is : And here is the header : The `` File '' is working fine , but the `` Content '' is always null.Where am I going wrong ? Thank you !
public class Content { public string Name { get ; set ; } public string Link { get ; set ; } } public class Model { public IEnumerable < Content > Contents { get ; set ; } public IFormFile File { get ; set ; } } [ HttpPost ] public async Task InsertAsync ( [ FromForm ] Model dataPost ) { await _services.Create ( dataPo...
Collection always null when using [ FromForm ] attribute
C#
I have a huge list of Items and need to Group them by one property . Then the oldest of each group should be selected.Simplified Example : Select the oldest User of each FirstName.Class User : I was wondering why this statement took so long until I set a breakpoint at Result and looked into the SQL statement generated ...
using ( ED.NWEntities ctx = new ED.NWEntities ( ) ) { IQueryable < ED.User > Result = ctx.User.GroupBy ( x = > x.FirstName ) .Select ( y = > y.OrderBy ( z = > z.BirthDate ) .FirstOrDefault ( ) ) .AsQueryable ( ) ; } public partial class User { public int UserID { get ; set ; } public string FirstName { get ; set ; } pu...
Entity Framework GroupBy take the oldest with mySQL
C#
I created new Azure account and trying to automatically deploy app inside it with following code : It works , if identifierUrl is hardcoded as Azure Active Directory name.How can I read identifierUrl ( Azure Active Directory domain name ) from Azure ? I can see this value in portal , but I can not find an API to read i...
var app = azure.AccessManagement.ActiveDirectoryApplications.Define ( appName ) .WithSignOnUrl ( appSignOnUrl ) .WithAvailableToOtherTenants ( true ) .WithIdentifierUrl ( identifierUrl ) .DefinePasswordCredential ( username ) .WithPasswordValue ( password ) .WithDuration ( ) .Attach ( ) ; .CreateAsync ( ) ;
How to read domain of Azure Active Directory
C#
Given this code : I would have expected ReflectedType to be SomeDerivedClass given that it is the type of the parameter for the expression . But it is SomeClass , which is - if i understand correctly - the declaring type . Why is that ?
static void Main ( string [ ] args ) { Expression < Func < SomeDerivedClass , object > > test = i = > i.Prop ; var body = ( UnaryExpression ) test.Body ; Console.WriteLine ( ( ( MemberExpression ) body.Operand ) .Member.ReflectedType ) ; } public class SomeClass { public int Prop { get ; private set ; } } public class ...
ReflectedType from MemberExpression
C#
I 'm developing a Windows Phone 8.1 app . I have a screen with a list of news ' titles with thumbnails . First I 'm making asynchronous http request to get news collection in JSON ( satisfying the NotifyTaskCompletion pattern ) NewsCategory : News : So far it works perfectly , but as soon as I get the ImagePath propert...
NewsCategories = new NotifyTaskCompletion < ObservableCollection < NewsCategory > > ( _newsService.GetNewsCategoriesAsync ( ) ) ; public class NewsCategory : ObservableObject { ... public string Title { get ; set ; } public ObservableCollection < News > Items { get ; set ; } } public class News : ObservableObject { ......
Async/await deadlock while downloading images
C#
I 'm having some problems setting up a command handling architecture . I want to be able to create a number of different commands derived from ICommand ; then , create a number of different command handlers derived from ICommandHandler ; Here 's the interface and classes I have begun to define : I have a helper class t...
interface ICommand { } class CreateItemCommand : ICommand { } interface ICommandHandler < TCommand > where TCommand : ICommand { void Handle ( TCommand command ) ; } class CreateItemCommandHandler : ICommandHandler < CreateItemCommand > { public void Handle ( CreateItemCommand command ) { // Handle the command here } }...
Contravariance ? Covariance ? What 's wrong with this generic architecture ... ?
C#
I am reviewing another developer 's code and he has written a lot of code for class level variables that is similar to the following : Does n't coding this way add unnecessary overhead since the variable is private ? Am I not considering a situation where this pattern of coding is required for private variables ?
/// < summary > /// how often to check for messages /// < /summary > private int CheckForMessagesMilliSeconds { get ; set ; } /// < summary > /// application path /// < /summary > private string AppPath { get ; set ; }
Is there any benefit to declaring a private property with a getter and setter ?
C#
I have two pages say Page1 and page2.In Page-1 I have a listview and an Image button ( tap gesture ) .Here if I click listview item , it navigates to Page2 whereit plays a song.Song continues to play . Then I go back to page1 by clicking back button . Then as mentioned I have an imagebutton in page1 , if I click this i...
Navigation.PushModalAsync ( new page2 ( parameter1 ) ) ;
Navigation in Xamarin.Forms
C#
I 've just found strange for me code in Jeffrey Richter book ( CLR via C # 4.0 , page 257 ) and have misunderstanding why it works so.Result : As you can see , we have an accessor property named 'Students ' , which has only getter ( not setter ! ) , but in 'Main ' function , when we 'd like to initialize 'classroom ' v...
public sealed class Classroom { private List < String > m_students = new List < String > ( ) ; public List < String > Students { get { return m_students ; } } public Classroom ( ) { } } class Program { static void Main ( string [ ] args ) { Classroom classroom = new Classroom { Students = { `` Jeff '' , `` Kristin '' }...
get and set misunderstanding in initialisation : Jeffrey Richter , CLR via C #
C#
I am saving xml from .NET 's XElement . I 've been using the method ToString , but the formatting does n't look how I 'd like ( examples below ) . I 'd like at most two tags per line . How can I achieve that ? Saving XElement.Parse ( `` < a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > ...
< a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > < c > five < /c > < /b > < /a > < a > < b > < c > one < /c > < c > two < /c > < /b > < b > three < c > four < /c > < c > five < /c > < /b > < /a >
Writing xml with at most two tags per line
C#
I connect to a 3rd party webservice that returns a complex JSON object that only contains a few bits of information I actually need.Basically , I just need the array in `` value '' . From that array , I just need the `` Id '' , `` Title '' and `` Status '' properties.I want to put those attributes into a c # class call...
public class Project { public String Id { get ; set ; } public String Title { get ; set ; } public String Status { get ; set ; } } using ( WebResponse response = request.GetResponse ( ) ) { using ( StreamReader reader = new StreamReader ( response.GetResponseStream ( ) ) ) { var serializer = new JsonSerializer ( ) ; va...
Selectively read part of JSON data using JsonSerializer and populate a c # object
C#
In C # , I can attach documentation for properties , methods , events , and so on , directly in the code using XML Documentation Comments . I know how to insert a reference to a particular method : Is there a way to insert a reference to a method group ? Where I 've got multiple overloads of the same method name ... I ...
< see cref= '' MethodName ( TypeForArg1 , TypeForArg2.. ) '' / > < see cref= '' M : MethodName '' / >
In xml doc , can I insert a reference to a method group ? How ?
C#
I 'm trying to learn MVVM , but there is something I do n't understand yet.Currently , I have this event handler : Very easy . However , I would like to apply the MVVM pattern in this application.I 'm wondering , am I supposed to put this logic in a ViewModel instead of directly in the view code ? If so , how am I supp...
private void Window_Closing ( object sender , System.ComponentModel.CancelEventArgs e ) { if ( MessageBox.Show ( `` Are you sure you want to close this application ? `` , `` Close ? ? `` , MessageBoxButton.YesNo , MessageBoxImage.Question ) == MessageBoxResult.No ) { e.Cancel = true ; } }
MVVM - Exit confirmation
C#
We have our integration tests set up using xUnit and Microsoft.AspNetCore.TestHost.TestServer to run tests against Web API running on ASP.NET Core 2.2.Our Web API is a single code base that would be deployed separately multiple times based on some configuration or application setting differences like country , currency...
public class TestStartup : IStartup { public IServiceProvider ConfigureServices ( IServiceCollection services ) { var configuration = new ConfigurationBuilder ( ) .SetBasePath ( Directory.GetCurrentDirectory ( ) ) .AddJsonFile ( `` appsettings.json '' , false ) .AddEnvironmentVariables ( ) .Build ( ) ; services.AddMvc ...
Run single test against multiple configurations in Visual Studio
C#
If a type has no static constructor , field initializers will execute just prior to the type being used— or anytime earlier at the whim of the runtimeWhy this code : yields : while this code : yields The order of a and b is understood . but why dealing with static method is different than static field.I mean why the st...
void Main ( ) { `` -- -- -- -start -- -- -- - '' .Dump ( ) ; Test.EchoAndReturn ( `` Hello '' ) ; `` -- -- -- -end -- -- -- - '' .Dump ( ) ; } class Test { public static string x = EchoAndReturn ( `` a '' ) ; public static string y = EchoAndReturn ( `` b '' ) ; public static string EchoAndReturn ( string s ) { Console....
static constructors and BeforeFieldInit ?
C#
It is quite a while that I have been trying to understand the idea behind IEnumerable and IEnumerator . I read all the questions and answers I could find over the net , and on StackOverflow in particular , but I am not satisfied . I got to the point where I understand how those interfaces should be used , but not why t...
while ( enumerator.MoveNext ( ) ) { object item = enumerator.Current ; // logic } class Collection : IForeachable { private int [ ] array = { 1 , 2 , 3 , 4 , 5 } ; private int index = -1 ; public int Current = > array [ index ] ; public bool MoveNext ( ) { if ( index < array.Length - 1 ) { index++ ; return true ; } ind...
Why do we need two interfaces to enumerate a collection ?
C#
I have an array of { 0,1,2,3 } and want to shuffle it . This is working pretty wellsome of the time . However , I 'm finding that it often produces a stack of { 1,2,3,0 } where 0 is just placed on the back of the stack . In fact , often enough that this does n't appear random at all . An `` original sequence of 3 in th...
Public Function ShuffleArray ( ByVal items ( ) As Integer ) As Integer ( ) Dim ptr As Integer Dim alt As Integer Dim tmp As Integer Dim rnd As New Random ( ) ptr = items.Length Do While ptr > 1 ptr -= 1 alt = rnd.Next ( ptr - 1 ) tmp = items ( alt ) items ( alt ) = items ( ptr ) items ( ptr ) = tmp Loop Return itemsEnd...
ensuring a sequential stack of 3 does n't appear in a shuffled array of 4 ?
C#
I am new to GraphQL , when I try to upgrade .net core version from 2.2 to 3.0I got problem about UI display on /graphql page when using UseGraphiQlAPI is working normally but the UI is display incorrect.I googled for find out solutions , but nothing really helpful.Here is my config for graphql : Any help is greatly app...
services.AddRazorPages ( ) .SetCompatibilityVersion ( CompatibilityVersion.Version_3_0 ) ; app.UseGraphiQLServer ( new GraphiQLOptions ( ) ) ; app.UseGraphiQl ( `` /graphiql '' , `` /graphql '' ) ; app.UseEndpoints ( x = > { x.MapControllers ( ) ; } ) ;
Upgrade GraphQL from .NET core 2.2 to 3.0
C#
Been coding .net for years now yet I feel like a n00b . Why is the following code failing ? UpdateApproved the answer from CodeInChaos . Reason for the 16 bytes becomming 32 bytes can be read in his answer . Also stated in the answer : the default constructor of UTF8Encoding has error checking disabledIMHO the UTF8 enc...
byte [ ] a = Guid.NewGuid ( ) .ToByteArray ( ) ; // 16 bytes in arraystring b = new UTF8Encoding ( ) .GetString ( a ) ; byte [ ] c = new UTF8Encoding ( ) .GetBytes ( b ) ; Guid d = new Guid ( c ) ; // Throws exception ( 32 bytes recived from c ) byte [ ] a = Guid.NewGuid ( ) .ToByteArray ( ) ; string b = new UTF8Encodi...
It sould be so obvious , but why does this fail ?
C#
I 'm navigating the ins and outs of ref returns , and am having trouble emitting a dynamic method which returns by ref.Handcrafted lambdas and existing methods work as expected : But emitting a dynamic method fails . Note : I 'm using Sigil here . Apologies , I 'm less familiar with System.Reflection.Emit.This fails at...
class Widget { public int Length ; } delegate ref int WidgetMeasurer ( Widget w ) ; WidgetMeasurer GetMeasurerA ( ) { return w = > ref w.Length ; } static ref int MeasureWidget ( Widget w ) = > ref w.Length ; WidgetMeasurer GetMeasurerB ( ) { return MeasureWidget ; } WidgetMeasurer GetMeasurerC ( ) { FieldInfo lengthFi...
How can I emit a dynamic method returning a ref ?
C#
I try to Delete a Row from the Database on the phpAdmin the Query is workingfine , but when I execute it with the Code : I get theError : Destination array is not long enough to copy all the items in the collection . Check array index and length.I Insert the to deleting user before without any trouble.The Database has ...
MySqlCommand getUserID = new MySqlCommand ( `` SELECT UserID FROM User '' , connection ) ; MySqlDataReader reader = getUserID.ExecuteReader ( ) ;
MySqlException on ExecuteReader by Selecting UserID ( PK )
C#
I have a DLL written in C # .NET which exposes a COM interface , so a vb6 application can call my DLL . This interface looks like : This works fine . But each time I build this DLL without changing the interface ( because I had to fix something somewhere in the logic ) the reference with the vb6 application is broken a...
[ System.Runtime.InteropServices.Guid ( `` 3D2C106C-097F-4ED7-9E4F-CDBC6A43BDC4 '' ) ] public interface IZDPharmaManager { [ System.Runtime.InteropServices.DispId ( 2 ) ] SearchPatientEventArgs FoundPatient { get ; set ; } [ System.Runtime.InteropServices.DispId ( 3 ) ] IntPtr Start ( string server , string database , ...
c # .net COM dll breaks reference with vb6 application
C#
I am using FxCopCmd tool for static code analysis . Since we already had a huge codebase , we baselined existing issues using baseline.exe tool that comes with FxCop.I am observing that if I add a new method to my C # class , then some of the suppression messages in GlobalSuppression.cs file stop working and I get issu...
namespace ConsoleApplication1 { class Program { public async Task < string > method1 ( ) { string a = `` '' ; a.Equals ( `` abc '' , StringComparison.InvariantCultureIgnoreCase ) ; return a ; } static void Main ( string [ ] args ) { } } }
FxCop : Suppression message for async method
C#
I am writing a live-video imaging application and need to speed up this method . It 's currently taking about 10ms to execute and I 'd like to get it down to 2-3ms.I 've tried both Array.Copy and Buffer.BlockCopy and they both take ~30ms which is 3x longer than the manual copy.One thought was to somehow copy 4 bytes as...
public byte [ ] ApplyLookupTableToBuffer ( byte [ ] lookupTable , ushort [ ] inputBuffer ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; // Precalculate and initialize the variables int lookupTableLength = lookupTable.Length ; int bufferLength = inputBuffer.Length ; byte [ ] ...
How to optimize copying chunks of an array in C # ?
C#
I have the following objects structureIs there any way to make some kind of binding between these parent and child interfaces in DryIOC ? EDIT : I did some research and found that RegisterMany did the trick but I am a bit confused becauseIf I uncomment back individual registrations lines above , Resolve works for IActi...
public interface IParser { } public interface IAction : IParser { } public interface ICommand : IParser { } //implpublic class Action1 : IAction { } public class Command1 : ICommand { } //registrationcontainer.Register < IAction , Action1 > ( ) ; container.Register < ICommand , Command1 > ( ) ; //resolvevar parsersList...
How to resolve using parent hierarchy interfaces using DryIOC
C#
Note 1 : Here CPS stands for `` continuation passing style '' I would be very interested in understanding how to hook into C # async machinery.Basically as I understand C # async/await feature , the compiler is performing a CPS transform and then passes the transformed code to a contextual object that manages the sched...
async MyTask < BigInteger > Fib ( int n ) // hypothetical example { if ( n < = 1 ) return n ; return await Fib ( n-1 ) + await Fib ( n-2 ) ; } void Fib ( int n , Action < BigInteger > Ret , Action < int , Action < BigInteger > > Rec ) { if ( n < = 1 ) Ret ( n ) ; else Rec ( n-1 , x = > Rec ( n-2 , y = > Ret ( x + y ) )...
How to use C # async/await as a stand-alone CPS transform
C#
Is there a cost in passing an object to a function that implements a particular interface where the function only accepts that interface ? Like : and I pass : which all of them implements IEnumerable . But when you pass any of those to the Change method , are they cast to IEnumerable , thus there is a cast cost but als...
Change ( IEnumerable < T > collection ) List < T > LinkedList < T > CustomCollection < T >
C # interface question
C#
I 'm implementing an automatic `` evaluator '' for a course I 'm currently teaching . The overall idea is that every student delivers a DLL with some algorithms implemented . My evaluator loads all these DLLs using Reflection , finds the student implementations and evaluates them in a tournament . All these algorithms ...
public interface IContinuousMetaheuristic { // ... Some unimportant properties Vector Evaluate ( Function function , int maxEvaluations , ... ) ; } public class Function : { private Vector xopt ; // The optimum point private double fopt ; // The optimum value public double Evaluate ( Vector x ) ; }
Avoiding user code calling to Reflection in C #
C#
Today I was debugging some code of mine that builds a few ExpressionTrees , compiles them to callable Delegates and calls them afterwards if required . While doing this I encountered a FatalExecutionEngineError stepping through the code : At first I was a little bit shocked since I had no idea what could have been poss...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Linq.Expressions ; using System.Reflection ; using System.Text ; using System.Threading.Tasks ; namespace ExpressionProblem { public class MainClass { public static void DoSomething ( bool stop ) { var method = typeof ( MainClass ) .GetM...
C # Expressions - FatalExecutionEngineError
C#
IEnumerable is a query that is lazily evaluated . But apparently my understanding is a bit flawed . I 'd expect the following to work : What am I misunderstanding here ? How can I alter the results of what this query returns ?
// e.Result is JSON from a server JObject data = JObject.Parse ( e.Result ) ; JsonSerializer serializer = new JsonSerializer ( ) ; // LINQ query to transform the JSON into Story objects var stories = data [ `` nodes '' ] .Select ( obj = > obj [ `` node '' ] ) .Select ( storyData = > storyOfJson ( serializer , storyData...
Changes to an IEnumerable are not being kept between queries
C#
first time posting , please be kind ! : - ) New to VB/C # , Trying to fix up a CLR function that calls a web service . I 've cobbled together the following : This will only return 4000 characters even though it is coded for sqlChars . The API call could potentially return upwards of 14MB during a full inventory pull . ...
using System ; using System.Data ; using System.Data.SqlClient ; using System.Data.SqlTypes ; using System.Collections ; using System.Globalization ; // For the SQL Server integrationusing Microsoft.SqlServer.Server ; // Other things we need for WebRequestusing System.Net ; using System.Text ; using System.IO ; public ...
CLR function will not return more than 4000 chars
C#
I think there are people who may be able to answer this , this is a question out of curiosity : The generic CreateInstance method from System.Activator , introduced in .NET v2 has no type constraints on the generic argument but does require a default constructor on the activated type , otherwise a MissingMethodExceptio...
Activator.CreateInstance < T > ( ) where T : new ( ) { ... } private T Create < T > ( ) where T : struct , new ( ) error CS0451 : The 'new ( ) ' constraint can not be used with the 'struct ' constraint
More trivia than really important : Why no new ( ) constraint on Activator.CreateInstance < T > ( ) ?
C#
I would like to build a facebook application similar to nametest or Meaww and almost succeeded to have my API calls to Facebook Graph API and return data from facebook.What makes me confused is the UI of aforementioned web applications . When you complete a test on Meaww or Nametests the result is represented to the us...
public async Task < ActionResult > FB_Analyse ( ) { var access_token = HttpContext.Items [ `` access_token '' ] .ToString ( ) ; if ( ! string.IsNullOrEmpty ( access_token ) ) { var appsecret_proof = access_token.GenerateAppSecretProof ( ) ; var fb = new FacebookClient ( access_token ) ; # region FacebookUser Name and P...
Is there anyway to make one image out of 3 image URLs using asp.net mvc ?
C#
Assume that I have a class that exposes the following event : How should methods that are registered to this event be named ? Do you prefer to follow the convention that Visual Studio uses when it assigns names to the methods it generates ( aka . += , Tab , Tab ) ? For example : Or do you use your own style to name the...
public event EventHandler Closing private void TheClass_Closing ( object sender , EventArgs e )
Naming methods that are registered to events
C#
F # provides a feature , where a function can return another function . An example of function generating a function in F # is : The best way I could come up with to achieve the same in C # was this : Is there some other way ( /better way ) of doing this ?
let powerFunctionGenarator baseNumber = ( fun exponent - > baseNumber ** exponent ) ; let powerOfTwo = powerFunctionGenarator 2.0 ; let powerOfThree = powerFunctionGenarator 3.0 ; let power2 = powerOfTwo 10.0 ; let power3 = powerOfThree 10.0 ; printfn `` % f '' power2 ; printfn `` % f '' power3 ; class Program { delega...
Best way to generate a function that generates a function in C #
C#
I 'm loading in a solution in the MSBuildWorkspace : Projects without ProjectReferences show all MetadataReferences , including mscorlib . Projects with ProjectReferences have an empty collection of MetadataReferences . As compilation works , I guess the compiler platform for some reason is not populating this collecti...
var msWorkspace = MSBuildWorkspace.Create ( ) ; var solution = msWorkspace.OpenSolutionAsync ( solutionPath ) .Result ;
Project MetadataReferences is not populated when ProjectReferences are present
C#
I have a User entity which has a HasCompletedSecurity property which indicates whether that particular User has answered the number of security questions required by the system . The number of security questions the system requires is configurable and retrieved from a config file . How should the User class access the ...
public class User { private static readonly IConfigurationService _configurationService = InjectionService.Resolve < IConfigurationService > ( ) ; public bool HasCompletedSecurity { get { // Uses the static _configurationService to get the // configured value : int numberOfRequiredResponses = GetConfiguredNumberOfRequi...
Domain Driven Design : access a configured value from an Entity without using a Service Locator
C#
My code calls a WCF service that is current not running . So we should expect the EndPointNotFoundException . The using statement tries to Close ( ) the faulted connection which causes a CommunicationObjectFaultedException which is excepted . This exception is caught in a try catch block surrounding the using block : N...
class Program { static void Main ( ) { try { using ( ChannelFactory < IDummyService > unexistingSvc = new ChannelFactory < IDummyService > ( new NetNamedPipeBinding ( ) , `` net.pipe : //localhost/UnexistingService- '' + Guid.NewGuid ( ) .ToString ( ) ) ) { using ( IClientChannel chan = ( unexistingSvc.CreateChannel ( ...
Visual studio breaks on exception that IS handled with unhandled exception dialog
C#
I managed to consume a java based web service ( third party ) with WS-Security 1.1 protocol . The web service needs only to be signed over a x509 certificate , not encrypted.But I 'm getting this error : The signature confirmation elements can not occur after the primary signature.The captured server response package l...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < soapenv : Envelope xmlns : soapenv= '' http : //www.w3.org/2003/05/soap-envelope '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < soapenv : Header > < wsse : Security xmlns : wsse= '' http :...
WCF Client consuming WS-Security webservice
C#
Here is a part of my code : I expect testBranches will be https : //127.0.0.1:8443/svn/CXB1/Validation/branches/test , but it is https : //127.0.0.1:8443/svn/CXB1/Validation/test . I can not understand why Uri ( Uri , string ) constructor eats the last part of the path .
Uri branches = new Uri ( @ '' https : //127.0.0.1:8443/svn/CXB1/Validation/branches '' ) ; Uri testBranch = new Uri ( branches , `` test '' ) ;
Uri ( Uri , String ) constructor does not works properly ?
C#
On the current project we are working on we have n't upgraded to MVC 2.0 yet so I 'm working on implementing some simple validation with the tools available in 1.0.I 'm looking for feedback on the way I 'm doing this.I have a model that represents a user profile . Inside that model I have a method that will validate al...
public FooController : Controller { public ActionResult Edit ( User user ) { user.ValidateModel ( this ) ; if ( ModelState.IsValid ) ... ... . ... ... . } } public void ValidateModel ( Controller currentState )
Simple ASP.Net MVC 1.0 Validation
C#
I tried to use firewallAPI.dll to add a rule . It works fine for calc.exe ( or some other files ) as described bellow but fails for msdtc.exe with the following exception : System.IO.FileNotFoundException : 'The system can not find the file specified . ( Exception from HRESULT : 0x80070002 ) 'Example : Note : I checked...
static void Main ( string [ ] args ) { var manager = GetFirewallManager ( ) ; if ( manager.LocalPolicy.CurrentProfile.FirewallEnabled ) { var path = @ '' C : \Windows\System32\calc.exe '' ; //var path = @ '' C : \Windows\System32\msdtc.exe '' ; // System.IO.FileNotFoundException : 'The system can not find the file spec...
Add a firewall rule for Distributed Transaction Coordinator ( msdtc.exe )
C#
I have the following code : What 's the difference between passing a pointer and a ref keyword as a parameter in the method ?
class Program { private unsafe static void SquarePtrParam ( int* input ) { *input *= *input ; } private static void SquareRefParam ( ref int input ) { input *= input ; } private unsafe static void Main ( ) { int value = 10 ; SquarePtrParam ( & value ) ; Console.WriteLine ( value ) ; int value2 = 10 ; SquareRefParam ( r...
What is the difference between referencing a value using a pointer and a ref keyword
C#
When generating GetHashCode ( ) implementation for anonymous class , Roslyn computes the initial hash value based on the property names . For example , the class generated foris going to have the following GetHashCode ( ) method : But if we change the property names , the initial value changes : What 's the reason behi...
var x = new { Int = 42 , Text = `` 42 '' } ; public override in GetHashCode ( ) { int hash = 339055328 ; hash = hash * -1521134295 + EqualityComparer < int > .Default.GetHashCode ( Int ) ; hash = hash * -1521134295 + EqualityComparer < string > .Default.GetHashCode ( Text ) ; return hash ; } var x = new { Int2 = 42 , T...
Why does initial hash value in GetHashCode ( ) implementation generated for anonymous class depend on property names ?
C#
I need to find out what the current Row index from within a foreach loop.An exception can occur at any point within the try/catch block , but if I use an incremental counter within the foreach loop , and the exception occurs outside of the loop , I 'll get an invalid row because I 've moved the pointer along by one.I k...
foreach ( DataRow row in DataTable [ 0 ] .Rows ) { // I do stuff in here with the row , and if it throws an exception // I need to pass out the row Index value to the catch statement } int i = 0 ; try { // Some code here - which could throw an exception foreach ( DataRow row in DataTables [ 0 ] .Rows ) { // My stuff i+...
Clean implementation of storing current row index
C#
I use EntityFramework 4 + generated POCOs with Lazy loading disabled.Let 's say there are SQL tables named Table1 , Table2 , Table3 and Table4 and assume they contain some data.Let 's assume the simplified POCO representation of these tables looks like this : If the following code would be executed : EF would generate ...
public class Table1 { public int ID ; public DateTime TableDate ; public int Table2ID ; public Table2 Table2 ; public ICollection < Table3 > Table3s ; } public class Table2 { public int ID ; public string SomeString ; public int Table4ID ; public Table4 Table4 ; } public class Table3 { public int ID ; public int Table1...
Query returning nothing when there is data in the database
C#
Update ! See my dissection of a portion of the C # spec below ; I think I must be missing something , because to me it looks like the behavior I 'm describing in this question actually violates the spec.Update 2 ! OK , upon further reflection , and based on some comments , I think I now understand what 's going on . Th...
class Type0 { public string Value { get ; private set ; } public Type0 ( string value ) { Value = value ; } } class Type1 : Type0 { public Type1 ( string value ) : base ( value ) { } public static implicit operator Type1 ( Type2 other ) { return new Type1 ( `` Converted using Type1 's operator . `` ) ; } } class Type2 ...
Equivalent implicit operators : why are they legal ?
C#
I came accross the following code today and I did n't like it . It 's fairly obvious what it 's doing but I 'll add a little explanation here anyway : Basically it reads all the settings for an app from the DB and the iterates through all of them looking for the DB Version and the APP Version then sets some variables t...
using ( var sqlConnection = new SqlConnection ( Lfepa.Itrs.Framework.Configuration.ConnectionString ) ) { sqlConnection.Open ( ) ; var dataTable = new DataTable ( `` Settings '' ) ; var selectCommand = new SqlCommand ( Lfepa.Itrs.Data.Database.Commands.dbo.SettingsSelAll , sqlConnection ) ; var reader = selectCommand.E...
A C # Refactoring Question
C#
Suppose I have following program : I can not understand compiled il code ( it uses too extra code ) . Here is simplified version : Why does compiler create not static equal methods b/b1 ? Equal means that they have the same code
static void SomeMethod ( Func < int , int > otherMethod ) { otherMethod ( 1 ) ; } static int OtherMethod ( int x ) { return x ; } static void Main ( string [ ] args ) { SomeMethod ( OtherMethod ) ; SomeMethod ( x = > OtherMethod ( x ) ) ; SomeMethod ( x = > OtherMethod ( x ) ) ; } class C { public static C c ; public s...
Weird behaviour of c # compiler due caching delegate
C#
Any suggestion how to make the below query more `` readable '' ? Its difficult to read with the long code of condition and value .
var result = result .OrderBy ( a = > ( conditionA ) ? valueA : ( conditionB ? valueB : ( conditionC ? ( conditionD ? valueC : valueD ) : valueE ) ) ) ;
Ternary operator difficult to read
C#
I hear that Nullable < T > is a C # generic class and it does not work with COM - like any other generic class.Well , in my C # class library I have : Surprisingly that compiles and I am able to attach references to my COMClass library in VBE.I know that : VBA does not list .GetNullable ( ) in the list of members on Ob...
[ InterfaceType ( ComInterfaceType.InterfaceIsDual ) , Guid ( `` 2FCEF713-CD2E-4ACB-A9CE-E57E7F51E72E '' ) ] public interface ICOMClass { int ? GetNullable ( ) ; } [ ClassInterface ( ClassInterfaceType.None ) ] [ Guid ( `` 57BBEC44-C6E6-4E14-989A-B6DB7CF6FBEB '' ) ] public class COMClass : ICOMClass { public int ? GetN...
How does a COM server marshal nullable in C # class library with different ComInterfaceType Enumerations ?
C#
Does using the braced initializer on a collection type set it 's capacity or do you still need to specify it ? That is , does : result in the same as this :
var list = new List < string > ( ) { `` One '' , `` Two '' } ; var list = new List < string > ( 2 ) { `` One '' , `` Two '' } ;
Does using the braced initializer on collection types set the initial capacity ?
C#
Had to pick up a bit of work from another developer so just trying to wrap my head round it all ! But I 'm having issues building an Azure Functions project and continuously getting a error coming form Microsoft.NET.Sdk.Functions.Build.targets , specifically unable to resolve a reference to Microsoft.Azure.WebJobs.Exte...
Severity Code Description Project File Line Suppression StateError Mono.Cecil.AssemblyResolutionException : Failed to resolve assembly : 'Microsoft.Azure.WebJobs.Extensions , Version=3.0.6.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 ' at Mono.Cecil.BaseAssemblyResolver.Resolve ( AssemblyNameReference name , R...
Failed to resolve for reference Microsoft.Azure.WebJobs.Extensions - Metadata generation failed
C#
Apps downloaded from the Windows Store are installed in this location : If you look inside this folder you can access each application 's .exe and use reflector to decompile them.Currently , my Windows RT application sends a password over SSL to a WCF service to ensure that only people using my app can access my databa...
C : \Program Files\WindowsApps
What can I do to stop other people running my Windows RT code ?
C#
I 'm attempting to find a minimized window and Show it.The program can be downloaded from Samsung and it is titled `` SideSync '' . To fully replicate my question you would need to install this and also have a Samsung phone to plug in to your computer . Here is a screen shot of it fully configured and running : Observe...
public static Process GetProcessByWindowTitle ( string windowTitleContains ) { foreach ( var windowProcess in GetWindowProcesses ( ) ) if ( windowProcess.MainWindowTitle.Contains ( windowTitleContains ) ) return windowProcess ; return null ; } [ Ignore ( `` Requires starting SideSync and clicking one of the windows . O...
C # minimized windows not being returned by call to System.Diagnostics.Process.GetProcesses ( )
C#
I have a form which I 'm bringing up using ShowDialog which contains a couple of text boxes , labels and a button . The problem I 'm having is that the text boxes are being drawn before the form itself and the other controls are drawn.I am overriding the OnPaint method I 'm not sure if this could be causing the problem...
protected override void OnPaint ( PaintEventArgs e ) { ControlPaint.DrawBorder ( e.Graphics , e.ClipRectangle , Color.Black , ButtonBorderStyle.Solid ) ; base.OnPaint ( e ) ; }
Controls not being drawn at the same time
C#
I have a form in HTML which contains multiple same name fields . For example : Now on the server side ( C # ) , I have an action method and a model class Product : Now my question is : I am submitting the form using jquery $ .ajax method . On the server side the action method accepts a Product class array . Now how can...
< form action= '' '' method= '' post '' id= '' form '' > < div class= '' itemsection '' id= '' item1 '' > < input type= '' text '' name= '' Price '' / > < input type= '' text '' name= '' Name '' / > < input type= '' text '' name= '' Catagory '' / > < /div > < div class= '' itemsection '' id= '' item2 '' > < input type=...
How to serialize the form fields and send it to server , jquery ?
C#
I 've an array of objects DataTestplans from which I try to retrieve records for a particular DataID and ProductID using the LINQ query shown , my current query has Distinct ( ) which distiguishes on all 5 mentioned properties , how do I retrieve distinct records based on properties DataID , TestPlanName , TCIndexList ...
[ { `` DataTestPlanID '' : 0 , `` DataID '' : 19148 , `` TestPlanName '' : `` string '' , `` TCIndexList '' : `` string '' , `` ProductID '' : 2033915 } , { `` DataTestPlanID '' : 0 , `` DataID '' : 19148 , `` TestPlanName '' : `` string '' , `` TCIndexList '' : `` string '' , `` ProductID '' : 2033915 } , { `` DataTes...
how do I write LINQ query to retrieve distinct records based on only specific properties ?
C#
I am trying to achieve something like this : So I can do something like this : Is this possible ?
interface IAbstract { string A { get ; } object B { get ; } } interface IAbstract < T > : IAbstract { T B { get ; } } class RealThing < T > : IAbstract < T > { public string A { get ; private set ; } public T B { get ; private set ; } } RealThing < string > rt = new RealThing < string > ( ) ; IAbstract ia = rt ; IAbstr...
Generics IAbstract < T > inherits from IAbstract
C#
Yes , I am using a profiler ( ANTS ) . But at the micro-level it can not tell you how to fix your problem . And I 'm at a microoptimization stage right now . For example , I was profiling this : ANTS showed that the y-loop-line was taking a lot of time . I thought it was because it has to constantly call the Height get...
for ( int x = 0 ; x < Width ; x++ ) { for ( int y = 0 ; y < Height ; y++ ) { packedCells.Add ( Data [ x , y ] .HasCar ) ; packedCells.Add ( Data [ x , y ] .RoadState ) ; packedCells.Add ( Data [ x , y ] .Population ) ; } }
How do I learn enough about CLR to make educated guesses about performance problems ?
C#
Consider this example code : Here B.TheT is null . However , changing the Main method like this : B.TheT is `` Test '' , as expected . I can understand that this forces the static constructor to run , but why does this not happen for the first case ? I tried reading the spec , and this caught my attention ( §10.12 ) : ...
public class A < T > { public static T TheT { get ; set ; } } public class B : A < string > { static B ( ) { TheT = `` Test '' ; } } public class Program { public static void Main ( String [ ] args ) { Console.WriteLine ( B.TheT ) ; } } public static void Main ( ) { new B ( ) ; Console.WriteLine ( B.TheT ) ; }
Static initialization of inherited static member
C#
Using C # for ASP.NET and MOSS development , we often have to embed JavaScript into our C # code . To accomplish this , there seems to be two prevalent schools of thought : The other school of thought is something like this : Is there a better way than either of these two methods ? I like the second personally , as you...
string blah = `` asdf '' ; StringBuilder someJavaScript = new StringBuilder ( ) ; someJavaScript.Append ( `` < script language='JavaScript ' > '' ) ; someJavaScript.Append ( `` function foo ( ) \n '' ) ; someJavaScript.Append ( `` { \n '' ) ; someJavaScript.Append ( `` var bar = ' { 0 } ' ; \n '' , blah ) ; someJavaScr...
How do you embed other programming languages into your code ?
C#
In C # you can refer to values in a class using the 'this ' keyword.While I presume the answer will likley be user preference , is it best practice to use the this keyword within a class for local values ?
class MyClass { private string foo ; public string MyMethod ( ) { return this.foo ; } }
Should you always refer to local class variables with `` this ''
C#
I have a piece of software written with fluent syntax . The method chain has a definitive `` ending '' , before which nothing useful is actually done in the code ( think NBuilder , or Linq-to-SQL 's query generation not actually hitting the database until we iterate over our objects with , say , ToList ( ) ) .The probl...
//The `` factory '' class the user will be dealing withpublic class FluentClass { //The entry point for this software public IntermediateClass < T > Init < T > ( ) { return new IntermediateClass < T > ( ) ; } } //The class that actually does the workpublic class IntermediateClass < T > { private List < T > _values ; //...
How to enforce the use of a method 's return value in C # ?
C#
I 'm using Newtonsoft JSON library and I 'm trying to deserialize a JSON . The problem is that when I use [ JsonConverter ( typeof ( StringEnumConverter ) ) ] I get this error : Can not apply attribute class 'JsonConverter ' because it is abstract.Here are my classes : I get the squiggly line under the JsonConverter.ED...
public class ActionRepository { [ JsonConverter ( typeof ( StringEnumConverter ) ) ] public enum AllowedActions { FINDWINDOW , } public enum AllowedParameters { WINDOWNAME , } } public class Action { public AllowedActions Name { get ; set ; } public List < Parameter > Parameters { get ; set ; } }
Can not apply attribute class 'JsonConverter ' because it is abstract
C#
I have a code which updates an array based on values in another , small array.Where c is a struct that is a pair of bytes representing cards from a deck.one is an array size of 52 ( with entries for each of 52 cards from a deck ) I wrote a benchmark to profile this code : Setting testRepetitions = 25 million , and usin...
for ( var i = 0 ; i < result.Length ; i++ ) { var c = cards [ i ] ; result [ i ] -= one [ c.C0 ] + one [ c.C1 ] ; } private void TestCards2 ( int testRepetitions , float [ ] result , float [ ] one , Cards [ ] cards ) { for ( var r = 0 ; r < testRepetitions ; r++ ) for ( var i = 0 ; i < result.Length ; i++ ) { var c = c...
Accessing 5-byte struct is much slower than 8-byte
C#
return confControl ; throws an exception : Can not implicitly convert type ConfigControlBase < ProviderX > to ConfigControlBase < ProviderBase >
public class ConfigControlBase < T > : UserControl where T : ProviderBase { public T Provider { get ; set ; } public void Init ( T provider ) { this.Provider = provider ; } } public abstract class ProviderBase { public abstract ConfigControlBase < ProviderBase > GetControl ( ) ; } public class ProviderXConfigControl : ...
Casting a generic element type downwards
C#
What 's the simple way to add the dollar sign ( ' $ ' ) or currency to a decimal data type on the following query : Thanks for the help !
SELECT TOP 100000 SUM ( [ dbo ] . [ Entry ] . [ Amount ] ) AS 'Total Charges '
How to convert , cast , or add ' $ ' to a decimal SQL SUM ( )
C#
In Perl I can sayWhat is the equivalent of this in C # ASP.NET ? Specifically what I 'm looking for is something so that other members of my team can know when they 're still using a deprecated routine . It should show up at run time when the code path is actually hit , not at compile time ( otherwise they 'd get warni...
use warnings ; warn `` Non-fatal error condition , printed to stderr . `` ;
What 's the C # equivalent of perl warn ?
C#
This question is not so much about finding a solution as about getting an explanation for the bizarrest behavior I have ever seen from SQL Server.I had a stored procedure with the following signature : Given a certain set of parameters , this proc was taking a very long time to run from C # ( using SqlCommand.ExecuteRe...
alter procedure MySP @ param1 uniqueidentifier , @ param2 uniqueidentifier , @ param3 uniqueidentifier declare @ param1_copy uniqueidentifier , @ param2_copy uniqueidentifier , @ param3_copy uniqueidentifierselect @ param1_copy = @ param1 , @ param2_copy = @ param2 , @ param3_copy = @ param3
Stored procedure performance - this is WILD ?