Saturday, February 13, 2010

Resize image and save without saving it to temporary file, C#

Upload an image after resizing to specific size without saving it to temporary file.      


ResizeImageAndSave(fileImage.PostedFile.InputStream, Width, Height, FileName);

        ///
        /// Resize image of Weight X Height and save
        ///

        public static void ResizeImageAndSave(Stream fs, int intW, int intH, string FileName)
        {
            System.Drawing.Image objImg = Bitmap.FromStream(fs);
            int intImgH = objImg.Height;
            int intImgW = objImg.Width;
            double R = ((double)intImgW / (double)intImgH);
            //if image is greater than 800*800
            if (intImgH > intImgW)
            {
                if (intImgH > intH)
                {
                    intImgH = intH;
                    intImgW = (int)(intH * R);
                }
            }
            else
            {
                if (intImgW > intW)
                {
                    intImgW = intW;
                    intImgH = (int)(intW / R);
                }
            }

          
            Bitmap outputImage = new Bitmap(intImgW, intImgH,PixelFormat.Format24bppRgb);
            outputImage.SetResolution(objImg.HorizontalResolution, objImg.VerticalResolution);
            Graphics graphics = Graphics.FromImage(outputImage);
            graphics.Clear(Color.White);
            graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.DrawImage(objImg, new Rectangle(0, 0, intImgW, intImgH), new Rectangle(4, 4, objImg.Width - 4, objImg.Height - 4), GraphicsUnit.Pixel);
            graphics.Dispose();
            outputImage.Save(FileName);
            outputImage.Dispose();
            outputImage = null;
        }

Stored procedure for paging with sorting


CREATE PROCEDURE DataWithPagingAndSorting
--Add the parameters for the stored procedure here
    @insPageNo SMALLINT = 1,
    @insPageSize SMALLINT = 10,
    @SortType varchar(128) = 'DT',
AS
BEGIN
    DECLARE @intTotalCount INT,
            @intPageCount INT
      SET NOCOUNT ON

   SELECT @intTotalCount = COUNT(Id) from TableName
                   
        SET @intPageCount = @intTotalCount/@insPageSize;       
        IF (@intTotalCount%@insPageSize<>0)
            SET @intPageCount= @intPageCount+1
        IF (@insPageNo>@intPageCount)
            SET @insPageNo=@intPageCount       

        SELECT TOP (@insPageSize) *
            FROM (
                    SELECT ROW_NUMBER() OVER ( ORDER BY 
                                                    CASE WHEN @SortType  = 'NM' THEN Name END
                                                    ,CASE WHEN @SortType  = 'EM' THEN [Email] END
                                                    ,CASE WHEN @SortType  = 'MN' THEN ContactNo END
                                                    ,CASE WHEN @SortType  = 'CC' THEN Country END
                                                    ,CASE WHEN @SortType  = 'DT' THEN CreDate END DESC
                                                ) AS RowNum,
                            M.Id [ID], [Name],M.Add1, M.Add2,
                            M.Town, M.PostCode, M.ContactNo, M.CreDate, M.ActDate , Country, M.Email
                    from TableName M                
                ) A
                   
            WHERE A.RowNum > (@insPageSize * (@insPageNo - 1))
               
           
            SELECT @intTotalCount as TotalCount;
END

Friday, February 12, 2010

Code to Read Files from Directory - C#, ASP.NET

public void ReadFile(strFileName)
{
      System.IO.DirectoryInfo obj = new DirectoryInfo(Server.MapPath("FolderName/" + strFileName);
      FileInfo[] Files = obj.GetFiles();

      for (int i = 0; i < Files.Length; i++)
     {
          string FileName = Files[i].Name;
          string FileExtension = FileName.Substring(0, FileName.LastIndexOf("."));
          InsertToDB(FileName, FileExtension ); --Function to save in database
     }
}

Thursday, February 11, 2010

Get value of radiobuttonlist, javascript

Call the javascript function at page_load()

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rbtnList.Attributes.Add("onclick", "javascript:checkOthersOption('" + rbtnList.ClientID + "');");
}
}

And Add javascript to the aspx page


function checkOthersOption(id)
{
var radioList = document.getElementById(id);
var radio = radioList.getElementsByTagName('input');
alert(radio.length);
for (var i = 0; i < radio.length; i++)
{
if(radio[i].type =="radio")
{
if (radio[i].checked)
alert(radio[i].value);
}
}

}

Saturday, February 6, 2010

Javascript Date validation function

function checkDate(ddlDay,ddlMonth,ddlYear)
{

var d=document.getElementById(ddlDay).value;
var m=document.getElementById(ddlMonth).value;
var y=document.getElementById(ddlYear).value;

var yl=1900; // least year to consider
var ym=2100; // most year to consider
var flag = true;

if (m<1>12) flag=false;
if (d<1>31) flag=false;
if (yym) flag=false;
if (m==4 || m==6 || m==9 || m==11)
if (d==31) flag=false;
if (m==2)
{
var b=parseInt(y/4);
if (isNaN(b)) flag=false;
if (d>29) flag=false;
if (d==29 && ((y/4)!=parseInt(y/4))) flag=false;
}

if(flag)
{
return (true);
}
else
{
return (false);
}

return(true);
}

How to use client script on button with validation controls

Call function onClientClick='Validate()'

JavaScript function:

function Validate()
{
Page_ClientValidate('Valid') ;//where "Valid" is validation group

if (Page_IsValid == true && Page_ValidationActive == true)
{
//do something
}

}

How to Print a Panel

First do the necessary at server then save the control Panel in the session at Page MainPage.aspx

protected void btn_Click(object sender, EventArgs e)
{
Session["Ctrl"] = pnlContainer;//Panel ID
Response.Redirect("print.aspx");
}


Create a new page with the print.aspx, Html Code as follows:


Add Content PlaceHolder to html with name ph

"<asp:PlaceHolder ID="ph" runat="server" /&gt

And print.aspx.cs code is follows:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["Ctrl"] != null && Session["Ctrl"].ToString() != "")
Ph.Controls.Add((Panel)Session["Ctrl"]);
}
else
{
Response.Redirect("MainPage.aspx");
}
}

How to Avoid Sql-injection :-

Principle

Implementation

Never trust user input

Validate all textbox entries using validation controls, regular expressions, code, and so on

Never use dynamic SQL

Use parameterized SQL or stored procedures

Never connect to a database using an admin-level account

Use a limited access account to connect to the database

Don't store secrets in plain text

Encrypt or hash passwords and other sensitive data; you should also encrypt connection strings

Exceptions should divulge minimal information

Don't reveal too much information in error messages; use customErrors to display minimal information in the event of unhandled error; set debug to false

How to get the readonly textbox value on the server

The ReadOnly TextBox will ignore the submitted text , this change due to security reasons .

For example you want to use the textbox and you don't want to let the user to change the textbox manually , now the problem is that the selected value will not be
accepted by the textbox when the user submit the form , because the textbox is in readonly mode ,
in this case you need to manually set the submitted textbox value , you can easily use the values that is submitted via form collection ,

something like this:

Protected void Page_Load(object Sender,EventArgs e)
{
TextBox1.Text = Server.HtmlEncode(Request.Form(TextBox1.UniqueID))
}

Wednesday, February 3, 2010

Trim Function in Javascript

function trim(str)
{
if(!str || typeof str != 'string')
return null;

return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}