Archive for March, 2009

Programmatically generating SQL(DDL) from M

In this post, i will show how you can generate SQL programmatically from M. Now, so far i have learnt that MGrammer is a contract that converts user’s input into MGraph. Now, Oslo by default comes with MSchema. Through MSchema you can define a type and extend it with MGraph to populate your repository. Here, i will use MSchema to define an entity object , then MGraph and finally run this through a custom SQL generator in C# to get my DDL statement similar to what you can generate by using intellipad that comes with Oslo SDK.

Let’s define a Contacts M

module Contacts {
    type Person {
        Id : Integer32;
        Name: Text;
        Age: Integer32;
    } where identity Id;
    
    People : Person*
    {    
        {Id = 1, Name="Steve",Age=36}, 
        {Id = 2, Name="Kazi",Age=30}
    };
    Employee : Person*
    {    
        {Id = 1, Name="Nike",Age=29} 
    };
}

So, “Person” is a type with ID,Name and Age respectively that is under “Contacts” module with two different MGraph which are “People” and “Employee” that will generate separate create table statements of “Person” type.

Internally , M is  represented somewhat like

image

Parsing the M all starts with Microsoft.M.Parser.SourceParser. In my sample M to SQL project, i used it like

SqlGenerator generator = SqlGenerator.Load(new StringReader(code));
string sql = generator.Generate();

Inside Load…

SourceParser parser = new SourceParser();
syntaxTerm = (CompilationUnit)parser.ParseTerm(reader, "buffer.m");
...
...

/// check if the parse was successful
if (!parser.LastParseSuccessful)
{
    /// do some error processing for invalid schema.
}

Now, once we have a valid grammar, our next step is to get the modules from ISytaxTerm implementation, for each module we have to process the MGraph for the specified type.

foreach (IModuleDeclaration declaration in syntaxTerm.Modules)
{
    builder.AppendSetExtactAbort();
    builder.AppendGo();

    builder.AppendBeginTransaction();
    builder.AppendGo();

    builder.AppendSetANSINulls();
    builder.AppendGo();

    builder.AppendCreateSchema(declaration.Name.Value);
    builder.AppendGo();
    builder.Append(ProcessMembers(declaration.Name.Value, declaration.Members));

    builder.AppendCommitTransaction();
    builder.AppendGo();
}

This shows the basic skeleton of how the output will look like. ProcessMembers is the actual place that generates the entity from type and associates Insert statements. Only, during the MGraph initialization type is realized. Therefore, the table name is equal to the extent name not to the type name.

Inside ProcessMembers …

/// There will be three declaration 
/// -TypeDeclaion
///- ExtentDeclaration
///- ExtnetDeclaration
foreach (IDeclaration declaration in declarations)
{
    if (declaration is TypeDeclaration)
    {
        typeDeclaration = (TypeDeclaration) declaration;
    }
 
    if (declaration is ExtentDeclaration)
    {
       /// use the type declaration from previous step.
        builder.Append(ProcessExtent(name, typeDeclaration, (ExtentDeclaration) declaration));
    }
}

TypeDeclaration is narrowed down to ParameteriedExpression , which has different operations for the declaring type, which is tracked by  DeclartionReference.Name (“$Operator$Where”, “$Operator$Identity” , etc). Therefore, to process constraint and data types separately, we need to switch them for operation type.  Now, the question is how the MGraph is referred from the type specified. The JSON like string  is basically translated to GraphExpression. Like for the “Person” type , we have three properties. GraphExpression.Successors.Count will be equal to numeric value 3 and each of those which are GraphExpression themselves will have only one successor which is a M.Literal. This will actually contain the property name, type and value for parent type ref.

GraphExpression graphExpression = (GraphExpression) extentDeclaration.InitialValue;

