Sponsors

Thứ Sáu, 5 tháng 10, 2012

Convert Int32 to Base 2, 8, 10 or 16

A few weeks ago I had a requirement to convert an Int32 value (base 10 or decimal) to its binary representation as a string. I encapsulated the logic to convert the decimal number to a binary string in a method. I used the base 10 to base 2 algorithm where the decimal number is continiously divided by two until it becomes zero. Within the iteration, the modulo two of the number is then appended to the output binary string. At the time of writing that code, it seemed like the best way to go about it, and because it was neatly encapsulated in a method, I knew I could swap out the implementation at a later date without much hassle.

Today, I came across an overload of the Convert.ToString method which surprisingly accepted a parameter called toBase. I wish I had come across this earlier... The overload accepts the bases 2, 8, 10 or 16 and throws an ArgumentException if one of these are not passed in. Anyway, I converted the method I wrote to an extension method on Int32 called "InBase" - I think that reads better than Convert.ToString with a base passed in. The implementation is below in case you want to include it in your libraries.


public static string InBase(this int number, int @base)
{
    return Convert.ToString(number, @base);
}
Example usage:

Console.WriteLine("{0}", 10.InBase(2)); // Outputs "1010" (Binary)
Console.WriteLine("{0}", 10.InBase(8)); // Outputs "12" (Octal)
Console.WriteLine("{0}", 10.InBase(10)); // Outputs "10" (Decimal)
Console.WriteLine("{0}", 10.InBase(16)); // Outputs "a" (Hexadecimal)
Console.WriteLine("{0}", 10.InBase(3)); // Throws ArgumentException

Thứ Năm, 4 tháng 10, 2012

The Pragmatic Programmer

When studying for my undergrad degree, one of my lecturers recommended the book The Pragmatic Programmer (by Andrew Hunt and David Thomas). The book is written by a couple of experienced Software Engineers and contains a wealth of useful knowledge for anyone who is considering a serious career in software development.

The topics covered range from general tips that the authors learnt from their experiences, some useful tools you should know about as a programmer, how to think when you're writing code, how to write testable code and much more. It's a mixed bag of eight chapters, with each chapter broken down into smaller digestable sections. It was the perfect companion to someone who commuted into university on the train.

I know this post isn't relevant to C# per se, but thought it may encourage you to get hold of the book and learn some useful practices that you can apply in your projects.

Chủ Nhật, 19 tháng 8, 2012

How to Add / Update record using GridView control (c#)

A Gridview is a control for displaying and manipulating data from different data sources. It shows data from a variety of data sources in a tabular format.

Instead of boundfiled, I prefer to use TemplateField coz of its simplicity. Here in this Artilce i am going to implement how to Add, Update, Delete selected record from GirdView control.
Tested Sample code : Add new record from footer and Update the selected row
Default.aspx:


<asp:gridview allowpaging="True" autogeneratecolumns="False" cellpadding="4" forecolor="#333333" gridlines="None" id="gvstatus" onpageindexchanging="gvstatus_PageIndexChanging" onrowcancelingedit="gvstatus_RowCancelingEdit" onrowcommand="gvstatus_RowCommand" onrowediting="gvstatus_RowEditing" onrowupdating="gvstatus_RowUpdating" onselectedindexchanged="gvstatus_SelectedIndexChanged" runat="server" showfooter="True" width="600px">
            <columns>
 <asp:templatefield headerstyle-horizontalalign="Left" headertext="SrNo ">
            <itemtemplate>
                    &lt;%# Container.DataItemIndex + 1 %&gt;
                </itemtemplate>
 </asp:templatefield>

 <asp:templatefield headertext="ID" visible="false">
      <itemtemplate>
      <asp:label columnname_id="" id="lblid" runat="server" text="&lt;%# Bind(">"&gt; </asp:label>
     </itemtemplate>
</asp:templatefield>
<asp:templatefield headertext="EmpName">
      <itemtemplate>
        <asp:label columnname_empname="" id="lblEmpName" runat="server" text="&lt;%# Bind(">"&gt;</asp:label>
       </itemtemplate>
       <edititemtemplate>
           <asp:textbox id="txtEmpName" runat="server" text="&lt;%# Bind(&quot;columnname_EmpName&quot;) %&gt;"></asp:textbox>
        </edititemtemplate>
        <footertemplate>
              <asp:textbox id="txtfEmpName" runat="server"></asp:textbox>
        </footertemplate>
</asp:templatefield>
 <asp:templatefield headertext="empSalary">
        <itemtemplate>
           <asp:label id="lblempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:label>
        </itemtemplate>
        <edititemtemplate>
             <asp:textbox id="txtempSalary" runat="server" text="&lt;%# Bind(&quot;columnname_EmpSalary&quot;) %&gt;"></asp:textbox>
         </edititemtemplate>
         <footertemplate>
            <asp:textbox id="txtfempSalary" runat="server"></asp:textbox>
         </footertemplate>
</asp:templatefield>
 <asp:templatefield itemstyle-width="190px" showheader="False">
         <itemtemplate>
             <asp:button causesvalidation="False" commandname="Edit" id="btnedit" runat="server" text="Edit"></asp:button>
          </itemtemplate>
          <edititemtemplate>
               <asp:button causesvalidation="True" commandname="Update" id="btnupdate" runat="server" text="Update"></asp:button>
                        &nbsp;<asp:button causesvalidation="False" commandname="Cancel" id="btncancel" runat="server" text="Cancel"></asp:button>
         </edititemtemplate>
        <footertemplate>
            <asp:button commandname="Add" id="btnadd" runat="server" text="Add">
        </asp:button></footertemplate>
 </asp:templatefield>
            </columns>
            <pagerstyle backcolor="#A86E07" forecolor="White" horizontalalign="Center">
            <selectedrowstyle backcolor="#E2DED6" font-bold="True" forecolor="#333333">
          <headerstyle backcolor="#A86E07" font-bold="True" forecolor="White">
        <editrowstyle backcolor="#d9d9d9">
    <alternatingrowstyle backcolor="White" forecolor="#A86E07">
 </alternatingrowstyle></editrowstyle></headerstyle></selectedrowstyle>
</pagerstyle>
</asp:gridview>



CodeBehind:


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
gvBind(); //Bind gridview
}
}

