Uploaded binary Picture into database and display in listview - asp.net

I am try to uploaded an image to a database which work but I can't display the image in a ListView which has a sql datasource
This is my upload image code
int img = ImageUpload1.PostedFile.ContentLength;
byte[] msdata = new byte[img];
ImageUpload1.PostedFile.InputStream.Read(msdata, 0, img);
myCommand.Parameters.AddWithValue("#image_1", msdata);
display image
<asp:Image ID="Image1" runat="server" src='<%# DataBinder.Eval(Container.DataItem, "image_1") %>' CssClass="background-image: url(data:image/jpeg;base64,IVB)" />
This is the error I keep getting
Unable to translate Unicode character \uDAFF at index 15 to specified code page.

You don't have to go my way immediately, but I tried it, and worked quite quickly:
I created a method that returns a File object to the browser:
public ActionResult GetThumbnail(Guid id)
{
var fileToRetrieve = Db.Pictures.Find(id);
if (fileToRetrieve == null)
return null;
if (fileToRetrieve.Thumbnail == null)
return null;
return File(fileToRetrieve.Thumbnail, fileToRetrieve.ContentType);
}
In the browser, I just set the img src attribute to that method with the ID I need to retrieve.
<img src="~/Picture/GetThumbnail?id=#item.Id" />

Related

What is going on with the ajax AutoCompleteExtender?

