This something like - anybody would think why I will require to do this thing ever?. I mean calling a web service without adding reference of it. Obviously, to call a web service I would simply add the "Web Reference.." from the Solution Explorer; select the web service and once I am done; I would create the object of the Web Service and use its method - As simple as that.
BUT, recently I came into a bit different scenario which I would like to share. While working on one of my DotNetNuke Solution - I require to have a web service inside my DotNetNuke project (in one of custom module) which is to be consumed by another application. The whole solution was a product which seem to be hosted at the potential customer's side (on their server) - with appropriate configuration. That means, while hosting the DotNetNuke application at the client side - a fresh installation (using Install version) is needed with whatever "Virtual Directory" name they prefer.
Here the problem starts; because every client may like to have different name/url of the application. That means, name of the "Virtual Directory" can be different at each client space. In this case, in another application which is consuming the web service - I need to modify the web reference as per the "Virtual Directory" name of the hosted DotNetNuke solution! That is not desirable. Another scenario to call a web service without adding web reference - I can think of - is to call a method from more then one web services based on some user input (That is - if you want to dynamically call appropriate web service method).
Anyways, I end up with to calling web method without adding web reference.
for the sake of simplicity, Below is the simple default web method "Hello World" which you will find while you add a web service in your solution.

Once you done with the web methods, you add the web reference where you actually consume the web service methods. When you add a web reference - based on the WSDL specifications IDE actually created proxy classes in your application which represents the web service classes and its methods on the remote server. Visual Studio provides Intellisense with Web services, which will not be accurate till you update your web reference each time you change your web service, it is because the proxy classes which are local to your solution are being used to offer you the Intellisense. So, ultimately when you invoke a Web method you are invoking a method in one of these proxy classes. These classes, in turn, are capable of invoking the remote methods on the Web Service URL.
So, every time the web service is updated, these proxy classes need to be regenerated by clicking Update Web Reference. However, the proxy classes do not always have to be generated from the IDE, .NET also gives us the WSDL.exe utility to manually generate these proxy classes and include them in your project.

To generate this proxy classes you need to generate these proxy classes thru "WSDL.exe" utility from Visual Basic Command Prompt.
Once you are done, notice that WSDL.exe utility has created a proxy class for our Test web service at "C:\Program Files\Microsoft Visual Studio 10.0\VC\WebService.cs
Just grab the class, create a new website and add that proxy class in App_Code folder. If you open the proxy class you will notice the constructor of the proxy class contains "url" member property which is by default assigned the url of the website in which the web service exists. You can store the web service url in web.config or in database or whereever you wish it to be.

So, finally to call the "Hello World" web method - you need to create object of this proxy class and assign the url property correctly as below:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebService objService = new WebService();
objService.Url =
System.Configuration.ConfigurationManager.AppSettings["WebServiceUrl"];
Response.Write("Output of the Web method call: " + objService.HelloWorld());
}
}
First we created object of the proxy class, assigned the url property value from web.config file's appsetting section and call the web method. Thats it!.Hope this would be helpful and informational to somebody who need the same.
Below is the output of our example application:

