lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
C#
I have run some tests on the new spatial library SqlGeography in SQL Server 2016 , which according to Microsoft should be a lot faster than the previous versions : SQL Server 2016 – It Just Runs Faster : Native Spatial Implementation ( s ) . Apply SQL Server 2016 and a breadth of methods and spatial activities are fast...
var line1 = CreateLine ( 56 , -4 , 58 , 16 ) ; var line2 = CreateLine ( 58 , -4 , 56 , 16 ) ; for ( int i = 0 ; i < 50000 ; i++ ) { var intersection = line1.STIntersects ( line2 ) ; var contains = line1.STBuffer ( 1000 ) .STContains ( line1 ) ; } public static SqlGeography CreateLine ( double fromLat , double fromLon ,...
SqlGeography spatial operations slow - SQL Server 2016
C#
Exhibit 1 : some code wrapping an Async ( not async ! ) network call into a TaskInstalling .Net 4.5 ( not pointing VS at it , nor recompiling ) stops this working . The callback is never invoked.Any ideas what could be causing this , and otherwise , what I can do to try and further narrow down the root cause of the pro...
public static Task < byte [ ] > GetAsync ( IConnection connection , uint id ) { ReadDataJob jobRDO = new ReadDataJob ( ) ; //No overload of FromAsync takes 4 extra parameters , so we have to wrap // Begin in a Func so that it looks like it takes no parameters except // callback and state Func < AsyncCallback , object ,...
.Net 4.5 killed my TPL , now what ?
C#
I try to get a data record ID from Entity Framework : The problem is , that there is a PlantArea with the ID 0 . SingleOrDefault returns 0 , though , if it does n't find any record . So how can I differenciate between ID 0 and the case , where no data was found ? My first idea was to provide a default value -1 , but Si...
var plantAreaID = await db.PlantAreas .Where ( p = > p.Plant.CompanyNo == companyNo & & p.Plant.Abbreviation == companyAbbr ) .Select ( p = > p.ID ) .SingleOrDefaultAsync ( ) ;
Define default value for SingleOrDefault Linq method
C#
Assume I have an array of bytes which are truly random ( e.g . captured from an entropy source ) . Now , I want to get a random double precision floating point value , but between the values of 0 and positive 1 ( like the Random.NextDouble ( ) function performs ) .Simply passing an array of 8 random bytes into BitConve...
byte [ ] myTrulyRandomBytes = MyEntropyHardwareEngine.GetBytes ( 8 ) ;
Get random double ( floating point ) value from random byte array between 0 and 1 in C # ?
C#
I have a KeyPressed signal in Gtk # /mono C # for two different purposes which are not present in the default TreeView : a ) go to the next cell by pressing TAB , and b ) start editing by pressing any key.The TreeView is simple , it has a ListStore showing only rows and columns , i.e . it holds tabular data.The code I ...
[ GLib.ConnectBefore ] protected void OnTableKeyPressed ( object o , Gtk.KeyPressEventArgs args ) { int rowIndex ; int colIndex ; // Do not `` eat '' the key , by default args.RetVal = false ; // Get the current position , needed in both cases . this.GetCurrentCell ( out rowIndex , out colIndex ) ; // Adapt the column ...
How to manage key pressings for special purposes in Gtk # TreeView ?
C#
I have a WPF application that does a lot of matching across large datasets , and currently it uses C # and LINQ to match POCOs and display in a grid . As the number of datasets included has increased , and the volume of data has increased , I 've been asked to look at performance issues . One of the assumptions that I ...
public class CsClassWithProps { public CsClassWithProps ( ) { CreateDate = DateTime.Now ; } public long Id { get ; set ; } public string Name { get ; set ; } public DateTime CreateDate { get ; set ; } } static void CreateCppObjectWithMembers ( ) { List < CppClassWithMembers > results = new List < CppClassWithMembers > ...
Differences Between Output of C # Compiler and C++/CLI Compiler
C#
Say I have the following class definitions : If I would want to do the work done in DoWork ( ) , on the form , asynchronously I could add a method ( GetCalculationTask ) that returns a task using Task.Run ( ) and add a async eventhandler i.e . For a button ( MethodOne ) . Please correct me if I 'm wrong , but it seems ...
public class Calculator { public CalculatorResult Calculate ( ) { return LongRunningCalculation ( ) ; } private CalculatorResult LongRunningCalculation ( ) { return new CalculatorResult ( 0.00 ) ; } } public class ClassThatUsesACalculator { private readonly Calculator calculator ; public ClassThatUsesACalculator ( ) { ...
Best practice on using async / await
C#
I have following code in c # In this case I am getting 0 and 3 but in the following case I am getting 3,3 why is it so ?
class Test { public static int X = Y ; public static int Y = 3 ; } static void Main ( ) { Console.WriteLine ( Test.X ) ; Console.WriteLine ( Test.Y ) ; } class Test { public static int X = 3 ; public static int Y = X ; } static void Main ( ) { Console.WriteLine ( Test.X ) ; Console.WriteLine ( Test.Y ) ; }
Static field initializers in c #
C#
I 'm trying to trim a string with String.Trim : But I 'm getting the result of : Instead of : I also tried using : But it still returns the same result.Also if I do : I get : I 'm really confused why this is happening . Could it be because the semicolon is not the last character in the string ? Here is the full code : ...
split [ 2 ] .Trim ( ' ; ' ) System ; System split [ 2 ] .TrimEnd ( ' ; ' ) split [ 2 ] .Trim ( 'S ' , ' ; ' ) ystem ; string line = @ '' using System ; using System.Windows.Forms ; class HelloWorld { static void Main ( ) { # if DebugConfig Console.WriteLine ( `` WE ARE IN THE DEBUG CONFIGURATION '' ) ; # endif Console....
Why is String.Trim not trimming a semicolon ?
C#
With the new C # 8 Using Declaration Syntax , what is containing scope of a second consecutive using statement ? TL ; DRPrevious to C # 8 , having a consecutive using statement like : would expand to something like the following ( My Source ) : I know that there are two other possible expansions but they all are roughl...
using ( var disposable = new MemoryStream ( ) ) { using ( var secondDisposable = new StreamWriter ( disposable ) ) { } } MemoryStream disposable = new MemoryStream ( ) ; try { { StreamWriter secondDisposable = new StreamWriter ( disposable ) ; try { { } } finally { if ( secondDisposable ! = null ) ( ( IDisposable ) sec...
C # 8 Using Declaration Scope Confusion
C#
Short and simple . Does the new string interpolation in C # 6.0 rely on reflection ? I.e . doesuse reflection at runtime to find the variable `` name '' and its value ?
string myStr = $ '' Hi { name } , how are you ? `` ;
Does C # 6.0 's String interpolation rely on Reflection ?
C#
When I use Entity Framework against a SQL table , it only refers to the necessary columns in the generated SQL : becomesHowever , if I make an analogous query against a SQL view , Entity Framework generates SQL referring to every column in the view : becomesI 'm sure SQL Server will perform its own optimization to end ...
ctx.Types.Select ( rdi = > rdi.Name ) SELECT [ Extent1 ] . [ Name ] AS [ Name ] FROM [ dbo ] . [ Types ] AS [ Extent1 ] ViewTypes.Select ( rdi = > rdi.Name ) SELECT [ Extent1 ] . [ Name ] AS [ Name ] FROM ( SELECT [ ViewTypes ] . [ Name ] AS [ Name ] , ... every other column in my view ... FROM [ dbo ] . [ ViewReferenc...
Entity Framework selects too many columns in views
C#
Quick Question , See this code : And : Why result.Add ( value ) not executed ? However this not executed , Another question that is have a way do a foreach on a IEnumerable with Extention Method ? Except this way : IEnumerable.ToList ( ) .Foreach ( p= > ... )
List < int > result = new List < int > ( ) ; var list = new List < int > { 1 , 2 , 3 , 4 } ; list.Select ( value = > { result.Add ( value ) ; //Does not work ? ? return value ; } ) ; result.Count == 0 //true
Foreach with Extension Method on IEnumerable
C#
This works perfectly.. This returns a compiler error ... Same happen when using reflection ... So , does somebody know why the enum-base is just an integral-type ?
public enum NodeType : byte { Search , Analysis , Output , Input , Audio , Movement } public enum NodeType : Byte { Search , Analysis , Output , Input , Audio , Movement }
Why can you use just the alias to declare a enum and not the .NET type ?
C#
I came across this line of code in a book : This sort of thing seems like tail-chasing to me ... Why is the c = > c. necessary ? Would n't the following be understandable ( by the compiler , and even more so by humans ) ? I 'm sure there 's all kinds of fancy stuff going on behind the scenes that purportedly needs this...
var data = db.Query ( sql ) .OrderByDescending ( c = > c.DatePosted ) ; var data = db.Query ( sql ) .OrderByDescending ( DatePosted ) ;
Why do lambdas require = > as part of their syntax ?
C#
Recently I moved from VB to C # , so I often use a C # to VB.NET converter to understand syntax differences.While moving next method to VB I noticed an interesting thing.C # original code : VB.NET result : C # 's ++ operator replaced with System.Threading.Interlocked.IncrementDoes it mean that not threadsafe ++ operato...
public bool ExceedsThreshold ( int threshold , IEnumerable < bool > bools ) { int trueCnt = 0 ; foreach ( bool b in bools ) if ( b & & ( ++trueCnt > threshold ) ) return true ; return false ; } Public Function ExceedsThreshold ( threshold As Integer , bools As IEnumerable ( Of Boolean ) ) As BooleanDim trueCnt As Integ...
Does C # ++ operator become threadsafe in foreach loop ?
C#
I know how to use locks in my app , but there still few things that I do n't quite understand about locking ( BTW - I know that the lock statement is just a shorthand notation for working with Monitor class type ) .From http : //msdn.microsoft.com/en-us/library/ms173179.aspx : The argument provided to the lock keyword ...
public class TestThreading { private System.Object lockThis = new System.Object ( ) ; public void Function ( ) { lock ( lockThis ) { // Access thread-sensitive resources . } } } public class TestThreading { private System.Object lockThis = new System.Object ( ) ; public static void Function ( ) { lock ( new TestThreadi...
Few confusing things about locks
C#
I find myself quite often in the following situation : I have a user control which is bound to some data . Whenever the control is updated , the underlying data is updated . Whenever the underlying data is updated , the control is updated . So it 's quite easy to get stuck in a never ending loop of updates ( control up...
public partial class View : UserControl { private Model model = new Model ( ) ; public View ( ) { InitializeComponent ( ) ; } public event EventHandler < Model > DataUpdated ; public Model Model { get { return model ; } set { if ( value ! = null ) { model = value ; UpdateTextBoxes ( ) ; } } } private void UpdateTextBox...
Event circularity
C#
I need an idea how to do the following animation idea . Lets assume I have a view model defined as such : The IPage object is , plainly spoken , a piece of paper with the title and the description written on it . When the IPage object changes in my view model I want to have an animation as outlined below : The paper sh...
public interface IMyViewModel { IPage CurrentPage { get ; set ; } } public interface IPage { string Title { get ; set ; } string Description { get ; set ; } }
WPF animation idea for flipping a page
C#
I was tasked with converting a solution from VB to C # . There were 22 projects and hundreds of classes , so I decided to research converters . I finally settled on SharpDevelop , which is an IDE with an included converter . I ran it on each of my projects , and have plenty of errors to fix , but I should be able to go...
-- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- line 0 col 0 : Case labels with binary operators are unsupported : Equality -- l...
Converting from VB to C #
C#
I have list object 's . But it has duplicate records for 2 key - itemId and itemTypeId . How do I remove duplicates from the list ? I tried GroupBy - but it can only use one key at a time.Actual Result : to1 and to3
public class TestObject { public string Name ; public int itemTypeId ; public int itemId ; public int id ; } List < TestObject > testList = new List < TestObject > ( ) ; TestObject to1 = new TestObject ( ) ; TestObject to2 = new TestObject ( ) ; TestObject to3 = new TestObject ( ) : to1.id = 1 ; to1.itemId = 252 ; to1....
How to remove duplicate object in List with double key
C#
I have two methods ( in C # ) : These operations have no common objects ( aside from the pizzas that are passed from one to the other ) , and are thread-safe . They each take several seconds to execute and they each use different resources ( oven vs car ) . As such , I want to run them at the same time.How do I organiz...
List < Pizza > CookPizza ( List < Order > ) ; List < HappyCustomers > DeliverPizza ( List < Pizza > ) ;
Pizza , Threading , Waiting , Notifying . What does it mean ?
C#
I was writing some unit tests for a utility library when I came across a test I would expect to fail that actually passed . The issue is related to comparing two float variables , versus comparing one float ? and one float variable.I 'm using the latest versions of both NUnit ( 2.6.0.12051 ) and FluentAssertions ( 1.7....
using FluentAssertions ; using FluentAssertions.Assertions ; using NUnit.Framework ; namespace CommonUtilities.UnitTests { [ TestFixture ] public class FluentAssertionsFloatAssertionTest { [ Test ] public void TestFloatEquality ( ) { float expected = 3.14f ; float notExpected = 1.0f ; float actual = 3.14f ; actual.Shou...
Is this a bug when comparing a nullable type with its underlying type using FluentAssertions ?
C#
I have a list of prime numbers up to 2 000 000 . That 's a list containing almost 150 000 very large integers . I want a sum of all the numbers in it . Here 's a random list of large integers just for demonstration : I 'm getting a `` Arithmetic operation resulted in an overflow '' exception . I guess the sum is too la...
List < int > numbers = new List < int > ( ) ; for ( int i = 0 ; i < 100 ; i++ ) { numbers.Add ( 1000000000 ) ; } Console.WriteLine ( numbers.Sum ( ) .ToString ( ) ) ; Console.WriteLine ( Convert.ToUInt64 ( numbers.Sum ( ) ) .ToString ( ) ) ; long sum = numbers.Sum ( ) ; Console.WriteLine ( sum.ToString ( ) ) ;
List sum too large , throwing overflow exception
C#
I 'm using an ActiveDirectory server to query the groups that a user belongs to . I would like to get all the groups that a user belongs to , but using the Network Management funcions of the Network API.I realized that already exist a function called NetUserGetGroups , but unfortunately , this function does not include...
MyGroup1 |_ MyGroup2 |_ MyUser MyGroup2 public static List < string > GetUserGroupsAD ( string dc , string userName ) { var result = new List < string > ( ) ; try { using ( var context = new PrincipalContext ( ContextType.Domain , dc.Replace ( `` \\ '' , `` '' ) ) ) { var user = UserPrincipal.FindByIdentity ( context ,...
How to get user 's groups using the Network API
C#
I 'm creating a chain of responsibility pipeline using System.Func < T , T > where each function in the pipeline holds a reference to the next.When building the pipeline , I 'm unable to pass the inner function by reference as it throws a StackOverflowException due to the reassignment of the pipeline function , for exa...
Func < string , Func < string , string > , string > handler1 = ( s , next ) = > { s = s.ToUpper ( ) ; return next.Invoke ( s ) ; } ; Func < string , string > pipeline = s = > s ; pipeline = s = > handler1.Invoke ( s , pipeline ) ; pipeline.Invoke ( `` hello '' ) ; // StackOverFlowException Func < string , Func < string...
Chain of responsibility using Func
C#
Hi lets say i have tree of following typelets say root of the tree is I know it is possible to check length of this tree using recursionbut is this possible to check length of this tree using linq ?
public class Element { public List < Element > element ; } Element root = GetTree ( ) ;
Checking length of tree using linq
C#
I 'm trying to create a binding from code in a library that targets multiple frameworks ( WPF , WinRT , UWP etc ) , and I 'm hitting a brick wall . The property I 'm trying to bind to is a custom attached property . In WPF , I can pass the DependencyProperty itself as the binding path : But in WinRT the PropertyPath cl...
new PropertyPath ( MyClass.MyAttachedProperty ) new PropertyPath ( `` ( MyClass.MyAttachedProperty ) '' )
Binding from code to a custom attached property in WinRT/UWP
C#
I am new to MVC and started with MVC 4 . I want to make an online shop application.-Same shopping logic will be used by two different web sites/domains.-And the views must alter according to domain name and their mobile versions.Logic file structe is like this : View file structure for first domain : View file structur...
Controllers/HomeController.csControllers/ProductController.csModels/Home.csModels/Product.cs Views/my_1st_Domain/Home/Index.cshtmlViews/my_1st_Domain/Home/Index.Mobile.cshtmlViews/my_1st_Domain/Home/Terms.cshtmlViews/my_1st_Domain/Home/Terms.Mobile.cshtmlViews/my_1st_Domain/Product/Index.cshtmlViews/my_1st_Domain/Produ...
MVC 4 same logic with different view folders
C#
We are using System.Linq.Expressions.Expression to build custom expressions which are applied on the .Where ( ) of our IQueryable.What I want to achieve is , to apply the .HasFlag ( ) method ( introduced in EF 6.1 ) on the property which is then used in the .Where ( ) expression.I have following code : The value of pro...
var memberExpression = propertyExpression as MemberExpression ; var targetType = memberExpression ? .Type ? ? typeof ( decimal ? ) ; var value = Enum.Parse ( type , searchValue ) ; var hasFlagMethod = targetType.GetMethod ( nameof ( Enum.HasFlag ) ) ; var hasFlagExpression = Expression.Call ( propertyExpression , hasFl...
LINQ to Entities does not recognize the method 'Boolean HasFlag ( System.Enum ) ' when creating the expression via System.Linq.Expressions.Expression
C#
According to MSDN , Environment.StackTrace can throw ArgumentOutOfRangeException but I do n't understand how this is possible.Environment.cs StackTrace ( source ) Calls GetStackTrace ( Exception , bool ) where Exception is null.Environment.cs GetStackTrace ( Exception , bool ) ( source ) ( comments removed , they are i...
public static String StackTrace { [ System.Security.SecuritySafeCritical ] get { Contract.Ensures ( Contract.Result < String > ( ) ! = null ) ; new EnvironmentPermission ( PermissionState.Unrestricted ) .Demand ( ) ; return GetStackTrace ( null , true ) ; } } internal static String GetStackTrace ( Exception e , bool ne...
How can Environment.StackTrace throw ArgumentOutOfRangeException ?
C#
I 'm implementing some real-time charts in a C # WPF application , but am using WinForms charts as they are generally easy to work with and are surprisingly performant.Anyway , I 've got the charts working just fine except for one major issue which I ca n't for the life of me figure out : When I add data to the chart ,...
< WindowsFormsHost Grid.Row= '' 1 '' Grid.ColumnSpan= '' 2 '' Margin= '' 5 '' > < winformchart : Chart Dock= '' Fill '' x : Name= '' Session0Chart '' > < winformchart : Chart.ChartAreas > < winformchart : ChartArea/ > < /winformchart : Chart.ChartAreas > < /winformchart : Chart > < /WindowsFormsHost > // initialize it ...
How to cure C # winforms chart of the wiggles ?
C#
It is possible to register dependencies manually : When there are too much dependencies , it becomes difficult to register all dependencies manually.What is the best way to implement a convention based binding in MVC 6 ( beta 7 ) ? P.S . In previous projects I used Ninject with ninject.extensions.conventions . But I ca...
services.AddTransient < IEmailService , EmailService > ( ) ; services.AddTransient < ISmsService , SmsService > ( ) ;
Convention based binding in ASP.NET 5 / MVC 6
C#
WCF makes it easy to call services synchronously or asynchronously , regardless of how the service is implemented . To accommodate clients using ChannelFactory , services can even define separate sync/async contract interfaces . For example : This allows the client to reference either contract version , and WCF transla...
public interface IFooService { int Bar ( ) ; } [ ServiceContract ( Name = `` IFooService '' ) ] public interface IAsyncFooService { Task < int > BarAsync ( ) ; }
Unit-test WCF contracts match for sync / async ?
C#
I have been handing the closing and aborting of channels this way : Assume only a single thread uses the channel . How do we know the channel will not fault right after checking the state ? If such a thing were to happen , the code would try to Close ( ) and Close ( ) will throw an exception in the finally block . An e...
public async Task < MyDataContract > GetDataFromService ( ) { IClientChannel channel = null ; try { IMyContract contract = factory.CreateChannel ( address ) ; MyDataContract returnValue = await player.GetMyDataAsync ( ) ; channel = ( IClientChannel ) ; return returnValue ; } catch ( CommunicationException ) { // ex han...
Is it possible for a WCF channel to fault right after checking the state ( single thread ) ?
C#
How would you create a Class that whichever class extends the Class , methods are automatically invoked/called . Just edit my question if it sounds misleading . I 'll just showcase some samplesExample 1 : In unity when you extend monobehavior your methods are automatically called . I do n't know if I 'm right . on libg...
public class MyController : MonoBehaviour { void Start ( ) { //Being Called Once } void FixedUpdate ( ) { //Being Called every update } Game implements ApplicationListener { @ Override public void render ( ) { //Called multiple times } } public abstract Test { protected Test ( ) { onStart ( ) ; } public abstract void o...
Calling methods from a super class when a subclass is instantiated
C#
I have the following code which is in a transaction . I 'm not sure where/when I should be commiting my unit of work.On purpose , I 've not mentioned what type of Respoistory i 'm using - eg . Linq-To-Sql , Entity Framework 4 , NHibernate , etc.If someone knows where , can they please explain WHY they have said , where...
using ( TransactionScope transactionScope = new TransactionScope ( TransactionScopeOption.RequiresNew , new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted } ) ) { _logEntryRepository.InsertOrUpdate ( logEntry ) ; //_unitOfWork.Commit ( ) ; // Here , commit # 1 ? // Now , if this log entry was a Ne...
At which line in the following code should I commit my unit of work ?
C#
Given the following method : This works if I call it passing a array of strings : But will not work if I call it using string arguments : I understand that the compiler will wrap Michael and Jordan on an array , so should n't the results be the same on both cases ?
static void ChangeArray ( params string [ ] array ) { for ( int i = 0 ; i < array.Length ; i++ ) array [ i ] = array [ i ] + `` s '' ; } string [ ] array = { `` Michael '' , `` Jordan '' } // will become { `` Michaels '' , `` Jordans '' } ChangeArray ( array ) ; string Michael = `` Michael '' ; string Jordan = `` Jorda...
C # Inconsistent results using params keyword
C#
I was just looking at the question `` SubQuery using Lambda Expression '' and wondered about compiler optimization of Linq predicates.Suppose I had a List < string > called names , and I was looking for the items with the shortest string length . So we have the query names.Where ( x = > x.Length == names.Min ( y = > y....
int i = 0 ; return names.Where ( x = > x.Length == names.Min ( y = > ++i ) ) ; int minLength = names.Min ( y = > y.Length ) ; return names.Where ( x = > x.Length == minLength ) ; List < string > names = new List < string > ( new [ ] { `` r '' , `` abcde '' , `` bcdef '' , `` cdefg '' , `` q '' } ) ; return names.Where ...
In a Linq predicate , will the compiler optimize a `` scalar '' call to Enumerable.Min ( ) or will it be called for each item ?
C#
I have two questions : Question 1 Background : I noticed when looking at the implementation of 'AsEnumerable ( ) ' method in LINQ from Microsoft , which was : Question 1 : I was expecting some kind of casting or something here , but it simply returns the value it was passed . How does this work ? Question 2/3 Backgroun...
public static IEnumerable < TSource > AsEnumerable < TSource > ( this IEnumerable < TSource > source ) { return source ; } List < char > content = `` testString '' .AsEnumerable ( ) ; IEnumerable < char > content1 = `` testString '' ; IList < char > content2 = content1 ;
Internal Implementation of AsEnumerable ( ) in LINQ
C#
I have a problem with writing a C # linq query for retrieving data from the database , based on multiple columns of a filter list.The list of items contains multiple columns ( For example A and B ) and is dynamic.My first idea was to write an any statement in an where statement , but this is not allowed in EF.I also tr...
var result = _repository.Where ( x = > items.Any ( y = > x.A == y.A & & x.B == y.B ) ) ; var ListA = items.Select ( x = > x.A ) .ToList ( ) ; var result = _repository.Get ( x = > ListA.Contains ( x.A ) ) ; SELECT A , B , C , DFROM Items WHERE ( A = 1 AND b = 1 ) OR ( A = 7 AND b = 2 ) OR ( A = 4 AND b = 3 )
Retrieve records from the database matching multiple values of a list
C#
I am drawing a header for a timeline control.It looks like this : I go to 0.01 millisecond per line , so for a 10 minute timeline I am looking at drawing 60000 lines + 6000 labels.This takes a while , ~10 seconds.I would like to offload this from the UI thread.My code is currently : I had looked into BackgroundWorker ,...
private void drawHeader ( ) { Header.Children.Clear ( ) ; switch ( viewLevel ) { case ViewLevel.MilliSeconds100 : double hWidth = Header.Width ; this.drawHeaderLines ( new TimeSpan ( 0 , 0 , 0 , 0 , 10 ) , 100 , 5 , hWidth ) ; //Was looking into background worker to off load UI //backgroundWorker = new BackgroundWorker...
10000's+ UI elements , bind or draw ?
C#
In unity3D I am creating and destroying capsule dynamically at run-time . I used space to create capsule and C for destroying.I want create multiple object and destroy multiple object at time . When I pressed Space multiple times object is creating multiple time it fine . But the problem is when I pressed C multiple ti...
using System ; using System.Collections ; using System.Collections.Generic ; using UnityEngine ; public class DynamicCreate : MonoBehaviour { public GameObject caps ; // Update is called once per frame void Update ( ) { if ( Input.GetKeyDown ( KeyCode.Space ) ) { createObject ( ) ; } if ( Input.GetKeyDown ( KeyCode.C )...
How to Destroy multiple gameObject at runtime ?
C#
This is a question I was asked at my interview recently : Which 'Random ' object ( s ) would get collected during the 'GC.Collect ( ) ' call ? I answered that this is an implementation-specific question and it highly depends on the GC implementation and the corresponding weak reference semantics . As far as I know , C ...
String a = new Random ( ) .Next ( 0 , 1 ) ==1 ? `` Whatever 1 '' : `` Whatever 2 '' ; String b = new WeakReference ( new Random ( ) ) .Target.Next ( 0 , 1 ) == 1 ? `` Whatever 1 '' : `` Whatever 2 '' ; GC.Collect ( ) ;
Which of these objects are eligible for garbage collection ?
C#
Lets say I have a function that needs to return some integer value . but it can also fail , and I need to know when it does.Which is the better way ? orthis is probably more of a style question , but I 'm still curious which option people would take.Edit : clarification , this code talks to a black box ( lets call it a...
public int ? DoSomethingWonderful ( ) public bool DoSomethingWonderful ( out int parameter )
which is better , using a nullable or a boolean return+out parameter
C#
I have an application that needs to take in several million char* 's as an input parameter ( typically strings less than 512 characters ( in unicode ) ) , and convert and store them as .net strings.It turning out to be a real bottleneck in the performance of my application . I 'm wondering if there 's some design patte...
String ^StringTools : :MbCharToStr ( const char *Source ) { String ^str ; if ( ( Source == NULL ) || ( Source [ 0 ] == '\0 ' ) ) { str = gcnew String ( `` '' ) ; } else { // Find the number of UTF-16 characters needed to hold the // converted UTF-8 string , and allocate a buffer for them . const size_t max_strsize = 20...
Optimizing several million char* to string conversions
C#
I 'm having trouble serialising and de-serialising NodaTime 's LocalTime through a WebAPI.Class definitionTry to serialize the outputI want to time format formatted to a ISO like standard e.g . 12:34:53 , but instead it de-serialisers to the following with local time represented as ticks ; { `` ExampleLocalTime '' : { ...
public class ExampleClass { public LocalTime ExampleLocalTime { get ; set ; } } // create example objectvar exampleclass = new ExampleClass ( ) { ExampleLocalTime = new LocalTime ( DateTime.Now.Hour , DateTime.Now.Minute ) } ; // serialise outputvar jsonsettings = new JsonSerializerSettings ( ) { DateParseHandling = Da...
Proper serialization of LocalTime through WebAPI
C#
Somebody gives me a type t.I 'd like to know if that type is an enumeration or not .
public bool IsEnumeration ( Type t ) { // Mystery Code . throw new NotImplementedException ( ) ; } public void IsEnumerationChecker ( ) { Assert.IsTrue ( IsEnumeration ( typeof ( Color ) ) ) ; Assert.IsFalse ( IsEnumeration ( typeof ( float ) ) ) ; }
Is there any way to check that a type is a type of enumeration ?
C#
I am getting all events , with a certain attribute , and I want to modify these events adding a call to another method.What I want is basically what is commented above . `` Modify '' the subscribed methods of the event . I guess I ca n't subscribe to it , because I need to pass the parameters the method is passing to t...
var type = GetType ( ) ; var events = type.GetEvents ( ) .Where ( e = > e.GetCustomAttributes ( typeof ( ExecuteAttribute ) , false ) .Length > 0 ) ; foreach ( var e in events ) { var fi = type.GetField ( e.Name , BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField ) ; var d = ( Delegate ) fi.GetValu...
How can I change a method assigned on an event ?
C#
I would like to parse an input string that contains either a time , a date and time , or just a date , and I need to know which parts where included in the input string.Parsing the actual values is not a problem : These all successfully parse as you 'd expect.However , if the date element is not provided , DateTime.Par...
var dt1 = DateTime.Parse ( `` 10:00:00 '' , CultureInfo.CurrentCulture ) ; var dt2 = DateTime.Parse ( `` 10pm '' , CultureInfo.CurrentCulture ) ; var dt3 = DateTime.Parse ( `` 01/02/2014 '' , CultureInfo.CurrentCulture ) ; var dt4 = DateTime.Parse ( `` 01/02/2014 10:00:00 '' , CultureInfo.CurrentCulture ) ;
Parsing Time , Date/Time , or Date
C#
EDIT 1 : I know there are alternatives such as telescoping , this was a purely educational question.I know that this is true , but why must it be ? It seems like with something like this : The compiler could change the method to something like this : Why would n't that work , or would it , and it 's just a design decis...
public class Foo { private int bar ; public void SetBar ( int baz = ThatOtherClass.GetBaz ( 3 ) ) { this.bar = baz ; } } public void SetBar ( int baz ) { //if baz was n't passed : baz = ThatOtherClass.GetBaz ( 3 ) ; this.bar = baz ; }
Why must default method parameters be compile-time constants in C #
C#
I 'm trying to create several enums as such , that gives the syntax of Dropdown.Category.Subcategory . However , I have been reading that this is n't such a good idea . My choice for this was mostly because I could n't think of any other way to select different enum values depending on the choice of the category , and ...
public class Dropdown { public enum Gifts { GreetingCards , VideoGreetings , UnusualGifts , ArtsAndCrafts , HandmadeJewelry , GiftsforGeeks , PostcardsFrom , RecycledCrafts , Other } public enum GraphicsAndDesign { CartoonsAndCaricatures , LogoDesign , Illustration , EbookCoversAndPackages , WebDesignAndUI , Photograph...
Alternative to nesting enums
C#
If I have two yield return methods with the same signature , the compiler does not seem to be recognizing them to be similar.I have two yield return methods like this : With this , I would expect the following statement to compile fine : Func < int , IEnumerable < int > > generator = 1 == 0 ? EvenNumbers : OddNumbers ;...
public static IEnumerable < int > OddNumbers ( int N ) { for ( int i = 0 ; i < N ; i++ ) if ( i % 2 == 1 ) yield return i ; } public static IEnumerable < int > EvenNumbers ( int N ) { for ( int i = 0 ; i < N ; i++ ) if ( i % 2 == 0 ) yield return i ; }
C # compiler not recognizing yield return methods as similar ?
C#
I 'm trying to create a set of C # classes that I can schedule to run at a future time . The intention is to programmatically schedule these via other parts of my code.This is the current class I 'm trying to call via COM.Here 's how I 'm attempting to schedule the taskMicrosoft.Win32.TaskScheduler is version 2.7.2 of ...
using System ; using System.Linq ; using System.Runtime.InteropServices ; using Microsoft.Win32.TaskScheduler ; namespace SchedulableTasks { [ Guid ( `` F5CAE94C-BCC7-4304-BEFB-FE1E5D56309A '' ) ] public class TaskRegistry : ITaskHandler { private ITaskHandler _taskHandler ; public void Start ( object pHandlerServices ...
Unable to register a COM object for usage in a scheduled task
C#
PreambleI have been investigating a concept and what I am posting below is a cut down version of what I have been trying . If you look at it and think `` That does n't make any sense to do it that way '' then it is probably because I does n't make any sense - there may be more efficient ways of doing this . I just want...
K | Amt | Instruction | Order -- + -- -- -+ -- -- -- -- -- -- -+ -- -- -- A | 100 | Push | 1A | 1 | Multiply | 2A | 10 | Push | 3A | 2 | Multiply | 4A | | Add | 5A | 1 | Push | 6A | 3 | Multiply | 7A | | Add | 8 SELECT K , dbo.ReversePolishAggregate ( dbo.ToReversePolishArguments ( Instruction , Amt ) ) FROM dbo.Revers...
SQL ORDER BY within OVER clause incompatible with CLR aggregation ?
C#
Consider the following codeSteps to reproducePut a breakpoint on Console.Read ( ) ; Run to breakpointInspect count++ ( should display 0 ) Inspect values2 and populate the Results ViewInspect count++ ( should display 100 ) ProblemGiven that I have only taken 50 items from values1 , I would expect count++ to display 50 ....
namespace ConsoleApp1 { using System ; using System.Collections.Generic ; using System.Linq ; public class Program { public static void Main ( string [ ] args ) { int count = default ( int ) ; IEnumerable < int > values1 = Enumerable.Range ( 1 , 200 ) .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 100 ) ; IEnumerable < in...
LINQ projection ( Select ) returning an odd result
C#
I 've read that it is usually bad practice to extend System.Object , which I do agree with.I am curious , however , if the following would be considered a useful extension method , or is it still bad practice ? It is similar to extending System.Object but not exactly , This essentially allows any object to invoke any f...
public static R InvokeFunc < T , R > ( this T input , Func < T , R > func ) { return func.Invoke ( input ) ; }
Extension method that extends T - bad practice ?
C#
When I bump my mousewheel , my WPF application crashes sometimes , with an OverflowException . Here 's the start of the stack trace : From that , I 've traced it down to the WindowChrome - I can even reproduce it with just the WindowChrome . But it seems like it has to be fullscreen . What 's going on here ? Is there a...
at System.Windows.Shell.WindowChromeWorker._HandleNCHitTest ( WM uMsg , IntPtr wParam , IntPtr lParam , Boolean & handled )
Why does my WPF application crash when I bump my mousewheel ?
C#
I 'm having trouble understanding why arrays in C # are covariant and what benefits this covariance can bring . Consider the following trivial code example : This code will compile okay , but will unceremoniously and perhaps unsurprisingly explode at runtime.If I try to attempt this same thing using generics , the comp...
object [ ] myArray = new string [ 1 ] ; myArray [ 0 ] = 1 ;
Why are C # arrays covariant and what benefits does it bring ?
C#
If I have a synchronous method `` GetStrings ( ) '' : ( which itself calls async method `` GetString ( ) '' ) And I call this synchronous `` GetStrings ( ) '' method from an async method : What would be the behavioural difference , if GetStrings ( ) was actually async ? ( and performed an await on the Task.WhenAll ) Wo...
private static Task < string [ ] > GetStrings ( IEnumerable < int > ids ) { var tasks = ids.Distinct ( ) .Select ( GetString ) ; return Task.WhenAll ( tasks ) ; } private static async Task < string > GetString ( int stringId ) { await Task.Delay ( 15000 ) ; return `` hello '' + stringId ; } public static async Task Mai...
What happens when you await a synchronous method
C#
Hi i have two Writablebitmap , one from jpg and another from png and use this method to mix color in a loop : My problem is in alpha channel , my watermark effect result is bad ( quality ) ! This is the original png.This is the original jpg.Any Help ?
private static Color Mix ( Color from , Color to , float percent ) { float amountFrom = 1.0f - percent ; return Color.FromArgb ( ( byte ) ( from.A * amountFrom + to.A * percent ) , ( byte ) ( from.R * amountFrom + to.R * percent ) , ( byte ) ( from.G * amountFrom + to.G * percent ) , ( byte ) ( from.B * amountFrom + to...
Png over jpeg ( water mark effect ) bad quality ?
C#
In C # I have ( saw with Visual Studio watch tool ) : And in C++ : Why are the values not the same ? And how can I get -3.40282347E+38 ( C # value ) in C++ ?
float.MinValue = -3.40282347E+38 std : :numeric_limits < float > : :min ( ) = 1.17549435e-038
Why is float.min different between C++ and C # ?
C#
Given the following code , Resharper will correctly warn me about a possible NullReferenceException on foo.Bar because there could be null elements in the enumerable : One way to satisfy the static analyzer is to explicitly exclude nulls : I find myself typing .Where ( x = > x ! = null ) a lot , so I wrapped it up in a...
IEnumerable < Foo > foos = GetFoos ( ) ; var bars = foos.Select ( foo = > foo.Bar ) ; IEnumerable < Foo > foos = GetFoos ( ) .Where ( foo = > foo ! = null ) ; IEnumerable < Foo > foos = GetFoos ( ) .NotNull ( ) ; [ NotNull ] public static IEnumerable < T > NotNull < T > ( this IEnumerable < T > enumerable ) { return en...
How do I tell Resharper that my IEnumerable method removes nulls ?
C#
I recently came across what seems to puzzle my logic of maths in a piece of codeFor some reason , C # is claiming that this is false but if one were to think logically , 0.123 is larger than 0.Is there any reason that it is claiming that 0.123 is smaller than 0 ? I have read that there will be a comparison issue with d...
if ( ( 123/1000 ) > 0 )
if ( ( 123 / 1000 ) > 0 ) returns false
C#
There are two Point3D 's ( A and B ) and I want to calculate the points of a cuboid ( a , b , c ... h ) surrounding the line between A and B like a hull : There is one degree of freedom , the angle of the cuboid , because it can rotate around the line AB . I am not sure yet if this is a problem.I tried to calculate a v...
double ax = Vector3D.AngleBetween ( E , new Vector3D ( 1 , 0 , 0 ) ) ; double ay = Vector3D.AngleBetween ( E , new Vector3D ( 0 , 1 , 0 ) ) ; double az = Vector3D.AngleBetween ( E , new Vector3D ( 0 , 0 , 1 ) ) ; ax = Math.Abs ( ax - 90 ) ; ay = Math.Abs ( ay - 90 ) ; az = Math.Abs ( az - 90 ) ; if ( ax < = ay & ax < =...
Calculating the Point3Ds of a Cuboid around a Line
C#
i use the httpclient from Microsoft.Net.Http ( version 2.2.22 ) to request some of my mvc pages.My page returns a HttpStatusCodeResult like : With the httpclient it is not problem to call the page . But i could n't find a way to access the statusDescription ( `` Blub Blub '' ) . Is there a way to access the description...
return new HttpStatusCodeResult ( clientResponse.StatusCode , `` Blub Blub '' ) ;
HttpClient StatusDescription is missing
C#
I found this explanation and solution for using Dapper to search a VARCHAR field using a string as input : Source : Dapper and varcharsBut is there a way to adapt this to do the DbString conversion for every item in a list ( using an IN clause ) ? The query I am trying to run looks like this : Unfortunately , this quer...
Query < Thing > ( `` select * from Thing where Name = @ Name '' , new { Name = new DbString { Value = `` abcde '' , IsFixedLength = true , Length = 10 , IsAnsi = true } ) ; Query < IndexRec > ( `` SELECT * FROM T_INDEX WHERE CallId IN @ callIds '' , new { callIds = model.LogEntries.Select ( x = > x.Id ) } ) ;
How do I tell Dapper to use varchar for a list of params in a `` WHERE '' clause that uses `` IN '' ?
C#
What are some good ways to handle known errors that occur in a method ? Let 's take a user registration method as an example . When a user is signing up , a method SignUp ( User user ) is called . There are a few known errors that might happen.Email is already registeredUsername is already registeredEtcYou could throw ...
public void SignUp ( User user ) { // Email already exists throw new EmailExistsException ( ) ; } public bool SignUp ( User user , out/ref string errorMessage ) { // Email already exists errorMessage = `` Email already exists . `` ; return false ; } public enum Errors { Successful = 0 , EmailExists , UsernameExists , E...
Handling Known Errors and Error Messages in a Method
C#
I 've been having really bad memory problems with an ASP.NET Application . It seems as if every time the page loads , the old previous instance of the page is not removed from memory . If you press F5 ten times , the memory adds 10-20MB to the instance . During Stress and performance testing , this would max out the me...
# region Services [ Dependency ] public ReviewReportService SummaryService { get ; set ; } [ Dependency ] public Portfolios.PortfolioService PortfolioService { get ; set ; } # endregion protected override void OnInit ( EventArgs e ) { base.OnInit ( e ) ; ApplicationContainer.BuildUp ( this.Context , this ) ; }
ASP.NET Pages not removed from memory
C#
I wan na select some records from the informix database via Odbc connection and insert them to a Sql database table.I 've searched regrading that , but they did n't solve my issue . Is it possible to have both connections at one place ? Any help or suggestions would be appreciated . Thanks
INSERT INTO SAS.dbo.disconnectiontemp ( meterno ) SELECT DISTINCT met_number FROM Bills.dbadmin.MeterData
Odbc & Sql connection in one query
C#
I wrote User Control ( yay ! ) . But I want it to behave as a container . But wait ! I know about Trick . The problem is - I do n't want all of my control to behave like container , but only one part . One - de facto - panel ; ) To give wider context : I wrote a control that has Grid , some common buttons , labels and ...
[ Designer ( `` System.Windows.Forms.Design.ParentControlDesigner , System.Design '' , typeof ( IDesigner ) ) ]
UserControl with header and content - Allow dropping controls in content panel and Prevent dropping controls in header at design time
C#
I was fiddling around with parsing in C # and found that for every string I tried , string.StartsWith ( `` \u2D2D '' ) will return true . Why is that ? It seems it works with every char . Tried this code with .Net 4.5 the Debugger did not break .
for ( char i = char.MinValue ; i < char.MaxValue ; i++ ) { if ( ! i.ToString ( ) .StartsWith ( `` \u2d2d '' ) ) { Debugger.Break ( ) ; } }
Why does string.StartsWith ( `` \u2D2D '' ) always return true ?
C#
I am currently working on a C # .NET Add-In for Microsoft Outlook.The goal of the Add-In is , to capture the search input from the Outlook Instant Search , and show in a Custom Pane my own search results.It works pretty well , and with subclassing the Outlook Window with a Native Window , I get the search string , and ...
protected override void WndProc ( ref Message m ) { base.WndProc ( ref m ) ; switch ( ( uint ) m.Msg ) { case WindowMessages.WM_DESTROY : case WindowMessages.WM_QUIT : case WindowMessages.WM_NCDESTROY : this.ReleaseHandle ( ) ; return ; case WindowMessages.WM_KEYUP : case WindowMessages.WM_LBUTTONDOWN : case WindowMess...
Native Window : Release Handle On Close
C#
This compiles correctly in C # 7.3 ( Framework 4.8 ) : I know that this is syntactic sugar for the following , which also compiles correctly : So , it appears that ValueTuples can be assigned covariantly , which is awesome ! Unfortunately , I do n't understand why : I was under the impression that C # only supported co...
( string , string ) s = ( `` a '' , `` b '' ) ; ( object , string ) o = s ; ValueTuple < string , string > s = new ValueTuple < string , string > ( `` a '' , `` b '' ) ; ValueTuple < object , string > o = s ; struct MyValueTuple < A , B > { public A Item1 ; public B Item2 ; public MyValueTuple ( A item1 , B item2 ) { I...
What makes ValueTuple covariant ?
C#
I have encountered a problem while using Invariants with Code Contracts . I want to define an Invariant within my abstract class but it is simply ignored . The code below shows my interface and the abstract class.Afterwards , I implement this interface within my Point class and create an object from it . This should at...
[ ContractClass ( typeof ( IPointContract ) ) ] interface IPoint { int X { get ; } int Y { get ; } } [ ContractClassFor ( typeof ( IPoint ) ) ] abstract class IPointContract : IPoint { public int X { get { return 0 ; } } public int Y { get { return 0 ; } } [ ContractInvariantMethod ] private void PointInvariant ( ) { C...
Code Contracts : Invariants in abstract class
C#
Would it be considered bad practice to have a viewmodel that has a property of another view model ? ... as in : EDITA little more about my particular situation : I have a view model that currently contains 2 domain classes . I pass this viewmodel to a view that loads 2 partials views ( one for each domain class in the ...
public class PersonViewModel { public PersonJobViewModel Peron { get ; set ; } //other properties here ... }
Is it bad practice to have a ViewModel with a property typed as another ViewModel in ASP.NET MVC
C#
I have some code that was recently upgraded from EF 4.2 to EF 5.0 ( actually EF 4.4 since I am running on .Net 4.0 ) . I have discovered that I had to change the syntax of my query , and I 'm curious as to why . Let me start off with the problem.I have an EventLog table that is populated by the client periodically . Fo...
from el in _repository.EventLogswhere ! _repository.Reports.Any ( p = > p.EventLogID == el.EventlogID ) from eventLog in _repository.EventLogsjoin report in _repository.Reports on eventLog.EventlogID equals report.EventLogID into alreadyReportedwhere ! alreadyReported.Any ( )
Why does EF 5.0 not support this EF 4.x LINQ syntax when compiling to sql ?
C#
Let 's say , hypothetically ( read : I do n't think I actually need this , but I am curious as the idea popped into my head ) , one wanted an array of memory set aside locally on the stack , not on the heap . For instance , something like this : I 'm guessing the answer is no . All I 've been able to find is heap based...
private void someFunction ( ) { int [ 20 ] stackArray ; //C style ; I know the size and it 's set in stone }
Are stack based arrays possible in C # ?
C#
Let 's assume I have a class that has a property of type Dictionary < string , string > , that may be null.This compiles but the call to TryGetValue ( ) could throw at a NullRef exception at runtime : So I 'm adding a null-propagating operator to guard against nulls , but this does n't compile : Is there an actual use ...
MyClass c = ... ; string val ; if ( c.PossiblyNullDictionary.TryGetValue ( `` someKey '' , out val ) ) { Console.WriteLine ( val ) ; } MyClass c = ... ; string val ; if ( c.PossiblyNullDictionary ? . TryGetValue ( `` someKey '' , out val ) ? ? false ) { Console.WriteLine ( val ) ; // use of unassigned local variable } ...
Null propagation operator , out parameters and false compiler errors ?
C#
My test code : My problem is : I can not directly declare pictureUrl like this : I 've tried to do that , it threw me error message : 'Task < UserProfileViewModels > ' does not contain a definition for 'PictureUrl ' and no extension method 'PictureUrl ' accepting a first argument of type 'Task < UserProfileViewModels >...
using ( var db = new MyDbContext ( ) ) { string id = `` '' ; string pictureUrl = db.UserProfile.Single ( x = > x.Id == id ) .PictureUrl ; //valid syntax var user = await db.UserProfile.SingleAsync ( x = > x.Id == id ) ; //valid syntax string _pictureUrl = user.PictureUrl ; //valid syntax } string pictureUrl = await db....
Why can not I directly access property `` .SingleAsync ( ) .Property '' ?
C#
I am creating ( then altering ) a bitmap using `` unsafe '' code in a C # winforms project . This is done every 30ms or so . The problem I 'm having is that `` noise '' or random pixels will show up sometimes in the resulting bitmap where I did not specifically change anything.For example , I create a bitmap of 100x100...
// Create new output bitmapBitmap Output_Bitmap = new Bitmap ( 100 , 100 ) ; // Lock the output bitmap 's bitsRectangle Output_Rectangle = new Rectangle ( 0 , 0 , Output_Bitmap.Width , Output_Bitmap.Height ) ; BitmapData Output_Data = Output_Bitmap.LockBits ( Output_Rectangle , ImageLockMode.WriteOnly , PixelFormat.For...
How to avoid `` noise '' when setting pixels of image in unsafe code
C#
This is very baffling to me . Somehow the IndexOf ( string ) method of my List < string > object is returning -1 even though the value is CLEARLY in the List.string prefix is `` 01 '' validPrefixes index 0 is `` 01 '' .indexOf is -1 . Umm ... How ?
protected readonly List < string > validPrefixes = new List < string > ( ) { `` 01 '' , `` 02 '' , `` 03 '' , `` FE '' , `` E1 '' , `` E2 '' , `` E3 '' } ;
List < string > object IndexOf returning -1 . How ?
C#
I have a situation where I have a simple , immutable value type : When I box an instance of this value type , I would normally expect that whatever it is that I boxed would come out the same when I do an unbox . To my big suprise this is not the case . Using Reflection someone may easily modify my box 's memory by rein...
public struct ImmutableStruct { private readonly string _name ; public ImmutableStruct ( string name ) { _name = name ; } public string Name { get { return _name ; } } } class Program { static void Main ( string [ ] args ) { object a = new ImmutableStruct ( Guid.NewGuid ( ) .ToString ( ) ) ; PrintBox ( a ) ; MutateTheB...
Why does the CLR allow mutating boxed immutable value types ?
C#
Given a set of sixteen letters and an English dictionary file , need to find a solution where those sixteen letters can fit into a 4x4 grid so that a valid word can be read across each row , and down each column.My current solution:1 ) Get a list of all of the possible 4-letter words that can be made with those letters...
namespace GridWords { class Program { static void Main ( string [ ] args ) { string [ ] words = new string [ ] { `` zoon '' , `` zonk '' , `` zone '' , `` zona '' , `` zoea '' , `` zobo '' , `` zero '' , `` zerk '' , `` zeal '' , `` zack '' , `` rore '' , `` roon '' , `` rook '' , `` rood '' , `` rone '' , `` role '' ,...
My iteration is taking forever . Looking for a better way
C#
I wrote the following console app to test static properties : As this console app demonstrates , the MyProperty property exists once for all instances of BaseClass . Is there a pattern to use which would allow me to define a static property which will have allocated storage for each sub-class type ? Given the above exa...
using System ; namespace StaticPropertyTest { public abstract class BaseClass { public static int MyProperty { get ; set ; } } public class DerivedAlpha : BaseClass { } public class DerivedBeta : BaseClass { } class Program { static void Main ( string [ ] args ) { DerivedBeta.MyProperty = 7 ; Console.WriteLine ( Derive...
What is the best way to define a static property which is defined once per sub-class ?
C#
I am using application insights sdk for a wpf app I 've been working on to capture some simple telemetry . I am loading the configuration file that looks like thisThe problem is when I run the installed application and am offline the telemetry is captured just fine . Next time I open the app when I 'm online that data ...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ApplicationInsights xmlns= '' http : //schemas.microsoft.com/ApplicationInsights/2013/Settings '' > < TelemetryChannel Type= '' Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel , Microsoft.AI.ServerTelemetryChannel '' / > < Teleme...
App Insights Telemetry not sending when offline
C#
I am trying to develop an algorithm in C # that can take an array list of URL 's and output them in an outline numbered list.As you can imagine I need some help . Does anyone have any suggestions on the logic to use to generate this list ? Example Output : ... and so on
1 - http : //www.example.com/aboutus1.2 - http : //www.example.com/aboutus/page11.3 - http : //www.example.com/aboutus/page21.3.1 - http : //www.example.com/aboutus/page2/page31.3.1.1 - http : //www.example.com/aboutus/page2/page3/page41.3.2 - http : //www.example.com/aboutus/page5/page61.3.2.1 - http : //www.example.c...
c # outline numbering
C#
I have function which serialize objects . It is working fine in every case except when I run with specific object . This is object of class which contains Tasks . But I do n't see why would this be problem.In debug mode code is just stuck without any error , or any exception . Just stop and waiting for ever.Also to men...
[ NonSerialized ] private Task < bool > isConnected ; public Task < bool > IsConnected { get { return isConnected ; } set { isConnected = value ; } } public static string ToJson ( this object obj ) { try { var res = JsonConvert.SerializeObject ( obj , Formatting.Indented , new JsonSerializerSettings { ReferenceLoopHand...
SerializeObject is waiting for ever
C#
I have this code ( the unimportant details are that it runs on EC2 instances in AWS , processing messages on an SQS queue ) .The first statement in the method gets some data over http , the second statement saves state to a local dynamo data store.The performance characteristics are that the http round trip takes 100-2...
public bool HandleMessage ( OrderAcceptedMessage message ) { var order = _orderHttpClient.GetById ( message.OrderId ) ; _localDynamoRepo.SaveAcceptedOrder ( message , order ) ; return true ; } public async Task < bool > HandleMessage ( OrderAcceptedMessage message ) { var order = await _orderHttpClient.GetByIdAsync ( m...
Should I make a fast operation async if the method is already async
C#
Our code base has a lot of StringBuilder.AppendFormats that have strings that end with newline characters . I 've made an extension method called AppendLineFormat and would like to use Resharper 's Custom Patterns feature to identify and fix those old calls to use the new extension method ( and to suggest this new exte...
StringBuilder sb = new StringBuilder ( ) ; int i = 1 ; sb.AppendFormat ( `` i is { 0 } \r\n '' , i ) ; sb.AppendLineFormat ( `` i is { 0 } '' , i ) ; $ sb $ .AppendFormat ( $ newLineString $ , $ args $ ) $ sb $ .AppendLineFormat ( $ newLineString $ , $ args $ )
Can I use regex to find strings in Resharper 's Custom Patterns ?
C#
I have a VC++ COM component with a type library . The type library of this component declares an interface and a co-class : In order to consume the component from a C # application I add a reference to the C # project and an interop assembly is generated.In the Object Browser of Visual Studio 2003 I see that the intero...
[ object , uuid ( ActualUuidHere ) , dual , nonextensible , oleautomation , hidden , helpstring ( ActualHelpStringHere ) ] interface IWorkflow : IDispatch { //irrelevant properties here } [ uuid ( ActualClassIdHere ) , noncreatable ] coclass Workflow { [ default ] interface IWorkflow ; } ; public abstract interface IWo...
Names in the interop assembly have wrong capitalization
C#
My Application can perform 5 business functions . I now have a requirement to build this into the licensing model for the application.My idea is to ship a `` keyfile '' with the application . The file should contain some encrypted data about which functions are enabled in the application and which are not . I want it s...
BUSINESS FUNCTION 1 = ENABLED BUSINESS FUNCTION 2 = DISABLED ... . etc
How can I secure an `` enabled functions '' license file for my program ?
C#
Good day ! I allow my content editors to store CSS as very basic components ( usually containing a single , multi-line field called `` code '' that they paste into ) , and these are then added as Component Presentations into a Page with a .css file extension . When creating the page , users are able to set a few config...
// Create a reference to the Page object in the package.Page page = this.GetPage ( ) ; // Retrieve a reference to the page 's file name.string currentFileName = Utilities.GetFilename ( page.FileName ) ; // Set the published file name on its way out the door.page.FileName = currentFileName + `` _min '' ; // ? ? ? // Pro...
Tridion 2011 : Changing a page 's file name as it 's being published
C#
I found this bit of code that computes Levenshtein 's distance between an answer and a guess : But I need a way to do a count for the amount of times each error occurs . Is there an easy way to implement that ?
int CheckErrors ( string Answer , string Guess ) { int [ , ] d = new int [ Answer.Length + 1 , Guess.Length + 1 ] ; for ( int i = 0 ; i < = Answer.Length ; i++ ) d [ i , 0 ] = i ; for ( int j = 0 ; j < = Guess.Length ; j++ ) d [ 0 , j ] = j ; for ( int j = 1 ; j < = Guess.Length ; j++ ) for ( int i = 1 ; i < = Answer.L...
Levenshtein distance c # count error type
C#
I have the following code : I want to write one function that will properly trim the fields , something like : Of course , this is not permitted in C # .One option I have is to write a helper and use reflection.Is there another way I can achieve this ( reflecting on so many properties will deffinitely have a performanc...
class SearchCriteria { public string Name { get ; set ; } public string Email { get ; set ; } public string Company { get ; set ; } // ... around 20 fields follow public void Trim ( ) { if ( ! String.IsNullOrEmpty ( Name ) ) { Name = Name.Trim ( ) ; } if ( ! String.IsNullOrEmpty ( Email ) ) { Email = Email.Trim ( ) ; }...
Modify multiple string fields
C#
I was writing some code today and was mid line when I alt-tabbed away to a screen on my other monitor to check something . When I looked back , ReSharper had colored the 3rd line below grey with the note `` Value assigned is not used in any execution path '' . I was confused ; surely this code ca n't compile . But it d...
var ltlName = ( Literal ) e.Item.FindControl ( `` ltlName '' ) ; string name = item.FirstName ; name += ltlName.Text = name ;
Why is `` someString += AnotherString = someString ; '' valid in C #
C#
If JavaScript 's Number and C # 's double are specified the same ( IEEE 754 ) , why are numbers with many significant digits handled differently ? I am not concerned with the fact that IEEE 754 can not represent the number 1234123412341234123 . I am concerned with the fact that the two implementations do not act the sa...
var x = ( long ) 1234123412341234123.0 ; // 1234123412341234176 - C # var x = 1234123412341234123.0 ; // 1234123412341234200 - JavaScript
Why are numbers with many significant digits handled differently in C # and JavaScript ?
C#
I need to replace some parts of a string with each other using C # .I could find only one similar question about how to achive this here but it was PHP.My situation involves a Dictionary [ string , string ] which holds pairs to replace like : dog , cat cat , mouse , mouse , raptorAnd I have a string with the value of :...
`` My dog ate a cat which once ate a mouse got eaten by a raptor '' `` My cat ate a mouse which once ate a raptor got eaten by a raptor '' `` My raptor ate a raptor which once ate a raptor got eaten by a raptor ''
How to replace two or more strings with each other ?
C#
The following code finds instances of the word `` Family '' in a Word document . It selects and deletes the instances . The code works fine , but I want to find all instances of only highlighted words .
public void FindHighlightedText ( ) { const string filePath = `` D : \\COM16_Duke Energy.doc '' ; var word = new Microsoft.Office.Interop.Word.Application { Visible = true } ; var doc = word.Documents.Open ( filePath ) ; var range = doc.Range ( ) ; range.Find.ClearFormatting ( ) ; range.Find.Text = `` Family '' ; while...
Find highlighted text
C#
I have an int array in one dimension : and I want to convert it to two dimensions , such as : How do I achieve this with C # ?
var intArray=new [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ; var intArray2D=new [ , ] { { 1 , 2 } , { 3 , 4 } , { 5 , 6 } } ;
How to Convert int [ ] to int [ , ] - C #