Showing posts with label Tips. Show all posts
Showing posts with label Tips. Show all posts

Thursday, March 19, 2020

A TwoWay or OneWayToSource binding cannot work on the read-only property

I ran into an InvalidOperationException when binding to a read-only property in the model

I.e. my model looks something like this:
public class Customer
{
 public Guid Id { get; set; }
 public string Name { get; set; }
 public List Orders { get; set; }
 public double CalculatedProperty => Orders.Sum(x => x.TotalPrice);
}
And my binding in XAML something like:
{Binding CalculatedProperty, StringFormat='0.00'}

To get around this, we need to update the binding to set the Mode to something else then TwoWay or OneWayToSource, simplest is to just set it to OneWay like the following:
{Binding CalculatedProperty, StringFormat='0.00', Mode=OneWay}



Hope this helps someone out there!

Full exceptioon stack-trace
System.InvalidOperationException
  HResult=0x80131509
  Message=A TwoWay or OneWayToSource binding cannot work on the read-only property 'CalculatedProperty' of type 'Model.Entity.Customer'.
  Source=PresentationFramework
  StackTrace:
   at MS.Internal.Data.PropertyPathWorker.CheckReadOnly(Object item, Object info)
   at MS.Internal.Data.PropertyPathWorker.ReplaceItem(Int32 k, Object newO, Object parent)
   at MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(Int32 k, ICollectionView collectionView, Object newValue, Boolean isASubPropertyChange)
   at MS.Internal.Data.ClrBindingWorker.AttachDataItem()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run()
   at UI.WPF.App.Main()

  This exception was originally thrown at this call stack:
 MS.Internal.Data.PropertyPathWorker.CheckReadOnly(object, object)
 MS.Internal.Data.PropertyPathWorker.ReplaceItem(int, object, object)
 MS.Internal.Data.PropertyPathWorker.UpdateSourceValueState(int, System.ComponentModel.ICollectionView, object, bool)
 MS.Internal.Data.ClrBindingWorker.AttachDataItem()
 System.Windows.Data.BindingExpression.Activate(object)
 System.Windows.Data.BindingExpression.AttachToContext(System.Windows.Data.BindingExpression.AttachAttempt)
 System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(bool)
 MS.Internal.Data.DataBindEngine.Task.Run(bool)
 MS.Internal.Data.DataBindEngine.Run(object)
 MS.Internal.Data.DataBindEngine.OnLayoutUpdated(object, System.EventArgs)
    ...
    [Call Stack Truncated]

Sunday, September 10, 2017

Typescript Array.Map


TypeScript made me go back to web development again, bringing in the compile time type checks really makes it easier to write correct code faster.
But sometimes it is a little tricky to figure out the syntax. For example last night when I tried to store the result from an array.map call in a variable. Most of the examples I found used the var keyword and pretty much ignoring the type check making me wonder why even bother with TypeScript if you don't use the types?

So, I wanted to try the array.map in the render method of a React JSX file to render a list of items. The end result was something like this:
public render() {
 const itemNames: string[] = ["Item One", "Item Two"];
 let itemNamesRender: JSX.Element[] = equipmentNames.map((name: string) => <li>{name}</li>);
 return <div>
  <h1>My Items</h1>

  <ul>{equipmentNamesRender}</ul>
 </div>;
}

Where the
let result: JSX.Element[] = array.map()
is the key. So pretty much just like all other variable declarations. The issue I had turned out to be that I didn't know that the type was JSX.Element, instead I was trying to force it to a string type.

Hope this helps someone out there. : )

Saturday, October 22, 2016

Foreign Key constraint issue, hard to find cause

This hard to figure out issue has popped up from time to time

The DELETE statement conflicted with the REFERENCE constraint "FK_Order_Customer".
The conflict occurred in database "DATABASE", table "dbo.Order", column 'CustomerID'.

Not so much to do with the actual execution of your program, it works for most data but it seems that if a co-worker has manually edited data in the database with Sql Management Studio, there is a possibility that an extra line-break is introduced if the user confirms her edit with the return button.

To find the issue, copy the data and paste it to your favorite text-editor, in between two quotation marks.
Correct data:
'data'
Bad data:
'data
'
Remove the extra line break and you should be good to go.

Of course, good database design should prevent this from happening but sometimes you are stuck with legacy systems and it is good to know that this can happen, especially if you have people manually editing data in the database.

