Friday, March 29, 2013

Asp.Net MVC 4 ?

Past three years I have been working with ASP.NET MVC3 and it is very good frame work to develop web application .Now Microsoft  has released ASP.NET MVC4 Framework .So let see what they introduce for us.

Mobile Application

ASP.NET MVC4 introduces new project template for build mobile web application .It has same structure of the ASP.NET MVC and a lot of handful CSS and JavaScript files are now inside, including jQuery Mobile. So we can develop mobile browser compatible applications easily  .

Display Modes

One new features of ASP.NET MVC 4 is support for display modes. This means that you can conditionally show different output to different user agents like desktop and mobile browsersSo we can develop two version of the same page.
For example, if a desktop browser requests the Home page, the application might use the Views\Home\Index.cshtml template. If a mobile browser requests the Home page, the application might return the Views\Home\Index.mobile.cshtml template.

Web API

ASP.NET Web API is a framework for building and consuming HTTP services that can reach a broad range of clients including browsers, phones and tablets. We  can use XML or JSON or something else with your API. JSON is nice for mobile apps with slow connections, for example. You can call an API from jQuery and better utilize the client's machine and browser.

Bundling and Minification

The new bundling feature in ASP.NET  packs a set of JS or CSS files into a single element, and reduces its size by minifying the content (i.e. removing not required blank spaces, removing comments, reducing identifiers). This can help to reduce the file size and make the site perform faster.

OAuth and OpenID

 ASP.NET MVC4 include library that enables users to log in with credentials from an external provider, such as Facebook, Twitter, Microsoft, or Google, and then integrate some of the functionality from those providers into your web application.

Enhanced support for Asynchronous methods

The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET MVC 4 supports Task. Tasks are represented by theTask  type and related types in the System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this asynchronous support with  the await and async keywords that make working with Task objects much less complex than previous asynchronous approaches.

Add Controller to any project folder

You can now right click and select Add Controller from any folder in your MVC project. This gives you more flexibility to organize your controllers however you want, including keeping your MVC and Web API controllers in separate folders.

Database Migrations

ASP.NET MVC 4 projects now include Entity Framework 5. One of the great features in Entity Framework 5 is support for database migrations. This feature enables you to easily evolve your database schema using a code-focused migration while preserving the data in the database.



Monday, February 25, 2013

Java script online editors/web playground

Today I’m going to share information regarding tools which I use for test my Javascript/HTML/CSS  functionality.

jsfiddle(http://jsfiddle.net)


This is very useful web playground which can be used to simulate/test our javascript function .


jsbin(jsbin.com)

This is also  web playground which can be used to simulate/test our javascript function .

Thursday, February 21, 2013

Why should we learn advanced Java Script?

Although, JavaScript introduces as web scripting language in 1995 by Brendan Eich (employee of Netscape), JavaScript is not only a web scripting language further; it can be used as server side programming language (node.js), Client Application development language (windows 8)

Some Characterizes of Javascript

Prototype-based-( not as Object Oriented Language)
Dynamic (can be drop property in any time in the cycle)
Weekly Type -(every type variable declare as var and function can receive any type variable)


JavaScript Basic

Declaring array:

var myArray= []

Creating empty Object:

var myStudentObject={};
var myStudentObject=new Object();
var myStudentObject=Object.create(null);

Initialization object

myStudentObject.name=”Dinesh”;
or
var myStudentObject= {name:”Dinesh”}

Functions

How to declared function

function firstFunction (){
}
or
var secondFunction=function(){
}

arguments –Key word

We can pass any arguments to function without declare and we can use arguments key word which inherit for every function to retrieve those arguments.

Ex:
function addNumber (){
var answer=arguments[0]+ arguments[1];
return answer;
}
Then we can call it as
firstFunction(1,2);

Method

var Operation={
add: function addNumber (){
var answer=arguments[0]+ arguments[1];
return answer;
}
};

//call it
var x= Operation.add(2,3)

Immediate Function

These function execute immediately .
(function(){
}())
Or
(function(){})();

Passing parameters to immediate  function
(function(a,b){
}(1,2))


DOM Selector

var a=documents.getElementsById(“pic”);//
 var q=documents.quarySelector(“h2”);//get first element
var list=documents.quarySelectorAll(“h2”);//get all elements

Monday, July 11, 2011

MVC3 TryUpdateModel() -Update Model for Edit

When we want to update model with edited values we can use TryUpdateModel() method.

example
[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }

    return view()
}