if (extentDeclaration.InitialValue != null)
{
foreach (GraphExpression successor in graphExpression.Successors)
{
    int index = 0;

    foreach (var expression in successor.Successors)
    {
        if (expression is GraphExpression)
        {
            GraphExpression node = (GraphExpression) expression;

            Literal literal = (Literal) (node).Successors[0];
           /// process fragment
        }

        index++;
    }
   /// process the final statement
}

That’s all to get started. All the code has been taken from a MSqlProvider that i created while learning M. The technology is itself in bleeding edge so things will change and i will share my updated knowledge forward. You can further enhance MSQLProvider to run the result in configured database along with the mx.exe that comes with Oslo SDK.

You can download the source here to play around and see it live.

Enjoy!!

kick it on DotNetKicks.com

Comments Off more...

Streaming large content from a WCF RESTFul service

Streaming large content such as media content, images or files is a common scenario for RESTful services. If a scenario like this is not well addressed or implemented on the service side, there is a high risk of consuming server resources like memory or CPU in a matter of seconds. This usually happens when the complete content is loaded in memory before it is transferred to the service consumer.

The WCF REST Starter kit introduced a new mechanism for addressing this scenario, an “AdapterStream” utility class, which basically pushes small pieces of content (and thus, only small memory buffers are used) to the client application as it becomes necessary.

The kit also comes with an example “PushStyleStreaming” that shows this class in action

Stream GetImage(string text)

{

    if (string.IsNullOrEmpty(text))

    {

        throw new WebProtocolException(HttpStatusCode.BadRequest, "text must be specified", null);

    }

    Bitmap theBitmap = GenerateImage(text);

    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";

    return new AdapterStream((stream) => theBitmap.Save(stream, ImageFormat.Jpeg));

}

In the code above, the AdapterStream is used to transfer an image to a service consumer. As you can also notice in that code, that class receives a lambda  expression or Action<T> delegate in the constructor. That provides some flexibility at the moment of generating the final stream that will be sent to the client application.

Another example that uses an TextWriter for generating text content,

  new AdapterStream((writer) =>

    {

        writer.WriteLine("You said: ");

        writer.WriteLine(text);

        writer.WriteLine("Didn't you?");

        writer.Flush();

    }, Encoding.UTF8);

In addition to this feature, you might also want to have a better control of service usage by restricting the throttling settings. This is a good thing about REST services implemented with the WCF stack. Other implementations such as the ASP.NET MVC rely on the ASP.NET for handling this aspect, where these settings are applied only at application domain level (For all services running in the same app).

Comments Off more...

Faking the Initialized Event in Silverlight

This is another nugget of gold gleaned from the Climbing Mt Avalon workshop, although I believe this one came from Jonathan Russ. He was talking about a bunch of threading tricks in WPF and showed how if you wanted to run some code after everything was initialized you could use the BeginInvoke method of the Dispatcher object. Since there are many places in my code where I want to execute something when the control loads, but only once (since the loaded event gets fired whenever the object gets re-added to the visual tree) I end up writing a lot of code like:

public partial class Page : UserControl
{
    private bool initialized = false;

    public Page()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(Page_Loaded);
    }

    void Page_Loaded(object sender, RoutedEventArgs e)
    {
        if (!initialized)
        {
            // do some initialization work
            initialized = true;
        }
    }

}

This works, but it isn’t perfect and there seems to be a lot of issues with the timing of the loaded event. So based on what Jonathan was saying, you could instead just put a call into BeginInvoke in the contructor like so:

public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
        Dispatcher.BeginInvoke(Initialized);
    }

    private void Initialized()
    {
        // do some initialization work
    }
}

So what is this actually doing? BeginInvoke puts a message in the message pump that is running under the covers of everything (note: I’m not a C++ programming so I don’t really fully understand message pumps so this is an over simplification). Because it is last in line in the queue of messages to process, it gets executed after all the other initialization code which has already lined up. If you debug this you will see it actually gets called after the Loaded event gets called. However, this code is the first thing to execute once everything has been loaded and setup which is usually when I want my code to execute.

So this is a much better way to handle initialization code since you aren’t adding event handlers that really only need to fire once and it executes once everything is fully initialized.


Comments Off more...

Faking the Initialized Event in Silverlight

This is another nugget of gold gleaned from the Climbing Mt Avalon workshop, although I believe this one came from Jonathan Russ. He was talking about a bunch of threading tricks in WPF and showed how if you wanted to run some code after everything was initialized you could use the BeginInvoke method of the Dispatcher object. Since there are many places in my code where I want to execute something when the control loads, but only once (since the loaded event gets fired whenever the object gets re-added to the visual tree) I end up writing a lot of code like:

public partial class Page
: UserControl { private bool initialized
= false; public Page() { InitializeComponent();
Loaded += new RoutedEventHandler(Page_Loaded); } void Page_Loaded(object sender,
RoutedEventArgs e) { if (!initialized) { //
do some initialization work initialized = true; }
} }

This works, but it isn’t perfect and there seems to be a lot of issues with the timing of the loaded event. So based on what Jonathan was saying, you could instead just put a call into BeginInvoke in the contructor like so:

public partial class Page
: UserControl { public Page() { InitializeComponent(); Dispatcher.BeginInvoke(Initialized);
} private void Initialized() { //
do some initialization work } }