Conclusion: you can call web service method without adding reference by creating proxy class thru wsdl.exe utility.
Did you ever need to write disconnected process which should be run at a defined interval time? Commonly, when we are in such need - we use to write window service which is based on some timer mechanism where we set some interval for the timer and in its elapsed method we execute the process we want to run at defined interval.
When you work with DotNetNuke and you come across with such functionality that need tobe implemented - you can consider creating "DotNetNuke Scheduler". While creating a DNN Scheduler - you are actually creating a simple class library which would be built and hosted in the DNN Schedule environment to be executed at the defined interval time.
The possible scenario in which one need to look at such schedule functionality is:
[1] You may need to send some set of fixed newletter everyday at defiend time to your customers.
[2] You may need to read some of third party product feed to read regular update and modify your product database.
[3] You may need to send some system generated reports to your third party vendor at some regular intervals.
To Create a DNN Scheduler; you need to:
[1] Create a class library project with a class which inherits DotNetNuke.Services.Scheduling.SchedulerClient.
[2] Write the process which you wish to be executed at some interval and call it in DoWork() method. (You can consider the DoWork() method as entry point of the disconnected process execution.
[3] Build the class library project and get th dll.
[4] Copy the dll inside /bin directory of your DNN solution.
[5] Make an entry in DNN Schedule (Host menu > Schedule submenu) service and host the dll by giving proper namespace and the elapsed time.
Let us explore above step in some details.
First step is to create a class library for which you need to add a new class library project inside your DNN solution.

Once you add the class library; just rename/modify the namespce, classname and the class filename which is appropriate to your DNN Solution. Like I modified the namespace and classname as: YouProjectName.ModuleName.TestSchedule
The namespace is important to define correctly as it will be used later on to define the entry in DNN Schedule.
Next, you need to add DotNetNuke.Library (DotNetNuke.dll) reference to your class library by right click class library project in the solution explorer and "Add Reference.." option. Once you add the DotNetNuke.Library reference you would be able to access DNN namespaces and classes which would be require to access DNN related functions and methods.
After adding reference, you need to inherit "DotNetNuke.Services.Scheduling.SchedulerClient" abstract class and implement DoWork() overridable method.


Here, I am also adding a parameterized constructor to properly record the schedule history:

For ease, I am creating a simple "Hello World" function which would create a new txt file at the defined path specifying current date and time.
public override void DoWork()
{
try
{
//--start the pocessing
this.Progressing();
//--call the function/process that you wish to be executed
ExecuteHelloWorld();
//--intimate the schedule mechanism to write log note in schedule history
this.ScheduleHistoryItem.AddLogNote("HelloWorld Service Start. Success.");
this.ScheduleHistoryItem.Succeeded = true;
}
catch (Exception Ex)
{
//--intimate the schedule mechanism to write log note in schedule history
this.ScheduleHistoryItem.Succeeded = false;
this.ScheduleHistoryItem.AddLogNote("HelloWorld Service Start. Failed. " + Ex.ToString());
this.Errored(ref Ex);
}
}
//--function which needs tobe executed at specified interval
public void ExecuteHelloWorld()
{
try
{
System.IO.File.WriteAllText(@"C:\\_SCHEDULER\\test" + Guid.NewGuid().ToString() + ".txt",
"Hello World. The Time is - " + DateTime.Now.ToString());
}
catch (Exception Ex)
{
throw Ex;
}
}
If you look at the above code - The processing always start from DoWork() method where I am calling the ExecuteHelloWorld() function. This is the function which will be executed at the defiend interval. Here, I am also logging in the Schedule history which would help us to know the status of the schedule execution.
Thats it!. You are done with the coding part. Next, all you need to do is; build the class library project get the dll, copy inside /bin directory of DNN solution and host it under DNN Schedule. For that Go to "Host" menu > "Schedule" submenu option. Once you are there, you would see there are some schedule entries already exists in the list which are being used in DotNetNuke environment


You would see a list of scheduled processes with its name, current status (enabled or disabled), the frequency of the execution, the next run as well as link to see the "Execution History". To add our process; Click on the "Add Item to Schedule" link. You will be redirected to "Edit Schedule" page where in you need to add your process to schedule.

[1] Give "Friendly Name" of the schedule process which will be seen in the schedule list.
[2] Provide full classname with namespace along with the assembly name. For example, in our case it will be YouProjectName.ModuleName.TestSchedule,TestSchedule. Please note that you dont need to write ".dll" extension; just full classname and name of assembly (dll) followed by a comma separator. This entry should be correct.
[3] Check the checkbox to enable the schedule.
[4] Provide the interval time to execute the process
[5] Provide the retry interval time; incase of failure.
[6 ] Specify the number of records in "Retain Schedule History" for History listing.
[7] You can specify "Run On Event" which will show Global.asax events; incase if you want schedule to execute the process on a specific event of global.asax. For example, APPLICATION_START event.
[8 ] Check the checkbox "Catch Up Enabled"; incase if you want the schedule process tobe executed in a scenario like the webserver is ever out of service, when the webserver is back in service this event will run once for each frequency that was missed during the downtime.
Click on the Update and you will see the newly hosted process in DNN Schedule list. You can click on "History" link to see the history of the execution. On History page, you will be presented with detailed Hisory records which we logged in our class library. This will helps to know the status of scheduled process.

Here, some important note is that A DotNetNuke Scheduler can have 2 running modes:
[1] Request Mode - in which DotNetNuke Scheduler will execute and run each time ONLY when a Browser Request is made.
[2] Timer Mode - in which DotNetNuke Scheduler will execute and keep running behind the scene on the specified elapse time.
By default, "Request Mode" is set which you can change from "Host" Menu > "Host Setting" submenu > Other Setting section > and Scheduler Mode Dropdown.

Thats it!. I hope this would help a lot to one who needs to implement continuous background process execution in DNN environment.
Oh Yes!,, The output of our test Schedule :)

