29 May 2012

Customer KnockoutJS Validation

This article is the second on KnockoutJS series I am writing.
The first article was introductory: Customer KnockoutJS and MVC demo using JSON

Now I am going to focus on KnockoutJS and validation. I am going to use a KnockoutJS Plugin for model and property validation that is named Knockout Validation. You can download it from here.

The Asp.Net MVC Controller have the actions to Get and Add a customer. This example has a new customer property: the country.
This property allows to add an input type select to KnockoutJS and validation.
namespace KnockoutDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "";

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Get(int customerID)
        {
            // Get the customer ...
            Customer customer = new Customer {CustomerID = customerID, 
                                              FirstName = "John", 
                                              LastName = "Doe", 
                                              IsMale = true, 
                                              CountryID = 1 };
            return Json(customer);
        }

        [HttpPost]
        public JsonResult Add(Customer customer)
        {
            // Save the customer ...

            // return status message 
            var message = string.Format("Customer: {0} {1} Added. IsMale: {2} Age:{3}  CountryID: {4} ",
                                        customer.FirstName, customer.LastName, customer.IsMale.ToString(), 
                                        customer.Age.ToString(), customer.CountryID.ToString());
            return Json(message);
        }

    }
}

The Asp.Net MVC model is the customer with the new property:
 namespace KnockoutDemo.Models
{
    public class Customer
    {

        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsMale { get; set; }
        public int Age { get; set; }
        public int CountryID { get; set; }
    }
}


The Asp.Net MVC Layout includes the new knockout validation plugin:
       
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.validation.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>Knockout Demo</h1>
            </div>
            <div>&nbsp;</div>
        </header>
        <div>&nbsp;</div>
        <div>&nbsp;</div>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>
And the Asp.Net MVC view has the KnockoutJS and validation specifics:
@{
    ViewBag.Title = "Add Customer";
}



@ViewBag.Message

Customer Number:

First Name: Last Name: Age: Male Country:


The KnockoutJS now has a observableArray of countries in the VewModel, that is bind to the country select.
Note the data-bind oprtions of the select:
- options: controls what options should appear in a drop-down lis
- optionsValue: The name of the ViewModel property to bind to the option value
- optionsText: The name of the ViewModel property to bind to the option text
- value: The name of the ViewModel property to bind to the selected value
- optionsCaption: The option that is used to make the user select a value on the select list

There is also the validation plugin specifics in the VewModel declaration:
- The extend is used to extend the observables with the validation rules. (you can read about all of them here)
In the example I am using the required  (required: true) and number (number: true) validation rules.
- validatedObservable in the view model declaration
- isValid() - Before saving the data validate that the model is valid
- validation.init - Used to configure the validation engine

In the example the invalid inputs are painted in red, that is where the css class is used by the validation.

07 May 2012

Customer KnockoutJS and MVC demo using JSON

After reading about KnockoutJS I have decided to create a simple demo using JSON to comunicate with the web server.
The application retrieves a Customer from an ASP.Net MVC Action and sends it to be saved.

The KnockoutJS is a JavaScript Model View ViewModel (MVVM) framework.
The View Model object contains properties which values are specified as ko.observable(). Knockout will automatically updates the UI when the view model changes.
KnockoutJS has a declarative binding syntax where the HTML view elements are bind with our view model object. Knockout uses the "data-bind" attribute in the HTML elements for the data binding.

To learn the basics goto the KnockoutJS site by pressing here

Pr-requisites:
1) KnockoutJS
2) json2.js - for json parsing
3) ASP.NET MVC
4) jQuery

The Asp.Net MVC Controller have the actions to Get and Add a customer.

namespace KnockoutDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "";

            return View();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Get(int customerID)
        {
            // Get the customer ...
            Customer customer = new Customer {CustomerID = customerID, FirstName = "John", LastName = "Doe", IsMale = true };

            return Json(customer);
        }


        [HttpPost]
        public JsonResult Add(Customer customer)
        {
            // Save the customer ...

            // return status message 
            var message = "Customer: " + customer.FirstName + " " + customer.LastName + " Added.";
            message += " IsMale: " + customer.IsMale.ToString();
            return Json(message);
        }

    }
}

The Asp.Net MVC model is the customer:
    public class Customer
    {
        public int CustomerID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool IsMale { get; set; }
    }


The Asp.Net MVC Layout:
    
 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/json2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/knockout.validation.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>Knockout Demo</h1>
            </div>
            <div>&nbsp;</div>
        </header>
        <div>&nbsp;</div>
        <div>&nbsp;</div>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>



And finally the Asp.Net MVC view has the KnockoutJS specifics:
@{
    ViewBag.Title = "Add Customer";
}

