Friday, 18 April 2014

Disable Buttons Until Textboxes/Inputs are Not Filled Using Jquery


Disable Buttons Until Textboxes/Inputs are Not Filled Using Jquery


Today I will share a nasty trick to disable the buttons in the form until the inputs are not filled properly using Jquery...

Design Part:


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Disable Button</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js" ></script>
    <script type="text/javascript">
    
    $(document).ready(function (){
    validate();
    $('#txtName, #txtAddress, #txtPhone').change(validate);
});

function validate(){
    if ($('#txtName').val().length   >   0   &&
        $('#txtAddress').val().length  >   0   &&
        $('#txtPhone').val().length    >   0) {
        $("#btnClick").prop("disabled", false);
    }
    else {
        $("#btnClick").prop("disabled", true);
    }
}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Name:"></asp:Label>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="Address"></asp:Label>
        <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label3" runat="server" Font-Bold="True" Text="Phone:"></asp:Label>
        <asp:TextBox ID="txtPhone" runat="server"></asp:TextBox><br />
        <br />
        <asp:Button ID="btnClick" runat="server" OnClick="Button1_Click" Text="Submit" /></div>
    </form>
</body>
</html>

And here is the Output for the same:



Thursday, 17 April 2014

Upload and Read Flat Files[.txt] Using File Upload in Gridview Using C#.Net


Upload and Read Flat Files[.txt] Using File Upload in Gridview Using C#.Net

In this Post I will show you how to read the content of Flat files by uploading and showing it inside a Gridview..
Refer the Code Snippet Below:

Design Part:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Upload and Display in Gridview</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="UploadFile" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EmptyDataText = "No files uploaded">
    <Columns>
        <asp:BoundField DataField="Text" HeaderText="File Name" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkDownload" Text = "Download" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "DownloadFile"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
           <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkView" Text = "View" CommandArgument = '<%# Eval("Value") %>' runat="server" OnClick = "ViewFile"></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID = "lnkDelete" Text = "Delete" CommandArgument = '<%# Eval("Value") %>' runat = "server" OnClick = "DeleteFile" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
        <br />
        <asp:Label ID="lblMsg" runat="server" Font-Bold="True" Font-Italic="True" ForeColor="#00C000"></asp:Label>&nbsp;<br />
        <br />
        <asp:Button ID="btnClear" runat="server" OnClick="btnClear_Click" Text="Clear" /></div>
    </form>
</body>
</html>


Code-Behind: 


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                files.Add(new ListItem(Path.GetFileName(filePath), filePath));
            }
            GridView1.DataSource = files;
            GridView1.DataBind();
        }
    }
    protected void UploadFile(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected void DownloadFile(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        string filePath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
        Response.WriteFile(filePath);
        Response.End();
    }

    protected void DeleteFile(object sender, EventArgs e)
    {
        lblMsg.Text = "";
        string filePath = (sender as LinkButton).CommandArgument;
        File.Delete(filePath);
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected void ViewFile(object sender, EventArgs e)
    {
        string filePath = (sender as LinkButton).CommandArgument;
        string inputString;
        lblMsg.Text = "";
        using (StreamReader streamReader = File.OpenText(filePath))
        {
            inputString = streamReader.ReadLine();
            while (inputString != null)
            {
                lblMsg.Text += inputString + "<br />";
                inputString = streamReader.ReadLine();
            }
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        lblMsg.Text = "";
    }
}

Resize Image Using C#.Net


Resize Image Using C#.Net

In this Post I will show you how to resize a Uploaded Image and Save the same in a specific Directory Using C#.Net..

Design Part:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Resize Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Text="Height"></asp:Label>
        <asp:TextBox ID="txtheight" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label2" runat="server" Font-Bold="True" Text="Width"></asp:Label>
        <asp:TextBox ID="txtWidth" runat="server"></asp:TextBox><br />
        <br />
        <asp:Label ID="Label3" runat="server" Font-Bold="True" Text="Image Name"></asp:Label>
        <asp:TextBox ID="txtImage" runat="server"></asp:TextBox><br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" /><br />
        <br />
        <asp:Label ID="lblMsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label></div>
    </form>
</body>
</html>

Code-Behind:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
//using ImageResizer;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public static void SaveImage(int imgheight, int imgwidth, string imgfilename, string path, FileUpload upImage)
    {
        int width = imgwidth;
        int height = imgheight;
        string fileName = imgfilename;
        float redPercentage = 100;

        try
        {
            var bmpOrg = new Bitmap(upImage.PostedFile.InputStream);
            float wPercentage = (Convert.ToSingle(width) * 100) / Convert.ToSingle(bmpOrg.Width);
            float hPercentage = (Convert.ToSingle(height) * 100) / Convert.ToSingle(bmpOrg.Height);
            redPercentage = (wPercentage < hPercentage) ? wPercentage : hPercentage;
            redPercentage = (redPercentage > 100) ? 100 : redPercentage;
            bmpOrg.MakeTransparent();
            //to save image with new height and width without frame
            //var imgBanner = ImageResize.ScaleByPercent(bmpOrg, redPercentage);
            //to save image with new height and width with frame specified
            System.Drawing.Image imgBanner = ScaleByPercent(bmpOrg, redPercentage);
            System.Drawing.Bitmap bmpOrg1 = new System.Drawing.Bitmap(imgBanner);
            Graphics newGraphic = Graphics.FromImage(bmpOrg1);
            newGraphic.Clear(Color.Transparent);
            newGraphic.DrawImage(bmpOrg, 0, 0, bmpOrg1.Width, bmpOrg1.Height);
            bmpOrg1.MakeTransparent(bmpOrg1.GetPixel(0, 0));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            bmpOrg1.Save(path + fileName + ".jpeg");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public static System.Drawing.Image ScaleByPercent(System.Drawing.Image imgPhoto, float Percent)
    {
        float nPercent = ((float)Percent / 100);
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int sourceX = 0;
        int sourceY = 0;
        int destX = 0;
        int destY = 0;
        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);
        Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
        grPhoto.Clear(Color.White);
        grPhoto.DrawImage(imgPhoto,
        new Rectangle(destX, destY, destWidth, destHeight),
        new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
        GraphicsUnit.Pixel);
        grPhoto.Dispose();
        return bmPhoto;

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //Set the Path where output file should be saved
        string path=@"D:\Practice New\Transparent Image\Image\";
        //ImageResizer.Class1.SaveImage(Convert.ToInt32(txtheight.Text), Convert.ToInt32(txtWidth.Text), txtImage.Text, path, FileUpload1);
        SaveImage(Convert.ToInt32(txtheight.Text), Convert.ToInt32(txtWidth.Text), txtImage.Text, path, FileUpload1);
    }
}

Check Server Status Using C#.Net


Check Server Status Using C#.Net

  
A SMALL NOTE FROM EDITOR:

Hi all, This is my 200th Post. All this Journey started with a single Post in a small newbie blog @ October,2012 which has evolved into this massive asp.net Repository as of today. This site has crossed more than 0.2 Millions Pageviews from 160 Countries which itself speaks of its Popularity . I would heartily thank all the readers of this site and request you to be the part of this site in the future as well. New Ideas and Innovative thoughts are always welcomed. You can contact me Personally at my mail Id vishalranjan2k11@gmail.com.

In this Post We can see check how to check the status of the Server Using C#.Net. Its a kind of Ping Request to the Target server to check its Status. Refer the Code Snippet Below:

Design Part:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Check Server Status</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <br />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /><br />
        <br />
        <asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>&nbsp;</div>
    </form>
</body>
</html> 

Code-Behind:
 

using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.NetworkInformation;

public partial class CheckServerStatus : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected string PingSvrs(string hostname)
    {
        string functionReturnValue = null;
        long rtTime = 0;
        Ping ping = new Ping();
        try
        {
            PingReply reply = ping.Send(hostname);
            if (reply.Status == IPStatus.Success)
            {
                functionReturnValue = "G:Response Received";
                rtTime = reply.RoundtripTime;
            }
            else
            {
                functionReturnValue = "R:" + hostname + " Status: " + reply.Status.ToString();
            }
        }
        catch (Exception ex)
        {
            functionReturnValue = "R:" + hostname + " error: " + ex.Message;
        }
        return functionReturnValue;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        lblMsg.Text = PingSvrs(TextBox1.Text);
    }
}

Friday, 4 April 2014

Validating HTML Tags in Textbox/Input Using Javascript : Error - A potentially dangerous Request.Form value was detected from the client


Validating HTML Tags in Textbox/Input Using Javascript


Hi You might have came across this Error when someone entered a html tag in the textbox.. This will generate an error as below:

A potentially dangerous Request.Form value was detected from the client

To Resolve this issue you can use validation using javascript which will validate the input strings and forbade the user from entering HTML tags..

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Restrict HTML Tags</title>
    
      <script type="text/javascript">
      function Validate(x,y) {
          str = (document.getElementById('TextBox1')).value;
          if (str.match(/([\<])([^\>]{1,})*([\>])/i) == null) {
             
              y.IsValid = true;
          }
          else {
           
              y.IsValid = false;  
          }
      }
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox ID="TextBox1" runat="server" />

<asp:CustomValidator ID="CustomValidator2" runat="server" 
            ErrorMessage="HTML Tags Not Allowed" ControlToValidate="TextBox1" 
            ClientValidationFunction="Validate"></asp:CustomValidator><br />
        <br />
            
      
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <br />
        <br />
        <asp:Label ID="lblMsg" runat="server"></asp:Label></div>
    </form>
</body>
</html>  

Another Alternative Approach is to Use Global.asax's Application_Error Event to display a User Friendly Error Message whenever this kind of Error occurs..


protected void Application_Error(object sender, EventArgs e)
{
    Exception appError = Server.GetLastError();
    if (appError is HttpRequestValidationException)
    {
       Response.Write("<h2>Global Page Error</h2>\n");
       Response.Write("<p>" + appError.Message + "</p>\n");   
       // Clear the error from the server
       Server.ClearError();
    }
}

back to top