I use C# 4.0 and SQL Server 2008 R2 and I've a simple button click that call a function that save the data into database and redirect the page.
The probleme is when the client click more than one on this save button, then i save more than one item also into the database.
I want to avoid the client make a mistake, that meant the client can only do 1 clic = 1 save data.
<dx:ASPxButton ID="ASPxButton_save" runat="server" Image-Url="~/images/Icon/Good-or-Tick-icon.png" Text="Enregistrer" Width="110px" onclick="ASPxButton_save_Click" ValidationGroup="Savebouton">
</dx:ASPxButton>
protected void ASPxButton_save_Click(object sender, EventArgs e)
{
string ErrPos = "";
try
{
ErrPos = "Affct CP DEST";
string FA_Choisi = ASPxTextBox_CP_dest.Text.Substring(0, 2);
string CLIENT_de_FA = ClientId.Substring(0, 2);
List<string> ClotList_FA = new List<string>();
ErrPos = "Affct Trans";
foreach (DataRow myRow in oOrdre_BL.Get_Tranporteur(ClientId).Tables["Le_Transporter"].Rows)
{
ClotList_FA.Add(myRow["LIBELLE"].ToString());
}
Pers_Client_Entrp oPersclientEntrp = GetOPersclientEntrp();
Pers_Ordre oPersOrdr = new
.......
if (ASPxCheckBox_NewDesti.Checked)
{
string ResTemp = oDest_BL.Compare_Dest(ClientId, ASPxTextBox_Desti_ID.Text, ASPxTextBox_RS_NOM_dest.Text, ASPxTextBox_ADRESSE_dest.Text);
if (!String.IsNullOrWhiteSpace(ResTemp))
{
lbl_err.Text = ResTemp;
}
else
{
Pers_Dest TheDest = new Pers_Dest();
TheDest.CodeDest = ASPxTextBox_Desti_ID.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.CodeClient = ClientId;
TheDest.RaisonSoc = ASPxTextBox_RS_NOM_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Adresse = ASPxTextBox_ADRESSE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Cp = ASPxTextBox_CP_dest.Text;
TheDest.Ville = ASPxComboBox_VILLE_dest.Text;
TheDest.Pays = ASPxComboBox_PAYS_dest.Value.ToString();
TheDest.Tel = ASPxTextBox_TEL_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Fax = ASPxTextBox_FAX_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Email = ASPxTextBox_EMAIL_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Insee = ASPxTextBox_INSEE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
TheDest.Siret = ASPxButton_SIRET_dest.Text.Replace('-', ' ').Replace('\'', ' ');
oDest_BL.CrUp_Dest(TheDest, true);
oPersOrdr.Ville = ASPxComboBox_VILLE_dest.Text;
Save_Part(oPersOrdr, oPersclientEntrp, OrdreID);
}
}
else
{
oPersOrdr.Ville = ASPxTextBox_VILLE_dest.Text.Replace('-', ' ').Replace('\'', ' ');
Save_Part(oPersOrdr, oPersclientEntrp, OrdreID);
}
catch (Exception ex)
{
lbl_err.Text = ex.Message;
if (ex.InnerException != null) { lbl_err.Text += "-->" +ex.InnerException.Message; }
Outils_IHM.SendingEmail("Save Odre --> Err Position: " + ErrPos + "-----" + lbl_err.Text, ClientId);
}
private void Save_Part(Pers_Ordre oPersOrdr, Pers_Client_Entrp oPersclientEntrp, string OrdreID)
{
oOrdre_BL.SaveUpdt_Ordre_BL(oPersOrdr, OrdreID);
string QuelleID = TempId;
if (!String.IsNullOrWhiteSpace(OrdreID))
{ QuelleID = OrdreID; }
if (oPersclientEntrp.TypPrint == "Zebra")
{ Response.Redirect("../Print/BonEticket_Web.aspx?ConnPrint=UnDirect&OdreID=" + QuelleID + "&CountOrdre=" + ASPxTextBox_NBR_COLIS.Text + "&TypeAR=" + TypeEnlev, false); }
else
{ Response.Redirect("../Print/BonEticket_Web.aspx?OdreID=" + QuelleID + "&CountOrdre=" + ASPxTextBox_NBR_COLIS.Text + "&TypeAR=" + TypeEnlev, false); }
Context.ApplicationInstance.CompleteRequest();
}
I have an idea, when the user clic this button, than it will call client side function to disable it. But i don't know how and if it work as i want to.
you can use the below mentioned code as ref.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
var submit = 0;
function CheckIsRepeat() {
if (++submit > 1) {
alert('An attempt was made to submit this form more than once; this extra attempt will be ignored.');
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="return CheckIsRepeat();" />
</div>
</form>
</body>
</html>
Before saving data to database disbale the button , then save the data, then clear the controls & then again enable the button.
<dx:ASPxButton ID="ASPxButton_save" runat="server" Image-Url="~/images/Icon/Good-or-Tick-icon.png" Text="Enregistrer" ClientInstanceName="ASPxButton_save" Width="110px" onclick="ASPxButton_save_Click" ValidationGroup="Savebouton">
<ClientSideEvents Click ="function(s,e) { MyBtnClick(s,e); } " />
</dx:ASPxButton>
function MyBtnClick(s, e) {
if (ASPxClientEdit.AreEditorsValid())
ASPxButton_save.SetVisible(false);
}
Related
First attempt at this: I created the Windows Media Player programmatically by adding the WMPLib as a reference in my project. I am trying to play a playlist using Windows Media Player in a ASP.Net web page (Visual Studio 2015). I cannot use the video tag used in examples for HTML 5 as I need to display .wmv, .mp4, .jpg formats in the control. When I run the code, no errors are displayed and I see an empty browser, what am I missing?
Here is my sample code:
WMPLib.WindowsMediaPlayer Player;
protected void Page_Load(object sender, EventArgs e)
{
FileNames();
}
public void FileNames()
{
String[] extentions = { "*.wmv", "*.mp4", "*.jpg" };
List<string> files = new List<string>();
foreach (string filter in extentions)
{
files.AddRange(System.IO.Directory.GetFiles(#"C:\Documents\", filter));
}
foreach (string ss in files)
{
String name = System.IO.Path.GetFileName(ss);
Player = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPPlaylist playList = Player.newPlaylist("myPlayList", "");
playList.appendItem(Player.newMedia(name));
Player.currentPlaylist = playList;
Player.controls.play();
}
}
I am aware of the hard coded path which is not good practice, however I just need to get this displaying on my local machine.
Thanks!
After two more weeks of research we managed to come up with a solution by toggling between different types of controls based on the content that needs to be displayed. To display PowerPoint slideshows, we converted all slides to images and then looped through the collection. Here is a snippet of the code in case someone else needs a bit of guidance with a similar issue:
<body>
<form id="form1" runat="server">
<%-- Video DIV --%>
<div runat="server" id="VidDiv" class="fullscreen-bg">
</div>
<%-- IMAGE DIV --%>
<div runat="server" id="container">
<div runat="server" id="containers">
</div>
<%-- this is where the code gets dynamically created --%>
</div>
</form>
</body>
<script src="Scripts/jquery-3.1.1.js"></script>
<script id="CallMyFunction" type="text/javascript">
var index = 1;
document.getElementById("VidDiv").style.display = "none";
var ImageCount = 1;
autoSlide();
function autoSlide() {
var x = document.getElementsByClassName("Images");
var video_player = document.getElementsByClassName("fullscreen-bd__video");
var count;
var video;
var videoSource = new Array(), vids, i;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
if (index > x.length) {
index = 1
}
x[index - 1].style.display = "block";
count = x.length;
if (ImageCount <= count) {
index++;
ImageCount = 1 + ImageCount;
setTimeout(autoSlide, 8000);
}
else {
//this is where we should switch from image div to video div
document.getElementById("container").style.display = "none";
document.getElementById("VidDiv").style.display = "block";
//create a counter to check the number of video tags
video = document.getElementsByTagName('video'), numVideos = video.length;
for (i = 0; i < numVideos; i++) {
videoSource[i] = video.item(i).src;
document.getElementById("myVideo" + i).style.display = "none";
}
var videoCount = 0;
if (videoCount <= numVideos -1) {
function videoPlay(videoNum) {
if (videoCount > 0)
{
document.getElementById("myVideo" + (videoCount - 1)).style.display = "none";
}
document.getElementById("myVideo" + videoCount).style.display = "block";
document.getElementById("myVideo" + videoCount).setAttribute("src", "" + videoSource[videoCount] + "");
document.getElementById("myVideo" + videoCount).load();
document.getElementById("myVideo" + videoCount).play();
onEndedVid = document.getElementById("myVideo" + videoCount);
var onEndedVid;
onEndedVid.onended = function () {
//at the end of the video, close full screen
myHandler();
};
videoCount = videoCount + 1;
}
function myHandler() {
if (videoCount == numVideos) {
//this is where we should switch from image div to video div
document.getElementById("container").style.display = "none";
document.getElementById("VidDiv").style.display = "none";
location.reload();
}
else {
videoPlay(videoCount);
}
}
myHandler();
}
else
{
///back to images
//refresh the page
location.reload();
}
}
}
Code behind:
// this will be a watcher that checks if is new content... if there is, delete the existing .wpl file and recreate the .wpl with new content links included
private void CreateNewPlayList(string folder)
{
try
{
System.Threading.Thread.Sleep(5000);
fileName = getDrive(folder) + #"\" + folder + "Playlist.wpl";
FileInfo fileInfo = new FileInfo(fileName);
String f = #"<?wpl version=""1.0""?>
<smil>
<head><meta name=""Generator"" content=""Microsoft Windows Media
Player -- 10.0.0.3646""/>
<author/>
<title> a title goes here </title>
</head>
<body>
<seq> ";
String ff = #"
</seq>
</body>
</smil>";
using (FileStream fs = fileInfo.Create())
{
Byte[] txt = new UTF8Encoding(true).GetBytes(f);
fs.Write(txt, 0, txt.Length);
////write paths and load only certain file types according to requirements into array
String[] extentions = { "*.mp4", "*.wmv", "*.JPG".ToLower(), "*.ppt", "*.png" };
List<string> files = new List<string>();
foreach (string filter in extentions)
{
files.AddRange(System.IO.Directory.GetFiles(getDrive(folder) + #"\", filter));
}
int filecount = files.Count;
string[] video_lists = new string[files.Count];
int counts = 0;
foreach (string file in files)
{
video_lists[counts] = file.ToString();
string PathfileName = Path.GetFileName(file);
Byte[] author;
//use the ppt to be able to go into the folder and add each slide as part of the playlist
if (Path.GetExtension(PathfileName) == ".ppt" || Path.GetExtension(PathfileName) == ".pptx")
{
//create a loop to loop through the folder that has the same name as ppt/pptx(PathFileName)
string pptDrive = getDrive(folder) + #"\" + Path.GetFileNameWithoutExtension(PathfileName) + #"\";
if (Directory.Exists(pptDrive))
{
string[] pptFilesFolder = Directory.GetFiles(pptDrive);
int counter = 1;
while (counter <= pptFilesFolder.Length)
{
foreach (string pptFile in pptFilesFolder)
{
string pptFileName = Path.GetFileName(pptFile);
string pptFileNameNoExt = Path.GetFileNameWithoutExtension(pptFile);
int i = pptFilesFolder.Length;
int ss = Convert.ToInt16(new String(pptFileNameNoExt.Where(Char.IsDigit).ToArray()));
if (ss <= i && ss == counter)
{
author = new UTF8Encoding(true).GetBytes(#"<media src=""" + pptDrive + #"\" + pptFileName + "\"/>");
fs.Write(author, 0, author.Length);
counter++;
}
}
}
}
else
{
//do something...
}
}
else
{
author = new UTF8Encoding(true).GetBytes(#"<media src=""" + getDrive(folder) + #"\" + PathfileName + "\"/>");
fs.Write(author, 0, author.Length);
}
counts = counts + 1;
}
Byte[] toptxt = new UTF8Encoding(true).GetBytes(ff);
fs.Write(toptxt, 0, toptxt.Length);
}
}
catch (IOException io)
{
//error handling....
return;
}
catch (Exception ex)
{
//error handling...
return;
}
}
The code can obviously be improved and optimized, but this is the base we used to get our app working. Thanks for all the advice and input!
when i click on link button for adding more file upload then this add only 1 .. means 1 file upload which is already visible and 1 which is display on clicking on linkbutton ..
but when i click again on linkbutton for adding more then this not display ..
i try this
ok i do this
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">upload</asp:LinkButton><br />
<asp:Panel ID="Panel1" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="submit" OnClick="Button1_Click" />
</form>
suppose there is file upload control.. when we select file by clicking on browse and then click on upload then file name with extension i.e. abc.doc should be display ... then when we use again same file upload and click on browse and select another file then file will be display i.e. xyz.pdf.. so there is two files abc.doc and xyz.doc .. so this is want to do .. i want to upload files and display these uploaded files
UPDATE
for this i try this
protected void LinkButton1_Click(object sender, EventArgs e)
{
fileuploadd(FileUpload1.FileName);
}
public void fileuploadd(string filename)
{
try
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
SMSEntities s = new SMSEntities();
uploaded_file u = new uploaded_file();
{
u.fileupload = filename;
}
s.uploaded_file.Add(u);
s.SaveChanges();
}
//hpf.SaveAs(Server.MapPath("upload") + "\\" + System.IO.Path.GetFileName(hpf.FileName));
Response.Write("<b>File: </b>" + hpf.FileName + " <b>Size:</b> " + hpf.ContentLength + " <b>Type:</b> " + hpf.ContentType + " Uploaded Successfully <br/>");
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
so when i select file and click on upload then file name is display .. but when i select again file and click on upload then 1st file name is disappear and 2nd file name is display where as i want both ..
so how i display both filenames ... and when click on submit then record files should be inserted in tables individually i am done with this but not with both filename display at a time ..
Create a FileUpload Control on your .aspx like:
<asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true" />
then in your code behind:
protected void uploadFile_Click(object sender, EventArgs e)
{
if (UploadImages.HasFiles)
{
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
uploadedFile.SaveAs(System.IO.Path.Combine(Server.MapPath("~/Images/"),
uploadedFile.FileName)); listofuploadedfiles.Text += String.Format("{0}<br />", uploadedFile.FileName);
}
}
}
Multiple File Upload
HI Super User Previously I also had same Problem.
What i Actually did was I have Created 5 File Control's For Example
1) FileUpload1
2) FileUpload2
3) FileUpload3
4) FileUpload4
5) FileUpload5
And I have 4 of them as Hidden on load.
On click of 1 st I am showing 2nd One and on click of 2nd I am showing the 3rd one and So on...
In the Controller/Method I am checking if the File Control is not null then proceeding with the normal File Upload Process By taking Array of File Uploads.
<div id="flOther" runat="server">
<div id="fileOtherUploadarea">
<asp:FileUpload ID="flOtherUPL" runat="server" />
</div>
<input style="width: 20px; border: 0px none; background-color:transparent;" id="btnOtherAddMoreFiles" type="button" onclick="AddOtherMoreImages();" class="icon-plus-sign" />|
<asp:LinkButton ID="lnkOtherUpload" OnCommand="btnLnk_UploadOtherFiles" CommandArgument='<%# Eval("ID") %> 'runat="server">Upload Files</asp:LinkButton>
</div>
<script language="javascript" type="text/javascript">
function AddMoreImages() {
if (!document.getElementById && !document.createElement)
return false;
var fileUploadarea = document.getElementById("fileUploadarea");
if (!fileUploadarea)
return false;
var newLine = document.createElement("br");
fileUploadarea.appendChild(newLine);
var newFile = document.createElement("input");
newFile.type = "file";
newFile.setAttribute("class", "fileUpload");
if (!AddMoreImages.lastAssignedId)
AddMoreImages.lastAssignedId = 100;
newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
var div = document.createElement("div");
div.appendChild(newFile);
div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
fileUploadarea.appendChild(div);
AddMoreImages.lastAssignedId++; }
</script>
protected void btnLnk_UploadOtherFiles(object sender, CommandEventArgs e)
{
int ID;
try
{
if (!String.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
ID = Convert.ToInt32(e.CommandArgument);
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(hpf.FileName);
if (ValidExtesion(fileExtension))
{
int MaxSizeAllowed = Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]);
if (hpf.ContentLength < MaxSizeAllowed)
{
int lastIndex = Convert.ToInt32(hpf.FileName.LastIndexOf("\\"));
string FileName = DateTime.Now.Millisecond + hpf.FileName.Substring(lastIndex + 1);
string FileName1 = hpf.FileName.Substring(lastIndex + 1);
FileName = FileName.Replace(" ", "");
StringBuilder AncTag = new StringBuilder();
AncTag = AncTag.Append("<a href='Attachments/AMT/'" + FileName + "' target='_blank'>'" + FileName1 + "' </a>");
string strAncTag = AncTag.ToString();
strAncTag = strAncTag.Replace("'", "");
hpf.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "Attachments/AMT/" + FileName);
obj.UploadOtherFiles_ProblemDescription(ID, strAncTag);
}
else
{
}
}
else
{
}
}
}
}
}
catch (Exception ex)
{
ErrorLog objER = new ErrorLog(ex);
}
finally
{
obj = null;
grdPDC.EditIndex = -1;
}
}
I want to upload the image to web server file and get the path and save it to database.
HTML and Javascript
<img id="imgDisplay" alt="" src="" style="display: none" class="img-thumbnail" />
<ajaxToolkit:AsyncFileUpload OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" UploaderStyle="Traditional" CompleteBackColor="White" UploadingBackColor="#CCFFFF"
ThrobberID="imgLoader" OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />
<asp:Image ID="imgLoader" runat="server" ImageUrl="~/Images/loader2.gif"
Height="21px" Width="23px" />
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
}
</script>
C# code behind, event file upload complete
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
}
With code above, I success to do it... But the problem become when I want to rename the file with GUID, the image not appear after upload.
C# code behind
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
}
I realize in the javascript, it will refer to agrs from file upload control. So that means it cannot refer the new file name.
Javascript
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
So I google to find how to paste a value from code behind to javascript. And I found it. Then modified my behind code something like this
protected string UploadFolderPath = "~/Images/";
protected string image = "";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
image = this.ResolveUrl(this.UploadFolderPath) + file_id + filename;
}
And the javascript
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(image) %>";
}
</script>
Still not appear because the image variable not have a value inside it. How to solved this?
Sorry for my bad english
Nothing issue with your codes, the only problem i see is that since you edited the path you must revert it back to the original values if you retrieve it unless no image will show.
aspx code for fileupload
<ajax:asyncfileupload id="Asyncfileupload1" onclientuploadcomplete="uploadComplete1"
width="350px" runat="server" uploaderstyle="Traditional"
throbberid="Image6" onuploadedcomplete="Asyncfileupload1_UploadedComplete" />
javascript function
function uploadComplete1()
{
window.location = window.location.href;
}
aspx.cs code
protected void Asyncfileupload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
string name = Asyncfileupload1.FileName;
string[] spi = name.Split('.');
int len = spi.Length;
string type = spi[len - 1];
if (type == "apk" || type == "ipa")
{
if (Asyncfileupload1.PostedFile.ContentLength > 10)
{
string filename = System.IO.Path.GetFileName(Asyncfileupload1.FileName);
string ext = Path.GetExtension(filename);
string newfilename = Path.GetRandomFileName();
newfilename += ext;
Asyncfileupload1.SaveAs(Server.MapPath("~/product_application/") + newfilename);
MobileStoreEntities mse = new MobileStoreEntities();
ProductMast um = new ProductMast();
int loginid = Utility.login_id();
um = mse.ProductMasts.Where(i => i.ProductID == proid).FirstOrDefault();
um.ApplicationFile = "~/product_application/" + newfilename;
int check1 = mse.SaveChanges();
lblDoc.Text = "Old file is available. Want to change? Then Upload";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Size problem." + "');", true);
}
//Response.Redirect("ProductFileUpload.aspx?proid="+HttpUtility.UrlEncode(enc));
//Response.Redirect("ProductFileUpload.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Must upload doc, docx or pdf file." + "');", true);
}
}
i am printing a gridview in asp.net that is contained within a panel - it works in IE perfectly
In Opera 12.02 it appears to be printing out my main form not the print page ? Do you know why this is.
In Mozilla firefox 16.0.2 it only loads one page in the print preview and prints that one page? Do you know why this is?
I'm assuming the issue is in my javascript - i can post markup if needed but hopefully that will not be required.
thanks
Damo
javascript
<script type="text/javascript">
function PrintGridData(GridToPrint, PanelName) {
try {
var Grid = document.getElementById(GridToPrint);
var printContent = document.getElementById(PanelName);
//alert(printContent);
if (Grid) // See if the Grid Exists First
{
if (Grid.rows.length > 0) { // See if the Grid contains any rows
var windowUrl = 'about:blank';
var UserLoggedIn = $("#lblUser").text()
var now = new Date();
var strDateTime = [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(now.getHours()), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
var Database = 'ProductionDatabase';
var windowName = 'Report';
var AuditPrintDetailEverypage = UserLoggedIn + ' Time : ' + strDateTime ;
var AuditPrintDetailLastPage = ' System Report ' + ' Source Database: ';
var WinPrint = window.open(windowUrl, windowName, 'left=300,top=300,right=500,bottom=500,width=1000,height=500');
WinPrint.document.write('<' + 'html' + '><head><link href="assets/css/Print.css" rel="stylesheet" type="text/css" /><title>' + AuditPrintDetailEverypage + '</title> </head><' + 'body style="background:none !important"' + '>');
WinPrint.document.write(printContent.innerHTML);
WinPrint.document.write(' ' + AuditPrintDetailLastPage);
WinPrint.document.write('<' + '/body' + '><' + '/html' + '>');
WinPrint.document.close();
//alert(printContent.innerHTML);
//alert(WinPrint.document);
if (window.opera) {
//alert('opera browser detected')
window.onload = window.print();
//window.onload = WinPrint.print();
//WinPrint.close();
}
else {
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
}
else { // No Results to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Results to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
}
}
else { // No Grid to print
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = 'You have no Grid to print. Please run a report.';
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
function AddZero(num) {
try {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
catch (err) {
//alert(err);
document.getElementById('lblErrorCode').innerHTML = '-1';
document.getElementById('lblErrorMessage').innerHTML = err;
document.getElementById('lblExMessage').innerHTML = '-1';
var modal = $find("modalPopupExtenderError");
modal.show();
return;
}
}
</script>
window.onload = window.print(); should be window.onload = window.print;
Also my css had overflow: hidden; which opera and mozilla dont like so i removed these
now its working ok
thanks
damo
I have been trying to sort this issue for the whole day so far I have no luck. I have a Web Form which has some asp.net form controls and Two AsyncFileUpload controls. When I upload the image using first AsyncFileUpload1, it uploads only one image and when I upload the second image using AsyncFileUpload2 it uploads two versions of the same image.
Things go crazy when I click the Save Button to save data it then upload 3 more version of the images in total sometime 6 or more. I have tried different way and have finally given up.
Sample code in HTML FILE
<script type = "text/javascript">
function uploadComplete(sender) {
// $get("<%=lblImageUploadMessage1.ClientID%>").innerHTML = "File Uploaded Successfully";
// $get("<%=lblImageUploadMessage2.ClientID%>").innerHTML = "File Uploaded Successfully";
clearContents();
clearContents2();
}
function uploadError(sender) {
// $get("<%=lblImageUploadMessage1.ClientID%>").innerHTML = "File upload failed. only Image files are allowed";
// $get("<%=lblImageUploadMessage2.ClientID%>").innerHTML = "File upload failed. only Image files are allowed";
clearContents();
}
</script>
<script type = "text/javascript">
function clearContents() {
var span = $get("<%=AsyncFileUpload1.ClientID%>");
var txts = span.getElementsByTagName("input");
for (var i = 0; i < txts.length; i++) {
if (txts[i].type == "text") {
txts[i].value = "";
}
}
}
function clearContents2() {
var span = $get("<%=AsyncFileUpload2.ClientID%>");
var txts = span.getElementsByTagName("input");
for (var i = 0; i < txts.length; i++) {
if (txts[i].type == "text") {
txts[i].value = "";
}
}
}
window.onload = clearContents;
</script>
<div class="row">
<asp:Label ID="lblPageTitleE" CssClass="txtLabel" runat="server" Text="Page Title (E) :"></asp:Label>
<asp:TextBox ID="txtPageTitleE" runat="server" CssClass="txtbox700"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVPageTitleE" runat="server" ErrorMessage="*"
ControlToValidate="txtPageTitleE" ValidationGroup="atpAddNewPage" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblPageTitleA" CssClass="txtLabel" runat="server" Text="Page Title (A) :"></asp:Label>
<asp:TextBox ID="txtPageTitleA" runat="server" CssClass="txtbox700"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVPageTitleA" runat="server" ErrorMessage="*"
ControlToValidate="txtPageTitleA" ValidationGroup="atpAddNewPage" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<!-- Image Control -->
<div class="row">
<asp:Label ID="lblBannerImageE" CssClass="txtLabel" runat="server" Text="Banner Image (E) :"></asp:Label>
<asp:AsyncFileUpload OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
runat="server" ID="AsyncFileUpload1" UploaderStyle="Modern" CompleteBackColor="White"
UploadingBackColor="#336699" ThrobberID="imgLoader" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" CssClass="AFU2" Width="400px" />
<asp:Label ID="lblImageUploadMessage1" CssClass="imgLabel" runat="server" Text=""></asp:Label>
<asp:Image ID="imgLoader" runat="server" ImageUrl="~/images/ajax-loader-small.gif" />
</div>
<div class="row">
<asp:Label ID="lblBannerImageA" CssClass="txtLabel" runat="server" Text="Banner Image (A) :"></asp:Label>
<asp:AsyncFileUpload OnClientUploadError="uploadError" OnClientUploadComplete="uploadComplete"
runat="server" ID="AsyncFileUpload2" UploaderStyle="Modern" CompleteBackColor="White"
UploadingBackColor="#336699" ThrobberID="imgLoader2" OnUploadedComplete="AsyncFileUpload2_UploadedComplete" CssClass="AFU2" Width="400px" />
<asp:Label ID="lblImageUploadMessage2" CssClass="imgLabel" runat="server" Text=""></asp:Label>
<asp:Image ID="imgLoader2" runat="server" ImageUrl="~/images/ajax-loader-small.gif" />
</div>
<!-- Image Control -->
Below is the sample code of .CS file
In this file i am assigning each image unique name using GUID and image upload AsyncFileUpload code gets execute multiple times and i am not able to figure out i am so confused now.
public partial class _Default : System.Web.UI.Page
{
String BannerImageNameEn, BannerImageNameAr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Session["BannerImageNameEn"] = "Null";
//Session["BannerImageNameEn"] = "Null";
}
}
protected void btnCreatePage_Click(object sender, EventArgs e)
{
BusinessLogic objBLAddNewPage = new BusinessLogic();
Pages objPages = new Pages();
objPages.PageNameEn = txtPageNameE.Text;
objPages.PageNameAr = txtPageNameA.Text;
objPages.PageTitleEn = txtPageTitleE.Text;
objPages.PageTitleAr = txtPageTitleA.Text;
objPages.PageDescEn = txtPageDescE.Text;
objPages.PageDescAr = txtPageDescA.Text;
objPages.PageKeywordEn = txtPageKeywordsE.Text;
objPages.PageKeywordAr = txtPageKeywordsA.Text;
objPages.PageBodyEn = CKEditorPageBodyE.Text;
objPages.PageBodyAr = CKEditorPageBodyA.Text;
objPages.PageLinkPositionNo = int.Parse(txtPageLinkPosition.Text);
objPages.PageLayoutPosition = ddPageLayoutPosition.SelectedItem.Value.ToString();
// Assign Name to Images
objPages.PageBannerImageEn = Session["BannerImageNameEn"].ToString();
objPages.PageBannerImageAr = Session["BannerImageNameAr"].ToString();
objPages.PageBannerLinkEn = txtBannerLinkEnglish.Text;
objPages.PageBannerLinkAr = txtBannerLinkArabic.Text;
objPages.PageWindow = ddPageWindow.SelectedItem.Value.ToString();
objPages.PageActive = bool.Parse(ddPageActive.SelectedItem.Value.ToString());
objPages.PageVisible = bool.Parse(ddPageHidden.SelectedItem.Value.ToString());
objPages.PageCreateDate = Helper.GetUAEDateTime();
objPages.PageUpdateDate = Helper.GetUAEDateTime();
objPages.PageIPAddress = Request.ServerVariables["REMOTE_ADDR"];
try
{
bool result;
//result = objBLAddNewPage.CreateNewPage(objPages);
result = false;
if (result == true)
{
Response.Redirect("PageCreated.aspx");
}
else
{
}
}
catch (Exception ex)
{
//lblresult.Text = ex.ToString();
}
}
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
try
{
String filePath = string.Empty;
String CurrentGUID = Guid.NewGuid().ToString();
if (AsyncFileUpload1.HasFile)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
System.IO.FileInfo f = new System.IO.FileInfo(AsyncFileUpload1.PostedFile.FileName);
int fileSize = Int32.Parse(System.IO.Path.GetFileName(e.FileSize));
if (fileSize < 1024000) // 1 MB current size size in bytes 102400=100kb 512000 = 500kb
{
if ((f.Extension.ToLower() == ".jpg") || (f.Extension.ToLower() == ".png") || (f.Extension.ToLower() == ".gif") || (f.Extension.ToLower() == ".jpeg"))
{
filename = CurrentGUID + f.Extension;
//string productGUID
filePath = Server.MapPath("../ImageUploads/") + filename;
if (System.IO.File.Exists(filePath))
{
return;
}
else
{
//Upload files
AsyncFileUpload1.PostedFile.SaveAs(Server.MapPath("../ImageUploads/") + filename);
Session["BannerImageNameEn"] = filename.ToString();
string errMsg = "File Uploaded Successfully";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
// ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
Helper.ResizeImage(filePath, filePath, 150, 80, true);
}
return;
}
}
else
{
lblImageUploadMessage1.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File must be an Image type of .jpg, .png, .gif, .jpeg";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
else
{
//lblMesg.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File size is greater the 1MB";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage1.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
catch (Exception ex)
{
}
}
protected void AsyncFileUpload2_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
try
{
String filePath = string.Empty;
String CurrentGUID = Guid.NewGuid().ToString();
if (AsyncFileUpload1.HasFile)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
System.IO.FileInfo f = new System.IO.FileInfo(AsyncFileUpload1.PostedFile.FileName);
int fileSize = Int32.Parse(System.IO.Path.GetFileName(e.FileSize));
if (fileSize < 1024000) // 1 MB current size size in bytes 102400=100kb 512000 = 500kb
{
if ((f.Extension.ToLower() == ".jpg") || (f.Extension.ToLower() == ".png") || (f.Extension.ToLower() == ".gif") || (f.Extension.ToLower() == ".jpeg"))
{
filename = CurrentGUID + f.Extension;
//string productGUID
filePath = Server.MapPath("../ImageUploads/") + filename;
if (System.IO.File.Exists(filePath))
{
return;
}
else
{
//Upload files
AsyncFileUpload2.PostedFile.SaveAs(Server.MapPath("../ImageUploads/") + filename);
Session["BannerImageNameAr"] = filename.ToString();
string errMsg = "File Uploaded Successfully";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
// ResizeImage(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)
Helper.ResizeImage(filePath, filePath, 150, 80, true);
}
return;
}
}
else
{
lblImageUploadMessage1.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File must be an Image type of .jpg, .png, .gif, .jpeg";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
else
{
//lblMesg.Text = "Only type .jpg, .png, .gif are allow";
string errMsg = "File size is greater the 1MB";
//client-side error
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "size", "top.$get(\"" + lblImageUploadMessage2.ClientID + "\").innerHTML='" + errMsg + "';", true);
return;
}
}
catch (Exception ex)
{
}
}
}
I simply want a functionality where i can upload two images assign them unique name using GUID and finally same the image name along with the other form data in the database.
I am using ASP.NET, C# 3.0 and Framework 4, Latest version of Ajax downloaded today And i have to do assignment in ASP.Net only