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>
                

Friday, 28 November 2014

Page life cycle of ASP.net

MethodsDescription
Page_InitPage Initialization
LoadViewStateView State Loading
LoadPostDataPostback Data Processing
Page_LoadPage Loading
RaisePostDataChangedEventPostBack Change Notification
RaisePostBackEventPostBack Event Handling
Page_PreRenderPage Pre Rendering Phase
SaveViewStateView State Saving
Page_RenderPage Rendering
Page_UnloadPage Unloading
The first processed method is Page_Init(). Once the control tree has been created, the controls declared in the .aspx file are initialized. The controls can modify some of the settings set in this method to be used later in the page life cycle. Obviously no other information is available to be modified at this time.
The next processed method is LoadViewState(). The Viewstate contains stored information that is set by the page and controls of the page. This is carried to and from every aspx page request per visitor.
The next processed method is LoadPostData(). These are values associated with the HTML form elements the visitor has typed, changed or selected. Now the control has access to this information which can update their stored information pulled from the Viewstate.
The next processed method is Page_Load(). This method should look familiar and is usually the most common used method on the server side application code for an .aspx file. All code inside of this method is executed once at the beginning of the page.
The next processed method is RaisePostDataChangedEvent(). When a visitor completes a form and presses the submit button, an event is triggered. This change in state signals the page to do something.
The next processed method is RaisePostBackEvent(). This method allows the page to know what event has been triggered and which method to call. If the visitor clicks Button1, then Button1_Click is usually called to perform its function.
The next processed method is Page_PreRender(). This method is the last chance for the Viewstate to be changed based on the PostBackEvent before the page is rendered.
The next processed method is SaveViewState(). This method saves the updated Viewstate to be processed on the next page. The final Viewstate is encoded to the _viewstate hidden field on the page during the page render.
The next processed method is Page_Render(). This method renders all of the application code to be outputted on the page. This action is done with the HtmlWriter object. Each control uses the render method and caches the HTML prior to outputting.
The last processed method is Page_Unload(). During this method, data can be released to free up resources on the server for other processes. Once this method is completed, the HTML is sent to the browser for client side processing.

Thursday, 20 November 2014

Getting current directory in .NET web application

The current directory is a system-level feature; it returns the directory that the server was launched from. It has nothing to do with the website.

You want HttpRuntime.AppDomainAppPath.

If you're in an HTTP request, you can also call Server.MapPath("~/Whatever").

Find current Location of user using Google API in Asp.net

<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>

Monday, 17 November 2014

Animation in AjaxModalPopup

<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server"
                             TargetControlID="ImageButton2" PopupControlID="Rate_Panel1"
                                  DropShadow="True" BackgroundCssClass="modalBackground"
                                 CancelControlID="cross2" >
                                  <Animations>
                                <OnShown>
                                <Fadein />
                                </OnShown>
                                <OnHiding>
                                <Fadeout />
                                </OnHiding>
                                </Animations>
                             </asp:ModalPopupExtender>

Wednesday, 12 November 2014

Show alert box before session expire

<script language="javascript" type="text/javascript">
       var sessionTimeoutWarning =
    "<%= System.Configuration.ConfigurationSettings.AppSettings
    ["SessionWarning"].ToString()%>";
        var sessionTimeout = "<%= Session.Timeout %>";

        var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
        setTimeout('SessionWarning()', sTimeout);

        function SessionWarning() {
var message = "Your session will expire in another " +
    (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning)) +
    " mins! Please Save the data before the session expires";
alert(message);
        }
</script>

Saturday, 1 November 2014

