Friday, 26 December 2014

Show youtube vedio on Popup

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Show YoutTube Videos in popup window when click on link</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

/* video settings come here */
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '350',
width: '600',
videoId: 'Sne_5PwcAss',
events: {
'onReady': onPlayerReady
}
});
}
/* Autoplay when the dialog opens */
function onPlayerReady(event) {
event.target.playVideo();
}
$(document).ready(function(){
var overlay = jQuery('<div id="overlay"></div>');
$('.close').click(function(){
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
});

$('.x').click(function(){
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
});

$('.click').click(function(){
overlay.show();
overlay.appendTo(document.body);
$('.popup').show();
return false;
});
});
</script>
<style type="text/css">
#overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000;
filter:alpha(opacity=70);
-moz-opacity:0.7;
-khtml-opacity: 0.7;
opacity: 0.7;
z-index: 100;
display: none;
}
.content a{
text-decoration: none;
}
.popup{
width: 100%;
margin: 0 auto;
display: none;
position: fixed;
z-index: 101;
}
.content{
min-width: 600px;
width: 600px;
min-height: 150px;
margin: 100px auto;
background: #f3f3f3;
position: relative;
z-index: 103;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 5px #000;
}
.content p{
clear: both;
color: #555555;
font-size: 13px;
text-align: justify;
}
.content p a{
color: #d91900;
font-weight: bold;
}
.content .x{
float: right;
height: 35px;
left: 22px;
position: relative;
top: -25px;
width: 34px;
}
.content .x:hover{
cursor: pointer;
}
</style>
</head>
<body>
<div class='popup'>
<div class='content'>
<img src='http://www.developertips.net/demos/popup-dialog/img/x.png' alt='quit' class='x' id='x' />
<div id='player'></div>
<p><a href='' class='close'>Close</a></p>
</div>
</div>                
<div id='container'>
<a href='' class='click'><b>Click Here to See Popup! </b></a> <br/>
</div>
</body>
</html>

Show Current Location of user in Map


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get User Current Location using Google Map Geolocation API Service in asp.net website</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places">
</script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("Geo Location is not supported on your current browser!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city=position.coords.locality;
var myLatlng = new google.maps.LatLng(lat, long);
var myOptions = {
center: myLatlng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title: "lat: " + lat + " long: " + long
});

marker.setMap(map);
var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:"+lat+"<br /> Longitude:"+long+"" });
infowindow.open(map, marker);
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div id="map_canvas" style="width: 500px; height: 400px"></div>
</form>
</body>
</html>

Restriction in File upload Extension

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function validate() {
var uploadcontrol = document.getElementById('<%=FileUpload1.ClientID%>').value;
//Regular Expression for fileupload control.
var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.doc|.docx|.DOC|.DOCX)$/;
if (uploadcontrol.length > 0)
{
//Checks with the control value.
if (reg.test(uploadcontrol))
{
return true;
}
else
{
//If the condition not satisfied shows error message.
alert("Only .doc, docx files are allowed!");
return false;
}
}
} //End of function validate.
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center">
<tr>
<td>
<b>Restrict File Upload sample</b> <br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return validate();" />
<br />
<asp:Label ID="Label1" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Bouncing Menu or Button

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Menu with Bounce Effect</title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="http://dev.css-zibaldone.com/js/jquery/plugins/jquery.easing.js"></script>
<script type="text/javascript">
$(function () {
$('li', '#navigation').each(function () {
var $li = $(this);
var $a = $('a', $li);
$a.hover(function () {
$a.stop(true, true).animate({
height: '3em',
lineHeight: '3em',
bottom: '1em'
}, 'slow', 'easeOutBounce');
}, function () {
$a.stop(true, true).animate({
height: '2em',
lineHeight: '2em',
bottom: 0
}, 'slow', 'easeOutBounce');
});
});
});
</script>
<style type="text/css">
#navigation {
height: 4em;
margin: 0;
padding: 0 1em;
list-style: none;
border-bottom: 2px solid #0270BF;
}
#navigation li {
height: 100%;
float: left;
margin-right: 0.5em;
}
#navigation a {
float: left;
height: 2em;
padding: 0 1em;
background: #0270BF;
color: #fff;
line-height: 2;
text-transform: uppercase;
font-weight: bold;
text-decoration: none;
margin: 2em 0 0 0;
letter-spacing: 0.1em;
position: relative;
}
#navigation a:hover {
background: #F86000;
}
</style>
</head>
<body>
<div>
<ul id="navigation">
<li><a href="#">Home</a></li>
<li><a href="#">Articles</a></li>
<li><a href="#">About</a></li>
</ul>
</div>
</body>
</html>

