How to get image from Image control and save into local directory as jpeg image in asp.net? - asp.net

i am loading image from asp.net handler as below> handler fetches image using web service. Handler returns as bytes[] data.
<asp:Image ID="image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
Now, I have image in the web page. I have save Image button in the web page. When button clicked, I want to save this image into local directory (c:\images) as a jpeg image. How to achieve this?

Try to use the following code for handler, which returns image data:
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
bool isSave = !String.IsNullOrEmpty(context.Request["save"]);
int imgId;
if (String.IsNullOrEmpty(context.Request["id"]) || Int32.TryParse(context.Request["id"], out imgId))
throw new ArgumentException("No parameter specified");
byte[] imageData = LoadImageFromWebService(imgId); //load image from web service
context.Response.ContentType = "image/jpeg";
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
context.Response.AddHeader("Content-Disposition", String.Format("{0} filename=image.jpeg", isSave ? "attachment;" : String.Empty));
context.Response.BinaryWrite(imageData);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Change asp.net page as follows:
<asp:Image ID="Image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>
<asp:ImageButton ID="ImageButton1" OnClick="OnImageClick" runat="server" />
In this case your OnImageClick handler in page will be:
protected void OnImageClick(object sender, ImageClickEventArgs e)
{
Response.Redirect("~/Handler1.ashx?id=1&save=1");
}

I think that you must get the path of the image control
inside the click event
as
string path = image1.ImageUrl;
and then save it to the file
hope this helps you

public class ImageHandler : IHttpHandler
{
Users objimage = new Users();
public void ProcessRequest(HttpContext context)
{
Int32 theID;
if (context.Request.QueryString["Id"] != null)
theID = Convert.ToInt32(context.Request.QueryString["Id"]);
else
throw new ArgumentException("No parameter specified");
HttpResponse r = context.Response;
r.ContentType = "image/jpeg";
context.Response.ContentType = "image/jpeg";
objimage.imageId = theID; //select image using id
Stream strm = objimage.SelectImageByID(theID);
byte[] buffer = new byte[2048];
if (strm != null)
{
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
else
{
r.WriteFile("~/img/img-profile.jpg");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

Related

What is the Most simple way to store image in Data base in MVC

ok, So criticism apart, I'm New to MVC, my Point is how can i store an image in data base that will be uploaded by user.
i'm Creating a simple blog via MVC And what i Want is A form Same like WordPress "ADD NEW POST". Where user can enter title,TAGS,Headings, But What my Part is, I have to store all of them in DB. i can Do the CSS part, but i'm struck in Functionality that will be Getting all values From user (view) And Then Storing it in database also Displaying it.
below is my google-d Code for View in MVC.
#model SimpleBlogg.Models.PostContent
#{
ViewBag.Title = "AddContentToDB";
}
<div class="UploadPicForm" style="margin-top:20px;">
#using (Html.BeginForm("AddContentToDB", "AddNewPost", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
}
</div>
Save as Base64 string:
static string base64String = null;
public string ImageToBase64()
{
string path = "D:\\SampleImage.jpg";
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
public System.Drawing.Image Base64ToImage()
{
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
ms.Write(imageBytes, 0, imageBytes.Length);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
return image;
}
protected void ImageToBase_Click(object sender, EventArgs e)
{
TextBox1.Text = ImageToBase64();
}
protected void BaseToImage_Click(object sender, EventArgs e)
{
Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));
Image1.ImageUrl = "~/Images/Hello.jpg";
}
source: http://www.c-sharpcorner.com/blogs/convert-an-image-to-base64-string-and-base64-string-to-image

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

How to pass image to Eval method from handler.ashx to imageurl?

I want to retrieve image from database and display in an aspx page. I use Linq to SQL. And a Generic handler.
Handler2.ashx code:
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["id"] != null)
{
int id;
string sid = context.Request.QueryString["id"];
if (int.TryParse(sid, out id))
{
Stream strm = getImage(id);
byte[] buffer = new byte[4096];
int i = strm.Read(buffer, 0, 4096);
while (i > 0)
{
context.Response.OutputStream.Write(buffer, 0, 4096);
i = strm.Read(buffer, 0, 4096);
}
}
else
{
//
}
}
}
public Stream getImage(int id)
{
using (DummyDBEntities cntx = new DummyDBEntities())
{
var db = from c in cntx.Images
where c.imageId == id
select c.imageData;
MemoryStream ms = new MemoryStream();
byte[] byteArray = new byte[db.ToArray().Length];
ms.Write(byteArray, 0, db.ToArray().Length);
return new MemoryStream(byteArray);
}
}
And a button control in Default.aspx page when I click, redirects to handler1.ashx. Gets the id of image from database and supposed to Show it in Default.aspx asp:image control
protected void btnGetID_Click(object sender, EventArgs e)
{
int id=Convert.ToInt32(txtGetID.Text);
Response.Redirect("Handler2.ashx?id="+id);
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
}
How do i supposed to write Eval method and the querystring to pass the image to imageurl?
Image1.ImageUrl = '<%# "~/Handler2.ashx?id=" + Eval("imageData"); %>';
Please help, thanks.
I hope I understood your problem right.
You want to display the image from your handler in the Image1. For that you can just do the following
Image1.ImageUrl = ResolveUrl("~/Handler2.ashx?id=" + id);

