I was waiting for such day since 3 years. When i wake up i usually start my day by reading some of my favorite ASP.NET blogs. One of them as you might have realized is Scott Guthrie. Scott announced today the release of an ASP.NET chart control in which you can embed inside an ASPX webform. for more information check below blog post
New ASP.NET Charting Control
Enjoy
As you may already know, one of the reasons why the asp.net worker process recycles which kills all the session variables in memory is due to dynamically deleting a folder under the root application folder. You have two options to follow in this case
1- To use out-of-process mode session
2- To use the below code which uses reflection to disable monitoring for the folders inside the application. In this way, once you delete a folder, the Application domain won't restart thus you won't be losing any session variable
PropertyInfo p = typeof(System.Web.HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
object o = p.GetValue(null, null);
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
object monitor = f.GetValue(o);
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
m.Invoke(monitor, new object[] { });
Do not forget to import System.Reflection Namespace
Hope this helps,
Well it started out from 3 and a half years when i start working in my company and start building web applications using ASP.NET. I used to concentrate too much in the design and planning phase of the project then when it is time to write code, I grab my headphones and start my trance playlist (which is about 25 GB). Listening to music in the development phase in my case could be because of two factors
1- Disconnect myself from the surrounding. We used to be 4 developers in 1 medium sized room and of course you know about the chit-chatting between employees which might distract other employees.
2- Somehow this type of music makes my imagination works better. After several self monitoring sessions, I found out that i could write more effective code and be able to provide neat solutions while listening to trance music.
Up till today, i still get comments on how I’m able to perform in such environment but only the success of my projects will answer that question!
Happy coding...
Bilal has worked hard to publish his first book titled "Professional ASP.NET 3.5 Security, Membership, and Role Management with C# and VB.NET". Finally it is in stock now. Check out below link
Professional ASP.NET 3.5 Security, Membership, and Role Management with C# and VB.NET
I wish for Bilal lots of success in the future and hope this book won't be the last.
Regards,
In this blog post, we will see how to create an XML schema file for an xml file and how to validate if a certain XML complies to our schema.
First of all, open the XML file in Visual Studio. Right click the solution explorer select add Existing file and select the xml file. Open the file and choose from the menu XML --> Create Schema.
Now you have the schema and the XML file, it is time to write some code to validate the xml file.
try
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, XSDFILEPATH);
settings.ValidationType = ValidationType.Schema;
XmlDocument document = new XmlDocument();
document.Load(XMLFILEPATH);
XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
while(rdr.Read()){}
}
catch
{
isValid = false;
}
if the validation fails, a private field is set to false (isValid) in which you can check at runtime to see if the status of the validation process.
Hope this helps,
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,
More Posts
Next page »