But some times when we use TryUpdateModel() the model does not update that mean the method return false.So in that case we need to find out the error so we can do that as flowing it will return the list of errors and their corresponding properties.

[Httppost]
public ActionResult edit(int id)
{
    var user= UserRepository.GetUser(id);

    if (TryUpdateModel(user))
    {
        UserRepository.save();
    }
else{
//the tru update method return false
    
    var errors = ModelState
    .Where(m => m.Value.Errors.Count > 0)
    .Select(m => new { m.Key, m.Value.Errors })
    .ToArray();

}

    return view()
}

Why TryUpdateModel() return false ?

Most of the time the TryUpdateModel() method return false when we have not add editable field or hidden filed for all the required fields to view page.
so we can simply add hidden filed to the view which we don't need to change during the update method.

so My user Model
Public Class User{
[Requried]
public int UserId{get;set}
[Requried]
public string UserName {get;set}
[Requried]
pubic string UserCode{get;set}

pubic string Description{get;set}

public string Address{get;set}

}

So if  I want to update UserDescription in my edit page
I have to put UserId,UserName and UserCode as Hidden filed

But if our model content large number of fields and we only need to update few of fields in that case we can do it by specify the fields which we need to update as following

TryUpdateModel(model, new [] {"Description", "Address"}); // In this case the TryUpdate() only  check vaidation "Description","Address"




And also we can do it as fallowing by mentioning the field which should not update
TryUpdateModel(model, null, null, new [] {"UserId","UserName ","UserCode"});//In this case the TryUpdate() ignore "UserId","UserName" and "Usercode" vaidation

Monday, July 4, 2011

Remove Validation Error messege when click Reset Button in MVC3 Razor

The reset button does not clear validation message in mvc3 by default so  we need to do this with jQuery.The fallowing function clear validation messages in MVC3 pages.
.

jQuery(document).ready(function () {

            $("input:reset").click(function () {
                $('.field-validation-error')
               .removeClass('field-validation-error')
                .addClass('field-validation-valid');

                $('.input-validation-error')
                .removeClass('input-validation-error')
                 .addClass('valid');
            });

  });
Professional ASP.NET MVC 3

Monday, June 27, 2011

MVC 3 Razor TextBox max length

@Html.TextBoxFor(model => model.Organization.OrganizationName, new { maxlength = 50 }) 

Applied ASP.NET MVC 3 in Context (Pro)

Sunday, June 12, 2011

MVC 3 Razor Editor Template

Editor Template is very useful future in Asp.net MVC3 Framework.With Editor Template we can create template for model and  It  can be access easily in the application (like user controller in asp.net).
So I'm going to create Editor Template for Book Model in my application.
Book.cs

public class Book
{
public int BookId { get; set; }
public string BookName { get; set; }
public string Description { get; set; }
}
Then I'm going to create folder  as EditorTemplates in Shared folder  and add new view Book.cshtml as following.(The Name of the Template should be same as Class Name)
 .
@model MySimpleEditorTemplate.Models.Book

@Html.DisplayFor(p => p.BookId) @Html.EditorFor(p => p.BookId)
@Html.DisplayFor(p => p.BookName)@Html.EditorFor(p => p.BookName)
@Html.DisplayFor(p => p.Description)@Html.EditorFor(p => p.Description)

Then in view page simply we can add editor for book as

@Html.EditorFor(model => model.Book) 
 
then it will display above block

Wednesday, October 6, 2010

Accsess The Magento Core API With Dot net technologies