So what is this actually doing? BeginInvoke puts a message in the message pump that is running under the covers of everything (note: I’m not a C++ programming so I don’t really fully understand message pumps so this is an over simplification). Because it is last in line in the queue of messages to process, it gets executed after all the other initialization code which has already lined up. If you debug this you will see it actually gets called after the Loaded event gets called. However, this code is the first thing to execute once everything has been loaded and setup which is usually when I want my code to execute.

So this is a much better way to handle initialization code since you aren’t adding event handlers that really only need to fire once and it executes once everything is fully initialized.


Animation Hack Using Attached Properties in Silverlight

In my last post I blogged about using Attached Properties to get around the limitation that only Dependency Properties can be animated. One astute commented noted that he was guessing this could be applied to animations as well and the answer is yet it can. However, it requires one extra step that makes it a little less appealing.

Also I mentioned in my last post, I got this idea from the Climbing Mt Avalon workshop at MIX which has now been posted online and I would recommend watching if you’re doing Silverlight or WPF work. And now on to the code…

Typically if you want to animating something like the width of a grid in a column that isn’t animatable either because it isn’t a double, color, or another easily animatable type, then you would declare a dependency property on your own host class, usually a UserControl, and then animate that instead. A good example is this blog post on the subject which is what I’ve referred to many times.

However, if we take the attached property route instead of putting the code in our user control, we could declare our own attached property to do the work for us. Here is a simple example:

public static class Attachments
{

    public static readonly DependencyProperty ColumnWidthProperty =
            DependencyProperty.RegisterAttached("ColumnWidth", 
            typeof(double), typeof(Attachments), 
            new PropertyMetadata(
                new PropertyChangedCallback(OnColumnWidthChanged)));

    public static void SetColumnWidth(DependencyObject o, double value)
    {
        o.SetValue(ColumnWidthProperty, value);
    }

    public static double GetColumnWidth(DependencyObject o)
    {
        return (double)o.GetValue(ColumnWidthProperty);
    }

    private static void OnColumnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((ColumnDefinition)d).Width = new GridLength((double)e.NewValue);
    }

}

Once we have this code we can now simply animate the attached property like so:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SilverlightApplication1"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.Resources>
            <Storyboard x:Name="expandBlue">
                <DoubleAnimation Storyboard.TargetName="blue"
                                 To="300" Duration="0:0:1" />
                <DoubleAnimation Storyboard.TargetName="red"
                                 To="100" Duration="0:0:1" />
            </Storyboard>
            <Storyboard x:Name="expandRed">
                <DoubleAnimation Storyboard.TargetName="red"
                                 To="300" Duration="0:0:1" />
                <DoubleAnimation Storyboard.TargetName="blue"
                                 To="100" Duration="0:0:1" />
            </Storyboard>
        </Grid.Resources>
        <Grid.ColumnDefinitions>
            <ColumnDefinition x:Name="blue" local:Attachments.ColumnWidth="200" />
            <ColumnDefinition x:Name="red" local:Attachments.ColumnWidth="200"/>
        </Grid.ColumnDefinitions>
        <Rectangle Grid.Column="0" Fill="Blue" MouseLeftButtonDown="Blue_MouseLeftButtonDown" />
        <Rectangle Grid.Column="1" Fill="Red" MouseLeftButtonDown="Red_MouseLeftButtonDown"/>
    </Grid>
</UserControl>

Unfortunately if you try the above code (after adding in the mouse event handlers) it won’t work. Why not? Well there seems to be an issue with animating custom attached properties when setting the target property directly in code (actually you’ll notice I left that out above. However, there is a way around it which I found over on Ed’s blog which is to set the target property in code. So here is the code behind with the work around:

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        Storyboard.SetTargetProperty(expandBlue.Children[0], new PropertyPath(Attachments.ColumnWidthProperty));
        Storyboard.SetTargetProperty(expandBlue.Children[1], new PropertyPath(Attachments.ColumnWidthProperty));
        Storyboard.SetTargetProperty(expandRed.Children[0], new PropertyPath(Attachments.ColumnWidthProperty));
        Storyboard.SetTargetProperty(expandRed.Children[1], new PropertyPath(Attachments.ColumnWidthProperty));
    }

    private void Blue_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        expandBlue.Begin();
    }

    private void Red_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        expandRed.Begin();
    }
}

Once we set the target property via code, then everything works great. However, that is a pain and makes things a lot less clean. But still I think this is a useful approach to animating the properties that are not easily animatable.


Comments Off more...

  • Sponsored Links

  •  

    March 2009
    M T W T F S S
    « Feb   Apr »
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031  
  • .

    Copyright © 1996-2010 Answer My Query. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress