lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I am trying to build an ASP.NET Core docker image with following Dockerfile : The build fails , and it gives the following error : /app/MyPCL/MyPCL.csproj ( 70,3 ) : error MSB4019 : The imported project `` /usr/share/dotnet/sdk/1.0.1/Microsoft/Portable/v4.5/Microsoft.Portable.CSharp.targets '' was not found . Confirm t...
FROM microsoft/aspnetcore-build:1.1.1WORKDIR /appCOPY src .RUN dotnet restoreRUN dotnet publish -- output /out/ -- configuration ReleaseEXPOSE 5000ENTRYPOINT [ `` dotnet '' , '' /out/MyWebApp.dll '' ] < Import Project= '' $ ( MSBuildExtensionsPath32 ) \Microsoft\Portable\ $ ( TargetFrameworkVersion ) \Microsoft.Portabl...
Ca n't build ASP.NET Core app that references PCL in docker
C#
I 'm trying to zip and unzip data in memory ( so , I can not use FileSystem ) , and in my sample below when the data is unzipped it has a kind of padding ( '\0 ' chars ) at the end of my original data . What am I doing wrong ?
[ Test ] public void Zip_and_Unzip_from_memory_buffer ( ) { byte [ ] originalData = Encoding.UTF8.GetBytes ( `` My string '' ) ; byte [ ] zipped ; using ( MemoryStream stream = new MemoryStream ( ) ) { using ( ZipFile zip = new ZipFile ( ) ) { //zip.CompressionMethod = CompressionMethod.BZip2 ; //zip.CompressionLevel =...
Unzipped data being padded with '\0 ' when using DotNetZip and MemoryStream
C#
Just wondering if this is considered a clear use of goto in C # : I feel like this is ok , because the snippet is small and should make sense . Is there another way people usually recover from errors like this when you want to retry the operation after handling the exception ? Edit : That was fast . To answer a few que...
IDatabase database = null ; LoadDatabase : try { database = databaseLoader.LoadDatabase ( ) ; } catch ( DatabaseLoaderException e ) { var connector = _userInteractor.GetDatabaseConnector ( ) ; if ( connector == null ) throw new ConfigException ( `` Could not load the database specified in your config file . `` ) ; data...
Is this a clear use of goto ?
C#
I have an entity collection of Readings.Each Reading is linked to an entity called Meter . ( And each Meter holds multiple readings ) .each Reading holds a field for meter id ( int ) and a field for time.Here is some simplified code to demonstrate it : Given a specific period and list of meterids , what would be the mo...
public class Reading { int Id ; int meterId ; DateTime time ; } public class Meter { int id ; ICollection < Readings > readings ; }
Efficient LINQ to Entities query
C#
I 'm having trouble understanding how to render a collection as a drop down list.If I have a model like : I would like the string collection to render as a drop down list . Using the html page helper InputFor does n't seem to work . It simply render 's a text box . I 've noticed that InputFor can reflect on the propert...
public class AccountViewModel { public string [ ] Country { get ; set ; } }
fubumvc - rendering a collection as a drop down list
C#
I 'm using EntityFramework ( EF V6 ) with Asp.Net for creating one website , In that I 've Created the .edmx and .tt and DBContext.I 'm trying to create an objects for each table to summoner it later with aspxI do n't know if I 'm writing my LINQ Queries in the right way ! , that 's why I need your help on this.The Tab...
public class LINQSubjects { NewsPaperEntities ctx = new NewsPaperEntities ( ) ; // Get Subject public Subject GetSubject ( int SubjectID ) { Subject sub = ctx.Subjects.FirstOrDefault ( s= > s.Subject_ID==SubjectID ) ; return sub ; } // Get All Subject Info public List < Subject > GetAllSubjects ( ) { List < Subject > s...
How to write LINQ Queries for CRUD using Entity Framework ?
C#
I 've started using Swashbuckle with Web API . None of my types are getting rendered correctly in my Swagger UI . On every method , I see something like this ( unrendered ) : So I investigated , and found this in my Swagger definitions file for many of my methods : typeName exists in the definitions listing ... but its...
< span class= '' strong '' > Typename is not defined ! < /span > { $ ref : `` # /definitions/Typename '' , vendorExtensions : { } } [ assembly : WebActivatorEx.PreApplicationStartMethod ( typeof ( SwaggerConfig ) , `` Register '' ) ] public class SwaggerConfig { public static void Register ( ) { var thisAssembly = type...
Can not find type name in schema definitions
C#
I have a constant flow of certain items that I need to process in parallel so I 'm using TPL Dataflow . The catch is that the items that share the same key ( similar to a Dictionary ) should be processed in a FIFO order and not be parallel to each other ( they can be parallel to other items with different values ) .The...
_actionBlocks = new ActionBlock < Item > [ Environment.ProcessorCount ] ; for ( int i = 0 ; i < _actionBlocks.Length ; i++ ) { _actionBlocks [ i ] = new ActionBlock < Item > ( _ = > ProcessItemAsync ( _ ) ) ; } bool ProcessItem ( Key key , Item item ) { var actionBlock = _actionBlocks [ ( uint ) key.GetHashCode ( ) % _...
Hashed/Sharded ActionBlocks
C#
I created a simple WPF application for enable and disable the aero shake behavior . My code is like this : Why my code does not function ? What this application do now : When I shake my window , the others windows are minimized.What I want to do : When I shake my window , or I shake any window , no window should be min...
using System.Windows ; using System.Runtime.InteropServices ; namespace TestDisableShaking { public partial class MainWindow : Window { const uint DWM_EC_DISABLECOMPOSITION = 0 ; const uint DWM_EC_ENABLECOMPOSITION = 1 ; [ DllImport ( `` dwmapi.dll '' , EntryPoint = `` DwmEnableComposition '' ) ] extern static uint Dwm...
How to disable the aero shake for whole system ?
C#
Situation : Say we are executing a LINQ query that joins two in-memory lists ( so no DbSets or SQL-query generation involved ) and this query also has a where clause . This where only filters on properties included in the original set ( the from part of the query ) . Question : Does the linq query interpreter optimize ...
from category in categoriesjoin prod in products on category.ID equals prod.CategoryIDwhere category.ID == 1 // < -- -- -- below joinselect new { Category = category.Name , Product = prod.Name } ; from category in categorieswhere category.ID == 1 // < -- -- -- above joinjoin prod in products on category.ID equals prod....
Does `` where '' position in LINQ query matter when joining in-memory ?
C#
I am getting the error in my log . I spent most of my day finding the solution but could not find the one which meets my requirement.Here is the log errorseverity= [ ERROR ] , ipaddress=xxxx , subprocess=Microsoft.AspNetCore.Antiforgery.Internal.DefaultAntiforgery , description=An exception was thrown while deserializi...
`` Certificates '' : { `` StoreName '' : `` My '' , `` StoreLocation '' : `` LocalMachine '' `` SerialNumber '' : `` xxxxxxxxxxxx '' } , private X509Certificate2 LCertificate ( ) { var storeName = Configuration [ `` Certificates : StoreName '' ] ; var storeLocation = Configuration [ `` Certificates : StoreLocation '' ]...
An exception was thrown while deserializing the token.The antiforgery token could not be decrypted in .Net Core 2.2 application
C#
Consider the following , at first glance absurd , pattern match : Both is will return false . However if we use var the behavior changes completely : If you hover over var in VS2017 , the type is string but the behavior of is is completely different . The compiler is doing something radically different even though the ...
string s = null ; if ( s is string ss ) //falseif ( s is string ) //false string s = null ; if ( s is var ss ) //true ! ? !
Different behavior in pattern matching when using var or explicit type
C#
I have some working code that retrieves data from data base . It is interesting for me to get some better code for my solution . Are there some ways to combine two queries into one or something like this ? Same code with C # ( hope no syntax errors occurred ) : SCustomerInfo represented by folowing Structure ( code is ...
Dim customerTitlesAndIDs = contex.CustomerTable.Select ( Function ( row ) New With { .ID = row.ID , .CustomerTitle = row.Title } ) .ToList ( ) Dim cutomerIdPayment = contex.CustomerPayments.Select ( Function ( table ) New With { .ID = table.CustomerID , .Range = table.PaymentsRange , .Values = table.Values } ) .ToList ...
How merge two sequences into one ?
C#
Say , I have an array of lists , and I want to get a count of all of the items in all of the lists . How would I calculate the count with LINQ ? ( just general curiosity here ) Here 's the old way to do it : How would you LINQify that ? ( c # syntax , please )
List < item > [ ] Lists = // ( init the array of lists ) int count = 0 ; foreach ( List < item > list in Lists ) count+= list.Count ; return count ;
What 's the LINQ'ish way to do this
C#
With the new readonly instance member features in C # 8 , I try to minify unnecessary copying of struct instances in my code.I do have some foreach iterations over arrays of structs , and according to this answer , it means that every element is copied when iterating over the array.I thought I can simply modify my code...
// Example struct , real structs may be even bigger than 32 bytes.struct Color { public int R ; public int G ; public int B ; public int A ; } class Program { static void Main ( ) { Color [ ] colors = new Color [ 128 ] ; foreach ( ref readonly Color color in ref colors ) // note 'ref readonly ' placed here Debug.WriteL...
Can I foreach over an array of structs without copying the elements in C # 8 ?
C#
When working with Domain Objects , how do you typically unit test a method that calls another method in the object ? For example : Unit testing GetTotalAmt ( ) is easy , but with GetExtendedTotalAmt ( ) I 'd have to use stub/mock InvoiceLine objects to make it work , when all I really want to do is test that a discount...
public class Invoice { public IList < InvoiceLine > InvoiceLines ; public string Company ; public bool IsDiscounted ; public DateTime InvoiceDate ; // ... public GetTotalAmt ( ) ; public GetExtendedTotalAmt ( ) ; public decimal GetTotalAmt ( ) { decimal total ; foreach ( InvoiceLine il in InvoiceLines ) { total += il.Q...
How to test methods that call other methods in a domain object
C#
I 've been writing things like this in my implementations : However , I do n't know exactly what 's happening here ... Maybe everything was `` copied '' to the delegate . Or maybe , like reference types , all value types will have a copy associated to the Task delegate until it exists ? I 'm just trying to understand w...
public void SomeMethod ( int someValue , List < int > someValues ) { Task generatedTask = null ; { int anotherValue = 2 ; object valuesRef = someValues ; generatedTask = new Task ( delegate { anotherValue += someValue + GetSum ( valuesRef ) ; Console.WriteLine ( anotherValue ) ; } ) ; } generatedTask.Start ( ) ; }
How local variables are handled when referenced in another scope ?
C#
Possible Duplicate : What is the C # Using block and why should I use it ? My question : Is using using ( a ) { do something with a } better than declaring ' a ' and using it that way . ie : more secure , faster , ... see examples for clarification.Example 1 : ( without using ) Example 2 : ( with using )
StreamWriter sw ; string line ; sw = new StreamWriter ( `` D : \\NewCon.xml '' ) ; sw.WriteLine ( `` < ? xml version=\ '' 1.0\ '' encoding=\ '' UTF-8\ '' standalone=\ '' no\ '' ? > '' ) ; sw.WriteLine ( `` < config > '' ) ; for ( int i = 0 ; i > =36 ; i++ ) { line = `` '' ; line = `` < `` + xmlnodes [ i ] + `` > '' ; l...
Is using using Better ?
C#
I 'm using an API call to return some XML data from a web server . The XML data is in the following format : I can retrieve the raw XML data successfully , and I want to add the < quoteText > and < quoteAuthor > node values to strings but seem to be unable to do this . My current code : My program bombs out with An unh...
< forismatic > < quote > < quoteText > The time you think you 're missing , misses you too. < /quoteText > < quoteAuthor > Ymber Delecto < /quoteAuthor > < senderName > < /senderName > < senderLink > < /senderLink > < quoteLink > http : //forismatic.com/en/55ed9a13c0/ < /quoteLink > < /quote > < /forismatic > private v...
C # - Setting XML Node values as Stings from StreamReader result
C#
Can I simplify this statement with a lambda expression ?
var project = from a in accounts from ap in a.AccountProjects where ap.AccountProjectID == accountProjectId select ap ;
Lambda Expression
C#
Some programmers argue that it is better to pass IEnumerable < T > parameters over passing implementations like List < T > , and one of the popular reasons to do this is that the API is immediately usable in more scenarios because more collections will be compatible with IEnumerable < T > than any other specific implem...
static void LookAtCollection ( IEnumerable < int > collection ) { foreach ( int Value in collection.ToArray ( ) /* take a snapshot by converting to an array */ ) { Thread.Sleep ( ITEM_DELAY_MS ) ; } } static void LookAtCollection ( int [ ] collection ) { foreach ( int Value in collection ) { Thread.Sleep ( ITEM_DELAY_M...
Is T [ ] not better than IEnumerable < T > as parameter type ? ( Considering threading challenges )
C#
I added 3 optional boolean parameters to a method found within a VB6 DLL . The class that houses it is MultiUse ( public ) , and the method itself is Private . The class implements a specific interface from a TLB , allowing for public calls to this method.After adding the 3 optional parameters on the VB6 side , I modif...
HRESULT MyMethod ( //Cut out the other parameters - they are working fine . [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMyFirstOptionalBoolean , [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMySecondOptionalBoolean , [ in , optional , defaultvalue ( -1 ) ] VARIANT_BOOL blnMyThirdOptionalBoolean , ...
Is it possible that C # has problems calling VB6 methods that have optional parameters ?
C#
I have a class that holds on to a delegate , in order to lazily evaluate something later.Once I 've evaluated it , by calling the delegate , I clear out the reference to the delegate , hoping that it would be eligible for collection . After all , it might hold on to a world of local variables if it was constructed as a...
void Main ( ) { WeakReference wr ; Lazy < int > l ; CreateTestData ( out wr , out l ) ; wr.IsAlive.Dump ( ) ; // should be alive here GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; wr.IsAlive.Dump ( ) ; // and alive here as well l.Value.Dump ( ) ; // but now we clear the reference GC.Collect ( ) ; ...
GC of delegates , what am I missing ? ( my delegate is not collected )
C#
It 's not unusual to want a limit on the interval between certain events , and take action if the limit is exceeded . For example , a heartbeat message between network peers for detecting that the other end is alive.In the C # async/await style , it is possible to implement that by replacing the timeout task each time ...
var client = new TcpClient { ... } ; await client.ConnectAsync ( ... ) ; Task heartbeatLost = new Task.Delay ( HEARTBEAT_LOST_THRESHOLD ) ; while ( ... ) { Task < int > readTask = client.ReadAsync ( buffer , 0 , buffer.Length ) ; Task first = await Task.WhenAny ( heartbeatLost , readTask ) ; if ( first == readTask ) { ...
Task-based idle detection
C#
I have a solution of three projects : CoreOutlook Add-InASP.NET WebsiteBoth , the Outlook Add-In and the Website use the same methods from Core project to get data from SQL Server . When I write my data into database , I convert all DateTime values of two tables into UTC time : andWhen I get the data in my Outlook Add-...
POLL_START POLL_END2013-07-31 12:00:00.000 2013-08-01 12:00:00.000 PICK_DATE2013-07-31 12:00:48.0002013-07-31 13:00:12.000 private static void ConvertToLocalTime ( POLL item ) { item.POLL_START = item.POLL_START.FromUTC ( ) ; item.POLL_END = item.POLL_END.FromUTC ( ) ; } private static void ConvertToLocalTime ( PICK pi...
Converting UTC to local time returns strange result
C#
How to intentionally crash an application with an AccessViolationException in c # ? I have a console application that use an unmanaged DLL that eventually crashes because of access violation exceptions . Because of that , I need to intentionally throw an AccessViolationException to test how it behaves under certain cir...
public static void Crash ( ) { throw new AccessViolationException ( ) ; } public static unsafe void Crash ( ) { for ( int i = 1 ; true ; i++ ) { var ptr = ( int* ) i ; int value = *ptr ; } }
How to make C # application crash with an AccessViolationException
C#
I am working with two C # stream APIs , one of which is a data source and the other of which is a data sink.Neither API actually exposes a stream object ; both expect you to pass a stream into them and they handle writing/reading from the stream.Is there a way to link these APIs together such that the output of the sou...
using ( var buffer = new MemoryStream ( ) ) using ( var transferUtil = new TransferUtility ( s3client ) ) { // This destructor finishes the file and transferUtil closes // the stream , so we need this weird using nesting to keep everyone happy . using ( var parquetWriter = new ParquetWriter ( schema , buffer ) ) using ...
How to link two C # APIs that expect you to provide a stream ?
C#
I have 1 line with 2 known points : I 'd like to iterate through 10 pixels to the left ( or right ) to 1 line ( at x1 , y1 ) .The red dots are the ones that I 'd like process . Example : How do I iterate through these coords ?
PointF p2_1 = new PointF ( ) ; p2_1.X = 100 ; // x1p2_1.Y = 150 ; // y1PointF p2_2 = new PointF ( ) ; p2_2.X = 800 ; // x2p2_2.Y = 500 ; // y2float dx = p2_2.X - p2_1.X ; float dy = p2_2.Y- p2_1.Y ; float slope = dy / dx ; // slope mfloat intercept = p2_1.Y - slope * p2_1.X ; // intercept c // y = mx + c for ( int i = ...
Iterate through N points that are perpendicular to another line
C#
I have a method that I want to be `` transactional '' in the abstract sense . It calls two methods that happen to do stuff with the database , but this method does n't know that.Because in real terms the TransactionScope means that a database transaction will be used , we have an issue where it could well be promoted t...
public void DoOperation ( ) { using ( var tx = new TransactionScope ( ) ) { Method1 ( ) ; Method2 ( ) ; tc.Complete ( ) ; } } public void Method1 ( ) { using ( var connection = new DbConnectionScope ( ) ) { // Write some data here } } public void Method2 ( ) { using ( var connection = new DbConnectionScope ( ) ) { // U...
Method knows too much about methods it 's calling
C#
I have been asked at interview ( C # 3.0 ) to provide a logic to remove a list of items from a list.I responded1 ) The interviewer replied that the algorithm i had employed will gradually take time if the items grow and asked me to give even better and faster one.What would be the efficient algorithm ? 2 ) How can i ac...
int [ ] items= { 1,2,3,4 } ; List < int > newList = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 , 56 , 788 , 9 } ; newList.RemoveAll ( ( int i ) = > { return items.Contains ( i ) ; } ) ;
C # Improved algorithm
C#
I 'm working with some generics in C # . I have an abstract generic class : and the type parameter is specified when other classes inherit from the base class.I 'm also trying to write some code for another abstract class that needs to store one of these base classes , but it wo n't know the parameter of the base class...
public abstract class BaseClass < T > where T : Foo { } protected BaseClass < ? > myBaseClass ; protected BaseClass < Foo > myBaseClass ;
C # Equivalent of Java 's GenericType < ? >
C#
I 've just installed the .NET 4.5 reference source from Microsoft as I 'm trying to debug an issue I 'm seeing and I stumbled across the following in HttpApplication.cs.Notice the next-to-last line private bool _ [ ... . ] ; // per call.Is _ [ ... . ] a valid identifier ( at any level of compilation , including IL ) or...
// execution step -- call asynchronous eventinternal class AsyncEventExecutionStep : IExecutionStep { private HttpApplication _application ; private BeginEventHandler _beginHandler ; private EndEventHandler _endHandler ; private Object _state ; private AsyncCallback _completionCallback ; private AsyncStepCompletionInfo...
Is ` _ [ ... . ] ` a valid identifier ?
C#
I am planning to use Auto reset Event Handle for Inter Thread communication.My producer thread code look like below In the consumer thread , I have to download data for every one minute or when producer is called Set methodMy question is if consumer thread is running doSomething function and producer calls set function...
EventWaitHandle handle = new EventWaitHandle ( false , EventResetMode.AutoReset ) ; produceSomething ( ) ; handle.Set ( ) ; try { while ( true ) { handle.WaitOne ( 60000 , false ) ; doSomething ( ) ; // Downloads data from Internet . // Takes lot of time to complete it . } } catch ( ThreadAbortException ) { cleanup ( )...
.NET Thread Synchronization
C#
If I look at the IL that is created in Linqpad for the two following code snippets , I wonder what happens here.In c # results in the following IL codewhereas in VBit isApparently , the c # compiler understands the the value is never used and thus simply returns nothing . In VB.NET the actual code is translated.Is that...
int i = 42 ; IL_0000 : ret Dim i As Integer = 42 IL_0000 : ldc.i4.s 2A IL_0002 : stloc.0
Is the c # compiler smarter than the VB.NET compiler ?
C#
I am beginner with programming in c # and i am just doing a pingpong game . I am using threads - one for collision , one for move , one for painting.My question is why the program run faster , when i open steam : D to me it seems like a nonsense.Witch slower i mean - ball is slower and the pads too . It looks like the ...
public void move ( ) { DelegateSetScore d = new DelegateSetScore ( SetScore ) ; while ( ! isDisposing ) { pad1.Y = pad1.Y + 4 * pad1Down + 4 * pad1Up ; if ( pad1.Y < 0 ) { pad1.Y = 0 ; } if ( pad1.Y + pad1.Height > HEIGHT ) { pad1.Y = HEIGHT - pad1.Height ; } pad2.Y = pad2.Y + 4 * pad2Down + 4 * pad2Up ; if ( pad2.Y < ...
pingpong game run faster when i open STEAM - why ?
C#
I have the following code : The following statements works fine and the program compile despite i did n't implement the interface : So my first question is : Why did it work ? Then , i add the following interface implementation to Calculator class : When trying again the following statement : The method overriden from ...
interface ICalculator { int Sum ( int x , int y ) ; } abstract class AbsCalculator { public abstract int Sum ( int x , int y ) ; } class Calculator : AbsCalculator , ICalculator { public override int Sum ( int x , int y ) { Console.WriteLine ( `` From overriden method '' ) ; return x + y ; } } Calculator calculator = n...
Code work despite the interface is not implemented
C#
I tried the following code to enable some kind of not null checking for retrieved entities to ensure they are exist before doing some concrete business : But in compile time I 'm getting : After contract block , found use of local variable 'obj ' defined in contract blockAm I using Contract.Requires in the wrong way ?
protected T GetRequired < T > ( object id ) where T : EntityObject { var obj = Get < T > ( id ) ; Contract.Requires < ArgumentNullException > ( obj ! = null ) ; return obj ; }
CodeContracts `` Required '' understanding
C#
I 'm reading a book about C # for beginners and I 'm at the part `` Understanding Values and References '' , but there is something I do n't understand . What I 'm seeing is that the books tries to explain this to me ( and I 've seen this happening in a couple of tutorial video 's on Youtube as well ) that the class is...
Circle c = new Circle ( 42 ) ; Circle copy = new Circle ( 99 ) ; //Circle refc = c ; ... copy = c ;
Point of initializing a class ?
C#
I have created a custom Attribute to decorate a number of classes that I want to query for at runtime : Each of these classes derive from an abstract base class : Do I need to put this attribute on each derived class , even if I add it to the base class ? The attribute is marked as inheritable , but when I do the query...
[ AttributeUsage ( AttributeTargets.Class , AllowMultiple=false , Inherited=true ) ] public class ExampleAttribute : Attribute { public ExampleAttribute ( string name ) { this.Name = name ; } public string Name { get ; private set ; } } [ Example ( `` BaseExample '' ) ] public abstract class ExampleContentControl : Use...
Attribute Inheritance and Reflection
C#
What does a syntax like this mean in C # ?
public abstract class HostFactory < TApp > : ServiceHostFactory where TApp : IFoo
What does a syntax like this mean in C # ?
C#
I am facing some problems using GalaSoft 's RelayCommand.I have a NextCommand property that works , but only several times.Afterwards , it stops working completely . You can try this out with the sample project : http : //s000.tinyupload.com/ ? file_id=65828891881629261404The behaviour is as follows : NextCommand : pop...
// Items Collectionpublic class ItemCollection : ViewModelBase { // List of Items private readonly ObservableCollection < Item > _items = new ObservableCollection < Item > ( ) ; public ObservableCollection < Item > Items { get { return _items ; } } // Constructor public ItemCollection ( ) { BackCommand = new RelayComma...
RelayCommand stops working after a while
C#
I am developing a portable class library in C # and I want to bit convert a double to a long . The most straightforward solution to this issue would be to use the BitConverter.DoubleToInt64Bits method , but unfortunately this method is not available in the Portable Library subset of the .NET class library.As an alterna...
var result = BitConverter.ToInt64 ( BitConverter.GetBytes ( x ) , 0 ) ;
.NET Portable library missing BitConverter.DoubleToInt64Bits , replacement very slow
C#
I am using the Roslyn feature of generating version number from current date/time.I can see the auto generated date/time based version number gets stamped correctly as AssemblyVersion , and I can read it at runtime using API . Question : How do I get the same auto generated date time based version number stamped as fil...
< Project Sdk= '' Microsoft.NET.Sdk.WindowsDesktop '' > < PropertyGroup > < OutputType > WinExe < /OutputType > < TargetFramework > netcoreapp3.1 < /TargetFramework > < UseWindowsForms > true < /UseWindowsForms > < AssemblyVersion > 1.0 . * < /AssemblyVersion > < FileVersion > 1.0 . * < /FileVersion > < Deterministic >...
How do I get AssemblyVersion stamped as FileVersion on the binary
C#
Let 's say I have 3 DLLs ( BlueCar , RedCar , YellowCar ) that each have a named class ( BlueCarClass , etc ) that also all implement the same interface , Car , and are all built from the same namespace ( Car_Choices ) . So a DLL looks something like this before compiled : And the DLL 's name would be `` BlueCar.dll ''...
namespace Car_Choices { public interface Car { void What_Color ( ) ; } public class BlueCarClass : Car { public void What_Color ( ) { MessageBox.Show ( 'The color is blue . ' ) ; } } } static void Main ( ) { string car_choice = win_form_list.ToArray ( ) [ 0 ] ; //gets choice from a drop down Assembly car_assembly = Ass...
How to dynamically load a DLL and use a class in it ( that implements a known interface ) [ C # ]
C#
I have the following entitiesWhat I 'm trying to do is to get Active Auctions with Auctions loaded and Auction also have Departments loadedI know that I should write Include for every object to be loaded so the generated SQL by EF will have join statement to select there object for mebut this is the existing code I do ...
//Active Auction Entitypublic class ActiveAuction { public int Id { get ; set ; } public string Title { get ; set ; } public int ? FirstAuctionId { get ; set ; } public int ? SecondAuctionId { get ; set ; } public int ? ThirdAuctionId { get ; set ; } public virtual Auction FirstAuction { get ; set ; } public virtual Au...
Entity-Framework Join Explanation
C#
I have this code which gets the value from the Test class and then converts it to the type it is . It prints correctly as `` Int32 '' but when I test the equality with another variable with the same value , it prints `` false '' . I suspect it is because it is testing reference equality and that the 2 variables are rea...
class Test { public int y ; } static void Main ( ) { var test1 = new Test { y=1 } ; var test2 = new Test { y=1 } ; var fields = test1.GetType ( ) .GetFields ( ) ; var test1Value = fields [ 0 ] .GetValue ( test1 ) ; var test2Value = fields [ 0 ] .GetValue ( test2 ) ; var test1Converted = Convert.ChangeType ( test1Value ...
How can I compare value-types acquired from Reflection 's `` GetValue '' ?
C#
I need to implement SO like functionality on my asp.net MVC site.For example when user go to https : //stackoverflow.com/questions/xxxxxxxxafter loading the subject line is concatenated with the url and url becomes like this https : //stackoverflow.com/questions/xxxxxxxx/rails-sql-search-through-has-one-relationship Ab...
routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // URL with parameters new { controller = `` Account '' , action = `` LogOn '' , id = UrlParameter.Optional } // Parameter defaults ) ;
how to implement url rewriting similar to SO
C#
From what I understand , records are actually classes that implement their own equality check in a way that your object is value-driven and not reference driven.In short , for the record Foo that is implemented like so : var foo = new Foo { Value = `` foo '' } and var bar = new Foo { Value = `` foo '' } , the foo == ba...
public sealed record SimpleVo : IEquatable < SimpleVo > { public bool Equals ( SimpleVo other ) = > throw new System.NotImplementedException ( ) ; public override bool Equals ( object obj ) = > obj is SimpleVo other & & Equals ( other ) ; public override int GetHashCode ( ) = > throw new System.NotImplementedException ...
Custom Equality check for C # 9 records
C#
I tried to use C # DI method to implement something . following is my code snippet.and code that creates a ServiceLocator : now , I create a test code with but , it looks like , I always get null returned by GetService ( ) function . Instead I expect to get EmailService object via GetService ( ) function , so how to do...
public interface IMessageService { void Send ( string uid , string password ) ; } public class MessageService : IMessageService { public void Send ( string uid , string password ) { } } public class EmailService : IMessageService { public void Send ( string uid , string password ) { } } public static class ServiceLocat...
Regarding to Type in C #
C#
As stated here , the PropertyChangedEventManager class Provides a WeakEventManager implementation so that you can use the `` weak event listener '' pattern to attach listeners for the PropertyChanged event.There are two ways to subscribe for property changes : They both end up calling the same method : with either list...
void AddHandler ( INotifyPropertyChanged source , EventHandler < PropertyChangedEventArgs > handler , string propertyName ) void AddListener ( INotifyPropertyChanged source , IWeakEventListener listener , string propertyName ) private void AddListener ( INotifyPropertyChanged source , string propertyName , IWeakEventLi...
PropertyChangedEventManager : AddHandler vs AddListener
C#
When I have a IEnumerable < SomeClass > from which I do n't know wheter its a list or not ( in terms of List < T > ) , and I have to enumerate that IEnumerable to make sure that I dont enumerate that enumerable twice ( such as looping over it twice , or something like that ) .Resharper warns me about possible multiple ...
var enumeratedItems = items as IList < SomeClass > ? ? items.ToList ( ) ;
Is casting to IList and then calling ToList ( ) when null better than plain ToList ( ) ?
C#
I 'm writing a WinForms app in C # . I need to ensure no two Datarows in my Datatable are more than 100 km apart . Each row has a UTM Zone , Easting , and Northing in separate DataColumns . All coordinates use the same datum , but some have different zones ( otherwise , I would just use pythag math since UTMs are in me...
dtTrap.Rows [ i ] [ `` TrapGeog '' ] = DbGeography.PointFromText ( pointWellKnownText : `` POINT M ( `` + dtTrap.Rows [ i ] [ intEastingIndex ] .ToString ( ) + `` `` + dtTrap.Rows [ i ] [ intNorthingIndex ] .ToString ( ) + `` `` + dtTrap.Rows [ i ] [ Zone ] .ToString ( ) + `` ) '' , coordinateSystemId : SRID ) ; using ...
Parsing UTM coordinates to DBGeography in C #
C#
I 'm writing a Tiger compiler in C # and I 'm going to translate the Tiger code into IL.While implementing the semantic check of every node in my AST , I created lots of unit tests for this . That is pretty simple , because my CheckSemantic method looks like this : so , if I want to write some unit test for the semanti...
public override void CheckSemantics ( Scope scope , IList < Error > errors ) { ... } Assert.That ( errors.Count == 0 ) ; Assert.That ( errors.Count == 1 ) ; Assert.That ( errors [ 0 ] is UnexpectedTypeError ) ; Assert.That ( scope.ExistsType ( `` some_declared_type '' ) ) ;
Writing unit tests in my compiler ( which generates IL )
C#
I 'm on learning for C # .I heared C # is one of the most constructible language . so would you guys make my code more elegant and efficient ? Here is a my class ISO639 . This class provides enum for ISO639 code , but I need a type conversion on from ISO639 enum to plain string . ( ex . ISO639.ISO639Code.Italian = > ``...
public class ISO639 { public enum ISO639Code { Afrikaans , //af Albanian , //sq Amharic , //am ... Yiddish , //yi Unknown } public static string GetISO639CodeString ( ISO639.ISO639Code l ) { switch ( l ) { case ISO639Code.English : return `` en '' ; case ISO639Code.Japanese : return `` ja '' ; ... case ISO639Code.Hebre...
more elegant design about enum
C#
I am writing an application to capture the screen using the CopyFromScreen method , and also want to save the image I capture to send over my local network.So , I am trying store the captured screen on one bitmap , and save another bitmap , which is the previously captured screen , on two threads . However , this is th...
Bitmap ScreenCapture ( Rectangle rctBounds ) { Bitmap resultImage = new Bitmap ( rctBounds.Width , rctBounds.Height ) ; using ( Graphics grImage = Graphics.FromImage ( resultImage ) ) { try { grImage.CopyFromScreen ( rctBounds.Location , Point.Empty , rctBounds.Size ) ; } catch ( System.InvalidOperationException ) { re...
InvalidOperationException while saving a bitmap and using graphics.copyFromScreen parallel-y
C#
I got a scenario to create the anonymous list from the anonymous types , and i achieved that using these are the error messages System.Collections.Generic.List.Add ( AnonymousType # 1 ) ' has some invalid arguments Argument ' 1 ' : can not convert from 'AnonymousType # 2 ' to 'AnonymousType # 1'whats the reason behind ...
public static List < T > MakeList < T > ( T itemOftype ) { List < T > newList = new List < T > ( ) ; return newList ; } static void Main ( string [ ] args ) { //anonymos type var xx = new { offsetname = x.offName , RO = y.RO1 } ; //anonymos list var customlist = MakeList ( xx ) ; //It throws an error because i have giv...
is order of field important in anonymous types automatic initialization ?
C#
Possible Duplicate : C # Why can equal decimals produce unequal hash values ? I 've come across an issue in my .NET 3.5 application ( x86 or x64 , I 've tried both ) where decimals with a different number of trailing zeros have different hash codes . For example : Outputs the following on my machine : I presume the dif...
decimal x = 3575.000000000000000000M ; decimal y = 3575.0000000000000000000M ; Console.WriteLine ( x.GetHashCode ( ) ) ; Console.WriteLine ( y.GetHashCode ( ) ) ; Console.WriteLine ( x == y ) ; Console.WriteLine ( x.GetHashCode ( ) == y.GetHashCode ( ) ) ; 10850094091085009408TrueFalse
Decimal.GetHashCode Depends On Trailing Zeros
C#
I create an entry usingIt is inside a ListView > ItemTemplate > DataTemplate > ViewCellThe thing is I need a way once a user clicks the submit button in that ViewCell it gets the text for the entry in that cell . I am using Binding to set the values so I do n't how to get the text .
< Entry Placeholder= '' Reply ... '' / >
How to get text from entry
C#
Let 's say we have two interfaces with conflicting method signatures : and now we create a class like this : The method named as IB.F looks like a private method , however you can do something like this : So my question is : how does the C # compiler know that IB.F can be called outside the class scope ? I guess it 's ...
interface IA { void F ( ) ; } interface IB { int F ( ) ; } class Test : IA , IB { public void F ( ) { ... } int IB.F ( ) { ... } } var t = new Test ( ) ; t.F ( ) ; //Calls public method F ( ( IB ) t ) .F ( ) ; //Calls private method IB.F ! ! !
Class implementing interfaces with conflicting method signatures
C#
First things off , I had no idea what to title this question - I 'm even confused how to state it . Now for the question . Let 's take the System.IO.FileSystemWatcher class where you set it 's NotifyFilter property : That 's quite a bit of code to set a single property . Inspecting NotifyFilter , it is an enumeration ....
this.FileSystemWatcher1.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size ;
Is there a way to set an Enumerated Property in a class to All available enums ?
C#
I am using this code to extract a chunk from file Is there any way to speed up this process ? Currently for a 530 MB file it takes around 4 - 5 seconds . Can this time be improved ?
// info is FileInfo object pointing to filevar percentSplit = info.Length * 50 / 100 ; // extract 50 % of filevar bytes = new byte [ percentSplit ] ; var fileStream = File.OpenRead ( fileName ) ; fileStream.Read ( bytes , 0 , bytes.Length ) ; fileStream.Dispose ( ) ; File.WriteAllBytes ( splitName , bytes ) ;
Improve speed of splitting file
C#
I have the following class : Can someone explain why they Customer information is coded with virtual . What does it mean ?
public class Delivery { // Primary key , and one-to-many relation with Customer public int DeliveryID { get ; set ; } public virtual int CustomerID { get ; set ; } public virtual Customer Customer { get ; set ; } // Properties string Description { get ; set ; } }
Why would I need to use a virtual modifier in a c # class ?
C#
I think I 'm missing something obvious here , but how do I update the GUI when using a task and retrieving the value ? ( I 'm trying to use await/async instead of BackgroundWorker ) On my control the user has clicked a button that will do something that takes time . I want to alert the parent form so it can show some p...
private void ButtonClicked ( ) { var task = Task < bool > .Factory.StartNew ( ( ) = > { WorkStarted ( this , new EventArgs ( ) ) ; Thread.Sleep ( 5000 ) ; WorkComplete ( this , null ) ; return true ; } ) ; if ( task.Result ) MessageBox.Show ( `` Success ! `` ) ; //this line causes app to block } myControl.WorkStarting ...
How do I update the GUI on the parent form when I retrieve the value from a Task ?
C#
I have an application that has a concept of a Venue , a place where events happen . A Venue has many VenueParts . So , it looks like this : A Venue can be a GolfCourseVenue , which is a Venue that has a Slope and a specific kind of VenuePart called a HoleVenuePart : In the future , there may also be other kinds of Venu...
public abstract class Venue { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < VenuePart > VenueParts { get ; set ; } } public class GolfCourseVenue : Venue { public string Slope { get ; set ; } public virtual ICollection < HoleVenuePart > Holes { get ; set ; } } public abst...
How do I organize C # classes that inherit from one another , but also have properties that inherit from one another ?
C#
This question is not about managing Windows pathnames ; I used that only as a specific example of a case-insensitive string . ( And I if I change the example now , a whole bunch of comments will be meaningless . ) This may be similar to Possible to create case insensitive string class ? , but there is n't a lot of disc...
sealed class WindowsPathname : IEquatable < WindowsPathname > /* TODO : more interfaces from System.String */ { public WindowsPathname ( string path ) { if ( path == null ) throw new ArgumentNullException ( nameof ( path ) ) ; Value = path ; } public string Value { get ; } public override int GetHashCode ( ) { return V...
How can System.String be properly wrapped for case-insensitivy ?
C#
I hava a mvvm wpf application that worked properly all until one moment when it freezes and causes massive memory leak.Solution files : Google Disk Solution LinkThe application uses local mdf file , uses Mahhaps , and some additional references ( for example one for displaying gifs ) This is the method call in the View...
public async void OnLoad ( ) { IsRefreshEnabled = false ; IsRefreshProgressActive = true ; Contacts =await Task.Run ( ( ) = > _repository.GetContactsAsync ( ) ) ; IsRefreshEnabled = true ; IsRefreshProgressActive = false ; } < DataGrid SelectedItem= '' { Binding Contact } '' AutoGenerateColumns= '' True '' ItemsSource=...
Wpf application freezes - massive memory leak puzzle
C#
The docs show this for a POST : But what about a GET : The problem is the ampersand in this line : /// GET /Todo ? iscomplete=true & owner=mike . The compiler complains : warning CS1570 : XML comment has badly formed XML -- 'Expected an end tag for element 'owner ' . ' I also tried & amp ; .I actually have n't found an...
/// < summary > /// Creates a TodoItem./// < /summary > /// < remarks > /// Sample request : ////// POST /Todo/// { /// `` id '' : 1 , /// `` name '' : `` Item1 '' /// } /// < /remarks > [ HttpPost ] public ActionResult < TodoItem > Create ( TodoItem item ) { } /// < summary > /// Gets a TodoItem./// < /summary > /// <...
Querystring with ampersand in Swashbuckle xml comments
C#
Currently I have I want to make the path relative to the original path.For example if Tenant1/PageThatThrowsError then app.UseExceptionHandler ( `` Tenant1/Home/Error '' ) ; but if Tenant2/PageThatThrowsError then app.UseExceptionHandler ( `` Tenant2/Home/Error '' ) ; I thought I would be able to dobut this throws a 50...
app.UseExceptionHandler ( `` /Home/Error '' ) ; app.UseExceptionHandler ( new ExceptionHandlerOptions { ExceptionHandler = async ( ctx ) = > { //logic that extracts tenant ctx.Request.Path = new PathString ( Invariant ( $ '' { tenant } /Home/Error '' ) ) ; } } ) ;
How to handle dynamic error pages in .net MVC Core ?
C#
This is a somewhat obscure question , but after wasting an hour tracking down the bug , I though it worth asking ... I wrote a custom ordering for a struct , and made one mistake : My struct has a special state , let us call this `` min '' .If the struct is in the min state , then it 's smaller than any other struct.My...
struct MyStruct : IComparable < MyStruct > { public int State ; public MyStruct ( int s ) { State = s ; } public int CompareTo ( MyStruct rhs ) { // 10 is the `` min '' state . Otherwise order as usual if ( State == 10 ) { return -1 ; } // Incorrect /*if ( State == 10 ) // Correct version { if ( rhs.State == 10 ) { ret...
Why does failing to recognise equality mess up C # List < T > sort ?
C#
Using NUnit 2.6.4 & FakeItEasy 1.25.2 to unit test a C # code in Visual Studio 2013 Community EditionThe following test fragment executes as expectedhowever as soon as I decorate my fake with a CallTo/Returns ( ) or ReturnsLazily ( ) statement ... fakeStream.Read ( ) throws a System.InvalidOperationException with the m...
[ Test ] public void test_whatIsUpWithStreamRead ( ) { Stream fakeStream = A.Fake < Stream > ( ) ; byte [ ] buffer = new byte [ 16 ] ; int numBytesRead = fakeStream.Read ( buffer , 0 , 16 ) ; Assert.AreEqual ( 0 , numBytesRead ) ; } [ Test ] public void test_whatIsUpWithStreamRead ( ) { Stream fakeStream = A.Fake < Str...
A.Fake < Stream > ( ) .Read ( ... ) throwing InvalidOperationException
C#
I use the following razor code to generate some javascript to produce markers on a Google map.In development , this correctly becomes : However , on our production server , it becomes : Which is producing just a grey Google map . What is causing this strange ToString behavior ? editThe Point class is a custom class , n...
@ foreach ( Point point in Model.Points.Take ( 3 ) ) { String longitude = point.Longitude.ToString ( CultureInfo.InvariantCulture ) ; String latitude = point.Latitude.ToString ( CultureInfo.InvariantCulture ) ; < text > var location = new google.maps.LatLng ( @ ( longitude ) , @ ( latitude ) ) ; bounds.extend ( locatio...
Invalid Double.ToString ( ) result in razor code generating javascript
C#
Its a well known fact that a static method can work only on static members.Here the Main method is static , but I have n't declared t1 as static . Is it implicitly static ?
public static void Main ( ) { Test t1 = new Test ( ) ; }
Are variables in the main methods static
C#
In short , I am looking for guidance on which of the following two methods should be preferred ( and why ) : Argument in favour of DistinctA : Obviously , the constraint on T is not required , because HashSet < T > does not require it , and because instances of any T are guaranteed to be convertible to System.Object , ...
static IEnumerable < T > DistinctA < T > ( this IEnumerable < T > xs ) { return new HashSet < T > ( xs ) ; } static IEnumerable < T > DistinctB < T > ( this IEnumerable < T > xs ) where T : IEquatable < T > { return new HashSet < T > ( xs ) ; }
When to specify constraint ` T : IEquatable < T > ` even though it is not strictly required ?
C#
I 've been asking questions on hex and bitwise manipulation ( here and elsewhere ) for the past week trying to wrap my head around their representation in Java . After much Googling and chagrin I must ask one final time how to perform logical arithmetic on bits that ought to be unsigned , but are represented as signed ...
int cmdtype = data [ pos ] > > 5 ; int len = ( data [ pos ] & 0x1F ) + 1 ; if ( cmdtype == 7 ) { cmdtype = ( data [ pos ] & 0x1C ) > > 2 ; len = ( ( data [ pos ] & 3 ) < < 8 ) + data [ pos + 1 ] + 1 ; pos++ ; }
Performing bitwise left shifts on `` signed '' data in Java -- better to move to JNI ?
C#
I was asked today if there was a library to take a list of strings and to compute the most efficient regex to match only those strings . I think it 's an NP Complete problem by itself , but I think we can refine the scope a bit.How would I generate and simplify a regex to match a subset of hosts from a larger set of al...
appserver1\.domain\.tld|appserver2\.domain\.tld|appserver3\.domain\.tld appserver [ 123 ] \.domain\.tld
Simplifying regex OR patterns
C#
I 'm trying to get to the bottom of an entity Framework issue when using it with a TableControllerI 've created the following setup.The basic TodoItem example provided with a new Mobile Web API which leverages EntityFramework , TableController & the default EntityDomainManagerA vanilla Web API 2 controller.I 've gone t...
public class TodoItemController : TableController < TodoItem > { protected override void Initialize ( HttpControllerContext controllerContext ) { base.Initialize ( controllerContext ) ; context = new MobileServiceContext ( ) ; context.Database.Log += LogToDebug ; DomainManager = new EntityDomainManager < TodoItem > ( c...
Why is Entity Framework generating the following nested SQL for Azure Mobile Services Table Controllers
C#
I am rendering my game in a Winform in the same way as done in this sample : WinForms Series 1 : Graphics Device In my game I have some object , for example a rectangle that I can already put and move , in my game world , once created . My project here is a level-editor.What I want to do is to make every object `` siza...
public abstract class GameObject { protected Vector2 position_ = Vector2.Zero ; protected float rotation_ = 0.0f ; protected Vector2 scale_ = Vector2.One ; protected float depth_ = 0.0f ; protected bool is_passable_ = true ; protected GameObject ( Vector2 starting_position ) { this.position_ = starting_position ; } [ D...
How to make an object `` scalable '' while rendered in a form
C#
Consider the following example : This compiles well.I wonder why can not I remove < string > generic argument ? I get an error that it can not be inferred from the usage.I understand that such an inference might be challenging for the compiler , but nevertheless it seems possible.I would like an explanation of this beh...
class Test { public void Fun < T > ( Func < T , T > f ) { } public string Fun2 ( string test ) { return `` '' ; } public Test ( ) { Fun < string > ( Fun2 ) ; } } class Test { public void Fun < T1 , T2 > ( T1 a , Func < T1 , T2 > f ) { } public string Fun2 ( int test ) { return test.ToString ( ) ; } public Test ( ) { Fu...
`` Two-level '' generic method argument inference with delegate
C#
A fairly common idiom in C is for functions taking a polymorphic closure to represent this as two arguments , a function pointer and void pointer ( which is passed as one of the arguments to the function pointer . An example taken from the GPGME library : Conceptually , the function pointer plus void pointer represent ...
typedef gpgme_error_t ( *gpgme_passphrase_cb_t ) ( void *hook , const char *uid_hint , const char *passphrase_info , int prev_was_bad , int fd ) ; void gpgme_set_passphrase_cb ( gpgme_ctx_t ctx , gpgme_passphrase_cb_t cb , void *hook_value ) ;
P/Invoke - Marshaling delegate as function pointer + void*
C#
I run into this frequently enough that I thought I 'd see what others had to say about it . Using the StyleCop conventions , I find that I often have a property name that is hard to make different than the class name it is accessing . For example : It compiles and runs , but seems like it would be an easy way to confus...
public class ProjectManager { // Stuff here } public class OtherClass { private ProjectManager ProjectManager { get ; set ; } }
What is a good naming convention to differentiate a class name from a property in C # ?
C#
A few years back , I got an assignment at school , where I had to parallelize a Raytracer.It was an easy assignment , and I really enjoyed working on it.Today , I felt like profiling the raytracer , to see if I could get it to run any faster ( without completely overhauling the code ) . During the profiling , I noticed...
// Sphere.Intersect public bool Intersect ( Ray ray , Intersection hit ) { double a = ray.Dir.x * ray.Dir.x + ray.Dir.y * ray.Dir.y + ray.Dir.z * ray.Dir.z ; double b = 2 * ( ray.Dir.x * ( ray.Pos.x - Center.x ) + ray.Dir.y * ( ray.Pos.y - Center.y ) + ray.Dir.z * ( ray.Pos.z - Center.z ) ) ; double c = ( ray.Pos.x - C...
Why is a simple get-statement so slow ?
C#
I am working on a runtime composite resource library for ASP.NET WebForms/MVC . I support both standard ASP.NET WebForms via WebControls and have also recently added support for ASP MVC Html Helpers . One feature that I currently support with the WebForms WebControls is the concept of `` Partial '' resource definitions...
< % using ( Html.CreateCompositeResourcePartContext ( ) ) { Html.CompositeCssResourcePart ( `` ResourceName '' , new [ ] { `` /Styles/SharedStyle1.css '' , `` /Styles/SharedStyle2.css '' } ) ; % > < asp : ContentPlaceHolder ID= '' head '' runat= '' server '' > < /asp : ContentPlaceHolder > < % } % > < asp : Content ID=...
Help with ASP.NET MVC HtmlHelper API Design
C#
I 've been working with DDD for a few months now and I 've come across a few things I 'm unsure of . Take the simplistic example of adding a Product to an Order object . From our Controller , we 'd have an int passed via the UI which represents a Product in the database . Which of the following two examples is correct ...
public class OrderController { // Injected Repositories private readonly IProductRepository _productRepository ; // Called by UI public void AddProduct ( int productId ) { Order order = ... ; // Persisted Order Product product = _productRepository.GetProduct ( productId ) ; order.AddProduct ( product ) ; } } void AddPr...
Which of these examples represent correct use of DDD ?
C#
A colleague has passed me an interesting code sample that crashes with an InvalidProgramException ( `` CLR detected an Invalid Program '' ) when run.The problem seems to occur at JIT time , in that this compiles fine but throws the exception just before the method with the `` offending '' line is called - I guess as it...
using System ; using System.Linq ; internal class Program { private static void Main ( string [ ] args ) { Test.Try ( ) ; } } public class Test { public static readonly int [ ] integers = new [ ] { 1 , 3 , 5 } ; public static void Try ( ) { var line = new Line { A = 3 , B = 5 } ; // PASSES var dict = integers.ToDiction...
`` CLR detected an Invalid Program '' when using Enumerable.ToDictionary with an extension method
C#
I 'm working on a project that needs to support both async and sync version of a same logic/method . So for example I need to have : The async and sync logic for these methods are identical in every respect except that one is async and another one is not . Is there a legitimate way to avoid violating the DRY principle ...
public class Foo { public bool IsIt ( ) { using ( var conn = new SqlConnection ( DB.ConnString ) ) { return conn.Query < bool > ( `` SELECT IsIt FROM SomeTable '' ) ; } } public async Task < bool > IsItAsync ( ) { using ( var conn = new SqlConnection ( DB.ConnString ) ) { return await conn.QueryAsync < bool > ( `` SELE...
How to avoid violating the DRY principle when you have to have both async and sync versions of code ?
C#
I have an empty list defined to hold 120 values , I want to insert an element at index ( 45 ) , even though the list is currently empty . Is this possible ?
public List < Ticket > Tickets = new List < Ticket > ( 120 ) ; Tickets.Insert ( 45 , ticket ) ; // Here I am getting the ArgumentOutOfRangeException
How to Insert an object in a list at custom index
C#
I upgraded ReSharper and seeing an error that I was not present previously . I checked around , but found nothing about the error or the underlying issue it is flagging . ** Edit ** : as pointed out below , it is actually the 'Heap Allocation Viewer ' plugin , not ReSharper itself that is marking it as an error -- thou...
public void Subscribe ( IPluginHandler subscriber ) { Executing += subscriber.OnExecuting ; // -- additional subscriptions -- }
Slow delegate creation
C#
On our application we have a clickable label which will pop up another window . I have been reading through the Microsoft Automation UI documentation , and ca n't find a way in which I 'm able to click a label control.I know that I ca n't use the Invoke Pattern as this only deals with Button controls.Below is the code ...
< Label Name= '' LblCompleteOrdersCount '' Content= '' { Binding CompleteOrders , Mode=OneWay } '' Margin= '' 434,45,0,0 '' Height= '' 62 '' Width= '' 170 '' Padding= '' 0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' VerticalContentAlignment= '' Top '' FontSize= '' 56 '' FontWeight= '' Bold '' > < La...
Is it possible to Click a label control on WPF/WinForm App using Microsoft Automation UI
C#
For the purpose of learning , I 'm trying to understand how C # strings are internally stored in memory.According to this blog post , C # string size is ( x64 with .NET framework 4.0 ) : A string with a single character will take ( 26 + 2 * 1 ) / 8 * 8 = 32 bytes .This is indeed similar to what I measured.What puzzle m...
26 + 2 * length string abc = `` abcdeg '' ; string aaa = `` x '' ; string ccc = `` zzzzz '' ;
How many bytes does a string take up in x64 ?
C#
I am tring to open memory mapped file in the system volume information subfolder . I know and see in explorer that it is exists there , and path is correct ( it is copy-pasted from explorer ) , moreover File.Exists for that path returns true , but MemoryMappedFile.OpenExisting fails with DirectoryNotFoundException . Wh...
const string filePath = @ '' C : \\System Volume Information\\Foo\\2.ext '' ; bool exists = File.Exists ( filePath ) ; //is trueusing ( MemoryMappedFile bitmapFile = MemoryMappedFile.OpenExisting ( filePath , MemoryMappedFileRights.Read ) ) //Throws DirectoryNotFoundException { ... }
File.Exists returns true and OpenExisting fails with DirectoryNotFoundException
C#
Ca n't find simple way to convert double to string . I need to convert large numbers without distortion . Such as : How to get string value from double value exactly the same as user enter.11111111111111111111111 = > `` 11111111111111111111111 '' 1.111111111111111111111 = > `` 1.111111111111111111111 '' Any ideas how i...
double d = 11111111111111111111 ; string s = d.ToString ( ) ; Console.WriteLine ( s ) ; //1.11111111111111E+19
Get string from large double value ( C # )
C#
I 'm hoping for a concise way to perform the following transformation . I want to transform song lyrics . The input will look something like this : And I want to transform them so the first line of each verse is grouped together as in : Lyrics will obviously be unknown , but the blank line marks a division between vers...
Verse 1 lyrics line 1Verse 1 lyrics line 2Verse 1 lyrics line 3Verse 1 lyrics line 4Verse 2 lyrics line 1Verse 2 lyrics line 2Verse 2 lyrics line 3Verse 2 lyrics line 4 Verse 1 lyrics line 1Verse 2 lyrics line 1Verse 1 lyrics line 2Verse 2 lyrics line 2Verse 1 lyrics line 3Verse 2 lyrics line 3Verse 1 lyrics line 4Vers...
Tricky string transformation ( hopefully ) in LINQ
C#
I was wondering if it is possible to reference a dynamic generic class name in a comment and have it conditionally resolved in the IDE ? Simple base class example : If I now inherit from this class and happens to be class User then I 'd like to have IntelliSense show my comment as `` Retrieves all User members from the...
// < summary > // Retrieves all < T > members from the database.// < /summary > public void GetAll < T > ( ) { //magic }
Reference generic comment
C#
Question : given IEnumerable < > , how to check what sequence contains more than x items ? MCVE : The problem here is what Count ( ) will run complete sequence and that 's 1E6+ items ( ToList ( ) is also bad idea ) . I am also not allowed to change consumer code ( it 's a method accepting complete sequence ) .
static void Main ( string [ ] args ) { var test = Test ( ) .Where ( o = > o > 2 & & o < 6 ) ; // ToList ( ) if ( test.Count ( ) > 1 ) // how to optimize this ? foreach ( var t in test ) // consumer Console.WriteLine ( t ) ; } static IEnumerable < int > Test ( ) { for ( int i = 0 ; i < 10 ; i++ ) yield return i ; }
Optimize LINQ Count ( ) > X
C#
I 'm writing a filter function to return the specific type specified out of a larger collection of supertypes ( objects for example ) . The idea is I give you an enumerable and you return me all the strings for example . you can write it this way without generics : if we want to return generics there are a few differen...
public static IEnumerable Filter ( IEnumerable source , Type type ) { List < object > results = new List < object > ( ) ; foreach ( object o in source ) { if ( o ! = null & & o.GetType ( ) == type ) { results.Add ( o ) ; } } return results ; } public static IEnumerable < TResult > Filter < TResult > ( IEnumerable sourc...
What is the appropriate way to strongly type the return of a generic function ?
C#
Can someone explain to me why I can not seem to throw an exception from inside the AppDomain.Assembly load event ? For example : When I execute this , the output is as follows : Can anyone explain this behavior to me ? Thank you.EDIT To clarify a couple things : The assembly load event runs fine , when I expect it to r...
class Program { static Program ( ) { AppDomain.CurrentDomain.UnhandledException += ( s , a ) = > { Console.WriteLine ( `` Caught exception ! `` ) ; } ; AppDomain.CurrentDomain.AssemblyLoad += ( s , a ) = > { Console.WriteLine ( string.Format ( `` Assembly { 0 } loaded '' , a.LoadedAssembly.FullName ) ) ; throw new Exce...
Throw exception from AppDomain.AssemblyLoad event
C#
i tried this code but it takes so long and I can not get the resultplease help
public long getCounter ( [ FromBody ] object req ) { JObject param = Utility.GetRequestParameter ( req ) ; long input = long.Parse ( param [ `` input '' ] .ToString ( ) ) ; long counter = 0 ; for ( long i = 14 ; i < = input ; i++ ) { string s = i.ToString ( ) ; if ( s.Contains ( `` 14 '' ) ) { counter += 1 ; } } return...
how many numbers between 1 to 10 billion contains 14
C#
Suppose we have a nested generic class : Here , typeof ( A < int > .B < > ) is in essence a generic class with two parameters where only the first is bound.If I have a single class with two parametersIs there a way to refer to `` AB with T=int and U staying open '' ? If not , is this a C # limitation , or a CLR limitat...
public class A < T > { public class B < U > { } } public class AB < T , U > { }
Does .Net support curried generics ?
C#
I have a dll wich expose a type like inside this library I also have an IPackage implementation which register the MyDbContext in the container like This assembly is then referenced from two different types of applications : - a web api project - an asp.net mvc applicationThis is the initialization of the web api proje...
public class MyDbContext { [ ... ] } public void RegisterServices ( Container container ) { container.Register < MyDbContext > ( Lifestyle.Scoped ) ; } var container = new Container ( ) ; container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle ( ) ; InitializeContainer ( container ) ; container.RegisterWebA...
DbContext creation into message handler
C#
I 'm trying to create a shortcut ( .lnk ) on my windows filesystem.The code I have is working fine . However , when I run the same console application on a Windows 2008R2 Server , it acts differently.So I have my console application and here is what happens : My program simply creates a shortcut on the desktop with a ....
using System ; using System.IO ; using System.Runtime.InteropServices ; using System.Runtime.InteropServices.ComTypes ; using System.Text ; namespace TestShortcut { class Program { static void Main ( string [ ] args ) { //ShortcutTarget var sTarget = @ '' U : \test.docx '' ; //ShortCutName var sName = @ '' MyWordFile.l...
Creating shortcut modifies the path to target