Thursday, 18 December 2014

Email Integration

try
        {
            string mailmsg = string.Format("Sales " +
            "<b>Enquiry Details</b> <br /> <br /> " +
            "<br /> Ticket ID: " + ticket_id.ToString() );

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("demo@gmail.com");
            mail.To.Add("pqr@gmail.com");
            mail.To.Add("abc@gmail.com");
            mail.To.Add("xyz@gmail.com");
            mail.Subject = "Sales Team";
            mail.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
            System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailmsg, @"<(.|\n)*?>", string.Empty), null, "text/plain");
            System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailmsg, null, "text/html");
            mail.AlternateViews.Add(plainView);
            mail.AlternateViews.Add(htmlView);
            mail.Body = mailmsg;
            mail.IsBodyHtml = true;

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Host = "smtpout.asia.secureserver.net";
            smtpClient.Port = 80;
            smtpClient.EnableSsl = false;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("demo@gmail.com", "password");
            smtpClient.Send(mail);
        }
        catch (Exception)
        {
            // throw ex;
        }

Saturday, 13 December 2014

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).


WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

This error is related to Requiredfied validation
To remove this error you can use below statement with in webconfig file

<configuration>
 
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    
    </system.web>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> // use this statement
  </appSettings>
</configuration>

Monday, 8 December 2014

State Management

Different types of state management?
There are two different types of state management:

Client Side State Management
View State
Hidden Field
Cookies
Control State

Server Side State Management
Session
Application Object
Caching
Database

Client Side state management does not use any server resource , it store information using client side option. Server Side state management use server side resource for store data. Selection of client side and server side state management should be based on your requirements and the selection criteria that are already given.

What is view state?
View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.

Example:

If you want to add one variable in View State,

 ViewState["Var"]=Count;
For Retrieving information from View State


string Test=ViewState["TestVal"];
Sometimes you may need to typecast ViewState Value to retreive. As I give an Example to strore and retreive object in view state  in the last of  this article.

Advantages of view state?
This are the main advantage of using View State:
Easy to implement
No server resources are required
Enhanced security features ,like it can be encoded and compressed

Disadvantages of view state?
This are the main disadvantages of using View State:

It can be performance overhead if we are going to store larger amount of data , because it is associated with page only.
Its stored in a hidden filed in hashed format (which I have discussed later) still it can be easily trapped.
It does not have any support on mobile devices.

When we should use view state?
I already describe the criteria of selecting State management. A few point you should remember when you select view state for maintain your page state.

Size of data should be small , because data are bind with page controls , so for larger amount of data it can be cause of performance overhead.
Try to avoid storing secure data in view state

When we should avoid view state?
You won't need view state for a control for following cases,
The control never change
The control is repopulated on every postback
The control is an input control and it changes only of user actions.
Where is view state stored?
View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client Browser. View State use Hidden field to store its information in a encoding format.

QuestionsAnswer
Client Side or Server Side ?Client Side
Use Server Resource ?No
Easy to implement ?Yes
Cause Performance Issue ?For heavy data and case of encryption & decryption
Support Encryption Decryption?Yes
Can store objects ?Yes, but you need to serialize the class.
TimeoutNo

Tuesday, 2 December 2014

Log File in Asp.Net