Export Gridview Data in Excel

  public void export_attendence()
    {
        string attachment = "attachment; filename=Student_attendence_Report.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }


<%@ Page Title="" Language="C#" MasterPageFile="~/vShksha.master" AutoEventWireup="true" CodeFile="expense_details.aspx.cs" Inherits="expense_details" EnableEventValidation="false"  %>

Thursday, 9 October 2014

Generate Date Time as a random no.

            int n1, s1 = 0;
            int z1 = 2;
            string m1 = "";
            string reverse1 = "";

            string i1 = System.DateTime.Now.ToShortDateString();               \\Current  Date
            string j1 = System.DateTime.Now.ToLongTimeString();                \\Current Time
            string[] a1 = i1.Split('-');
            int k1 = Convert.ToInt32(a1[0]);
            while (z1 != 0)
            {
                n1 = k1 % 10;
                m1 += (s1 * 10 + n1).ToString();
                k1 = k1 / 10;
                z1 = z1 - 1;
            }

            for (int eb = m1.Length - 1; eb > -1; eb--)                               \\ Find last 2 digit of the year
            {
                reverse1 += m1[eb];
            }
            string[] b1 = j1.Split(' ');
            string x01 = b1[0];
            string[] c01 = x01.Split(':');
            string ran = reverse1 + a1[1] + a1[2] + c01[0] + c01[1];
            string bno = "R" + ran;                                         \\ Add "R" in starting of the random no                                      

Ajax Modal Popup Example

Design Page
<div style="width:20px;float:right; position:fixed;">
                           <asp:ImageButton ID="ImageButton1" runat="server"
                               ImageUrl="~/Images/feedback1.png"  Height="120px" Width="25px" />
                           
    </div>    
Add ModalPopupExtender
  <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
                                 TargetControlID="ImageButton1" PopupControlID="panel_feedback"
                                  DropShadow="True" BackgroundCssClass="modalBackground"
                                 CancelControlID="cross1" / >
Design Panel
<asp:Panel ID="panel_feedback" runat="server"  >
                             <center>
                             <div class="form_enquiry"><div style="float:right"><asp:ImageButton ID="cross1" runat="server" ImageUrl="~/images/cross.jpg" Width="20px" Height="20px" /></div>
                          <center><h4>FEEDBACK </h4></center>  <div>

<table>
<tr>
    <td>
        <asp:Label ID="Label4" runat="server" Text="Name"></asp:Label>
    </td>
</tr>
   <tr>
        <td>
            <asp:TextBox ID="TextBox1" runat="server" Width="221px"></asp:TextBox>
       
        </td>
   </tr>
   <tr>
    <td>
        <asp:Label ID="Label1" runat="server" Text="Email"></asp:Label>
    </td>
</tr>
   <tr>
        <td>
            <asp:TextBox ID="TextBox2" runat="server" Width="222px"></asp:TextBox>
        </td>
   </tr>
<tr>
    <td>
        <asp:Label ID="Label2" runat="server" Text="Message"></asp:Label>
    </td>
</tr>
   <tr>
        <td>
            <asp:TextBox ID="TextBox3" runat="server" Height="44px" TextMode="MultiLine"
                Width="222px" MaxLength="499" />
        </td>  </tr><tr> <td></td>
        <td style="float:right;">
 <asp:Button ID="feedButton1" runat="server" Text="Submit" onclick="feedButton1_Click" />
        </td>
   </tr>
</table></div>     </div>  </center>  </asp:Panel>
Ajax Modal Popup

Wednesday, 8 October 2014

Add text in a Gridview using RowDatabound in ASP.NET using C#

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label l1 = (Label)e.Row.FindControl("Label5");
            if (!string.IsNullOrEmpty(l1.Text))
            {
                if (l1.Text != "300" && l1.Text != "450")
                {
                    e.Row.Cells[3].Text = "Rs. " + l1.Text + " per hour";
                    //e.Row[].Cells[3].Text = "Rs. " + l1.Text + " ";
                }
                else
                {
                    e.Row.Cells[3].Text = "Rs. " + l1.Text + " ";
                }
            }
        }
    }

Email Integration

 public void sendMail()
    {
        try
        {
            mailmsg = "Name - " + txtname.Text + "<br />Email - "+txtemail.Text+"<br />Mobile no. - " + txtmobileno.Text + "<br />" + "Message - " + txturreq.Text + "<br /><b>ABC Team</b>";
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("#####@gmail.com");
            mail.To.Add("customer1@gmail.com");
            mail.To.Add("customer2@gmail.com");
         
            mail.Subject = "Subject";
            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 = 25;
            smtpClient.EnableSsl = false;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("#####@gmail.com", "*********");
                       smtpClient.Send(mail);

        }
        catch (Exception ex)
        {
             Response.Write(ex);
        }
    }

SMS Integration in ASP.NET

HttpWebRequest myReq =(HttpWebRequest)WebRequest.Create("http://###.###.##.#/SendSMS/sendmsg.php?uname=*****&pass=*****&send=*****%20&dest=" + mobile_no. + "&msg=Dear " + "Mr./Mrs " + Name_of_user+ " Thanks! for Feedback !!! ");
             
                HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
                System.IO.StreamReader respStreamReader = new                                                                                  System.IO.StreamReader(myResp.GetResponseStream());
                string responseString = respStreamReader.ReadToEnd();
                respStreamReader.Close();
                myResp.Close();

Highlight values in Gridview using Rowdatabound in ASP.NET

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label chk1 = (Label)e.Row.FindControl("Label9");
            if (!string.IsNullOrEmpty(chk1.Text))
            {
                if (chk1.Text == "Approved")
                {
                    e.Row.Cells[9].ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    e.Row.Cells[9].ForeColor = System.Drawing.Color.Red;
                }
            }
        }
}


Friday, 19 September 2014

Alert box




Response.Write("<script>alert('your message') ; location.href='MainView.aspx?LineNumber=" + customer.LineNumber.ToString() + "&id=" + CustomerId.ToString()+ "'</script>")

