Sponsors

Thứ Tư, 7 tháng 3, 2012

Ajax Auto Complete suggestion in asp.net using webservices (Ajax AutocompleteExtender)

AutoCompelete using Ajax in Asp.net 

Ajax a powerfull script on the web,It provides you a lot more functionality to
improve your application Performance.
Heres the article to show how to work with AutoCompleteExtender (Control in AjaxControlToolKIt).


AutoComplete Description
  • AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control,
    and will associate that control with a popup panel to display words that
    begin with the prefix typed into the textbox.
  • The dropdown with candidate words supplied by a web service is
    positioned on the bottom left of the text box
    .

This means that the control will fetch the data from a webservice(sdsd), and it can be attached to a asp.net TextBox control.
Whenever users starts typing in the textbox, it automatically fetches a suggestion list from the configured webservice.


Note: Add latest Ajax dll in your application bin folder.

Step 1: Add  webservices (WebService.asmx)
code:  appcode/WebService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections;

/// Summary description for WebService
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string[] GetNames(string prefixText, int count, string contextKey)
{
ArrayList sampleList = new ArrayList();
sampleList.Add("ABC"); sampleList.Add("Hello");
sampleList.Add("Hi"); sampleList.Add("Apple");
sampleList.Add("Hey");
ArrayList filteredList = new ArrayList();
foreach (string s in sampleList){
if (s.ToLower().StartsWith(prefixText.ToLower()))
filteredList.Add(s);
}
return (string[])filteredList.ToArray(typeof(string));
}
}


Step 2: AC.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ac.aspx.cs" Inherits="Ac" %>

<%@  Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="Ajaxtoolkit"  %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
 <body>

  <form id="form1" runat="server">
    <asp:scriptmanager id="ScriptManager1" runat="server"></asp:scriptmanager>
   <div>
        <asp:textbox id="TextBox1" runat="server"></asp:textbox>
          <ajaxtoolkit:autocompleteextender enabled="true" minimumprefixlength="0" runat="server" servicemethod="GetNames" servicepath="WebService.asmx" targetcontrolid="TextBox1" usecontextkey="true">
        </ajaxtoolkit:autocompleteextender>
    </div>
</form>
</body>
</html>

Thứ Ba, 6 tháng 3, 2012

Save and retrive Binarydata from database into image

How to Save and Retrive BinaryData from Database into Image


This article will demonstrate how to display/store and retrieve image data from an SQL database to aspx page. First we have to add generic handler.

Create an ashx page that you'll target as an image URL.Then you need to write the byte array as response stream in the ProcessRequest method inside that handler as show in below code snippet.

ShowImage.ashx
%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}

public Stream ShowEmpImage(int empno)
{ string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT* FROM table WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}

catch
{ return null; }

finally
{ connection.Close(); }
}
public bool IsReusable
{
get { return false; }
}
}

Default page.aspx.cs


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = "INSERT INTO 
table(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
cmd.Parameters.AddWithValue("@eimg", imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format("Employee ID is {0}", id);

// Display the image from the database
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
}
catch
{
lblResult.Text = "There was an error";
}
finally { connection.Close(); }
}
}

Thứ Bảy, 3 tháng 3, 2012

NDataFlow - Open Source .NET Dataflow Library

Last year, a colleague of mine showed me an open source .NET extract, transform and load (ETL) helper library that he's working on. It is called NDataFlow and allows you to annotate methods with attributes to create a dataflow in your application. It's a nice lightweight library that you can use whenever you are developing simple or complex ETL programs. The example below simulates a very simple ETL scenario where a set of people (hard-coded in the example) are filtered based on their location and then output to a file.

class Program : DataflowComponent
{
static void Main(string[] args)
{
new Program().Run();
}

//First method in the flow
[Operation]
public void DataSource(Output output)
{
//Imagine retrieving people from a real data source
//e.g. database, xml file, csv file, etc.
output.Emit(new Person() { Name = "Alice", City = "London" });
output.Emit(new Person() { Name = "Bob", City = "New York" });
output.Emit(new Person() { Name = "Foo", City = "London" });
output.Emit(new Person() { Name = "Bar", City = "Sydney" });
}

[Operation]
public IEnumerable FilterForLondonPeople
([Link("DataSource")] IEnumerable input)
{
return input.Where
(p => p.City.Equals("London",
StringComparison.InvariantCultureIgnoreCase));
}

[Operation]
public void OutputResults
([Link("FilterForLondonPeople")] IEnumerable results)
{
using (var sw = new StreamWriter(@"C:\LondonPeople.txt", false)
{
foreach (var p in results)
sw.WriteLine("{0} {1}", p.Name, p.City);
}
}
}
The example shows that there is little work needed to get a simple dataflow setup and running. You inherit the Run method by deriving from the NDataFlow.DataflowComponent class. Then, if you've setup your method and attributes correctly using the LinkAttribute it's a simple case of calling Run to start your dataflow. In this case, the first method in the dataflow would be DataSource, whose output is sent to FilterForLondonPeople and finally whose output is sent to the OutputResults method.