Today, I am going to describe complete process of
creating a perfect DotNetNuke Environment or say how would you install DNN Site
(whether install or source version). I am going to use most latest and stable
05.04.00 install version of DotNetNuke.
To download the source/install version you need to
have login/account at official DotNetNuke site. Once you login; you would go to
Download page where you can select “Community” Edition to download. There are 2
variations in DotNetNuke that you would find there. One is Community Edition
and other is “Professional” edition. You can install DotNetNuke via downloading
“Microsoft Web Platform Installer” that is available on the same page. This
installer additionally provides you other valuable resources to install as
well. For more information on Web Platform you would get here - http://www.microsoft.com/web/default.aspx,
Otherwise, you may click on the “Older version” link which would redirect you
to the version track page at “Codeplex” site. You would find the total “Release
Track/History” at the right hand side. I have selected most stable install version
to download.
As I requested – I received the download of “DotNetNuke_Community_05.04.00_Install.zip”
file. Once File get downloaded; you copy the zip file and extract at the particular
place where you want to have the DotNetNuke site physical folder. For sake of simplicity,
I have extracted the zip file under c:\inetpub\wwwroot folder.

Please remember that if you are using Source
version and going to develop custom modules on that application than you need
to first keep the “web.config” (or just rename it something like
web.config.backup) file in backup and rename the “release.config” to “web.config”.
Also, remove the source control information from .sln file via opening the .sln
file in notepad and remove/delete the Global…EndGlobal section.
DNN is using some of Telerik Controls. So, just
make sure that Telerik dll (Telerik.Web.UI.dll) is exist in /bin folder. Other
thing to take care is (I don’t know whether they have corrected this one or
not. But, This problem was THERE in version 05.02.00) – if you are using source
version then Telerik dll was not exist in /bin folder and you have to take it
from the install version.
Once you extracted the zip file you need to create
the “Application Pool” (for OS other than XP) and Virtual Directory for the DNN
Site. Just go to the IIS (inetmgr) and create an “Application Pool” which would
target to proper .Net Framework version.

Remember the “Identity” on which Application Pool
will be running on. On my case – It is “NetworkService” Identity. It will be
require when you are giving proper permission to the extracted folder. You can
also change the Identity via “Advance Setting” of Application Pool.
After creating Application Pool – you need to create
Virtual Directory (Create Application..) under default website. Select the
AppPool that you have created for your DNN Site.

You are now done with IIS. Next is you need to
create a blank database and a sql user account in sql server. Go to Sql
Management Studio and Create a blank database as usual. Create one Sql user (or
you may use the existing “sa” account). Make sure that the user account that
you are selecting must have the proper permission to execute on the blank
database that you have created for DNN installation.
You are now done with Creating Database for the
installation. Move to the physical folder and apply proper permission for the
AppPool Identity user (Network Service in my case) as well as IIS user. This is
required otherwise DNN installation wizard would give you error related with
permission.
After giving permission – you are ready to run the
installation wizard and start installing your DNN Site. To start the wizard,
browse thru http://localhost/dotnetnuke/install/installwizard.aspx
and you would serve with below first stage.

On this step, you would find 3 options to install
the DNN Site.
[1] Custom: The
"Custom" installation method provides you with the ability to
completely customize your DotNetNuke installation. Select this option if you
wish to control which optional components get installed
.
[2] Typical: The "Typical"
installation method makes some "typical" choices for you.
[3] Auto: The "Auto"
installation method bypasses the Wizard completely and uses the legacy
Auto-Install procedure.
You can also browse thru http://localhost/dotnetnuke/install/install.aspx
to start the legacy Auto-Install procedure directly.
For sake of simplicity I am selecting most common “Custom”
option and click next.

On this step DNN Installation Wizard would check
the permission set given to the physical folder and would provide you the appropriate
warning information if permission were not applied correctly. Otherwise it
would pass this stage via giving successful message. Click Next.

On this step above – you will be asked to enter
the database information that you have created earlier in this installation
process. Select proper sql databse, server, name of the database (dotnetnuke in
my case) and give the user and password information (by un-checking the “Integrated
Security” Checkbox, because its better not to use windows authentication).
Select “Run as DB Owner” checkbox option and give the “Object Qualifier” you
wish. This Qualifier would be appended to each table, procedure, view etc.. in
the database installation.

Once database get installed successfully, Click
Next. Here you need to configure the “Host” account detail which is the “super
user” account for your DNN site.

Provide proper information for the Host Account.
Remember the password as it will be the super user which will be used to manage
host and portal sites. It’s preferable if you give correct SMTP details because
this way you would able to identify and come to know the correct activity
whenever any new user gets registered, blocked, or deactivated. DNN Site would
shoot email on important activity or action.
Once you are done with the Host Account
configuration, in next few steps you would be asked to select and install:
[1] Option Modules
[2] Skin and Containers
[3] Language Packs
[4] Authentication System (out of Active
Directory, LiveID and OpenID)
[5] Install Providers
You would be given available options in above
steps via checkbox where you can select the options you wish to install with
your DNN installation procedure. If you don’t select anything out of this step;
you can later do that via “Host Menu” > Module Definition > Install
Extension menu option. You would also find the same option from “Host Menu”
> Extension > Install available Extension link at the bottom of the page.
After above all steps get passed; you would come
across below steps where you would configure Admin account just like you did
for Host Account. Give proper information for admin account.

That’s it!! It’s the final stage where you are
just a single click away to your installed DNN Site. Click on “Start Building
Your New Site” and you are presented with the all new fresh DNN site installed.
Well well well, lets move on and play with it J


I hope this would help novice people in
configuring perfect DNN environment.
Here are few notes that are good to know:
[1] You would require installation templates if
you want to create custom DNN Skin or Dynamic/Simple DNN Custom Modules. You
would find these visual studio templates at the official DotNetNuke site
itself.
[2] Once you are done with the site installation
and you redirected to installed DNN site. You may face IIS error saying “The
Web server is configured to not list the contents of this directory” or you can
notice the address of the site in address bar something like http://localhost/dotnetnuke/install/.
In this case only you need to do is > Go to the Database and open the “PortalAlias”
table. You would find the portal alias of the site configured incorrectly. Just
correct it to “localhost/dotnetnuke” instead of “localhost/dotnetnuke/install”.
Reset the IIS (iisreset) or recycle the App Pool and you are Done!.
Have a Nice Day!!
after Long time.... back in the community finally... :)
I was working in DNN application since I used to add css classes as and when I need to add which are related to specific my custom dnn modules. Initially, I used to add those classes in MinimulExtropy skin css file. But, as time goes.. it grows in size and there are situations when skin tend to change everytime (because some skin related issues or client didnt like it). Sp, everytime when any skin got changed I need to manually "copy" and "paste" those application (related to custom desktop modules) css classes in to the targetted skin folder's css files. Because, somehow AFAIK dnn doesn't support App_Theme folder or .skin files (because of its skin architecture).
Then I found a silly solution to add all those application css classes and images related to it in the base css file. So, whenever you need or arise in such type of situation > you can simply put the image files at "portals/_default" folder and copy-paste all the css files in "portals/_default/default.css" file. Once you have done all this > you gonna have a css file with having your application css classes and you dont worry about this when you change or modify skin for any portals!!
Thats it! Happy DNNing!!
public string GetOrdinal(int Number)
{
if (((Number % 100) / 10) != 1)
{
if ((Number % 10) == 1)
return "st";
else if ((Number % 10) == 2)
return "nd";
else if ((Number % 10) == 3)
return "rd";
else
return "th";
}
else
return "th";
}
Source -http://www.dotnetnuke.com
Comparison of the Professional and Community Editions
The
DotNetNuke Professional Edition 5.1 is a tested and verified version of
the DotNetNuke framework that meets the requirements of organizations
running business-critical web applications. The Professional Edition
offers the same features as the Community Edition plus some additional
features specifically designed for business-critical applications. The
matrix below indicates the differences between the DotNetNuke Community
and Professional Editions.
For more information, also see:
| Feature |
Community
Edition |
Professional
Edition |
|
Google Analytics Support
Support for injection of analytics tracking code or other content in a specific location of every page
|
 |
 |