public void gvBind()
{ SqlDataAdapter dap = new SqlDataAdapter("select id, empName,empSalary from myTable", conn);
DataSet ds = new DataSet();
dap.Fill(ds);
gvstatus.DataSource = ds.Tables[0];
gvstatus.DataBind();
}
Update the select row from girdview
protected void gvstatus_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
lblmsg.Text = "";
try
{
GridViewRow row = (GridViewRow)gvstatus.Rows[e.RowIndex];
Label lblid = (Label)gvstatus.Rows[e.RowIndex].FindControl("lblid");
TextBox txtname = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtEmpName");
TextBox txtSalary = (TextBox)gvstatus.Rows[e.RowIndex].FindControl("txtempSalary");
string empName = txtname.Text;
string empSalary = txtSalary.Text;
string lblID=lblid.Text;
int result = UpdateQuery(empName, empSalary,lblID);
if (result > 0)
{
lblmsg.Text = "Record is updated successfully.";
}
gvstatus.EditIndex = -1;
gvBind();
}
catch (Exception ae)
{
Response.Write(ae.Message);
}

}
Code to add new record to database form girdview footer
  protected void gvstatus_RowCommand(object sender, GridViewCommandEventArgs e)
{

if (e.CommandName == "Add")
{
string empName = ((TextBox)gvstatus.FooterRow.FindControl("txtfempName")).Text;
string empSalry = ((TextBox)gvstatus.FooterRow.FindControl("txtfempSalary")).Text;
int result = InsertNewRecord(empName, empSalry);
if (result > 0)
{
lblmsg.Text = "Record is added successfully.";
}
gvstatus.EditIndex = -1;
gvBind();

}
}

protected void gvstatus_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvstatus.EditIndex = -1;
gvBind();
}
protected void gvstatus_RowEditing(object sender, GridViewEditEventArgs e)
{
lblmsg.Text = "";
gvstatus.EditIndex = e.NewEditIndex;
gvBind();
}

public void UpdateQuery(string empName, string empSalary, string lblID)
{
SqlCommand cmd = new SqlCommand("update myTable set empName='" + empName + "',empSalary='" + empSalary + "' where id='" + lblID + "'", conn);
conn.Open();
int temp = cmd.ExecuteNonQuery();
conn.Close();
return temp;
}


public void InsertNewRecord(string empName, string empSalary)
{
SqlCommand cmd = new SqlCommand("your insert query ", conn);
conn.Open();
int temp = cmd.ExecuteNonQuery();
conn.Close();
return temp;
}

Thứ Bảy, 18 tháng 8, 2012

How to Resize image while uploading in asp.net using c#

Resize image while uploading in asp.net using c#?