Monday, 11 August 2014

Encrypt and decrypt the value or password.

// Encrypt and decrypt the value or password and save in database.



        con.Open();                        // connection open
        byte[] encData_byte = new byte[b.Length];                     // Encrypt the code and store in "b1" string variable
        encData_byte = System.Text.Encoding.UTF8.GetBytes(b);    // " b " is the value which you want to encrypt
        string b1 = Convert.ToBase64String(encData_byte);                  // Encrypted result

        System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();     // Encrypt the code and store in "b2" string 
        System.Text.Decoder utf8Decode = encoder.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(b1);       // " b1 " is the value which you want to decrypt
        int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        string b2= new String(decoded_char);           // Decrypted result
       
        string sq = "insert into testlogin values('" + a.ToString() + "','" + b.ToString() + "','" + b1.ToString() + "','" + b2.ToString() + "')";
        SqlCommand cmd = new SqlCommand(sq, con);
        cmd.ExecuteNonQuery();    // Execute the query

Thursday, 7 August 2014

Date Picker Calender

//  Date Picker Calender.

<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#firstdate" ).datepicker();
    $( "#lastdate" ).datepicker();
  });
  </script>

Saturday, 19 July 2014

SQL using GROUP BY .

 Table which is used for  GROUP BY :-




1.  select MIN(score) AS 'total' from test1 GROUP BY id



2.  select COUNT(score) AS 'total' from test1 GROUP BY id






3.  select SUM(score) AS 'total' from test1 GROUP BY id





4. select MAX(score) AS 'total' from test1 GROUP BY id

Friday, 18 July 2014

Sql Join query


Table name : - atim

Table name :- asignup

1.  select dat,name,email from atim a1 INNER JOIN asignup a2 ON a1.eid=a2.eid





2.  select atim.eid , asignup.name FROM atim FULL OUTER JOIN asignup ON atim.eid=asignup.eid




3.  select dat,name,email from atim a1 LEFT OUTER JOIN asignup a2 ON a1.eid=a2.eid





4.  select dat,name,email from atim a1 RIGHT OUTER JOIN asignup a2 ON a1.eid=a2.eid



5.  select dat,name,email from atim a1 FULL OUTER JOIN asignup a2 ON a1.eid=a2.eid


Sql query of create,check,Distinct and order by.


Check that Table is exist in current database or not.

SELECT * FROM "+x+" WHERE 1 = 0

Create new Table.

 "create table " + x + " (" + "name nvarchar(50)," + "gender nvarchar(50)," + "email nvarchar(50)," + "mobile nvarchar(50))";

 Check the person should be major using CHECK keyword.

create table test1
(
 name varchar(50) not null ,
 age int NOT NULL CHECK (age >=18)
)

Check condition using AND keyword.

select * from atim where eid='123' AND dtim ='00:00:27'

Check condition using OR keyword.

select * from atim where eid='123' OR dtim ='00:00:27'

Show data in Desecending order.

select * from atim ORDER BY eid desc

Show data in Asecending order.

select * from atim ORDER BY eid asec

Show data in case order (own order).

select * from atim ORDER BY (case eid when 123 then 1
when 321 then 2
 else 100 end )

Show data in unrepeated form.

 select DISTINCT eid from atim ORDER BY eid



Thursday, 10 July 2014

