Programmatically Embedding another file to the word document

Hi

Many a times we want to embed some document in the word file, with the help of Insert-> File-> Select File menu item. This will copy the content of the file to the word document. This can also be done programmatically. 

String LocationOfFileToMerge = "C:\\Myfile.doc";

range.InsertFile(LocationOfFileToMerge,ref oMissing, ref oFalse, ref oFalse, ref oFalse);

We can also embed the document in the word file instead of copying the text of the document. In this case you can embed any kind of document.


Object NameForLabel = "File Name";

Continued...

Word Automation and Basic text formatting option

Hi,

when you start working with word programmatically, many a times you will have to add some text in the word document with formatting. Word automation gives you easy way top format the text that you are writing in the Word document programmatically.

To make the same impact as would an enter button in the word document we can use the following code.

oWord.Selection.TypeParagraph();

Basically this will enter a new paragraph in the word document. But you are in a bullet mode than this will take you to next line and also add the next bullet in the sequence.

Some of the common word formatting functionality can easily be performed with the help of word automation.

Continued...

Word automation and find and replace in Word document

Hi,

In My last two posts I talked about

·         How to open and close a word document programmatically.

Continued...

Saving word document in different format using Word Automation

Hi,

In my last post I talked about how to open and close a word document programmatically. In this post I will talk about how we can save the word document.

While using a word document there can be three kind of save functionality that can be required.

1.       When we open an existing word document and make some changes to the word document and save the word document.

Continued...

Microsoft word 2007 automation with C Sharp

Hi,

Some time in our project we need to work with word (winword) document programmatically. Word provides a good way to automate nearly all the functionality that can be used through interface.  The process of programmatically working with word document is commonly termed as word Automation.

I will be using a series of blogs to discuss some of the functionality that can be achieved through word automation. In this Blog I will discuss how we can start programmatically open a new or and existing word document and close it.

To work with word 2007 automation we need to have the word 2007 installed in the machine where the application will run. When we install the word 2007, it also installs with it the com component required to automate word 2007.

Continued...

Large Blob Data problem in Oracle stored procedure

Hi,

Few days back I was working with Oracle database and one of my stored procedures which was inserting a blob data to the database.  But I started getting a strange when the data in the blob data type got large. For large blob data I was getting the following error.

ORA-01460: unimplemented or unreasonable conversion requested.

The system would work consistently for small files but for large files I was getting this error.  After Doing a bit of Google I found that this is a drawback of using stored procedure in Oracle database.  If you try to pass over 32 Kb (or greater than 32512 char of string) then oracle will give this error in case of Blob data type.

Continued...

Asp.Net List Box control and flickering issue

Hi,

Last few days I was working on a page which had lots of list box in it which had multi select option. My master page also had a Menu control for the navigation purpose.  One major problem I was facing was with the flickering of the List box as soon as take my mouse over the menu.

Continued...

Handling Dropdown list inside Gridview with Autopostback

Hi,

Many a times there are circumstances where by we need to use dropdown list inside a Gridview and also handle the index changed event of the dropdown list. The easy example of this kind of requirement would be when we nee to fill another dropdown list in the same row from the value selected in the first dropdown list.

We all know that the dropdown list does not support command name property so you cannot handle the event in the row command event.

Continued...

Sorting and Paging Gridview without datasource control

Hi

Many a times while working with Gridview we want to work with the paging and sorting functionality without using any datasource control. Gridview is flexible enough to perform these tasks without the use of any datasource control and only a few lines of code.  

For paging a Gridview manually we have to handle the Gridview’s PageIndexChanged Event.  In the event we need to change the PageIndex of Gridview to the page that user has clicked and again bind the Gridview.

Continued...

Creating a list of the data cached at a point in the asp.net Application cache

Hi,

 

We all know about the use of caching in our application. With good use of cache we can increase the performance of the application considerably since application does not have to process the stuff again and again. But if we use too much of caching in the application, it can be problem. After all the data in the cache has to be stored in the memory and most of the application have limited memory. And more so in case of shared hosting.

 

Continued...

Going mouse less using keyboard shortcut in Asp.Net

Hi,

 