This post will show you how you can resize images in ASP.Net C# during uploading image file.
For we Dotnet Developer in most of our ASP.Net application we have uploaded image facility where will face the performance issue while loading uploaded images to display for the user. In my project their is a similar requiremnt that the user uploaded images will be resized internally through server side while uploading.
I have an .aspx page which will upload images to server harddisk from client pc. And i need to write a program in such a way that it would allow me to resize the image while uploading.

Here's the code:
Firstly, we are going to need the System.Drawing and System.Drawing.Drawing2D namespaces

Design Uploadlogo.aspx:
Upload Logo :


<asp:fileupload id="File1" runat="server">
</asp:fileupload>
 <asp:button id="Button1" onclick="Button1_Click" runat="server" text="Save">
 <asp:label id="lblmsg" runat="server" text=""></asp:label>
</asp:button>



Code Behind: UploadLogo.aspx.cs
  public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
public partial class UploadLogo : System.Web.UI.Page
{
public Size OriginalImageSize { get; set; } //Store original image size.
public Size NewImageSize { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
lblmsg.Text="";
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
Guid uid = Guid.NewGuid();
string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);
string SaveLocation = Server.MapPath("LogoImages") + "\\" + uid+fn;
try
{
string fileExtention = File1.PostedFile.ContentType;
int fileLenght = File1.PostedFile.ContentLength;
if (fileExtention == "image/png" || fileExtention == "image/jpeg" || fileExtention == "image/x-png")
{
if (fileLenght <= 1048576)
{
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
objImage.Save(SaveLocation,ImageFormat.Png);
lblmsg.Text = "The file has been uploaded.";
lblmsg.Style.Add("Color", "Green");
}
else{
lblmsg.Text = "Image size cannot be more then 1 MB.";
lblmsg.Style.Add("Color", "Red");
}
}
else {
lblmsg.Text = "Invaild Format!";
lblmsg.Style.Add("Color", "Red");
}
}
catch (Exception ex)
{
lblmsg.Text= "Error: " + ex.Message;
lblmsg.Style.Add("Color", "Red");
}
}
}

}



Chủ Nhật, 15 tháng 7, 2012

Implementing Convert.ToInt32(string)

Earlier today I used the static helper method System.Convert.ToInt32(string). I thought it would be interesting to have a go at writing my own version of this method.

public static int ConvertToInt32(string integerAsString)
{
var result = 0;
var positiveSigned = integerAsString[0] == '+';
var negativeSigned = integerAsString[0] == '-';

for (var i = (positiveSigned || negativeSigned) ? 1 : 0;
i < integerAsString.Length;
i++)
{
var currentCharAsInt = (int) integerAsString[i] - (int) '0';

if (currentCharAsInt < 0 || currentCharAsInt > 9)
throw new ArgumentException(
string.Format("The String value '{0}' " +
"is not in a recognisable format.",
integerAsString));

result *= 10;
result += currentCharAsInt;
}

return (negativeSigned) ? -result : result;
}

Thứ Hai, 18 tháng 6, 2012

Download .apk from Asp.net website using android phone browser



Here in this article i let you know how to Download .apk file from Asp.net website (WebApplication) by using your android mobile browser. Recently in my project their is one requirement to download .apk file. In my webapplication download page i inserted a button and set path it works fine when you use to download it from your computer, but a problem comes when same i access it from my android phone browser it gives errors (Instead of 605 kb it only download 22kb ie only html content not actual apk file). 
So after small research i figured out the solution and it to simple here it is that by adding  mimeType="application/vnd.android.package-archive".

Environment : My Application is hosted under Window server 2008r2 having IIS 7.

Following the steps you can Download .apk file.

Step 1:  In .aspx page add hyperlink set navigateurl as file path

<asp:HyperLink ID="lnkdwnload" runat="server" NavigateUrl="~/Application_Android/MyAndroidAppAame.apk">Download MyApp</asp:HyperLink>



Step 2: Web.config add mimeMap element under staticContent

<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive"/>
    </staticContent>
</system.webServer>

Thứ Ba, 12 tháng 6, 2012

How to create website with multiple languages in asp.net c#

How to make website for multiple languages?

A website which can support Multiple Languages and change according to the culture of a specific geographical location is not a new topic. Websites to support multiple languages can be a challenging and time-consuming process. You find many artilce related on internet and well explained, But i still see that many of them are complicated for "Beginners". I tried to make this article to approach a more dynamic way to manage languages regarding Globalization/ Localization/ Culture concepts.