try
{

}
  catch (Exception ex)
        {
            using (TextWriter tws = new StreamWriter(Server.MapPath("Log.txt"), true))
            {
                tws.WriteLine(System.DateTime.Now.ToString());
                tws.WriteLine(ex.ToString());
            }
        }

Monday, 1 December 2014

Give own column name in Export in excel from sql

 StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            Response.ClearContent();
            Response.Charset = "";

            htw.Write("<table border=2><b><tr><td align=center>Name</td><td>Mobile No.</td><td>Alternate No.</td><td align=center>Email</td><td>Date of Birth</td><td>Gender</td><td>Marital Status</td><td align=center>Spouse Name</td><td>Spouse Mobile</td><td>Spouse Alternate No.</td><td>Spouse Date of Birth</td><td align=center>Residential Address</td><td align=center>Official Address</td><td>Car</td><td>Car Brand</td><td>Car No.</td><td align=center>Father Name</td><td>Father Mobile No.</td><td>Father Date of Birth</td><td align=center>Mother Name</td><td>Mother Mobile No.</td><td>Mother Date of Birth</td><td align=center>Brother Name</td><td>Brother Mobile No.</td><td>Brother Date of Birth</td><td align=center>Sister Name</td><td>Sister Mobile No.</td><td>Sister Date of Birth</td><td>Credit Card No.</td align=center><td>Delivery Address</td><td>Anniversary Date</td><td>No. of Child</td><td>Child Name</td><td>Child Mobile no.</td><td align=center>Child School</td><td>Child Name</td><td>Child Mobile no.</td><td align=center>Child School</td><td>Child Name</td><td>Child Mobile no.</td><td align=center>Child School</td><td>Child Name</td><td>Child Mobile no.</td><td align=center>Child School</td><td>Child Name</td><td>Child Mobile no.</td><td align=center>Child School</td><td>Date</td><td>Ticket No.</td><td>Temprorary</td><td>Temprorary</td><td>Temprorary</td></tr></b></table>");


            Response.ClearContent();
            Response.Charset = "";
            Response.AddHeader("content-disposition", "attachment; filename=Squarekart_log.xls");
            Response.ContentType = "application/vnd.ms-excel";
            GridView gridExcel = new GridView();
             gridExcel.ShowHeader = false;         // hide header comes from sql

            gridExcel.RowStyle.Font.Size = FontUnit.Point(9);
            gridExcel.AlternatingRowStyle.Font.Size = FontUnit.Point(9);
            gridExcel.AlternatingRowStyle.ForeColor = System.Drawing.Color.FromName("Black");
            gridExcel.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("White");
            gridExcel.RowStyle.BackColor = System.Drawing.Color.FromName("White");
            gridExcel.RowStyle.ForeColor = System.Drawing.Color.FromName("Black");
            gridExcel.HeaderStyle.Font.Bold = true;
            gridExcel.AllowPaging = false;
            gridExcel.AllowSorting = false;
            gridExcel.GridLines = GridLines.Both;

            gridExcel.DataSource = dobj.search_dashboard(txtfrom.Text, txtto.Text, txtmob.Text, txtname.Text);
            gridExcel.DataBind();
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter htw = new HtmlTextWriter(sw);
            gridExcel.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();

show multiple column in limited column in gridview


        i_temp = Convert.ToInt32(ds.Tables[0].Rows[0]["child"].ToString());// fetch all detail