Many a times when working with the Web Application you would like to give the user the comfort of getting the job done without using the mouse. It can be of great use to the user if they can perform many tasks using the keyboard in a web application. If you have used Gmail you would know how easy it can be to select mails using some key.  This feature can be implemented in Asp.net also very easily.

 

Continued...

Content Page referencing content in Master Page

Hi,

 

Many a times while using a master page we want to refer content, Controls and properties in Master Page while working in Content page. We come across requirement where by we can change or access the values of controls residing in Master page when we are coding in the content page itself.

 

We can write code in the content pages to access properties, methods and controls in the master page, but there are some limits to it. We can only work with those properties and methods which are declared public. For controls we can refer any control on the master page independent of referencing public member.

Continued...

Redirect and refresh a page using the Meta tag

Hi

 

Many a times we have a requirement where by we want to make a pager refresh by itself at a certain interval. We may also want to redirect the page to another page after a certain amount of time. I know we can do this with the help of Asp.Net Ajax Extension’s Timer control. But that can only be used when you are using Ajax in your page and more importantly should be used when you have requirement to update some small section of the page. For this requirement we can simply use a Meta tag in the Page header.

 

Continued...

Obsolete API list for Dot Net framework 2.0

Hi,

Microsoft has come out with a list of APIs which have become obsolete in the .Net Framework 2.0. The same can be accessed from: .NET Framework V2.0 Obsolete API List. The list also contains alternate APIs that can be used for most of the obsolete APIs. In case there is no alternative suggested then this means that there is no replacement for the API.

You can also check the list grouped upon Asembly Here and Grouped by Namespace here.

Vikram


Using ObjectDataSource and passing Object as a parameter

Hi,

 

ObjectDataSource was a great addition to Asp.Net 2.0. But when working with asp.net 2.0’s ObjectDataSource had one limitation when working in Visual Studio designer. When working with ObjectDataSource we cannot pass object as a parameter. We always need to pass string, integer etc as the parameter.

 

But many a times we want to pass some object as parameter instead of passing all the values as string. Passing all the values can also be difficult when working with large number of columns.

 

Continued...

Concurrent request and how session behave

Hi

 

We all have worked with Asp.Net session objects in some point of time. An interesting question came in between the discussion with my colleagues on concurrent request and session state.  Here is what I have to share with all on session and concurrent users.

Continued...

Use Retail attribute to define that all the application run in release mode only

Hi,

 

Lets say you are running multiple application in a single machine, and want to make sure that all the application run in the release mode (debug is false, page output of trace is false etc..). These settings can easily be changed in the web.config. and you do not want any application to run with these setting even by mistake.

Well Asp.Net has a way for that also. You can set the attribute retail to true in the deployment tag inside the System.Web tag in Machine.config.

 

<System.Web>

   <deployment retail=true />

Continued...

Template column and HTML Encoding

Hi,

 

I have seen this question a few times in the forum so decided to blog on that. Many a times we store HTML characters in the database. When we want to show these values in the Gridview, detailsview or similar control.

But when we are displaying the value we want to encode (or sometime even decode) the value displayed. With bound column we get a property to HTMLEncode the value, but what do we do when we are using template column.

 

When we are using template Column we have two ways to HTML Encode (or decode the data). Firstly we can do the encoding in code in the rowdatabaound event

Continued...

Using 301 redirect in the Search Engine friendly web world

Hi,

When working in a Search engine friendly world, every small detail in your page and programming matter on how you can move your site in top position in the search engine. One of those important matter is how we redirect a page to another page.

 

By default we use response redirect which causes a 302 Redirect. For a search engine 302 redirect means that the document has only been temporarily moved and not permanently, hence the search engine will continue to index that page and show it in search result.

Continued...

Multiple column sorting in dataview

Hi,

 

Yesterday I was wondering through the msdn and found an interesting stuff that I did not knew before. I have worked with Dataview many a times and know how to work with it sort property. The sort property takes a string. The string is the columnname on which the dataview will be sorted.

 

What I did not knew was that the dataview can be sorted on multiple columns using the sort property. For sorting the columns on multiple columns we need to separate the columns with a comma. To define the sort direction we can use ASC or DESC after the column name.