|
Google Analytics for Marketing Support
Support for advanced Google Analytics functionality such as visitor
type, landing page, role, or referrer segmentation
|
|
 |
|
Advanced Content Approval Process
Allows administrators to create custom workflows with an unlimited number of states and reviewers
|
|
 |
|
Change Audit
Last modified and full history audit trails
|
 |
 |
|
Granular Permissions
Page, module and folder level extended permissions to provide more granular security rights
|
|
 |
|
Distributed Caching Provider
More efficient resource usage in large web farms
|
|
 |
|
File Integrity Checking
Checks files in the installation and reports any inconsistencies which may impact website reliability
|
|
 |
|
Health Monitoring
Pings the website periodically to identify failures and will notify the
site owner. Also ensures the site stays in web server memory for faster
user accessibility
|
|
 |
|
Vulnerability Database
Maintains a vulnerability database for each product version to easily identify potential issues
|
|
 |
|
Comprehensive documentation and online Knowledge Base that provide guidance for DotNetNuke administrative tasks and answers to common technical questions
|
|
 |
friends...
I have been re-awarded with 2009 Microsoft® MVP Award in .NET/ASP.NET Category. This is the second consecutive year as an MVP; and it feels like allmost full moon of my career!!
The mail I received:
Dear Kaushal Parik,
Congratulations! We are pleased to present you with
the 2009 Microsoft® MVP Award! This award is given to exceptional technical
community leaders who actively share their high quality, real world expertise
with others. We appreciate your outstanding contributions in ASP/ASP.NET
technical communities during the past year.
........ long live community :)
Hi all …
This time a great news for all the technology enthusiast and want to meet
great peoples in technology and you missed TechEd India 2009 so
you can attend now the same kind of event in Ahmedabad, India on June
20, 2009 Saturday(TechEd on Road) by 1:30 PM.
You will get a chance to meet Two MVP’S here Jacob Sebastian
and Pinal Dave , who presents
numerous technical sessions on SQL Server, Exchange Server 2010, Windows Server
2008 and Virtualization.
Anyone who is interested in technology can attend this event .This is free
event no charges will be taken to attend this event. You can get detailed
information about this event on Pinal’s
Blog and Jacob’s
Blog .
So mark your calendar for this grand event in Ahmedabad here are the details
of this event ::
Location ::
Hotel Rock Regency
C.G. Road
Ahmedabad, India.
Date & Time::
June 20, 2009 Saturday
1:30 PM
Just check out microsoft.com/areyoucertifiable
a funny dummy test environment who wants to appear and test yourself for ms certification. You can create login or can play as guest, select avtar. There are more than 400 Questions (objective - options to select) with 20 episodes and 5 seasons.
lol.. i loved this :)
The default behaviour of AJAX Accordion is: you click on any Accordion pane (say; any control placed in Accorion Pane Header section) cause that pane to Expand and collapse rest of the panes other than the pane which you clicked.
It is also fairly easy to open Accordion Panes when you "MouseOver" on Pane rather than need to click the pane to open it.