// initailize column  which shows in gridview
   
        string ch1 = ds.Tables[0].Rows[0]["c_name1"].ToString();
        string ch1m = ds.Tables[0].Rows[0]["c_mobile1"].ToString();
        string ch1s = ds.Tables[0].Rows[0]["c_school1"].ToString();
        string ch2 = ds.Tables[0].Rows[0]["c_name2"].ToString();
        string ch2m = ds.Tables[0].Rows[0]["c_mobile2"].ToString();
        string ch2s = ds.Tables[0].Rows[0]["c_school2"].ToString();
        string ch3 = ds.Tables[0].Rows[0]["c_name3"].ToString();
        string ch3m = ds.Tables[0].Rows[0]["c_mobile3"].ToString();
        string ch3s = ds.Tables[0].Rows[0]["c_school3"].ToString();
        string ch4 = ds.Tables[0].Rows[0]["c_name4"].ToString();
        string ch4m = ds.Tables[0].Rows[0]["c_mobile4"].ToString();
        string ch4s = ds.Tables[0].Rows[0]["c_school4"].ToString();
        string ch5 = ds.Tables[0].Rows[0]["c_name5"].ToString();
        string ch5m = ds.Tables[0].Rows[0]["c_mobile5"].ToString();
        string ch5s = ds.Tables[0].Rows[0]["c_school5"].ToString();


//array to show values in a gridview
        string[,] details = { { ch1, ch1m, ch1s }, { ch2, ch2m, ch2s }, { ch3, ch3m, ch3s }, { ch4, ch4m, ch4s }, { ch5, ch5m, ch5s } };

        DataTable dt = new DataTable();
        dt.Columns.Add("StudentName");
        dt.Columns.Add("StudentMobile");
        dt.Columns.Add("StudentAddress");
        //dt.WriteXml();
        for (int i = 0; i < 5; i++)// insert array values in a gridview
        {
            dt.Rows.Add();
            for (int j = 0; j < 3; j++)
            {
                dt.Rows[i][j] = details[i, j].ToString();

            }
            dobj.tempchild(dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString(), dt.Rows[i][2].ToString(), (i + 1).ToString());
        }
        GridView1.DataSource = dobj.tempchild1();
        GridView1.DataBind();
        dobj.tempchild2();//flush temp table

Get IP address of client system

  string VisitorsIPAddr = string.Empty;
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
        {
            VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
        }
        string IP = "Your IP is: " + VisitorsIPAddr;
        Response.Write(IP);

Get page URL or page name


 protected void Page_Load(object sender, EventArgs e)
    {

        string pagename = Request.Url.AbsolutePath;
        string url = Request.Url.AbsoluteUri;
        Response.Write("URL :- " + url + "<br />Page name:- " + pagename);
    }

Load page with fade in effect

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="fadediv" style="display:none">
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
Load page with fade in effect...<br />
</div>
    </form>
</body>
</html>

Tree View in asp.net

//Tree view show,select and show selected values

 <div>
        <asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="Leaf" >
            <Nodes>
                <asp:TreeNode Text="Main" Value="Main">
                    <asp:TreeNode Text="child" Value="child"></asp:TreeNode>
                    <asp:TreeNode Text="child2" Value="child2"></asp:TreeNode>
                    <asp:TreeNode Text="child3" Value="child3"></asp:TreeNode>
                </asp:TreeNode>
                <asp:TreeNode Text="Main2" Value="Main2">
                    <asp:TreeNode Text="child4" Value="child4"></asp:TreeNode>
                    <asp:TreeNode Text="child5" Value="child5"></asp:TreeNode>
                </asp:TreeNode>
            </Nodes>
           
        </asp:TreeView>
        <asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
    </div>
//Show selected values
 protected void Button1_Click(object sender, EventArgs e)
    {
        foreach( TreeNode t1 in this.TreeView1.CheckedNodes )
        {
            Response.Write(t1.Text);
        }
    }

Date validation format yyyy-MM-dd

     <asp:TextBox ID="txtto" runat="server"></asp:TextBox>// textbox
                      // calender theme
    <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtto"      Format="yyyy-MM-dd" CssClass="cal_Theme1" />
                        // validation
 <asp:RegularExpressionValidator ID="RegularExpressionValidatorfatdob" runat="server" ErrorMessage="*" ForeColor="Red" ValidationExpression="^(19|20)\d\d[\- /.](0[1-9]|1[012])[\- /.](0[1-9]|[12][0-9]|3[01])$" ValidationGroup="valsearch" ControlToValidate="txtto"></asp:RegularExpressionValidator>