Change the colour of textbox Onclick event

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        .textbox
        {
            background-color:RED;
        }
       
        .textbox:focus
        {
            background-color: Silver;  
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
   <table>
 <tr>
        <td>
            <asp:TextBox ID="TextBox2" runat="server" Height="61px" TextMode="MultiLine"
                Width="160px" CssClass="textbox"></asp:TextBox>
        </td>
   <tr>
  </table>
    </form>
</body>
</html>

Wednesday, 9 July 2014

Pass the selected single row from gridview to another page.

// First page in which select the chekbox for passing value to another page .

protected void Gridvaluepass_Click(object sender, EventArgs e)
    {
        ArrayList selectedValues = new ArrayList();
        foreach (GridViewRow row in GridView1.Rows)
        {
            bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;      // finds the selected checkbox control
            if (result)
            {
                int categoryID = Convert.ToInt32(((Label)row.FindControl("Label10")).Text);        // find the selected row value control which is unique
                selectedValues.Add(categoryID);
            }
        }
        Session["SELECTEDVALUES"] = selectedValues;         // pass the selected value with the help of session
        Session["view"] = "view";
        Response.Redirect("complaint.aspx");
    }




// Second page which displays the selected value of previous page

  protected void Page_Load(object sender, EventArgs e)
    {

 if (Session["SELECTEDVALUES"] != null )                       // check that session is available or not

            {
                ArrayList selectedValues = (ArrayList)Session["SELECTEDVALUES"];

                foreach (int intValue in selectedValues)
                {
                    maincall(intValue);
                }
      }        
}
  public void maincall(int intValue)
    {
        con.Open();
        string s = " select cno,name,type,zone,ward,pno,lmark,mob,ticket,tstatus from complaint1 where id='"+intValue.ToString()+"' ";
        SqlDataAdapter da=new SqlDataAdapter(s,con);
        DataSet ds=new DataSet();
        da.Fill(ds);
        TextBox1.Text=ds.Tables[0].Rows[0]["cno"].ToString();
        TextBox2.Text=ds.Tables[0].Rows[0]["name"].ToString();
        TextBox8.Text = ds.Tables[0].Rows[0]["mob"].ToString();
        TextBox9.Text = ds.Tables[0].Rows[0]["ticket"].ToString();
        DropDownList1.SelectedItem.Text = ds.Tables[0].Rows[0]["tstatus"].ToString();
        DropDownList2.SelectedItem.Text = ds.Tables[0].Rows[0]["zone"].ToString();
        DropDownList3.SelectedItem.Text = ds.Tables[0].Rows[0]["ward"].ToString();
        DropDownList4.SelectedItem.Text = ds.Tables[0].Rows[0]["type"].ToString();
        con.Close();
    }
           

Show city name in dropdownlist after selecting the country name.

 Database for fetching city name



 protected void Page_Load(object sender, EventArgs e)
    {
        drop2();
        drop();


    }

 public void drop2()
    {
        if (DropDownList4.SelectedItem.Text == "--Selectcountry--")
        {
            DropDownList5.Enabled = false;
            DropDownList5.SelectedValue = null;
        }
        else
            DropDownList5.Enabled = true;

    }

Autopost enabled in Dropdownlist of country 

 public void drop()
    {
        con.Open();
        string s = "select ward from country where cont='" + DropDownList4.SelectedValue.ToString() + "'";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader dr = cmd.ExecuteReader();
        DropDownList5.DataSource = dr;
        DropDownList5.DataTextField = "city";
        DropDownList5.DataValueField = "city";
        DropDownList5.DataBind();
        con.Close();
    }

Export Gridview data in Excel sheet.

  protected void Excel_exportButon_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
           // GridView1.AutoGenerateColumns = false;
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            GridView1.AllowPaging = false;
            this.search();

            GridView1.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in GridView1.HeaderRow.Cells)
            {
                cell.BackColor = GridView1.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in GridView1.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = GridView1.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            GridView1.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
   

Monday, 30 June 2014

Method Overloading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public class Program : abc              \\Main class
    {
        public static void Main(string[] args)
        {
            System.Console.WriteLine("I m main class");
            abc x = new abc();
            x.add(7, 9);
            x.add("hello ", "world");
        }
    }
    public class abc                                   \\ inheritted class for Method overloading
    {
        public void add(int a, int b)
        {
            int c = a + b;
            System.Console.WriteLine(c);
        }
        public void add(string a, string b)         \\ Overloaded method(add())
        {
            string c = a + b;
            System.Console.WriteLine(c);
        }
    }
 

Multi Level Inheritance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class xyz                                             \\ First class
{
    public void demo()
    {
        System.Console.WriteLine("First class");
    }

}
public class abc : xyz                                       \\ second class which inherit the first class
{
    public void demo()
    {
        System.Console.WriteLine("Second class abc");
    }
}
        public class Program:abc                              \\ Main class
        {
        public static void Main(string []args)
        {
            System.Console.WriteLine("I m main class");
            abc k = new abc();                                   \\ creating object
            k.demo();
            xyz p = new xyz();
            p.demo();
        }
        }
     

Single Inheritance

\\ Namespace
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

        public class Program : abc     \\ Main Class
        {
        public static void Main(string []args)       \\ Main Function
        {
            System.Console.WriteLine("I m main class");
            Program x = new Program();
            x.demo();
            abc k = new abc();                           \\ creating object of inherited class
            k.demo();
        }
        public void demo()                                \\Function in class
        {
            System.Console.WriteLine("function in main class");
        }
        }
        public class abc                                        \\base class or inherited class
        {
            public void demo()
            {
                System.Console.WriteLine("class abc");
            }
        }

Sunday, 29 June 2014

Check the IP Address is valid or not.

// First we add Namespaces
 
using System.Data;
using System.Net;


protected void Button5_Click(object sender, EventArgs e)
{
        try
        {
            IPAddress address = IPAddress.Parse(TextBox1.Text);        //Check the IP address is Valid or Not
            Reponse.Write(" Valid IP address ");
        }
        catch(Exception ex)
        {
            Response.Write("incorrect IP address");
        }
}