All you need to add a JavaScript function to ahieve that and call it or "MouseOver" event of ImageButton / Link / or any submit control which is placed inside Accordion Pane.
You need to add below script in your page:
<script language="javascript">
function Openpane(paneIndex)
{
//MyAccordion is the ID of AJAX Accordion control
var behavior = $get("<%=MyAccordion.ClientID%>").AccordionBehavior;
behavior.set_SelectedIndex(paneIndex);
}
</script>
You need to pass the current Accordion Pane index as asrument of the above script function and call this function on "MouseOver" event as:
<Panes>
<ajaxToolkit:AccordionPane ID="AccordionPane1" runat="server">
<Header>
<a href="" class="accordionLink" onmouseover="Openpane('0')">1. Accordion</a></Header>
<Content>
The Accordion is a web control that allows you to provide multiple panes and display
them one at a time. It is like having several Panes where only one can be expanded
at a time. The Accordion is implemented as a web control that contains AccordionPane
web controls. Each AccordionPane control has a template for its Header and its Content.
We keep track of the selected pane so it stays visible across postbacks.
</Content>
</ajaxToolkit:AccordionPane>
</Panes>
for every pane, you can call the script function on "MouseOver" event by passing the index of that pane as argument.
Thats it! Hope it would be helpful for someone in same need.
I need to add Captcha Control for couple of contact and submission forms to stop
possible spam bots. I tried with the similar way I approched In previous website
application developed in ASP.NET. But, Its even too easy to add Captcha capability
in forms than we do for simple websites. DotNetNuke/DNN is having a built in Captcha
control which can be used on contact and submission forms.
First you need to add register tag for the control on your module user control.
This will allow to create Captcha control and use it in code. The register line
goes as:
<%@
Register TagPrefix="dnn"
Assembly="DotNetNuke"
Namespace="DotNetNuke.UI.WebControls"%>
Next, is you need to create the control in ascx page as:
<dnn:CaptchaControl runat="server"
ID="dnnCaptchaControl"
ErrorStyle-CssClass="NormalRed"
cssclass="Normal"
ErrorMessage="The
typed code must match the image, please try again"
CaptchaHeight="35"
CaptchaWidth="120"
/>

