how to Create RSS feed Using Asp.net | RSS Feed Sample using asp.net

Posted by imomins on October 8, 2012 at 12:25 AM Comments comments (1)
Introduction:

Here I will explain how to create RSS feed using asp.net.

Description:

RSS stands for "Really Simple Syndication". RSS solves a problem for people who regularly use the web. It allows you to easily stay informed by retrieving the latest content from the sites you are interested in. You save time by not needing to visit each site individually.

To implement RSS feed concept using asp.net just follow below steps
Step 1: Create Table In tblRss SQl Server as below. 

ColumnName
DataType
ID
int
Title
varchar(50)
Description
varchar(50)
Url
Varchar(50)
Step 2: Insert the Data In to the tblRss some Dummy data Url must be related Rss Link just like this

ID
Title
Description
Url
1
Test
testing
http://aspdotnet-suresh.com
2
aspdotnet
aspdotnet-suresh
http://aspdotnet-suresh.com
Step 3: In Default.aspx page add these 2 lines of code.     

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="120" VaryByParam="*" %>

Step4: In code behind


using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class GridviewEditUpdate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=MYCBJ017550027;Initial Catalog=MySamplesDB;Integrated Security=True";
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * from tblRSS", conn);
ad.Fill(dt);
}

Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter TextWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
TextWriter.WriteStartDocument();
//Below tags are mandatory rss
TextWriter.WriteStartElement("rss");
TextWriter.WriteAttributeString("version", "2.0");
// Channel tag will contain RSS feed details
TextWriter.WriteStartElement("channel");
TextWriter.WriteElementString("title", "C#.NET,ASP.NET Samples and Tutorials");
TextWriter.WriteElementString("link", "http://aspdotnet-suresh.blogspot.com");
TextWriter.WriteElementString("description", "Free ASP.NET articles,C#.NET,ASP.NET tutorials and Examples,Ajax,SQL Server,Javascript,XML,GridView Articles and code examples -- by Suresh Dasari");
TextWriter.WriteElementString("copyright", "Copyright 2009 - 2010 aspdontnet-suresh.blogspot.com. All rights reserved.");
foreach (DataRow oFeedItem in dt.Rows)
{
TextWriter.WriteStartElement("item");
TextWriter.WriteElementString("title", oFeedItem["Title"].ToString());
TextWriter.WriteElementString("description", oFeedItem["Description"].ToString());
TextWriter.WriteElementString("link", oFeedItem["URL"].ToString());
TextWriter.WriteEndElement();
}
TextWriter.WriteEndElement();
TextWriter.WriteEndElement();
TextWriter.WriteEndDocument();
TextWriter.Flush();
TextWriter.Close();
Response.End();
}
}
     
Demo




RichTextbox example or sample in asp.net or how to insert or store richtextbox data into database and display richtextbox data from database in gridview using asp.net

Posted by imomins on October 8, 2012 at 12:20 AM Comments comments (0)
Introduction

Here I will explain how to use richtextbox and how we can save our richtextbox data in database and how we can retrieve and display saved richtextbox data into our application using asp.net.

Description:
  
Today I am writing this post to explain about freely available richtextbox.  I found one free available richtextbox. We can validate and we can use richtextbox very easily and by using this richtextbox we can insert data in different formats like bold, italic and different color format texts and we can insert images also. To use free Richtextbox download available dll here FreeTextbox . After download dll from that site create one new website in visual studio and add FreeTextbox dll reference to newly created website after that design aspx page like this 

After that Design your aspx page like this 


<%@ Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Richtextbox Sample</title>
<script type="text/javascript">
function validate() {
var doc = document.getElementById('FreeTextBox1');
if (doc.value.length == 0) {
alert('Please Enter data in Richtextbox');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
<FTB:FreeTextBox ID="FreeTextBox1" runat="server">
</FTB:FreeTextBox>
</td>
<td valign="top">
<asp:GridView runat="server" ID="gvdetails" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="RichtextBoxData">
<ItemTemplate>
<asp:Label ID="lbltxt" runat="server" Text='<%#Bind("RichtextData") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="return validate()"
Text="Submit" onclick="btnSubmit_Click" /><br />
<asp:Label ID="lbltxt" runat="server"/>
</form>
</body>
</html>
After that run your application richtextbox appears like this 


Now our richtextbox is ready do you know how we can save richtextbox data into database and which datatype is used to save richtextbox data and do you know how to display richtextbox on our web page no problem we can implement it now.

To save richtextbox data we need to use datatype nvarchar(MAX) now Design table like this in your SQL Server database and give name as RichTextBoxData

Column Name
Data Type
Allow Nulls
Id
Int(Set Identity=true)
No
RichTextData
nvarchar(MAX)
Yes
After that add following namespaces in code behind

using System.Data;
using System.Data.SqlClient;
Now write the following code in code behind 


SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select RichTextData from RichTextBoxData", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("insert into RichTextBoxData(RichTextData) values(@Richtextbox)", con);
cmd.Parameters.AddWithValue("@Richtextbox", FreeTextBox1.Text);
cmd.ExecuteNonQuery();
con.Close();
FreeTextBox1.Text = "";
BindGridview();
}
Demo


Download sample code attached

jQuery Enable or Disable Textbox Controls on WebPage in Asp.net

Posted by imomins on October 7, 2012 at 2:55 PM Comments comments (0)
Introduction

Here I will explain how to enable or disable textboxes on a page focus using
JQuery in asp.net.

Description:
  
In previous articles I explained Enable/Disable all controls on webpage, enable/disable particular controls on page using
JQuery in asp.net and another article Enable/disable button using JavaScript and many articles relating to JQuery and JavaScript. Now I will explain how to enable or disable textboxes on a page focus using JQuery in asp.net.

To implement this one we need to write code as shown below in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Disable or Enable textbox Controls on a Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnEnableDisable").toggle(function() {
$("input:text").attr("disabled", "disabled");
$(this).attr("disabled", "");
}, function() {
$("input:text").attr("disabled", "");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>Name:</b></td>
<td><asp:TextBox ID="txtName" runat="server"/></td>
</tr>
<tr>
<td><b>First name:</b></td>
<td><asp:TextBox ID="txtfname" runat="server"/></td>
</tr>
<tr>
<td><b>Last name: </b></td>
<td><asp:TextBox ID="txtlname" runat="server"/></td>
</tr>
<tr>
<td><b>Location: </b></td>
<td><asp:TextBox ID="txtlocation" runat="server"/></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnEnableDisable" runat="server" Text="Enable/Disable" /></td>
</tr>
</table>
</form>
</body>
</html>

If you observe above code in header section I added script file link by using that file we have a chance to interact with JQuery and in the script we have btnEnableDisable button toggle function like

<script type="text/javascript">
$(document).ready(function() {
$("#btnEnableDisable").toggle(function() {
$("input:text").attr("disabled", "disabled");
$(this).attr("disabled", "");
}, function() {
$("input:text").attr("disabled", "");
});
});
</script>
Here whenever we click on button it will disable or enable all textbox controls on page

Demo

If you want to enable or disable particular controls check this article Enable/Disable particular controls on page using jQuery

jQuery fadein fadeout fadeto Effects div Example in Asp.net

Posted by imomins on October 7, 2012 at 2:50 PM Comments comments (0)
Introduction

Here I will explain how to implement simple div with fadein fadeout, fadeto effects using
JQuery in asp.net.

Description:
  
In previous posts I explained
Draggable and Resizable example, split the string, add fade in effect to page, Password strength jquery plugin examples and many articles relating to JQuery. Now I will explain how implement simple div with fadein fadeout, fadeto effects in JQuery.

To implement fadein fadeout, fadeto effects div in JavaScript we need to write much code but in JQuery we can achieve this functionality just by simple properties fadein, fadeout and fadeto that would be like as shown below


<script type="text/javascript">
$(document).ready(function() {
$('#fadeindiv').fadeIn('slow');
$('#fadeoutdiv').fadeOut('slow');
$('#fadetodiv').fadeTo('slow', 0.2);
});
</script>
OR


<script type="text/javascript">
$(document).ready(function() {
$('#fadeindiv').fadeIn(2000); 
$('#fadeoutdiv').fadeOut(2000); 
$('#fadetodiv').fadeTo(2000, 0.2); 
});
</script>
If you observe above script I used one div with fadeIn, Second div with fadeout and another div with fadeTo properties.

fadein():  This method display the matched elements with fade in effect

fadeOut(): This method hide the matched elements with fade out or transparent effect

fadeTo(): This method fades the matched elements with opacity. In this we can set the opacity between 0 and 1 (If you observe above fadeTo method I mentioned 0.2)

If you want check this code in sample check below code

Example:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>JQuery fadein fadeout and fadeTo effects for div example</title>
<style type="text/css">
.fadediv{
width: 150px; height: 50px; padding: 0.5em;background:#EB5E00;color:#fff;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>

</head>
<body>
<form id="form1" runat="server">
<h2> jQuery fadeIn, fadeOut and fadeTo effects for div Example</h2>

<table>
<tr>
<td>
<div id="fadeindiv" class="fadediv">
<b>Click me - fadeIn()</b>
</div>
</td>
<td>

<div id="fadetodiv"  class="fadediv">
<b>Click me - fadeTo()</b>
</div>
</td>
<td>

<div id="fadeoutdiv"  class="fadediv">
<b>Click me - fadeOut()</b>
</div>
</td>
</tr>
<tr>
<td colspan="3"><button id="btnReset">Reset</button></td>
</tr>
</table>

<script type="text/javascript">
// Applying fadein effect
$("#fadeindiv").click(function() {
$(this).hide().fadeIn('slow');
});
// Applying fadeout effect
$("#fadeoutdiv").click(function() {
$(this).fadeOut('slow');
});
// Applying fadeto effect
$("#fadetodiv").click(function() {
$(this).fadeTo('slow', 0.2);
});
// Reset the div's
$('#btnReset').click(function() {
$('#fadeindiv').fadeIn('slow');
$("#fadeoutdiv").fadeIn('slow');
$("#fadetodiv").fadeIn('slow');
})
</script>
</form>
</body>
</html>

Live Demo

To check Live demo click on below div’s

jQuery fadeIn, fadeOut and fadeTo effects for div Example

Click me - fadeIn()
Click me - fadeTo()
Click me - fadeOut()
Reset
.fadediv{ width: 150px; height: 50px; padding: 0.5em;background:#EB5E00;color:#fff; } // Applying fadein effect $("#fadeindiv").click(function() { $(this).hide().fadeIn('slow'); }); // Applying fadeout effect $("#fadeoutdiv").click(function() { $(this).fadeOut('slow'); }); // Applying fadeto effect $("#fadetodiv").click(function() { $(this).fadeTo('slow', 0.2); }); // Reset the div's $('#btnReset').click(function() { $('#fadeindiv').fadeIn('slow'); $("#fadeoutdiv").fadeIn('slow'); $("#fadetodiv").fadeTo('slow', 1); })


WPF (Windows Presentation Foundation) in .NET

Posted by imomins on October 7, 2012 at 4:55 AM Comments comments (0)
Windows Presentation Foundation (WPF)
The Windows Presentation Foundation is Microsoft’s next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.
WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.



Separation of Appearance and Behavior
WPF separates the appearance of a user interface from its behavior. The appearance is generally specified in the Extensible Application Markup Language (XAML), the behavior is implemented in a managed programming language like C# or Visual Basic. The two parts are tied together by data binding, events and commands. The separation of appearance and behavior brings the following benefits:

  • Appearance and behavior are loosely coupled
  • Designers and developers can work on separate models.
  • Graphical design tools can work on simple XML documents instead of parsing code.
Rich composition
Controls in WPF are extremely composable. You can define almost any type of controls as content of another. Although this flexibility sounds horrible to designers, it’s a very powerful feature if you use it appropriate. Put an image into a button to create an image button, or put a list of videos into a combo box to choose a video file.






 <Button>

    <StackPanel Orientation="Horizontal">

        <Image Source="speaker.png" Stretch="Uniform"/>

        <TextBlock Text="Play Sound" />

    </StackPanel>

</Button>
 Highly customizable
Because of the strict separation of appearance and behavior you can easily change the look of a control. The concept of styles let you skin controls almost like CSS in HTML. Templates let you replace the entire appearance of a control.
The following example shows a default WPF button and a customized button.

Resolution independence
All measures in WPF are logical units - not pixels. A logical unit is a 1/96 of an inch. If you increase the resolution of your screen, the user interface stays the same size - if just gets crispier. Since WPF builds on a vector based rendering engine it's incredibly easy to build scalable user interfaces.

 


Introduction to XAML

XAML stands for Extensible Application Markup Language. It’s a simple language based on XML to create and initialize .NET objects with hierarchical relations. Although it was originally invented for WPF it can be used to create any kind of object trees.
Today XAML is used to create user interfaces in WPF, Silver light, declare workflows in WF and for electronic paper in the XPS standard.

Advantages of XAML

All you can do in XAML can also be done in code. XAML is just another way to create and initialize objects. You can use WPF without using XAML. It's up to you if you want to declare it in XAML or write it in code. Declare your UI in XAML has some advantages:

  • XAML code is short and clear to read
  • Separation of designer code and logic
  • Graphical design tools like Expression Blend require XAML as source.
  • The separation of XAML and UI logic allows it to clearly separate the roles of designer and developer.

XAML vs. Code

As an example we build a simple StackPanel with a textblock and a button in XAML and compare it to the same code in C#.

 

<StackPanel>

    <TextBlock Margin="20">Welcome to the World of XAML</TextBlock>

    <Button Margin="10" HorizontalAlignment="Right">OK</Button>

</StackPanel>

 

 
The same expressed in C# will look like this:

 

// Create the StackPanel

StackPanel stackPanel = new StackPanel();

this.Content = stackPanel;

 

// Create the TextBlock

TextBlock textBlock = new TextBlock();

textBlock.Margin = new Thickness(10);

textBlock.Text = "Welcome to the World of XAML";

stackPanel.Children.Add (textBlock);

 

// Create the Button

Button button = new Button ();

button.Margin= new Thickness (20);

button.Content = "OK";

stackPanel.Children.Add(button);

 

 
As you can see is the XAML version much shorter and clearer to read. And that's the power of XAMLs expressiveness.

 

Properties as Elements

Properties are normally written inline as known from XML <Button Content="OK" />. But what if we want to put a more complex object as content like an image that has properties itself or maybe a whole grid panel? .To do that we can use the property element syntax. This allows us to extract the property as an own child element.

 

<Button>

  <Button.Content>

     <Image Source="Images/OK.png" Width="50" Height="50" />

  </Button.Content>

</Button>

 

 

Implicit Type conversion

A very powerful construct of WPF are implicit type converters. They do their work silently in the background. When you declare a Border Brush, the word "Blue" is only a string. The implicit Brush Converter makes a System.Windows.Media.Brushes.Blue out of it. The same regards to the border thickness that is being converted implicit into a Thickness object. WPF includes a lot of type converters for built-in classes, but you can also write type converters for your own classes.

 

JQuery UI autocomplete textbox with database in asp.net

Posted by imomins on October 7, 2012 at 4:20 AM Comments comments (0)
Introduction:

In this article I will explain how to implement Asp.net autocomplete textbox with database using JQuery.


Description:
  
In previous articles I explained Ajax autocomplete extender example and JQuery autocomplete textbox with images in asp.net. Now I will explain another article relating to autocomplete textbox with JQuery UI in asp.net.
To implement this concept first we need to design table in database to save user details in database.

Column Name
Data Type
Allow Nulls
UserId
int(set identity property=true)
No
UserName
varchar(50)
Yes
Location
nvarchar(max)
Yes
After completion table design enter some of user details in database to work for our sample.
Write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script and css files by using those files we have a chance to display auto complete text with css style. To get those files just add those urls in in your application.

Another thing here we need to know is script function in header section

$(".autosuggest").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
}
});
This is the function declaration of JSON format we are using this JSON function to call web methods using JQuery $.ajax() whenever we need to make Ajax call with JQuery then we will use JSON functions like as we mentioned in above format. Here type, ContentType and dataType are same for all functions only url, data and success functions will vary based on our requirement.

url: This is the path of our Webmethods

data: we will pass parameters using this parameter if no parameters then we need to use data: "{}"

success: Once our web method execution completed then success function will execute and return username matching’s

(Note: JSON is a case sensitive please be careful before write JSON format of data)

Now open code behind file and add following namespaces


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
After that write the following code

C#.NET Code

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]

public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'[email protected]+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
VB.NET Code:


Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services

Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

End Sub

<WebMethod()> _
Public Shared Function GetAutoCompleteData(ByVal username As String) As List(Of String)
Dim result As New List(Of String)()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'[email protected]+'%'", con)
con.Open()
cmd.Parameters.AddWithValue("@SearchText", username)
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
result.Add(dr("UserName").ToString())
End While
Return result
End Using
End Using
End Function
End Class
Now run your application and check the output that would be like this   



Download sample code attached

 

Jquery autocomplete textbox with multiple words separated by comma or semicolon in asp.net

Posted by imomins on October 7, 2012 at 4:15 AM Comments comments (0)
Introduction:

In this article I will explain how to implement JQuery UI autocomplete textbox with multiple words or values with comma separated or semi colon separated in asp.net.
Description:

In previous articles I explained JQuery autocomplete textbox with asp.net and
JQuery autocomplete textbox with images in asp.net and many articles relating to JQuery. Now I will explain how to implement autocomplete textbox with multiple word selection in asp.net.
To implement this concept first we need to design table in database to save user details in database.

Column Name
Data Type
Allow Nulls
UserId
int(set identity property=true)
No
UserName
varchar(50)
Yes
Location
nvarchar(max)
Yes
After completion table design enter some of user details in database to work for our sample.
Write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>AutoComplete Box with jQuery</title>
<link href="css/ui-lightness/jquery-ui-1.8.21.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script> 
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtSearch").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<asp:TextBox ID="txtSearch" runat="server" Width="300px"></asp:TextBox>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script and css files by using those files we have a chance to implement autocomplete textbox with multiple values selection in asp.net. To get those files download attached folder and add the urls mentioned in header section to your application

Another thing here we need to know is script functions in header section

$("#txtSearch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
This is the function declaration of JSON format we are using this JSON function to call web methods using JQuery $.ajax() whenever we need to make Ajax call with JQuery then we will use JSON functions like as we mentioned in above format. If you want to know more about it check these posts call pagemethods with JSON and autocomplete textbox with Jquery.

Now open code behind file and add following namespaces


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
After that write the following code

C#.NET Code

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]

public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'[email protected]+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
VB.NET Code:


Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services

Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

End Sub

<WebMethod()> _
Public Shared Function GetAutoCompleteData(ByVal username As String) As List(Of String)
Dim result As New List(Of String)()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("select DISTINCT UserName from UserInformation where UserName LIKE '%'[email protected]+'%'", con)
con.Open()
cmd.Parameters.AddWithValue("@SearchText", username)
Dim dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read()
result.Add(dr("UserName").ToString())
End While
Return result
End Using
End Using
End Function
End Class
Now run your application and check the output that would be like this   