Here is an example on how to sort a dataview in multiple columns

Continued...

Showing row number in Gridview

Hi,

 

A few days ago some one asked me this in a mail. After thinking on this a bit I decided to make a post as I thought this might be useful to many. Many a times while using a Gridview or a Datagrid we want to show a row number along with the Row, so that its easy for the user. The row number should always start from 1 no matter what the sorting is.

 

Continued...

Less known important functionality of Request Object

Hi,

Today I was discussing with my friends about some of the cool stuff available in the request class but rarely used or talked. After the talk I discussed on posting them in the blog.

The first in the list is the Request.AcceptTypes. The property returns an array of all the mime types supported by the browser. The results were interesting for me. The number of mime type supported by IE7 are far more than Firefox. The extra mime types included in IE are image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword. This means that IE can easily recognize these file types and open them in correct application.

Continued...

C Sharp how to find if a given string is a number or not

Hi,

When using JavaScript many a times we have a requirement to find if a value is number or not. With JavaScript its pretty easy, as it gives us a function isNaN which tells us if the string is a number or not. But how can you tell in C# if a string is number or not?

When I confronted with the problem, one of the solution was to use the int.Parse() method inside a try catch block. Below is an example of what I meant

try

{ int.Parse("5000"); }

catch

{ }

Continued...

Creating a generic function to work on all the similar controls in a page using the delegate

Hi,

Of late I have found this one question related to finding controls inside the page dynamically and apply some similar function to them. Like put a css class to all the textbox (or for that matter any control) in a page. Remember a page can have textbox as a control directly under it, or the textbox can be inside another composite control (like login control, gridview, detailview) inside the page.

Many a times we do not want to do this work for individual control but rather have a function, which will do this for all the control in the page. This way it becomes more maintainable and easy to implement.

Continued...

Finding more about Asp.Net Environment using the GetEnvironmentVariables method of Environment class

Hi,

What do you do when you need to find the values of various environment variables in the system like USERDOMAIN, PROCESSOR_ARCHITECTURE, COMPUTERNAME, USERNAME, PROCESSOR_IDENTIFIER, etc. well with asp.net this can be a very simple Job. You can get all these value along with a set of other values with the help of

Environment.GetEnvironmentVariables().

The static function returs the IDictionary collection of the Envirement varibales. To view the value you need to know the key for each value. But its not always known to us.

So what you can do is bind the dictionary to a grid view and see all the keys and values avilable.

Continued...

Preventing one click attack on you site by using ViewStateUserKey

Hi,

One of the very rich security feature and also one of the least known is the ViewStateUserKey. The key is used to add an identifier to the individual user in the viewstate variable for the page.

The value of the variable needs to be set in the page’s init phase. If you try and set the value in page load then it will give an error. Normally the value will be set to a value which is unique to individual users. Setting a constant value for all the users is equivalent to keeping it null. Normally we can fill the value with the userId or sessionID. For many technical reasons it is best to use the sessionID for the same (SessionID are unique, varies from time to time and are different from individual users.).

Continued...

Subkeys scope limitation of a cookie in Asp.Net

Hi,

In My last 2 posts I have talked about the overview of cookie and how to read and write with the help of a cookie. In this post I will talk about some of the more advanced work that can be done with cookie in Asp.Net.

Many a time we just don’t want to store some values in cookie but a collection of name value pair in a cookie. Remember that there are many limitations in number of cookies you should use. If we use more number of cookies in our application then the possibility of browser deleting the cookie will increase. Hence we should try and use less number of cookies and utilize a cookie to store maximum amount of data.

Continued...

Asp.net Reading and writing value in cookies

Hi,

In my last post I wrote about and overview of cookie, there basic use and some of their limitation. In this post I will talk on how do we read and write cookies with the help of Asp.Net.

When a browser makes a request to the server it also send existing (at the browser end) cookies information for that website. In Asp.Net the HttpRequest (also referred as Request property in the page class) objects contains a collection of all the cookies sent by the browser.

We can read the cookies from the request object like this.

if (Request.Cookies["lastVisit"] != null)

Continued...

Asp.net cookies an overview

Hi,

When working with a web application many a times we want to store the client specific data on the client side only. This helps in showing personalized data for the client. The session maintained by default is also done with the help of the session cookie only.

In a layman developer word a cookie is a small amount of data that is passed between the client and the server in the request and response. The data in the cookie can be read in interpreted by the server and is sent to the server whenever the user visits the same site.

But remember maintenance of cookie also depends on the user. Many user can turn there cookie off or the users can delete the cookies in there cookies. Moreover client can read the information kept in the cookie. That is why cookie cannot be used to store sensitive data.

Continued...

How to read XML data sent in a post request

Hi,

A few days ago I posted about how we can send XML data as a post request to any URL. You can read the stuff here. After that many people have asked me on how we can read the data when data is sent as a Post Request.

Reading data when it is sent as a post request value is very simple. We use the Request.InputStream to read the incoming stream request. Here is a glimpse of code to work with the same.

byte[] b = new byte[Request.ContentLength];

Request.InputStream.Read(b, 0, Request.ContentLength);

Here we first get the length of the request and then read the same in an array of byte.

We can convert the bytes into a string by using correct encoding. (Note: I am using the UTF8 encoding for example).

Continued...

How to prevent client cache and getting a server request even when back button is clicked

Hi,

Many a times we do not want browser to show data from cache. For example when user hits the back button of the browser, the browser shows the last page from the cache and does not make a post back to the server. (This is why when some one clicks on the back button of the browser the system looks so fast).

But many a times we do not want the browser to show data from the cache. There are requirements where the data is very dynamic and if browser shows the data from the cache then it can give wrong indication to the user.

Controlling the back button of the browser is not such a good idea because we are trying to stop the user at the client end.  But what we can do is ask the browser to not to cache the page in the client end and always make a call to the server before showing the page.

This can be easily done by expiring the response. Here is the code for the same.

Continued...

How to create a POST request and send XML data

Hi,

Many a times when we are working with the third party services we have to pass the data to the third party over the web. Most of the times we pass the data in the querystring. The data is passed in a get request along with the querystring. The third party takes the value from the querystring and process the data.

But many a times the data need to be passed in the Post method. Many a third party component takes the data in XML format in the POST request. In these cases we have to pass the data as XML string in the post request. Here is an example on how to pass XML in the post request.

string xml = “SomeXML Data”;

string url = @”http://www.vikramlakhotia.com/HomePage.aspx”;

WebRequest request = WebRequest.Create(url);

Continued...

Using tag mapping to change the mapping of user control through out the application

Hi,

Lets say you are working in a fairly large asp.net application. You have about 200 web pages. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control.

This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 or Asp.net 3.0, wait, there is a very easy way to get this done.

Tag mapping seems to be made for these kinds of situations. In asp.net 2.0 we can map tags in web.config. With the help of tag mapping we can remap the tag types to other tag types at compile time.

The remapping will make all the original tag to use the new mapping for all the pages and user control in the asp.net application coming in scope of the configuration file.

Continued...

Reducing the size of HTML by removing the ID of control when not required

Hi,

Many a time we have many server controls with long Id which are never required once there value has been set. We normally disable their viewstate to reduce the size of both viewstate and the page. Especially if these controls are inside nested repeaters (or grid view or likes) the view state size can be huge.

Making the viewstate false reduces the size of the viewstate but when these controls are rendered they render with a long ID. If we are using a master page than the ID of such a label (or other controls) would be something like Ctl100_ + Contentplaceholderid + Repeater Name + ct102 + the label of control. If the repeater is nested than the name of ID can be very very large.

Continued...

What are the limitation of different trust level in a application

Hi,

Most of us have worked with web application and one thing which is very commonly heard is of trust level at which the application is running. I have read many articles which talks (in some way or the other about trust level of the application). But I also feel that most of the developers do not know the limitations or capabilities of different levels.

Here is a list of major restriction and capabilities for an application at different trust levels.

Full trust –

No restriction is imposed on the application by the code aces security.

High trust  -

Continued...

Difference between ASP.NET Server Controls and HTML Server Controls

Hi

ASP.NET Server Controls

Advantages:

1. ASP .NET Server Controls can detect the target browser's capabilities and render themselves accordingly. No issues for compatibility issues of Browsers i.e page that might be used by both HTML 3.2 and HTML 4.0 browsers code is written in the Server Controls.

2. Newer set of controls that can be used in the same manner as any HTML control like Calender controls. Without any need of Activex Control without bringing up issues of Browser compatibility).

3. Processing would be done at the server side. In built functionality to check for few values(with Validation controls) so no need to choose between scripting language which would be incompatible with few browsers.

Continued...

Multiple session updating the application variable at same time

Hi,

Many a times we want to keep some values in our application, which should be available Application Wide. We normally keep these values in the application variables. This is very handy and fast to use.

One of the examples of use of Application Variable that I normally use is a Boolean value describing if the application is running locally or Live (Production). The value is retrieved in the Application_start event from the web.config file. This is very handy as at many point in the application I keep a check on the work to be done based on this value. And I do not have to refer to the config file all the time to know if the application is running locally or on production.

Writing and reading to an application variable is very simple. We can write to an application variable like this.
Application["Local"] = false;

Continued...

Asp.Net 2.0 referring to another page, user control with the help of Reference tag

Hi,

In Asp.net 2.0  if we want to create the object of another page  (in the same application) then we can not do it. We get a compiler error in this case. The reason is that each page is compiled into an assembly (We can also make the directory to be compiled in the same assembly). Hence the two pages might not be in the same assembly. And hence we are not able to create the object of another page in the same web application in another page (As they will not be in the same assembly).

But many a times we want to create the object of another page in the code behind class. I know we can use a base page (will be kept in App_Code folder) for all class and derive all the pages from that class. Now we can create the object of the page by typecasting the base page. But this will not solve the entire problem. As we will not have all the methods of the individual class.

Continued...

Finding the Virtual path of the web Application

Hi,

Many a times we want to find the Virtual path of the Web Application. Getting the virtual paths local to server is pretty straight forward Page.ResolveURL("~").

If you require the same in the BLL, then you have to use the System.Web.HttpRuntime.AppDomainAppVirtualPath

Remember if the web application is in the server root then the following command will return “/” and if the web application is not in the root folder then the command will return the path of the root folder without the “/” in the end.

Vikram


An overview of use of predicate with generic List

Hi

Predicate are type of filter which can filter data based on certain criteria. Predicate is a generic delegate which represents a method that defines a set of criteria to filter records in a generic list.

Lets take an example of a generic list of string.

List<string> strName = new List<string>();