<h2>
@ViewBag.Message</h2>
<form action="" method="post">
<b>Customer Number: </b> <span data-bind="text: CustomerID"></span><br />
<br />
<b>First Name: </b><input data-bind="value: FirstName" style="width: 200px;" type="text" /> <br />
<br />
<b>Last Name: </b><input data-bind="value: LastName" style="width: 200px;" type="text" /> <br />
<br />
<input data-bind="checked: IsMale" type="checkbox" /><b>Male</b><br />
<br />
<input data-bind="click: KnockoutDemoNamespace.addCustomer" type="button" value="Add Customer" /><br />
<div id="message">
</div>
</form>


The KnockoutJS has the following specifics:
1) View Model object: customerViewModel
2) HTML View: The HTML from the page with the KnockoutJS specific attributes for data binding
The demo performs a data bind with a span, and the input types text, checkbox and button.
Note that the "data-bind" has the html element attribute to be affected and the View Model property associated.
3) View Model activation: ko.applyBindings(viewModel);

03 May 2012

Error deleting a file: Could not find this item. This is no longer located in

When I was trying to delete a file I got a strange error:
      "Could not find this item. This is no longer located in..."

After some investigation I found the following solution:
1) Open a command prompt
2) Go to the folder where is the located the problematic file:
   cd c:\temp
3) Type the command:
                   dir /x
4) Find the 8.3 filename
5) Delete the file using the command:
    del filenam~1.txt

And bingo...the file is deleted !

30 April 2012

T-SQL And Linq To Sql Reference: IN

1. T-SQL
 select *   
 from Orders o  
 where ProductID IN (3, 4, 5)  
2. Linq
Code:
List<int> filter = new List<int>();  
filter.add(3);  
filter.add(4);  
filter.add(5);  
var orders = from o in dc.Orders    
          where filter.Contains(o.ProductID)  
          select o;  

13 December 2011

How to Convert rows to CSV in T-SQL

To convert several rows to unique row in CSV using T-SQL, use the following code:
 
DECLARE @myList varchar(MAX)
SELECT @myList = coalesce(@myList + ',', '') + UserName 
FROM [User]

SELECT @myList

WCF: The maximum string content length quota (8192) has been exceeded

A very annoying error I received when passing a very large string to a WCF Service was:

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter . The InnerException message was 'There was an error deserializing the object of type System.String. The maximum string content length quota (8192) has been exceeded while reading XML data. This quota may be increased by changing the MaxStringContentLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 8, position 9944.'. Please see InnerException for more details.

This is a cryptic error and only after some investigation I found the solution:

The readerQuotas element must be configured on the binding configuration:

<binding name="basicHttpBinding_IMyService" maxReceivedMessageSize="63400320">
      <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647"
       maxBytesPerRead="2147483647"   maxNameTableCharCount="2147483647"/>
</binding><br />

This is a simple example, you must configure it for your own needs.
I have added the additional configuration elements to show the other options.

Bulk insert efficiently

Using an ORM like Entity Framework or performing single inserts is not efficient to perform bulk operations.
To  bulk insert efficiently, the SqlBulkCopy class ADO.Net must be used.

The SqlBulkCopy class is used to efficiently bulk load a Sql Server table with data from another sources.
SQL Server has a command-prompt utility named bcp to also perform a bulk insert. The SqlBulkCopy is the equivalent for writing managed code.

The data source, like for example a flat file, can be converted to a generic list, that is the source of the SqlBulkCopy or a DataTable can be used directly.

To bulk insert a generic list, it must be converted to a DataTable so that it can be used by the SqlBulkCopy:
public static DataTable ConvertToDataTable<T>(IList<T> list)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type propType = propertyDescriptor.PropertyType;
        if (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            table.Columns.Add(propertyDescriptor.Name, Nullable.GetUnderlyingType(propType));
        }
        else
        {
            table.Columns.Add(propertyDescriptor.Name, propType);
        }
    }
    object[] values = new object[propertyDescriptorCollection.Count];
    foreach (T listItem in list)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = propertyDescriptorCollection[i].GetValue(listItem);
        }
        table.Rows.Add(values);
    }
    return table;
}

Then the SqlBulkCopy can be used.
The steps to use the SqlBulkCopy are simple:
1) A SqlConnection open must be passed to it's constructor.
2) A DataTable must have the data to bulk insert
3) The mappings between the database columns and the DataTable must be defined, using the ColumnMappings propery.  The Column mappings define the relationships between columns in the data source and columns in the destination.
4) The DestinationTableName property must be set with the name of the destination table on the server.
5) The WriteToServer method copies all the rows of the DataTable to the specified destination table.

In the following example the user table is bulk inserted, where dt is the DataTable with the data to bulk insert.

DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(connection))
    {
        sqlBulkCopy.ColumnMappings.Add("UserID", "UserID");
        sqlBulkCopy.ColumnMappings.Add("UserName", "UserName");
        sqlBulkCopy.ColumnMappings.Add("Password", "Password");
        sqlBulkCopy.DestinationTableName = "User";
        sqlBulkCopy.WriteToServer(dt);
    }
}
The WriteToServer method also supports a DataRow array or a IDataReader.

05 December 2011

Recover the mirror database

Database mirroring is a software solution for increasing database availability.
Database mirroring maintains two copies of a single database that must reside on different server instances of SQL Server Database Engine.
When the mirror is removed from the Primary database the mirrored one sometimes doesn't recover and it says "Recovering".
If the database doesn't leave this state, the following TSQL command can help:

RESTORE DATABASE myDatabase WITH RECOVERY
 
This will allow to recover the former mirror database.




14 November 2011

ValidateRequest=“false” doesn't work in Asp.Net 4

Before Asp.Net 4.0 is some scenarios it was useful to disable the automatic request validation performed by the .Net Framework to prevent Script Attacks.

This could be done by going to web.config or the page and setting

 ValidateRequest="false"

In Asp.Net 4.0 this feature only works if we set requestValidationMode="2.0" :



10 November 2011

Transaction management

In the context of a transaction each work-unit performed in a database must either complete in its entirety or rollback entirely.
In SQL Server an "normal" exception does not rollback a transaction by default.

In the old days the T-SQL  to manage a transaction was tedious.
An error variable must be checked to rollback the transaction if needed.
 Example:
BEGIN TRANSACTION 

...
IF (@@ERROR <> 0)
BEGIN
   ROLLBACK TRANSACTION 
    RAISERROR ('Error Description.', 16, 1)
END

COMMIT TRANSACTION


But the newer versions of SQL Server support TRY CATCH block, that simplifies the process:
BEGIN TRY
BEGIN TRANSACTION

...

IF @@TRANCOUNT > 0
BEGIN
    COMMIT TRANSACTION
END

END TRY
BEGIN CATCH

 DECLARE @ErrorMessage VARCHAR(4000)
  
 SET @ErrorMessage = 'Procedure: ' + ISNULL(ERROR_PROCEDURE(), '') + ' Line: ' + 
CAST(ERROR_LINE() AS VARCHAR(10)) + ' Message: ' + ERROR_MESSAGE()
  
 IF @@TRANCOUNT > 0
 BEGIN
  ROLLBACK TRANSACTION;
 END
  
 RAISERROR (@ErrorMessage, 16, 1)  

END CATCH;

Another way of doing the same is using SET XACT_ABORT. I don't recommend using it, but in some temporary scripts it can be useful.

The SET XACT_ABORT specifies whether SQL Server automatically rolls back the current transaction when a statement raises a run-time error.

SET XACT_ABORT ON
BEGIN TRANSACTION

....

COMMIT TRANSACTION


Note also that the RAISERROR stament does not honor the XACT_ABORT setting, so if an error occurs there is no automatic rollback even if XACT_ABORT is ON.

Sql Server 2012 implements the THROW statement that is suggested by Microsoft to be used instead of the RAISERROR.
The main difference is that the THROW:
1) Can re-throw the original exception that is caught in the CATCH block.
2) Causes the statement batch to be ended and the next statements aren't executed.
3) There is no severity parameter.The exception severity is always set to 16.
4) Requires preceding statement to end with semicolon (;).
5) Default THROW statement will show the exact line where the exception was occurred


A simple usage example:
BEGIN TRY
BEGIN TRANSACTION

...

IF @@TRANCOUNT > 0
BEGIN
    COMMIT TRANSACTION
END

END TRY
BEGIN CATCH 
 IF @@TRANCOUNT > 0
 BEGIN
  ROLLBACK TRANSACTION;
 END;
  
  THROW  

END CATCH;


Note that Microsoft states that: "The THROW statement honors SET XACT_ABORT RAISERROR does not. New Applications should use THROW instead of RAISERROR."

The THROW syntax is:
THROW [error number] [message] [state]

The two first parameters are self explanatory.
The state parameter is a constant or variable between 0 and 255 that indicates the state to associate with the message.

28 October 2011

How to stop windows time synchronization

In a testing scenario where there are calculations depending on the current time, it may be useful to set the windows time to a fixed date.

The problem is that the NTP time source in Windows Server 2008 will sync the time with the internet or the active directory. To stop this synchronization, the service windows time can be stopped or even un-installed.

This is where de command w32tm comes in:
w32tm /unregister

Also to stop the windows time service:
net stop "windows time"

Now the date can be fixed.

The problem is that the windows authentication is going to fail when trying to connect those servers. The problem isn’t a issue if the testing scenario is to set the sql server database server date and you can use sql server authentication.

Good testing.

01 September 2011

WCF And Debugging Exceptions

A common problem in WCF is to receive the exceptions on client when debugging.
The WCF behaviors configuration allows this using the includeExceptionDetailInFaults, but to receive the inner expection the returnUnknownExceptionsAsFaults must also be set to true.
The maxItemsInObjectGraph is only to avoid the error of exceeding the maximum number of items that can be serialized or deserialized.


<behaviors>
    <serviceBehaviors>
        <behavior name="MyServiceBehavior" returnUnknownExceptionsAsFaults="True">          
            <serviceDebug includeExceptionDetailInFaults="true" />
            <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
    </serviceBehaviors>
</behaviors>            

20 April 2011

Run Visual Studio in the context of an administrator account

If visual studio displays the error "... run Visual Studio in the context of an administrator account" a simple fix can be made:
1) Goto C:\Program Files (x86)\Common Files\Microsoft shared\MSEnv
2) Find the file VSLauncher.exe
3) Right click on it, select Properties, and then the Compatibility tab
4) Check the box for Run this program as an administrator

From now on when a solution file is opened the visual studio runs in the context of an administrator.

The same procedure must also be made for any shortcut to visual studio that you may have.

12 April 2011

How to set a date to the first / last day in TSQL

To set a date to the first / last day in TSQL:

First day:
SELECT DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0)
Last Day :
SELECT DATEADD(dd, -1, DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) + 1, 0))

11 April 2011

How to convert a table column in comma separated values (CSV)

To convert a table column in comma separated values (CSV), I use the following snippet:


DECLARE @table TABLE
(
    Id INT
)

INSERT INTO @table
VALUES (1),(5),(88), (99)

SELECT SUBSTRING(
(
SELECT ',' + CAST(Id AS VARCHAR(200))
FROM @table 
FOR XML PATH('')
)
,2,2000) AS VAL

24 March 2011

Web developer tools for the browser

The Web Developer extension adds various web developer tools to a browser. The extension is available for Firefox and Chrome, and will run on any platform that these browsers support including Windows, Mac OS X and Linux.

For more information press here.

01 March 2011

IIS7 Sessions Getting Crossed / Mixed Up / Copied

I have detected a problem on a web farm:
IIS 7 Sessions of the useres were getting Crossed / Mixed Up / Copied. A user was getting the session of another!!!!

After some research I found that IIS 7 now has the ability to cache dynamic content as well.
It is a new feature in IIS7, this version of IIS introduced some new caching features.
(i) IIS7 automatically caches static content, such as HTML pages, images, and style sheets.
(ii) IIS7 now has the ability to cache dynamic content as well.

In IIS7, disable the caching for .aspx pages in any directory with an asp.net page that depends on the session state. The steps to do this are:
1. Run the Server Management console and navigate to Roles -> Web Server (IIS) -> Internet Information Services.
2. Select the site you wish to modify.
3. Select the folder that contains the .aspx pages you need to turn caching off for.
4. In the Feature View, double-click “Output Caching”.
5. If there is a rule there already for the .aspx extension double click it. Otherwise right click and select “Add…”
6. Enter .aspx for the “File name extension”
7. Check "User-mode caching", "Prevent all caching", check "Kernel-mode caching" and "Prevent all caching"

For more detailed information press here.

29 December 2010

HTML : white space nowrap

In the gold days to avoid a white space wrap we could use the nobr tag. Now since the tag is deprecated we must use css:

.nobr { white-space:nowrap; }

This class can be applied to a span with the text we need to avoid the wrap.

16 December 2010

Immediate Window is missing in Visual Studio 2010 Menu

When the Immediate Window is missing in Visual Studio Menu, just do the following steps:
1) In the menu, select View -> Other Windows -> Command Window
2) Type immed in the command window and the It will bring the Immediate Window
3) Type cmd inside the Immediate Window and it will bring the Command Window back again

15 December 2010

Fix the MaxItemsInObjectGraph quota error

When there is a great amount of data to send to a WCF service, the following error occurs:

Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.

To fix the error the MaxItemsInObjectGraph must be defined on the wcf service server and the client.

On the server:

<system.serviceModel>   
    <services>
        <service behaviorConfiguration="Service1Behavior" name="Service1">
           <endpoint address="" binding="basicHttpBinding" contract="IService1"></endpoint>
        </service>
    </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="Service1Behavior">          
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

On the client:

<system.serviceModel>
    <client>
        <endpoint address="http://localhost/Service1.svc" behaviorConfiguration="Service1Behavior" binding="basicHttpBinding" contract="IService1Event" name="Service1">
      </endpoint>
    </client>
    <behaviors>
        <endpointBehaviors>
            <behavior name="Service1Behavior">
              <dataContractSerializer maxItemsInObjectGraph="2147483647"/>    
            </behavior>
        </endpointBehaviors>
</behaviors>
</system.serviceModel>