Tuesday, 25 December 2012

Remove all HTML tag in c#


Suppose  label named lblDescription have html tags. We can remove all html tags as following.

Input Data: <p>Test</p>

Output Data:  Test  ( No <p> tag )

 lblDescription.Text="<p>Test</p>"
string result = Regex.Replace(lblDescription.Text, @"<(.|\n)*?>", string.Empty);
 lblDescription.Text  = result.Trim();

Sunday, 16 December 2012

Regular expression for textbox accepting only alphabet and spaces only

Regular expression for textbox accepting only alphabet and spaces only:

^([a-zA-Z]+(_[a-zA-Z]+)*)(\s([a-zA-Z]+(_[a-zA-Z]+)*))*$

Wednesday, 12 December 2012

Count specific character occurances in string withou looping

To find the occurance of particular character without looping:

String TestString = "12345678901234567890";
Int32 Count = (TestString).Length - (TestString.Replace("9", "")).Length;


Above i want to find the occurance of "9"

Wednesday, 5 December 2012

Javascript code to get latitude and longitude for address

 Javascript code to get latitude and longitude for address

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">

        var geocoder = new google.maps.Geocoder();
        var address = "New York";

        geocoder.geocode({ 'address': address }, function(results, status) {

            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                alert(latitude);
                alert(longitude);
            }
        });

   </script>

Function to return multiple values in SQL SERVER

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Function with input parameter and it will return table parameter(only one as function return only one parameter in this case it is table type)

Create FUNCTION MyTestFunction
(
@DataBaseTableColumn3 int
)
RETURNS @Dummytable TABLE
(
    MyColumn1 nvarchar(max),
    MyColumn2 nvarchar(max)
)
AS
Begin
    insert into @Dummytable(MyColumn1,MyColumn2)SELECT top 1 DataBaseTableColumn1,DataBaseTableColumn2 FROM DatabaseTable where DataBaseTableColumn3=@DataBaseTableColumn3
    RETURN
End

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Function without input parameter and it will return table parameter(only one as function return only one parameter in this case it is table type)

Create FUNCTION MyTestFunction
(

)
RETURNS @Dummytable TABLE
(
    MyColumn1 nvarchar(max),
    MyColumn2 nvarchar(max)
)
AS
Begin
    insert into @Dummytable(MyColumn1,MyColumn2)SELECT top 1 DataBaseTableColumn1,DataBaseTableColumn2 FROM DatabaseTable
    RETURN
End

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Monday, 3 December 2012

How To Use Text Over Images with HTML

<IMG SRC="newjoe03.jpg">
<DIV STYLE="position:absolute; top:250px; left:20px; width:200px; height:25px">
<CENTER><FONT SIZE="+2" COLOR="00ff00">Looking Into The Future</FONT></CENTER>
</DIV>



Use the link: http://www.htmlgoodies.com/tutorials/web_graphics/article.php/3480021/Text-Over-Images.htm

Thursday, 29 November 2012

Four square venus api

Method 1:

 <form id="NewForm2" action="https://api.foursquare.com/v2/venues/search" method="Get">
     <input type="input" name="ll" value="44.3,37.2" />
    <input type="input" name="near" value="Chicago, IL" />
    <input type="input" name="oauth_token" value="Your token" />
      <input type="submit" value="Buy!"  />
 </form>

when you click Buy button it will return a json file.


Method 2:

Down Load
   Newtonsoft.Json.Compact.dll
   Newtonsoft.Json.Net35.dll.refresh
   Newtonsoft.Json.Net35.pdb
   Newtonsoft.Json.Net35.xml

Put all above files in bin folder.

Write the below code on a page:

using System;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Data;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web.Services;
using System.Net;
using System.Drawing;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Xml;

public partial class Default4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string url = "https://api.foursquare.com/v2/venues/search?"; //The authorization url
        string fullUrl = url + "oauth_token=yourtoken&ll=44.3,37.2&near=Chicago, IL";
        WebClient  wc = new WebClient();
        string JsonPersonalDet = wc.DownloadString(fullUrl);
        
    // converting json to xml (deserialization)
        XmlDocument xd = new XmlDocument();
        xd = (XmlDocument)JsonConvert.DeserializeXmlNode(JsonPersonalDet.ToString(), "jsonData");
        DataSet ds = new DataSet();
        ds.ReadXml(new XmlNodeReader(xd));
    }
     
}


Thursday, 8 November 2012

Clear cache of browser / PageLoad event is not working when refresh (do not find break point)

Problem due to browser cache.

Solution: Write below code in code file on page load event.

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Close window without prompt

Code for aspx file

Give id to the body tag and make it runat= server.
<body id="Body" runat ="server" >

Code for aspx.cs file