This really is bizarre. I'm trying to implement the AutoCompleteExtender using a database. I enter the first character, let's say 'T' into the textbox, and the drop down results panel shows all of the page's source code (client side rather than server side), one character per line as seen in the image.
AutoComplete Results Screenshot
Incidentally, Google Chrome displays this straight away, while IE has a good think about it, saying localhost is not responding because it's running a long script.
If I then select any one of those characters it then displays the correct results beginning with 'T', though replaces the character I typed with whatever I selected.
I pulled the code from a tutorial on codeproject.com and apart from changing the textbox ID and a bit of ADO so it points to my database, it's identical.
I'll include the code. What's going wrong?
Now for some reason, it's not letting me post the code, regardless of how I format, but this is what I used. AutoComplete With DataBase and AjaxControlToolkit
It is very hard to give answer without seeing the code... try this
<asp:TextBox ID="txtSearchKey" runat="server" Width="350" AutoPostBack="true" OnTextChanged="txtSearchKey_TextChanged" />
<asp:TextBoxWatermarkExtender ID="weSearchKey" runat="server" Enabled="True" TargetControlID="txtSearchKey" WatermarkText="Search by Name" WatermarkCssClass="watermark" />
<asp:AutoCompleteExtender ServiceMethod="YourWebMethod" MinimumPrefixLength="3" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtSearchKey" ID="searchExtender" runat="server" FirstRowSelected="false" OnClientItemSelected="GetSelectedId" CompletionListCssClass="completionList" CompletionListItemCssClass="listItem" CompletionListHighlightedItemCssClass="itemHighlighted" CompletionListElementID="divCompletionListElement" />
<input type="hidden" id="hdnSelectedId" name="hdnSelectedId" value="" />
Have a javascript method to ensure selected item is captured
function GetSelectedId(source, eventArgs) {
var selectedId = eventArgs.get_value();
var e = document.getElementById('hdnSelectedId');
if (e) {
e.value = selectedId;
}
}
Create a WebMethod in your back end code that is configured in ServiceMethod property of AutoCompleteExtender
[ScriptMethod()]
[WebMethod]
public static List<string> YourWebMethod(string prefixText, int count)
{
var totalRecords = 0;
var searchResults = <<get your results here into a list or whatever container>>
//I used DataTable as a container here for searchResults
if (searchResults.Rows.Count == 0)
return new List<string>() { "No result found" };
//Create a List from your search results and return it
List<string> items = new List<string>();
foreach (DataRow searchResult in searchResults.Rows)
items.Add(AutoCompleteExtender.CreateAutoCompleteItem(searchResult["Name"].ToString(), searchResult["BuilderID"].ToString());
return items;
}

How to solve playing video issue in asp.net

Helli Guys!
I have a issue with playing video based on path of video on run time in web video player. there is a ASP code:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<video src='<%# GetVideoPlayUrl(Eval("id")) %>' width="900" height="400"
controls="" preload=""></video>
</ItemTemplate>
</asp:Repeater>
I have a video Path in database that is saved in db like this ~\StoreVideo\VQOFY.mp4
protected string GetVideoPlayUrl(object Id)
{
int id = Convert.ToInt32(Id);
string ret = "";
ret = "" + VideoUploads.GetVideoPath(id) + "";
return ret; I'm return value `~\StoreVideo\VQOFY.mp4`
}
The video is not uploading in player i also tried this
protected string GetVideoPlayUrl(object Id)
{
int id = Convert.ToInt32(Id);
string ret = "";
ret = "" + VideoUploads.GetVideoPath(id).Replace("~\\","").Replace("\\","/") + "";
return ret; I'm return value `StoreVideo/VQOFY.mp4`
}
still not working i dont know where was im doing wrong I really need a help in this issue. to know what is the mistake I'm doing here. please correct me with my code where was a mistake.hope some buddy have a solution for me with it.
Thank you
URLs that start with ~/ should be 'resolved' before you use them client-side (the <video> element is a client-side HTML element, it is unaware of ASP.NET on the server). Try the following code inside the src attribute:
<%# ResolveUrl(GetVideoPlayUrl(Eval("id"))) %>
If you are returning "~/videos/some-video.mp4" from the GetVideoPlayUrl(id) method, then the call to ResolveUrl() will 'translate' that, maybe to "../../videos/some-video.mp4" or maybe to "videos/some-video.mp4". It all depends on where the current page is located relative to the location of the file.
You should check in the final HTML that the (relative) path from the ASPX page to the video file is now correct.

Passing url to Image tag in asp.net C#

I dont know how to pass value from page.aspx.cs (string url = dr["report_image"].ToString();) to page.aspx ( )
i save image filename (eg:sunset.jpg) to sql database and retrieve it using reader (string url = dr["report_image"].ToString();) and i want to use this url (or filename) to use in the main webpage (aspx). I dont know how to pass this value from ".aspx.cs" to ".aspx"
Any help would be appreciated. thank you
<asp:Image ID="img" Runat="Server" />
Аnd in the code:
img.ImageUrl = url
or you can simply generate Image element in aspx.cs side.
the code below
Image img = new Image();
img.ImageUrl = "your string";

Get File ID in page after upload file by AsyncFileUpload(ajaxToolkit)

I am using AsyncFileUpload (ajaxToolkit) control for uploading image file from registration page. uploaded file content are store into DB. So I need to show my uploaded file in asp:image control by httphander like <asp:image id="imgLogo" runat="server" ImageUrl="Images.aspx/id=12" />. So how to do this.
Assuming you are storing the image as a byte[] in DB;
var data = new byte[1]; //Replace this with your values from DB
var mimeType = "application\pdf"; //Replace this with your values from DB
response.ContentType = mimeType ;
response.BinaryWrite(data);
This code should be placed in page_load in images.aspx after you have retrieved the values from the DB.
Your image page handler page_load method will be
Images.aspx
protected void Page_Load(sender s, eventagrs e){
var imagecontent= new byte[XXXX]; // Read DB content as bytes for the passed Id
response.ContentType = 'jpeg/gif/anything' ;
//this should be a valid MIME type saved in database
response.BinaryWrite(imagecontent);
}
Edit:
From your comments you are trying to update the image tag src value
from codebehind using Asp.Net Ajax.
If you want to do this, first make sure your page has access to view state
information about those image tags. This is not a big deal, you simply
wrap the image tags container panel/div with update panel.
So your ajax request will send the information about those viewstate and
push the partial update for those image container panel also.
I have reviewed many site and I got answer of this question..
http://www.mikeborozdin.com/post/AJAX-File-Upload-in-ASPNET-with-the-AsyncFileUpload-Control.aspx
<ajaxToolkit:AsyncFileUpload ID="afuCompanyLogo" runat="server"
OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
UploaderStyle="Modern" UploadingBackColor="#CCFFFF"
ThrobberID="myThrobber"
onuploadedcomplete="afuCompanyLogo_UploadedComplete" />
<asp:Image ID="imgCompanylogo" CssClass="imgCompanylogo" runat="server" Height="80px" Width="80px" AlternateText="" />
protected void afuCompanyLogo_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if(afuCompanyLogo.HasFile)
{
FileManagementEntity fileManagementEntity = new FileManagementEntity();
FileManagement fileManagement = fileManagementEntity.Create();
fileManagement.FileContentType = afuCompanyLogo.ContentType;
fileManagement.FileContent = afuCompanyLogo.FileBytes;
fileManagement.Size = afuCompanyLogo.FileBytes.Count();
fileManagement.OriginalName = afuCompanyLogo.FileName;
fileManagementEntity.Save(fileManagement);
ViewState["logoID"] = fileManagement.FileManagementID;
imgCompanylogo.ImageUrl = "Image.aspx?id=" + fileManagement.FileManagementID.ToString();
ScriptManager.RegisterClientScriptBlock(afuCompanyLogo, afuCompanyLogo.GetType(), "img", "top.document.getElementById('" + imgCompanylogo.ClientID + "').src='Image.aspx?id=" + fileManagement.FileManagementID + "';", true);
}
}

