Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Monday 4 November 2013

Subdomain with ASP.NET MVC using Attribute Routing

ASP.NET MVC Routing allows defining various mappings and recently I have looked at an interesting framework known as Attribute Routing.

Using Attribute Routing setting up a subdomain for your website that uses ASP.NET MVC is very simple. Now consider you have a website www.csharptechies.com and you would want to define subdomains such as blog.csharptechies.com, projects.csharptechies.com, labels.csharptechies.com etc.... Each of these subdomain can be a different project (any technology such as webforms, MVC etc) by themselves or can be an area defined in an ASP.NET MVC project.

Lets consider we are going to follow the approach of having areas inside ASP.NET MVC project. Here are the list of steps to achieve this.

1. Create your ASP.NET MVC project with all the content and publish to your IIS. You should now be able to access your website using http://localhost/csharptechies or based on your machine http://saifpc.localhost.com/csharptechies. You could define hosts file to include the references.

I have added following to "hosts" file under C:\Windows\System32\Drivers\etc with data as

127.0.0.1 www.csharptechies.com

Now website can be accessed as www.csharptechies.com\csharptechies(ie.. http://localhost/csharptechies)

2. Lets code for subdomain routing. First add references for attribute routing via nuget using "Install-Package AttributeRouting"

3. Create an area with the name "Blog".

4. Add a new folder "Blog" under "Areas\Blog\Views". create a new view "articles" under "Areas\Blog\Views\Blog"

5. Add a controller BlogController.cs with following code under "Areas\Blog\Controllers"
 [RouteArea("Blog", Subdomain = "blog")]
    public class BlogController : Controller
    {
        //
        // GET: /articles/
        [GET("")]
        public ActionResult articles()
        {
            return View();
        }
    }
6. Update "AttributeRoutingConfig.cs" to add routing to blog
public static class AttributeRoutingConfig
 {
  public static void RegisterRoutes(RouteCollection routes) 
  {   
routes.MapAttributeRoutes(config => config.AddRoutesFromController());
  }

        public static void Start() 
  {
            RegisterRoutes(RouteTable.Routes);
        }
    }

7. Now add new entry to hosts file

127.0.0.1 blog.csharptechies.com

8. Publish latest version of the project and using IE browse to the website as

http://blog.csharptechies.com/csharptechies

This will show the view as articles, since BlogController now understands the attribute definition of subdomain as "blog" it will route the url to blog instead of standard csharptechies website. You could also look at possible routing via www.csharptechies.com\csharptechies\routes.axd

Technology is just a tool. In terms of getting the kids working together and motivating them, the teacher is the most important.
Bill Gates

Friday 25 October 2013

Restricting access to a webservice in ASP.NET

Restricting access to a webservice can be done via web.config but if you would want to make the decision at runtime then here is an example of how you could achieve this
 

protected void Application_BeginRequest(Object sender, EventArgs e)
{
  if (/*Condition*/)
  {
    if (HttpContext.Current.Request.Url.ToString().Contains("Admin.asmx"))
    {
       HttpContext.Current.Response.StatusCode = 404;
    }
   }
}
Genius ain't anything more than elegant common sense.
Josh Billings

Wednesday 16 October 2013

Mock frameworks for .NET Part 2

As we have already seen the basics of Mock framework, let's look at some of Mock frameworks that are available and understand what they do or don't support.

NMock


Software License Apache License 2.0
Last Active Jul-2011
Latest Version NMock3
Supported .NET Version .NET 4.0
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything No
Mock Legacy Code No
Auto Recursive Fakes No
Fake Dependencies No
Url http://nmock3.codeplex.com/

TypeMock


Software License Commercial
Last Active Jul-2013
Latest Version Isolater 7.4.1
Supported .NET Version .NET 4.0
Build Server Integration Yes (Microsoft TFS, MSBuild, Nant, Final Builder)
Code Coverate Integration Yes (CoverageEye, NCover, PartCover, DevPartner, Clover.NET, ExactMagic's TestMatrix, MSTest Code Coverage (Visual Studio and Team System), dotTrace, ReSharper, AQtime)
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code Yes
Auto Recursive Fakes Yes
Fake Dependencies Yes
Url http://www.typemock.com/isolator-product-page

Rhino Mocks


Software License BSD license
Last Active Jan-2010
Latest Version Rhino Mocks 3.6
Supported .NET Version .NET 3.5
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code No
Auto Recursive Fakes No
Fake Dependencies No
Url http://hibernatingrhinos.com/oss/rhino-mocks

Moq


Software License BSD license
Last Active Apr-2011
Latest Version Moq 4.0
Supported .NET Version .NET 3.5
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code No
Auto Recursive Fakes No
Fake Dependencies No
Url https://code.google.com/p/moq/

Nsubstitute


Software License BSD license
Last Active Aug-13
Latest Version NSubstitute-1.6.1.0
Supported .NET Version .NET 4.0
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code No
Auto Recursive Fakes No
Fake Dependencies No
Url http://nsubstitute.github.io/

JustMock


Software License Full Version - Commercial, Lite - Free
Last Active Oct-2013
Latest Version V 2013.3.1015.0
Supported .NET Version .NET 4.0
Build Server Integration Yes (TFS, CruiseControl.NET, Team City & Jenkins etc)
Code Coverate Integration Yes (NCover, PartCover, JetBrains dotTrace, PostSharp etc)
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code Yes
Auto Recursive Fakes Yes
Fake Dependencies Yes
Url http://www.telerik.com/products/mocking.aspx

FakeItEasy


Software License MIT License
Last Active Oct-2013
Latest Version v 1.13.1
Supported .NET Version .NET 3.5
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code No
Auto Recursive Fakes Yes
Fake Dependencies No
Url https://github.com/FakeItEasy/FakeItEasy

Microsoft Flakes


Software License Commercial with Visual Studio
Last Active Mar-2013
Latest Version -
Supported .NET Version .NET 4.0
Build Server Integration No
Code Coverate Integration No
Mock Interfaces Yes
Mock Everything Yes
Mock Legacy Code No
Auto Recursive Fakes No
Fake Dependencies No
Url http://msdn.microsoft.com/en-us/library/hh549175.aspx


Now you should be able to select the right framework that suits your needs.

It's fine to celebrate success but it is more important to heed the lessons of failure.
Bill Gates

Monday 7 October 2013

Mock frameworks for .NET Part 1

Mock frameworks are used for unit testing your code and are used for Test Driven Development (TDD). A mock framework should support Arrange Act Assert (AAA) pattern. There are various mock frameworks available and choosing the right one is not easy. Before looking at various frameworks available let's understand some basics of what a framework should have to be known as a Mock framework.

Mock Interfaces & abstract classes

Interfaces or Abstract classes allows Mock framework to be able to create stubs, A stub is a small block of code that is replacement of another component or code block. TDD approach of R-G-R (Red-Green-Refactor) is an example where a stub might be useful. In order to make a test successfull (Green), you would need a stub for places where actual definition is either not written or unknown.

Mock Everything in .NET

Able to mock everything in a class, such as
  • mock dependent objects
  • non-virtual methods
  • sealed classes
  • static methods
  • static classes
  • non-public members
  • non-public types

Mock Legacy Code

Assume some legacy code that has got some core business logic but has been designed/coded way before TDD has even started
  • no interfaces
  • no abstract classes
  • has dependencies

Auto Recursive Fakes

Once a mock is created some methods and properties will automatically return non null values such as interfaces, delegate, virtual class etc. This is also known as recursive mock.

Fake Dependencies

If a mock is dependent on another object, framework should allow to either populate or assign dependency so as to make the test succeed. Most of the frameworks will support it by default.

Unit Test Integration

Allow easy integration with unit test tools such as NUnit, MSTest, Xunit etc.

Build Server Integration

Mock framework should allow you to be able to automate unit tests as part of your build & continuous integration. It should be able to support various build servers such as TFS, MSBuild, Nant, CruiseControl.NET etc

Code coverage Integration

Mock framework should allow to be integrated with 3rd party code coverage so as to produce various metrics that can easily point out areas of code that has not been covered by a unit test or has been wrongly written. It should be able to support various 3rd party code coverage software such as NCover, MSTest Code Coverage, ReSharper etc.

All of the these are only related to .net code. The mock framework features that are required for javascript mocking is out of scope of this article. The list of mock frameworks can be seen at Mock frameworks for .NET Part 2

Intelligence is the ability to adapt to change.
Stephen Hawking

Wednesday 25 September 2013

Using ASP.NET Web API for streaming pictures

ASP.NET Web API 2.0 provides various new features and one of which is Attribute Routing. Attribute routing allows custom configuration for routing by assigning attribute to the web method.

Get latest version of ASP.NET Web API 2.0 via Nuget package
Install-Package Microsoft.AspNet.WebApi.WebHost
Update WebApiConfig to include config.MapHttpAttributeRoutes()
 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
The [HttpGet] attribute defines an HTTP GET method. Now create RESTful endpoint using web api
[HttpGet("api/invoice/scan/{id}")]
public HttpResponseMessage GetScannedInvoiceById(string id)
{
 HttpResponseMessage result = new HttpResponseMessage();
 string isPath = GetInoviceScanPath(id);
        result.Content = new StreamContent(new FileStream(isPath, FileMode.Open));
 result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
 return result;
}
http://localhost/csharptechies/api/invoice/scan/1908765 will now get the image as HttpResponseMessage.

Apart from using attributes to define an uri for controller methods, Route Prefixes can be defined as a controller attribute that will become base uri for for all of the controller methods.

Do you realize if it weren't for Edison we'd be watching TV by candlelight.
Al Boliska

Saturday 21 September 2013

Server Side MVC vs Client Side MVC

MVC (Model–view–controller) is an architecture patterns that addresses separation of concerns, test driven development, statelessness, extensibility, SEO, REST and many more. Choosing MVC pattern for developing web application is a very easy decision, but that is just the beginning. Rest of decision is deciding how to design, develop and implement the web application.Now deciding on "Server Side MVC" or "Client Side MVC" is not any easy job as there are number of options available.

Server Side MVC

Overview

Server side MVC is a combination of server-side framework and javascript/jquery. There are various server-side framework's available depending on the platform you are developing. Here is a list of few of them

Why

Various benefits of using Server Side MVC are
  • Mature (been there for year)
  • Routing decided by Server
  • Server renders the views
  • Server binds model to views
  • View request can return html, json, xml, text, binary etc
  • CRUD managed by Controller & Data Models on Server
  • Code security
  • Routing decided on application start
  • Supports multi-page application

Client Side MVC

Overview

Client Side MVC is a combination of js frameworks and REST API. Partially still relies on server side application for providing REST API. There are various client-side framework's available depending on your choice of coding style. Here is a list of few of them

Why

  • Recently introduced but got more attention now (look at the list of examples where backbone.js is used
  • Routing decided by Client
  • Client renders the views
  • Client binds model to views via javascript frameworks
  • Uses REST API for getting data from server
  • CRUD managed by Controller & Data Models on Client via REST API
  • Started with single-page application, but now various frameworks support multi-page application
  • Routing can be modified dynamically as it is maintained on client


Look at TODO MVC for more options on Client Side MVC.

Also you could use mixture of both Server Side MVC and Client Side MVC. I have used this combination ASP.NET MVC + KnockoutJS on Techcipher.

Think? Why think! We have computers to do that for us.
Jean Rostand

Sunday 15 September 2013

Streaming millions of rows as a csv in ASP.NET MVC

Generating reports using the data from the database is something any project will generally have, but to be able to actually download all of the data as a csv is not easy. Not just thousands of rows but if database has millions of rows then challange will be to decide best approach. Consider following approaches

1. Generate the report on server and then stream the file to clients machine

2. Stream data in batches onto client machine

First approach is not a good idea as there is no feedback to the user when download will actually start, but with second option user will actually see the streaming immediately.

So let's look at option 2 and how that can be achieved

1. Define a custom result that derives from FileResult
public class CsvResult : FileResult
{
   protected override void WriteFile(HttpResponseBase response)
   {
            response.Clear();
            response.ClearContent();
            response.BufferOutput = false;
            var streamWriter = new StreamWriter(response.OutputStream, Encoding.UTF8);
            //write the header line first
            streamWriter.WriteLine("InvoiceDate,InvoiceNumber,Quantity,Price");
            long count = GetInvoiceRecCount();
            
            long batchSize = 10000;
            long numberOfBatches = count / batchSize;
            long startRow = 0;
            for (int i = 0; i < numberOfBatches; i++)
            {
                startRow = i * batchSize;
                //Get batch of rows
                var invoiceRows = GetInvoiceRows(startRow, batchSize);
                foreach(DataRow row in invoiceRows)
                {
                    //write data 
                    streamWriter.WriteLine(dataLine);
                }

                streamWriter.Flush();
            }

            if (startRow + batchSize < count)
            {
                batchSize = count - startRow;
                //Get batch of rows
                var invoiceRows = GetInvoiceRows(startRow, batchSize);
                //write final batch
                foreach (DataRow row in invoiceRows)
                {
                    //write data 
                    streamWriter.WriteLine(dataLine);
                }

                streamWriter.Flush();
            }
   }

}
2. Now write controller action
public ActionResult ExportInvoicesToCsv()
{
   CsvResult csvResult = new CsvResult();
   csvResult.FileDownloadName = "InvoiceReport.csv";
   return csvResult;
}
And that's it all done. Now when user tries to download millions of rows as csv they are batches in the size of 10000 and will be streamed to users machine.

Technology is just a tool. In terms of getting the kids working together and motivating them, the teacher is the most important.
Bill Gates

Wednesday 17 July 2013

Enabling HTTP Handler to render in IE Compatibility mode

HTTP handlers are generally used for download a file, show an image, or even to show a report (ie.. generated as html at runtime and stream it through)

Now consider your html report was generated and now all you need to do is show through your website using ASP.NET http handler. Opening the report html just show all the formatting properly but via http handler some of styles were not correctly applied.

To resolve this you have got 2 options
- Modify your CSS to render it properly
- Force your handler to render in compatibility mode

In order to force your handler to render in compatibility mode all you need is to just add a header

for eg you can force usage of IE8
Response.AddHeader("X-UA-Compatible", "IE=EmulateIE8");


or use microsoft standard. Refer to microsoft article "Specifying legacy document modes"
Response.AddHeader("X-UA-Compatible", "IE=edge");


Be nice to nerds. Chances are you'll end up working for one.
Bill Gates, Microsoft

Wednesday 10 July 2013

Using Selenium WebDriver to simulate button click for ASP.NET Webforms application that uses DevExpress Controls

First lets create a simple ASP.NET Web application that uses DevExpress controls. I have created a test.aspx page that has got 2 buttons





Code behind (test.aspx.cs)

protected void TestMe_Click(object sender, EventArgs e)
{
  Response.Redirect("success.aspx");
}

protected void TestMe2_Click(object sender, EventArgs e)
{
  Response.Redirect("Fail.aspx");
}


Now here is the snippet of code that can be used to simulate button click
WebDriver driver = new InternetExplorerDriver(@"C:\selenium\selenium-dotnet-2.33.0\IEDriverServer_x64_2.33.0");
driver.Navigate().GoToUrl("http://localhost/test/Test.aspx");
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
var result = js.ExecuteScript("TestMe.click();");
//or
IWebElement btn = driver.FindElement(By.Id("TestMe"));
btn.Click();

Use this Quick Start guide to setup your machine for testing ASP.NET Web applications. For more detailed or complete understanding goto Selenium WebDriver

Nearly all men can stand adversity, but if you want to test a man's character, give him power. Abraham Lincoln

Thursday 13 June 2013

Live tiles with Bootmetro and Metro JS

Bootmetro is a simple web ui framework which I have used on my website TechCipher. There are various samples inside Bootmetro for implementing various type of tiles but not for live tiles. This article will give you insight of how live tiles can be implemented with Bootmetro and Metro JS. 1. Define tile
       
  
Latest Updates
Bootmetro is a simple web ui framework
TechCipher is all about exploring technologies available to date
2. Add references to MetroJs (css and js)

..

3. Finally make your tile live

Now this is how it would look

That's it.

“Before software should be reusable, it should be usable.” – Ralph Johnson

Thursday 6 June 2013

Input string was not in a correct format exception thrown by DevExpress controls

Recently I have stumped upon an exception thrown by DevExpress controls and this is trace :
2013-06-04 15:29:37.9138   6: csdrtg55bpufcimx3dm2o145 Error:global_asax threw EXCEPTION: Input string was not in a correct format.
2013-06-04 15:29:37.9138   6: csdrtg55bpufcimx3dm2o145    SOURCE:mscorlib 
2013-06-04 15:29:37.9138   6: csdrtg55bpufcimx3dm2o145    METHOD:StringToNumber 
2013-06-04 15:29:37.9138   6: csdrtg55bpufcimx3dm2o145    STACK is as follows:
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at DevExpress.Web.ASPxEditors.ListEditItemsSerializingHelper.ParseItemIndex(String serializedItem, Int32& startPos)
   at DevExpress.Web.ASPxEditors.ListBoxItemsSerializingHelper.DeserializeItems(String serializedItems, Boolean sortRequired)
   at DevExpress.Web.ASPxEditors.ListBoxProperties.SynchronizeItems(String serializedItems, Boolean isInsertingSyncType)
   at DevExpress.Web.ASPxEditors.ASPxComboBox.SynchronizeItems(NameValueCollection postCollection)
   at DevExpress.Web.ASPxEditors.ASPxComboBox.LoadPostData(NameValueCollection postCollection)
   at DevExpress.Web.ASPxClasses.ASPxWebControl.LoadPostDataInternal(NameValueCollection postCollection, Boolean raisePostDataEvent) 
2013-06-04 15:29:39.7810   6: csdrtg55bpufcimx3dm2o145 Callback error message : Input string was not in a correct format. 


Everything works fine If I debug the code and I am not able to see any exception been thrown. So made so many changes to code to see cause of failure but finally gave up. Then realised that visual studio allows you to catch CLR exceptions and here are the steps I have taken to find out the culprit :
1. First disable "Just My Code".
Tools -> Options



2. Enable CLR exceptions
Debug -> Exceptions



3. Now start debugging the code and skip all exceptions until you reach the exception that you are looking for.

4. After seeing the exception that you are looking for, use "Ok" button not "Continue" button.

5. Now see call stack window



6. You will have enable "Parameter Names" to see the control name that has caused the issue



Now your callstack should show something like this



Callstack will show you the control name and its data that has caused the failure.

Man is the best computer we can put aboard a spacecraft... and the only one that can be mass produced with unskilled labor. ~Werner von Braun

Friday 26 April 2013

Set deadlock priority with NHibernate

Sometimes you would want to explicitly set dead lock priority as part of a transaction which is not possible if you are using NHibernate as of now. In such cases you can define a custom Interceptor which does the trick. Here is a small snippet of code that can help you achieve that:
public class DeadLockPriorityInterceptor : EmptyInterceptor
{
 private ISession session;
 private string priority;

 public DeadLockPriorityInterceptor(string Priority)
 {
  priority = Priority;
 }

 public override void AfterTransactionBegin(ITransaction tx)
 {
  using (var command = session.Connection.CreateCommand())
  {
   session.Transaction.Enlist(command);
   string sql = string.Format("SET DEADLOCK_PRIORITY {0}", priority);
   // Create a SQL Command
   //System.Data.IDbCommand command = session.Connection.CreateCommand();
   // Set the query you're going to run
   command.CommandText = sql;
   // Run the query
   command.ExecuteNonQuery();
  }
 }

 public override void SetSession(ISession sessionLocal)
 {
  session = sessionLocal;
 }
}
Now your interceptor is ready. So if you would like to set your deadlock priority to High (ie.. SET DEADLOCK_PRIORITY HIGH), then just use following single line of code shown below:

ISession session = sessionFactory.OpenSession(new DeadLockPriorityInterceptor("HIGH"));
session.BeginTransaction()

This is how it works

1. sessionFactory.OpenSession will pass the interceptor to session.
2. OpenSession() verifies if there are any interceptors defined in this case it will be "DeadLockPriorityInterceptor".
3. Executes SetSession() as it is overridden by an interceptor.
4. session.BeginTransaction() will start the transaction.
5. BeginTransaction() verifies if an interceptor is defined by OpenSession().
6. Executes AfterTransactionBegin() as it is overridden by an interceptor.

That's it. NHibernate offers various interceptor points which will become quite handy at times.

“Simplicity, carried to the extreme, becomes elegance.” – Jon Franklin

Wednesday 24 April 2013

CompositeId() throws exception - Could not compile the mapping document: (XmlDocument)

After defining a map for composite key

 CompositeId()
                .KeyProperty(x => x.title)
                .KeyProperty(x => x.label);
The following exception is raised when trying to create a composite key
CreateSessionFactory() - Inner exception: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
..
CreateSessionFactory() - Inner exception: Could not compile the mapping document: (XmlDocument)
CreateSessionFactory() - Inner exception: composite-id class must override Equals(): CSharpTechies.Data.Entities.post
This means "post" entity definition should override at least 2 members GetHashCode() and Equals(object obj) Now here is how code snippet looks
public override int GetHashCode()
{
 int hashCode = 0;
 hashCode = hashCode ^ title.GetHashCode() ^ label.GetHashCode();
 return hashCode;
}

public override bool Equals(object obj)
{
 var toCompare = obj as post;
 if (toCompare == null)
 {
  return false;
 }
 return (this.GetHashCode() != toCompare.GetHashCode());
} 
Remember if the entity "post" is referenced elsewhere (ie.. foreign key) then you might get some more exceptions
CreateSessionFactory() - caught EXCEPTION: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
..
CreateSessionFactory() - Inner exception: Foreign key (FK36342426872A80CB:AuthorPosts [Post_id])) must have same number of columns as the referenced primary key (Post[title, label])
So update reference mapping as
  References(x => x.Post)
                .Columns(new string[] { "title", "label" })
                .Not.Update()
                .Not.Insert();
or one-to-many mapping as
 HasMany(x => x.Posts)
                .KeyColumns.Add("title")
                .KeyColumns.Add("label")
                .Not.LazyLoad()
                .Inverse();


“We have to stop optimizing for programmers and start optimizing for users.” – Jeff Atwood

Saturday 13 April 2013

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Have encountered with an sql error after running following sql:
INSERT INTO [Member](FirstName, LastName, CreationDate, LastActivityDate) 
VALUES ('Saif', 'Ikram' , '13/04/2013 22:15:44', '01/01/1753 00:00:00')
go

"The conversion of a varchar data type to a datetime data type resulted in an out-of-range value". Actually there is nothing wrong with sql. Now run following sql to see if this works
set language british
go
INSERT INTO [Member](FirstName, LastName, CreationDate, LastActivityDate) 
VALUES ('Saif', 'Ikram' , '13/04/2013 22:15:44', '01/01/1753 00:00:00')
go

Now surprisingly this works, only addition is assigning language to "British". As I am using NHibernate this still is not acceptable. So I have updated my default language
USE CSharpTechies;
GO
EXEC sp_configure 'default language', 1033 ; 
GO
RECONFIGURE ;
GO
1033 for "British English" as described in msdn sys.syslanguages. But this also failed. The reason was the user that sql is run as. So update the language setting for user
EXEC sp_defaultlanguage 'saif', 'british'
sql now executes without any error

Education makes machines which act like men and produces men who act like machines. ~Erich Fromm

Thursday 4 April 2013

Consuming return value from stored procedure using NHibernate without mapping

After haggling around I have found a solution that works. First I have created a stored procedure as follows:

CREATE PROCEDURE GETTOTALINCOME
AS 
DECLARE
     @TOTALINCOMECOUNT MONEY;
BEGIN
     SELECT @TOTALINCOMECOUNT = SUM(INVAMOUNT) FROM INVOICE
     RETURN @TOTALINCOMECOUNT;
END;
This is a simple stored procedure that just returns a value. Now lets look at NHibernate code block that can execute the stored procedure and read the return value.

using (var session = OpenSession())
{
     var query = session.CreateSQLQuery("EXEC GETTOTALINCOME");
     object result = query.UniqueResult();
     retVal = Convert.ToInt64(result);
}
I am getting exceptions so I started debugging it and have found "result" is null. I have looked at some articles of using stored procedure, but I do not want to define mapping either FulentNHibernate mapped classes or .hbm configuration.

I have looked again into stored procedure definition, NHibernate can read the values that are returned by a "SELECT" statement but not "RETURN". So I have changed my stored procedure as follows:

CREATE PROCEDURE GETTOTALINCOME
AS 
DECLARE
     @TOTALINCOMECOUNT MONEY;
BEGIN
     SELECT @TOTALINCOMECOUNT = SUM(INVAMOUNT) FROM INVOICE
     SELECT @TOTALINCOMECOUNT;
END;
Now this works.

“We have to stop optimizing for programmers and start optimizing for users.” – Jeff Atwood

Monday 25 March 2013

First Release of TechCipher 0.0.13.2303 Beta

First version of TechCipher 0.0.13.2303b released. TechCipher is for Developers, Technical or Solution Architects. TechCipher helps anyone to explore various technologies available in the market to date.

This first public beta release is readonly, you will be able to browse and explore various options.

TechCipher on first glance will show 2 sections
- Type of Applications (An application that has been or can be developed falls into one of these categories)
- Patterns (List of industrial patterns that are available in various arena's )

Next release will include

- User Login via TechCipher, Google, Facebook
- Allow users to comment on articles or categories
- Allows users to publish new categories or articles

If you would like to either contribute or provide feedback click on the link TechCipher

Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.

Sunday 6 January 2013

Custom splash screen for windows store app

Visual Studio 2012 provides various templates for developing windows store app (WinRT apps) such as Blank App, Grid App & Split App. All of these templates allows displaying a splash screen which is nothing but a static image. Sometimes that will not be the ideal solution so why not design a custom splash screen which shows some progress. So this is how it looks


Now lets look at the mechanics of this can be done. First create an windows store app by using any of the default templates. Add a new "Blank Page" to you application. Add a grid (with darkgray background) and progressring as shown below :


    
        
        
                    
        
        
    

In this sample I would like to initialize some data before actually displaying main page and also would like to show user what's being done during initialization such as:

Connecting to database ....
Populating data ....
Initialisation Completed.

So I have used DispatcherTimer. look at the code below:-
 public sealed partial class LoadingSplashScreen : Page
    {
        internal bool dismissed = false; // Variable to track splash screen dismissal status.
        private SplashScreen splash;
        internal Frame rootFrame;

        public LoadingSplashScreen(SplashScreen splashscreen, bool loadState)
        {
            this.InitializeComponent();
            lblProgress.Text = "Loading ....";
            if (splash != null)
            {
                // Register an event handler to be executed when the splash screen has been dismissed.
                splash.Dismissed += new TypedEventHandler(DismissedEventHandler);
            }
            rootFrame = new Frame();
        }

        // Include code to be executed when the system has transitioned from the splash screen to the extended splash screen (application's first view).
        void DismissedEventHandler(SplashScreen sender, object e)
        {
            dismissed = true;

            // Navigate away from the app's extended splash screen after completing setup operations here...
            // This sample navigates away from the extended splash screen when the "Learn More" button is clicked.
        }

        DispatcherTimer dispatcherTimer;
        int timesTicked = 1;

        public void DispatcherTimerSetup()
        {
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += dispatcherTimer_Tick;
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            dispatcherTimer.Start();
            //IsEnabled should now be true after calling start
            lblProgress.Text = "Connecting to database ....";
        }

        void dispatcherTimer_Tick(object sender, object e)
        {
            DateTimeOffset time = DateTimeOffset.Now;
            timesTicked++;
            if (timesTicked == 2)
            {
                lblProgress.Text = "Populating data ....";
            }

            if (timesTicked == 4)
            {
                lblProgress.Text = "Initialisation Completed";
                dispatcherTimer.Stop();                               
                rootFrame.Navigate(typeof(ItemsPage), "AllGroups");
                // Place the frame in the current Window 
                Window.Current.Content = rootFrame;
            }
        }

        void LoadingSplashScreen_Loaded(object sender, RoutedEventArgs e)
        {
            DispatcherTimerSetup();
        }

        /// 
        /// Invoked when this page is about to be displayed in a Frame.
        /// 
        /// Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }
    }
So far we have designed and coded custom splash screen. Now here are the steps that will show this custom splash screen

1. create a new image with the color filled with darkgray and save it to assets folder as "splashscreen2.png"

2. using "Package.appxmanifest" assign splash screen properties as

background : darkGray
image : assests\splashscreen2.png

3. Edit code-behind for App.xaml as follows:
 protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame; 
if (args.PreviousExecutionState != ApplicationExecutionState.Running)
            {
                bool loadState = (args.PreviousExecutionState == ApplicationExecutionState.Terminated);
                LoadingSplashScreen loadingSplashScreen = new LoadingSplashScreen(args.SplashScreen, loadState);
                Window.Current.Content = loadingSplashScreen;
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }

All done.
Technology is just a tool. In terms of getting the kids working together and motivating them, the teacher is the most important. - Bill Gates
Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers