Wednesday, 28 August 2013

How to find absolute position of control

The following code from MSDN come in very handy today, just change “this” to your control and it’ll give your the absolute position of your control on the page:

GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
Point offset = gt.Transform(new Point(0, 0));
double controlTop = offset.Y;
double controlLeft = offset.X;

Thursday, 15 August 2013

How to flip a path in xaml

For those with Blend installed simply select the path and set the transform properties:

image

If you don’t have Blend then you can use on the following properties:

<Path Width="50" 
Height="50"
Data="F1M1719.66,218.12L1735.66,246.166 1751.66,274.21 1719.66,274.21 1687.66,274.21 1703.66,246.166 1719.66,218.12z"
Fill="Red"
Stretch="Uniform"
RenderTransformOrigin="0.5,0.5">
<Path.RenderTransform>
<CompositeTransform Rotation="-180"/>
</Path.RenderTransform>
</Path>

Wednesday, 31 July 2013

List<string> to string

var strings = new List<string> { "blah", "de", "hoo", "ha" };

var result = strings.Aggregate((i, j) => i + " " + j);

Console.Write(result);
image001

And with a complex type, where a response has a collection of messages, each with a text property:

var messages = this.Response
.Messages
.Select(m => m.Text)
.Aggregate((i, j) => i + " " + j);

Friday, 19 July 2013

Sequential vs Parallel Service Requests

Sequential

image
public async Task<HttpResponseMessage> DownloadWithHttpClient()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://stevenhollidge.com/sample.json?" + DateTime.Now.Ticks);
var response = await httpClient.SendAsync(request);
return response;
}

private async void HttpClientGoButton_OnClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
await DownloadWithHttpClient();
}
}

Parallel


image
public async Task<HttpResponseMessage> DownloadWithHttpClient()
{
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://stevenhollidge.com/sample.json?" + DateTime.Now.Ticks);
var response = await httpClient.SendAsync(request);
return response;
}

private async void HttpClientGoButton_OnClick(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 9; i++)
{
DownloadWithHttpClient();
}
}

Saturday, 6 July 2013

C# client for Server Side Events (EventSource)

Examples of one way streaming from server to client can be found on the web but it’s pretty much always JavaScript clients.  Here is a working example using the .NET stack, with WebAPI as the server and a C# console application as the client.

Download and run this WebAPI chat application which emits Server Side Events:

https://github.com/filipw/html5-push-asp.net-web-api/

I then open Visual Studio running as admin, update the code to use IIS with my machine name (Zeus) and a virtual directory, clicking the create virtual directory button, so I can track requests using Fiddler:

image

Then update the JavaScript within the app to use the same path:

image

The create a Console application, using NUGET add Json.NET and paste this code in:

using System;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
new WebClientWrapper();
Console.ReadKey();
}
}

public class WebClientWrapper
{
WebClient wc { get; set; }

public WebClientWrapper()
{
InitialiseWebClient();
}

// When SSE (Server side event) occurs this fires
private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs args)
{
using (var streamReader = new StreamReader(args.Result, Encoding.UTF8))
{
var cometPayload = streamReader.ReadLine();
var jsonPayload = cometPayload.Substring(5);
var message = JsonConvert.DeserializeObject<Message>(jsonPayload);
Console.WriteLine("Message received: {0} {1} {2}", message.dt, message.username, message.text);
InitialiseWebClient();
}
}

private void InitialiseWebClient()
{
wc = new WebClient();
wc.OpenReadAsync(new Uri("http://zeus/chatapp/api/chat/"));
wc.OpenReadCompleted += OnOpenReadCompleted;
}
}

public class Message
{
public string username { get; set; }
public string text { get; set; }
public string dt { get; set; }
}
}


You’ll need to update the code for your machine name.


Now run Fiddler, the WebAPI project and the console app and add a message in the chat window:


image


In Fiddler, select the request your console just made and select Raw, you’ll see nothing.  Now right click and select COMETPeek and you’ll see the payload that was streamed.


image

