How to work with ImageButton in code behind in C# - c#

protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string path = Server.MapPath("~//Images//" + FileName);
FileUpload1.SaveAs(path);
string imagepathsource = path;
string imagepathdest = #"D:\\" + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
File.Move(imagepathsource, imagepathdest);
uploadedimage.ImageUrl = "D://" + Session["brandname"].ToString() + "//" + Seasonfolders.SelectedItem.Text + "//" + stylefolders.SelectedItem.Text + "//Images//" + FileName;
}
}
uploadedimage is a ImageButton where I need to display the image using imageurl with that link. The image is not displaying and no error.. I could see when the above code gets execute the page is getting refreshed? What code can be added in this ??

ImageUrl needs an URL.
So instead of assigning it with a local file name on disk, use something like this (where ~ stands for 'application root folder':
uploadedimage.ImageUrl = "~/Images/yourImage.png"
You have to supply it with:
An image inside your application root folder;
An URL that is catched by a HttpHandler, that generates / loads the image from a different location (a little harder to do, but if you need to load from another location then inside application root, this is the best option).

Related

Paypal sandbox url opens my documents

I've been encountering a problem when I click on the button that should redirect to paypal it opens my documents. It was running before but when I transferred the codes to another PC the error occurs. Help!
Here is the code in aspx.cs
protected void btnPayOnline_Click(object sender, EventArgs e)
{
string url = "";
string business = "business#yahoo.com";
string description = "Buy";
string country = "PH";
string currency = "PHP";
string amount = Label1.Text;
url += "https://www.sandbox.paypal.com/cgi-bin/webscr" +
"?cmd=" + "_xclick" +
"&business=" + business +
"&amount=" + amount +
"&lc=" + country +
"&item_name=" + description +
"&currency_code=" + currency +
"&bn=" + "PP%2dBuyNowBF";
System.Diagnostics.Process.Start("explorer.exe", url);
}
Here is the aspx codes:
I really dont see what the problem is
Your program starts the folder explorer (thus showing your default local directory), not your web browser.
Replacing explorer.exe by iexplore.exe should solve your issue.

How to Apply css to webbrowser.documentText and print the html with the applied css?

I have a asp.net mvc web app that has a controller which has an action that returns html to a windows forms client.
The html that is returned gets printed.
This works perfectly and the html looks like the following:
NOTE that the html is always diffirent.
I designed the html with the help of bootstrap and some other custom css (including inline styles).
As shown above there are stylsheets being linked in to the html.
I haven't been able to figure out how to apply this css to the webBrowser.DocumentText.
With the help of google I found that I have to find the file and link it from there and here is my attempt:
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var document = ((WebBrowser) sender);
string content = document.DocumentText;
char separator = Path.DirectorySeparatorChar;
string startupPath = AppDomain.CurrentDomain.BaseDirectory;
string[] pathItems = startupPath.Split(separator);
string projectPath = string.Join(separator.ToString(),
pathItems.Take(pathItems.Length - 4));
string file = Path.Combine(projectPath, "\\IautmationWeb\\Content\\bootstrapSmall.css");
content = content.Replace("<link href='/Content/bootstrapSmall.css' rel=stylesheet'/>", "<link href='" + projectPath + file + "'rel='stylesheet'/>");
document.DocumentText = content;
// add css ... how?
// print...implemented
for (int i = 0; i < copies; i++)
{
document.Print();
}
((WebBrowser)sender).Dispose();
}
This doesn't work. What am I doing wrong?
EDIT:
after some info from #Peter B I tried:
content = content.Replace("href='/Content/bootstrapSmall.css'", "href='" + file + "'");
document.DocumentText = content;
But the replace method is still not doing what I want it to do:
EDIT:
Thanks to #Peter B
I managed to navigate to the files.
string file = Path.Combine(projectPath, "\\IautmationWeb\\Content\\bootstrapSmall.css");
string fileTwo = Path.Combine(projectPath, "\\IautmationWeb\\Content\\Automation.css");
string fileThree = Path.Combine(projectPath, "\\IautmationWeb\\Content\\octicons.css");
content = content.Replace("href=\"/Content/bootstrapSmall.css\"", "href='" + projectPath + file + "'");
content = content.Replace("href=\"/Content/Automation.css\"", "href='" + projectPath + fileTwo + "'");
content = content.Replace("href=\"/Content/octicons.css\"", "href='" + projectPath + fileThree + "'");
document.DocumentText = content;
how the html looks now:
You seem to get the quotes wrong, a ' is not the same as a ".
Try this:
content = content.Replace("href=\"/Content/bootstrapSmall.css\"", "href='" + file + "'");
For the 2nd parameter it doesn't really matter which quotes you use, but for the 1st parameter it does.

C# file not saving on correct folder

I Need save the txt file on a correct create folder. But its saving on C:\Nova Pasta i need save on "C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text whats is wrong ?
private void btn_SaveFile_Click(object sender, EventArgs e)
{
objSQL.Search_RGP_CadastroPrint(Convert.ToInt32(comboBox1.Text), str_list);
objSQL.SearchPrint(Convert.ToInt32(comboBox1.Text));
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
file.WriteLine("---------------------------------------------------------------------------------------------------------");
file.WriteLine("Nome: " + valor.retorna_nome);
file.WriteLine("RGP: " + comboBox1.Text);
file.WriteLine("Endereço: " + valor.retorna_endereco);
file.WriteLine("Telefone: " + valor.retorna_telefone + " Celular: " + valor.retorna_celular + "\r\n");
str_list.ForEach(file.WriteLine);
file.Close();
}
Say valor.retorna_nome is "hello", and comboBox1.Text is "world". Your code does the following:
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
// -> path = "C:\Nova pasta\helloworld"
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// -> created directory "C:\Nova pasta\helloworld"
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
// -> writes to file "C:\Nova pasta\helloworld.txt"
So it's doing exactly what you told it to. What would you like the directory to be called? And the filename?
Your String path is equals to something like that : "C:\Nova pasta\aNameXXX"
where :
aName = valor.retorna_nome
XXX = Combobox1.Text
You create a directory, this must success, but after that your file path is :
path+.txt : "C:\Nova pasta\aNameXXX.txt"
it's creating a file named (aNameXXX.txt) next to your folder.
you need to add an "\" and a name to your file to make a path like : "C:\Nova pasta\aNameXXX\FILENAME.txt"
StreamWriter file = new System.IO.StreamWriter(path + "\" + FILENAME + ".txt");

Upload File attached to FileUpload Control to FTP C#

I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));

how upload image to folder and display it

I try to upload image to folder (using FileUpload) by pressing one submit button to whole form. i manage to upload the image to separate folders but i can't display it.
thank you.
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(".") + "\\images\\" + ulProj.groupCode;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
Directory.CreateDirectory(path);
fname = path + "\\" + tempFU.FileName;
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;
}
catch
{
//return;
}
Points to remember:
you should use tilde ~ operator to represent the current project
root folder.
use System.IO.Path.Combine() to combine your path and filename to get the valid complete path.
you are creating the Directory for the given path 2 times. so remove the later part where you are creating the Directory 2'nd time.
as said in the above comments as your catch block is not having anycode,
remove the try-catch block
Complete Solution:
String fname;
FileUpload tempFU = new FileUpload();
string path = Server.MapPath(#"~\images\" + ulProj.groupCode);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
tempFU = (FileUpload)customerUC.FindControl("CustomerLogoUrlFU");
fname = System.IO.Path.Combine(path,tempFU.FileName);
tempFU.SaveAs(fname);
tempCus.logoUrl = fname;

Categories