Fetching photos dynamically? - c#

I am trying to integrate a JavaScript photo album in ASP.NET (C#).
The code which I have uses hardcoded images; I want to fetch those images dynamically.
<div class="image_stack" style="margin-left:300px">
<img id="photo1" class="stackphotos" src="photos/4.jpg" >
<img id="photo2" class="stackphotos" src="photos/5.jpg" >
<img id="photo3" class="stackphotos" src="photos/6.jpg" >
</div>
I want to replace these hardcoded photos with 3 URLs fetched from a database. How can I achieve this?

One simple way:
use ASP:Image control
<asp:Image ID="photo1" class="stackphotos" runat="server" ImageUrl=" " />
<asp:Image ID="photo2" class="stackphotos" runat="server" ImageUrl=" " />
<asp:Image ID="photo3" class="stackphotos" runat="server" ImageUrl=" " />
then you can assign ImageUrl on the server Side i.e.
var obj= GetUserImages(); //method fetching image urls from db.
photo1.ImageUrl = obj.ImageUrl1;
photo2.ImageUrl = obj.ImageUrl2;
photo3.ImageUrl = obj.ImageUrl3;
2. you can simply place runat="server" attribute on your existing img tags and access them on the server side and set their url. i.e place runat="server" on your img like below
<img id="photo1" runat="server" class="stackphotos" src="photos/4.jpg" >
and then access this on server side like
photo1.Src = dbObject.Url;
3. you can dynamically insert imgs from the server side in a loop.
string imgs = string.Empty;
foreach(var item in GetAllUserImages())
{
images +="<img src='"+ item.ImageUrl +"' class='stackphotos' />";
}
div1.InnerHtml= images;
where div is
<div id="div1" runat="server">
</div>
4. you can call a webmethod (a method on your .aspx.cs page, marked with attribute [WebMethod] and call it via ajax and update your img tags in a javascript function.

Page:
<%# Page Language="C#" %>
other page content
<asp:PlaceHolder runat="server" ID="myimages" />
other page content
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
using(var db = new myDataContext()) // see linq to sql / entity framework
foreach(var i in db.ImagesTable.Select(img => new { Id = img.Id })) // ImagesTable is the name of your table with info about your images
myimages.Controls.Add(new LiteralControl(#"<img src=""myimgdir/" + i.Id + "".jpg" class=""stackphotos"" />")); // presuming that images are named according to an id in the database
}

Related

How to change IFrame src dynamically on Menu item selection

i am working on Power BI reporting emebedded to asp web forms, rather creating multiple webforms, i am looking for refreshing single wegbage URL with iframe src changes where src values matained in multi menu table in SQL,
i can populate menu items from SQL DB with below code and even navigate to new URL stored in SQL DB for selected multi menu items. but i am looking for changing only iframe src of the url. if i try to identify src on menu item selected option, it will try to apply last src found in SQL DB. how to use same url and read only iframe SRC
this is my SQL table with IFrame src storedin 'PBISource' column
below is my master page where i store src values in 'lblMenuSRC' label which will be retrieved in content page :
<asp:ContentPlaceHolder ID="MainContent1" runat="server">
</asp:ContentPlaceHolder>
<br />
<asp:Label runat="server" ID="lblMenuSRC" Text="" Visible="false"></asp:Label>
c# code
below is my code.:, iframe source values stored in "PBISource" column in SQL table, i tried to apply this to 'Selected = 'row["PBISource"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)'
string currentPage = Path.GetFileName(Request.Url.AbsolutePath);
MenuItem menuItem = new MenuItem
{
Value = row["MenuId"].ToString(),
Text = row["MenuTitle"].ToString(),
NavigateUrl = row["AccessURL"].ToString(),
Selected = row["AccessURL"].ToString().EndsWith(currentPage, StringComparison.CurrentCultureIgnoreCase)
};
aspx Content page code where iframe applied:
<asp:Content ContentPlaceHolderID="MainContent1" ID="contentSRC" runat="server">
<iframe id="myIframe" name="myIframe" runat="server" width="100%" height="700" onload="myIframe_Load" allowfullscreen="true">
</iframe>
</asp:Content>
content page c# code on loading iframe
<
protected void myIframe_Load(object sender, EventArgs e)
{
Label lbl = (Label)Page.Master.FindControl("lblMenuSRC");
lbltxt = lbl.Text;
if (lbltxt.Length > 0)
{ myIframe.Attributes["src"] = lbltxt; }
} >
please help me with some example on how to achieve this. i am not that great expert and as some basic knowledge on this.

Showing Byte Image in repeater

I want to some images in asp repeater which comes from databas image table.
HTML
<asp:Repeater ID="rpt_" runat="server">
<ItemTemplate>
<li>
<img src="<%="data:image/jpg;base64," + Convert.ToBase64String((byte[])Eval("Photo")) %>" alt="" />
</li>
</ItemTemplate>
</asp:Repeater>
C#
private void Load_()
{
ClassDo class_ = new ClassDo;
DataTable dt = class_.Ann().Tables[0];
rpt_.DataSource = dt;
rpt_.DataBind();
}
These are my codes, and get me error I cannot show images.
HTML
<img alt="" src="<%="data:image/jpg;base64," + Convert.ToBase64String(Class_._image) %>" />
C#
Class_._image = (byte[])dt.Rows[0]["Photo"];
It works like that somewhere else, but with repeater I cannot read it with Eval.
Is there any working way to show images?
Can you try this?
Create a function
public string GetImage(object img)
{
return "data:image/jpg;base64," + Convert.ToBase64String((byte[])img);
}
Then change your declaration like this
<asp:Image ImageUrl='<%# GetImage(Eval("Photo")) %>' />

download image files from path stored in sql server database asp.net c#

I am making a web form application that allows a user to upload image file to a folder and store its path in database.
there is a data-list that is populated by the image path.
I want the functionality to download image when it is selected from data-list.
I am new to it and didn't get clear guidance from other questions.
Kindly help me.
Here is my code for uploading file
try
{
if (FileUploadzz.HasFile)
{
Guid g = Guid.NewGuid();
string strguid = g.ToString();
string uniqueString = strguid + FileUploadzz.FileName;
FileUploadzz.SaveAs(Server.MapPath(#"~\AllUploads\AllUserImages\" + uniqueString));
DataClasses1DataContext db2 = new DataClasses1DataContext();
Picture p = new Picture();
p.picturePath = "http://localhost:12237/AllUploads//AllUserImages/" + uniqueString;
db2.Pictures.InsertOnSubmit(p);
db2.SubmitChanges();
}
}
catch (Exception)
{
throw;
}
i have a button in my datalist itemtemplate that i want to use for downloading that specific image
i need help on downloading the image when button is clicked.
To show list of files in aspx
<asp:DataList ID="DataList1" runat="server" >
<ItemTemplate>
<a href='/download/<%# DataBinder.Eval(Container.DataItem, "FileName") %>'>
<%# DataBinder.Eval(Container.DataItem, "FileName") %>
</a>
</ItemTemplate>
</asp:DataList>
In the code-behind
DataList1.DataSource = ...;
DataList1.DataBind();
where FileName is a name of column in the database and /download is a folder of files.
To download using a button with onclick event, replace a-tag with
<input type="button" value="download"
onclick="window.location.href='/download/<%# DataBinder.Eval(Container.DataItem, "FileName") %>'">

Alternate image display in asp.net

I am trying to provide alternate image as some of the images are corrupt and do not get display, I tried with js but no success, so need help and suggestions on how to do the same. the scenario is on page load the information of students get bound to DataList and on the basis of it image is pulled from another table by GetImage class but the problem is some images are corrupt so I want to display another dummy image. I changed BG image using CSS but its not as expected.
<asp:DataList ID="DataList1" CssClass="slider" r RepeatColumns="6" RepeatDirection="Vertical" runat="server" OnEditCommand="DataList1_EditCommand" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<ul>
<li><a class="info" href="#">
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
</li>
</ul>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
string city = Request.QueryString["city"];
string RollNo = Request.QueryString["RollNo"];
string state = Request.QueryString["state"];
string fname = Request.QueryString["fname"];
string lname = Request.QueryString["lname"];
DataAccess dao = new DataAccess();
dao.openConnection();
byte[] arr = dao.GetPicture(city, RollNo, state, fname, lname);
//Response.BinaryWrite(arr);
try
{
Response.BinaryWrite(arr);
}
catch (Exception) { }
}
You can use the onerror of the image and show an alternative image if not loaded.
Here is a basic example with one img tag, on asp.net you can place similar the onerror call
<img id="one" src="image.gif" onerror="imgError(this)">​
and the javascript
function imgError(me)
{
// place here the alternative image
var AlterNativeImg = "/images/emptyimage.gif";
// to avoid the case that even the alternative fails
if(AlterNativeImg != me.src)
me.src = AlterNativeImg;
}
and live: http://jsfiddle.net/DxN69/2/
and also http://jsfiddle.net/DxN69/3/
and final: http://jsfiddle.net/DxN69/4/
on asp.net image button
you simple add the onerror="imgError(this)" on your asp.net tag as:
<asp:ImageButton ID="ImageButton1" runat="server" onclick="ImageButton1_Click" ImageUrl="image.jpg" onerror="imgError(this)" />
even if the image button is rendered as input the final result is the same.
image send from code behind
after your last update is clear that you have make a big mistake trying to send a page as an image, and you did not even change the ContentType of it. So use a handler, eg make a new handler named loadImage.ashx and there write your code as:
public void ProcessRequest(HttpContext context)
{
// this is a header that you can get when you read the image
context.Response.ContentType = "image/jpeg";
// cache the image - 24h example
context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
context.Response.Cache.SetMaxAge(new TimeSpan(24, 0, 0));
// render direct
context.Response.BufferOutput = false;
// load here the image as you do
....
// the size of the image
context.Response.AddHeader("Content-Length", imageData.Length.ToString());
// and send it to browser
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
and your call will be something like:
<asp:ImageButton CssClass="imagetest" AlternateText=" " ID="Image1" name="mybutton" runat="server" Width="140" Height="140" CommandName="image" OnLoad="changeImage();" CommandArgument="image" CausesValidation="false" ImageUrl='<%# "loadImage.ashx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>'
now here you can double check if the image exist and send some default image if not exist.
<img src="images.png" onerror="this.onerror=null;this.src='default.png'">
I would preffer to set imageURL property for the default image you want to display. If the image is exists in database record then replace the imageURL with that record else keep it as it is.
Just do using onerror event
<img src="image.gif" onerror="alert('The image could not be loaded.')">
Instead of creating a server side image button why you just not create an html image with a link, that acts as an image button.
<a class="info" href="#">
<img src="<%# GetImage.aspx?source=" + Eval("city") +"&RollNo="+ Eval("RollNo") +"&state="+ Eval("state")+"&fname="+Eval("FirstName") +"&lname=" + Eval("LastName") %>" onerror="this.src='<%=Page.ResolveClientUrl("~/images/emptyimage.gif") %>'" alt="" class="imagetest" />
</a>

write the same code from aspx page to behind code in the cs page

is there a way to write this code from an aspx page
to a behind code of the aspx page (cs), in asp.net.
<a rel="lightbox" id="userImageLightBox" runat="server" title="profile image">
<img id="userImage" runat="server" width="150" height="146" alt="" src=""/>
</a>
for example if i have the code in apsx:
<asp:Label ID="pageProfileHeadName" runat="server" Visible="true"/>
in the behind code i can do:
Label label = new Label();
label.ID = "pageProfileHeadName";
label.Visible = true;
thanks
Short answer - yes - a hyperlink control renders as <a> so you could do this:
Hyperlink a = new Hyperlink();
a.ID = "userImageLightBox";
See the MSDN regarding this server control:
http://msdn.microsoft.com/en-us/library/k0b15efk(v=vs.71).aspx
Anytime a control is runat=server this means you will be able to access it from the aspx code behind page (.cs, .vb, etc). So if you ever want to change a specific property, such as the NavigateURL property you could do so.
a.NavigateURL = "someURL";
Since you have already set the runat="server" attribute, you can access the HTML controls in your code-behind through its id:
// *.aspx:
<a id="userImageLightBox" runat="server" ...>
<img id="userImage" runat="server" ... />
</a>
// code-behind:
userImageLightBox.Title = "New Title";
userImage.Src = "~/images/profile.png";
// To get or set an attribute like `rel`:
userImageLightBox.Attributes["rel"] = "test";
Update: If you want to create the HTML from the code-behind, you can do as JonH wrote:
HyperLink a = new HyperLink();
a.ID = "userImageLightBox";
a.Attributes["rel"] = "lightbox";
Image img = new Image();
img.ID = "userImage";
img.ImageUrl = "img.png";
img.Width = 150;
img.Height = 146;
a.Controls.Add(img);
Oh, and please increase your accept rate.

Categories