Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Wednesday, August 21, 2013

Custom Message box and Confirm window all in one

Hello,
I have created a custom message box and confirm window which can be used in all programming languages and all platforms.
syntex :
AlertCust([Control], {Message Title}, [Message Text], {IconType}, {PromptType}, [OnOk], [OnCancel]);



Description :

  • [Control] : Optional, Pass the control which raises the prompt. in Confirm or Alert window when click ‘OK’ button is clicked, the default server event will be executed, if value is passed. if null, clicking on ‘OK’ the prompt window will be closed, no further action.
  • {Message Title} : Required, Message Title. Title will appear in bold font.
  • [Message Text] : Optional, Message text in second line, in normal fonts.
  • {IconType} : Required, Enum values. pass icon type to display icon specific to message. options Error, Warning, Information
  • {PromptType} : Required,  This property helps to decide what kind of prompt we need. e.g. Validation, MessageBox(OkOnly), OKCancel, YesNo.
  • [OnOk] : Optional, To provided custom callback method, set javascript method name, will be executed when clicked ‘OK’.
  • [OnCancel] : Optional, To provided custom callback method, set javascript method name, will be executed when clicked ‘Cancel’.





Message




anyone can download code from Here

Thursday, November 1, 2012

JavaScriptStringEncode : Javascript Compitable encoding

Hello,

Recently I was facing very interesting issue. and the solution for the issue was introduced in the new updates in asp.net framework 4.0.

Generally when we try to render HTML content on page clientside/ by javascript, it gives error of Potential dangerous content error.

http://msdn.microsoft.com/en-us/library/ms972967.aspx

There are lot's solutions but have to compromise security of page.
by setting

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs"
    Inherits="_default" ValidateRequest="false"%>


 But now we have perfect solution which is introduced in .net framework 4.0

HttpUtility.JavaScriptStringEncode Method


URL encoding makes sure that all browsers correctly encodes text in URL strings. Few Characters such as a question mark (?), ampersand (&), slash (/), and spaces might be truncated or corrupted by some browsers. Therefore, these characters must be encoded in a elements or in query strings where the strings can be re-sent by a browser in a request string.

refer following  MSDN link
http://msdn.microsoft.com/en-us/library/system.web.httputility.javascriptstringencode%28v=vs.100%29.aspx

http://msdn.microsoft.com/en-us/library/dd991914%28v=vs.100%29.aspx

Hope this helps

Tuesday, October 16, 2012

Disable Server Validation Control from ClientSide/ Javascript - ValidatorEnable

Hello Friends,

Recently I required to disable server validation control (RequiredFieldValidator, CompareValidator, CustomValidator, RangeValidator, RagularExpressionValidator, etc) from clientside/ Javascript.
There are few patches to accomplish the  requirement by I liked an approach which is perfect for ClientSide handling.

ValidatorEnable is a javascript mathod lying at asp.net framework javascriptscript

ValidatorEnable(document.getElementById(myVal), Status);

Thanks



Friday, November 18, 2011

Scroll to particular record in GridView

Hello Friends,
here is a tip to scroll the gridview to particular record.
the basic concept is html scrolling. to scroll at particular position create an anchor tag with name as address (eg. #ScrollPoint '# is must')

now redirect the page to the location using javascript call
window.location.href = "#ScrollPoint";

 
same thing can be achieved by anchorlink href
here is sample code

HTML Page
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return MoveTo();" />
    <div style="height: 100px; overflow: auto;">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="ID" SortExpression="ID">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <a name='<%# Eval("ID") %>'></a>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
            </Columns>
        </asp:GridView>
    </div>  


<script type="text/javascript">
        function MoveTo() {
            window.location.href = "#" + document.getElementById('<%= TextBox2.ClientID %>').value;
            return false;
        }
    </script>

Code Behind
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindControls();
            }
        }

        private void BindControls()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Name");
            for (int i = 0; i < 200; i++)
            {
                AddRow(dt);    
            }


            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

        private static void AddRow(DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr["ID"] = dt.Rows.Count + 1;
            dr["Name"] = "Sandeep" + dt.Rows.Count + 1;
            dt.Rows.Add(dr);
        }
    }
Happy Coding...

Thursday, May 26, 2011

Track Error in Javascript Page


Hi
Many times we have faced problems to find what is javascript errors and exactly where??
To track javascript error, It is a good practice to write code in Try..Catch
but sometimes some small syntax error are not allowing to execute the whole js file.
so to track such error during development, we can track by this sample code
  <script type="text/javascript">
        onerror = CallOnError;
        function CallOnError(msg, url, line) {
            var strErrMessage = "";
            strErrMessage += "Message: " + msg + "\n";
            strErrMessage += "Page: " + url + "\n";
            strErrMessage += "Line Number: " + line + "\n\n";
            alert(strErrMessage);
            return true;
        }
    </script>
  

Here is a sample error