Body.Attributes.Add("onload", "javascript:window.open('','_self','');window.close();");

FilteredTextBoxExtender

<ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtenderPhone" runat="server"
TargetControlID="txtPhone" ValidChars="1234567890-()" />

Friday, 26 October 2012

AutoComplete Extender with Web Service

Use below link, and DOWNLOADS: Code (C#)

http://www.asp.net/web-forms/videos/ajax-control-toolkit/how-do-i-use-the-aspnet-ajax-autocomplete-control

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Step 1: Make a Web service:named as AutoComplete.asmx

public string[] GetCompletionList(string prefixText, int count)
    {
      
        SqlConnection con = new SqlConnection("Connection String from web config");
        SqlDataAdapter dad = new SqlDataAdapter("SELECT column1 from table where column2 like '" + prefixText + "%'", con);

     
        DataSet ds = new DataSet();
        dad.Fill(ds);
        List<string> list = new List<string>(ds.Tables[0].Rows.Count);
        //string[] list = new string[ds.Tables[0].Rows.Count];

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            list.Add(dr[0].ToString());
            //list.SetValue(dr[0].ToString(), i);

        }
        return list.ToArray();
    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Step2: Add reference to your default page:

<asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
        <asp:ServiceReference Path="AutoComplete.asmx" />
        </Services>
        </asp:ScriptManager>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Step 3: Add Ajax tol kit ( AjaxControlToolkit.dll ) to bin folder and register it
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Step 4: Add AutoCompleteExtender

<div>           
            <asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
            <ajaxToolkit:AutoCompleteExtender
                runat="server"
                ID="autoComplete1"
                TargetControlID="myTextBox"
                ServicePath="AutoComplete.asmx"
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="2"
                CompletionInterval="1000"
                EnableCaching="true"
                CompletionSetCount="12" />
    </div>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Thursday, 25 October 2012

Rediect to another aspx page after few seconds

Code file code:

Response.AddHeader("REFRESH", "5;URL=yourpage.aspx");

SQL SERVER – How to Rename a Column Name or Table Name

The script for renaming any column :
sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'
The script for renaming any object (table, sp etc) :
sp_RENAME '[OldTableName]' , '[NewTableName]'

Tuesday, 23 October 2012

Jquery Pop up

<style type="text/css">
/* popup_box DIV-Styles*/
#popup_box {
    display:none; /* Hide the DIV */
    position:fixed; 
    _position:absolute; /* hack for internet explorer 6 */ 
    height:150px; 
    width:500px; 
    background:#FFFFFF; 
    left: 400px;
    top: 150px;
    z-index:100; /* Layering ( on-top of others), if you have lots of layers: I just maximized, you can change it yourself */
    margin-left: 15px; 
   
    /* additional features, can be omitted */
    border:2px solid #ff0000;     
    padding:15px; 
    font-size:15px; 
    -moz-box-shadow: 0 0 5px #ff0000;
    -webkit-box-shadow: 0 0 5px #ff0000;
    box-shadow: 0 0 5px #ff0000;
   
}

#container {
    background: #d2d2d2; /*Sample*/
    width:100%;
    height:100%;
}

a{ 
cursor: pointer; 
text-decoration:none; 
}

/* This is for the positioning of the Close Link */
#popupBoxClose {
    font-size:20px; 
    line-height:15px; 
    right:5px; 
    top:5px; 
    position:absolute; 
    color:#6fa5e2; 
    font-weight:500;     
}
</style>



<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript"></script>

<script type="text/javascript">

    $(document).ready(function() {

        // When site loaded, load the Popupbox First
        $('#a_CancelPayment').click(function() {
            loadPopupBox();
        });

        $('#popupBoxClose').click(function() {
            unloadPopupBox();
        });



        function unloadPopupBox() {    // TO Unload the Popupbox
            $('#popup_box').fadeOut("slow");
            $("#wrapper").css({ // this is just for style       
                "opacity": "1"
            });
        }

        function loadPopupBox() {    // To Load the Popupbox
            $('#popup_box').fadeIn("slow");
            $("#wrapper").css({ // this is just for style
                "opacity": "0.3"
            });
        }
        /**********************************************************/

    });
</script>


Put the below code in form tag in your body....
  <div id="popup_box">    <!-- OUR PopupBox DIV-->
    <table style="width :100%;">
 
    <tr ><td style="width :15%;"></td>
    <td align="center" style="width :70%;">
    <table>
    <tr style="height:100px;">
    <td align="center">Do you really want to cancel your recurring payments?</td>
    </tr>
    <tr><td align="center"><asp:Button ID="btn_ConfirmCancelPayment" runat="server" Text ="Confirm" OnClick ="btn_ConfirmCancelPayment_Click" />
    <asp:Button ID="btn_CancelPayment" runat="server" Text ="Cancel" OnClick ="btn_CancelPayment_Click"/></td></tr>
    <tr></tr>
    </table>
   
   
    </td><td style="width :15%;"></td>
    </tr>
    </table>
   
    <a id="popupBoxClose">Close</a>   
</div>

Wednesday, 20 June 2012

insert directly from application to database

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

try

{

    using (SqlConnection connect = new SqlConnection(connectionString))

    {

        SqlCommand command = new SqlCommand();

        command.Connection = connect;

        command.CommandText = "insert into customer(name, address) values(@name, @address)";

        command.Parameters.Add(new SqlParameter("@name", SqlDbType.VarChar));

        command.Parameters.Add(new SqlParameter("@address", SqlDbType.VarChar));

        command.Parameters["@name"].Value = name.Text.ToLower();

        command.Parameters["@address"].Value = address.Text.ToLower();

        connect.Open();

    }

}

Friday, 17 February 2012

Simplest Way of Sending Email from Gmail

Simplest Way of Sending Email from Gmail

protected void btnSendEmail_Click(object sender, EventArgs e)
{
//Create Mail Message Object with content that you want to send with mail.System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("dotnetguts@gmail.com","myfriend@yahoo.com",
"This is the mail subject", "Just wanted to say Hello");

MyMailMessage.IsBodyHtml = false;

//Proper Authentication Details need to be passed when sending email from gmail
System.Net.NetworkCredential mailAuthentication = new
System.Net.NetworkCredential("dotnetguts@gmail.com", "myPassword");

//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);

//Enable SSLmailClient.EnableSsl = true;

mailClient.UseDefaultCredentials = false;

mailClient.Credentials = mailAuthentication;

mailClient.Send(MyMailMessage);
}

XML

Why is XML DOM?
XML is a standard by which two incompatible system can communicate. XML DOM works with XML data in your application. It is used to read, write and modify XML document programatically.


Understanding Nodes in XML Document

Node type
Description
Root
This node type is the container for all the nodes and is also known as the document root.
Element
This node type represents element nodes.
Attribute
This node type represents the attributes of an element node.
Text
This node type represents the text that belongs to a particular node or to an attribute.


Example of XML Document, employee.xml<?xml version="1.0" encoding="utf-8" ?>
<employees>
<employee>
<FirstName>Ajay</FirstName>
<LastName>Thakur</LastName>
<DateOfBirth>08/09/1968</DateOfBirth>
<DateOfJoining>04/01/1992</DateOfJoining>
<Address>2010 Stanley Dr., Charlotte, NJ 08830</Address>
<Basic>2100</Basic>
<Designation>HR Manager</Designation>
<LeaveBalance>12</LeaveBalance>
</employee>
<employee>
<FirstName>Ganesh</FirstName>
<LastName>Patil</LastName>
<DateOfBirth>01/12/1972</DateOfBirth>
<DateOfJoining>06/01/2000</DateOfJoining>
<Address>7862 Freepoint Pkwy, Tampa, NJ 08820</Address>
<Basic>1400</Basic>
<Designation>Software Professional</Designation>
<LeaveBalance>4</LeaveBalance>
</employee>
</employees>


Understanding XML Document
  • Every XML Document contains a single root element that contains all other nodes of the XML Document. Here <employees> is a root element.
  • XML Element is a Record which contains information. Here <employee>
  • XML Element Attribute further describe the Record details. Here <FirstName> etc are XML Element Attributes.

What is XML Document Object?
XMLDocument provides an in-memory representation of and XML document.

Example of XML DocumentCreate a Asp.net Website
Create a XML Document and name it employee.xml

Loading of XML DocumentYou can load xml document using XMLDocument object's load method

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
XmlDocument EmpXMLDoc = new XmlDocument();
string XMLDocPath = Server.MapPath("Employee.xml");
EmpXMLDoc.Load(XMLDocPath);
Response.Write(EmpXMLDoc.InnerText.ToString());
}
}


Saving XML Document
You can save XML Document with XMLDocument.Save method
Example: XMLDocument.Save("Employee.xml");


Read XML Document and display on WebPage
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
XmlDocument EmpXMLDoc = new XmlDocument();
string XMLDocPath = Server.MapPath("Employee.xml");
EmpXMLDoc.Load(XMLDocPath);

//Read XML Document //Note: Begin for ChildNode[1] foreach (XmlNode node1 in EmpXMLDoc.ChildNodes[1])
{
foreach (XmlNode node2 in node1.ChildNodes)
{
Response.Write("<b>" + node2.Name + "</b>: " + node2.InnerText + " ");
}
Response.Write("<br>");
}
}
}

//Output