Calling a WCF service over SSL with a certificate

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="binding_Default" maxReceivedMessageSize="2147483647">
<security mode="Transport">
<transport clientCredentialType="Certificate"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="endpointBehavior">
<clientCredentials>
<clientCertificate storeLocation="CurrentUser"
storeName="My"
findValue="28dfc90a0d22763ca41bb937e91925e10f9de7a4"
x509FindType="FindByThumbprint"/>
<serviceCertificate>
<authentication certificateValidationMode="None" revocationMode="NoCheck"/>
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="https://SERVERNAME/SERVICENAME"
binding="basicHttpBinding"
bindingConfiguration="binding_Default"
contract="NAMESPACE.INTERFACE"
name="MyServiceEndpoint"
behaviorConfiguration="endpointBehavior">
</endpoint>
</client>
</system.serviceModel>
</configuration>

image

Wednesday, 3 July 2013

WebApi.SelfHost

using System.Web.Http;
using System.Web.Http.SelfHost;

namespace Workflow.Console
{
class Program
{
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:8080");

config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });

using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
System.Console.WriteLine("Press Enter to quit.");
System.Console.ReadLine();
}
}
}
}
using System.Collections.Generic;
using System;
using System.Web.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Workflow.Console
{
public class DocumentUploadController : ApiController
{
public Guid Post([FromBody] DocumentRequest reportData)
{
var id = Guid.NewGuid();
Task.Factory.StartNew(() => CreateReport(id.ToString(), reportData.Parameter1));
return id;
}

private void CreateReport(string key, string documentData)
{
Thread.Sleep(5000);
DocumentDownloadController.Cache.Add(key, "GENERATED DOCUMENT: " + documentData);
}
}

public class DocumentDownloadController : ApiController
{
public static Dictionary<string, string> Cache = new Dictionary<string, string>();

public DocumentResponse Get(string id)
{
string document;
var response = new DocumentResponse { Id = id };
if (Cache.TryGetValue(id, out document))
{
response.IsAvailable = true;
response.Document = document;
}
else
{
response.IsAvailable = false;
}
return response;
}
}

public class DocumentRequest
{
public string Parameter1 { get; set; }
}

public class DocumentResponse
{
public string Id { get; set; }
public bool IsAvailable { get; set; }
public string Document { get; set; }
}
}
image

image


image


image


With XML:


image


or add this line to Program Main and you can remove the namespace from the xml:

config.Formatters.XmlFormatter.UseXmlSerializer = true;

image

Thursday, 27 June 2013

Updating MVC view based on model updated in code

The following code increments a model property in MVC3 and updates the UI:

[HttpPost]
public ActionResult Edit(Movie model)
{
var temp = model.Age + 1;
ModelState.Remove("Age");
model.Age = temp;

if (ModelState.IsValid)
{
db.Entry(model).State = EntityState.Modified;

db.SaveChanges();
//return RedirectToAction("Index");
}
return View(moviedb2);
}

CellTemplateSelector

In the telerik grid, if you would like to create a custom layout based on data in the row then you can do the following:

image

Notice how the price of a swap contains two values.

public class Trade
{
public int Id { get; set; }
public DateTime DealDate { get; set; }
public decimal Price { get; set; }
public Type Type { get; set; }
public decimal Price2Leg { get; set; }
}

public enum Type
{
NotSet = 0,
Option,
Swap,
Forward
}

public class Trade
{
public int Id { get; set; }
public DateTime DealDate { get; set; }
public decimal Price { get; set; }
public Type Type { get; set; }
public decimal Price2Leg { get; set; }
}

public enum Type
{
NotSet = 0,
Option,
Swap,
Forward
}

public class TradePriceCellTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var trade = (Trade)item;

return trade.Type == Type.Swap ? this.SwapTemplate : this.NormalTemplate;
}

public DataTemplate SwapTemplate
{
get;
set;
}

public DataTemplate NormalTemplate
{
get;
set;
}
}

 

<UserControl x:Class="DataTemplates.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:dataTemplates="clr-namespace:DataTemplates"
mc:Ignorable="d">

<UserControl.Resources>
<DataTemplate x:Key="NormalRow">
<StackPanel>
<TextBlock Text="{Binding Price}" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SwapRow">
<StackPanel>
<TextBlock Text="{Binding Price}" />
<TextBlock Text="{Binding Price2Leg}" />
</StackPanel>
</DataTemplate>

<dataTemplates:TradePriceCellTemplateSelector x:Key="tradePriceCellTemplateSelector"
NormalTemplate="{StaticResource NormalRow}"
SwapTemplate="{StaticResource SwapRow}"/>
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">

<telerik:RadGridView x:Name="TradeGrid"
RowDetailsVisibilityMode="Visible"
RowIndicatorVisibility="Collapsed"
GroupRenderMode="Flat"
Background="WhiteSmoke"
AutoGenerateColumns="False">
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn Header="DEAL ID / REF NO"
DataMemberBinding="{Binding Id}"/>

<telerik:GridViewDataColumn Header="DEAL DATE"
DataMemberBinding="{Binding DealDate, StringFormat='{}{0:dd.MM.yyyy}'}"/>

<telerik:GridViewDataColumn Header="TYPE"
DataMemberBinding="{Binding Type}"/>

<telerik:GridViewDataColumn Header="PRICE"
CellTemplateSelector="{StaticResource tradePriceCellTemplateSelector}" />
</telerik:RadGridView.Columns>
</telerik:RadGridView>
</Grid>
</UserControl>


Source:  https://github.com/stevenh77/DataTemplate/

Thursday, 23 May 2013

Xbox One Menu

image

image

image

image

image

image

Some nice HTML and CSS bits and pieces

https://aligntoday.com/Application/login.aspx

image

https://aligntoday.com/sales/request-demo.aspx

image

Gauge:  http://thecodeplayer.com/walkthrough/make-gauge-charts-using-canvas-and-javascript

image

Accordion menu:  http://thecodeplayer.com/walkthrough/vertical-accordion-menu-using-jquery-css3

image

Stop watch:  http://thecodeplayer.com/walkthrough/make-a-stopwatch-using-css3-without-images-or-javascript

image

Family tree:  http://thecodeplayer.com/walkthrough/css3-family-tree

image

Image slider(ish):  http://thecodeplayer.com/walkthrough/make-an-accordian-style-slider-in-css3

image

Overloading methods for derived classes

Using dynamic keyword to resolve double dispatch, overloaded methods using derived types at compile time.

image

using System;
using System.Collections.Generic;
using System.Reflection;

namespace OverloadedMethod
{
class Program
{
static void Main(string[] args)
{
var processor = new Processor();
var shapes = new List<Shape> {new Circle(), new Triangle()};

foreach (var shape in shapes)
{
// option 1
processor.GetType()
.GetMethod("Execute",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { shape.GetType() },
null)
.Invoke(processor,
new object[] { shape });

// or option 2 (requires known definition of all drived types and a line per type)
if (shape is Circle) processor.Execute(shape as Circle);
else if (shape is Triangle) processor.Execute(shape as Triangle);

// option 3... BOOM!!!! Works a treat :)
processor.Execute(shape as dynamic);
}
}
}

class Shape { }

class Circle : Shape
{
public int Circumference { get { return 10; } }
}

class Triangle : Shape
{
public int HypotenuseLength { get { return 20; } }
}

class Processor
{
internal void Execute(Circle circle)
{
Console.WriteLine("Executing with a Circle with circumference {0}!", circle.Circumference);
}

internal void Execute(Triangle triangle)
{
Console.WriteLine("Executing with a Triangle hypotenuse length of {0}!", triangle.HypotenuseLength);
}
}
}


Source:  https://github.com/stevenh77/OverloadedMethod/


So what about this, using an extension method?  Apparently Circle doesn’t have a definition for Execute…


image


Source:  https://github.com/stevenh77/OverloadedMethodExtensions/

using System;
using System.Collections.Generic;

namespace OverloadedMethod
{
class Program
{
static void Main(string[] args)
{
var shapes = new List<Shape> {new Circle(), new Triangle()};

foreach (var shape in shapes)
{
// option 4: so what about this....?
// (shape as dynamic).Execute(); // doesn't work
ExtensionMethods.Execute(shape as dynamic); // this works!
}
}
}

class Shape { }

class Circle : Shape
{
public int Circumference { get { return 10; } }
}

class Triangle : Shape
{
public int HypotenuseLength { get { return 20; } }
}

static class ExtensionMethods
{
public static void Execute(this Circle circle)
{
Console.WriteLine("Executing with a Circle with circumference {0}!", circle.Circumference);
}

public static void Execute(this Triangle triangle)
{
Console.WriteLine("Executing with a Triangle hypotenuse length of {0}!", triangle.HypotenuseLength);
}
}
}

Sunday, 19 May 2013

TortoiseSVN hidden features

Hold down the shift key before right clicking on a SVN repo and you see some hidden features! :)

image