Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, February 16, 2015

Reactive programming in WPF


http://obtics.codeplex.com

Project Description
The object of this project is to create a library that offers Functional Reactive Programming abilities to common .Net languages.
With FRP your calculations automatically respond to changes in the underlying data. Obtics includes a live Object Linq and Linq to Xml.


Project Description
Continous LINQ is a .NET Framework 3.5 extension that builds on the LINQ query syntax to create continuous, self-updating result sets. 
In traditional LINQ queries, you write your query and get stale results. With Continuous LINQ, 

you write a query and the results of that query are continuously updated as changes are made to the source collection or items within the source collection. 

CLINQ has tremendous value in GUI development and is especially useful in binding to filtered streams of data such as financial or other network message data.

https://rx.codeplex.com

The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams withObservablesquery asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers.
Whether you are authoring a traditional desktop or web-based application, you have to deal with asynchronous and event-based programming from time to time. Desktop applications have I/O operations and computationally expensive tasks that might take a long time to complete and potentially block other active threads. Furthermore, handling exceptions, cancellation, and synchronization is difficult and error-prone.
Using Rx, you can represent multiple asynchronous data streams (that come from diverse sources, e.g., stock quote, tweets, computer events, web service requests, etc., and subscribe to the event stream using the IObserver interface. The IObservable interface notifies the subscribed IObserver interface whenever an event occurs.
Because observable sequences are data streams, you can query them using standard LINQ query operators implemented by the Observable extension methods. Thus you can filter, project, aggregate, compose and perform time-based operations on multiple events easily by using these standard LINQ operators. In addition, there are a number of other reactive stream specific operators that allow powerful queries to be written.  Cancellation, exceptions, and synchronization are also handled gracefully by using the extension methods provided by Rx.
Rx complements and interoperates smoothly with both synchronous data streams (IEnumerable) and single-value asynchronous computations (Task).
(currently not supported)

Thursday, November 6, 2014

Combined results for serializing / deserialzing a single row of each table in the Northwind database 1,000,000 times

from: https://github.com/ServiceStack/ServiceStack.Text

SerializerSizePeformance
Microsoft DataContractSerializer4.68x6.72x
Microsoft JsonDataContractSerializer2.24x10.18x
Microsoft BinaryFormatter5.62x9.06x
NewtonSoft.Json2.30x8.15x
ProtoBuf.net1x1x
ServiceStack TypeSerializer1.78x1.92x

Wednesday, June 18, 2014

SetForegroundWindow Win32 API not always works on Windows 7

SetForegroundWindows has some remarks usage, which could be found here:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms633539%28v=vs.85%29.aspx

At least one of the following must be true:
  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked.
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.
Alternative solution is to use  AttachedThreadInputAction pattern:


Other "classic" approaches using Mutexes and EventWaitHandle:



VB style approach:

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;    // Add reference to Microsoft.VisualBasic

namespace WindowsFormsApplication1 {
    class Program : WindowsFormsApplicationBase {
        public Program() {
            this.EnableVisualStyles = true;
            this.IsSingleInstance = true;
            this.MainForm = new Form1();
        }
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {
            e.BringToForeground = true;
        }
        [STAThread]
        public static void Main(string[] args) {
            new Program().Run(args);
        }
    }
}

Thursday, January 9, 2014

Adaptive LINQ

Tuesday, February 5, 2013

Safely comparing local and universal DateTimes


When you call .Equal or .Compare, internally the value .InternalTicks is compared. This field isunequal, because it has been adjusted a couple of hours to represent the time in the universal time. You should see it this way: the DateTime object represents a time in an unnamed timezone, but not a universal time plus timezone. The timezone is either Local (the timezone of your system) or UTC. You might consider this a lack of the DateTime class.
When converting to another timezone, the time is — and should be — adjusted. This is probably why Microsoft chose to use a method as opposed to a property, to emphasize that an action is taken when converting to UTC.
Originally I wrote here that the structs are compared and the flag for System.DateTime.Kind is different. This is not true: it is the amount of ticks that differs:
t1.Ticks == t2.Ticks;       // false
t1.Ticks.Equals(t2.Ticks);  // false
To safely compare two dates, you could convert them to the same kind. If you convert any date to universal time before comparing you'll get the results you're after:
DateTime t1 = DateTime.Now;
DateTime t2 = t1;
t1.Compare(t1.ToUniversalTime(), t2.ToUniversalTime());  //true
The moral: never compare DateTime naively

Wednesday, January 11, 2012

DateTime.UtcNow is generally preferable to DateTime.Now

DateTime.UtcNow is generally preferable to DateTime.Now:
This seems to be commonly known and accepted best practice to use DateTime.UtcNow for non-user facing scenarios such as time interval and timeout measurement.
I’ve just done an audit of the Roslyn codebase and replaced most DateTime.Now calls with DateTime.UtcNow. I thought it’d be useful to post my changeset description here (although none of it is new – I just summarize some common knowledge readily available in the sources linked below).
====
Replacing DateTime.Now with DateTime.UtcNow in most cases.
We should be using DateTime.Now only in user-facing scenarios. It respects the timezone and Daylight Savings Time (DST), and the user feels comfortable when we show them the string that matches their wall clock time.
In all other scenarios though DateTime.UtcNow is preferable.
First, UtcNow usually is a couple of orders of magnitude faster, since Now is basically first calling UtcNow and then doing a very expensive call to figure out the time zone and daylight savings time information. Here’s a great chart from Keyvan’s blog:

Second, Now can be a big problem because of a sudden 1-hour jump during DST adjustments twice a year. Imagine a waiting loop with a 5-sec timeout that happens to occur exactly at 2am during DST transition. The operation that you expect to timeout after 5 sec will run for 1 hour and 5 seconds instead! That might be a surprise.
Hence, I'm replacing DateTime.Now with DateTime.UtcNow in most situations, especially polling/timeout/waiting and time interval measurement. Also, everywhere where we persist DateTime (file system/database) we should definitely be using UtcNow because by moving the storage into a different timezone, all sorts of confusion can occur (even "time travel", where a persisted file can appear with a future date). Granted, we don't often fly our storage with a supersonic jet across timezones, but hey.
For precise time interval measurements we should be using System.Diagnostics.StopWatch which uses the high resolution timer (QueryPerformanceCounter).
For a cheap timestamp, we should be generally using Environment.TickCount - it's even faster than DateTime.UtcNow.Ticks.
I'm only leaving DateTime.Now usages in test code (where it's never executed), in the compiler Version parsing code (where it's used to generate a minor version) and in a couple of places (primarily test logging and perf test reports) where we want to output a string in a local timezone.
Sources:
* http://www.keyvan.ms/the-darkness-behind-datetime-now
* http://stackoverflow.com/questions/62151/datetime-now-vs-datetime-utcnow
* http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance

Wednesday, December 7, 2011

Sharp Tests Ex: Unit Tests fluent assertion

Cute small framework for fluent assertions in Unit Tests.

Description from the project page:

SharpTestsEx (Sharp Tests Extensions) is a set of extensible extensions. The main target is write short assertions where the Visual Studio IDE intellisense is your guide. #TestsEx can be used with NUnit, MsTests, xUnit, MbUnit... even in Silverlight

Available at:

Samlpe source code:


Thursday, November 10, 2011

Unity 2 - InjectionMember usage


IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers);
What "injectionMembers" parameters are for?


The overload with the InjectionMember array is used, when you do not provide a configuration file, that the Unity container tells how to create an instance of the given type or if you want to create an instance on another way than defined in the configuration file. The overloads are used, when you want to configure an unity container without an configuration file. An InjectionMember can be an constructor, property or method call. The following code, taken from the Unity help, shows how to use InjectionMembers through the fluent interface of the container.

IUnityContainer myContainer = new UnityContainer();
myContainer.Configure<InjectedMembers>()
  .ConfigureInjectionFor<MyObject>( 
    new InjectionConstructor(12, "Hello Unity!"), 
    new InjectionProperty("MyStringProperty", "SomeText"));

<type type="MyObject" mapTo="MyObject" name="MyObject">
  <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> 
 
 
      <param name="someInt" parameterType="int"> 
        <value value="12"/>
      param> 
      <param name="someText" parameterType="string">
        <value value="Hello Unity!"/>
      param> 
    constructor> 
    <property name="MyStringProperty" propertyType="string">
      <value value="SomeText"/>
    property>
  typeConfig> type>
Another use case would be using InjectionFactory. For example:
var container = new UnityContainer();
container.RegisterType(new InjectionFactory((c) => Customer.NewCustomer()));
var newCustomer = container.Resolve();
Console.WriteLine(newCustomer.Name);

I use InjectionFactory when there is no chance to add an injection attribute for a third party class constructor or property. In this case you can create delegate creating an object.

Powered by Blogger.