Hope this helps someone out there :)

Saturday, March 16, 2013

DateTime.Now vs DateTime.UtcNow

Please note that this post does not take into account any other perspective of when to use DateTime.Now or DateTime.UtcNow other than performance.

This morning I tried to find numbers that compare DateTime.Now and DateTime.UtcNow but all I found was long discussions on the subject of when to use them. So I decided to write a quick sample myself to see.

Last value was 2013-03-16 12:50:18
DateTime.Now:           00:00:06.6733481 for 10000000 iterations
Last value was 2013-03-16 11:50:18
DateTime.UtcNow:        00:00:00.0741262 for 10000000 iterations
DateTime.UtcNow is 1,11% of DateTime.Now




   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          const int iterations = 10000000;
   6:          DateTime dt = DateTime.UtcNow;
   7:          Stopwatch sw = Stopwatch.StartNew();
   8:          for (int i = 0; i < iterations; i++)
   9:              dt = DateTime.Now;
  10:          sw.Stop();
  11:          Console.WriteLine("Last value was {0}", dt);
  12:          Console.WriteLine("DateTime.Now:\t\t{0} for {1} iterations", sw.Elapsed, iterations);
  13:          double nowMs = sw.ElapsedMilliseconds;
  14:          sw = Stopwatch.StartNew();
  15:          for (int i = 0; i < iterations; i++)
  16:              dt = DateTime.UtcNow;
  17:          sw.Stop();
  18:          Console.WriteLine("Last value was {0}", dt);
  19:          Console.WriteLine("DateTime.UtcNow:\t{0} for {1} iterations", sw.Elapsed, iterations);
  20:          double utcNowMs = sw.ElapsedMilliseconds;
  21:          Console.WriteLine("DateTime.UtcNow is {0:0.00}% of DateTime.Now", CalcPercentage(utcNowMs, nowMs));
  22:          Console.ReadLine();
  23:      }
  24:      private static double CalcPercentage(double value, double max)
  25:      {
  26:          double p = (100.0 / max);
  27:          return p * value;
  28:      }
  29:  }

Thursday, June 9, 2011

SGEN: Could not load file or assembly 'xxx' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515)

Always nice to see our old friend HRESULT in an error message.

Ran into this today when converting some .NET3.5 projects to .NET4.0 and at the same time upgrading some 3rd party libraries.

Seems that downloaded files get a blocked attribute set on them that prevents the usage of them. In Visual Studio 2010, the HRESULT: 0x80131515 is shown when linking to dll’s that are blocked.

To come around this, open Windows Explorer, navigate to the folder hosting the dll. Right click on it and select properties. There should be a Unblock button in the dialog window. Click on it and SGEN should stop complaining.

Hope this helps : )

Thursday, November 18, 2010

How to block advertisements in Windows Live Messenger

A friend asked me how I managed to get rid of the advertisements in Windows Live Messenger so I thought that I'd share it here.
I found this little trick some years ago when I got annoyed by the mouse over adverts that expanded outside the initial box that they appear in. I honestly do not remember where I found it and when I try to Google for the fix now it only finds some downloadable applications that should 'fix the ads'. They seem a little suspicious thou so I'll just share my fix here.

It seems that Windows Live Messenger gets all its advertisements from various feeds from msn.com, msads.net and live.com. Lucky us the feeds originate from subdomains to these addresses so we don't have to block the whole domains.

1. Open your "hosts" file that is located in one of the system folders.
  XP : C:\WINDOWS\system32\drivers\etc

Note that the file may be read-only so you should open it with administrative privileges. Right click and select "Run as Administrator".

2. Add the following lines to the end of the hosts file below the reference to localhost.
0.0.0.0 rad.msn.com
0.0.0.0 global.msads.net
0.0.0.0 rss.video.msn.com
0.0.0.0 ads1.msn.com
0.0.0.0 rad.live.com
0.0.0.0 specials.uk.msn.com

3. Save the file.

Done.

windows_live_messenger_after_no_advertisements_fixThe advertisements may still show for a little while after the fix has been applied. The next time Windows Live Messenger tries to download new advertisements it will only show a non clickable logo as seen in the picture to the right.
To speed up the process just restart Windows Live Messenger and the fix should be applied immediately.