Search This Blog

Monday, August 1, 2011

Creating Custom HTML Helpers in ASP.NET MVC

ASP.NET MVC provides many built-in HTML Helpers.  With help of HTML Helpers we can reduce the amount of typing of HTML tags for creating a HTML page.
For example we use Html.TextBox() helper method it generates html input textbox. Write the following code snippet in MVC View:
<%=Html.TextBox("txtName",20)%>
It generates the following html in output page: 
List of built-in HTML Helpers provided by ASP.NET MVC.
  • ActionLink() – Links to an action method.
  • BeginForm() – Marks the start of a form and links to the action method that renders the form.
  • CheckBox() – Renders a check box.
  • DropDownList() – Renders a drop-down list.
  • Hidden() – Embeds information in the form that is not rendered for the user to see.
  • ListBox() – Renders a list box.
  • Password() – Renders a text box for entering a password.
  • RadioButton() – Renders a radio button.TextArea() – Renders a text area (multi-line text box).
  • TextBox () – Renders a text box.
How to develop our own Custom HTML Helpers?
For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag.
using System;
using System.Web.Mvc;
namespace MvcHelpers
{
    public static class CustomHtmlHelpers
    {
        public static TagBuilder Image(this HtmlHelper helper, string imageUrl, string alt)
        {
            if (!String.IsNullOrEmpty(imageUrl))
            {
                TagBuilder imageTag = new TagBuilder("img");
                imageTag.MergeAttribute("src", imageUrl);
                imageTag.MergeAttribute("alt", alt);
                return imageTag;
            }
            return null;
        }
    }
}
The next step is in order to make it available to Views, we should include the name space of out custom HTML helper class into Web.config
Build the solution to make sure the helper method is available to views. Goto any view in the solution access the newly created HTML image helper method.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>


      Home


      

<%= Html.Encode(ViewData["Message"]) %>

<%=Html.Image("/Images/logo.png","logo") %>

<%=Html.Image(“/Images/logo.png”,”logo”) %>
The image HTML helper generates the following HTML.
”logo”/
Image Tag Helper is simple example of HTML helpers, we can put any sort of complex logic into HTML Helpers & access them with in the views with a simple method call. in turn which makes the view simpler.

How To Create Session-less Controller in MVC3

How to manage the controller’s session state?
Simply we can decorate the controller class with “SessionState” attribute. [SessionState()] attribute accepts SessionStateBehaviour enumeration.
SessionStateBehaviour enumeration has the following constants.
  • SessionStateBehavior.Default - ASP.NET default logic is used to determine the session state behavior for the request.
  • SessionStateBehavior.Required – Full read-write session state behavior is enabled for the request.
  • SessionStateBehavior.ReadOnly – Read only session state is enabled for the request.
  • SessionStateBehavior.Disabled – Session state is not enabled for processing the request.

Sessionless Controller
We decorated controller class with [SessionState(SessionStateBehaviour.Disabled)] to disable the session. Important point to remember when we are disabling session of the controller, we should n’t use TempData[] Dictionary to store any values with action method controller, it uses session to store it’s values. If you use TempData[] Dictionary when session is disabled on controller it will throw an exception “The SessionStateTempDataProvider class requires session state to be enabled“.
Note: In earlier release of MVC3 (Beta) [SessionState()] attribute was refereed as  [ControllerSessionState()]

How to return 404 Http status code from ASP.NET MVC Application?

ASP.NET MVC3 includes a new class HttpNotFoundResult in  System.Web.Mvc namespace.
HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?
First way is to instantiate HttpNotFoundResult class and return the object.
public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}
Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.
public ActionResult Index()
{
return HttpNotFound();
}
we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).
public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}

Difference between a UserControl and a CustomControl

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:
UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.
Limitation of UserControl :
1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.
2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.
3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.
Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.
Note: Please don’t create a new custom control just to change the UI appearance as you can do this with any control available using custom Template
Limitation :
1. You have to define each behaviour for your control using Code. So it is hard way of achieving a behaviour.
2. Generic style is needed to be defined with your custom control to ensure that your control has a default look and feel.
Hence, based on your own requirement, if you are looking for a new behaviour which is different from existing userinterfaces available with WPF, you go for a Custom Control. A customControl can be styled and templated and best suited for a situation when you are building a Control Library.
On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don’t need to use it as a Control Library.
I hope this gives you a brief idea on the differences between the two.
Happy Coding.

Sunday, May 22, 2011

God

God always like to know again and again what you want. It is not that he forgets your needs, but he love to feel the sweetness of your prayer..
 

Saturday, May 21, 2011

Import contact from mail service using asp.net with php

First Download openinviter from http://openinviter.com/download.php and edit example.php to adjust it for your needs

Just like, below php file (example).


include('openinviter.php');
$inviter=new OpenInviter();
$oi_services=$inviter->getPlugins();
if (isset($_POST['provider_box']))
{
if (isset($oi_services['email'][$_POST['provider_box']])) $plugType='email';
elseif (isset($oi_services['social'][$_POST['provider_box']])) $plugType='social';
else $plugType='';
}
else $plugType = '';
function ers($ers)
{
if (!empty($ers))
{
//$contents="
";
foreach ($ers as $key=>$error)
$contents.="{$error}
";
//$contents.="

";
return $contents;
}
}
function oks($oks)
{
if (!empty($oks))
{
$contents="
";
foreach ($oks as $key=>$msg)
$contents.="{$msg}
";
$contents.="

";

return $contents;
}
}

if (!empty($_POST['step'])) $step=$_POST['step'];
else $step='get_contacts';

$ers=array();$oks=array();$import_ok=false;$done=false;
if ($_SERVER['REQUEST_METHOD']=='GET')
{
$plugType='email';
if ($step=='get_contacts')
{
if (empty($_GET['email_box']))
$ers['email']="Email missing !";
if (empty($_GET['password_box']))
$ers['password']="Password missing !";
if (empty($_GET['provider_box']))
$ers['provider']="Provider missing !";
if (count($ers)==0)
{
$inviter->startPlugin($_GET['provider_box']);
$internal=$inviter->getInternalError();
if ($internal)
$ers['inviter']=$internal;
elseif (!$inviter->login($_GET['email_box'],$_GET['password_box']))
{
$internal=$inviter->getInternalError();
$ers['login']=($internal?$internal:"Login failed. Please check the email and password you have provided and try again later !");
}
elseif (false===$contacts=$inviter->getMyContacts())
$ers['contacts']="Unable to get contacts !";
else
{
$import_ok=true;
$step='send_invites';
$_GET['oi_session_id']=$inviter->plugin->getSessionID();
$_GET['message_box']='';
}
}
}
elseif ($step=='send_invites')
{
if (empty($_POST['provider_box'])) $ers['provider']='Provider missing !';
else
{
$inviter->startPlugin($_POST['provider_box']);
$internal=$inviter->getInternalError();
if ($internal) $ers['internal']=$internal;
else
{
if (empty($_POST['email_box'])) $ers['inviter']='Inviter information missing !';
if (empty($_POST['oi_session_id'])) $ers['session_id']='No active session !';
if (empty($_POST['message_box'])) $ers['message_body']='Message missing !';
else $_POST['message_box']=strip_tags($_POST['message_box']);
$selected_contacts=array();$contacts=array();
$message=array('subject'=>$inviter->settings['message_subject'],'body'=>$inviter->settings['message_body'],'attachment'=>"\n\rAttached message: \n\r".$_POST['message_box']);
if ($inviter->showContacts())
{
foreach ($_POST as $key=>$val)
if (strpos($key,'check_')!==false)
$selected_contacts[$_POST['email_'.$val]]=$_POST['name_'.$val];
elseif (strpos($key,'email_')!==false)
{
$temp=explode('_',$key);$counter=$temp[1];
if (is_numeric($temp[1])) $contacts[$val]=$_POST['name_'.$temp[1]];
}
if (count($selected_contacts)==0) $ers['contacts']="You haven't selected any contacts to invite !";
}
}
}
if (count($ers)==0)
{
$sendMessage=$inviter->sendMessage($_POST['oi_session_id'],$message,$selected_contacts);
$inviter->logout();
if ($sendMessage===-1)
{
$message_footer="\r\n\r\nThis invite was sent using OpenInviter technology.";
$message_subject=$_POST['email_box'].$message['subject'];
$message_body=$message['body'].$message['attachment'].$message_footer;
$headers="From: {$_POST['email_box']}";
foreach ($selected_contacts as $email=>$name)
mail($email,$message_subject,$message_body,$headers);
$oks['mails']="Mails sent successfully";
}
elseif ($sendMessage===false)
{
$internal=$inviter->getInternalError();
$ers['internal']=($internal?$internal:"There were errors while sending your invites.
Please try again later!");
}
else $oks['internal']="Invites sent successfully!";
$done=true;
}
}
}
else
{
$_POST['email_box']='';
$_POST['password_box']='';
$_POST['provider_box']='';
}


if (!$done)
{
if ($step=='get_contacts')
{
}
else{}
}
if (!$done)
{
if ($step=='send_invites')
{
if ($inviter->showContacts())
{

if (count($contacts)==0){}
else
{
$odd=true;$counter=0;
foreach ($contacts as $email=>$name)
{
$counter++;
if ($odd) {}
$contents.= "{$email}".",";
$odd=!$odd;
}

}

}
}
}

print_r($contents);
?>


Then create one class like that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Data;

///

/// Summary description for ImportsContacts
///

public class ImportsContacts
{
public ImportsContacts()
{
//
// TODO: Add constructor logic here
//
}

public static DataTable GetDataTableFromArray(string url, string provider, string email, string pass)
{

DataTable dt = new DataTable();
///get all contact from url as array format
///split into array
object[] array = TinyEAIPostRequest(+ url +"/example.php?step=get_contacts&provider_box=?step=get_contacts&provider_box=" + provider + "&email_box=" + email + "&password_box=" + pass , string.Empty).Split(',');
dt.Columns.Add(new DataColumn("EmailID"));

for (int i = 0; i <>
{
DataRow dr = dt.NewRow();
dr["EmailID"] = array[i];
dt.Rows.Add(dr);
}
return dt;

}
public static string TinyEAIPostRequest(string strURL, string strRequest)
{

HttpWebResponse objHttpWebResponse = null;
UTF8Encoding encoding;
string strResponse = "";

HttpWebRequest objHttpWebRequest;
objHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
objHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
objHttpWebRequest.PreAuthenticate = true;

objHttpWebRequest.Method = "GET";

//Prepare the request stream
if (strRequest != null && strRequest != string.Empty)
{
encoding = new UTF8Encoding();
Stream objStream = objHttpWebRequest.GetRequestStream();
Byte[] Buffer = encoding.GetBytes(strRequest);
// Post the request
objStream.Write(Buffer, 0, Buffer.Length);
objStream.Close();
}
objHttpWebResponse = (HttpWebResponse)objHttpWebRequest.GetResponse();

encoding = new UTF8Encoding();
StreamReader objStreamReader = new StreamReader(objHttpWebResponse.GetResponseStream(), encoding);
strResponse = objStreamReader.ReadToEnd();
objHttpWebResponse.Close();

objHttpWebRequest = null;

return strResponse;
}
}

Then
Call example.php file from your aspx file.
see below code how to call php file using asp.net

DataTable dt = ImportsContacts.GetDataTableFromArray(url +"/example.php", ddlmailoption.SelectedValue, txtusername.Text, txtpass.Text);//GContactsImport.GetGmailContacts(App_Name, txtusername.Text, txtpass.Text);
repgooglecontact.DataSource = dt;
repgooglecontact.DataBind();


I hope you will get good result and help to you.

Export Data into CSV file using Asp.net

How to use below code.

First create one default.aspx page and add below code into code behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string[] mylist = new string[5]; //Declaring the string array;

//Assigning values to each element in the array
mylist[0] = "Hello";
mylist[1] = "how";
mylist[2] = "are";
mylist[3] = "you";
mylist[4] = "?";

//Creating a new List of type
List StringtoList = new List(mylist.Length);

//AddRange is a method of List objects that enables the conversion.
//We just need to pass the reference to the array.
StringtoList.AddRange(mylist);

CSVExporter.WriteToCSV(StringtoList);
}
}


Then create one CSVExporter.cs file into app_code and add below code into class file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

///

/// Summary description for CSVExporter
///
public class CSVExporter
{
public static void WriteToCSV(List personList)
{
string attachment = "attachment; filename=PersonList.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName();
foreach (String person in personList)
{
WriteUserInfo(person);
}
HttpContext.Current.Response.End();
}

private static void WriteUserInfo(String person)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(person);
//AddComma(person.Name, stringBuilder);
//AddComma(person.Family, stringBuilder);
//AddComma(person.Age.ToString(), stringBuilder);
//AddComma(string.Format("{0:C2}", person.Salary), stringBuilder);
HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private static void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private static void WriteColumnName()
{
string columnNames = "Name, Family, Age, Salary";
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}
}

Then press f5 and you will get result.