Check if Image Exists on Remote Site ASP.NET VB - asp.net

I'm trying to get my website to detect if an image exists on the server, display if it does, if it doesn't display another image (which is just called blank.png).
I have tried to use Server.MapPath with relative pathings but havent been able to get it to work. When using Server.MapPath and checking in the broswer after the page has loaded i uses the full path of the file (eg G:\domain\path\blank.png).
If i use The normal path (Dim sImagePath As String = "\Images\DriversNew\"'). The image will display, but the check for whether the image exists or not always returns false. I'm assuming its to do with the physical location of the file.
'Dim sImagePath As String = Server.MapPath("Images/DriversNew/")
Dim sImagePath As String = "\Images\DriversNew\"
Dim sHeadshot As String = sImagePath & dsDriver.Tables("Driver").Rows(0).Item("Name") & ".png"
If File.Exists(sHeadshot) Then
imgDriver.ImageUrl = sHeadshot
Else
imgDriver.ImageUrl = sImagePath & "Blank.png"
End If
Any advice? I know its something simple, but with the reading ive been doing it hasnt been able to get it working on the site.
Thanks, much appreciated!

Assuming that your database column Name contains only the short filename (i.e. no directory path information or folder names) then you can do this:
String nameFromDatabase = (String)dsDriver.Tables("Driver").Rows[0]["Name"] + ".png";
String appRootRelativeHttpResourcePath = "~/Images/DriversNew/" + nameFromDatabase;
String localFileSystemPath = Server.MapPath( appRootRelativeHttpResourcePath );
if( File.Exists( localFileSystemPath ) ) {
imgDriver.ImageUrl = appRootRelativeHttpResourcePath; // you can specify app-root-relative URLs ("~/...") here
}
else {
imgDriver.ImageUrl = "~/Images/DriversNew/Blank.png";
}

Related

Why the Generated ImageUrl is wrong

i have strored images in a folder within my project with name like this
(ProductID).Extention
and other details of image are stored in the database
i have used the following procedure to fetch the image
create proc prcMainPhoto(#ProductID int)
as
select p.ProductID ,
isnull(( select top 1 convert(varchar,PhotoID,10) + '.' + ExtName from ProductPhoto where ProductID= p.ProductID ),'NoImage.jpg')as MainPhoto
from ProductInfo as p where p.ProductID=#ProductID
and give imageurl to image like this
DataSet ds1 = new ClientProductView().GetMainPhotoInDeatailPage(productid);
string img = ds1.Tables[0].Rows[0]["MainPhoto"].ToString();
imgmain.ImageUrl ="./productimages / main / "+ img;
but the image is genrating this url
http://localhost:1030/SShopping%20Website/ProductDetails.aspx?ProductID=1#
i have coded in page ProductDetails which is placed outside
Please help
Must give imageurl like this
DataSet ds1 = new ClientProductView().GetMainPhotoInDeatailPage(1);
string img = ds1.Tables[0].Rows[0]["MainPhoto"].ToString();
image.ImageUrl = string.Format("productimages/main/" + img);
I think that the issue here is that ImageUrl can only be assigned with either a relative or an absolute URL. I think that the use of . in your URL path is that is causing the issue.
Try setting the image url with a relative path:
imgmain.ImageUrl ="~/productimages/main/" + img;

How to remove the full file path from YSOD?

In the YSOD below, the stacktrace (and the source file line) contain the full path to the source file. Unfortunately, the full path to the source file name contains my user name, which is firstname.lastname.
I want to keep the YSOD, as well as the stack trace including the filename and line number (it's a demo and testing system), but the username should vanish from the sourcefile path. Seeing the file's path is also OK, but the path should be truncated at the solution root directory.
(without me having to copy-paste the solution every time to another path before publishing it...)
Is there any way to accomplish this ?
Note: Custom error pages aren't an option.
Path is embedded in .pdb files, which are produced by the compiler. The only way to change this is to build your project in some other location, preferably somewhere near the build server.
Never mind, I found it out myself.
Thanks to Anton Gogolev's statement that the path is in the pdb file, I realized it is possible.
One can do a binary search-and-replace on the pdb file, and replace the username with something else.
I quickly tried using this:
https://codereview.stackexchange.com/questions/3226/replace-sequence-of-strings-in-binary-file
and it worked (on 50% of the pdb files).
So mind the crap, that code-snippet in the link seems to be buggy.
But the concept seems to work.
I now use this code:
public static void SizeUnsafeReplaceTextInFile(string strPath, string strTextToSearch, string strTextToReplace)
{
byte[] baBuffer = System.IO.File.ReadAllBytes(strPath);
List<int> lsReplacePositions = new List<int>();
System.Text.Encoding enc = System.Text.Encoding.UTF8;
byte[] baSearchBytes = enc.GetBytes(strTextToSearch);
byte[] baReplaceBytes = enc.GetBytes(strTextToReplace);
var matches = SearchBytePattern(baSearchBytes, baBuffer, ref lsReplacePositions);
if (matches != 0)
{
foreach (var iReplacePosition in lsReplacePositions)
{
for (int i = 0; i < baReplaceBytes.Length; ++i)
{
baBuffer[iReplacePosition + i] = baReplaceBytes[i];
} // Next i
} // Next iReplacePosition
} // End if (matches != 0)
System.IO.File.WriteAllBytes(strPath, baBuffer);
Array.Clear(baBuffer, 0, baBuffer.Length);
Array.Clear(baSearchBytes, 0, baSearchBytes.Length);
Array.Clear(baReplaceBytes, 0, baReplaceBytes.Length);
baBuffer = null;
baSearchBytes = null;
baReplaceBytes = null;
} // End Sub ReplaceTextInFile
Replace firstname.lastname with something that has equally many characters, for example "Poltergeist".
Now I only need to figure out how to run the binary search and replace as a post-build action.

ado.net query removes file exention when adding string filename to the database

I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}
Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.
Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);

how do i get section target page number in pdf file using iTextSharp?

I have a pdf file which contains Index Page that includes section with target page.
I could get the section name(Section 1.1, Section 5.2) but i can not get the target page number...
For ex:
http://www.mikesdotnetting.com/Article/84/iTextSharp-Links-and-Bookmarks
Here is my code:
string FileName = AppDomain.CurrentDomain.BaseDirectory + "TestPDF.pdf";
PdfReader pdfreader = new PdfReader(FileName);
PdfDictionary PageDictionary = pdfreader.GetPageN(9);
PdfArray Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
if ((Annots == null) || (Annots.Length == 0))
return;
foreach (PdfObject oAnnot in Annots.ArrayList)
{
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(oAnnot);
if (AnnotationDictionary.Keys.Contains(PdfName.A))
{
PdfDictionary oALink = AnnotationDictionary.GetAsDict(PdfName.A);
if (oALink.Get(PdfName.S).Equals(PdfName.GOTO))
{
if (oALink.Keys.Contains(PdfName.D))
{
PdfObject objs = oALink.Get(PdfName.D);
if (objs.IsString())
{
string SectionName = objs.ToString(); // here i could see the section name...
}
}
}
}
}
How do i get the target page number?
also I couldn't access the Section name for some pdf ex: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/adobe_supplement_iso32000.pdf
In this PDF 9th page contains a section I could not get the section.
so please give me solution....
There's two possible types of Link Annotations, either A or Dest. The A is the more powerful type but is often overkill. The Dest type just specifies an indirect reference to a page along with some fitting and zooming options.
The Dest value can be a couple of different things but is usually (as far as I've ever seen) a named string destination. You can look up named destinations in the document's name destination dictionary. So before your main loop add this so that it can be referenced later:
//Get all existing named destinations
Dictionary<string, PdfObject> dests = pdfreader.GetNamedDestinationFromStrings();
Once you've got the Dest as a string you can look that object up as a key in the above dictionary.
PdfArray thisDest = (PdfArray)dests[AnnotationDictionary.GetAsString(PdfName.DEST).ToString()];
The first item in the array returned is the indirect reference that you're used to. (Actually, the first item could be an integer representing a page number in a remote document so you might have to check for that.)
PdfIndirectReference a = (PdfIndirectReference)thisDest[0];
PdfObject thisPage = PdfReader.GetPdfObject(a);
Below is code that puts most of the above together, omitting some of the code that you already have. A and Dest are mutually exclusive per the spec so no annotation should ever have both specified.
//Get all existing named desitnations
Dictionary<string, PdfObject> dests = pdfreader.GetNamedDestinationFromStrings();
foreach (PdfObject oAnnot in Annots.ArrayList) {
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(oAnnot);
if (AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK)) {
if (AnnotationDictionary.Contains(PdfName.A)) {
//...Do normal A stuff here
} else if (AnnotationDictionary.Contains(PdfName.DEST)) {
if (AnnotationDictionary.Get(PdfName.DEST).IsString()) {//Named-based destination
if (dests.ContainsKey(AnnotationDictionary.GetAsString(PdfName.DEST).ToString())) {//See if it exists in the global name dictionary
PdfArray thisDest = (PdfArray)dests[AnnotationDictionary.GetAsString(PdfName.DEST).ToString()];//Get the destination
PdfIndirectReference a = (PdfIndirectReference)thisDest[0];//TODO, this could actually be an integer for the case of Remote Destinations
PdfObject thisPage = PdfReader.GetPdfObject(a);//Get the actual PDF object
}
} else if(AnnotationDictionary.Get(PdfName.DEST).IsArray()) {
//Technically possible, I think the array matches the code directly above but I don't have a sample PDF
}
}
}
}

Virtual path exception in asp.Net

I have to save files to a physical folder. But i got the following exception. "The path is not a virtual path" How can i change a physical path to a virtual path. How can i solve this problem
Grades grade = new Grades();
grade.Exam = Exams.Search(ddlExam.SelectedValue);
grade.Person = Person.GetStudent(ddlStudent.SelectedValue);
try{
if (afuPaper.HasFile)
{
string strPath = Server.MapPath(grade.Exam.FileUrl) + ddlExam.SelectedValue +
grade.Person.TcNo + Path.GetFileName(afuPaper.FileName);
afuPaper.SaveAs(strPath); grade.GradeJpeg = strPath;
}
}
Grades grade = new Grades();
grade.Exam = Exams.Search(ddlExam.SelectedValue);
grade.Person = Person.GetStudent(ddlStudent.SelectedValue);
try
{
if (afuPaper.HasFile)
{
string strPath = Server.MapPath(grade.Exam.FileUrl) + ddlExam.SelectedValue + grade.Person.TcNo + Path.GetFileName(afuPaper.FileName);
afuPaper.SaveAs(strPath);
grade.GradeJpeg = strPath;
}
grade.Exam.FileUrl is a pyhsical path like C:\File\Paper1
Server.MapPath expects a virtual path and converts it to a physical path.
Assuming you require a physical path for SaveAs, then you can simply remove that call.
The MapPath method is used to convert a virtual path, such as "~/Location/File.aspx" to a physical path such as "C:\inetput\wwwroot\MyApplication1\Location\File.aspx"
EDIT: Modified code
try
{
if (afuPaper.HasFile)
{
string strPath = Path.Combine(grade.Exam.FileUrl, ddlExam.SelectedValue + grade.Person.TcNo + Path.GetFileName(afuPaper.FileName));
afuPaper.SaveAs(strPath);
grade.GradeJpeg = strPath;
}
Note that I also included a call to Path.Combine, which is the method of choice for combining a folder and file name (It will automatically add a \ if needed between FileUrl and whatever)

Resources