public class ImageHandler : IHttpHandler - asp.net

cmd.Parameters.AddWithValue("#id", new system.Guid (imageid));
What using System reference would this require?
Here is the handler:
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Globalization;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Web.Profile;
using System.Drawing;
public class ImageHandler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
string imageid;
if (context.Request.QueryString["id"] != null)
imageid = (context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowProfileImage(imageid.ToString());
byte[] buffer = new byte[8192];
int byteSeq = strm.Read(buffer, 0, 8192);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 8192);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowProfileImage(String imageid)
{
string conn = ConfigurationManager.ConnectionStrings["MyConnectionString1"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT image FROM Profile WHERE UserId = #id";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id", new system.Guid (imageid));//Failing Here!!!!
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Maybe typo. Capitalize the first letter of System namespace.
new System.Guid (imageid)

Related

Need to change the format of data return from JSON

I'm creating a webservice which should get data from database(sql server) and return it.
Every thing working fine. But what I need is I need to display the data with the format which I needed.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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 Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
// public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
con.Open();
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT * FROM Contact e WHERE FirstName LIKE '%" + SearchTerm + "%'";
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(ds);
con.Close();
// Create a multidimensional array
string[][] EmpArray = new string[ds.Tables[0].Rows.Count][];
int i = 0;
foreach (DataRow rs in ds.Tables[0].Rows)
{
//EmpArray[i] = new string[] { rs["FirstName"].ToString(), rs["LastName"].ToString(), rs["Contactno"].ToString() };
EmpArray[i] = new string[] { "FNAME: " + rs["FirstName"].ToString(), "LName: " + rs["LastName"].ToString(), "Contactno: " + rs["Contactno"].ToString()};
i = i + 1;
}
// Return JSON data
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(EmpArray);
return strJSON;
}
catch (Exception ex) { return errmsg(ex); }
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Here is my output:
[["FNAME: devi","LName: priya ","Contactno: 965577796 "],
["FNAME: arun","LName: kumar ","Contactno: 9944142109"],
["FNAME: karu ","LName: ronald","Contactno: 8883205008"]]
But I need the result in the following format:(which should contain curly braces and the word cargo at starting each name and value should start and end with double codes..
{ "Cargo": [ { "FNAME": "devi", "LName": "priya " },
{"FNAME": "arun", "LName": "kumar" }, { "FNAME": "karu ", "LName": "ronald" }] }
The followiing code solves my problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[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]
[ToolboxItem(false)]
public class CService : System.Web.Services.WebService
{
public CService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
//public string GetEmployees(string SearchTerm)
public void CargoNet()
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT TOP 1 * FROM cargo_tracking ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
//return serializer.Serialize(rows);
//return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
//JavaScriptSerializer js = new JavaScriptSerializer();
//string strJSON = js.Serialize(new { Cargo = rows });
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
//return serializer.Serialize(new { Cargo = rows });
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}

how to ignore default value(string) in the output of Json webservice

I need to neglect the default value(*string *) in the output which is displayed when executing the webservice JSON.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace Webservice
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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 Service1 : System.Web.Services.WebService
{
public Service1()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
//public string GetEmployees(string SearchTerm)
public string GetEmployees()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Contact e ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col]);
}
rows.Add(row);
}
return "{ \"Cargo\": " + serializer.Serialize(rows) + "}";
}
public string errmsg(Exception ex)
{
return "[['ERROR','" + ex.Message + "']]";
}
}
}
Output is;
<string>
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
</string>
But the actual output i need is;
{ "Cargo": [{"Id":1,"FirstName":"devi","LastName":"priya ","Contactno":"965577796 "},{"Id":2,"FirstName":"arun","LastName":"kumar","Contactno":"9944142109"},{"Id":3,"FirstName":"karu","LastName":"ronald","Contactno":"8883205008"}]}
In the above output i dont want to see the string /string
is there is a way to omit that if so please suggest me.
Thanks in advance
Try replacing return "{ \"Cargo\": " + serializer.Serialize(rows) + "}"; with return serializer.Serialize(new { Cargo = rows });
Your question can be found here:
ResponseFormat.Json returns xml
And try to use this http://www.nuget.org/packages/Newtonsoft.Json/
it can be very helpful to deal with JSON.
Good Luck.

Encryption Decryption of Password using TripleDES