Download sample code attached


  

how to bind dropdownlist in asp.net using jquery or JSON

Posted by imomins on October 7, 2012 at 4:10 AM Comments comments (0)
Introduction

Here I will explain how to bind dropdownlist using JQuery ajax or JSON in asp.net.
Description:
  
In previous articles I explained
Bind gridview using JQuery in asp.net  and AutoComplete textbox with JQuery using asp.net. Now I will explain how to bind dropdownlist using JQuery or JSON in asp.net.
To implement this concept first design table in database and give name as Country as shown below
Column Name
Data Type
Allow Nulls
CountryId
int(set identity property=true)
No
CountryName
varchar(50)
Yes
After completion table design enter some of Country details in database to work for our sample and write the following code in your aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind Dropdownlist with JQuery in asp.net</title>
<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() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/BindDatatoDropdown",
data: "{}",
dataType: "json",
success: function(data) {
$.each(data.d, function(key, value) {
$("#ddlCountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));
});
},
error: function(result) {
alert("Error");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlCountry" runat="server" />
</div>
</form>
</body>
</html>
If you observe above code in header section I added script file link by using that file we have a chance to interact with JQuery. If you want to know about script function mentioned in header section check these posts JQuery AutoComplete textbox with database in asp.net and call asp.net page methods in JQuery.

Now open code behind file and add following namespaces


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
After that write the following code

C#.NET Code

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]
public static CountryDetails[] BindDatatoDropdown()
{
DataTable dt = new DataTable();
List<CountryDetails> details = new List<CountryDetails>();

using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("SELECT CountryID,CountryName FROM Country", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
CountryDetails country = new CountryDetails();
country.CountryId = Convert.ToInt32(dtrow["CountryId"].ToString());
country.CountryName = dtrow["CountryName"].ToString();
details.Add(country);
}
}
}
return details.ToArray();
}
public class CountryDetails
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
VB.NET Code:


Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services

Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
<WebMethod()> _
Public Shared Function BindDatatoDropdown() As CountryDetails()
Dim dt As New DataTable()
Dim details As New List(Of CountryDetails)()

