lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I 'm refactoring a little bit of C # data access code from a previous developer and am curious about a pattern he used.The code initially exposed collections ( arrays ) of a variety of ActiveRecord-style business objects - essentially objects wrapping database fields . I 'm changing the arrays to generic lists , but th...
public Thing GetThing ( int i ) { return things [ i ] ; } for ( int i = 0 ; i < thingsCount ; i== ) { dosomthing ( GetThing ( i ) ) ; dosomethingelse ( GetThing ( i ) ) ; } for ( int i = 0 ; i < thingsCount ; i== ) { Thing thing = things [ i ] ; dosomthing ( thing ) ; dosomethingelse ( thing ) ; }
Any advantage to objects.GetObject ( i ) over objects [ i ] ?
C#
As a learning exercise , I 'm trying to reproduce an async/await deadlock that occurs in a normal windows form , but using a console app . I was hoping the code below would cause this to happen , and indeed it does . But the deadlock also happens unexpectedly when using await.I 'm mostly curious if anyone knows why thi...
using System ; using System.Threading ; using System.Threading.Tasks ; using System.Windows.Forms ; static class Program { static async Task Main ( string [ ] args ) { // no deadlocks when this line is commented out ( as expected ) SynchronizationContext.SetSynchronizationContext ( new WindowsFormsSynchronizationContex...
async/await deadlock when using WindowsFormsSynchronizationContext in a console app
C#
If I have a method like thisis f created every time SomeMethod is called ? I mean , does that line take time to compute or does the compiler store the function somewhere on compile time skips it at execution ?
void SomeMethod ( ) { Func < A , B > f = a = > /*Some code*/ ; ... b = f ( a ) ; }
Inline lambda function creation behaviour in C #
C#
Consider this simple .js code : // UsageI 'm pretty sure c # support first class function , note that I do n't want to use classes to remake the code above . What is the equivalent closure in c # ? I have made this :
const createCounter = ( ) = > { let value = 0 ; return { increment : ( ) = > { value += 1 } , decrement : ( ) = > { value -= 1 } , logValue : ( ) = > { console.log ( value ) ; } } } const { increment , decrement , logValue } = createCounter ( ) ; public Func < WhatType ? > CreateCounter = ( ) = > { var value = 0 ; retu...
What is the equivalent javascript closure in c # ?
C#
Firstly , This might seem like a long question . I do n't think it is ... The code is just an overview of what I 'm currently doing . It does n't feel right , so I am looking for constructive criticism and warnings for pitfalls and suggestions of what I can do.I have a database with business objects.I need to access pr...
public class User { public string ID { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public string PhoneNo { get ; set ; } public AccountCollection accounts { get ; set ; } public User { accounts = new AccountCollection ( this ) ; } public static List < Users > GetUsers ( ...
Overly accessible and incredibly resource hungry relationships between business objects . How can I fix this ?
C#
I have the following two button click methods that create an array from three TextBoxes , order the values , insert them into a database and then select the values in the same order . The only difference between the two buttons is that one orders the values in ascending order and the other in descending order.I 'm not ...
protected void Button1_Click ( object sender , EventArgs e ) { var list = new string [ ] { TextBox1.Text , TextBox2.Text , TextBox3.Text } ; var orderedlist = list.OrderBy ( x = > ( x ) ) .ToArray ( ) ; SqlCommand cmd = new SqlCommand ( `` Select * from lists order by values asc '' , conn ) ; protected void Button2_Cli...
Structuring button click methods to avoid code repetition
C#
Possible Duplicates : What does placing a @ in front of a C # variable name do ? What ’ s the use/meaning of the @ character in variable names in C # ? As you can imagine , Googling or Binging for any phrase containing an ' @ ' is difficult.In creating a new web service , one of the members of the imported C # proxy cl...
plan . @ event = new Insurance.Event ( ) ;
What is the purpose of @ as part of a member name in C # ?
C#
On the internet I see a lot of code which uses this . to access local members of a class , like this : ( do n't expect the code to do something sensible . I just wanted to show a few different uses for `` this . `` ) I wonder why to do this ? To add more clarity to the source ? Or is it just a waste of space ?
private String _whatever ; public String Whatever { get { return this._whatever ; } set { this._whatever = value ; } } public void DoSomething ( ) { String s = this.Whatever ; this.DoSomething ( ) ; }
Use this . to access internal class members ?
C#
I 'm gettin an error pointing to in in the foreach loop ! ? Has never happens before . What could be the reason for this ? Have I missed something ? Error message : An exception of type 'System.NotSupportedException ' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information : Un...
List < int > WeeksInProject = new List < int > ( ) ; var w = from x in db.Activities where x.ProjectID.Equals ( 1 ) select x ; foreach ( var wNum in w ) { WeeksInProject.Add ( wNum.WeekNumber ) ; }
Foreach loop error
C#
Similar to how lambda expressions with free variables work I would like to implement my own closure class that captures some method parameter.Then I have some class that works with DateTime instances . One of the methods that should use this closure class is this : I would like to convert it to use Closure class . The ...
public class Closure < TObject , TVariable > { public TVariable Variable { get ; set ; } public Func < TObject , bool > Predicate { get ; set ; } } // Original Versionpublic IEnumerable < Item > GetDayData ( DateTime day ) { this.items.Where ( i = > i.IsValidForDay ( day ) ) ; } private Closure < Item , DateTime > clos...
Storing pointer to method parameter for later reuse
C#
I 've seen this piece of code from one of the jetbrain 's team : Looking at this code : Question : What is the scope of the lock ?
object myLock = new object ( ) public IEnumerable < int > Values ( ) { lock ( myLock ) { for ( var i=0 ; i < 10 ; i++ ) yield return i ; } } public void Test ( ) { foreach ( var value in Values ( ) ) { DoHugeJob ( value ) ; } } void Main ( ) { Test ( ) ; }
What is the scope of the lock ?
C#
How can I have a type reference that refers to any object that implements a set of interfaces ? For example , I can have a generic type like this : Java : C # That 's how to have a class-wide generic type . However , I 'd like to simply have a data member which references any object that extends a given set of interfac...
public class Foo < T extends A & B > { } public class Foo < T > where T : A , B { } public class Foo { protected < ? extends A , B > object ; public void setObject ( < ? extends A , B > object ) { this.object = object ; } }
C # - How can I have an type that references any object which implements a set of Interfaces ?
C#
So I 'm making a tile based game and I 'd like to add some fake shadows to the tiles . It 's kinda hard to explain so I 'll do it with pictures : Let 's say this is my tile world : And I want it to have shadows like this : Because the world is tile based , I can split all the shadow parts into separate images : But now...
bool ul = adjacentBlocks [ 0 , 0 ] == Block.Type.Rock ; //Upper Leftbool um = adjacentBlocks [ 1 , 0 ] == Block.Type.Rock ; //Upper Middlebool ur = adjacentBlocks [ 2 , 0 ] == Block.Type.Rock ; //Upper Rightbool ml = adjacentBlocks [ 0 , 1 ] == Block.Type.Rock ; //Center Left//bool cm = adjacentBlocks [ 1 , 1 ] == Bloc...
How would I efficiently make fake tile shadows ?
C#
Code : Two identical blocks in identical usings . Output : Second block takes 2.2 seconds ! But if to get rid of usings , durations became same ( ~0.3s , like first one ) .I 've tried with .net framework 4.5 and .net core 1.1 , in release , results are same.Can anybody explain that behavior ?
internal class Program { private static void Main ( string [ ] args ) { const int iterCount = 999999999 ; var sum1 = 0 ; var sum2 = 0 ; using ( new Dis ( ) ) { var sw = DateTime.Now ; for ( var i = 0 ; i < iterCount ; i++ ) sum1 += i ; Console.WriteLine ( sum1 ) ; Console.WriteLine ( DateTime.Now - sw ) ; } using ( new...
What is the reason of so different durations of same code blocks execution ?
C#
I 'm struggling with implementing the IEquatable < > interface for a class . The class has a Parameter property that uses a generic type . Basically the class definition is like this : In the Equals ( ) method I 'm using EqualityComparer < T > .Default.Equals ( Parameter , other.Parameter ) to compare the property . Ge...
public class MyClass < T > : IEquatable < MyClass < T > > { public T Parameter { get ; } ... } var parameterType = typeof ( T ) ; var enumerableType = parameterType.GetInterfaces ( ) .Where ( type = > type.IsGenericType & & type.GetGenericTypeDefinition ( ) == typeof ( IEnumerable < > ) ) .Select ( type = > type.GetGen...
How to compare two IEnumerable < T > in C # if I do n't know the actual object type ?
C#
This loads a set of values from an XML file and places them into a class for storage . I 'm trying to figure out how to output the values as a list so I can place them into a Listbox.I thought there would be an easy way like a .ToList ( ) method or to be able to foreach through the strings in the class ( no public GetE...
using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.IO ; using System.Xml ; namespace ThereIsOnlyRules { public partial class Form1 : Form { public Form1 ( ) { Initial...
Outputting Class Of Stored Values To List
C#
My understanding is that x is not actually declared as a variable eg . var x = 3 . Instead , it 's passed into the outer function , which returns a function that returns the original value . At the time it is returning this , it creates a closure around x to remember its value . Then later on , if you alter s , it has ...
static void Main ( string [ ] args ) { var s = 3 ; Func < int , Func < int > > func = x = > ( ) = > { return x ; } ; var result1 = func ( s ) ; func = null ; s = 5 ; var result2 = result1 ( ) ; Console.WriteLine ( result2 ) ; Console.ReadKey ( ) ; } int s = 0 ; Func < int , Func < int > > func = x = > ( ) = > { return ...
Is this an example of a closure in C # ?
C#
There are two ways to implement overloads . The first one is to do everything in one method/constructor and call it from other overloads , which leads to longer method bodies . The second one is to do the minimum in each overload , thus having a code sometimes difficult to navigate and to understand which overload does...
public Cat ( string name , int ? weight , Color mainColor ) ; public Cat ( string name ) ; public Cat ( string name , int ? weight , Color mainColor ) { // Initialize everything . this.name = name ; if ( weight.HasValue ) this.weight = weight.Value ; // There is a bug here ( see the anwer of @ Timwi ) : mainColor can b...
How to choose between one big method with passive overloads and a bunch of small overloads , each one doing a small amount of work ?
C#
Is this possible in C # ? The following code produces a compiler error.The C # compiler complains , `` Error CS0149 : Method name expected . '' It 's unable to infer the lambda method 's return type.Note my technique of invoking the lambda method immediately via the ( ) after the the lambda block is closed { } . This e...
HashSet < Task < ( string Value , int ToNodeId ) > > regionTasks = new HashSet < Task < ( string Value , int ToNodeId ) > > ( ) ; foreach ( Connection connection in Connections [ RegionName ] ) { regionTasks.Add ( async ( ) = > { string value = await connection.GetValueAsync ( Key ) ; return ( value , connection.ToNode...
Assign C # Async Lambda Method to Variable Typed as a Task
C#
When I run my C # application , Visual Studio reports that it has loaded a managed binary with ( what looks like ) a randomly generated name . For example : or : What is this , and why is its name ( seemingly ) randomly generated ?
'WindowsFormsApplication1.vshost.exe ' ( Managed ) : Loaded 'ehmgcsw7 ' 'WindowsFormsApplication1.vshost.exe ' ( Managed ) : Loaded 'jvo4sksu '
When I run my C # application , Visual Studio reports that it has loaded a managed binary with ( what looks like ) a randomly generated name
C#
I 'm using string.Join to be able to show what values an array contains . I have stumbled upon a strange behavior when using a byte array and startIndex and count.gives this resultWhole byteArr : 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8Whole stringArr : 1 , 2 , 3 , 4 , 5 , 6 , 7 , 80 - 5 byteArr : System.Byte [ ] , 0 , 50 - 5 str...
byte [ ] byteArr = new byte [ ] { 1,2,3,4,5,6,7,8 } ; string [ ] stringArr = new string [ ] { `` 1 '' , '' 2 '' , '' 3 '' , '' 4 '' , '' 5 '' , '' 6 '' , '' 7 '' , '' 8 '' } ; Console.WriteLine ( string.Format ( `` Whole byteArr : { 0 } '' , string.Join ( `` , `` , byteArr ) ) ) ; Console.WriteLine ( string.Format ( ``...
Strange behavior of string.Join on byte array and startIndex , count
C#
I 'm making a WPF text-editor using TextFormatter . I need to justify the last line in each paragraph . Something like that : how to make this happen ? Thanks in advance ! !
I need to justify the last line in eachparagraph I need to justify the last line in each paragraph I need to justify the last line in each paragraph I need to justify the last line in
Full justify of last line in WPF TextFormatter
C#
is that an `` ok '' code ? I need to do complex operation in the finally and it might crash since it 's connecting to the a DBthis look weird to me , so . is this the proper way ?
try { /*stuff*/ } catch ( Exception e ) { /*stuff*/ } finally { try { /*stuff*/ } catch { /*empty*/ } }
is it ok to have a try/catch in a finally ?
C#
Currently , I have a bunch of classes of this form that I 'd like to create at runtime using Reflection.Emit . However , I 'm running into an issue when I attempt to add the parent - since the TestAdmin class does n't exist before runtime , I do n't know how to create Any ideas ?
[ Name ( `` Admin '' ) ] public class TestAdmin : TestUserBase < TestAdmin > { public TestAdmin ( Type webDriverType ) : base ( webDriverType ) { } } TestUserBase < TestAdmin >
Using emitted type as type parameter in Reflection.Emit
C#
I have a few days looking at RX , and I have read a lot ; I have read IntroToRx ; I have also looked at 101 RX Samples , and many other places , but I ca n't figure this out . It sounds so simple , but I ca n't get what I need : I need to know which `` ID '' has been `` stuck '' in state 'STARTED ' for at least 30 minu...
public class MyInfo { public string ID { get ; set ; } public string Status { get ; set ; } } var subject = new Subject < MyInfo > ( ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 1 '' , Status = `` STARTED '' } ) ; subject.OnNext ( new MyInfo ( ) { ID = `` 2 '' , Status = `` PHASE1 '' } ) ; subject.OnNext ( new MyInfo ...
Using RX queries , how to get which records have same status for a window of 3 seconds every second ?
C#
I 'm writing a translator , not as any serious project , just for fun and to become a bit more familiar with regular expressions . From the code below I think you can work out where I 'm going with this ( cheezburger anyone ? ) .I 'm using a dictionary which uses a list of regular expressions as the keys and the dictio...
var dictionary = new Dictionary < string , List < string > > { { `` ( ? ! e ) ight '' , new List < string > ( ) { `` ite '' } } , { `` ( ? ! ues ) tion '' , new List < string > ( ) { `` shun '' } } , { `` ( ? : god|allah|buddah ? |diety ) '' , new List < string > ( ) { `` ceiling cat '' } } , .. } var regex = `` ( `` +...
Determining which pattern matched using Regex.Matches
C#
I have created a method for reading inbox new messages by using exchange server like below.How to add these IEnumerable collection to a Queue and Process each List of item inside the queue asynchronously ? The below are the process i need to call asynchronously by using each items in the queue
private static IEnumerable < ExchangeEmailInformation > GetInboxItems ( ExchangeService service ) { var emailInformations = new List < ExchangeEmailInformation > ( ) ; try { SearchFilter searchFilter = new SearchFilter.SearchFilterCollection ( LogicalOperator.And , new SearchFilter.IsEqualTo ( EmailMessageSchema.IsRead...
How to add an IEumerable Collection to a Queue and Process each item asynchronously in .NET ?
C#
I have a simple .NET application which runs as Windows Service . Say it has one Class I want to create a console application where I would type simple human readable commandslike Pretty much like you do in windows console . I wonder what is the best way to implement this mapping . A straight methods is of course create...
MyClass { Run ( Destination d ) Walk ( Destination d ) Wash ( Dishes d ) } run leftwalk right
Scripting .NET objects
C#
I am using string builder to format my string to append and prepend white spaces at the start and end of the stringhere is what I have so far : but I 'm getting the error incorrect format . What am i doing wrong ?
private void button1_Click ( object sender , EventArgs e ) { String Word = textBox1.Text ; AppendPrependText ( Word ) ; } private void AppendPrependText ( String Word ) { int count = Convert.ToInt32 ( textBox2.Text ) ; int WordCount = Word.Count ( ) ; int totalChar = count + WordCount ; string format = `` { - '' +total...
Inserting user defined number of spaces before and after string using C #
C#
I am currently migrating a project to PostSharp to remove a lot of boilerplate code , most of it is going very smoothly but I 'm left confused about how to force a command to recheck if it CanExecute . I expected PostSharp would inspect the command like it does properties to check for dependencies , here is a minimalis...
[ NotifyPropertyChanged ] public class MyWindowViewModel { /// Anything bound to this refreshes just fine as expected public ObservableCollection < SomeType > Documents = new ObservableCollection < SomeType > ( ) ; [ Command ] public ICommand AddDocumentCommand { get ; set ; } public void ExecuteAddDocument ( ) { Docum...
Triggering `` CanExecute '' on postsharp [ Command ] when a document changes ?
C#
I work an an automation team designing tests for electronic components . One thing our framework sorely needs is a single source point for our driver objects for the various pieces of test equipment at a workbench ( right now , driver object creation is very wild-west ) . Basically , the idea would be there would be on...
public object GetDriver ( string name ) ;
Is this method returning a System.Object class an anti-pattern ?
C#
I have the following class : When I try to find out size of this class on a 64 bit system by using WinDbg I get the size 40which I am not able to understand , as far as I have read MyClass should haveI do n't have 10 reputation that 's why i am not able to post image.Anyone has any idea why WinDbg is showing 4 extra by...
public class MyClass { public string Name { get ; set ; } public int Age { get ; set ; } public double Amount { get ; set ; } } 8 bytes for SyncBlock8 bytes for TypeHandle8 bytes for string reference4 bytes for Int328 bytes for double= 36 bytes
How to determine size of an object , c # ?
C#
Short Question : Provided I have given an implicit conversion mechanism for my object to convert its values from a plain string , can it be made to auto-bind to ViewModel 's property ? Details : I have a complex object like so ( simplified for brevity and clarity ) I am using the above object in my view model as below ...
public enum PrimaryScopeEnum { Pivot1 , Pivot2 } public enum SecondaryScopeEnum { Entity1 , Entity2 , Entity3 , Entity4 } public class DataScope { public PrimaryScopeEnum PrimaryScope { get ; set ; } public SecondaryScopeEnum SecondaryScope { get ; set ; } public static implicit operator DataScope ( string combinedScop...
Can a QueryString parameter be bound to a complex object if the complex object has implicit casting from string
C#
I 'm looking to add a `` recently opened '' functionality to my application , and was wondering if there was a simple built in way to do lists that `` overflow '' . By this I mean , when you add an element beyond the capacity of the list , all the items are shifted.Code example of desired functionality ( obviously its ...
List < string > list = new List < string > ( ) ; //if Overflow was 2list.Add ( `` A '' ) ; list.Add ( `` B '' ) ; //List now contains A , Blist.Add ( `` C '' ) ; //List now contains B , C
Does .NET have a simple way to do overflow lists ?
C#
I have a database table that looks like this : Now . This is a Status History indicator for DetectorID 1541.I only want to show 1 row at my website . To do this i excecute the following query.So what it does , it grabs the newest row ( Based on TimeStamp ) , and shows it.This will give me the results of ScannerStatusHi...
[ Query ] public IQueryable < ScannerStatusHistory > GetScannerStatusHistoryy ( int detectorID ) { return ObjectContext.ScannerStatusHistories.Where ( t = > t.DetectorID == detectorID ) .OrderByDescending ( d = > d.TimeStamp ) .Take ( 1 ) ; ; }
C # Query Select first since value changed
C#
I have to deserialize a response from an api which has the following structure : Some insights : The JSON is an array of objectsEvery object inside the array will ALWAYS have the properties `` starttime '' and `` endtime '' Objects `` var1 '' , `` var2 '' , `` var3 '' will ALWAYS have the same properties inside them .....
[ { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } , `` var2 '' : { } } , { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } , `` var3 '' : { } } , { `` starttime '' : `` ... '' , `` endtime '' : `` ... . '' , `` var1 '' : { } } ] public class MyResponse { [ Jso...
How to deserialize JSON with dynamic and static key names in C #
C#
I 'm inheriting from TextBox and overriding OnInit . I have MyBase.OnInit ( e ) in the example above , but I 've been using my control for a while without it , as I forgot to put it in there . This is something I usually do out of habit , so I never gave its purpose much thought : When overriding OnInit in a derived cl...
Protected Overrides Sub OnInit ( e As EventArgs ) MyBase.OnInit ( e ) ' I 'm adding a dynamic control to go along with my textbox here ... Controls.Add ( Something ) End Sub
What 's the impact of not using MyBase.OnInit ( e ) when overriding it in a derived class ?
C#
I have an MVC application which has a restful service that updates latitude and longitude to the database . I am sending the values to the API as string and its converted to Double before it is stored in database as Double . Here is the code I am using to convert string to double : When its stored in database I am miss...
Double _latitude , _longitude ; try { Double.TryParse ( lattitude , NumberStyles.Any , CultureInfo.CurrentCulture , out _latitude ) ; Double.TryParse ( Longtitude , NumberStyles.Any , CultureInfo.CurrentCulture , out _longitude ) ; } catch ( Exception e ) { _latitude = 0 ; _longitude = 0 ; }
Double is not stored correctly in MySQL database
C#
I 'm trying to figure out how to define if string contains/does not contains list value and if contains but with other value . If I have input string : and I want find specific value for condition : But not sure what is a proper way if I want to know also about third condition , if string contains value but also contai...
string inputString = `` it was one '' ; var numbList = new List < string > { `` zero '' , `` one '' , `` two '' } ; if ( ! numbList.Any ( inputString.Contains ) ) { Console.WriteLine ( `` string does not contains list value '' ) ; } else { Console.WriteLine ( `` string contains list value '' ) ; } Console.WriteLine ( `...
How to check if string contains list value and separately if contains but with other value
C#
I 'm inheriting the code someone else wrote at work and found that there are a lot of `` new '' instantiating without actually assigning to a variable : I 'm just wondering if anyone has any experience with this and if this is anti-pattern or not .
new MyCoolClass ( ) .MyCoolMethod ( ) ;
Instantiating without assigning to a variable
C#
What is the difference in autofac between these two registrations : andwhere Instance is a ( non-static ) property of an autofac module in which the registration occurs , set by object initializer.My reason for asking is that the former has been done in a piece of code I 'm debugging and I 'm getting some strange behav...
builder.Register ( c = > Instance ) .As < ISomeInterface > ( ) ; builder.RegisterInstance ( Instance ) .As < ISomeInterface > ( ) .SingleInstance ( ) .ExternallyOwned ( ) ;
What is the difference between these two ways of registering an instance in autofac
C#
Given the following LinqPad example : Why can EnumerableMethod take the list directly while ListMethod needs a cast first ? I get that an cast is happening from DbItem to IDbItem , but what is different about the IEnumerable that allows it to make the cast without an express request ? I imagine the answer involves the ...
void Main ( ) { List < DbItem > dbItems = new List < DbItem > { new DbItem { Id = 4 , SomeValue = `` Value For 4 '' , OtherValue = 1 } , new DbItem { Id = 19 , SomeValue = `` Value For 19 '' , OtherValue = 2 } } ; ListMethod ( dbItems.Cast < IDbItem > ( ) .ToList ( ) ) ; < -+ EnumerableMethod ( dbItems ) ; < -+ } | |//...
Why does IEnumerable not need a cast but a List does ?
C#
So here is my problem , I have an API setup that returns results from Azure Storage Table in JSON string format : And I am trying to convert it back to Project object : I keep getting `` Error converting value from 'string ' to 'object'.I have tried : this , this , this , this , this , this and this and it wo n't work ...
[ { `` CustID '' : `` f3b6 ... ..0768bec '' , `` Title '' : `` Timesheet '' , `` CalendarID '' : `` AAMkADE5ZDViNmIyLWU3N2 ... ..pVolcdmAABY3IuJAAA= '' , `` PartitionKey '' : `` Project '' , `` RowKey '' : `` 94a6 ... ..29a4f34 '' , `` Timestamp '' : `` 2018-09-02T11:24:57.1838388+03:00 '' , `` ETag '' : `` W/\ '' date...
Converting from json to List < object > causing exception
C#
Assuming we have the following model : And the following implementation : Now my question : Is codesnippet # 1 equivalent to codesnippet # 2 ? Or does it take longer to run codesnippet # 1 ? CodeSnippet # 1 : CodeSnippet # 2 :
public class Father { public Child Child { get ; set ; } public string Name { get ; set ; } public Father ( ) { } } public class Child { public Father Father ; public string Name { get ; set ; } } var father = new Father ( ) ; father.Name = `` Brad '' ; var child = new Child ( ) ; child.Father = father ; child.Name = `...
Is the C # or JIT compiler smart enough to handle this ?
C#
I have a FlipView in my MainPage . It 's ItemTemplate binded to a UserControl called landscapeControl . It 's ItemsSource is binded to a List of a class called MyLandscape . landscapeControl : MyLandscape class : My images are showing perfectly . All I want is 3 things:1 ) I want to access my Canvas from my MainPage . ...
< Grid > < ScrollViewer x : Name= '' LScrollViewer '' MaxZoomFactor= '' 2.0 '' MinZoomFactor= '' 1.0 '' HorizontalScrollBarVisibility= '' Hidden '' VerticalScrollBarVisibility= '' Hidden '' DoubleTapped= '' LScrollViewer_DoubleTapped '' > < Canvas x : Name= '' inkCanvas '' Background= '' Transparent '' > < StackPanel x...
Access a Canvas inside an ItemsSource in a UserControl , from the MainPage
C#
There 's a subtle point about assembly dependencies I would like to understand . I have a project which uses SharpDX through a custom wrapper like so : SharpDX.dll < - Wrapper.dll < - Project.dllIn Wrapper.dll is a type such as : In this class , if I uncomment the commented constructor , then Project.dll must reference...
public class D3DWrapperTypeA { //public D3DWrapperTypeA ( SharpDX.Device device ) { // // } public D3DWrapperTypeA ( IntPtr devicePointer ) { SharpDX.Device device = new SharpDX.Device ( devicePointer ) ; // etc } } public class WrapperTypeB { public SharpDX.Device GetDevice ( int adapter ) { // etc } public IntPtr Get...
Why does an unused constructor cause an assembly dependency in this case ?
C#
In my form I have four RadioButtons , based on user selection , this code is executed : The code seems very redundant and repeated , but also I ca n't find a way to handle all 4 RadioButtons in a single line that has only one variable linked to user choice.myList is a List of a class I created that has 4 string propert...
private void button1_Click ( object sender , EventArgs e ) { listBox1.Items.Clear ( ) ; if ( radioButtonName.Checked ) { var Qr = from n in mylist where n.Name == textBoxSearch.Text select new { n.Name , n.Age , n.Occu , n.Gender } ; foreach ( var item in Qr ) { listBox1.Items.Add ( `` Name : `` + item.Name + `` `` + `...
Best way to handle redundant code that has repeated logic ?
C#
I do n't understand why code first does not add a new item to the collection until after calling savechanges . I installed EF4.1 from NuGet ( 4.1.10331.0 ) . I created the following example : First I added one record to the database . Then I ran this and these are the results : My questions are : - Why does the first c...
public class TinyItem { public int Id { get ; set ; } public string Name { get ; set ; } } public class TinyContext : DbContext { public virtual DbSet < TinyItem > Items { get ; set ; } } class Program { static void Main ( string [ ] args ) { using ( var ctx1 = new TinyContext ( ) ) { ListItems ( ctx1 , `` Start '' ) ;...
EF4 code first adding items not very clear to me
C#
Just ca n't get it with datepicker validation.I have datepicker From and datepicker To , so I want to prevent the user from doing some kung fu and seting datepicker From to be bigger than datepicker To , I 've bumped across some questions but could n't find the answer , so I 've tried doing the easiest way I could thin...
private void Form1_Load ( object sender , EventArgs e ) { datepickerFrom.MaxDate = datepickerFrom.Value ; } private void datepickerFrom_ValueChanged ( object sender , EventArgs e ) { datepickerFrom.MaxDate = datepickerFrom.Value ; } private void dtFrom_ValueChanged ( object sender , EventArgs e ) { DateTime from = date...
Proper way for datepickers validaton in c # ? ( windows forms )
C#
AKA why does this test fail ?
[ TestFixture ] public class Tests { [ Test ] public void InnerClassShouldBePublic ( ) { Assert.IsTrue ( typeof ( InnerClass ) .IsPublic ) ; } public class InnerClass { } }
Why are inner class not public when viewed in reflection ?
C#
Why , when I turn INT value to bytes and to ASCII and back , I get another value ? Example :
var asciiStr = new string ( Encoding.ASCII.GetChars ( BitConverter.GetBytes ( 2000 ) ) ) ; var intVal = BitConverter.ToInt32 ( Encoding.ASCII.GetBytes ( asciiStr ) , 0 ) ; Console.WriteLine ( intVal ) ; // Result : 1855
Why do I get a different value after turning an integer into ASCII and then back to an integer ?
C#
I 'm writing code that calls the following method that exists in Windows.Networking.PushNotificationsI want to be sure to cover all cases where exceptions can be thrown and deal with each appropriately . Is it possible for me to get a list of the different types of exceptions this can throw and different circumstances ...
// Summary : // Creates objects that you use to retrieve push notification channels from// the Windows Push Notification Services ( WNS ) . These channels are bound to// an app or secondary tile . [ Threading ( ThreadingModel.MTA ) ] [ Version ( 100794368 ) ] public static class PushNotificationChannelManager { // Summ...
How can I find out what kind of exceptions can be thrown by a method ?
C#
I would like to write custom SQL code for mysql and mssql ( perhaps more later ) .The Problem starts here . I would like to declare the connection via an interface or abstract-class before the if-statement . But it seems not possible , because the command-classes demand explicitly the specific SqlConnection or MySqlCon...
var dbSystem = `` mssql '' ; if ( `` mssql '' == dbSystem ) { var mssqlConn = new SqlConnection ( mssqlConnString ) ; new SqlCommand ( `` CREATE TABLE t1 ( c1 in NOT NULL PRIMARY KEY IDENTITY ( 1,1 ) , c2 int ) '' , mssqlConn ) .ExecuteNonQuery ( ) ; } else { var mysqlConn = new MySqlConnection ( mysqlConnString ) ; ne...
Abstractionlayer for Database-Access
C#
Initializing a class like this : I am getting an InvalidCastException on one of the assignments . There are quite a lot of them and the exception occurs on the whole expression even if I run the debugger line-by-line . The exception does n't give any clue either what it 's trying to cast to what.Is there a way to debug...
var x = new Item ( ) { ID = ( int ) ... , Name = ( string ) ... , .. } ;
Is it possible to debug a struct/class initialization member by member ?
C#
I 'm a bit puzzled here ... I have a test method which does a call to an async method and I changed the signature to async Task . Works.Now I read all over the web that support for async is required in unit tests and is now also in NUnit . But why is that so important ? I can write the test like this , using the Result...
[ TestMethod ] public async Task TestIt ( ) { bool result = await service.SomethingAsync ( ) ; Assert ( result ) ; } [ TestMethod ] public void TestIt ( ) { bool result = service.SomethingAsync ( ) .Result ; Assert ( result ) ; }
Why would one need `` async '' support for MS Unit Test if Task.Result can be used ?
C#
Ok so I am trying to get all the Companies assigned to BOTH courses that exist in a course mapping table.The course mapping table has 2 FK CourseIDs , that point to two different courses in the same table.Each course has a bundle , and the companies are assigned to bundles.I am trying to select all the companies that a...
Bundle vegasBundle = ( from cm in db.VegasToPegasusCourseMaps join c in db.Courses on cm.VegasCourseID equals c.CourseID join b in db.Bundles on c.BundleID equals b.BundleID where cm.VPCMapID == CourseMapID select b ) .FirstOrDefault ( ) ; Bundle pegasusBundle = ( from cm in db.VegasToPegasusCourseMaps join c in db.Cou...
Can anyone reduce these 3 LINQ to SQL statements into one ?
C#
I 'm reading Jon Skeet 's C # in Depth.On page 156 he has an example , Listing 5.13 `` Capturing multiple variable instantiations with multiple delegates '' .In the explanation after this listing , he says `` each of the delegate instances has captured a different variable in this case . `` I understand this well enoug...
List < ThreadStart > list = new List < ThreadStart > ( ) ; for ( int index=0 ; index < 5 ; index++ ; ) { int counter = index*10 ; list.Add ( delegate { Console.WriteLine ( counter ) ; counter++ ; } ) ; } foreach ( ThreadStart t in list ) { t ( ) ; } list [ 0 ] ( ) ; list [ 0 ] ( ) ; list [ 0 ] ( ) ; list [ 1 ] ( ) ; .l...
In closure , what triggers a new instance of the captured variable ?
C#
So , I am writing this school project that should be some basic chat program that consists of a client and a server . I am trying to handle either the server or the client programs being closed.So when you press the big red X in the Client window , this is what happens : It sends a message to the server informing it th...
private void Window_Closing ( object sender , CancelEventArgs e ) { Data msgToSend = new Data ( ) ; msgToSend.cmdCommand = Command.Logout ; msgToSend.strName = LoginName ; byte [ ] b = msgToSend.ToByte ( ) ; ClientSocket.Send ( b ) ; }
C # Socket programming , closing windows
C#
I was trying to understand the answer for this question Why am I getting wrong results when calling Func < int > ? I wrote some sample code . The following code produces After reading the explanation by Jon Skeet and Eric Lippert I thought I will get Here both v and i are loop variables , while the value of i is picked...
public static void Main ( string [ ] args ) { var funcs = new List < Func < string > > ( ) ; for ( int v=0 , i=0 ; v < 3 ; v++ , i++ ) { funcs.Add ( new Func < string > ( delegate ( ) { return `` Hello `` + i++ + '' `` +v ; } ) ) ; } foreach ( var f in funcs ) Console.WriteLine ( f ( ) ) ; } Hello 3 3Hello 4 3Hello 5 3...
why this C # program outputs such a result ? How do I understand closure ?
C#
I want to make a list of pointers to locations that contains a certain value in the process memory of another process . The value can be a short , int , long , string , bool or something else . My idea is to use Generics for this . I have one problem with making it , how can I tell the compiler to what type he needs to...
public List < IntPtr > ScanProccessFor < T > ( T ItemToScanFor ) { List < IntPtr > Output = new List < IntPtr > ( ) ; IntPtr StartOffset = SelectedProcess.MainModule.BaseAddress ; int ScanSize = SelectedProcess.MainModule.ModuleMemorySize ; for ( int i = 0 ; i < ScanSize ; i++ ) if ( ReadMemory ( SelectedProcess , Star...
Compare byte [ ] to T
C#
I have a many-to-many relationship between tables of Games and Genres . During an analysis , i need to get items from Games that match specific criteria.The problem is , to check for this criteria , i need to analyse genres of this specific game . And linq wo n't let me do it.My request now looks like this : When I exe...
var result = GDB.Games.Where ( ( g ) = > g.GamesToGenres.Select ( ( gtg ) = > ( weights.ContainsKey ( gtg.Genre.Name ) ? weights [ gtg.Genre.Name ] :0.0 ) ) .Sum ( ) > Threshhold ) .ToArray ( ) ; Func < string , double > getW = ( name ) = > 1 ; var t = GDB.Games.Where ( ( g ) = > g.GamesToGenres.Select ( ( gtg ) = > ge...
Nested .Select ( ) inside of .Where ( )
C#
I have a struct that holds a single object field to make working with the object easier . I wanted to test the performance ( I expected some degradation ) , but I get very surprising results . The version with the struct actually is faster : Without box : 8.08 sWith box : 7.76 sHow is this possible ? Below is the compl...
using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Runtime.CompilerServices ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication68 { partial class Program { private const int Iterations = 100000000 ; static void Main ( string [ ] ar...
How can a struct with a single object field be faster than a raw object ?
C#
I 'm trying to create a string extension method with the following signature : I 'm getting a compiler error : Default parameter value for 'provider ' must be a compile-time constantCould n't find anything on google and my only work around is to do this : Anyone know how I can set the default value of IFormatProvider i...
public static DateTime ? TryParseExact ( this string src , string format , IFormatProvider provider = DateTimeFormatInfo.CurrentInfo , DateTimeStyles style = DateTimeStyles.None ) { } public static DateTime ? TryParseExact ( this string src , string format , IFormatProvider provider = null , DateTimeStyles style = Date...
Provide compile-time constant for IFormatProvider
C#
I have a line of code that is giving me an warning message ( CS0675 ) in VS2015 , but not in 2013 . Warning CS0675 Bitwise-or operator used on a sign-extended operand ; consider casting to a smaller unsigned type first . The compiler implicitly widened and sign-extended a variable , and then used the resulting value in...
shortValue |= ( short ) anEnum ;
Bug in compiler or misunderstanding ? Or operator on shorts
C#
I have a similar problem to the post Accessing a static property of a child in a parent method . The preferred answer hints that the design of the classes is faulty and more information is needed to discuss the problem . Here is the situation I want to discuss with you.I want to implement some unit aware datatypes like...
public class PhysicalQuantities { protected static Dictionary < string , double > myConvertableUnits ; public static double getConversionFactorToSI ( String baseUnit_in ) { return myConvertableUnits [ baseUnit_in ] ; } } public class Length : PhysicalQuantities { protected static Dictionary < string , double > myConver...
Accessing a static property of a child in a parent method - Design considerations
C#
I 'm refactoring a number of classes in an application to use interfaces instead of base classes . Here 's the interfaces I created so far : ICarryable implemented by all Item objects IActable implemented by all Actor objectsIUseable implemented by some Item sub-classesIWieldable implemented by some Item sub-classesYou...
public interface IUnnameable { event EventHandler < LocationChangedEventArgs > LocationChanged ; Location Location { get ; set ; } }
Need help choosing a name for an interface
C#
Is there a difference betweenAND ? If so , what ? Are n't they both just pointers to methods ?
Object.Event += new System.EventHandler ( EventHandler ) ; Object.Event -= new System.EventHandler ( EventHandler ) ; Object.Event += EventHandler ; Object.Event -= EventHandler ;
Wiring EventHandlers
C#
I have the following code that attempts to catch a null reference . It then throws an exception with a clearer reason for the error specified in the message property . What type of exception should it throw ? An IndexOutOfRangeException ? or a NullReferenceException ? or , should we have just let the exception run its ...
var existing = this.GetByItemId ( entity.ItemId ) ; // int or longif ( existing == null ) { throw new IndexOutOfRangeException ( `` The specified item does not exist . `` ) ; } var price = existing.Price ; var existing = this.GetByItemId ( entity.ItemId ) ; if ( existing == null ) { throw new NullReferenceException ( `...
IndexNotFoundException versus NullReferenceException
C#
I 'm developing an app that connects with WCF service to load data . I added a Web Service Reference directly from Visual Studio , and runs very well.But , my problem now is this : I have to connect with different WCF services depending the user who login app.Exists any way to doing this by code ? ? I 'm using a Xamari...
service = new ServicioWebClient ( binding , new EndpointAddress ( `` http : //myurl/wsdl '' ) ) ;
Multiple WCF connections in Xamarin Forms
C#
I have an MVC application with EF6 . Is there a way to automatically set all properties of a model to [ Required ] ? Some of our models are large with all required fields . Any way to save lines of code or make this cleaner ? Thanks
public class Employee { [ Required ] public string Name { get ; set ; } [ Required ] public string Address 1 { get ; set ; } [ Required ] public string Address 2 { get ; set ; } [ Required ] public int SSN { get ; set ; } [ Required ] public double PayRate { get ; set ; } [ Required ] public int PayType { get ; set ; }...
MVC model require all fields
C#
I know we can escape curly bracket in C # using { { and } } . But they do n't seem to work well if they are right after a format modifier ( like { 0 : F6 } ) .
string str ; // Prints `` { 3.14 } '' as expectedstr = string.Format ( `` { { { 0 } } } '' , 3.14 ) ; Console.WriteLine ( str ) ; // Expected `` { 3.140000 } '' , found `` { F6 } '' str = string.Format ( `` { { { 0 : F6 } } } '' , 3.14 ) ; Console.WriteLine ( str ) ;
C # escape curly bracket not working with format modifier ?
C#
I 'm looking for a way to implement something like this : Of course , I could define a conditional compilation symbol by myself , but it is n't suitable.Is there any built-in constant ? The questions I found are rather old . Maybe , the things were changed to the best ?
# if CSHARP_COMPILER_IS_FOR_CSHARP_6_OR_HIGHER foo ? .Bar ( ) ; # else if ( foo ! = null ) { foo.Bar ( ) ; } # endif
Conditional compilation depending on compiler version
C#
I have Kendo charts drawn on a page and I am posting their image data to an action to save this base64 encoded data to a ( SQL Server ) database . Here is the exportImage call in which I first split the base64 data from the dataURL : My Export_TargetPrice method is essentially just a call to Convert.FromBase64String an...
chart.exportImage ( { width : 727 , height : 262 } ) .done ( function ( data ) { // split 'image/png , xxxyyy= ' into two var dataParts = data.split ( ' , ' , 2 ) ; // TODO : need to strip from 'data : image/png ; base64 ' dataParts [ 0 ] = 'image/png ' ; $ .ajax ( { url : `` @ Url.Action ( `` Export_TargetPrice `` , `...
FromBase64String fails with Kendo charts
C#
I came across this code in which a variable is assigned to itself for no good reason.It is not making much sense to me . Is there a reason behind this ?
double x = x = ( a - b ) / ( c - 1 ) ;
What is the purpose of this : `` double x = x = ( a - b ) / ( c - 1 ) ; ''
C#
I wonder if there is a way of writing a method or a class that would add to any method some code that is shared between many methods . The methods return different things and some of them are just void.Below is a part of the code that is duplicated in the methods.Any help would be greatly appreciated.Nix solution appli...
StartTimer ( MethodBase.GetCurrentMethod ( ) .Name ) ; try { // Actual method body } catch ( Exception ex ) { bool rethrow = ExceptionPolicy.HandleException ( ex , `` DALPolicy '' ) ; if ( rethrow ) { throw ; } } finally { StopTimer ( MethodBase.GetCurrentMethod ( ) .Name ) ; } public T WrapMethod < T > ( Func < T > fu...
Is there a way of using one method to handle others to avoid code duplication ?
C#
I have the controller method GetLayer2 ( ) . It is extremely similar to GetLayer0 ( ) and GetLayer1 ( ) The code can be summed up as : Get the OrgCodeGet and parse the datePassedIn to the processDateUrlDecode the driverIdExecute a stored proc , putting the output in resultsConvert results to Json ( This was added to ai...
[ HttpGet ] public async Task < JsonResult > GetLayer2 ( string datePassedIn , string eventType , string driverId ) { string orgCode = `` HVO '' ; //User.Identity.GetOrgCode ( ) ; DateTime ? processDate ; DateTime defaultDate = DateTime.Today.AddDays ( -1 ) ; //default yesterday if ( String.IsNullOrEmpty ( datePassedIn...
MVC JsonResult has data , but browser has none
C#
In .Net , is there a way to convert , say , ' 2:45 ' to the decimal 2.75 ? ex : It should throw an exception if invalid data , ex , minutes < 0 < 60 or not in the h : m format.Thanks
decimal d = TimeToDecimal ( `` 2:45 '' ) ; Console.WriteLine ( d ) ; //output is 2.75
Parse time string to decimal ?
C#
These two statements look the same logically to me , but they 're resulting in different SQL being generated : Example # 1 does n't work , but example # 2 does.The generated SQL for the var people query is identical for both , but the SQL in the final query differs like this : Why is there this difference ? Edit : Up u...
# 1 var people = _DB.People.Where ( p = > p.Status == MyPersonEnum.STUDENT.ToString ( ) ) ; var ids = people.Select ( p = > p.Id ) ; var cars = _DB.Cars.Where ( c = > ids.Contains ( c.PersonId ) ) ; # 2 string s = MyPersonEnum.STUDENT.ToString ( ) ; var people = _DB.People.Where ( p = > p.Status == s ) ; var ids = peop...
What 's the difference between these two LINQtoSQL statements ?
C#
I 'm interpreting an exception report from a C # Windows Phone app . A method throws a NullReferenceException . The method goes : It 's consistent with m_Field being null - there 's simply nothing else there that can possibly be null . But here 's the mysterious part.The GetILOffset ( ) from the StackFrame from the Sta...
public void OnDelete ( object o , EventArgs a ) { if ( MessageBox.Show ( Res.IDS_AREYOUSURE , Res.IDS_APPTITLE , MessageBoxButton.OKCancel ) == MessageBoxResult.OK ) m_Field.RequestDelete ( ) ; } IL_0000 : call string App.Res : :get_IDS_AREYOUSURE ( ) IL_0005 : call string App.Res : :get_IDS_APPTITLE ( ) IL_000a : ldc....
NullReferenceException vs. MSIL
C#
Trying to follow the hints laid out here , but she does n't mention how to handle it when your collection needs to return a value , like so : This obviously wo n't work , because dispatcher.BeginInvoke does n't return anything . What am I supposed to do ?
private delegate TValue DequeueDelegate ( ) ; public virtual TValue Dequeue ( ) { if ( dispatcher.CheckAccess ( ) ) { -- count ; var pair = dict.First ( ) ; var queue = pair.Value ; var val = queue.Dequeue ( ) ; if ( queue.Count == 0 ) dict.Remove ( pair.Key ) ; OnCollectionChanged ( new NotifyCollectionChangedEventArg...
Returning objects from another thread ?
C#
Can we make a property of a class visible to public , but can only be modified by some specific classes ? for example , Child is a data class , Parent is a class that can modify data , Cat is a class that can only read data.Is there any way to implement such access control using Property in C # ?
// this is the property holderpublic class Child { public bool IsBeaten { get ; set ; } } // this is the modifier which can set the property of Child instancepublic class Father { public void BeatChild ( Child c ) { c.IsBeaten = true ; // should be no exception } } // this is the observer which can get the property but...
how to implement selective property-visibility in c # ?
C#
Suppose I want to write an extension method to dump some data from a T [ , ] to a CSV : which I could call withbut suppose myData is a Complex [ , ] and I want to write the magnitude of the complex number , not the full value . It would be handy if I could write : but I 'm not sure how to implement that in the extensio...
public static void WriteCSVData < T > ( this T [ , ] data , StreamWriter sw ) { for ( int row = 0 ; row < data.GetLength ( 0 ) ; row++ ) for ( int col = 0 ; col < data.GetLength ( 1 ) ; col++ ) { string s = data [ row , col ] .ToString ( ) ; if ( s.Contains ( `` , '' ) ) sw.Write ( `` \ '' '' + s + `` \ '' '' ) ; else ...
Lambda in C # extension method
C#
How is the below code is printing true ? I expected this to print False , because I expected two separate objects to be constructed and then their references compared .
string x = new string ( new char [ 0 ] ) ; string y = new string ( new char [ 0 ] ) ; Console.WriteLine ( object.ReferenceEquals ( x , y ) ) ;
Object.ReferenceEquals prints true for two different objects
C#
I 'd like to know how best to program three different editions of my C # ASP.NET 3.5 application in VS2008 Professional ( which includes a web deployment project ) .I have a Light , Pro and Ultimate edition ( or version ) of my application.At the moment I 've put all in one solution with three build versions in configu...
# if light//light code # endif # if pro//pro code # endif //etc ...
How to program three editions Light , Pro , Ultimate in one solution
C#
After migrating to ASP.NET Core 2.1 we have realized that some consumers of our API are sending GET requests with the Content-Type header set to application/json . Sadly , these requests have not been rejected in the past ( even though they should have ) , nevertheless this still is a breaking change..Since our consume...
[ Route ( `` api/file/ { id : guid } '' ) ] public async Task < IActionResult > Get ( Guid id ) { // Some simple code here } [ HttpGet ( `` api/file/ { id : guid } '' ) ] public async Task < IActionResult > Get ( [ FromRoute ] Guid id ) { // Some simple code here } $ ch = curl_init ( self : :API_URL . `` /file/ '' . $ ...
How to accept a bodyless GET request with JSON as it 's content type ?
C#
Considering the following : It is clear that you would say BudgetView extends ViewBase , and it implements IView , but what does it to to poor old Export ? Perhaps BudgetView uses Export ? Or BudgetView applies Export ? I need this for my documentation . I 'm need to be very formal and very detailed.Edit : My UML tool ...
[ Export ] public class BudgetView : ViewBase , IView { // Members Galore }
What verb would describe the relationship between a C # class and its Attribute ?
C#
If I have a model with a key of type Guid , is it bad practise to set the ID explicitly in the constructor ? I know it will be set implicitly by Entity Framework , but will anything bad happen ( perhaps performance wise ) from setting it explicitly ? Example : I 'm thinking a Guid is backed up by a sequential ID in SQL...
class MyModel { public MyModel ( ) { Id = Guid.NewGuid ( ) ; } [ Key ] public Guid Id { get ; set ; } }
Is instantiating a GUID in Entity Framework Core bad practice ?
C#
I need to create a Type instance for an array of a base type with a specified number of indexes . Essentially I need to method like the following that I can call ... So that calling the function would give the following result ... The only solution I can come up with is the following ... This does work but having to cr...
public Type GetArrayOfType ( Type baseType , int numOfIndexes ) { return /* magic does here */ } GetTypeArray ( typeof ( bool ) , 1 ) == typeof ( bool [ ] ) GetTypeArray ( typeof ( bool ) , 2 ) == typeof ( bool [ , ] ) GetTypeArray ( typeof ( bool ) , 3 ) == typeof ( bool [ , , ] ) public Type GetArrayOfType ( Type bas...
How to get the Type that describes an array of a base type ?
C#
I need to distribute a set of data evenly over time based on historical data such that each digit appears an equal ( or close to equal ) number of times in each position over time . The problem is , given a list of orderings used in the past , that look like this ( but could have any number of elements ) : how can I fi...
1,2,5,3,44,1,5,2,31,3,5,2,44,1,2,3,52,4,1,3,55,1,4,3,21,5,3,2,45,1,3,2,43,2,5,4,14,3,1,5,2
Finding the least-used permutation
C#
I have a code like this : We can notice some boring repetition in the code.So , it would be nice to write a generic method Update in a way we can afford ourselves to write something like this : Tell me , please , is it possible to write such a method ? Which book can I learn that from ? ( I have found only one close ex...
class PacketDAO { // ... public void UpdatePacketStatus ( Guid packetID , Status status ) { using ( var ctx = new DataContext ( ) ) { var packet = ctx.Packet.SingleOrDefault ( p = > p.PacketID == packetID ) ; packet.Status = status ; ctx.SubmitChanges ( ) ; } } public void UpdatePacketTime ( Guid packetID , DateTime ? ...
How to define my own LINQ construct in C # ?
C#
suppose I have : processing may take a long time and while it was in the middle another packet has arrived . What happens next : the processing gets done and then another event is fired or perhaps new event is fired immediately but on a new thread ?
ethernet_adapter.PacketArrived += ( s , e ) = > { //long processing ... } ;
events and threading
C#
As I am developing my small game , I have made a lot of progress yet frustrated about a lot of things . The latest thing was creating a list of required items and for you to understand that I will provide you with both Explanation as well as Code which I created but obviously does n't work ... I - ExplanationIn order f...
//Available Main Elements var carbon = new Element { Name = `` Carbon '' } ; var hydrogen = new Element { Name = `` Hydrogen '' } ; var oxygen = new Element { Name = `` Oxygen '' } ; var nitrogen = new Element { Name = `` Nitrogen '' } ; //Example Researchvar steam = new Research ( name : `` Steam '' , requiredElements...
Creating a tree of required items
C#
I have function like this : Everything is good , except that it complains about return null ; part Can not convert expression type 'null ' to type 'T'How do I return null from function like this ?
private T DeserializeStream < T > ( Stream data ) where T : IExtensible { try { var returnObject = Serializer.Deserialize < T > ( data ) ; return returnObject ; } catch ( Exception ex ) { this.LoggerService.Log ( this.AccountId , ex ) ; } return null ; }
How do I return null from generic function ?
C#
I have a simple ViewComponent works correctly in the browser chrome and Firefox but do not work in a browser Edge \ IE 11.The component shows the time ( just for example ) .Chrome and firefox time is displayed.Edge Browser \ IE 11 , time is displayed only the first time the page is up and remains so , time is `` frozen...
public IActionResult GetTime ( ) { return ViewComponent ( `` GetTime '' ) ; //// var time = DateTime.Now.ToString ( `` h : mm : ss '' ) ; //// return Content ( $ '' The current time is { time } '' ) ; } public class GetTimeViewComponent : ViewComponent { public IViewComponentResult Invoke ( ) { var model = new string [...
Rendering ViewComponent with ajax do n't work in Edge/IE11
C#
I am using .net core 3.1 . With the help of docker I uploaded my code to heroku . but when i make a web request I get a 405 error with all my endpoints . ( I cant see more details of the error ) using Get : from visual studio code and also locally from my IIS everything works fine . but the problem occurs when I deploy...
http : //xxxx.herokuapp.com/api/pqrs/test/1315315 using System ; using System.Collections.Generic ; using System.IdentityModel.Tokens.Jwt ; using System.Linq ; using System.Security.Claims ; using System.Text ; using System.Threading.Tasks ; using apiPQR.Contexts ; using apiPQR.Entities ; using apiPQR.Models ; using Mi...
Deploy ASP.NET Core Docker project - get a 405 error ( locally in my IIS , web requests works ) . How to fix it ?
C#
The best way I can describe what I 'm trying to do is `` Nested DistinctBy '' .Let 's say I have a collection of objects . Each object contains a collection of nicknames.I want to select all Persons but make sure nobody selected shares a nickname with another . Molly and Steve both share the nickname 'Lefty ' so I want...
class Person { public string Name { get ; set ; } public int Priority { get ; set ; } public string [ ] Nicknames { get ; set ; } } public class Program { public static void Main ( ) { var People = new List < Person > { new Person { Name = `` Steve '' , Priority = 4 , Nicknames = new string [ ] { `` Stevo '' , `` Lefty...
How Can I Achieve this Using LINQ ?
C#
I am working on some code which is something like this : Someclass contains the required constructor.The code for this compiles fine without any warning . But I get a code hazard in system : `` The Someclass ctor has been called from static constructor and/or static initialiser '' This code hazard part of system just t...
class A { static SomeClass a = new Someclass ( `` asfae '' ) ; }
Static variable initialization using new gives a code hazard
C#
This is a followup to this question : Why does a division result differ based on the cast type ? Quick Summary : The question is : Why are the results different depending on the cast type ? While working out an answer I ran into an issue I was n't able to explain.This outputs the following : Breaking it down in IEEE 75...
byte b1 = ( byte ) ( 64 / 0.8f ) ; // b1 is 79int b2 = ( int ) ( 64 / 0.8f ) ; // b2 is 79float fl = ( 64 / 0.8f ) ; // fl is 80 var bytes = BitConverter.GetBytes ( 64 / 0.8f ) .Reverse ( ) ; // Reverse endiannessvar bits = bytes.Select ( b = > Convert.ToString ( b , 2 ) .PadLeft ( 8 , ' 0 ' ) ) ; Console.WriteLine ( s...
Why does a division result differ based on the cast type ? ( Followup )
C#
I 'm working on a library that simplifies application configuration . Essentially , consumers of the library either decorate their configuration classes with attributes or they initialize the settings declaratively in code . It would be possible to specify 1 or more sources from which to read/write configuration proper...
[ ConfigurationNamespace ( DefaultAccessors = new Type [ ] { typeof ( AppSettingsAccessor ) } ) ] public class ClientConfiguration : Configuration < IClientConfiguration > { [ ConfigurationItem ( Accessors = new Type [ ] { typeof ( ( RegistryAccessor ) ) } ) ] public bool BypassCertificateVerification { get ; set ; } }...
Best practices for DI in a library involving Types in attributes
C#
I seem to be getting different results when filtering . I expect the same result from these two pieces of code : I am trying to find items which have the same name as my firstGuess.Method A works as expected , but B seems to give me a odd result in that ! matches2.any ( ) returns false , when I would expect true.Tested...
Sitecore.Data.Items.Item firstGuess = Sitecore.Context.Database.GetItem ( mediaPath ) ; var matches = new List < Item > ( ) ; //Method Aforeach ( var child in firstGuess.Parent.Children.InnerChildren ) { if ( child.DisplayName == firstGuess.DisplayName ) { matches.Add ( child ) ; } } //Matches.count = 2//Method Bvar ma...
Why am I getting different results filtering with foreach vs LINQ .Where ( ) ?