Magento is one of the most popular e-commerce platforms.which based  on PHP and Mysql.Magento Core API supports both SOAP and XML RPC protocols. The API is permission based and allows access to the Customer, Catalog and Order modules of Magento. Please reference the documentation for more information.
This article I am going to explaining How to access magento web service from Dot net Technologies .
we can access magento soap api with following url.
http://mymagento.com/api/v2_soap?wsdl (You can see wsdl definition by typing this url in web browser).
So let see how to display Magento customer list in my WindowsFormsApplication project.
To consume to the magento web service in our application we should add web Reference by rigth click on solution .

In the web reference dialog box type the magento web service URL (http://mymagento.com/api/v2_soap?wsdl) and click Go button then available service method display as following screen.
Then we can change the web service name and click Add Refference button.

 By doing above steps,we can generate  the web service proxy .
C# code to retrieve  customer list.
 using Magento.com.mymagento

public void  showCustomrs(){
   MagentoService ms = new MagentoService();
   string sesion= ms.login("Dinesh", "123456");
   filters myfilter=new filters();//filter criteriya
   customerCustomerEntity[] cusls= ms.customerCustomerList(sesion,myfilter);//get customers
   dgCutomer.ItemsSource = cusls; //display in grid
}









Saturday, August 7, 2010

How to Create WCF Application

Select WCF Service Application from New Project window in Visual Studio and name the project as MyWCFService

Add WCF Service to the “MyWCFService” project and named as Myservice.svc

What is Service Contracts ?
Describe which operations the client can perform on the service. There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

IMyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;


[ServiceContract]

public interface IService

{

    [OperationContract]

     Employeee GetEmployee(int id);// service method

      

}

Then we can implement above interface

MyService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using Common;

    public class MyService: IMyService

    {


        #region MyService Members


        public Employeee GetEmployee(int id)//service method implimentation

        {

 Employeee emp = new Employeee { EmpId = Guid.NewGuid(),Name="Dinesh",Type=EmployeeTypesEnum.Accounter };

                     return emp;

        }


        #endregion

    }

What is Data contracts?

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.
Types Supported by the Data Contract Serializer

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties

Add Class Employee to the solution

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

using System.ServiceModel;


    [DataContract]

    public class Employeee

    {

        [DataMember]

        public Guid EmpId { get; set; }

        [DataMember]

        public string Name { get; set; }

        [DataMember]

        public EmployeeTypesEnum Type { set; get; }

    }

How To Pass Enum with WCF services?

To pass Enum the Data contracts should be define with EnumMember() attributes.


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;


 [DataContract]

   public enum EmployeeTypesEnum

    {

    [EnumMember()]


          Administrator = 0,


    [EnumMember()]


          Manager = 1,


    [EnumMember()]


          Accounter = 2


}

How to Test WCF application ?

WCF service can test with WCF Test Client (WcfTestClient.exe) by  execute WcfTestClient.exe commond in Visual Studio Command prompt .
 

Saturday, April 10, 2010

VS 2008 service pack offline version

With fallowing link we can download VS2008 SP1 offline version and it is a .iso file so we need to burn it in to DVD and install with DVD ROM.
VS 2008 SP1

Thursday, March 11, 2010

COPY EXCELL SHEET DATA TO MS SQL DATA BASE WITH C#.NET

using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;

public class CopyExcellToMSSql
{
string _sourceConnectionString=;
string _destinationConnectionString;

public CopyExcellToMSSql(string sourceConnectionString,
string destinationConnectionString)
{
_sourceConnectionString =
sourceConnectionString;
_destinationConnectionString =
destinationConnectionString;
}

public void CopyTable(string Ftable,string Ttable)
{
using (OleDbConnection source =
new OleDbConnection(_sourceConnectionString))
{
string sql = string.Format("SELECT * FROM [{0}]",
Ftable);

OleDbCommand command = new OleDbCommand(sql, source);

source.Open();
IDataReader dr = command.ExecuteReader();

using (SqlBulkCopy copy =
new SqlBulkCopy(_destinationConnectionString))
{
copy.DestinationTableName = Ttable;
copy.WriteToServer(dr);
}
}
}
}

Calling above method
public void CopyData{
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\Documents and Settings\\Dinesh\\Desktop\\D-Garment\\work detailes.xls; Extended Properties=""Excel 8.0;HDR=Yes"";";

string sqlConnectionString ="Data Source=KIT\MYSERVER; Initial Catalog=EMS;User ID=ems; Password=ems123";

CopyExcellToMSSql cpLogic = new CopyExcellToMSSql(excelConnectionString, sqlConnectionString);
cpLogic.CopyTable("Employee$", "TempEMPLOYEE");// Employee is work sheet and "TempEMPLOYEE" is table

Wednesday, February 17, 2010

Insert Multiple Rows to Table in SQL

INSERT INTO [tabale1]
([col1]
,[col2]
,[col3]
,[col4])

(SELECT '11','1','1','1' UNION ALL 
SELECT '22','2','2','2')

Monday, November 2, 2009

How to call Dynamic Javascript Function from Gridview - Asp.Net

We can call dynamic java script function from grid view as fallow.say we need to call following java script function dynamically from gride view then we need to create java script function in .aspx page.
<script type="text/jscript">
function funcShow(id)
{
aleart(id);
}
</script>
After that we have to add Template filed with Hyperlink filed to Grdeview as fallowing
<asp:GridView ID="dg1" runat="server"                      
<Columns>
<asp:BoundField DataField="FileName" HeaderText="Description">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl='<%# RetrunClick(Eval("ID"))%>'>Click</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then we need to add following function to the code behind page that will call the java script function .
public string RetrunClick(object obj)
{
string str = string.Empty;
if (obj != null)
{
str = "javascript:funcShow('" + obj.ToString() + "')";
}
return str;
}
JavaScript Bible, Fifth EditionJavaScript Bible

Wednesday, October 14, 2009

Calculate Running Sum of the Texboxses in the ASP.NET with Javascript

If we need to get running total of the text boxes in asp.net page while allowing automatically calculate the sum when changed the any text box .
Ex:
we have 3 Text Boxes as "txtCallCharges","txtRentTaxies","txtTotalAmount" and we need to get sum of the entered values to the "txtTotalAmount" text box .and also It should be allowed to automatically get total when text changed in nay text box.
Solution:
Add following code to the Code behind page.
protected override void OnLoad(EventArgs e)
{
txtCallCharges.Attributes.Add("onblur", "javascript:calculateTotal();");
txtRentTaxies.Attributes.Add("onblur", "javascript:calculateTotal();");
}

Then add following javascript to .aspx page
function calculateTotal()
{
var ctrl1 = null;
var ctrl2=null;
var ctrl3=null;          
ctrl1= document.getElementById("<%=txtCallCharges.ClientID %>");
ctrl2= document.getElementById("<%=txtRentTaxies.ClientID %>");
ctrl3= document.getElementById("<%=txtTotalAmount.ClientID %>");
var total =null;
if(ctrl1.value != "")
{
total=total+parseFloat(ctrl1.value);
}
if(ctrl2.value != "")
{
total=total+parseFloat(ctrl2.value);
}
ctrl3.value= total;
}

Thursday, October 8, 2009

Update multiple columns of one table from another table- SQL

UPDATE [tableA]
SET
A1 = B.B1+B.B2,
A2=B.B3
FROM tableA, tableB as B WHERE tableA.ID = B.ID

Thursday, June 18, 2009

Refresh a content page without refreshing master page Vs Avoid flicker when click on the link

The master page class derives from the UserControl class. When the application is executing, the master page just like a child control. So we can say the master page is not a true page. “.And, when the page loads, we can notice the navigationURL of the Browser address bar is the content page's, but not the master page's.Because of that we cannot refresh a content page without refreshing master page .But we can avoid flickering with fallowing code by put one <HEAD> tag in the master page.

<meta http-equiv="Page-Enter" content="blendTrans(Duration=0)"/>

<meta http-equiv="Page-Exit" content="blendTrans(Duration=0)"/>

Friday, June 5, 2009

ASP.NET Master page Set Background Image to Table

Problem :When we set ASP Net - Master Page background image it only visible from pages in root directory
Solution : The images which are used in Masterpage should be set in the code behind file as fallow .
The runat='Server" attribute should be added to the controller which are going to set background image and ID should be set to that controller.
<td runat="server" id="tb1">set back ground image with code</td>

In the code behind page image should be set using ResolveClientUrl() method
protected void Page_Load(object sender, EventArgs e)
{
tb1.Style[HtmlTextWriterStyle.BackgroundImage] = ResolveClientUrl("~/App_Themes/Images/1-sri-lanka.JPG");
}


Tuesday, June 2, 2009

Sql Date Time Formatting

Remove Time Part From DateTime
---------------------------------
SELECT GETDATE() /// 2009-06-25 12:03:56.640
Declare @mydate DATETIME
SET @mydate=GETDATE()

-------------------------------------

1.Get Out put as Type of DateTime with zero time
SELECT DATEADD(day, DATEDIFF(day, '20000101',@mydate), '20000101')
or
SELECT DATEADD(DAY, 0, DATEDIFF(DAY,0,@mydate))
or
SELECT DATEADD(dd, DATEDIFF(dd, 0, @mydate), 0)

out put :2009-06-25 00:00:00.000

2.Get Out put as Type of Varchar without time

SELECT CONVERT(VARCHAR(10),@mydate, 103)
out put :25/06/2009

Or
SELECT CONVERT(VARCHAR(10), @mydate, 120)
out put :2009-06-25

Sunday, May 10, 2009

Unique Identifier In .Net & SQL

A GUID (Globally Unique Identifiers) is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated. In the .NET framework the System.Guid.NewGuid method is used to generate the unique identifiers.

System.Guid desiredGuid = System.Guid.NewGuid();

This desiredGuid can be directly save to DB. The data type of the filed should be “uniqueidentifier” or we can cast it as string …. And also we can store GUID in “System.Guid” data type variable(C#).

convert GUID to Sting

System.Guid desiredGuid = System.Guid.NewGuid();
string a=desiredGuid.ToString();

convert a string to a GUID

Guid MyGuid = new Guid(stringValue);

In SQL Server, the “uniqueidentifier” data type is used to store the GUIDs and newid() function will generate GUID.

Thursday, March 19, 2009

TypeForwardedTo (.NET)

We can use this class to move type from one assembly to another while not disrupting the callers compile against the original assembly .
Example : we have a source library (say lib.dll) which included lot of classes and we have use that class library for our application development. After some period of time the we refastening the source library (lib.dll) and it splits in to two source library to (say lib.dll and lib1.dll) .Then what happen to our application will it work? No because our application point to the lib.dll but some of the classes have move to lib1.dll to. So our application will generate error .To prevent this we can use “TypeForwardedTo”

Following 2 classes define in lib.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib
{
public class car
{
public static void Do()
{
System.Console.WriteLine("car");

}
}
public class van
{
public static void Do()
{
System.Console.WriteLine("van");
}
}
}

Then the develop application using above lib.dll as following

using System;
using System.Collections.Generic;
using System.Text;
using lib;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
car.Do();
van.Do();
Console.ReadLine();

}
}
}

The Out put is :
car
van


Now we split above lib.dll to 2 dll to as following

lib.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib
{
public class car
{
public static void Do()
{
System.Console.WriteLine("car");

}
}
}

lib1.dll
using System;
using System.Collections.Generic;
using System.Text;
namespace lib1
{
public class van
{
public static void Do()
{
System.Console.WriteLine("van");

}
}
}

Then replace the above lib.dll with new two dlls. Now what happen, the van class can’t find in new lib.dll so it generate and error.
So prevent such a error we ca use
“System.Runtime.CompilerServices.TypeForwardedTo” as following
Open the lib project and Open the AssemblyInfo.cs file and add the following line right after the assembly directives.

[assembly: TypeForwardedTo(typeof(lib1.van))]


now build projecj.
Now we have 2dlls, lib.dll and lib1.dll but we can still run oure previouse application without any error .....