try to put on your page

  <script type="text/javascript">
            alert('This is First Test Page);
    </script>

Enjoy Coding

Friday, April 29, 2011

Protect image from being copied

Hello Friends,

Many times I am asked to protect some copyrighted images over web,
so finally I have found a better way to protect from being copied.
There are some cases by which we can copy the image
Here I have taken care of following cases
  • Right click on image and Save the Image
  • Save the Entire page and all images displayed on page will be downloaded to its Data Folder
  • in mozila Firefox, We can save the media files by following steps
    1. Right click on Page, select “View Page Info”
    2. ViewSourceSandeep
    3. It will open a window, Select “Media” tab, here a list of all files will be available
    4. select particular file and click on “Save As” button to save the media
    5. SavemediaSandeep


Now Let’s Start our main topic,that is protect image from being copied
There is a concept called Data URI scheme.
Generally to display any image on page, we use Relative_URL and if we display image using this, the images can be easily copied.
Here we will save image in database and retrieve the same
To Create table
CREATE TABLE [dbo].[Images](
 [ImageID] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [varchar](50) NULL,
 [Image] [image] NULL,
 [ext] [varchar](50) NULL,
 CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
(
 [ImageID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Now,

the aspx page will be very simple like


Monday, October 18, 2010

Select Multiple Checkbox with Shift key in Gridview by javascript

Hello Friends,
Recently i was just looking at my Gridview where i have a checkbox in each row.. now i need to select all Check box.. for that lots of material is available on net..
and all are enough so i am not going to deep in it
check out this… http://www.codeproject.com/KB/grid/GridCheckBox.aspx

but now my problem was that i wanted to select few rows but not all
let’s say in my gridview the number of records are around 100.. and i want to check the checkbox of first 35 records
in that case i had to click on checkbox of all 35 rows.
i thought, like all mail accounts like gmail, yahoo, live and in may more…
i should be able to select multiple records by shift key.
means select the first record and pressing shift key select the 35st record so all the records in between will be selected..
and for that i found lots of jquery or any other javascripts.
but here i have tried to make something my own and i am happy to make it..
First With Shift Secod with Shift Selected with shift
here is code

on Page

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="Id" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" 

onclick="CheckAllCheckbox(document.getElementById('ctl00_ContentPlaceHolder1_GridView1'),this,event);"
                        runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>







on code Behind


protected void Page_Load(object sender, EventArgs e)
   {
       if (!IsPostBack)
       {
           DataTable dt = new DataTable();
           dt.Columns.Add("ID");
           dt.Columns.Add("Name");
           DataRow dr;
           for (int i = 1; i < 130; i++)
           {
               dr = dt.NewRow();
               dr["ID"] = i;
               dr["Name"] = "Record No" + i.ToString();
               dt.Rows.Add(dr);
           }
           GridView1.DataSource = dt;
           GridView1.DataBind();
       }
   }
Javascript
var lst = null;
        function CheckAllCheckbox(ctrl, sValue, e) {
            var chkName = sValue.id;
            var arlstr = sValue.id.split(ctrl.id);
            var id = arlstr[1].split('_')[1].substring(3);

            var ee = (window.event) ? event : e;
            if (ee.shiftKey) {
                if (lst != null) {
                    var First = 0, last = 0;
                    if (parseInt(lst) > parseInt(id)) {
                        First = parseInt(id);
                        last = parseInt(lst);
                    }
                    else {
                        First = parseInt(lst);
                        last = parseInt(id);
                    }

                    for (i = First; i < last; i++) {                        
                        var p = (i <= 9 ? '0' + i : i);
                        var ctrlnew = chkName.replace('ctl' + id, 'ctl' + p);                        
                        document.getElementById(ctrlnew).checked = sValue.checked;
                    }                    
                }
            }
            lst = id;
        }
Here is the Source to Download http://cid-552998535cb9985d.office.live.com/self.aspx/.Public/SelectWithShift.rar Thanks

Wednesday, April 14, 2010

Light-weight Popup using CSS and Javascript..

Hello Friends
Once Again with a Rocking point we have seen lots of Popup till now…..
all are good at their places just search on Google “Model Popup” and you will get a long list of examples and javascripts for popup…
Ajax Control toolkit Model Popup Extender http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/ModalPopup/ModalPopup.aspx
 then few more
 http://www.modalpopups.com/blog/
http://www.jquery-dev.com/2008/12/02/jqmodal-jquery-modal-popup-plugin
one more javascript framework is Dojo http://www.dojotoolkit.org/
here i am also one type of popup… but i am sure you will like it
because it don’t require any kind of configuration and dependencies…

    

it is combination of CSS and javascript… with 70:30 ratio….
means here CSS is used more and rest is javascript….
then also its more power full

so from first sight you can determine its light–weight compare to other model popups

here i have an example…
   1: <input id="Button1" type="button"

   2:      value="Dispay Message" onclick="ShowDiv('DivPopUp')" />





Drop the control on which you want to fire ModelPopup.. and assign javascript event to fire onclick="ShowDiv('DivPopUp')"




if you are using server control like


   1: <asp:Button ID="Button2" runat="server" Text="Dispay Message" />



then at Server Side code….


in Page_Load Event


   1: Button2.Attributes.Add("onclick", "ShowDiv('DivPopUp')");



now

Friday, March 5, 2010

Popup new Window by Javascript

A very Common trick
Open a new window as Popup by javascript…
Clicking on any Server Button

   1: <asp:Button ID="Button1" 
   2:                 runat="server" 
   3:                 OnClientClick="window.open('Page2.aspx',null,'height=200,width=400
   4:                         ,status=yes,toolbar=no,menubar=no,location=no,scroll=no');
   5:                         return false;"
   6:                 Text="Button" />







All The Best..