Using con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true")
Using cmd As New SqlCommand("SELECT CountryID,CountryName FROM Country", con)
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
For Each dtrow As DataRow In dt.Rows
Dim country As New CountryDetails()
country.CountryId = Convert.ToInt32(dtrow("CountryId").ToString())
country.CountryName = dtrow("CountryName").ToString()
details.Add(country)
Next
End Using
End Using
Return details.ToArray()
End Function
Public Class CountryDetails
Public Property CountryId() As Integer
Get
Return m_CountryId
End Get
Set(ByVal value As Integer)
m_CountryId = Value
End Set
End Property
Private m_CountryId As Integer
Public Property CountryName() As String
Get
Return m_CountryName
End Get
Set(ByVal value As String)
m_CountryName = Value
End Set
End Property
Private m_CountryName As String
End Class
End Class
Now run your application and check the output that would be like this

Download sample code attached


Posting Form Data from ASP.NET Page to Another URL Using Post Method

Posted by imomins on September 26, 2012 at 8:05 AM Comments comments (0)

Introduction

 

Sometime you need to post a form to an different url from asp.net pages, for example you might need to send user to third party payment processing system using post method, asp.net does not provide any straight forward way to accomplish this task.

Problem which most users faces with server side form in aspx page are, you are not allowed to change action of form and you are allowed to use only one server side form per page.

Possible Solutions

  1. One possible solution to this problem is to Create your own form control and use it on page this will allow you to change action of form, but again what if you do not want some existing input elements in current page to go to post.
  2. There is good way to post form data using HttpWebResponse & HttpWebRequest class if you want to post data behind the scenes, but if you want to post data using user browser then you are stuck.

Our Solution

I will try to show you one possible way to accomplish this task, we will create

  1. component that will create form with required fields and post the form to specified url, 
  2. web page that will use that component to post data and 
  3. page which will receive that data and display posted data.

A) RemotePost Class.

public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name,string value)
{
Inputs.Add(name,
value);
}
public void Post()
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Write("");
System.Web.HttpContext.Current.Response.Write(
string.Format("",FormName));
System.Web.HttpContext.Current.Response.Write(
string.Format("",FormName,Method,Url))
for(int i=0;i< Inputs.Keys.Count;i++)
{
System.Web.HttpContext.Current.Response.Write(
string.Format("",Inputs.Keys[i],Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("");
System.Web.HttpContext.Current.Response.Write("");
System.Web.HttpContext.Current.Response.End();
}
}

 

Properties of our component 

  1. "Url" which is action of our form. 
  2. "Method" which is Method of our form, default is Post but you can also use Get 
  3. "FormName" which is name of form.

Methods of our component. 

  1. "Add" which will be used to add form input name and value. and 
  2. "Post" which will render html on page to do actual posting, most important part of this method is onload event of rendered html's body which will post form to specified URL.

and private field Inputs which will hold name value pair collection of all inputs that goes into form.

you can compile this class to dll and use in your project but for simplicity I am including that class directly into page itself.

B) Sample Page.

Following is sample page code which posts form to specified url.

RemotePost myremotepost = new RemotePost();
myremotepost.Url = http://www.jigar.net/demo/HttpRequestDemoServer.aspx;
myremotepost.Add("field1","Huckleberry");
myremotepost.Add("field2","Finn");
myremotepost.Post() ;

 

C) Receiving Page.

Following is sample page code which posts form to specified url.

This is the page where posting will occur for simplicity we will just write posed value so that we can know what was posted.

<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e){
if (Request.Form["field1" != null ){
Response.Write("field1 : " + Request.Form["field1" + "")}
if(Request.Form["field2" != null ){
Response.Write("field2 : " +Request.Form["field2" + "")}
}
</script> 

 

Run Sample

Click "http://www.jigar.net/demo/RemotePost.aspx" target="new">here to run sample

There will be cases where you will need to tweak the code to suit your requirement. you will also need to check scenario where user uses back button of browser(from posted page) which will cause form to be posted again.

get IP

Posted by imomins on September 19, 2012 at 8:05 AM Comments comments (0)

 

System.Net.IPHostEntry IP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

System.Net.IPAddress[] IPAddr = IP.AddressList;

if (IPAddr.Length > 1)

{

strMachineNameIP = Convert.ToString(System.Environment.MachineName) + " ## " + Convert.ToString(System.Environment.UserName) + " ## " + IPAddr[1].ToString();

}

else if (IPAddr.Length > 0)

{

strMachineNameIP = Convert.ToString(System.Environment.MachineName) + " ## " + Convert.ToString(System.Environment.UserName) + " ## " + IPAddr[0].ToString();

}

else

{

strMachineNameIP = Convert.ToString(System.Environment.MachineName) + " ## " + Convert.ToString(System.Environment.UserName);

}