With standard HTML pages, you may have to create and maintain duplicate versions of each page for each supported language as well as having the language content embedded into the HTML, where content can’t easily be edited.  For those of you who have to develop multi-lingual interfaces and applications, you’ll be glad to know that ASP.NET makes things easier.
ASP.NET and the .NET framework ship with support for multilingual applications, namely in the form of Resource Files, the CultureInfo class, and the System.Globalization and System.Resources.ResourceManager namespaces.

However, we need to understand what is meant by "globalization", "localization" and "culture" in this context.
Globalization:
Globalization is a process of identifying all the parts of your application that need to be different for respective languages and separate them from the core application.

Localization:

Localization is process of creating and configuring your application for a specific language.

Cultures:

A culture is combination of the language that you speak and the geographical location you belong to. It also includes the way you represent dates, times and currencies. It's important to have a good understanding of Cultures since our new code will make use of them - specifically the System.Globalization.CultureInfo class, and the culture name value which follows the RFC 1766 naming standard. Basically, you create a new CultureInfo instance by specifying the culture name in the constructor:
CultureInfo c = new CultureInfo("en-US");

Follow the step to create website for multiple languages:
Step 1:
Create new website -> Solution Explorer -> Select sln right click and Add Asp.Net Folder - App_GlobalResources; 
Now under App_globalization add resources file (.resx  file), i add three resx file deafult for english, fr for french, de for german haivin key pair values;
Structure look like as in below image:

Step 2:
Add Global.asax file:
Code: write this piece of code
void Application_BeginRequest(Object sender, EventArgs e) 
{
// Code that runs on application startup
HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
}



Step 3:
Add masterPage having a dropdownlist control;
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
if (Session["ddindex"] != null) {
ddlanguage.SelectedValue = Session["ddindex"].ToString();
ddlanguage.SelectedIndex = Convert.ToInt32(Session["ddindex"].ToString());
}
else{
ddlanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
}
}
protected void ddlanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["language"] = ddlanguage.SelectedValue;
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlanguage.SelectedValue);

if (cookie.Value == "en"){
Session["ddindex"] = 0;
}
else if (cookie.Value == "fr"){
Session["ddindex"] = 1;
}
else if (cookie.Value == "de"){
Session["ddindex"] = 2;
}
Server.Transfer(Request.Path);
}
}








Add childPage with controls and on dropdownlist selected index it will display respective language content

My sample Childpage desin code :
set text as resoures key; i.e Text="<%$Resources:Resources,FieldName %>"



<table id="Table1">
<tbody>
<tr>
  <td class="style1"><asp:label id="Label2" runat="server" text="&lt;%$Resources:Resources, FirstName %&gt;"></asp:label></td>
  <td><asp:label id="Label3" runat="server" text="&lt;%$Resources:Resources, LastName %&gt;"></asp:label></td>
</tr>
<tr>
  <td class="style1"><asp:label id="Label4" runat="server" text="&lt;%$Resources:Resources, Gender %&gt;"></asp:label></td>
  <td><asp:radiobuttonlist id="RdBtnLtGender" repeatdirection="Horizontal" runat="server">
     <asp:listitem text="&lt;%$Resources:Resources, Male %&gt;" value="1"></asp:listitem>
     <asp:listitem text="&lt;%$Resources:Resources, Female %&gt;" value="0"></asp:listitem>
  </asp:radiobuttonlist></td>
</tr>
<tr><td class="style1"><asp:label id="Label7" runat="server" text="&lt;%$ Resources:Resources, Month %&gt;"></asp:label></td>
  <td><asp:dropdownlist height="20px" id="ddyear" runat="server" width="64px">
  <asp:listitem value="1">Jan</asp:listitem>
  <asp:listitem value="2">Feb</asp:listitem>
  <asp:listitem value="3">Mar</asp:listitem>
  <asp:listitem value="4">Apr</asp:listitem>
  <asp:listitem value="5">May</asp:listitem>
  <asp:listitem value="6">Jun</asp:listitem>
  <asp:listitem value="7">Jul</asp:listitem>
  <asp:listitem value="8">Aug</asp:listitem>
  <asp:listitem value="9">Sep</asp:listitem>
  <asp:listitem value="10">Oct</asp:listitem>
  <asp:listitem value="11">Nov</asp:listitem>
  <asp:listitem value="12">Dec</asp:listitem>
   </asp:dropdownlist>
  </td>

</tr>

</tbody></table>

ScreenShots :OutPut  

1) For English

















2) For French