lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have a class defined like this : But when I serialize it , `` version '' does n't show up in the attribute ( while `` action '' does ) .What 's going wrong ?
[ XmlRoot ( ElementName= '' request '' ) ] public class Request { # region Attributes [ XmlAttribute ( AttributeName = `` version '' ) ] public string Version { get { return `` 1.0 '' ; } } [ XmlAttribute ( AttributeName = `` action '' ) ] public EAction Action { get ; set ; } # endregion
C # Xml why does n't my attribute appears ?
C#
Suppose I have a method which changes the state of an object , and fires an event to notify listeners of this state change : The event handlers may throw an exception even if IncreaseCounter successfully completed the state change . So we do not have strong exception safety here : The strong guarantee : that the operat...
public class Example { public int Counter { get ; private set ; } public void IncreaseCounter ( ) { this.Counter = this.Counter + 1 ; OnCounterChanged ( EventArgs.Empty ) ; } protected virtual void OnCounterChanged ( EventArgs args ) { if ( CounterChanged ! = null ) CounterChanged ( this , args ) ; } public event Event...
Can I have strong exception safety and events ?
C#
I 've just started experimenting with CodeContracts in .NET 4 on an existing medium-sized project , and I 'm surprised that the static checker is giving me compile-time warnings about the following piece of code : Why is the CodeContracts static checker complaining about the strs.Add ( ... ) line ? There 's no possible...
public class Foo { private readonly List < string > strs = new List < string > ( ) ; public void DoSomething ( ) { // Compiler warning from the static checker : // `` requires unproven : source ! = null '' strs.Add ( `` hello '' ) ; } }
CodeContracts - false positives
C#
I have the following expression : When I perform a split as follows : Then it gives me three entries : Why does it give an empty line as the third entry and how can I avoid this ?
`` < p > What ? < /p > \n < pre > Starting Mini < /pre > '' var split = content .Split ( new [ ] { `` < pre > '' , `` < /pre > '' } , StringSplitOptions.None ) ; `` < p > What ? < /p > \n '' '' Starting Mini '' '' ''
Why does C # split give me an array ending in an empty line ?
C#
I 'm new to COBOL and I have been trying to read record information from a text file that is an output from the table.Most non-comp data-types i 'm okay with , it 's the 'COMP ' ones i 'm getting stuck on.I 've been trying to figure this out all day today reading as much as I can on this.The date fields below are the o...
05 VALDATE PIC 9 ( 6 ) COMP05 PAYDATE PIC 9 ( 6 ) COMP05 SYSDATE PIC 9 ( 6 ) COMP [ 32 ] [ 237 ] [ 44 ] [ 4 ] | 00100000 11101101 00101100 00000100 [ 33 ] [ 14 ] [ 32 ] [ 237 ] | 00100001 00001110 00100000 11101101 [ 131 ] [ 48 ] [ 48 ] [ 48 ] | 10000011 00110000 00110000 00110000 using ( BinaryReader reader = new Bina...
Read COBOL COMP data in C #
C#
I am Working on Xamarin.iOS.In the TableView . I am bind the Cell with Button.For Button Click I am doing Subscribe and Unsubscribe Cell event by below codethis is not working fine when I call data api again and set to the TableView.Explanation : When I open ViewController first time cell button click event fire 1 time...
cell.btn_Click.Tag = indexPath.Row ; cell.btn_Click.TouchUpInside -= BtnClickEvent ; cell.btn_Click.TouchUpInside += BtnClickEvent ; class StockListSourceClass : UITableViewSource { private List < PacketAndPacketDetailItem > stockLists ; private List < string > serialNoList ; private UINavigationController navigationCo...
Subscribe and Unsubscribe cell button Click event is not Working in iOS 11
C#
I have a simple test code that works as expected in .NET3.5 , but the same code behaves completely different on a project created with .NET4.5.1.First of all , the weird thing is that the NullReferenceException type exception is completely ignored in .NET4.5.1 when running the compiled RELEASE exe file . Basically , no...
class Program { static void Main ( string [ ] args ) { try { string a = null ; var x = a.Length ; } catch ( Exception ex ) { throw ; } finally { Console.WriteLine ( `` This is the finally block . `` ) ; } Console.WriteLine ( `` You should not be here if an exception occured ! `` ) ; } }
Try-Catch-Finally block issues with .NET4.5.1
C#
Should this regex pattern throw an exception ? Does for me.The error is : parsing `` ^\d { 3 } [ a '' - Unterminated [ ] set.I feel dumb . I do n't get the error . ( My RegexBuddy seems okay with it . ) A little more context which I hope does n't cloud the issue : I am writing this for a CLR user defined function in SQ...
^\d { 3 } [ a-z ] [ Microsoft.SqlServer.Server.SqlFunction ( IsDeterministic=true ) ] public static SqlChars Match ( SqlChars input , SqlString pattern , SqlInt32 matchNb , SqlString name , SqlBoolean compile , SqlBoolean ignoreCase , SqlBoolean multiline , SqlBoolean singleline ) { if ( input.IsNull || pattern.IsNull ...
Should this regex pattern throw an exception ?
C#
SetPartitions method accepts an array of prime numbers such as 2 , 3 , 5 , 2851 , 13.In the above example , it should assign : How to implement the logic ?
public int Partition1 { get ; set ; } public int Partition1 { get ; set ; } private void SetPartitions ( List < int > primeNumbers ) { this.Partition1 = // get the product of the prime numbers closest to 10000 this.Partition2 = // get the product of the remaining prime numbers } this.Partition1 = 2851 * 3 ; // which is...
How to find out the closest possible combination of some given prime numbers to 10000 ?
C#
I 'm trying to use the SearchBox control introduced in Windows 8.1 , but I ca n't figure out how to display the image in the result suggestions . The suggestions appear , but the space where the image should be remains blank : Here 's my XAML : And my code behind : Am I missing something ? Some extra details : I tried ...
< SearchBox SuggestionsRequested= '' SearchBox_SuggestionsRequested '' / > private async void SearchBox_SuggestionsRequested ( SearchBox sender , SearchBoxSuggestionsRequestedEventArgs args ) { var deferral = args.Request.GetDeferral ( ) ; try { var imageUri = new Uri ( `` ms-appx : ///test.png '' ) ; var imageRef = aw...
Image not shown for result suggestions in SearchBox
C#
I use C # , .NET 4.5 , Console application.I added WSDL file in service reference . Inside WSDL are validation rules like : There is XSD file too , with details of validation rules like : And I have automatically generated properties from WSDL in Reference.cs like : I serialize xRequest object into XML and I want to va...
< xs : complexType name= '' xRequest '' > < xs : sequence > < xs : element name= '' SenderDateTime '' type= '' ip : grDateTime '' / > < xs : element name= '' SenderId '' type= '' ip : grIdentifier '' / > < /xs : sequence > < /xs : complexType > < xs : simpleType name= '' grDateTime '' > < xs : restriction base= '' xs :...
How validate XML with XSD , when part of validation rules are in WSDL
C#
It has been a while since I 'd understood covariance , but should n't this compile ? Anything bar can return is also an IMyInterface . What seems to be the problem ?
public void Foo < T > ( Func < T > bar ) where T : IMyInterface { Func < IMyInterface > func = bar ; }
Covariance , delegates and generic type constraints
C#
I surfed into this site a few days ago on `` Anonymous Recursion in C # '' . The thrust of the article is that the following code will not work in C # : The article then goes into some detail about how to use currying and the Y-combinator to get back to `` Anonymous Recursion '' in C # . This is pretty interesting but ...
Func < int , int > fib = n = > n > 1 ? fib ( n - 1 ) + fib ( n - 2 ) : n ; using System ; public class Program { public static void Main ( string [ ] args ) { int x = int.Parse ( args [ 0 ] ) ; Func < int , int > fib = n = > n > 1 ? fib ( n - 1 ) + fib ( n - 2 ) : n ; Console.WriteLine ( fib ( x ) ) ; } } Func < int , ...
Does `` Anonymous Recursion '' work in .NET ? It does in Mono
C#
I have the follow extension method I have been using . I was not aware until recently that EF Core 2.x , by default , performs mixed evaluation , which means that for the things it does n't know how to convert into SQL , it will pull down everything from the database , and then perform the LINQ queries in memory . I ha...
public static class RepositoryExtensions { public static IQueryable < T > NonDeleted < T > ( this IQueryable < T > queryable ) where T : IDeletable { return queryable.Where ( x = > ! x.Deleted ) ; } } // Service layerpublic class OrganizationService { public IEnumerable < Data.Entities.Organization > GetAllForUser ( in...
EF Core 2.x - IQueryable extension is getting evaluated at the client and not the database
C#
What could be the purpose of the tilde in this code block ? ^ Operator ( C # Reference ) Visual Studio 2010Binary ^ operators are predefined for the integral types and bool . For integral types , ^ computes the bitwise exclusive-OR of its operands . For bool operands , ^ computes the logical exclusive-or of its operand...
public override int GetHashCode ( ) { return ~this.DimensionId.Id ^ this.ElementId.Id ; }
What is the purpose of the tilde in this situation ?
C#
Is it possible in C # ( I 'm using .Net 4.5 , but asking more generally ) to determine if two implementations of a generic type are functionally equivalent ? As an example of the need , suppose I have an IMapper interface defined as : My ideal implementation of this is : This would be functionally equivalent to : but t...
public interface IMapper < TTo , TFrom > { TTo MapFrom ( TFrom obj ) ; TFrom MapFrom ( TTo obj ) ; } public class MyMapper : IMapper < A , B > { A MapFrom ( B obj ) { ... } B MapFrom ( A obj ) { ... } } public class MyEquivalentMapper : IMapper < B , A > { B MapFrom ( A obj ) { ... } A MapFrom ( B obj ) { ... } } publi...
Determine type equivalence
C#
Consider this codeI 'm just taking my database type and converting to MailMessage.It get 's sent in another function . Code analysis tells me I 'm not disposing `` msg '' which is correct . But if I do it here - I get exception when I 'm trying to send it.Also , it complains about not disposing MemoryStream here : msg....
private MailMessage GetMailMessageFromMailItem ( Data.SystemX.MailItem mailItem ) { var msg = new MailMessage ( ) ; foreach ( var recipient in mailItem.MailRecipients ) { var recipientX = Membership.GetUser ( recipient.UserKey ) ; if ( recipientX == null ) { continue ; } msg.To.Add ( new MailAddress ( recipientX.Email ...
Code analysis complains I 'm not disposing objects . What is wrong here ?
C#
i am new to this and i am creating simple application in which i click a button and a notification on desktop should be displayed . i am doing this in windows form c # the error is `` NullReferenceException was unhandledi have one button Notify in form1 . i have tried this : form1.cscode for HTMLPage1.html : even if i ...
public Form1 ( ) { InitializeComponent ( ) ; this.Load += new EventHandler ( Form1_Load ) ; webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler ( webBrowser1_DocumentCompleted ) ; webBrowser1.ScriptErrorsSuppressed = true ; } private void btnNotify_Click ( object sender , EventArgs e ) { webBro...
desktop notification using javascript in windows form
C#
I am able to get faces from Live Web Cam as a list of Windows.Media.FaceAnalysis DetectedFace objects . Now I would like to pass these faces to Microsoft Cognitive Services API to detect faces and get the face attributes . How can I do this ?
IList < DetectedFace > faces = null ; // Create a VideoFrame object specifying the pixel format we want our capture image to be ( NV12 bitmap in this case ) .// GetPreviewFrame will convert the native webcam frame into this format.const BitmapPixelFormat InputPixelFormat = BitmapPixelFormat.Nv12 ; using ( VideoFrame pr...
How to detect face attributes using Microsoft Cognitive service by providing Windows.Media.FaceAnalysis DetectedFace list ?
C#
What Am I missing ? Error 2 Argument 1 : can not convert from 'System.Func ' to 'System.Collections.Generic.IComparer ' Error 1 The best overloaded method match for 'System.Collections.Generic.List.Sort ( System.Collections.Generic.IComparer ) ' has some invalid argumentsWhen I haveit works fine . Are they not the same...
List < bool > test = new List < bool > ( ) ; test.Sort ( new Func < bool , bool , int > ( ( b1 , b2 ) = > 1 ) ) ; private int func ( bool b1 , bool b2 ) { return 1 ; } private void something ( ) { List < bool > test = new List < bool > ( ) ; test.Sort ( func ) ; }
About list sorting and delegates & lambda expressions Func stuff
C#
I 'm trying to implement undo functionality with C # delegates . Basically , I 've got an UndoStack that maintains a list of delegates implementing each undo operation . When the user chooses Edit : Undo , this stack pops off the first delegate and runs it . Each operation is responsible for pushing an appropriate undo...
public void SetCashOnHand ( int x ) { int coh = this.cashOnHand ; undo u = ( ) = > this.setCashOnHand ( coh ) ; this.cashOnHand = x ; undoStack.Push ( u ) ; } undo u = ( ) = > this.setCashOnHand ( this.cashOnHand ) ;
C # Lambdas : How *Not* to Defer `` Dereference '' ?
C#
UPDATE : the next version of C # has a feature under consideration that would directly answer this issue . c.f . answers below.Requirements : App data is stored in arrays-of-structs . There is one AoS for each type of data in the app ( e.g . one for MyStruct1 , another for MyStruct2 , etc ) The structs are created at r...
public Dictionary < System.Type , System.Array > structArraysByType ; public void registerStruct < T > ( ) { System.Type newType = typeof ( T ) ; if ( ! structArraysByType.ContainsKey ( newType ) ) { structArraysByType.Add ( newType , new T [ 1000 ] ) ; // allowing up to 1k } } public T get < T > ( int index ) { return...
Storing a C # reference to an array of structs and retrieving it - possible without copying ?
C#
I want to do something like this : This does n't work as written ; is there some minimal workaround to make it work ? Basically I want 0 to chain until non-zero ( or end of chain ) .
public override int CompareTo ( Foo rhs ) { return Bar.CompareTo ( rhs.Bar ) ? ? Baz.CompareTo ( rhs.Baz ) ? ? Fuz.CompareTo ( rhs.Fuz ) ? ? 0 ; }
Can I use the coalesce operator on integers to chain CompareTo ?
C#
Possible Duplicate : What is the difference between String.Empty and “ ” Which of the following should I use for assigning an empty string and why ? or
string variableName = `` '' ; string variableName = string.Empty ;
Which should I use for empty string and why ?
C#
I do n't get it . The As operator : Then why does the following work ? Baby is a struct , creating it will put value in stack . There is no reference involve here.There are certainly no nullable types here.Any explanation as to why I 'm wrong ?
struct Baby : ILive { public int Foo { get ; set ; } public int Ggg ( ) { return Foo ; } } interface ILive { int Ggg ( ) ; } void Main ( ) { ILive i = new Baby ( ) { Foo = 1 } as ILive ; // ? ? ? ? ? ? Console.Write ( i.Ggg ( ) ) ; // Output : 1 }
The as operator on structures ?
C#
I have the following class declaration : I have an Html helper method : This is my ASP.NET MVC ascx : When I pass in an IQueryable collection to the ascx , I get this error : Compiler Error Message : CS1928 : 'System.Web.Mvc.HtmlHelper > ' does not contain a definition for 'TagCloud ' and the best extension method over...
public class EntityTag : BaseEntity , ITaggable public static string TagCloud ( this HtmlHelper html , IQueryable < ITaggable > taggables , int numberOfStyleVariations , string divId ) < % @ Control Language= '' C # '' Inherits= '' System.Web.Mvc.ViewUserControl < IQueryable < EDN.MVC.Models.EntityTag > > '' % > < % @ ...
Why does n't c # support an object with an interface as a parameter ?
C#
I was going through a website I 've taken over and came across this section in one of the pages : Apparently anyone who has ever used the site without javascript would not be able to log out properly ( surprisingly enough , this has never come up ) .So the first thing that comes to mind isThen I realized I do n't know ...
< a href= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a > < a href= '' < % =GetSignOutUrl ( ) '' onclick= '' javascript : window.location= ' < % =GetSignOutUrl ( ) % > ' ; '' > // img < /a >
Why use window.location in a hyperlink ?
C#
Here 's an example : In the VS2008 output window this shows : A first chance exception of type 'System.ArgumentException ' occurred in System.Drawing.dll Additional information : Parameter is not valid . ( pic http : //i.imgur.com/nM2oNm1.png ) This is on Windows 7.Documentation herehttps : //msdn.microsoft.com/en-us/l...
public MainForm ( ) { InitializeComponent ( ) ; LinearGradientBrush brush = new LinearGradientBrush ( new Rectangle ( 0,0,100,100 ) , Color.Blue , Color.White , angle:0 ) ; brush.WrapMode = WrapMode.Tile ; // OK brush.WrapMode = WrapMode.Clamp ; // Causes Unhandled exception alert , offering break }
Why does setting LinearGradientBrush.WrapMode to Clamp fail with ArgumentException ( `` parameter is not valid '' ) ?
C#
I just installed the fresh released Community Edition of Visual Studio 2015 ( RTM ) and I 'm trying to get my open source project working under VS2015 and C # 6.0 . Some of my .cs are shared across projects . This way I 'm able to build both a PCL version ( with limited functionality ) and a 'full ' version of the core...
/// < summary > < /summary > public class A { // Compile error on next line : /// < summary > < see cref= '' Y ( Type ) '' / > . < /summary > public void X ( ) { } /// < summary > < /summary > /// < param name= '' x '' > < /param > public void Y ( Type x ) { } /// < summary > < /summary > /// < param name= '' i '' > < ...
Visual Studio 2015 / C # 6 / Roslyn ca n't compile XML comments in PCL project
C#
Apologies if this seems a simple question , but I mostly just want to check that the solution I have is the most sensible/holds for all cases.The pre-existing SQL Server database we work with stores a 'period ' as inclusive start - > inclusive end UTC DateTime values . ( Both start & end columns are datetime2 ( 7 ) , a...
public static LocalDateTime AtEndOfDay ( this LocalDate localDate ) { return localDate .PlusDays ( 1 ) .AtMidnight ( ) .PlusTicks ( -1 ) ; } public static ZonedDateTime AtEndOfDay ( this DateTimeZone zone , LocalDate localDate ) { return zone .AtStartOfDay ( localDate.PlusDays ( 1 ) ) .Plus ( Duration.FromTicks ( -1 ) ...
What is the neatest way to find the last possible instant of a LocalDate , in a particular time-zone ?
C#
Consider this basic implementation of the maybe monad : Its purpose is to handle a chain of functions returning optional values in a clean way : In the above case both GetOrder and GetClient return a Maybe < T > , but handling of the None case is hidden inside Bind . So far so good.But how would I bind a Maybe < T > to...
public class Maybe < T > { private readonly T value ; private Maybe ( bool hasValue , T value ) : this ( hasValue ) = > this.value = value ; private Maybe ( bool hasValue ) = > HasValue = hasValue ; public bool HasValue { get ; } public T Value = > HasValue ? value : throw new InvalidOperationException ( ) ; public sta...
How do I do a monadic bind to an async function ?
C#
I have an extension method likeAnd I have two classesandI call RemoveDetail from an Action accepted by method public static void Foreach < T > ( this IEnumerable < T > source , Action < T > action ) ; : ReSharper suggest me to replace this call with method group likeThis worked fine in VS2013 and previous but it fails ...
public static void RemoveDetail < TMaster , TChild > ( this TMaster master , TChild child ) where TMaster : class , IMaster < TChild > where TChild : class , IDetail < TMaster > ; public class Principal : IMaster < Permission > { public virtual IEnumerable < Permission > Permissions { get ; } } public class Permission ...
Visual Studio 2015 extension method call as method group
C#
I have a list of objects that have a property Rank . This is an integer.I want to sort by rank on my view but when i do this : i get all of the zeros ( meaning these have n't been set at the top ) I want to order by 1 -- > n but have the zeros be at the bottom of the list.I would like it to be as efficient a sort as po...
myObjects = myObjects.Orderby ( r= > r.Rank ) ;
How can I sort but put zeros at the bottom ?
C#
I 'm developping a webapplication . For the security of the users information i need a https connection . I 'm developping this local at the moment . I have followed the tutorial on : http : //weblogs.asp.net/dwahlin/archive/2009/08/25/requiring-ssl-for-asp-net-mvc-controllers.aspxWhen I build my project the page loads...
[ RequiresSSL ] public ActionResult Index ( ) { //var model = Adapter.EuserRepository.GetAll ( ) ; return View ( db.Eusers.ToList ( ) ) ; } using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Mvc ; namespace extranet.Helpers { public class RequiresSSL : ActionFilter...
How to use https in c # ?
C#
Is it somehow possible to set alternate names for querystring parameters in ASP.NET MVC ? I have this simple controller Index action : Calling http : //mysite.com/mypage/ ? color=yellow works quite nicely , the color parameter automatically picks up its value `` yellow '' from the querystring.But now I would like to ha...
public ActionResult Index ( color = `` '' ) { ... }
Alternate names for querystring parameters
C#
Broken code The code above is expecting to express : The conclusion infers the premise because of the premise implies the conclusion . The the premise implies the conclusion because of the conclusion infers the premise . It would be circular reasoning , and definitely will cause stack overflow . I then redesign it as f...
public static partial class LogicExtensions { public static bool Implies < T > ( this T premise , T conclusion ) { return conclusion.Infers ( premise ) ; } public static bool Infers < T > ( this T premise , T conclusion ) { return premise.Implies ( conclusion ) ; } } public delegate bool Paradox < T > ( T premise , T c...
Informal fallacy causes stack overflow
C#
I am trying to create a parallel event subscriber . This is my first attempt : In your expert opinion , is this a valid approach ? Could you please suggest any improvements ? PS : Maybe : would be better ?
using System ; using System.Collections.Generic ; using System.Threading.Tasks ; using EventStore.ClientAPI ; namespace Sandbox { public class SomeEventSubscriber { private Position ? _latestPosition ; private readonly Dictionary < Type , Action < object > > _eventHandlerMapping ; private IEventStoreConnection _connect...
parallel event subscriber .net 4.5
C#
I have a C # .Net 4.0 Application on the one hand and on the other a VB6 App . I created a COM Interface by making the Project COM Visible and actived register COM Interop.I Tested the COM interface by implementing a C # Application wich imports the new tlb file . All seems to be fine . As next step I tried to use the ...
[ ComSourceInterfaces ( typeof ( COMEvents ) ) ] [ Guid ( `` 11947063-4665-4DE1-931D-9915CCD01794 '' ) ] [ InterfaceType ( ComInterfaceType.InterfaceIsIDispatch ) ] public interface COMEvents { void MethodOne ( ) ; void MethodTwo ( ) ; }
COM class visibility : C # to VB6
C#
I think so . But take a look at a built-in class in ASP.NET : Suppose I have an instance of HttpPostedFile called file . Since there is no Dispose method to explicitly invoke , file.InputStream.Dispose ( ) wo n't be invoked until it 's destructed , which I think goes against the original intention of IDisposable . I th...
public sealed class HttpPostedFile { public Stream InputStream { get ; } // Stream implements IDisposable // other properties and methods }
Should we implement IDisposable if one member is IDisposable
C#
With a generic List , what is the quickest way to check if an item with a certain condition exists , and if it exist , select it , without searching twice through the list : For Example :
if ( list.Exists ( item = > item == ... ) ) { item = list.Find ( item = > item == ... ) ... . }
Checking for item in Generic List before using it
C#
The SituationWe are selling a Windows Forms Application to customers all over the world.We installed it in several countries in Europe and America . No problems.Last week we installed our software in South-Korea and recognized a strange behaviour ... The problem occurs only on the customers office PCs , but on all of t...
InitializeComponent ( ) ; this.m_actSize = this.ClientSize ; void myFormSizeChanged ( object sender , EventArgs e ) { this.m_xFactor = ( float ) this.ClientSize.Width / ( float ) this.m_actSize.Width ; this.m_yFactor = ( float ) this.ClientSize.Height / ( float ) this.m_actSize.Height ; if ( this.m_MyOnResize ! = null ...
Wrong scaling on Korean PCs
C#
The following code using LINQ in NHibernate returns a different result from in-memory LINQ and EF LINQ . What is the correct way to do this in NHibernate ? It is fine to use QueryOver if the LINQ version is indeed broken.Expected resultsActual resultsLogged SQLThe full code is in the bug report Incorrect result when us...
using ( var session = factory.OpenSession ( ) ) using ( var transaction = session.BeginTransaction ( ) ) { for ( int i = 0 ; i < 10 ; ++i ) { session.Save ( new A ( ) { X = i % 2 , Y = i / 2 , } ) ; } transaction.Commit ( ) ; } using ( var session = factory.OpenSession ( ) ) using ( var transaction = session.BeginTrans...
How to query the first entry in each group in NHibernate
C#
I have mainly worked in C++ and I am now using C # at my new job , and after doing some reading on here about the 'ref ' keyword and c # value vs reference types I am still finding some confusion with them.As far as I 'm understanding these if you were passing these to a method these would be analogous C++ styles : Val...
public void CSharpFunc ( value ) public void CPlusplusFunc ( value ) public void CSharpFunc ( reference ) public void CPlusPlusFunc ( & reference ) public void CSharpFunc ( ref bar ) public void CPlusPlus ( *bar )
Use of C # 'ref ' keyword compared to C++
C#
I have this COM method signature , declared in C # : I call it like this : Does the .NET interop layer first copy the whole array to a temporary unmanaged memory buffer , then copy it back ? Or does the array get automatically pinned and passed by reference ? For the sake of trying , I did this in the COM object ( C++ ...
void Next ( ref int pcch , [ MarshalAs ( UnmanagedType.LPArray , SizeParamIndex = 0 ) ] char [ ] pchText ) ; int cch = 100 ; var buff = new char [ cch ] ; com.Next ( ref cch , buff ) ; *pcch = 1 ; pchText [ 0 ] = L ' A ' ; pchText [ 1 ] = L'\x38F ' ; // ' Ώ '
Does .NET interop copy array data back and forth , or does it pin the array ?
C#
Using c # Web Api 2 , I have code that throws an InvalidOperationException . When returning a status code of 302 , how do provide a location for the redirect using the HandleException annotation ? Edit : Sorry , I asked this question in a bit of haste . The above class uses a HandleExceptionAttribute class which inheri...
[ HandleException ( typeof ( InvalidOperationException ) , HttpStatusCode.Found , ResponseContent = `` Custom message 12 '' ) ] public IHttpActionResult GetHandleException ( int num ) { switch ( num ) { case 12 : throw new InvalidOperationException ( `` DONT SHOW invalid operation exception '' ) ; default : throw new E...
How do you specify the location when using handleexeption annotation for a 302 status code
C#
When should locks be used ? Only when modifying data or when accessing it as well ? Should there be a lock around the the entire block or is it ok to just add it to the actual modification ? My understanding is that there still could be some race condition where one call might not have found it and started to add it wh...
public class Test { static Dictionary < string , object > someList = new Dictionary < string , object > ( ) ; static object syncLock = new object ( ) ; public static object GetValue ( string name ) { if ( someList.ContainsKey ( name ) ) { return someList [ name ] ; } else { lock ( syncLock ) { object someValue = GetVal...
locking only when modifying vs entire method
C#
I have a class similar to : I then created a method to pull the names from the class.So when I get my array it would be in the following order : I was wondering if it was possible to change the order so that the base class fields were first followed by the derived class fields ?
public class MyClass : MyBaseClass { public string Field1 { get ; set ; } public string Field2 { get ; set ; } public string Field3 { get ; set ; } public string Field4 { get ; set ; } } public class MyBaseClass { public string BaseField1 { get ; set ; } public string BaseField2 { get ; set ; } public string BaseField3...
How to get a list of property names in a class in certain a order
C#
This may seem a little crazy , but it 's an approach I 'm considering as part of a larger library , if I can be reasonably certain that it 's not going to cause weird behavior.The approach : Run async user code with a SynchronizationContext that dispatches to a thread pool . The user code would look something like : I ...
async void DoSomething ( ) { int someState = 2 ; await DoSomethingAsync ( ) ; someState = 4 ; await DoSomethingElseAsync ( ) ; // someState guaranteed to be 4 ? }
Multiplexing C # 5.0 's async over a thread pool -- thread safe ?
C#
Expected end results is to get an IEnumerable with 1.2 , 2.3 , 3.1 , 4.2 which represents the SubTierId of each subTier.but what happens is I get this return type . What is the best way so that I just get a single IEnumerable of the SubSubTier ?
Top Tier Object SubTier Objects SubSubTier Objects 1.1,1.2,1.3 : SubTierId = 2 SubSubTier Objects 2.1,2.2,1.3 : SubTierId = 3 SubTier Objects SubSubTier Objects 3.1,3.2,3.3 : SubTierId = 1 SubSubTier Objects 4.1,4.2,4.3 : SubTierId = 2 SubSubTiers mySubSubTier = allTiers.Select ( topTier = > topTier.SubTiers.Where ( sb...
How to get Sub objects based on value using linq ?
C#
I ran into what I think is a really odd situation with entity framework . Basically , if I update an row directly with a sql command , when I retrive that row through linq it does n't have the updated information . Please see the below example for more information.First I created a simple DB tableThen I created a conso...
CREATE TABLE dbo.Foo ( Id int NOT NULL PRIMARY KEY IDENTITY ( 1,1 ) , Name varchar ( 50 ) NULL ) public class FooContext : DbContext { public FooContext ( ) : base ( `` FooConnectionString '' ) { } public IDbSet < Foo > Foo { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelB...
Unexpected behavior in entity framework
C#
I just came across a strange behavior with using async methods in structures . Can somebody explain why this is happening and most importantly if there is a workaround ? Here is a simple test structure just for the sake of a demonstration of the problemNow , let 's use the structure and do the following callsThe first ...
public struct Structure { private int _Value ; public Structure ( int iValue ) { _Value = iValue ; } public void Change ( int iValue ) { _Value = iValue ; } public async Task ChangeAsync ( int iValue ) { await Task.Delay ( 1 ) ; _Value = iValue ; } } var sInstance = new Structure ( 25 ) ; sInstance.Change ( 35 ) ; awai...
Struct 's private field value is not updated using an async method
C#
I had read data from an XML file into DataSet by using c # than I want to identify duplicate ( completely the same ) rows in that set.I tried such kind of grouping and that works ! But the number of data columns can be differ , so I can not apply static grouping in query like above . I had to generate the grouping arra...
var d= from r1 in table.AsEnumerable ( ) group r1 by new { t0 = r1 [ 0 ] , t1 = r1 [ 1 ] , t2 = r1 [ 2 ] , t3 = r1 [ 3 ] , t4 = r1 [ 4 ] , t5 = r1 [ 5 ] , t6 = r1 [ 6 ] , t7 = r1 [ 7 ] , t8 = r1 [ 8 ] , } into grp where grp.Count ( ) > 1 select grp ;
Query to detect duplicate rows
C#
Could you please explain me the reason of the following situation.Today I wrote the code ( only variables names are changed ) : Everything was fine until I decided to move the if condition to a variable : Now the compiler underlines firstInteger and secondInteger variables with error `` Local variable might not be init...
private void Foo ( ) { int firstInteger , secondInteger ; const string firstStringValue = `` 1 '' , secondStringValue = `` 2 '' ; if ( ! string.IsNullOrWhiteSpace ( firstStringValue ) & & int.TryParse ( firstStringValue , out firstInteger ) & & ! string.IsNullOrWhiteSpace ( secondStringValue ) & & int.TryParse ( second...
Moving `` if '' statement condition to a local variable makes C # compiler unhappy
C#
I have a business layer class that uses System.IO.File to read information from various files . In order to unit test this class I 've chosen to replace the dependency on the File class with an injected dependency like so : Now I can test my class using a Mock and all is right with the world . Separately , I need a con...
using System.IO ; public interface IFileWrapper { bool FileExists ( string pathToFile ) ; Stream Open ( string pathToFile ) ; } using System ; using System.IO ; public class FileWrapper : IFileWrapper { public bool FileExists ( string pathToFile ) { return File.Exists ( pathToFile ) ; } public Stream Open ( string path...
How do I ( or do I ) unit test a concrete dependency
C#
For EF6 , I had a method in my generic repository that I exposed to all service layers in order to retrieve entities from the database with any nested properties as needed : This way , I could use the method in the following way : In EF6 , this would load the Papers navigation property , the People navigation property ...
public IQueryable < T > OldMethod ( params Expression < Func < T , object > > [ ] includeProperties ) { var queryable = set.AsQueryable ( ) ; return includeProperties.Aggregate ( queryable , ( current , includeProperty ) = > current.Include ( includeProperty ) ) ; } var data = repo.OldMethod ( x = > x.Papers , = > x.Pe...
Translating generic eager load method from EF6 to EF Core
C#
This piece of code caught me out today : clientFile.Review month is a byte ? and its value , in the failing case , is null.The expected result type is string.The exception is in this codeThe right hand side of the evaluation is being evaluated and then implicitly converted to a string.But my question is why is the righ...
clientFile.ReviewMonth == null ? null : MonthNames.AllValues [ clientFile.ReviewMonth.Value ] public static implicit operator string ( LookupCode < T > code ) { if ( code ! = null ) return code.Description ; throw new InvalidOperationException ( ) ; }
C # Ternary Operator evaluating when it should n't
C#
I 've just upgraded to VS2015.1 and got a compiler crash when trying to compile one of my projects . If you put the following repo code in a console application ( and add a reference to moq.dll ) the code in line 12 crashes my compiler . It seems to happen during a Roslyn lamdba rewrite call.Anyone know why the crash o...
using System.Collections.Generic ; using System.Linq ; using Moq ; namespace RoslynError { class Program { static void Main ( string [ ] args ) { var mockRepo = new MockRepository ( MockBehavior.Strict ) ; var obj = mockRepo.OneOf < DTO > ( x = > x.Value == ( OptionEnum ? ) null ) ; } } class DTO { public DTO ( OptionE...
Why does Roslyn crash when trying to rewrite this lambda ? ( Visual Studio 2015 update 1 )
C#
Updated with a solution that works for me . See the bottom of this question.Context : I needed a way to evaluate the size of a generic type for the purpose of calculating array lengths to fit within a certain byte size . Basically , sizeof similar to what C/C++ provides.C # 's sizeof and Marshal.SizeOf are not suitable...
.assembly extern mscorlib { } .assembly extern netstandard { .publickeytoken = ( B7 7A 5C 56 19 34 E0 89 ) .ver 0:0:0:0 } .assembly extern System.Runtime { .ver 0:0:0:0 } .assembly extern System.Runtime { .ver 0:0:0:0 } .assembly Company.IL { .ver 0:0:1:0 } .module Company.IL.dll// CORE is a define for mscorlib , netst...
Using assemblies compiled from IL with .NET Core & Xamarin
C#
Ok , consider the following code : trueOrFalse is a compile time constant and as such , the compiler warns correctly that int hash = o.GetHashCode ( ) ; is not reachable.Also , constObject is a compile time constant and as such the compiler warns again correctly that int hash = o.GetHashCode ( ) ; is not reachable as o...
const bool trueOrFalse = false ; const object constObject = null ; void Foo ( ) { if ( trueOrFalse ) { int hash = constObject.GetHashCode ( ) ; } if ( constObject ! = null ) { int hash = constObject.GetHashCode ( ) ; } } if ( true ) { int hash = constObject.GetHashCode ( ) ; }
Compile time constants and reference types
C#
I have these statements and their ' results are near them.Why the last equality gives me false ? The question is why ( x == y ) is true ( k == m ) is false
string a = `` abc '' ; string b = `` abc '' ; Console.Writeline ( a == b ) ; //trueobject x = a ; object y = b ; Console.Writeline ( x == y ) ; // truestring c = new string ( new char [ ] { ' a ' , ' b ' , ' c ' } ) ; string d = new string ( new char [ ] { ' a ' , ' b ' , ' c ' } ) ; Console.Writeline ( c == d ) ; // t...
Object equality behaves different in .NET
C#
Hello I want to scan audio-video files and store their metadata in a database using php . I found this Command-line wrapper that uses TagLib.dll compiled by banshee developpers to do the job . It 's works fine but it limited by the functions implemented . I want to access directly to the dll methods via PHP.In PHP we h...
/* $ obj = new DOTNET ( `` assembly '' , `` classname '' ) ; */ $ stack = new DOTNET ( `` mscorlib '' , `` System.Collections.Stack '' ) ; $ stack- > Push ( `` .Net '' ) ; $ stack- > Push ( `` Hello `` ) ; echo $ stack- > Pop ( ) . $ stack- > Pop ( ) ; //Returns string ( 10 ) `` Hello .Net '' ; ; DESCRIPTION `` Simple ...
Build TagLib # DLL from source and make it COM Visible to PHP
C#
The following code : might be optimized toif x gets assigned in another thread only . See Illustrating usage of the volatile keyword in C # . The answer there solves this by setting x to be volatile.However , it looks like that is not the correct way to go about it according to these three contributors ( with a combine...
while ( x == 1 ) { ... } while ( true ) { ... }
Prevent bad-optimization in Multithreading
C#
Input in my case is a string with a list of elements separated by CommaInput : Expected Output ( a string ) : I 'm looking for a solution in VB.net but i 'm not so familiar with it . So , I tried it in c # . Not sure what i 'm missing . My Attempt : Actual Output : Any help in funding a solution in vb.net is much appre...
var input = `` 123,456,789 '' ; `` '123 ' , '456 ' , '789 ' '' var input = `` 123,456,789 '' ; var temp = input.Split ( new Char [ ] { ' , ' } ) ; Array.ForEach ( temp , a = > a = `` ' '' + a + `` ' '' ) ; Console.WriteLine ( String.Join ( `` , '' , temp ) ) ; `` 123,456,789 ''
Appending a Char to each element in a array
C#
I want to be able to specify something like this : Class FilterControl < > is a base class . I can not know what will be the generic argument for FilterControl < > .
public abstract class ColumnFilter < TCell , TFilterControl > : ColumnFilter where TFilterControl : FilterControl < > , new ( ) where TCell : IView , new ( ) { }
Generic type in generic constraint
C#
I 'm using specifications in this kind of form : Now I can use this specification in the form : But I 'm not sure how to use the specification against an associated object like this : Is there a way to do this , or do I need to rethink my implementation of specifications ?
public static Expression < Func < User , bool > > IsSuperhero { get { return x = > x.CanFly & & x.CanShootLasersFromEyes ; } } var superHeroes = workspace.GetDataSource < User > ( ) .Where ( UserSpecifications.IsSuperhero ) ; var loginsBySuperheroes = workspace.GetDataSource < Login > ( ) .Where ( x = > x.User [ ? ? ? ...
Linq : how to use specifications against associated objects
C#
Im making a graph program and im stuck at where I need to get mouse coordinates to equal graphic scale . With picturebox I use transform to scale my graphic : Im using MouseMove function . Is there a way to transform mouse coordinates ? When I put my mouse on x=9 I need my mouse coordinate to be 9 .
RectangleF world = new RectangleF ( wxmin , wymin , wwid , whgt ) ; PointF [ ] device_points = { new PointF ( 0 , PictureBox1.ClientSize.Height ) , new PointF ( PictureBox1.ClientSize.Width , PictureBox1.ClientSize.Height ) , new PointF ( 0 , 0 ) , } ; Matrix transform = new Matrix ( world , device_points ) ; gr.Transf...
Transforming mouse coordinates
C#
What is better : to have large code area in lock statementorto have small locks in large area ? ..exchanges in this sample are not changable . or
lock ( padLock ) { foreach ( string ex in exchanges ) { sub.Add ( x.ID , new Subscription ( ch , queue.QueueName , true ) ) ; ... ... ... } foreach ( string ex in exchanges ) { lock ( padLock ) { sub.Add ( x.ID , new Subscription ( ch , queue.QueueName , true ) ) ; } ... ..
What is the proper way to lock code areas
C#
I have an NUnit unit test which I have two collections of different types which I want to assert are equivalent.where Assert.IsPrettySimilar is defined like suchMy question is , is there a more idiomatic way of doing the above with the existing methods in NUnit ? I already looked at CollectionAssert and there 's nothin...
class A { public int x ; } class B { public string y ; } [ Test ] public void MyUnitTest ( ) { var a = GetABunchOfAs ( ) ; // returns IEnumerable < A > var b = GetABunchOfBs ( ) ; // returns IEnumerable < B > Assert.IsPrettySimilar ( a , b , ( argA , argB ) = > argA.ToString ( ) == argB ) ; } public static void IsPrett...
Assert two different types of enumerations are equivalent
C#
I am a new ASP.NET developer and I am developing a web-based application in which there is a menu bar that has many options . Some of these options will be displayed only to the Admin . There is a logic behind the system to check whether the user is an admin or not . If yes , the options will be displayed . I wrote the...
private bool isAdmin ( string username ) { string connString = `` Data Source=appSever\\sqlexpress ; Initial Catalog=TestDB ; Integrated Security=True '' ; string cmdText = `` SELECT ID , NetID FROM dbo.Admins WHERE NetID = ' '' + NetID + `` ' ) '' ; using ( SqlConnection conn = new SqlConnection ( connString ) ) { con...
How to remove the sql injection from this query and make it working well ?
C#
I am stepping through the WPF source code to debug some issue with my own code . I have the source and the pdb 's ( I 'm using dotpeek as a symbol server so I have the full pdbs with source code ) and I can step into the WPF code no problem . The modules I am interested in are PresentationFramework and System.Xaml . Th...
ngen uninstall PresentationFrameworkUninstalling assembly PresentationFramework , Version=3.0.0.0 , Culture=Neutral , PublicKeyToken=31bf3856ad364e35 , processorArchitecture=msilUninstalling assembly PresentationFramework , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35Uninstalling assembly Present...
How to temporarily stop optimisation of WPF framework elements ?
C#
I have a regex to match date format with comma . yyyy/mm/dd or yyyy/mmFor example : 2016/09/02,2016/08,2016/09/30My code : I use option multiline.If string data have `` \n '' .Any character will match this regex.For example : I find option definition in MSDN . It says : It changes the interpretation of the ^ and $ lang...
string data= '' 21535300/11/11\n '' ; Regex reg = new Regex ( @ '' ^ ( 20\d { 2 } / ( 0 [ 1-9 ] |1 [ 012 ] ) ( / ( 0 [ 1-9 ] | [ 12 ] \d|30|31 ) ) ? , ? ) * $ '' , RegexOptions.Multiline ) ; if ( ! reg.IsMatch ( data ) ) `` Error '' .Dump ( ) ; else `` True '' .Dump ( ) ; string data= '' test\n '' string data= '' 2100/...
Regex option `` Multiline ''
C#
I have 5 numbers i.e . : 1 1 1 2 3 ; I have to sum them except the minimum number , but I can remove it only one time ( if the minimum occurs more than one time I have to maintain the rest ) . How can I do it with Linq ? I thought : But it remove all the 1s from the lists . I need a way to go out from the where if ther...
var min = nums.Min ( ) ; var minSum = nums.Where ( x = > x ! = min ) .Sum ( ) ;
Linq remove only one item if there are duplicate
C#
Is there any way to find a path in C # dynamically without executing `` where '' command prompt command ? For example , if I want to find mspaint exe , I can type this in command promptand it returns the path .
where mspaint
Equivalent of `` where '' command prompt command in C #
C#
I just hit a situation where a method dispatch was ambiguous and wondered if anyone could explain on what basis the compiler ( .NET 4.0.30319 ) chooses what overload to callIn any case , why does the compiler not warn me or even why does it compile ? Thank you very much for any answers .
interface IfaceA { } interface IfaceB < T > { void Add ( IfaceA a ) ; T Add ( T t ) ; } class ConcreteA : IfaceA { } class abstract BaseClassB < T > : IfaceB < T > { public virtual T Add ( T t ) { ... } public virtual void Add ( IfaceA a ) { ... } } class ConcreteB : BaseClassB < IfaceA > { // does not override one of ...
c # Generic overloaded method dispatching ambiguous
C#
This question is about this code : I answered this question yesterday and if you notice in the comments to the question ( not the answer ) , one of the members @ gertarnold said this : entityEntry.Property ( `` InsertedBy '' ) does n't use reflection , it reads the EF metadata . Sure it uses the EF metadata to figure o...
entityEntry.Property ( `` WhateverProperty '' ) .CurrentValue = 1 ;
Does the Entity Framework DbEntityEntry.Property method use reflection ?
C#
I have a Mailchimp RSS campaign that reads an RSS feed on a website and is set to once a day . I would like to send this campaign pro-grammatically after I add an item to the feed.I am using PerceptiveMCAPI and My code for triggering the campaign isThe error I receive looks likeAny ideas on what would be causing this ?
campaignSendNowInput campaignSendNowInput = new campaignSendNowInput ( apiKey , campaignKey ) ; campaignSendNow campaignSendNow = new campaignSendNow ( campaignSendNowInput ) ; campaignSendNowOutput campaignSendNowOutput = campaignSendNow.Execute ( ) ; `` Error Code : 313 , Message : This Campaign has already been sent...
Mailchimp Campaign Send Error - This Campaign has already been sent and can not be sent again
C#
The following code will throw an exception : This seems like strange behavior to me , can someone explain why this is n't a bug ? Or perhaps suggest a workaround ? Instantiating a Regex object in place of the null will of course stop this from throwing an exception.The exception produced is : Newtonsoft.Json.JsonSerial...
class SimpleClassWithRegex { public Regex RegProp { get ; set ; } } [ TestMethod ] public void RegexTest ( ) { string json = JsonConvert.SerializeObject ( new SimpleClassWithRegex { RegProp = null } ) ; // json = { `` RegProp '' : null } SimpleClassWithRegex obj = JsonConvert.DeserializeObject < SimpleClassWithRegex > ...
Deserialize null regex property with json.net
C#
The language I use is C # .Let we have a List of objects of type T , Say that we want to go over each item of collection . That can be done in many ways . Among of them , are the following two : andDoes the second way be better than the first or not and why ? Thanks in advance for your answers .
List < T > collection = new List < T > { ... .. } ; foreach ( var item in collection ) { // code goes here } foreach ( T item in collection ) { // code goes here }
faster way between to ways of iterating through all the elements of a collection in C #
C#
I have this interface that is being used by a handful of concrete types , such as EmailFormatter , TextMessageFormatter etc.The issue I 'm having is that with my EmailNotificationService is that I want to inject EmailFormatter . The constructor signature for this service is public EmailNotificationService ( IFormatter ...
public interface IFormatter < T > { T Format ( CompletedItem completedItem ) ; } container.Register ( Component.For < IFormatter < string > > ( ) .ImplementedBy < EmailFormatter > ( ) ) ;
How to inject proper dependency based on constructor parameter name
C#
I am trying to understand how ASP.NET MVC works and I have been recommended to follow the MVC Music Store Tutorial , however I am having problems since I am using different ( more current ) software.According to this page I should add a List of genres to my action method inside my StoreController.cs . However according...
public ActionResult Index ( ) { var genres = new List < Genre > { new Genre = { Name = `` Disco '' } , new Genre = { Name = `` Jazz '' } , new Genre = { Name = `` Rock '' } } ; return View ( ) ; } public ActionResult Index ( ) { //var genres = new List < Genre > // { // new Genre = { Name = `` Disco '' } , // new Genre...
Is this deprecated way of coding ? ASP.Net MVC
C#
I 've imported Microsoft.VisualStudio.Threading into .Net Core Web App . I did this specifically to make use of AsyncLazy < T > .I wanted to make sure I did this right , so I imported the appropriate Analyzers.The warnings and the documentation clearly state that a JoinableTaskFactory should be injected into my impleme...
public void ConfigureServices ( IServiceCollection services ) { // ... services.AddSingleton ( new JoinableTaskFactory ( ) ) ; // ... }
Do I use a JoinableTaskFactory with AspNetCore ?
C#
So I want to execute PowerShell Calculated Properties ( I hope that 's the correct name ) from C # .My CmdLet in the PS ( Exchange ) Console looks like this : This works just fine , the problem occures when I try to execute it from C # .My Code looks like this : My result then contains the empty ToBeExpandedGuid ( null...
Get-Something -ResultSize unlimited |Select-Object DisplayName , @ { name= '' RenamedColumn ; expression= { $ _.Name } } , ToBeExpanded -Expand ToBeExpanded |Select-Object DisplayNameRenamedColumn , ToBeExpandedGuid List < string > parameters = new List < string > ( ) { `` DisplayName '' , '' @ { { name=\ '' RenamedCol...
Using PowerShell Calculated Properties from C #
C#
I am confused by some code that should n't be working , but oddly enough , is working and I know I 'm simply overlooking something obvious . I 'm looking at the source code for the Accord.NET framework and I downloaded it and its compiling just fine , but I 'm confused about something . In one of the assemblies , calle...
internal static class Indices { // Lots of code // ... // ... } return Accord.Math.Indices.Random ( k , n ) ;
Accessing an internal class from a different Dll file
C#
From the docs for the TakeUntil operator ( emphasis mine ) : The TakeUntil subscribes and begins mirroring the source Observable . It also monitors a second Observable that you provide . If this second Observable emits an item or sends a termination notification , the Observable returned by TakeUntil stops mirroring th...
Observable.Never < Unit > ( ) .TakeUntil ( Observable.Empty < Unit > ( ) ) .Wait ( ) ;
TakeUntil not working as documented ?
C#
I 'm developing a multi-tenant application in ASP.NET Core 2.1 . I 'm utilizing AspNetCore.Identity.EntityFrameworkCore framework for user management . I want to add a unique index combining NormalizedName with TenantId in Role Table . Also , in the user table NormalizedUserName with TenantId in User table . This does ...
modelBuilder.Entity < User > ( ) .HasIndex ( u = > new { u.NormalizedUserName , u.TenantId } ) .HasName ( `` UserNameIndex '' ) .IsUnique ( true ) ; modelBuilder.Entity < Role > ( ) .HasIndex ( u = > new { u.NormalizedName , u.TenantId } ) .HasName ( `` RoleNameIndex '' ) .IsUnique ( true ) ;
Override default indexes in AspNetCore.Identity tables
C#
FsCheck has some neat default Arbitrary types to generate test data . However what if one of my test dates depends on another ? For instance , consider the property of string.Substring ( ) that a resulting substring can never be longer than the input string : Although the implementation of Substring certainly is correc...
[ Fact ] public void SubstringIsNeverLongerThanInputString ( ) { Prop.ForAll ( Arb.Default.NonEmptyString ( ) , Arb.Default.PositiveInt ( ) , ( input , length ) = > input.Get.Substring ( 0 , length.Get ) .Length < = input.Get.Length ) .QuickCheckThrowOnFailure ( ) ; } var inputs = Arb.Default.NonEmptyString ( ) ; // I ...
FsCheck : How to generate test data that depends on other test data ?
C#
I am trying to insert millisecond into data type of datetime ( 6 ) in MySQL using c # .here is my code : the createtiming is created withI have read the value of createtiming before it inserts into MySQL , and it does contain milliseconds , however , when I do on MySQL , I only see time like While the time should be li...
MySqlCommand myCommand4 = new MySqlCommand ( `` Insert into Test_OrderRecord values ( ' '' + OrderID + `` ' , ' '' + customerCode + `` ' , ' '' + customer + `` ' , ' '' + TelComboBox.Text + `` ' , ' '' + LicenseComboBox.Text + `` ' , ' '' + DriverComboBox.Text + `` ' , ' '' + AddressComboBox.Text + `` ' , ' '' + Locati...
inserting millisecond into mysql from c #
C#
I would expect `` 2- '' and `` 22 '' to always compare the same way , but changing the 3rd character changes the sort order . What on earth is happening here ? Our culture is en-US by the way .
string.Compare ( `` 2-1 '' , '' 22- '' , StringComparison.CurrentCulture ) //-1string.Compare ( `` 2-2 '' , '' 22- '' , StringComparison.CurrentCulture ) //1
Character after hyphen affects string.compare
C#
I am using Visual Studio and I am very confused about the best way to store configuration strings . I am creating a Windows Forms Application . I need very basic security -- I do n't want the password to be readable in app.config but I am not concerned about someone disassembling my code in order to figure it out . So ...
public string MyConnectionString { get { return ( ( string ) ( `` Data Source=SQLSERVER\\ACCOUNTING ; Initial Catalog=ACCOUNTING ; User ID=MyUser ; Password=28947239SKJFKJF '' ) ) ; } }
Proper Storage of Configuration Strings
C#
ProblemProblem shapingImage sequence position and size are fixed and known beforehand ( it 's not scaled ) . It will be quite short , maximum of 20 frames and in a closed loop . I want to verify ( event driven by button click ) , that I have seen it before . Lets say I have some image sequence , like : http : //img514....
getKernel [ L_ ] : = Transpose [ { L } ] . { L } / ( Total [ Total [ Transpose [ { L } ] . { L } ] ] ) getVKernel [ L_ ] : = L/Total [ L ] { 1d/4 , 1d/2 , 1d/4 } { 1d/16 , 1d/4 , 3d/8 , 1d/4 , 1d/16 } { 1d/64 , 3d/32 , 15d/64 , 5d/16 , 15d/64 , 3d/32 , 1d/64 } private Bitmap getContentBitmap ( ) { Rectangle r = f.r ; B...
Verify image sequence
C#
I been scratching my head trying to figure out why a project I have ( what I did not touch ) was not working anymore.Basically I was trying trying to get some data back from google contacts . When I selected `` allow '' in the oAuth part it would keep giving me a 404 error . This is all done in the windows phone 7 emul...
string clientId = `` You client id here '' ; public MainPage ( ) { InitializeComponent ( ) ; string url = String.Format ( `` https : //accounts.google.com/o/oauth2/auth ? scope=https : //www.google.com/m8/feeds & redirect_uri=http : //localhost & response_type=code & approval_prompt=auto & client_id= { 0 } '' , clientI...
Google Api Redirect gives me 404 error on WP7 When using Windows 8 but not Windows 7
C#
I am currently writing a resource manager for my game . This is basically a class that will handle all kinds of other objects of different types , and each object is referred to by name ( a System.String ) . Now this is my current implementation , but since I am using a dictionary of objects I will still need to cast e...
public static class ResourceManager { public static Dictionary < string , object > Resources { get ; private set ; } public static void LoadResources ( ) { Resources = new Dictionary < string , object > ( ) ; //Sample resource loading code Resources.Add ( `` number '' , 3 ) ; Resources.Add ( `` string '' , `` bleh '' )...
Dictionary using generics
C#
The below code works fine : Whereas the below code wo n't compile : In the second example the compiler says that i am trying to set a property on a variable that has not been instantiated . In either case lstMyControl must be instantiated , but the compilr ca n't seem to follow that code paths through the switch statem...
ListControl lstMyControl ; if ( SomeVariable == SomeEnum.Value1 ) { lstMyControl = new DropDownList ( ) ; } else { lstMyControl = new RadioButtonList ( ) ; } lstMyControl.CssClass = `` SomeClass '' ; ListControl lstMyControl ; switch ( SomeVariable ) { case SomeEnum.Value1 : lstMyControl = new DropDownList ( ) ; break ...
Why ca n't C # compiler follow all code paths through a switch statement
C#
Is there a way to do what classmethod does in Python in C # ? That is , a static function that would get a Type object as an ( implicit ) parameter according to whichever subclass it 's used from.An example of what I want , approximately , isthe expected output being ( same code on codepad here . )
class Base : @ classmethod def get ( cls , id ) : print `` Would instantiate a new % r with ID % d . `` % ( cls , id ) class Puppy ( Base ) : passclass Kitten ( Base ) : passp = Puppy.get ( 1 ) k = Kitten.get ( 1 ) Would instantiate a new < class __main__.Puppy at 0x403533ec > with ID 1.Would instantiate a new < class ...
Python-style classmethod for C # ?
C#
I want to calculate the mean absolute deviation and I 'm currently using the following class from Stack Overflow ( link here ) , posted by Alex : The person who made that class , did it somehow weirdly and I do n't understand the calculations , because he 's using different formulas . For example , people normally calc...
public class MovingAverageCalculator { private readonly int _period ; private readonly double [ ] _window ; private int _numAdded ; private double _varianceSum ; public MovingAverageCalculator ( int period ) { _period = period ; _window = new double [ period ] ; } public double Average { get ; private set ; } public do...
Calculating mean absolute deviation
C#
While trying to organize some data access code using EF Core I noticed that the generated queries were worse than before , they now queried columns that were not needed . The basic query is just selecting from one table and mapping a subset of columns to a DTO . But after rewriting it now all columns are fetched , not ...
ctx.Items.ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' , i . `` Property2 '' , i . `` Property3 '' FROM `` Items '' AS ictx.Items.Select ( x = > new { Id = x.Id , Property1 = x.Property1 } ) .ToList ( ) ; // SELECT i . `` Id '' , i . `` Property1 '' FROM `` Items '' AS ictx.Items.Select ( x = > new Minimal...
EF Core queries all columns in SQL when mapping to object in Select
C#
Probably a silly question , since I may have already answered my question , but I just want to be sure that I 'm not missing something Constant expressions are evaluated at compile time within checked context . I thought the following expression should n't be evaluated at compile time , since I assumed C # considers a ...
int i= 100 ; long u = ( int.MaxValue + 100 + i ) ; //error int i=100 ; long l = int.MaxValue + i + ( 200 + 100 ) ; // works
It appears some parts of an expression may be evaluated at compile-time , while other parts at run-time
C#
Transparent images are pure evil in Windows Forms , that why I 've created a custom control class to handle them . The designer does n't show my control when it 's empty . I would like to add a subtle border , but only in the design view ( and when no border is added by the user ) . How would I do this ? My class is :
class TransparentImage : Control { public Image Image { get ; set ; } protected Graphics graphics ; public string FilePath { get ; set ; } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ExStyle |= 0x00000020 ; //WS_EX_TRANSPARENT return cp ; } } protected override void OnP...
How to add a border to a custom control in the design view ?
C#
This is not a question about how to change the font size . Rather , why is the size of my font changing by itself as I type ( or paste ) when it 's inside a plain TextBox control which , as you should know , only supports one color , one font , and one font size at any given time.My code : The font is set at 8pt . If I...
using ( FontDialog d = new FontDialog ( ) ) { // The usual properties ... if ( d.ShowDialog ( ) == DialogResult.OK ) { textbox1.Font = d.Font ; } }
Why do multiple font sizes display inside Plain TextBox ?
C#
I would like to create list of data in list of data . I believe this can be difficult to explain but I will try explain my problem very clear . I created list of data but in this list some arguments are also list of data . I have to write using this code because this are restriction ( Our Factory ) . If I take data , w...
DestynationName = ( List < dictionaryNewInfoSupportList > x.DictImportantInformationSDestination.Select ( n= > new DictionaryNewInfoSupportList { Id = n.Destination.Id , Name = n.Destination.Desciption } ) .ToList ( ) ; public Ilist < dictionaryNewInfoSupportList > DestynationName ; class dictionaryNewInfoSupportList {...
List in list ( Model ) Factory