i am working on login application and i have to Encrypt and Decrypt Password using TripleDES and i have a set of coding and that coding Encryption is working good but Decryption is not working it is showing an error.
and the error is:
The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
and the coding is:
newuser.aspx.cs
using System;
using System.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.IO;
namespace WebApplication5
{
public partial class WebForm6 : System.Web.UI.Page
{
SqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con1.Open();
SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=#USERNAME and PASSWORD=#PASSWORD ", con1);
cmd1.Parameters.AddWithValue("#username", txtUserName.Text);
cmd1.Parameters.AddWithValue("#password", txtPassword.Text);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('userName is already availables')</script>");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con.Open();
string strQuery = "insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text +
"','" + EncryptTripleDES(txtPassword.Text) + "')";
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(strQuery, connection);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("login.aspx");
}
con1.Close();
}
public static string EncryptTripleDES(string value)
{
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write);
StreamWriter streamWriter = new StreamWriter(cryptoStream);
streamWriter.Write(value);
streamWriter.Flush();
cryptoStream.FlushFinalBlock();
memoryStream.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, Convert.ToInt32(memoryStream.Length));
}
}
}
login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Security.Cryptography;
using System.IO;
namespace WebApplication5
{
public partial class WebForm4 : System.Web.UI.Page
{
SqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con1.Open();
SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=#USERNAME and PASSWORD=#PASSWORD ", con1);
cmd1.Parameters.AddWithValue("#username", txtUserName.Text);
cmd1.Parameters.AddWithValue("#password", EncryptTripleDES(DecryptTripleDES(txtPassword.Text)));
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("emplist.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
con1.Close();
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtUserName.Text = "";
txtPassword.Text = "";
}
public static string EncryptTripleDES(string value)
{
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(), CryptoStreamMode.Write);
StreamWriter streamWriter = new StreamWriter(cryptoStream);
streamWriter.Write(value);
streamWriter.Flush();
cryptoStream.FlushFinalBlock();
memoryStream.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, Convert.ToInt32(memoryStream.Length));
}
public static string DecryptTripleDES(string value)
{
TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
byte[] buffer = Convert.FromBase64String(value);
MemoryStream memoryStream = new MemoryStream(buffer);
CryptoStream cryptoSteam = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader streamReader = new StreamReader(cryptoSteam);
return streamReader.ReadToEnd();
}
}
}
and plz help me on this coding pbl......,
As I can see it, the problem is in two places:
byte[] buffer = Convert.FromBase64String(value);
int the DecryptTripleDES() function and
cmd1.Parameters.AddWithValue("#password", EncryptTripleDES(DecryptTripleDES(txtPassword.Text)));
in you button submit handler.
On the first line you try to convert a Base64-encoded string into an array of bytes. All well and good if it wasn't for the fact that in this case it probably is just some random text, or a password, entered by the user into the txtPassword control.
Or do you expect users to manually encrypt the password, Base64-encode it and then enter it into the txtPassword field?
Try doing this instead:
cmd1.Parameters.AddWithValue("#password", EncryptTripleDES(txtPassword.Text));

Showing image in GridView from the database?

I have images saved in SQL server database as a binary data. Now I want to show these images in the Gridview. But there web control which directly read the data from the database. Web image control requires ImageUrl property so can not use this as my images are in databases. However i can store the images in a folder but i want some different way which directly read image data from the database and show in a grid.
using generic handler you can convert binary data into image and display it
Code:
Set image control url as
Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
where ShowImage.ashx is a generic handler file.
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);
}
//context.Response.BinaryWrite(buffer);
}
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();
}
}
}
the blog may give you some help
http://hi.baidu.com/pxvddcbpbrbmqxq/item/3de72787e9e1c6eae496e098

Asp.net how to correct the error

I'm designing in my web page and image are stored in my database (The project is Photostudio management system)
MY Code:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace photoshops
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter();
SqlConnection cnn = new SqlConnection();
DataSet ds = new DataSet();
string constr = null;
SqlCommand cmd = new SqlCommand();
if (IsValid != true )
{
constr = #"Data Source=DEVI\SQLEXPRESS;Initial Catalog =cat; Integrated
Security=SSPI";
cnn.ConnectionString = constr;
try
{
if (cnn.State != ConnectionState.Open)
cnn.Open();
}
catch (Exception ex)
{
string str1 = null;
str1 = ex.ToString();
}
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "photoset";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#BillNo", TextBox1.Text);
cmd.Parameters.AddWithValue("#CustomerName", TextBox2.Text);
cmd.Parameters.AddWithValue("#Address", TextBox3.Text);
cmd.Parameters.AddWithValue("#StartDate",Rdbsdate.SelectedDate );
cmd.Parameters.AddWithValue("#EndDate", Rdbddate.SelectedDate );
SqlParameter param0 = new SqlParameter("#Systemurl", SqlDbType.VarChar,
50);
cmd.Parameters.AddWithValue("#Numberofcopies", TextBox7.Text);
cmd.Parameters.AddWithValue("#Amount", TextBox8.Text);
cmd.Parameters.AddWithValue("#Total", TextBox9.Text);
da.SelectCommand = cmd;
try
{
da.Fill(ds);
}
catch (Exception ex)
{
string strErrMsg = ex.Message;
//throw new applicationException("!!!! An error an occured while
//inserting record."+ex.Message)
}
finally
{
da.Dispose();
cmd.Dispose();
cnn.Close();
cnn.Dispose();
}
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
Msg.Text = "Photo setting sucessfullY";
}
else
{
Msg.Text = "photosetting failled";
}
}
}
}
}
}
My ERROR
The record are not stored and image is not stored how to change in my code .
Well first of all, you're not saving the image, you're saving the path of your computer.
You need to save the byte array of the photo.
In short:
Upload its the upload control where you select the image
pic its the byte arrey where you upload the binary content of the photo
and then you only send it as a simple parameter cmd.Parameters.Add ("#pic", pic);
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new
SqlConnection (#"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand cmd = new SqlCommand ("insert into Image "
+ "(Picture, Comment) values (#pic, #text)", connection);
cmd.Parameters.Add ("#pic", pic);
cmd.Parameters.Add ("#text", Comment.Text);
cmd.ExecuteNonQuery ();
}
finally
{
connection.Close ();
}
}
here are some tutorials, the first link it's very straightforward and the code its simple
http://www.codeproject.com/KB/web-image/PicManager.aspx
another, just in case:
http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/
Principal resource: http://www.codeproject.com/KB/web-image/PicManager.aspx

Resources