Now let say we want to fetch those data which starts with V. Without predicate we would write something like the code below.
for (int i = strName.Count - 1; i >= 0; i--)

    {

        if (!strName [i].StartsWith("V"))

        {

           strName.RemoveAt(i);

        }

Continued...

Passing ReadOnlyCollection using the AsReadonly method so that user cannot modify the list

Hi,

This was new to me so as always I decided to share with all. The generic List has a method AsReadonly. The methods can be used if you want to pass the list as readonly. The return value of the method is a ReadOnlyCollection.

The ReadOnlyCollection acts as a wrapper around the list. The only difference of a readonlycollection and a list is that a readonlycollection has a wrapper around it which prevents the modification of the collection.

If there are changes made to the underlying collection, the changes will be refelected in the readonly collection.

Let’s say you have a private collection (list) and want to expose it as read only format. This is when this method will be useful.

Vikram


Asp.Net 2.0 Page Element attributes and there meaning

Hi,

In asp.Net 2.0 there are many attributes in the page tag itself. Each attribute has a special meaning to it. These attributes are defined in the page so that we can specify them for specific pages. Most of them are also defined globally so that we do not have define them in the page.

Here is a list of attributes of the Page Tag.

asyncTimeout – This is an optional attribute to define the timeout for the asynchronous handler during asynchronous processing of the page. The default value is 45 sec.

autoeventWireup – This is also an optional attribute that defines if the events in the page are automatically enabled. The default value is true. This means

if we define a Page_load(with same signature) method in the page class, the event will be automatically be attached with page load method.

Continued...

Logging the exception of the Asp.Net application with the help of HttpModule

Hi,

One of the most critical aspect of and asp.net application is exception handling. When an application is there live on the web there can be an exception happening. These exception needs to be logged so that they can be rectified later.

There are many inbuilt ay in which this can be done. Like we can handle the exception at page level, or at the application level or even better create a simple reusable module that can be used in multiple applications.

In this post I will show how we can log the exception in an application. There are three prominent places where we can log the exception.

1 In a text file (or in XML format)

2 In a Database (I know text file is also a database but I meant a RDBMS)

Continued...

Session_End and mysttries on when does it fires in Asp.Net

Hi,

Following my post on few interesting things about session in Asp.Net many people asked me about the Session_End event. You can read the earlier post here.

Many people have asked me on exactly what are the reason for which the Session_End event fires. So I thought I would write a post on the same.

Continued...

Asp.Net and Session – some Interesting Facts

Hi,

Yesterday I was discussion with my colleagues about session and a few interesting things popped up. So I thought I would share the same with all.

If we have the session state enabled and we do not store anything in the session then the session Id will change every time a new request is made. This also means that a new session is created every time. But the sate is never saved as there is nothing to save. Note the session_Start event will not fire for every request. The session_start event will only fire once.

Another interesting stuff about session Id is that it does not changes after we have called the Session.Abondon() method or when the session times out. Even though Session State expires but the session ID remains same. The session Id will last as long as the browser session does.

Continued...

string.compare and string.Equals the difference in usage of culture

Hi

In the string class we have 2 methods to compare the string. I see most of the developers get confused between the 2. Both string.Compare and string.Equals methods are used for string comparison but they significant difference between them. The use of wrong method can lead to globalization and security issues.

String.Equals perform an ordinal comparison while string.Compare performs a culture sensitive comparison.

Continued...

Working with different path in the Request Object in Asp.Net

Hi,

When we are working on an asp.net Application we have to work with various type of Path. These paths are present in the Request Object. Each path has a different meaning and way for representation. Here is a list of different kind of paths used in Asp.net

Application Path – Will return the root path of the application. This is used to get the application path. This can be found in Request Object. By the default the

CurrentExecutionFilePath – used to get the virtual path of the current request. The difference from the FilePath property is that if there is a redirection of the request in the server code (Server.Transfer) then this will return the correct value. For example it might return the value /Vikramlakhotia.com/MyAdm/LogFeed.aspx

FilePath – will provide the Virtual Path of the current request. (See the difference with CurrentExecutionFilePath above.)

Continued...

Asp.Net Web Application different file types

Hi,

A web site Application can have multiple files of multiple file type. Many of these are managed by Asp.Net and many by IIS itself. File types that are managed by the Asp.Net are mapped to AspNet_isapi.dll in IIS. The file types that are not mapped to AspNet_isapi.dll are not managed by asp.net but by IIS only.

Here is a list of all the file types that are managed by Asp.Net.

.asax – The common most example is the Global.asax file. This normally contains code that is derived from HttpApplication class. The file contains application level event that are raised by application like Application start, application end etc. The file has to be kept in the root folder of the application.

.ascx – This file type is used to create web user control. The file can reside in either root folder on in a sub-directory.

.ashx – The file type is used to create generic handler by implementing the IHttpHandler interface.

Continued...

CompilationMode enumeration for the page tag in asp.net 2.0
Hi,

One of the new attribute of the page tag in Asp.Net 2.0 is the CompilationMode attribute. The attribute is used to specify whether the Asp.Net compiler should compile the page or not at the runtime. The attribute has been added new in the asp.net 2.0.

The attribute can have 3 possible values. Always, Auto and Never. The default value is Always. As the name suggest the always and never value are used to tell the compiler to compile the page always or never respectively. Auto value means that Asp.Net will only compile the page if required.

Setting a page to never compile using the Never attribute will increase performance by disqualifying the specified page in the compilation process. Here is how we set the attribute for a particular page.
<%@ page compilationMode=”never”
Continued...

Option group control now with indentation for group member

Hi,

Here is an update to the option control that I posted a few days ago. The control allows you to show group in dropdown list and list box