Believe
me, you are done with DNN Captcha control! You only need to validate whether the
entered value for captcha by user is correct or not. You can write below code in
contact/sybmission form's submit button click event:
if(ctlCaptcha.IsValid)
{
//Captcha is valid! Code to submit
the contact/submission form...
}
else
return;
This
is a mere note to remember for future rather than a blog entry. While I am working
on code to download file from server. I write below code:
{
int ChunkSize = 10000;
string sFileFullPath = Server.MapPath("New Text Document.txt");
System.IO.FileInfo toDownload = new System.IO.FileInfo(sFileFullPath);
if (System.IO.File.Exists(sFileFullPath))
{
Response.Clear();
using (FileStream iStream = System.IO.File.OpenRead(sFileFullPath))
{
long dataLengthToRead = iStream.Length;
Byte[] buffer = new Byte[dataLengthToRead];
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
while (ChunkSize > 0 && Response.IsClientConnected)
{
if (ChunkSize > dataLengthToRead)
{
ChunkSize = int.Parse(dataLengthToRead.ToString());
}
int lengthRead = iStream.Read(buffer, 0, ChunkSize);
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
}
Response.Close();
Response.End();
}
else
{
this.Page.ClientScript.RegisterStartupScript(GetType(), "ShowMessage", "<script language='javascript'>alert('No Files Available');</script>");
}
}
When I ran the application I found that the file which I
need to download was containing spaces in its name like “New Text Document.txt”.
The problem is:
In FF, was truncating the filename from space while showing
the file download dialog . So, its only showing the filename as “New”
(and truncating the rest of the filename after space).

In IE, was replacing the spaces in filename with underscore
( _ ) as “New_Text_Document.txt” while showing the file download dialog
box.

This something I dont want to have. I need to have the exact
filename as it is on server.
The solution is:
For FF: you need to enclose the name of the file in Quotes
while you add it as attachment in response header as:
Response.AddHeader("Content-Disposition",
"attachment;
filename=\""
+ filename +
"\"");
For IE: you need to identify and replace the space in
filename with “%20” (something like encoding filename) as:
String userAgent = Request.Headers.Get("User-Agent");
String filename = toDownload.Name;
if (userAgent.Contains("MSIE 7.0"))
filename = toDownload.Name.Replace(" ", "%20");
Thats It! Hope it would be helpful for
someone in same need!
Complete Code would be:
{
int ChunkSize = 10000;
string sFileFullPath = Server.MapPath("New Text Document.txt");
System.IO.FileInfo toDownload =
new System.IO.FileInfo(sFileFullPath);
if (System.IO.File.Exists(sFileFullPath))
{
Response.Clear();
using (FileStream iStream = System.IO.File.OpenRead(sFileFullPath))
{
long dataLengthToRead = iStream.Length;
Byte[] buffer = new Byte[dataLengthToRead];
Response.ContentType = "application/octet-stream";
String userAgent = Request.Headers.Get("User-Agent");
String filename = toDownload.Name;
if (userAgent.Contains("MSIE 7.0"))
filename = toDownload.Name.Replace(" ", "%20");
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
while (ChunkSize > 0 && Response.IsClientConnected)
{
if (ChunkSize > dataLengthToRead)
{
ChunkSize = int.Parse(dataLengthToRead.ToString());
}
int lengthRead = iStream.Read(buffer, 0, ChunkSize);
Response.OutputStream.Write(buffer, 0, lengthRead);
Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
}
Response.Close();
Response.End();
}
else
{
this.Page.ClientScript.RegisterStartupScript(GetType(), "ShowMessage", "<script language='javascript'>alert('No Files Available');</script>");
}
}
I
am trying to validate textbox for numeric entry, while I added this
code to accomplish in page_load event:
textbox.Attributes.Add("onkeypress",
"return
(window.event.keyCode == 45 || window.event.keyCode == 13 ||
window.event.keyCode == 8 || window.event.keyCode == 9 ||
window.event.keyCode == 189 || window.event.keyCode == 109 ||
(window.event.keyCode >= 48 && window.event.keyCode <=
58) )");
It
worked fine in IE7 and IE8, but it didnt work for FF though. A bit
googling gave me conclusion that FF doest recognize
window.event.keyCode.
Basically
Firefox supports the which property instead of the keyCode property
IE does. By checking which (window.event.which)
of
them exists with an if statement we can reliably get the key that was
pressed.
I
replaced above code with:
textBox.Attributes.Add("onkeypress",
"var
key; if(window.event){ key = event.keyCode;}else if(event.which){ key
= event.which;} return (key == 45 || key == 13 || key == 8 || key ==
9 || key == 189 || (key >= 48 && key <= 58) )");
it
worked for both IE and FF. Hope
it would help someone in same need!
Here is another requirement (perhaps a common requirement!) I needed to implement
in one of on-going project website application. I needed to generate a PDF file
as output from the inputs entered by end-user in a form. On Completing the form,
end-user should be able to download a PDF file of what they have given the inputs
in the form.
I need to generate PDF file in a given format and force the download dialog to let
the user save generated PDF save on their/client machine.
I tried searching any free :) third party dlls which would help me to generate PDF
files on-the-fly. Things I tried:
[1] Tried searching almost third party tools/dlls
including
Siberix PDF Library
,
PDF Vision .Net etc etc, which are having similar functionality. But not FREE
:(
[2] Tried with
iTextSharp - Tutorial
and
PDFsharp - Download PDFsharp Version 1.20 These dlls/libraries are totally free
and really interesting to work with. All we need to do is define elements like HTML
and add those elements to PDF document object which then finally generated as PDF
document. But, this is the problem for me as I am having a huge PDF file needed
to generate as output and it would required a loot of time to code for a document
by placing line by line cells, TR and TD, Tables and background, Border colors,
images etc. and most of all is annoying Texts to be placed in those elements with
proper fonts, colors and padding/alignment.
At last after wasting time in googling and
on free tools/libraries, I got an idea to create PDF on-the-fly. I was thinking
of creating PDF files dynamically and I created it smoothly with out too much work
and code.
This is how it goes:
[1] I created a clean A4 size SnapShot of
the PDF file I needed to be generated dynamically.
[2] Next, I added a blank crystal report
to the solution.
[3] I added/set the PDF SnapShot as the background
of the crystal report by Right Click on the detail section of the crystal report
> Insert > Picture > and select the SnapShot and place it inside the detail
section with proper left-top padding.

[4] as of now, Crystal Report is showing
exactly same as the PDF file with blank inputs.
[5] next is, to accept inputs from end-user
and pass those inputs as parameters to Crystal Report.
[6 ] I declared required parameters those
are needed to pass runtime with the input values entered by end-user to Crystal
Report. And place those parameters object in the Crystal Report accurately in a
way, like those parameters were showing as the resultant values in PDF files. At
this time, Crystal Report is having PDF like look with parameters. For this I need to set the PDF SnapShot background "send to BACK" as:

Below are the declared parameters which will be passed dynamically after accepting/submitting user inputs.

This is how Crystal Report saw when Parameters placed on the Crystal Report Detailed section after moving the SnapShot to move BACK:

[7] After Declaring parameters, only thing
left is to pass values and directly export the Crystal Report in PDF file rather
than to show it on user screen. And after successful Export in PDF file, force download
dialog to let end-user save the generated PDF file.
Below is the Code to pass parameters dynamically
and force download dialog to save the file:
'create
the report document
Dim doc
As
New ReportDocument()
Dim fileName
As
String
= Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.rpt")
'load the rpt
file to document
doc.Load(fileName)
'pass the user
inputs to crystal report parameters those will sit in the output pdf file
doc.SetParameterValue("@CompanyName", txtCompany.Text.Trim())
doc.SetParameterValue("@CustomerName", txtFirstName.Text.Trim()
+
" "
+ txtLastName.Text.Trim())
doc.SetParameterValue("@Address", txtAddress.Text.Trim())
doc.SetParameterValue("@City", txtCity.Text.Trim())
doc.SetParameterValue("@Province", txtProvince.Text.Trim())
doc.SetParameterValue("@PostalCode", txtPostalCode.Text.Trim())
doc.SetParameterValue("@Phone1", txtPhone11.Text.Trim()
+
" - "
+ txtPhone12.Text.Trim() + " - " + txtPhone13.Text.Trim())
doc.SetParameterValue("@Phone2", txtPhone21.Text.Trim()
+
" - "
+ txtPhone22.Text.Trim() + " - " + txtPhone23.Text.Trim())
doc.SetParameterValue("@Phone3", txtPhone31.Text.Trim()
+
" - "
+ txtPhone32.Text.Trim() + " - " + txtPhone33.Text.Trim())
'set the export
options to PDF
Dim exportOpts
As
ExportOptions = doc.ExportOptions
exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile
exportOpts.DestinationOptions =
New DiskFileDestinationOptions()
' Set the disk
file options.
Dim diskOpts
As
New
DiskFileDestinationOptions()
CType(doc.ExportOptions.DestinationOptions,
DiskFileDestinationOptions).DiskFileName = Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.pdf")
'export the report
to PDF rather than displaying the report in a viewer
doc.Export()
'force download
dialog to download the PDF file at user end.
'Set the appropriate
ContentType.
Response.ContentType = "Application/pdf"
'Get the physical
path to the file.
Dim FilePath
As
String
= Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.pdf")
'Write the file
directly to the HTTP content output stream.
Response.WriteFile(FilePath)
Response.End()
Thats it!
Hope it would help anybody who need to develop similar functionality!
UPDATE:
incase, if anybody needs code in C#:
//create the report document
ReportDocument doc = new ReportDocument();
string fileName = Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.rpt");
//load the rpt file to document
doc.Load(fileName);
//pass the user inputs to crystal report parameters those will sit in the output pdf file
doc.SetParameterValue("@CompanyName", txtCompany.Text.Trim());
doc.SetParameterValue("@CustomerName", txtFirstName.Text.Trim() + " " + txtLastName.Text.Trim());
doc.SetParameterValue("@Address", txtAddress.Text.Trim());
doc.SetParameterValue("@City", txtCity.Text.Trim());
doc.SetParameterValue("@Province", txtProvince.Text.Trim());
doc.SetParameterValue("@PostalCode", txtPostalCode.Text.Trim());
doc.SetParameterValue("@Phone1", txtPhone11.Text.Trim() + " - " + txtPhone12.Text.Trim() + " - " + txtPhone13.Text.Trim());
doc.SetParameterValue("@Phone2", txtPhone21.Text.Trim() + " - " + txtPhone22.Text.Trim() + " - " + txtPhone23.Text.Trim());
doc.SetParameterValue("@Phone3", txtPhone31.Text.Trim() + " - " + txtPhone32.Text.Trim() + " - " + txtPhone33.Text.Trim());
//set the export options to PDF
ExportOptions exportOpts = doc.ExportOptions;
exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat;
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
exportOpts.DestinationOptions = new DiskFileDestinationOptions();
// Set the disk file options.
DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
((DiskFileDestinationOptions)doc.ExportOptions.DestinationOptions).DiskFileName = Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.pdf");
//export the report to PDF rather than displaying the report in a viewer
doc.Export();
//force download dialog to download the PDF file at user end.
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = Server.MapPath("~/DesktopModules/OnlineForm/OnlineForm.pdf");
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();

Core ASP.NET: This Refcard summarizes the most commonly used core functions and controls in ASP.NET
Try it! Its free but requires registration.
More Posts
Next page »