How many times you tried to catch the maximum request length error thrown by the FileUplad control if the web.config HttpRuntime entry is not modified?
In this blog post, Haissam Abdul Malak will create an HttpModule which check if the file is larger than 4 MB to redirect the user to a webform "Error.aspx".
The module will register to the BeginRequest event to execute the needed code
Below is the implementation
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;
if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
// Redirect the user to an error page.
context.Response.Redirect("Error.aspx");
}
}
public void Dispose()
{
}
}
}
Now all you need to do is to add the module in the web.config file by adding the below entry under system.Web
<httpModules>
<add type="HAMModule.MyModule" name="MyModule"/>
</httpModules>
Hope this helps,
One interresting feature a developer should know is the ability to chunk the viewstate field into multiple fields. Why you
need such feature? Some proxy servers and firewalls won't allow a request to be processed if a hidden fields' length is
large. To overcome this, You can set up in the web.config file for all the pages to have a maximum viewstate field.
<system.web>
<pages maxPageStateFieldLength = "1024" />
</system.web>
The value of maxPageStateFieldLength is in Bytes.
In this way, if the hidden viewstate field is larger than 1 kb, ASP.NET will create multiple hidden viewstate field to hold
the data entered by the user before the postback. For example if the size of the data entered by the user is 2KB, the below
fields in the page once being rendered to HTML will be created
<input type="hidden" name="__VIEWSTATEFIELDCOUNT" value="2" />
<input type="hidden" name="__VIEWSTATE" value="..." />
<input type="hidden" name="__VIEWSTATE1" value="..." />
Keep in mind that this won't improve the application performance. It will add more steps to serialize the data back before
being sent to the client.
Hope this helps,
AS you may know, ASP.NET by default only allows the maximum request length to be 4MB. The developer needs to modify the web.config file to allow the upload process to handle large files.
If you use Reflactor and you dissamble the HttpRequest under System.Web, you will find a method called GetEntireRawContent which will check if the request is larger than the value in the web.config and throws an error
if (length > maxRequestLengthBytes)
{
throw new HttpException(SR.GetString("Max_request_length_exceeded"), null, 0xbbc);
}
In this article, Haissam Abdul Malak will demonstrate how to upload large files in ASP.NET without the need to modify the value of maxRequestLength attribute of the httpRuntime tag in the web.config.
We will create an HttpModule which will read the file in chunks (500KB per chunk).
We will handle the BeginRequest event and use the HttpWorkerRequest which provides more low level control for the request.
Below is the full implementation of the HttpModule. I included comments to enable you to fully understand each line of code.
I recommend connecting to msdn and read about HttpWorkerRequest class. Personally i didnt know about the existence of such class except lately.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HAMModule
{
public class MyModule : IHttpModule
{
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.ContentLength > 4096000)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
FileStream fs = null;
// Check if body contains data
if (wr.HasEntityBody())
{
// get the total body length
int requestLength = wr.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = wr.GetPreloadedEntityBody().Length;
if (!wr.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
string[] fileName = context.Request.QueryString["fileName"].Split(new char[] { '\\' });
fs = new FileStream(context.Server.MapPath("~/Uploads/" + fileName[fileName.Length-1]), FileMode.CreateNew);
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = wr.ReadEntityBody(buffer, buffer.Length);
// Write the chunks to the physical file
fs.Write(buffer, 0, buffer.Length);
// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = wr.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
fs.Flush();
fs.Close();
context.Response.Redirect("UploadFinished.aspx");
}
}
public void Dispose()
{
}
}
}
To know the file name selected by the user, I had to use javascript function on the page containing the fileupload control to change the action property of the form tag to post to the same page with a query
string parameter containing the selected file name. Users will be redirected to a page called "UploadFinished.aspx" to display a successful upload process message.
Below is the javascript function
<script language="javascript">
function SetAction()
{
document.form1.action = 'default.aspx?fileName=' + document.getElementById('FileUpload1').value;
}
</script>
And call it using
<asp:FileUpload ID="FileUpload1" runat="server" onpropertychange="SetAction()" />
You need to register the module in the application web.config file by placing the below inside the <system.web> tag.
<httpModules>
<add type="HAMModule.MyModule" name="MyModule"/>
</httpModules>
Hope this helps,
Convert ASPX Webforms To Word
We will discuss how to convert an ASPX page to word document and send it to the client. We will create an HttpModule which use the Application_BeginRequest event to check if a specific query string parameter exists to render the page into a word file.
First of all, Create a new class library project "WordConverter", Rename the class into "Converter" and let it implement IhttpModule interface which exists in System.Web namespace (you need to add it to your references before being able to add it to your namespace collection)
public class Converter : IHttpModule
After this stage, use the Init() to register for the Application_BeginRequest event.
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
}
// Dispose should be added
public void Dispose()
{
}
In the app_BeginRequest event you will need to write the below code
HttpContext.Current.Response.Clear();
// Check if ToWord exists in the query string parameters
if(HttpContext.Current.Request.QueryString["ToWord"]!=null)
{
// Set the buffer to true
HttpContext.Current.Response.Buffer = true;
// Create a new HttpWebRequest to the same url
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(HttpContext.Current.Request.Url.ToString().Split('?')[0]);
// Set the credentials to default credentials: used if you are under proxy server
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Get the response as stream
Stream stream = webRequest.GetResponse().GetResponseStream();
// Set the content type of the response on msword
HttpContext.Current.Response.ContentType = "application/msword";
// Read the response as string
string pageHTML = new StreamReader(stream).ReadToEnd();
// Write it to the response
HttpContext.Current.Response.Write(pageHTML.ToString());
// Complete the Request
((HttpApplication)sender).CompleteRequest();
// End the response.
HttpContext.Current.Response.End();
}
P.S: Make sure you added the below namespaces
using System.Net;
using System.Web;
using System.IO;
After finishing implementing the code, compile your project. Now you need to add this module to your web application by adding it to your references and add the below code into the web.config to register the module.
<httpModules>
<add type="WordConverter.Converter" name="Converter"/>
</httpModules>
You can find the Module solution attached to this blog post.
Hope this helps,
Have you ever encountered the need to execute lines of code on each page_load event for each page you have in your project! I have seen a lot of developers from the official ASP.NET forums writting the same code on each page which works fine but in case you need to change something you have to reflect it on all the pages.
Below i will describe a way you can implement to overcome this issue.
1- Create a class "MyPage" which inherits from Page class.
public partial class MyPage: Page
2- Override the onLoad event of the Page class by adding the below code
protected override void OnLoad(EventArgs e)
{
Response.Write("hello World");
base.OnLoad(e);
}
3- In your webform replace System.Web.UI.Page by MyPage
Hope this helps,
In this blog post, Haissam Abdul Malak will explain how to dynamically load a crystal report file into a webform by using the CrystalReportViewer class and how to successfully deploy the application. For instance, suppose you have ".rpt" file in your web application folder and you dynamically want to show it in the page. Below is the code to use
// Get the filePath
string filePath = Server.MapPath("~/Reports/report1.rpt");
// Create new instance of the CrystalReportViewerClass
CrystalReportViewer rptViewer = new CrystalDecisions.Web.CrystalReportViewer();
// Create new instance of the Report Document
ReportDocument rptDoc = new ReportDocument();
// Load the rpt file into the ReportDocument Class
rptDoc.Load(filepath);
// Set the already loaded rpt file into the CrystalReportViewer class
rptViewer.ReportSource = rptDoc;
// Add the control to the page
Page.Form.Controls.Add(rptViewer);
P.S: You should add CrystalDecisions.CrystalReports.Engine and CrystalDecisions.Web and import them.
Now locally it should work because when installing VS 2005, it will install to your local pc all the dlls needed for the crystal report rendering in the GAC . However, you might encounter problems when deploying the application on a web server where the dlls are not installed. One of the solutions is to install the dlls on the web server. You can locate the installer on your local pc at "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports". The file name is "CRRedist2005_x86.msi". Run this installer on your webserver and re-run the application.
Hope this helps,
Lots of ASP.NET developers took advantage of the free ASP.NET RSS toolkit to consume and provide RSS feeds. Thanks to dmitry in a matter of minutes, we will have a nice and robust toolkit which can be intergrated easily in our web application. However, After i finished my application and deploy it on one of our web servers, Consuming RSS stopped working. The error message was "unable to connect to remote server". After investigating and contacting dmitry, i realized our proxy server was rejecting the request. I looked into the open source code provided and knew that the RSS was being loaded directly into an XmlDocument. All we needed is to send an HttpWebRequest, set the proxy configuration, read the response, and finally load the XmlDocument.
In DownloadManager Class, replace DownloadFeedDom by the below
//// look for disk cache first
CacheInfo dom = TryLoadFromDisk(url);
if (CacheReadable(dom))
{
return dom;
}
string ttlString = null;
HttpWebRequest webRequest = null;
string strResult = null;
try
{
// Create a new web request
webRequest = WebRequest.Create(url) as HttpWebRequest;
// Check if ProxyServerUrl in the appSettings is not empty
if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString()))
{
// instantiate a new WebProxy class and send the ProxyServerUrl to the contructor parameter
System.Net.WebProxy proxy = new System.Net.WebProxy(WebConfigurationManager.AppSettings["ProxyServerUrl"].ToString(), true);
// Set the proxy credentials
proxy.Credentials = new NetworkCredential(WebConfigurationManager.AppSettings["PassThroughUser"].ToString(), WebConfigurationManager.AppSettings["PassThroughPwd"].ToString());
// Set the WebRequest proxy property by the WebProxy class already configured
webRequest.Proxy = proxy;
}
// Read the response
using (StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// Set strResult to the response
strResult = sr.ReadToEnd();
}
}
catch
{
}
// Load xml From the string
XmlDocument doc = new XmlDocument();
doc.LoadXml(strResult);
if (doc.SelectSingleNode("/rss/channel/ttl") != null)
{
ttlString = doc.SelectSingleNode("/rss/channel/ttl").Value;
}
//// compute expiry
int ttlMinutes = GetTtlFromString(ttlString, _defaultTtlMinutes);
DateTime utcExpiry = DateTime.UtcNow.AddMinutes(ttlMinutes);
//// save to disk
return TrySaveToDisk(doc, url, utcExpiry);
P.S: I would like to thank dmitry for his quick response eventhough i know that he would be busy.
Hope this helps,
As i'm an ASP.NET developer and knowing that this technology is powerfull, I needed to find a way to exchange data between Adobe Flex application used as front end and my ASP.NET application used as a backend. After spending some time googling, i found an open source library "The FluorineFx open source library provides an implementation of Flex/Flash Remoting, Flex Data Services and real-time messaging functionality for the .NET framework."
To start using this open source library go to http://www.fluorinefx.com/download.html and click on "Download FluorineFx v1.0.0.13".
Once the installation process is completed, A folder on your desktop will be created "DotNet", Navigate to "FlexToNet.AMFService\Bin" to get the dlls
required. Paste these 2 dlls into the bin folder of your ASP.NET application.
Configuration
Once you have placed the two dlls inside the bin folder of your application, in Visual Studio 2005 right click on References and click Add Reference.
Browse to the application bin folder and select the two dlls.
For the communication between ASP.NET and Adobe flex to work, you need to create a dummy page called "Gateway.aspx" and add the below code to the web.config file inside System.Web tags
<httpModules>
<add name="FluorineGateway" type="com.TheSilentGroup.Fluorine.FluorineGateway, com.TheSilentGroup.Fluorine"/>
</httpModules>
As you may have noticed, the dll being added to the application bin folder serves as http module which will serialize the objects and allow the communication between these two technologies
Adobe Flex
In Adobe Flex builder, create a new project of type mxml application and add the below code
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="HandleClick();">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import flash.net.NetConnection;
private function CallDotNetMethod(event:Event):void
{
// Create a new instance of NetConnection class
var net:NetConnection = new NetConnection();
// Connect to your ASP.NET application
net.connect("http://localhost/webApplication5/Gateway.aspx");
// Call a function in your application called RetrieveMsg inside a class called "Test"
net.call("WebApplication2.Test.RetrieveMsg", new Responder(Result,null));
// Close the connection
net.close();
}
public function Result(data:Object):void
{
// this method will be called once the result from the .NET class is received which will just display the message returned
Alert.show(data.toString());
}
public function HandleClick():void
{
// This method will be called on creation complete event of the mxml application
btnTest.addEventListener(MouseEvent.CLICK,CallDotNetMethod);
}
]]>
</mx:Script>
<mx:Button id="btnTest" x="74" y="51" label="Button"/>
</mx:Application>
ASP.NET Application
Create a new web application, create a new class called "Test" inside it add the below code
public string RetrieveMsg()
{
return "Hello World";
}
Finally you need to create a dummy page called "Gateway,aspx"
For demonstration only, this method will only return Hello world to adobe flex application.
Run the application
Once you run the application inside Adobe flex, or you added the swf file being compiled in Adobe flex builder to an aspx page, you can test the application by clicking on the button to see the alert message returning the data from the .net class
Of course you can use web services to enable this communication, but keep in mind that using webservices is slower than directly calling a .NET class. I have added the project as an attachment so you can download it and take a deeper look into it.
Hope this helps,
A lot of developers are asking how to restart the ASP.NET application or recycle the ASP.NET process without the need to modify the content of web.config file or changing its name.
You can use the HttpRuntime.UnloadAppDomain() which will terminate the application and of course remove all the session objects for all users the next time a request is being received.
Demonstration:
Create a dummy web application, drag and drop two buttons. and use some like below
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!IsPostBack)
Session.Add("ASP","hello");
}
private void Button1_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
HttpRuntime.UnloadAppDomain();
}
private void Button2_Click(object sender, System.EventArgs e)
{
Response.Write(Session["ASP"].ToString());
}
When you click Button2, you will have object reference not set to an instance of an object error which indicates that Session["ASP"] is equal to null.
Hope this helps
Always check out the blog that keeps you updated about latest technologies
http://bhaidar.net/cs/default.aspx
Bilal haidar is now preparing a book which will be released end of this summer. Congratulations Bilal on your achievements.
Best Regards,
In this blog post, I will explain how to submit user credentials to another application to authenticate users.
Suppose in your application, you wanted to retrieve data from another application (for instance RSS feeds), this rss feed isn't for public use, and you don't control the login authentication on that application.
Solution
You can submit user credentials from your application to the other application and process the login click event using the HttpWebRequest class. In this way, if the user is authenticated the authentication cookie will be saved in the response header. After this stage, Each time you want to retrieve information for Application B, you could set the authentication cookie already retrieved to the request header so Application B will deal with the request as an authenticated one.
Let's drill down to the code
string loginURL = "http://www.example.com/default.aspx";
// Create a webrequest to the above url
HttpWebRequest webRequest = WebRequest.Create(loginURL) as HttpWebRequest;
// Set the request method to post
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = false;
// Set the content type to urlencoded
webRequest.ContentType = "application/x-www-form-urlencoded";
// Set the data which needs to be posted. Note here os_username, os_password is the textbox ID for the //username, password on Application B. login is the ID of the login button control, LogIn is its value.
string postData = "os_username=haissam&os_password=password&login=LogIn";
// Set the content length of the request
webRequest.ContentLength = postData.Length;
// set the webrequest stream to the requestWriter
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
// Write the data which need to be posted to the streamwriter
requestWriter.Write(postData);
// Close the stream
requestWriter.Close();
// you don't need to get the response only the authentication cookie so directly we close it
webRequest.GetResponse().Close();
Hope this helps,
In this blog post, I will write a review on the 70-315 (Developing and Implementing Web Applications with MS visual C# and MS VS.NET) exam provided by UCertify.com.
The importance of preparation exams:
After you finish reading all the materials required for 70-315 exam, it is recommended to take a practice test before the official one. The practice test provided by Ucertify.com will give you an excellent idea about the type of questions you will face and prepare you both technically and mentally in order to pass the exam from the first try.
Before starting the test, it is recommended to read the exam objectives. After that, take a look into the Study Tips which, in my opinion, gives you a proper orientation about Microsoft exams and how to be fully prepared especially if it was the first exam you are taking.
Taking the test:
This will help you identify your weakness in order to enable you to focus on these topics. Each test you take is provided with a count down timer. This timer resembles to the timer provided in the real exam in this way, you can be sure that you will finish all the questions before you are running out of time. Taking advantage of the “Test History” using UCertify.com exam preparation will give you a better visual idea about each test you took, percentage of the questions answered, and the most important property is the “Remark” column in which you can check their remarks on each test.
One tip to consider during the exam is to take the questions that you can answer easily and mark the hard questions to be reviewed later. Using this technique will help you
1- Answering as much questions as you can
2- Refreshing your mind maybe later you could find the proper answer.
Make sure also to review the explanation of both correct and incorrect answers to ensure better understanding and learning.
Another cool feature is the Learning mode while taking the exam which enables you to get a feedback of the question before taking the next one.
Questions Engine:
In a technical point of view and considering the fact that I already passed this exam, I can say that the questions provided are efficient, cover all the topics required, and resemble to the actual exam questions. Much more, the tests seem to be harder than the official one which is good in this case because it guarantees that you will pass the actual exam.
Each required topic has its own set of questions, once you identify your weakness you can create a custom test to focus on this topic.
N.B: Make sure to update frequently the questions by going to File/Update PrepEngine.
Conclusion:
The idea is not just passing the actual exam; of course it is our main goal but also to improve our skills and ensure that we fully understand all the required topics which I think UCertify.com made it easy on us!
UCertify is making a 10% discount for all my blog readers. To get this discount, you can use the "HMALAK" discount code.
In this blog post, i will share my top 3 blog posts made during last year. It is a good way to monitor which blog post has the highest number of views and comments to better understand which topic(s) concerns web developers more.
1- Passing Data Between Parent and Child window
-
Views: 17442.
-
Comments: 43
2- Close window without the prompt message in IE7
-
Views: 13978
-
Comments: 50
3- Downloading Files C#
-
Views: 12319
-
Comments: 53
Best Regards,
Haissam Abdul Malak
In this blog post, Haissam Abdul Malak will demonstrate how to upload multiple files in ASP.NET taking advantage of Adobe Flex technology.
Why The integration between Flex and ASP.NET
Using the File Upload control provided in ASP.NET, the user can't select more than 1 file at a time however in Adobe Flex the user can select multiple files in the open dialog box through the
FileReferenceList.browse() method also one important feature to mention is the ability to monitor the upload progress. In other words, you can handle the Progress event to display the number of bytes being uploaded and the total size of each uploaded file.
After the user selects the files, you can access them by the fileReferenceList.fileList property which will return an Array of the selected files. In this way, You can loop through the array's elements and start the upload process for each file. To successfully upload a file, you need to send a "Post" request to a URL (the handler will be an aspx page) which will save the files in the application root folder.
Creating the Flex Application
If you have a Adobe Flex builder, you can open it and click on File --> New --> Flex Project.
An .mxml file will be created, Just copy and paste the below code
MXML:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="myFunction();">
<mx:Button x="10" y="10" label="Choose Files" id="btnSelectFiles"/>
<mx:Button x="114" y="10" label="Upload" id="btnUpload" visible="false"/>
<mx:Label x="10" y="208" width="100%" id="lblFileName" fontWeight="bold"/>
<mx:List borderStyle="none" backgroundAlpha="0" x="10" y="40" width="30%" id="listSelectedFiles" visible="false" />
<mx:Label x="10" y="234" width="100%" id="lblUploadedBytes" fontWeight="bold"/>
<mx:Label x="10" y="260" width="100%" id="lblTotalBytes" fontWeight="bold"/>
<mx:Script>
<![CDATA[
import mx.messaging.AbstractConsumer;
public var fileReferenceList:FileReferenceList = new FileReferenceList();
public function eventResponse(Event:MouseEvent):void
{
// Set the file filters in the open dialog box
var typeFiler:FileFilter = new FileFilter("All","*.*");
// show the dialog box
fileReferenceList.browse([typeFiler]);
}
public function selectResponse(event:Event):void
{
// Create an array with the size of the selected files.
var filesSelected:Array = new Array(fileReferenceList.fileList.length);
// Loop through all the selected files and add their names to the List control
for(var i:int=0;i<fileReferenceList.fileList.length;i++)
{
var fileReference:FileReference = fileReferenceList.fileList[ i ];
filesSelected[ i ] = fileReference.name;
}
listSelectedFiles.dataProvider = filesSelected;
listSelectedFiles.visible = true;
btnUpload.visible = true;
}
public function myFunction(): void
{
// This function is called on creationComplete event of this application
// Add event handler for the mouse click on the selectFiles button
btnSelectFiles.addEventListener(MouseEvent.CLICK, eventResponse);
// Add event handler for the mouse click on the upload button
btnUpload.addEventListener(MouseEvent.CLICK, btnUploadResponse);
// Add event handler for the select action in the open file dialog box
fileReferenceList.addEventListener(Event.SELECT,selectResponse);
}
public function UploadFiles():void
{
// If the user selected 1 or multiple files
if(fileReferenceList.fileList.length > 0)
{
// For each file selected
for(var i:int=0;i<fileReferenceList.fileList.length;i++)
{
// Create a FileReference instance of each file
var fileReference:FileReference = fileReferenceList.fileList[ i ];
// Create a new URLRequest class: The parameter is the aspx handler page
var request:URLRequest = new URLRequest("http://localhost/FlexUpload/Default.aspx");
// Add event handler for the progress
fileReference.addEventListener(ProgressEvent.PROGRESS, progressStatus);
// Set the content type
request.contentType = "application/octet-stream";
// Set the method of the request
request.method = "POST";
// Upload the file
fileReference.upload(request,fileReference.name,false);
}
}
}
public function btnUploadResponse(event:Event):void
{
// Disable the Select files button, upload button, and call the UploadFiles function
btnSelectFiles.enabled = false;
btnUpload.enabled = false;
UploadFiles();
}
public function progressStatus(event:ProgressEvent):void
{
var file:FileReference = FileReference(event.target);
// Set the name of the currently being uploaded file
lblFileName.text = "Uploading File: " + file.name;
// Set the number of bytes being uploaded
lblUploadedBytes.text = "Bytes Uploaded: " + event.bytesLoaded;
// Set the total number of bytes
lblTotalBytes.text = "Total Size: " + event.bytesTotal + " bytes";
}
]]>
</mx:Script>
</mx:Application>
ASP.NET Application
I decided to post the above code in case anyone wants to change the UI or some functionality of this control. However, if you want to use it as it is, All you need to do is to embed the ".swf" using the
Object tag file found in the attached zip file of this current post into your application.
Now create a folder "UploadedFiles" which will contain all the uploaded files (do not forget to give IUSR_<machinename> read/write permissions).
After this stage, you need to create a page called "UploadHandler.aspx" which will received the file and save it in the "UploadedFiles". Copy the below into the page_load event
for (int i = 0; i < Request.Files.Count; i++)
{
string fileName = System.IO.Path.GetFileName(Request.Files[ i ].FileName);
Request.Files[ i ].SaveAs(Server.MapPath("~/UploadedFiles/") + fileName);
}
After you complete the above steps, you can run the application and see how it functions.
Hope this Helps,
I always wanted to guarantee that users of my application can view my published documents even if they don't have the needed application installed on their machines. To achieve this requirement and MACROMEDIA FLASH being installed on almost every browser, i got to either build a tool to convert my PDF files to flash files or to use a free tool. I came across an excellent and effective tool called SWFTOOLS. The beauty of this tool is that it can convert not just all the pdf file to swf file but it can convert a specific page also. In this way, i reduce the time needed to convert all the file and make it on demand. This tool can run using shell commands and using ASP.NET we can execute this process by using the System.Diagnostics.Process class.
When you install this tool on your local machine, copy the "font" and the PDF2SWF.exe file into a folder in your application root folder "PDF2SWF" and use the below code
int pageNumber = 1;
string fileName = "Files/1.pdf";
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~");
p.StartInfo.FileName = HttpContext.Current.Server.MapPath("~/PDF2SWF/PDF2SWF.exe");
p.StartInfo.Arguments = "-F " + "\"" +HttpContext.Current.Server.MapPath("~/PDF2SWF/FONTS") + "\"" + " -p " + pageNumber + " " + fileName + " -o " + fileName + pageNumber + ".swf";
//Start the process
p.Start();
p.WaitForExit();
p.Close();
The above code will create an instance of the Process class, Set the working directory to the root application folder, set the filename to the exe file and send arguments to the process. you can check the tool's website to know more about the arguments list.
Now after the above code will finish executing, a new file called 11.swf will be saved in the folder which will you can use to display it in your webform.
Hope this helps,
More Posts
Next page »