ASHX image handler not working in ie, works in firefox and chrome

I am storing images in a database and I am using an image handler to display the images using the file path + id. The problem I have is when I update the image through the page, the image doesn't change. Wierd thing is I don't have this problem with firefox or chrome.
ASHX handler
public void ProcessRequest(HttpContext context)
{
Guid image_id;
if (context.Request.QueryString["id"] != null)
image_id = System.Guid.Parse(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = GetImageFromDatabase(image_id);
if (strm != null)
{
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);
}
}
User control code
string imagePath = "<a href=" + (Image.ImageUrl = "~/ShowImage.ashx?id=" + r["Image_id"]);
Markup
<asp:UpdatePanel ID="Upd1" runat="server" UpdateMode="Always" >
<ContentTemplate>
<div id="mpe" style="width: 600px; padding: 5px;">
<uc2:IMG ID="IMG1" cssclass="bodycopy" runat="server" />
</div>
<asp:UpdateProgress ID="upp1" runat="server" AssociatedUpdatePanelID="Upd1">
<ProgressTemplate>
<div id="progressBackgroundFilter">
</div>
<div id="modalPopup">
Loading...
<img align="middle" src="../images/Ajax/loading_1.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
I am not sure what other code to post but here is what I think is relevant. When I click my button to update an image it successfully updates the row in the database. Also I can update data about an image and this correctly updates.
Any ideas?
IE caches the data and shows the same if the URL does not change. I was also facing the same problem and removed it with the following trick: -
imgUser.ImageUrl = "Handler.ashx?UserID=" + Convert.ToString(Session["userid"]) + "extraQS=" + DateTime.Now.Second;
The extraQS query string with DateTime.Now.Second will make the trick by making the URL dynamic and thus the URL will change on each request and the image will not be used from browser cache.
Note: - Ignore the extra query string argument in Handler.ashx.
Could you try to use this code?
string imagePath = "<a href='" + Page.ResolveClientUrl("~/ShowImage.ashx?id=" + r["Image_id"]) + "' />";
What I ended up doing is using a guid as my image id in my Image handler. But in my SQL, when I update an image I use sql servers in-built newid() function so everytime an update is made that images guid will change. By doing this IE recognises that its not the same ID and doesn't use the cached image.
The issue can be resolved by adding the current seconds or random number at the end of QueryString. Its works fine for IE.
string imagePath = "<a href=" + (Image.ImageUrl = "~/ShowImage.ashx?id=" + r["Image_id"] + "&timeInSec="+ DateTime.Now.Second);
Another Example Which returns the Image URL
protected string getImageURL(int index)
{
return "ImageHandler.ashx?index=" + index + "&timeInSec=" + DateTime.Now.Second;
}

Resources