Throw error message on kendo upload after wrong columns in aspx - asp.net

I am using kendo upload to upload a file to my server and write the data to db
$('#files').kendoUpload({
async: {
saveUrl: 'test.aspx/ImportExcel'
},
dropZone: '.drop-zone',
multiple: true,
clear: function () {
},
complete: function(){
//This is called when all files are uploaded
},
In back-end aspx i read the excel save it to a datatable and i want to check if the datatable has 3 columns its ok and write the columns in the database else throw a message to the user that the excel is not in the correct format..How can i do this?
if dt.columns.count =3
{ write to database }
else
{ return error to user that the excel is not in correct format };

What you need is a "server side validation" for your uploaded file and a Panel to show a message. In the old asp.net webforms world it should looks like this:
<telerik:RadAsyncUpload runat="server" EnableCustomValidation="true" ID="RadAsyncUpload1" OnFileUploaded="RadAsyncUpload1_FileUploaded" >
</telerik:RadAsyncUpload>
<asp:Panel ID="InvalidFiles" Visible="false" runat="server" CssClass="qsf-error">
<h3>Validation Erros:</h3>
<ul class="qsf-list ruError" runat="server" id="InValidFilesList">
<li>
<p class="ruErrorMessage">Your Excel is not valid...</p>
</li>
</ul>
</asp:Panel>
public void RadAsyncUpload1_FileUploaded(object sender, FileUploadedEventArgs e)
{
var liItem = new HtmlGenericControl("li");
liItem.InnerText = "Your uploaded Excel does not look so nice";
InValidFilesList.Controls.AddAt(0, liItem);
e.IsValid = false; // (Add validation (see comment bellow))
}
To validate your Excel file you can use Open XML to check your excel file.

Related

ASP.NET using Button instead of FileUpload to upload files

I'm trying to upload a file with Button element using hidden FileUpload element with ASP.NET using this snippet:
protected void Page_Load(object sender, EventArgs e)
{
Button2.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");
}
My Button has Id = "Button2", FileUpload Id = "FileUpload1". Clicking on the button Windows Explorer opens successfully to upload files but FileUpload.HasFile still returns false in further code (no file gets loaded even though explorer gets opened and file is selected).
What is the cause of this problem and how to fix it?
Well, I suppose you want to hide the the FileUpload Control and still be able to upload the files.
Follow the following steps to achieve the required:
Place a FileUpload Control with the class hidden. Like below:
<style>
.hidden{
display: none;
}
</style>
<asp:FileUpload runat="server" ID="FileUpload1" CssClass="hidden" />
Then place a Button that will be visible to client and will handle the Javascript events
<asp:Button runat="server" ID="Button1" Text="Upload File" OnClick="Button1_Clicked" />
Add the Javascript events to handle things
$(document).ready(function(){
// This event will help click the FileUpload control
$('#<%= Button1.ClientID %>').on('click', function(){
$('#<%= FileUpload1.ClientID %>').click();
return false; // important to return false, so it does not posts back yet.
});
$('#<%= FileUpload1.ClientID %>').on('change', function(){ // To see if the file selection was changed and the user has selected something
if($(this).val() == ''){
alert('No file selected');
return false;
}
if(confirm('Do you want to upload this file? ' + $(this).val())){
__doPostBack('<%= Button1.ClientID %>', ''); // this will postback to the server click event
}
});
});
Now, handle the uploaded file.
public void Button1_Clicked(object sender, EventArgs e)
{
// Handle your upload function
var hasFile = FileUpload1.HasFile;
}
PS: It was a rough Idea, the code is not tested so it might need some love.

File Upload Control Change Event Not firing

I have an asp.net File upload control, I am using Jquery multi file upload with it.
When I select a file, it makes a div under the upload control to display list of files. I want to save the value of upload control in a hidden field, I am using jquery change event on fileupload control but its not firing.
I also tried using same event with the files div, but its also not firing, and no error in Fire Bug.
<asp:FileUpload ID="FileUpload1" runat="server" class="multi" />
<div id="ctl00_ContentPlaceHolder1_FileUpload1" class="MultiFile-list"></div>
$(document).ready(function () {
$("#ctl00_ContentPlaceHolder1_FileUpload1").change(function () {
alert("File Selected");
});
$(".MultiFile-list").change(function () {
alert("File Selected");
});
});
I also tried with div ID, but no luck.
Seems that jQuery don't support multiple file upload very well, but you can try with something like this on the change event:
$("#ctl00_ContentPlaceHolder1_FileUpload1").change(function() {
var files = $('#ctl00_ContentPlaceHolder1_FileUpload1')[0].files;
for (var i = 0; i < files.length; i++) {
$(".MultiFile-list").append(files[i].name);
}
});
As you can read, I get the files list and put the names in the div you defined, just to let you try the code.

calling C# function immediately file is selected in fileupload

I have a web form(asp.net) which I'm using to upload file. In current situation if a user choose a text file from their computer they have to click a buttton to upload the text in a box. I'm trying to find a way to skip the step with a button pressing.
How to call a C# function when the file is selected from user ?
Try this
<asp:FileUpload ID="FileUpload01" ClientIDMode="Static" onchange="this.form.submit()" runat="server"/>
in code behind Page_load event
if (IsPostBack && FileUpload01.PostedFile != null)
{
if (FileUpload01.PostedFile.FileName.Length > 0)
{
FileUpload01.SaveAs(Server.MapPath("~/Images/") + FileUpload01.PostedFile.FileName);
imguser.ImageUrl = "~/Images/" + FileUpload01.PostedFile.FileName;
}
}

Returning data with AjaxControlToolkit's async AJAXFileUpload control in ASP.NET

I'm using the above control (note it's the ASP.NET one. I seem to see lots of people using a similarly named one written in javascript) to allow upload multiple uploads of files with a progress bar, drag-n-drop, etc. That part all works fine but I need to return two pieces of data along with the file. Specifically, it's a user entered latitude and longitude that comes from two text boxes. Since the upload control is async, the contents of the text boxes don't get posted back so I can't access them. There seems to be a property I can hook into, ContextKeys, which will send the data back to the server, but it's a static field and I don't know how to manipulate it dynamically. I've tried hooking the ontextchanged events from the textboxes and using those to set the context keys. The post back works and it seems to set the value, but when the user presses the upload button the ContextKeys value is empty.
Does anyone how to programtically set the ContextKeys property, or another way to send data back with the upload?
Here's the code:
.ASPX
<div style="float:left; width: 325px;">
<cc1:AjaxFileUpload ID="AjaxFileUpload1" runat="server" Width="325px"
onuploadcomplete="UploadComplete" ClientIDMode="Static" />
<cc1:DynamicPopulateExtender ID="AjaxFileUpload1_DynamicPopulateExtender"
runat="server" Enabled="True" PopulateTriggerControlID=""
TargetControlID="AjaxFileUpload1">
</cc1:DynamicPopulateExtender>
</div>
<div style="float:left">Latitude:
<asp:TextBox ID="tbUploaderLat" runat="server"
ontextchanged="tbUploaderLat_TextChanged" AutoPostBack="True"></asp:TextBox><br />
Longitude:
<asp:TextBox ID="tbUploaderLon" runat="server"
ontextchanged="tbUploaderLon_TextChanged" AutoPostBack="True"></asp:TextBox>
</div>
code-behind:
protected void UpdateLatLon() //this is called from the two events above
{
AjaxFileUpload1.ContextKeys = tbUploaderLat.Text + "|" + tbUploaderLon.Text;
}
You can customize AjaxFileUpload control as described here and here and pass textboxes values to UploadCompleted event handler as below:
function uploadStarted(sender, args) {
var latitude = $get("<%= tbUploaderLat.ClientID %>").value;
var longitude = $get("<%= tbUploaderLon.ClientID %>").value;
sender.contextKeys = { "latitude": latitude, "longitude": longitude };
}​
After that, you can get latitude & longitude values in UploadComplete handler:
protected void AjaxFileUpload1_OnUploadComplete(object sender, AjaxFileUploadEventArgs file)
{
if (!string.IsNullOrEmpty(file.ContextKeys))
{
var longLat = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Dictionary<string, string>>(file.ContextKeys);
var longitude = longLat["longitude"];
var latitude = longLat["latitude"];
}
//code to save file
}

Crystal Report Viewer - Programmatically restricting File Format options

In Crystal Reports Viewer (2008) for ASP.Net, when you click on the Export button, the Export dialog shows up with File Format options:
Crystal Reports (RPT)
PDF
Microsoft Excel(97-2003)
Microsoft Excel(97-2003) Data-Only
Microsoft Word (97-2003)
Microsoft Word (97-2003) Editable
Rich Text Format (RTF)
XML
etc..
Does anyone know how to remove some of these options so that end users wouldn't see it?
We've ran into this same issue and ended up rolling our own export page and limited the selection there.
It works great, but I would have expected more from Crystal Reports!
From what I was able to find, you could try to create your own export button option, removing the given button option and adding your own to the asp page. You would need to start by dragging the button onto the page and double clicking it to auto generate the code. From there add the code
crystalReportViewer1.ExportReport ()
Once this code is in it will use the default settings for the export options, however if you want to change the export options within that button then you have to manually code it.
' Declare variables and get the export options.
Dim exportOpts As New ExportOptions()
Dim diskOpts As New DiskFileDestinationOptions()
Dim excelFormatOpts As New ExcelFormatOptions()
exportOpts = Report.ExportOptions
' Set the excel format options.
excelFormatOpts.ExcelTabHasColumnHeadings = true
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.FormatOptions = excelFormatOpts
' Set the export format.
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile
' Set the disk file options.
diskOpts.DiskFileName = fileName
exportOpts.DestinationOptions = diskOpts
Report.Export()
MSDN SITE
This link gives you the same code posted above. It show how to do it in Visual Basic code. therefor in your aspx.vb code you would have to manually enter the the types of formats you want.
You might be able to control the export options by removing the export DLLs. Search for crxf_*.dll in the Business Objects\Common\\bin directory.
Refer Below Answer to remove unwanted export Option from Crystal Reports
Display PDF and Excel export options in Crystal Reports?
<asp:ImageButton Width="20px" Height="20px" ID="btnPdf" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/PDF.png" AlternateText="Export To PDF" CssClass="AddedButton" />
<asp:ImageButton Width="20px" Height="20px" ID="btnXls" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/XLS.png" AlternateText="Export To Excel" />
<asp:ImageButton Width="20px" Height="20px" ID="btnDoc" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/DOC.png" AlternateText="Export To Word" />
try this:
<CR:CrystalReportViewer ... HasExportButton="false" HasPrintButton="False" >
<asp:ImageButton Width="20px" Height="20px" ID="btnPdf" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/PDF.png" AlternateText="Export To PDF" CssClass="AddedButton" />
<asp:ImageButton Width="20px" Height="20px" ID="btnXls" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/XLS.png" AlternateText="Export To Excel" />
<asp:ImageButton Width="20px" Height="20px" ID="btnDoc" runat="server"
OnClick="btnExport_Click" ImageUrl="~/Images/DOC.png" AlternateText="Export To Word" />
C# code:
protected void btnExport_Click(object sender, EventArgs e)
{
// Stop buffering the response
Response.Buffer = false;
// Clear the response content and headers
Response.ClearContent();
Response.ClearHeaders();
try
{
string senderID = ((ImageButton)sender).ID;
if (senderID == "btnPdf")
reportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, Page.Title);
else if (senderID == "btnXls")
reportDocument.ExportToHttpResponse(ExportFormatType.ExcelRecord, Response, true, Page.Title);
else if (senderID == "btnDoc")
reportDocument.ExportToHttpResponse(ExportFormatType.WordForWindows, Response, true, Page.Title);
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
}
catch (System.Threading.ThreadAbortException)
{
//The issue has been identified and logged under Problem Report ID
//ADAPT00765364. The error is likely caused because Response.End() is used inside the
//ExportToHttpResponse() method.
//It is a known issue that Reponse.End() causes the thread to abort. This is by design.
//See Microsoft KB312629 Article for more info.
}
catch (Exception ex)
{
//error management
}
}
Apparently a later version (13.0?) adds a AllowedExportFormats property to the CrystalReportViewer class.
I don't have that newer version (I just have 12.0) but apparently something like this is all you need:
int exportFormatFlags = (int)
(CrystalDecisions.Shared.ViewerExportFormats.PdfFormat |
CrystalDecisions.Shared.ViewerExportFormats.ExcelFormat |
// any other desired formats
);
crystalReportViewer1.AllowedExportFormats = exportFormatFlags;
using (ReportClass rptH = new ReportClass())
{
rptH.FileName = #"C:/Report/crJournal.rpt"; //Your rpt file path
// if you put your rpt file on Bin then you need to write only rpt file name
rptH.Load();
rptH.SetDataSource( ds );// Provide Dataset for report : Ds is DataSet
rptH.ExportToDisk(ExportFormatType.Excel, "Give Output file path");
}
This code is defenetly work :

Resources