lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
Overloading the comparison operator , how to compare if the two variables points to the same object ( i.e . not value )
public static bool operator == ( Landscape a , Landscape b ) { return a.Width == b.Width & & a.Height == b.Height ; } public static bool operator ! = ( Landscape a , Landscape b ) { return ! ( a.Width == b.Width & & a.Height == b.Height ) ; }
After overloading the operator== , how to compare if two variables points at the same object ?
C#
Pretty basic question , but I ca n't seem to find the answer anywhere.How do you specify a new instance of a Dictionary < string , string > in SOAP ? Basically I have this envelope ( ommitted envelope top level tag for readability ) : RequestInfo is the property in question , but it 's always null . I assumed that just...
< soapenv : Body > < tem : LogInWithCredentials > < tem : Request > < ttf1 : Password > password < /ttf1 : Password > < ttf1 : UserName > username < /ttf1 : UserName > < ttf1 : RequestInfo > < /ttf1 : RequestInfo > < /tem : Request > < /tem : LogInWithCredentials > < /soapenv : Body >
Creating a new Dictionary in a SOAP Envelope
C#
Why is it necessary to use the new keyword when a method shall be hidden ? I have two classes : Following code produces the given output : Output : ParentOutput : ChildI understand that this might be a problem if it the hiding was not intended but is there any other reason to use `` new '' ( excepted avoding of warning...
public class Parent { public void Print ( ) { Console.WriteLine ( `` Parent '' ) ; } } public class Child : Parent { public void Print ( ) { Console.WriteLine ( `` Child '' ) ; } } Parent sut = new Child ( ) ; sut.Print ( ) ; Child sut = new Child ( ) ; sut.Print ( ) ; public void foo ( Parent p ) { p.Print ( ) ; } Chi...
Why using `` new '' when hiding methods ?
C#
With this code : ... I 'm stopped dead in my tracks with So how do I accomplish this ?
private bool AtLeastOnePlatypusChecked ( ) { return ( ( ckbx1.IsChecked ) || ( ckbx2.IsChecked ) || ( ckbx3.IsChecked ) || ( ckbx4.IsChecked ) ) ; } Operator '|| ' can not be applied to operands of type 'bool ? ' and 'bool ?
How can I return a bool value from a plethora of nullable bools ?
C#
I am working on trying to close a specific MessageBox if it shows up based on the caption and text . I have it working when the MessageBox does n't have an icon.The above code works just fine when the MessageBox is shown without an icon like the following.However , if it includes an icon ( from MessageBoxIcon ) like th...
IntPtr handle = FindWindowByCaption ( IntPtr.Zero , `` Caption '' ) ; if ( handle == IntPtr.Zero ) return ; //Get the Text window handleIntPtr txtHandle = FindWindowEx ( handle , IntPtr.Zero , `` Static '' , null ) ; int len = GetWindowTextLength ( txtHandle ) ; //Get the textStringBuilder sb = new StringBuilder ( len ...
How to get the text of a MessageBox when it has an icon ?
C#
On the form called `` Dev '' I have the following OnFormClosing function to make sure a thread is closed properly when a user closes the form.Works fine if I close the `` Dev '' form directly . But if the `` Dev '' form closes because the main form ( `` Form1 '' ) was closed ( which causes the program to exit ) the OnF...
protected override void OnFormClosing ( FormClosingEventArgs e ) { base.OnFormClosing ( e ) ; dev.stopMultipleColorsWatcher ( ) ; } private void btn_opendev_Click ( object sender , EventArgs e ) { Dev frm = new Dev ( ) ; frm.Show ( ) ; } static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompati...
Forms not closing properly if terminated due to program exit / main form close
C#
I have an action method like this below.I have a model with the following classes , which I 'd like to load the data from the ajax JSON data . Here is the JSON data . DefaultModelBinder is handling the nested object structure but it ca n't resolve the different sub classes . What would be the best way to load List with...
[ AcceptVerbs ( HttpVerbs.Post ) ] public ActionResult Create ( Form newForm ) { ... } public class Form { public string title { get ; set ; } public List < FormElement > Controls { get ; set ; } } public class FormElement { public string ControlType { get ; set ; } public string FieldSize { get ; set ; } } public clas...
DefaultModelBinder and collection of inherited objects
C#
I 'm trying to implement something like the idea I 'm trying to show with the following diagram ( end of the question ) .Everything is coded from the abstract class Base till the DoSomething classes.My `` Service '' needs to provide to the consumer `` actions '' of the type `` DoSomethings '' that the service has `` re...
public async Task < Obj1 < XXXX > > DoSomething1 ( ... .params ... . ) { var action = new DoSomething1 ( contructParams ) ; return await action.Go ( ... .params ... . ) ; } var myCarService = new CarService ( ... paramsX ... ) ; var res1 = myCarService.StartEngine ( ... paramsY ... ) ; var res2 = myCarService.SellCar (...
C # how to `` register '' class `` plug-ins '' into a service class ?
C#
I 'm writing custom security attribute and got strange compiler behaviour ... When I 'm using the attribute at the same file , default parameter values works fine : But when I 'm separating the code above into two files like that - file 1 : And file 2 : I 've got an compiler error : Error : 'FooAttribute ' does not con...
using System.Security.Permissions ; [ System.Serializable ] sealed class FooAttribute : CodeAccessSecurityAttribute { public FooAttribute ( SecurityAction action = SecurityAction.Demand ) : base ( action ) { } public override System.Security.IPermission CreatePermission ( ) { return null ; } } [ Foo ] class Program { s...
Is this an C # 4.0 compiler optional parameters bug ?
C#
Why is n't it possible to cast an instance of : ... to this interface : ... even though Foo has the signature of IBar ? How can I turn an instance of Foo into an IBar ? Assume I have no control over Foo .
sealed class Foo { public void Go ( ) { } } interface IBar { void Go ( ) ; }
Possible to cast to interface that is n't inherited ?
C#
i have a stupid question , but i want to hear the community here.So here is my code : My question , is it any different than : Which one is better in general ? which one in terms of GC and why ?
using ( FtpWebResponse response = ( FtpWebResponse ) request.GetResponse ( ) ) { return true ; } ( FtpWebResponse ) request.GetResponse ( ) ; return true ;
Do I need to dispose of a resource which is not actually used ?
C#
Consider the following piece of code : As you can see we are on line 28 . Is there any way to see the return value of the function at this point , without letting the code return to the caller function ? Foo.Bar ( ) is a function call which generates a unique path ( for example ) . So it 's NOT constant.Entering ? Foo....
? Foo.Bar ( ) '' 80857466 '' ? Foo.Bar ( ) '' 2146375101 '' ? Foo.Bar ( ) '' 1106609407 '' ? Foo.Bar ( ) '' 792759112 ''
See return value in C #
C#
I happened upon this in an NHibernate class definition : So this class inherits from a base class that is parameterized by ... the derived class ? My head just exploded . Can someone explain what this means and how this pattern is useful ? ( This is NOT an NHibernate-specific question , by the way . )
public class SQLiteConfiguration : PersistenceConfiguration < SQLiteConfiguration >
C # unusual inheritance syntax w/ generics
C#
Say I have the following : Two Questions:1.I 'm a little confused on when my IDisposable members would actually get called . Would they get called when an instance of CdsUpperAlarmLimit goes out of scope ? 2.How would I handle disposing of objects created in the CdsUpperAlarmLimit class ? Should this also derive from I...
public abstract class ControlLimitBase : IDisposable { } public abstract class UpperAlarmLimit : ControlLimitBase { } public class CdsUpperAlarmLimit : UpperAlarmLimit { }
IDisposable Question
C#
Consider this code : Results : Why are the results different between List < T > and Array ? I guess this is by design , but why ? Looking at the code of List < T > .IndexOf makes me wonder even more , since it 's porting to Array.IndexOf .
public static void Main ( ) { var item = new Item { Id = 1 } ; IList list = new List < Item > { item } ; IList array = new [ ] { item } ; var newItem = new Item { Id = 1 } ; var lIndex = list.IndexOf ( newItem ) ; var aIndex = array.IndexOf ( newItem ) ; Console.WriteLine ( lIndex ) ; Console.WriteLine ( aIndex ) ; } p...
Why is Array.IndexOf not checking for IEquatable like List < T > does ?
C#
I wanted to create an observableCollection that is sortableso i started creating a class that inherit observable with some methods to sort it , then i wanted that class to persist the index into the childs , so i created an interface that expose an index property where i can write to , and i costrainted the T of my col...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ClassLibrary1 { public class SortableCollection < T > : System.Collections.ObjectModel.ObservableCollection < T > , ISortableCollection < T > where T : ISortable < T > { public void Sort ( ...
Covariance in generic interfaces
C#
I 'm trying to use a Microsoft.Toolkit.Wpf.UI.Controls.WebView control in a wpf desktop application . It seems to use substantially less resouces than the webbrowser control and is much more up to date , being based on edge . However , unlike the webbrowser control , it wo n't scroll unless selected . i.e . When the mo...
< Window x : Class= '' test0.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : WPF= '' clr-namespace : Microsoft.Toolkit.Wpf.UI.Controls ; assembly=Microsoft.Toolkit.Wpf.UI.Controls.WebView '' Title= '' MainWind...
how to make wpf webview scroll like webbrowser ?
C#
Why is it not possible to use implicit conversion when calling an extension method ? Here is the sample code : Error i get : 'int ' does not contain a definition for 'ToNumberString ' and the best extension method overload 'Ext.ToNumberString ( decimal ) ' requires a receiver of type 'decimal'As we can see . An implici...
using System ; namespace IntDecimal { class Program { static void Main ( string [ ] args ) { decimal d = 1000m ; int i = 1000 ; d = i ; // implicid conversion works just fine Console.WriteLine ( d.ToNumberString ( ) ) ; // Works as expected Console.WriteLine ( i.ToNumberString ( ) ) ; // Error Console.WriteLine ( ToNum...
Implicit conversion when calling an extension method not possible
C#
Often I have a bit of code I want to execute from time to time , for example seed the database , drop the database , download some data from the database and collate it in some funny way . All of these tasks can be represented as independent functions in C # . Ala a console app : Here , I comment out the function I do ...
class Program { static void Task1 ( ) { } static void Task2 ( ) { } static void Main ( ) { //Task1 ( ) ; //Task2 ( ) ; } }
Is there any extension to visual studio that allows to run functions as tasks ?
C#
I have a partial view that is using a different model than the view that I 'm rendering it in . I keep getting the error message . The model item passed into the dictionary is of type 'JHelpWebTest2.Models.CombinedModels ' , but this dictionary requires a model item of type 'JHelpWebTest2.Models.PagedStudentModel'.I 'm...
@ using System.Activities.Expressions @ using JHelpWebTest2.Models @ model JHelpWebTest2.Models.CombinedModels @ using ( Html.BeginForm ( `` _Grid '' , `` Sort '' ) ) { @ Html.Partial ( `` ~/Views/Sort/_Grid.cshtml '' ) } @ model JHelpWebTest2.Models.PagedStudentModel @ using JHelpWebTest2.Models ; < div id= '' grid ''...
Different Model in Partial View
C#
I fixed all the problems described here ( and one additional ) , and posted the modifiedcsharp-mode.el ( v0.7.1 ) at emacswikiThe csharp-mode I use is almost really good . It works for most things , but has a few problems : # if / # endif tags break indentation , but only within the scope of a method.attributes applied...
using System ; using System.IO ; using System.Linq ; using System.Collections.Generic ; using System.Runtime.InteropServices ; using System.Xml.Serialization ; namespace Cheeso.Says.TreyIsTheBest { public class Class1 { private void Method1 ( ) { // Problem 1 : the following if / endif pair causes indenting to break . ...
How can I fix csharp-mode.el ?
C#
I need to recover JSON stored in RavenDb database knowing its Id . What 's tricky here , I need to get it before it is deserialized into an actual object . Reason for that is , I need it in exact same form it was first stored in , regardless what happens to the CLR class ( it can drastically change or even be removed )...
using ( var session = Store.OpenSession ( ) ) { return JsonConvert.SerializeObject ( session.Load < object > ( id ) ) ; } class Object_AsJson : AbstractIndexCreationTask < JsonObject > { public Configuration_AsJson ( ) { Map = configuration = > configuration.Select ( x = > AsJson ( x ) .Select ( y = > y.Value ) ) ; } }...
RavenDb get raw JSON without deserialization
C#
I have around 6 WCF services that I want to host in an MVC application , routing requests to /services/foo to WcfFooService and /services/bar to WcfBarServiceI can accomplish IoC with StructureMap within the services and inject my constructor dependencies by using the example that Jimmy Bogard blogged about here : Jimm...
public class StructureMapServiceHostFactory : ServiceHostFactory { public StructureMapServiceHostFactory ( ) { ObjectFactory.Initialize ( x = > x.AddRegistry < FooRegistry > ( ) ) ; //var iTriedThisToo = ObjectFactory.Container ; //container.Configure ( x = > x . [ etc ] ) ; } protected override ServiceHost CreateServi...
How can I host multiple IoC-driven WCF services in MVC ?
C#
I have a bunch of systems , lets call them A , B , C , D , E , F , G , H , I , J.They all have similar methods and properties . Some contain the exact same method and properties , some may vary slightly and some may vary a lot . Right now , I have a lot of duplicated code for each system . For example , I have a method...
public Interface ISystem { public void GetPropertyInformation ( ) ; //Other methods to implement } public class A : ISystem { public void GetPropertyInformation ( ) { //Code here } } public abstract class System { public virtual void GetPropertyInformation ( ) { //Standard Code here } } public class B : System { public...
Interface , Abstract , or just virtual methods ?
C#
I have a datagrid which is bound to a datatable . I would like to know - How can we show the Cursor as blinking in the first cell of an empty row of this datagrid which is bound to the datatable . Also , when a user adds a new empty row to this datatable/datagrid by hitting the enter key , The cursor should blink on th...
< DataGrid x : Name= '' MyGrid '' ItemsSource= '' { Binding MyDataTable , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' VerticalAlignment= '' Top '' Height= '' 400 '' Width= '' Auto '' SelectionMode= '' Single '' AutoGenerateColumns= '' True '' GridLinesVisibility = '' Vertical '' Background= '' Transparent ''...
How to set the cursor on the first cell of an empty row in datagrid which is bound to a data table
C#
I 'm still a beginner to programming in high-level programming languages , so I do n't know if this is an easy solution , but I 'm happy to learn anyway . I 've programmed a little alarm program in C # that let 's the user input in how many seconds the alarm needs to go off . It works perfectly , but the input that the...
using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Test { class Alarm { public static void play ( ) { int sec ; sec = Convert.ToInt16 ( Console.ReadLine ( ) ) ; for ( int i = 0 ; i < seconds ; ++i ) { System.Threading.Thread.Sleep ( 1000 ) ; } for ( int i = 0 ; i < 10 ; ...
How to prevent certain forms of input when writing methods ?
C#
I got this idea while thinking of ways to recycling objects . I am doing this as an experiment to see how memory pooling works and I realize that in 99 % of scenario this is very unnecessary . However , I have a question . Is there a way to force the GC to keep the object ? In other words , can I tell the GC not to des...
~myObject ( ) { ( ( List < myObject > ) HttpContext.Current.Items [ typeof ( T ) .ToString ( ) ] ) .add ( this ) ; //Lets assume this is ASP }
Keep object on GC destruction attempt
C#
After two questions and much confusion - I wonder if I finally got it right . This is my understanding : async/await serves only one purpose - to allow code to be executed after an already asynchronous task is finished.e.g.allows AnotherMethod to be executed after the asynchronous AsyncMethod is finished instead of imm...
async Task CallerMethod ( ) { await AsyncMethod ( ) ; AnotherMethod ( ) ; }
async/await - Is this understanding correct ?
C#
Does taking address of a C # struct cause default constructor call ? For example , I got such structs : Then , of course , I ca n't do this : But once I obtain pointer to the struct , I can read its fields even without using the pointer , and even embedded struct 's fields : So , does it call the default constructor so...
[ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct HEADER { public byte OPCODE ; public byte LENGTH ; } [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public struct S { public HEADER Header ; public int Value ; } S s ; // no constructor call , so ... var v = s.Value ; // compiler error : use of ...
Struct pointer ( address ) , and default constructor
C#
My code is ... Resharper is recommending ...
public static void AssertNotNull < T > ( string name , T val ) { if ( val == null ) throw new ArgumentNullException ( String.Format ( `` { 0 } must not be null '' , name ) ) ; } public static void AssertNotNull < T > ( string name , T val ) { if ( Equals ( val , default ( T ) ) ) throw new ArgumentNullException ( Strin...
Why is resharper making the following recommendation ?
C#
I am a newbie to Cassandra and created a generic repository for my Cassandra database using linq . For my Single ( ) method , I am passing the where criteria as a parameter . This is my Single method : This is the linq code I am using to query the cassandra databaseThis is the method calling the single methodI keep get...
Single ( Expression < Func < T , bool > > exp ) public async Task < T > Single ( Expression < Func < T , bool > > exp ) { return await GetTable.Where < T > ( exp ) .FirstOrDefault ( ) .ExecuteAsync ( ) ; } public override Task OnConnected ( ) { if ( Context.User ! = null ) { string userName = Context.User.Identity.Name...
Cassandra : Argument types do not match
C#
Why does PHP return INF ( infinity ) for the following piece of code : The expected result was 4321 , but PHP returned INF , float type : I wrote the same code in Python and C # and got the expected output - 4321PythonC #
< ? php $ n = 1234 ; $ m = 0 ; while ( $ n > 0 ) { $ m = ( $ m * 10 ) + ( $ n % 10 ) ; $ n = $ n / 10 ; } var_dump ( $ m ) ; ? > float INF n = 1234m = 0while ( n > 0 ) : m = ( m * 10 ) + ( n % 10 ) n = n / 10print m static void Main ( string [ ] args ) { int n = 1234 ; int m = 0 ; while ( n > 0 ) { m = ( m * 10 ) + ( n...
Unexpected behavior in PHP - Same code gives correct results in C # and Python
C#
Possible Duplicate : .NET Enumeration allows comma in the last field Since both compile , is there any differences between these declarations ?
public enum SubPackageBackupModes { Required , NotRequired //no comma } public enum SubPackageBackupModes { Required , NotRequired , //extra unnecessary comma }
Unnecessary comma in enum declaration
C#
I read a book `` CLR via C # Fourth Edition '' . And I can not understand one statement : So , for example , if you have the following line of code : then when the CLR creates the FileStream [ ] type , it will cause this type to automatically implement the IEnumerable < FileStream > , ICollection < FileStream > , and I...
FileStream [ ] fsArray ; FileStream [ ] fsArray = new FileStream [ 0 ] ; string s = null ; foreach ( var m in fsArray.GetType ( ) .GetInterfaces ( ) ) s += m.ToString ( ) + Environment.NewLine ; System.ICloneableSystem.Collections.IListSystem.Collections.ICollectionSystem.Collections.IEnumerableSystem.Collections.IStru...
Auto implemented interfaces in Arrays
C#
For convenience and safety reasons i 'd like to use the using statement for allocation and release of objects from/to a pool and the access the pool likeI found some topics on abusing using and Dispose ( ) for scope handling but all of them incorporate using ( Blah b = _NEW_ Blah ( ) ) .Here the objects are not to be f...
public class Resource : IDisposable { public void Dispose ( ) { ResourcePool.ReleaseResource ( this ) ; } } public class ResourcePool { static Stack < Resource > pool = new Stack < Resource > ( ) ; public static Resource GetResource ( ) { return pool.Pop ( ) ; } public static void ReleaseResource ( Resource r ) { pool....
Abuse using and Dispose ( ) for scope handling of not to be released objects ?
C#
I am launching these two console applications on Windows OS.Here is my C # codeAnd here is my C code . I am assuming it is C because I included cstdio and used standard fopen and fprintf functions.When I start C # program I immediately see the message `` Done ! '' . When I start C++ program ( which uses standard C func...
int lineCount = 0 ; StreamWriter writer = new StreamWriter ( `` txt1.txt '' , true ) ; for ( int i = 0 ; i < 900 ; i++ ) { for ( int k = 0 ; k < 900 ; k++ ) { writer.WriteLine ( `` This is a new line '' + lineCount ) ; lineCount++ ; } } writer.Close ( ) ; Console.WriteLine ( `` Done ! `` ) ; Console.ReadLine ( ) ; FILE...
Why my C # code is faster than my C code ?
C#
I can easily start a process with it 's STD I/O redirected but how can I redirect the STD I/O of an existing process.Exception : StandardOut has not been redirected or the process has n't started yet.Side note : If you know how to do this in C/C++ I 'd be happy to re-tag and accept . I just need to know if it 's even p...
Process process = Process.GetProcessById ( _RunningApplication.AttachProcessId ) ; process.StartInfo.RedirectStandardOutput = true ; process.StartInfo.RedirectStandardError = true ; string text = process.StandardOutput.ReadToEnd ( ) ; //This line blows up .
How to redirect the STD-Out of an **existing** process in C #
C#
I have a C # function with following signature : I call it from C++ . I was informed by compiler that 2-nd param must have SAFEARRAY* type . So I call it in this way : But safeArray is not updated , it still contains zores . But I tested Get1251Bytes function in C # unit-test . It works properly and updates result arra...
int Get1251Bytes ( string source , byte [ ] result , Int32 lengthOfResult ) SAFEARRAY* safeArray = SafeArrayCreateVector ( VT_UI1 , 0 , arrayLength ) ; char str [ ] = { 's ' , 't ' , ' a ' , ' c ' , ' k ' , '\0 ' } ; converter- > Get1251Bytes ( str , safeArray , arrayLength ) ;
C # function does n't update SAFEARRAY
C#
I started out programming with C # a few days ago.Now an confusing error arised when playing around with operator overloading.The following code produces a StackOverflowException when running : I tried to write an own example after reading the chapter about operater overloading from the book `` Microsoft Visual C # 200...
using System ; namespace OperatorOverloading { public class Operators { // Properties public string text { get { return text ; } set { if ( value ! = null ) text = value ; else text = `` '' ; } } // Constructors public Operators ( ) : this ( `` '' ) { } public Operators ( string text ) { // Use `` set '' property . thi...
Operator Overloading causes a stack overflow
C#
I 'm developing a simple lambda function with .net core . For this , I 'm using the AWS tookit . My project have a three resources file , one with default message , and two with italian and french greetings.For this , my function receive a query string parameter , and depending on this value , I set the culture for the...
CultureInfo.CurrentCulture = new CultureInfo ( `` fr '' ) ; CultureInfo.CurrentUICulture = new CultureInfo ( `` fr '' ) ;
AWS Lambda is not recognizing the culture on .net core
C#
At work I just installed a brand new copy of my OS and a brand new copy of VS2015 . When I clone my solution for the first time , I can not build it anymore , even if I 've generated the C # files like I always do , by opening the .edmx file first , and clicking on `` save '' icon.When building it throws the error : CS...
public enum DocumentType : int { Identity = 1 , ResidenceProof = 2 , RegisterDoc = , }
EntityFramework not generating C # files properly ( some enums are incomplete , so build fails )
C#
I found this code snippet on a blog as a `` Convert Binary data to text '' And this provides a output of AAAAAQAB .. What is not clear is that how 000101 - > is mapped to AAAAAQAB , and will I able to use this to all a-z characters as a binary equivalent and how ? or is there a any other method ?
Byte [ ] arrByte = { 0,0,0,1,0,1 } ; string x = Convert.ToBase64String ( arrByte ) ; System : Console.WriteLine ( x ) ;
C # byte array problem
C#
I have a query that looks something like this : MultiframeModule and Frame have an many-to-many relation.With that query I want to find a MultiframeModule that contains all frames inside the frames collection I sent as a parameter , for that I check the ShaHash parameter.If frames contains 2 frames , then the generated...
private static IQueryable < MultiframeModule > WhereAllFramesProperties ( this IQueryable < MultiframeModule > query , ICollection < Frame > frames ) { return frames.Aggregate ( query , ( q , frame ) = > { return q.Where ( p = > p.Frames.Any ( i = > i.FrameData.ShaHash == frame.FrameData.ShaHash ) ) ; } ) ; } SELECT ``...
Query with large WHERE clause causes timeout exception in EF6 with npgsql
C#
So heres my question . I have a Asp.net application with a form based authentication . I have users in my database but the users also has to be in the active directory.The following code is for me to check if user is in the domain AThis code work fine . The problem is client is requesting that domain B should also be a...
DirectoryEntry de = new DirectoryEntry ( ) ; de.Path = `` LDAP : //domainA.com '' ; de.AuthenticationType = AuthenticationTypes.None ; DirectorySearcher search = new DirectorySearcher ( de ) ; search.Filter = `` ( SAMAccountName= '' + account + `` ) '' ; search.PropertiesToLoad.Add ( `` displayName '' ) ; SearchResult ...
How to query Active Directory B if application server is in Active Directory A
C#
Given the following test : I want to encapsulate fixture creation in its own class , something akin to : The problem is that I 'm using PropertyData and the latter is supplying two input parameters . The fact that I 'm then trying to automatically create my fixture as a parameter is causing an exception . Here is the C...
[ Theory ] [ PropertyData ( `` GetValidInputForDb '' ) ] public void GivenValidInputShouldOutputCorrectResult ( string patientId , string patientFirstName ) { var fixture = new Fixture ( ) ; var sut = fixture.Create < HtmlOutputBuilder > ( ) ; sut.DoSomething ( ) ; // More code } [ Theory ] [ CustomPropertyData ( `` Ge...
AutoFixture : PropertyData and heterogeneous parameters
C#
Is it possible to publish an build artifact to Azure Devops/TFS through build.cake script ? Where should the responsibility for publishing the build artifact be configured when converting to cake scripts , in the build.cake script or in the Azure DevOps pipeline ? To achieve versioning in our build and release pipeline...
Task ( `` Copy-Bin '' ) .WithCriteria ( ! isLocalBuild ) .Does ( ( ) = > { Information ( $ '' Creating directory { artifactStagingDir } /drop '' ) ; CreateDirectory ( $ '' { artifactStagingDir } /drop '' ) ; Information ( $ '' Copying all files from { solutionDir } / { moduleName } .ServiceHost/bin to { artifactStaging...
Publish build artifact through build.cake instead of Azure Devops
C#
BriefI 've created a beautiful WindowChrome style to apply to my windows . When I add ContentControl to my style , however , the application enters break mode.I 've pieced together code from this youtube video , this article , this SO question and Microsoft 's documentation and I 've come up with the following code.Not...
< Style x : Key= '' TestWindow '' TargetType= '' { x : Type Window } '' > < Setter Property= '' Background '' Value= '' # FF222222 '' / > < Setter Property= '' BorderBrush '' Value= '' WhiteSmoke '' / > < Setter Property= '' BorderThickness '' Value= '' 5,30,5,5 '' / > < Setter Property= '' WindowChrome.WindowChrome ''...
Why does adding ContentControl cause my application to enter break mode ?
C#
What I understand unboxing is when I take a object and unbox it to valuetype like the MSDN example : So I just was thinking , can a string be unboxed ? I think , No it ca n't because there is no valuetype that can represent a string . Am I right ?
int i = 123 ; object o = i ; o = 123 ; i = ( int ) o ; // unboxing
Can I unbox a string ?
C#
I have a array of data : I 'd like it to be sorted from Alphanumeric to Non-Alphanumeric.Example : A B E N ! $ How would I go about accomplishing this ?
! ABE $ N
Sorting from Alphanumeric to nonAlphnumeric
C#
Trying to get a custom CoreLib in .NET Core project to load in VS 2017 . This was super easy in .NET Framework as all you needed was `` NoStdLib '' but with .NET Core seems like a lot more parts are needed.I keep getting : `` Project file is incomplete . Expected imports are missing . `` Going off what System.Private.C...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ! -- < Project Sdk= '' Microsoft.NET.Sdk '' > -- > < Project ToolsVersion= '' 14.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < PropertyGroup > < ProjectGuid > { 3DA06C3A-2E7B-4CB7-80ED-9B12916013F9 } < /Proj...
Custom `` CoreLib '' In .NET Core ?
C#
My Regex is removing all numeric ( 0-9 ) in my string.I do n't get why all numbers are replaced by _ EDIT : I understand that my `` _ '' regex pattern changes the characters into underscores . But not why numbers ! Can anyone help me out ? I only need to remove like all special characters.See regex here :
string symbolPattern = `` [ ! @ # $ % ^ & * ( ) -=+ ` ~ { } '| ] '' ; Regex.Replace ( `` input here 12341234 '' , symbolPattern , `` _ '' ) ; Output : `` input here ________ ''
regex issue c # numbers are underscores now
C#
I 'm seeing an inconstancy with how the CRM SDK treats searching for entities by an OptionSetValue attribute , and creating an entity with an OptionSetValue Attribute.Back Ground : I have a method with this signaturewhere the columnNameAndValuePairs is a list of pairs that look like this : ( string name of the column ,...
GetOrCreateEntity < T > ( IOrganizationService service , params object [ ] columnNameAndValuePairs ) var user = GetOrCreateEntity < SystemUser > ( `` username '' , `` jdoe '' ) ; var user = GetOrCreateEntity < SystemUser > ( `` username '' , `` jdoe '' , `` Sex '' , new OptionSetValue ( 1 ) ) ; var user = GetOrCreateEn...
Why must I use an int when searching for an entity with an OptionSetValue attribute , but use an OptionSetValue object when creating an entity ?
C#
I have the following table in SQL Server : ProductAttributeName : nvarchar ( 100 ) Value : nvarchar ( 200 ) This is mapped via Entity Framework into my class : Some rows of ProductAttributes have the following form : { Name : `` RAM '' , Value : `` 8 GB '' } , { Name : `` Cache '' , Value : `` 3000KB '' } I need to con...
public class ProductAttribute { public string Name { get ; set ; } public string Value { get ; set ; } } double value = ... ; Expression < Func < ProductAttribute , bool > > expression = p = > { Regex regex = new Regex ( @ '' \d+ '' ) ; Match match = regex.Match ( value ) ; if ( match.Success & & match.Index == 0 ) { m...
Build Expression Tree convertible to valid SQL dynamically that can compare string with doubles
C#
I 've just `` earned '' the privilege to maintain a legacy library coded in C # at my current work.This dll : Exposes methods for a big legacy system made with Uniface , that has no choice but calling COM objects.Serves as a link between this legacy system , and another system 's API.Uses WinForm for its UI in some cas...
// my public method called by the external systempublic int ComparedSearch ( string application , out string errMsg ) { errMsg = `` '' ; try { Action < string > asyncOp = AsyncComparedSearch ; asyncOp.BeginInvoke ( application , null , null ) ; } catch ( ex ) { // ... } return 0 ; } private int AsyncComparedSearch ( st...
Make my COM assembly call asynchronous
C#
After instantiating a list ( so ignoring the overhead associated with creating a list ) , what is the memory cost of adding the same object to a list over and over ? I believe that the following is just adding the same pointer to memory to the list over and over , and therefore this list is actually not taking up a lot...
List < newType > list = new List < newType > ( ) ; newType example = new newType ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { list.Add ( example ) ; }
List with repeat objects - What is the memory cost ?
C#
Possible Duplicate : Should I Create a New Delegate Instance ? Hi , I 've tried searching for the answer to this , but do n't really know what terms to search for , and none of the site-suggested questions are relevant . I 'm sure this must have been answered before though.Basically , can somebody tell me what 's the d...
SomeEvent += SomeMethodSomeEvent += new SomeDelegate ( SomeMethod ) DataContextChanged += App_DataContextChanged ; DataContextChanged += new DependencyPropertyChangedEventHandler ( App_DataContextChanged ) ;
C # : what 's the difference between SomeEvent += Method and SomeEvent += new Delegate ( Method )
C#
I have a data table with the following details.I want to merge values of Column ENTITY as below.is there any way we can achieve it using Linq ?
ID | VERSION | ENTITY1 | 01 | A011 | 01 | A022 | 01 | A012 | 01 | A02 ID | VERSION | ENTITY1 | 01 | A01/A022 | 01 | A01/A02
C # : Merge Datarows in the datatable
C#
In my MVC controller , i have an action that will populate a stream which i will use later : I had this problem because ReSharper is giving out a warning : access on disposed closure on the line PopulateFile ( fileParams , stream ) and pointing out stream.I have searched for the meaning of it and it seems that it warns...
[ HttpPost ] public async Task < HttpResponseMessage > BuildFileContent ( FileParameters fileParams ) { byte [ ] output ; if ( fileParams ! = null ) { using ( var stream = new MemoryStream ( ) ) { await Task.Run ( ( ) = > PopulateFile ( fileParams , stream ) ) ; // Here i populate the stream stream.Flush ( ) ; output =...
await population of a stream
C#
I have a simple wrapper for a Unity IoC container ( a temporary use of Service Locator [ anti- ] Pattern to introduce DI to a legacy codebase ) , and since the IUnityContainer in Unity implements IDisposable I wanted to expose that through the wrapper as well.The wrapper is simple enough : IIoCContainer is the domain i...
public class IoCContainer : IIoCContainer { private IUnityContainer _container ; public IoCContainer ( IUnityContainer container ) { _container = container ; } public T Resolve < T > ( ) { return _container.Resolve < T > ( ) ; } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } ~IoCContainer...
Stack Overflow when Disposing a Managed Resource
C#
I 've made a class ( code below ) that handles the creation of a `` matching '' quiz item on a test , this is the output : It works fine.However , in order to get it completely random , I have to put the thread to sleep for at least 300 counts between the random shuffling of the two columns , anything lower than 300 re...
LeftDisplayIndexes.Shuffle ( ) ; Thread.Sleep ( 300 ) ; RightDisplayIndexes.Shuffle ( ) ; using System.Collections.Generic ; using System ; using System.Threading ; namespace TestSort727272 { class Program { static void Main ( string [ ] args ) { MatchingItems matchingItems = new MatchingItems ( ) ; matchingItems.Add (...
How can I get true randomness in this class without Thread.Sleep ( 300 ) ?
C#
I suppose this is more of a public rant , but why ca n't I get c # to infer my Id 's type ? and a defined EntityObject with a Guid as an Id as follows : Inheriting from the abstract EntityObject class defined as follows : Usage of the get method would be as follows : edited to provide further clarification .
public EntityT Get < EntityT > ( IdT id ) where EntityT : EntityObject < IdT > public Foo : EntityObject < Guid > public abstract class EntityObject < IdT > { public IdT id { get ; set ; } } IRepository repository = new Repository ( ) ; var hydratedFoo = repository.Get < Foo > ( someGuidId ) ;
Inference from Generic Type Question
C#
What I am looking for is a way to call a method after another method has been invoked but before it is entered . Example : In the example above I would like to have Tracer ( ) called after SomeFunction ( ) has been invoked by TestFun ( ) but before SomeFunction ( ) is entered . I 'd also like to get reflection data on ...
public class Test { public void Tracer ( ... ) { } public int SomeFunction ( string str ) { return 0 ; } public void TestFun ( ) { SomeFunction ( `` '' ) ; } }
Is there a way in .NET to have a method called automatically after another method has been invoked but before it is entered
C#
Not return value optimization in the traditional sense , but I was wondering when you have a situation like this : This could obviously be written more optimally : I just wondered whether anyone knew if the ( MS ) compiler was clever enough not to generate state machines for Method1 ( ) and Method2 ( ) in the first ins...
private async Task Method1 ( ) { await Method2 ( ) ; } private async Task Method2 ( ) { await Method3 ( ) ; } private async Task Method3 ( ) { //do something async } private Task Method1 ( ) { return Method2 ( ) ; } private Task Method2 ( ) { return Method3 ( ) ; } private async Task Method3 ( ) { //do something async ...
Does compiler perform `` return value optimization '' on chains of async methods
C#
This question stems from a bug where I iterated over a collection of Int64 and accidentally did foreach ( int i in myCollection ) . I was trying to debug the baffling problem of how when I did a linq query , i was not part of the myCollection.Here 's some code that surprised me : I expected the compiler to give me an e...
Int64 a = 12345678912345 ; Console.Write ( ( int ) a ) ;
Why does C # let me overflow without any error or warning when casting an Int64 to an Int32 and how does it do the cast ?
C#
I am trying to get the data from database by using the below code ... ..if there is no data in the table it will always goes to this statementI am using mysql.net connector for getting the data and i am doing winforms applicationsusing c # and the below code is for return sqlexceution ... function..even if there is no ...
public DataTable sales ( DateTime startdate , DateTime enddate ) { const string sql = @ '' SELECT memberAccTran_Source as Category , sum ( memberAccTran_Value ) as Value FROM memberacctrans WHERE memberAccTran_DateTime BETWEEN @ startdate AND @ enddate GROUP BY memberAccTran_Source '' ; return sqlexecution ( startdate ...
problem with getting data from database
C#
I 'm having some trouble finding answers to a question I have about some code specific to what i 'm working on and I can not seem to find some documentation on how Union works at it 's core mechanics in C # . So the problem is this.I have a set of data that works similar to this example : Is it more efficient to let Un...
object [ ] someMainTypeArray = new object [ n ] ; List < object > objList2 = new List < object > ( ) ; foreach ( object obj in someMainTypeArray ) { List < object > objList1 = new List < object > ( ) { `` 1 '' , '' 2 '' , '' 3 '' } ; //each obj has a property that will generate a list of data //objList1 is the result o...
C # Union vs Contains for lists of continuous data
C#
I am unable to view the debug information when using a Task of Tuple . E.G . When a breakpoint his hit , I can not view any variables on hover , in the local window , or in the watch window.The repro is just to create a new WPF app , add System.ValueTuple , add this code to MainWindow.xaml.cs , and then set breakpoints...
using System.Threading.Tasks ; using System.Windows ; namespace WpfApp2 { public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private async void Button_Click ( object sender , RoutedEventArgs e ) { var task1 = TaskWithLocalDebugInfo ( ) ; var task2 = TaskWithoutLocalDebugInfo ...
VS2017 Error debugging Task of Tuple
C#
I 'm trying to set up a TLS connection to an application running in a ( local ) VM using C # 's HttpClient on Windows . However , it results in a RemoteCertificateNameMismatch error every time . This piece of code : Results in this error : However , my certificate is valid according to Google Chrome and Mozilla Firefox...
HttpClientHandler handler = new HttpClientHandler ( ) ; handler.ServerCertificateCustomValidationCallback = ( request , cert , chain , policyErrors ) = > { Console.WriteLine ( $ '' Policy Errors : { policyErrors } '' ) ; return policyErrors == SslPolicyErrors.None ; } ; HttpClient httpClient = new HttpClient ( handler ...
How to start a trusted TLS connection with a server by IP address using HttpClient in C # ?
C#
Using the Entity-Component-System pattern I want to connect some systems with events . So some systems should n't run in a loop , they should just run on demand.Given the example of a Health system a Death system should only run when a component gets below 1 health.I thought about having two types of systems . The firs...
internal interface ISystem { List < Guid > EntityCache { get ; } // Only relevant entities get stored in there ComponentRequirements ComponentRequirements { get ; } // the required components for this system void InitComponentRequirements ( ) ; void InitComponentPools ( EntityManager entityManager ) ; void UpdateCacheE...
connect systems with events
C#
I 'm looking at customising the various pieces of text in an application for different customers . It seems like .resx resources would be a sensible way to do this . However , all the literature for resx I come across seems to be about localising for language differences ( as in English , French , Spanish , etc . ) , s...
CustomerA.resxCustomerA.en-US.resxCustomerA.de-DE.resxCustomerB.resxCustomerB.en-US.resxCustomerB.de-DE.resx ... etc
Are resx files a suitable way to customise for different customers ?
C#
In my services all exposed methods have : It 's boring and ugly to repeat it over and over again . Is there any way to avoid that ? Is there a better way to keep the service working even if exceptions occur and keep sending the exception details to the Log class ?
try { // the method core is written here } catch ( Exception ex ) { Log.Append ( ex ) ; }
How to refactor logging in C # ?
C#
I have an industrial computer with some Digital I/O pins . The manufacturer provides some C++ libraries and examples to handle pin status change.I need to integrate this events onto a C # application . AFAIK the most simple way to perform this is : Make a managed C++/CLI wrapper for the manufacturer libraries that fire...
using namespace System ; public ref class ThresholdReachedEventArgs : public EventArgs { public : property int Threshold ; property DateTime TimeReached ; } ; public ref class CppCounter { private : int threshold ; int total ; public : CppCounter ( ) { } ; CppCounter ( int passedThreshold ) { threshold = passedThreshol...
Firing events in C++ and handling them in C #
C#
I have such constructionCan I get all unique value from propIDs with LINQ.For example I have list of ( 1,2 ) ( 4,5 ) ( 1,5 ) ( 1,2 ) ( 1,5 ) and I must get ( 1,2 ) ( 4,5 ) ( 1,5 )
List < int [ ] > propIDs = new List < int [ ] > ( ) ;
How can I retrieve a set of unique arrays from a list of arrays using LINQ ?
C#
What is the correct way for a application to restart another copy of itself with the same arguments ? My current method is to do the followingHowever it seems like there is a lot of busy work in there . Ignoring the striping of the vshost , I still need to wrap arguments that have spaces with `` and combine the array o...
static void Main ( ) { Console.WriteLine ( `` Start New Copy '' ) ; Console.ReadLine ( ) ; string [ ] args = Environment.GetCommandLineArgs ( ) ; //Will not work if using vshost , uncomment the next line to fix that issue . //args [ 0 ] = Regex.Replace ( args [ 0 ] , `` \\.vshost\\.exe $ '' , `` .exe '' ) ; //Put quote...
Start a second copy of the program with the same arguments
C#
I 'm developing an app and I 'd like when the user is in Tablet Mode and switches from one app to other to show a black screen when you press `` alt + tab '' and the opened apps are being shown . I 'd like instead of showing the `` myTrip '' screenshot of the app to show a black screen.I know for WPF we had ShowInTaskb...
private void Current_VisibilityChanged ( object sender , VisibilityChangedEventArgs e ) { var parentGrid = RootPanel ( ) ; parentGrid.Visibility = e.Visible ? Visibility.Visible : Visibility.Collapsed ; }
Hide app preview from Alt-tab taskbar in Windows 10 Universal App Platform
C#
I want to learn how can I add to my controller some SQL query but I do n't know how to do it properly.My controller isBy default page is giving me the next data . I want to add the next SQL query to the controller which will give me data that I want it on page to display .
public ActionResult Index ( ) { return View ( db.Student.ToList ( ) ) ; } ID , NAME , STATUS 1 Bella , 5 2 Bella , 5 3 Bella , 7 ( select distinct id , name , max ( status ) from students group by id , name ) ID , NAME , STATUS 3 Bella , 7
ASP.net.MVC 5 create a page which will display sql query
C#
I have a situation where I 'd like the behaviour of the compiler explained . Given a little code : The following compiles and runs : If we make a change to the signature of the Foo class and add the sealed keyword : Then I get a compiler error on the following line : Of : Can not convert type 'MyNamespace.FooGetter ' t...
interface IFoo < T > { T Get ( ) ; } class FooGetter : IFoo < int > { public int Get ( ) { return 42 ; } } static class FooGetterGetter { public static IFoo < T > Get < T > ( ) { return ( IFoo < T > ) new FooGetter ( ) ; } } sealed class FooGetter : IFoo < int > // etc return ( IFoo < T > ) new FooGetter ( ) ; return (...
Sealed keyword affects the compiler 's opinion on a cast
C#
I 'm using Lidgren and for every new type of message I make , I end up writing the same kind of code . I 'm creating an instance of NetOutgoingMessage , running various assignment calls on it , then sending it when I 'm done . Creation and send are the same , so I want to write a wrapper to do this for me , but it 's a...
NetOutgoingMessage om = server.CreateMessage ( ) ; om.Write ( messageType ) ; om.Write ( data1 ) ; om.Write ( data2 ) ; server.SendMessage ( om , server.Connections , NetDeliveryMethod.UnreliableSequenced , 0 ) ; using ( AutoNetOutgoingMessage om ( server , messageType , NetDeliveryMethod.UnreliableSequenced ) ) { om.W...
Something similar to `` using '' that will create an object and call a method on it when done , but let me do what I want in between
C#
Is this code even complex enough to deserve a higher level of abstraction ?
public static JsonStructure Parse ( string jsonText ) { var result = default ( JsonStructure ) ; var structureStack = new Stack < JsonStructure > ( ) ; var keyStack = new Stack < string > ( ) ; var current = default ( JsonStructure ) ; var currentState = ParserState.Begin ; var key = default ( string ) ; var value = de...
How could I refactor this into more manageable code ?
C#
Let 's say I have a method as follows : But the above code has two lookups in the dictionary : The test for the existance of the keyThe actual retrieval of the valueIs there a more optimal way to phrase such a function , so that only one lookup is performed , but the case of `` not found '' is still handled via a null ...
internal MyClass GetValue ( long key ) { if ( _myDictionary.ContainsKey ( key ) ) return _myDictionary [ key ] ; return null ; // Not found } IDictionary < long , MyClass > _myDictionary= ...
C # optimal IDictionary usage for lookup with possibility of not found
C#
I 'm using ProtoBuf.NET to serialize/deserialize some classes . I 'm finding that on deserializing , I 'm getting a corrupt byte [ ] ( extra 0 's ) . Before you ask , yes , I need the *WithLengthPrefix ( ) versions of the ProtoBuf API since the ProtoBuf portion is at the starts of a custom stream : ) Anyway , I seeThe ...
Original object is ( JSON depiction ) : { `` ByteArray '' : '' M+B6q+PXNuF8P5hl '' , '' ByteArray2 '' : '' DmErxVQ2y87IypSRcfxcWA== '' , '' K '' :2 , '' V '' :1.0 } Protobuf : Raw Hex ( 42 bytes ) :29-2A-20-0A-0C-33-E0-7A-AB-E3-D7-36-E1-7C-3F-98-65-12-10-0E-61-2B-C5-54-36-CB-CE-C8-CA-94-91-71-FC-5C-58-08-02-15-00-00-80...
ProtoBuf corrupts byte array during deserialization ( extra 0 's added )
C#
If you are coding C # inside visual studio , and you have a multiline comment , thusly : Then if you are inside the comment , like after the word `` comment '' in my example , and you hit enter , Visual Studio adds a `` * `` on the new line and places your cursor even with the `` * '' that started the comment.I hate th...
/*This is a very interesting commentthat consists of multiple lines*/
Prevent Visual Studio from adding extra asterisks when hitting enter inside a multiline comment
C#
I want to achieve that I can subdivide a Bezier Curve with a given distance . Now it works if the Bezier is a straight line , but if I change a Controll-Point ( B & C ) so the Bezier get 's curved , the gap between the calculated Points are no more like the given Distance ! I 've look through the web , but did n't cras...
float t = Distance between subdividedParts / bezier length ; //A , B , C , D = ControllPoints of BezierGetPoint ( A , B , C , D , t ) ; //GetPoint equation : public static Vector3 GetPoint ( Vector3 p0 , Vector3 p1 , Vector3 p2 , Vector3 p3 , float t ) { t = Mathf.Clamp01 ( t ) ; float OneMinusT = 1f - t ; return OneMi...
Subdivide Bezier Curves
C#
Based on my understanding , given a C # array , the act of iterating over the array concurrently from multiple threads is a thread safe operation.By iterating over the array I mean reading all the positions inside the array by means of a plain old for loop . Each thread is simply reading the content of a memory locatio...
public class UselessService { private static readonly string [ ] Names = new [ ] { `` bob '' , `` alice '' } ; public List < int > DoSomethingUseless ( ) { var temp = new List < int > ( ) ; for ( int i = 0 ; i < Names.Length ; i++ ) { temp.Add ( Names [ i ] .Length * 2 ) ; } return temp ; } } public class UselessServic...
Is iterating over an array with a for loop a thread safe operation in C # ? What about iterating an IEnumerable < T > with a foreach loop ?
C#
I thought T ? is just a compiler shorthand for Nullable < T > . According to MSDN : The syntax T ? is shorthand for Nullable < T > , where T is a value type . The two forms are interchangeable.However , there is a little ( insignificant ) difference : Visual Studio does n't allow me to call static methods on shorthands...
bool b1 = Nullable < int > .Equals ( 1 , 2 ) ; //no errorbool b2 = int ? .Equals ( 1 , 2 ) ; //syntax error `` Invalid expression term 'int ' ''
Why is it impossible to call static methods on Nullable < T > shorthands ?
C#
I have existing ap.net c # website is working with mysql database . now i am planning to create mobile app for that website for that API needs to be ready.I am creating an API into PHP Laravel Framework . for RegistrationAPI needs to generate password.Asp.net using its inbuilt library for generating password like it au...
WebSecurity.CreateUserAndAccount ( `` username '' , `` password '' ) ; < ? php/* * Author : Mr. Juned Ansari * Date : 15/02/2017 * Purpose : It Handles Login Encryption And Decryption Related Activities */class MembershipModel { function bytearraysequal ( $ source , $ target ) { if ( $ source == null || $ target == nul...
How to Generate ASP.NET Password using PHP
C#
All , I have a method that is currently used to invoke DLLs of return type bool , this works great . This method isNow , I want to extend this method so that I can retrieve return values from a DLL of any type . I planned to do this using generics but immediately have gone into territory unknown to me . How do I return...
public static bool InvokeDLL ( string strDllName , string strNameSpace , string strClassName , string strMethodName , ref object [ ] parameters , ref string strInformation , bool bWarnings = false ) { try { // Check if user has access to requested .dll . if ( ! File.Exists ( Path.GetFullPath ( strDllName ) ) ) { strInf...
Defining Generic Methods
C#
I have a class called ConfigurationElementCollection < T > It 's a generic implementation of System.Configuration.ConfigurationElementCollectionIt 's stored in our solutions ' , Project.Utility.dll but I 've defined it as being part of the System.Configuration namespaceIs putting classes in the System . * namespaces co...
namespace System.Configuration { [ ConfigurationCollection ( typeof ( ConfigurationElement ) ) ] public class ConfigurationElementCollection < T > : ConfigurationElementCollection where T : ConfigurationElement , new ( ) { ... } }
Is using System . * Namespaces on your own classes considered Bad Practice ?
C#
We 're using the Stream functionality in RavenDB to load , transform and migrate data between 2 databases like so : The problem is that one of the collections has millions of rows , and we keep receiving an IOException in the following format : This happens quite a long way into streaming and of course transient connec...
var query = originSession.Query < T > ( IndexForQuery ) ; using ( var stream = originSession.Advanced.Stream ( query ) ) { while ( stream.MoveNext ( ) ) { var streamedDocument = stream.Current.Document ; OpenSessionAndMigrateSingleDocument ( streamedDocument ) ; } } Application : MigrateToNewSchema.exeFramework Version...
RavenDB Stream for Unbounded Results - Connection Resilience
C#
In an effort to explore how the C # compiler optimizes code , I 've created a simple test application . With each test change , I 've compiled the application and then opened the binary in ILSpy.I just noticed something that , to me , is weird . Obviously this is intentional , however , I ca n't think of a good reason ...
static void Main ( string [ ] args ) { int test_1 = 1 ; int test_2 = 0 ; int test_3 = 0 ; if ( test_1 == 1 ) Console.Write ( 1 ) ; else if ( test_2 == 1 ) Console.Write ( 1 ) ; else if ( test_3 == 1 ) Console.Write ( 2 ) ; else Console.Write ( `` x '' ) ; } private static void Main ( string [ ] args ) { int test_ = 1 ;...
Variables ending with `` 1 '' have the `` 1 '' removed within ILSpy . Why ?
C#
While investigating the new features in C # 7.x , I created the following class : And the following test code : If the Person class includes only the SECOND Deconstruct overload , the code compiles and runs fine ( `` Dennis was born a Friday '' ) . But as soon as the first overload is added to Person , the compiler sta...
using System ; namespace ValueTuples { public class Person { public string Name { get ; } public DateTime BirthDate { get ; } public Person ( string name , DateTime birthDate ) { Name = name ; BirthDate = birthDate ; } public void Deconstruct ( out string name , out int year , out int month , out int day ) { name = Nam...
C # deconstruction and overloads
C#
I have an IEnumerable parameter that is required to be non-empty . If there 's a precondition like the one below then the collection will be enumerated during it . But it will be enumerated again the next time I reference it , thereby causing a `` Possible multiple enumeration of IEnumerable '' warning in Resharper.The...
void ProcessOrders ( IEnumerable < int > orderIds ) { Contract.Requires ( ( orderIds ! = null ) & & orderIds.Any ( ) ) ; // enumerates the collection // BAD : collection enumerated again foreach ( var i in orderIds ) { /* ... */ } } // enumerating before the precondition causes error `` Malformed contract . Found Requi...
IEnumerable multiple enumeration caused by contract precondition
C#
I have often wanted to create a list of objects where each object must implement a number of interfaces . For example , I 'd like to do something similar to the following : Another option I considered was to create a third interface that implements these two so that any object that implements these two interfaces inher...
List < T > where T : IConvertible , IComparable _myList ; public interface IConvertibleAndComparable : IConvertible , IComparable { } List < IConvertibleAndComparable > _myList ; private MyGenericClass < T > where T : IA , IB , ... _myClass ; public interface IMyCombinedInterface : IA , IB , ... { } private MyGenericCl...
Inherently-Implemented Interfaces
C#
In .NET 4.5 this cipher worked perfectly on 32 and 64 bit architecture . Switching the project to .NET 4.6 breaks this cipher completely in 64-bit , and in 32-bit there 's an odd patch for the issue.In my method `` DecodeSkill '' , SkillLevel is the only part that breaks on .NET 4.6.The variables used here are read fro...
private void DecodeSkill ( ) { SkillId = ( ushort ) ( ExchangeShortBits ( ( SkillId ^ ObjectId ^ 0x915d ) , 13 ) + 0x14be ) ; SkillLevel = ( ( ushort ) ( ( byte ) SkillLevel ^ 0x21 ) ) ; TargetObjectId = ( ExchangeLongBits ( TargetObjectId , 13 ) ^ ObjectId ^ 0x5f2d2463 ) + 0x8b90b51a ; PositionX = ( ushort ) ( Exchang...
.Net 4.6 breaks XOR cipher pattern ?
C#
how to check for duplicate entry on a form using php ? my front end is c # windows applicationI am adding a new user to database using c # and php file.I have created the following : my project in c # ( form1 ) : c # coding : my PHP file : response.phpit add data successfully but when i enter the same userid in textbox...
private void btncreate_Click ( object sender , EventArgs e ) { var request = ( HttpWebRequest ) WebRequest.Create ( `` http : //***.**.*** . ***/response.php '' ) ; request.Method = WebRequestMethods.Http.Post ; request.ContentType = `` application/x-www-form-urlencoded '' ; using ( var stream = request.GetRequestStrea...
duplicate entry on database using php
C#
I 'm making user changeable settings for my media player and I 'm struggling to find an elegant solution to the problem.One of my settings for example - pauses the video at it 's last frame , if not checked it will either continue through the playlist or if it 's only 1 file , reset it and pause it at the start.This is...
private void OnMediaEndedCommand ( ) { if ( GeneralSettings.PauseOnLastFrame ) { MediaPlayer.SetMediaState ( MediaPlayerStates.Pause ) ; return ; } if ( PlayListViewModel.FilesCollection.Last ( ) .Equals ( PlayListViewModel.FilesCollection.Current ) & & ! Repeat ) { ChangeMediaPlayerSource ( PlayListViewModel.ChangeCur...
Conditional settings in WPF application
C#
Let 's assume that our system can perform actions , and that an action requires some parameters to do its work . I have defined the following base class for all actions ( simplified for your reading pleasure ) : Only a concrete implementation of BaseBusinessAction knows how to validate that the parameters passed to it ...
public abstract class BaseBusinessAction < TActionParameters > : where TActionParameters : IActionParameters { protected BaseBusinessAction ( TActionParameters actionParameters ) { if ( actionParameters == null ) throw new ArgumentNullException ( `` actionParameters '' ) ; this.Parameters = actionParameters ; if ( ! Pa...
How can I improve this design ?
C#
I was doing tutorial from this page : http : //msdn.microsoft.com/en-us/library/gg185927.aspxI think I did everything ok but I 'm getting this exception : What I did wrong ? I used certificate from sample . Maybe I should create my own certificate ? Is there any difference ? I noticed that hard coded credentials slight...
` An error occurred when processing the security tokens in the message. ` Server stack trace : at System.ServiceModel.Channels.SecurityChannelFactory ` 1.SecurityRequestChannel.ProcessReply ( Message reply , SecurityProtocolCorrelationState correlationState , TimeSpan timeout ) at System.ServiceModel.Channels.SecurityC...
WCF Username Authentication - exception in tutorial
C#
Why the following program prints ( as it should ) but if we remove keyword 'public ' in class B like so : it starts printing ?
BB public class A { public void Print ( ) { Console.WriteLine ( `` A '' ) ; } } public class B : A { public new void Print ( ) { Console.WriteLine ( `` B '' ) ; } public void Print2 ( ) { Print ( ) ; } } class Program { static void Main ( string [ ] args ) { var b = new B ( ) ; b.Print ( ) ; b.Print2 ( ) ; } } new void...
How method hiding works in C # ?
C#
The following is a typical implementation of SynchronizationContext.CreateCopy : The MSDN docs are scarce about this method . My questions are : Under what circumstances does it get called by the Framework ? When to implement the actual copy logic , rather than just returning a reference to thesource instance ?
public class CustomSynchronizationContext : SynchronizationContext { // ... public override SynchronizationContext CreateCopy ( ) { return this ; } }
The purpose of SynchronizationContext.CreateCopy