Page cannot be null error custom MOSS 2007 Webpart

I'm trying to write a webpart that basically pulls data from a list and displays it to the user. There is a feature news list where one of the columns holds a URL to an image. The web part should get the 3 most recent feature news items and create three image controls on the page. These image controls can be scrolled through by clicking on the buttons 1,2,3. (Ie, clicking on 2 will set the Visible property of image 1 and image 3 to false).
I have managed to implement AJAX here, but am now trying to use the UpdatePanelAnimationExtender from the AJAX Control Toolkit.
I have followed all instructions on how to use the toolkit, add it to the GAC, add a safe assembly, etc, and have gotten past all the errors besides this one:
"Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request"
My complete code below:
using System; using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.Extensions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.ComponentModel;
using AjaxControlToolkit;
namespace FeatureNewsWebpartFeature {
[Guid("7ad4b959-d494-4e85-b164-4e4231692b8b")]
public class FeatureNewsWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
private bool _error = false;
private string _listName = null;
private string _imageColumn = null;
Image image1;
Image image2;
Image image3;
UpdatePanelAnimationExtender upAnimator;
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("List Connection Settings")]
[WebDisplayName("List Name")]
[WebDescription("Enter the name of the news list")]
public string ListName
{
get
{
if (_listName == null)
{
_listName = "News";
}
return _listName;
}
set { _listName = value; }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("List Connection Settings")]
[WebDisplayName("Image Column Name")]
[WebDescription("Enter the column name of the ArtfulBits Image Upload column")]
public string ImageUrlColumn
{
get
{
if (_imageColumn == null)
{
_imageColumn = "Feature Image";
}
return _imageColumn;
}
set { _imageColumn = value; }
}
public FeatureNewsWebPart()
{
this.ExportMode = WebPartExportMode.All;
}
/// <summary>
/// Create all your controls here for rendering.
/// Try to avoid using the RenderWebPart() method.
/// </summary>
protected override void CreateChildControls()
{
if (!_error)
{
try
{
base.CreateChildControls();
//Create script manager
if (ToolkitScriptManager.GetCurrent(this.Page) == null)
{
ToolkitScriptManager scriptHandler = new ToolkitScriptManager();
scriptHandler.ID = "scriptHandler";
scriptHandler.EnablePartialRendering = true;
this.Controls.Add(scriptHandler);
}
//Create update panel
System.Web.UI.UpdatePanel imageUpdatePanel = new System.Web.UI.UpdatePanel();
imageUpdatePanel.ID = "imageUpdatePanel";
imageUpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
this.Controls.Add(new LiteralControl("<div id=\"updateContainer\">"));
this.Controls.Add(imageUpdatePanel);
this.Controls.Add(new LiteralControl("</div>"));
//Make SPSite object and retrieve the three most recent feature news items
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
SPList oList = web.Lists[ListName];
SPQuery oQuery = new SPQuery();
oQuery.RowLimit = 3;
oQuery.Query = "<OrderBy>" +
"<FieldRef Name='Modified' Ascending='False' /></OrderBy>" +
"<Where>" +
"<Eq>" +
"<FieldRef Name='ContentType' />" +
"<Value Type='Choice'>Feature News Item</Value>" +
"</Eq>" +
"</Where>";
oQuery.ViewFields = string.Concat(
"<FieldRef Name='Feature_x0020_Image' />" +
"<FieldRef Name='Feature_x0020_Order' />");
image1 = new Image();
image2 = new Image();
image3 = new Image();
//For each item, extract image URL and assign to image object
SPListItemCollection items = oList.GetItems(oQuery);
foreach (SPListItem oListItem in items)
{
string url = oListItem["Feature_x0020_Image"].ToString();
url = url.Substring(url.IndexOf("/Lists"));
url = url.Remove(url.IndexOf(";#"));
switch (oListItem["Feature_x0020_Order"].ToString())
{
case "1":
image1.ImageUrl = url;
break;
case "2":
image2.ImageUrl = url;
break;
case "3":
image3.ImageUrl = url;
break;
default:
//ERROR
break;
}
}
if (!(Page.IsPostBack))
{
image1.Visible = true;
image2.Visible = false;
image3.Visible = false;
}
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image1);
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image2);
imageUpdatePanel.ContentTemplateContainer.Controls.Add(image3);
//Create animation for update panel
upAnimator = new UpdatePanelAnimationExtender();
upAnimator.ID = "upAnimator";
upAnimator.TargetControlID = imageUpdatePanel.ID;
const string xml = "<OnUpdating>" +
"<Parallel duration=\".25\" Fps=\"30\">" +
"<FadeOut AnimationTarget=\"updateContainer\" minimumOpacity=\".2\" />" +
"</OnUpdating>" +
"<OnUpdated>" +
"<FadeIn AnimationTarget=\"updateContainer\" minimumOpacity=\".2\" />" +
"</OnUpdated>";
Animation.Parse(xml, upAnimator);
this.Controls.Add(upAnimator);
Button b1 = new Button();
b1.ID = "b1i";
b1.Click += new EventHandler(b1_Click);
b1.Text = "Image 1";
Button b2 = new Button();
b2.ID = "b2i";
b2.Click += new EventHandler(b2_Click);
b2.Text = "Image 2";
Button b3 = new Button();
b3.ID = "b3i";
b3.Click += new EventHandler(b3_Click);
b3.Text = "Image 3";
this.Controls.Add(b1);
this.Controls.Add(b2);
this.Controls.Add(b3);
AsyncPostBackTrigger tr1 = new AsyncPostBackTrigger();
tr1.ControlID = b1.ID;
//tr1.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr1);
AsyncPostBackTrigger tr2 = new AsyncPostBackTrigger();
tr2.ControlID = b2.ID;
//tr2.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr2);
AsyncPostBackTrigger tr3 = new AsyncPostBackTrigger();
tr3.ControlID = b3.ID;
//tr3.EventName = "Click";
imageUpdatePanel.Triggers.Add(tr3);
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void b1_Click(object sender, EventArgs e)
{
image1.Visible = true;
image2.Visible = false;
image3.Visible = false;
}
void b2_Click(object sender, EventArgs e)
{
image1.Visible = false;
image2.Visible = true;
image3.Visible = false;
}
void b3_Click(object sender, EventArgs e)
{
image1.Visible = false;
image2.Visible = false;
image3.Visible = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
/// <summary>
/// Ensures that the CreateChildControls() is called before events.
/// Use CreateChildControls() to create your controls.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(EventArgs e)
{
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
// Your code here...
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
/// <summary>
/// Clear all child controls and add an error message for display.
/// </summary>
/// <param name="ex"></param>
private void HandleException(Exception ex)
{
this._error = true;
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
} }
Here's a related question though being asked in the context of SP 2010, it's still directly applicable given the solution.
We have a CQWP on our MOSS farm that does essentially the same thing: reads items from a list using jQuery and the SPServices plugin and animates slider changes. The most difficult part of the process is actually tweaking the look, if I remember correctly. Once you have the right pieces, putting it together is a snap.

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources