Saturday, December 19, 2009

How to add validations to a FileUpload control in c#

I found a great article that demonstrates how to validate a File Upload control in APS.net.Here we can use simple asp.net required field validators & regular expression validators easily to filter file formats.

The following article gives an excellent demostration.

http://msdn.microsoft.com/en-us/library/aa478971.aspx

Thursday, December 17, 2009

How to Poppulate a dropdown in a gridview in Row Editing

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}

That if will only be valid for a DataRow (the actually row with data) and if it's in Edit mode... because you only Edit one row at a time the e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.

For More Info....

Visit

http://stackoverflow.com/questions/833490/asp-net-3-5-gridview-row-editing-dynamic-binding-to-a-dropdownlist

Tuesday, December 15, 2009

asp.net ajax client-side framework failed to load.

I got an error saying that "asp.net ajax client-side framework failed to load."

But it was working fine yesterday.Even code reverting didn't work for me.Then I found .Net 3.5 SP1 in my Control Panel - Add/Remove Programs. I clicked Change... and was relieved to see a "Repair" option.

With bated breath I waited for Windows to complete the repair. After a few minutes, I saw that the repair was complete. Now for the test. I ran my web application and all of the Ajax errors disappeared.

Perhaps this was coincidental; who knows. I suppose I could go through my logs, but I'm back in business and that is good enough for me. Of course, this doesn't explain how Ajax got broken in the first place.

Sunday, December 13, 2009

Ajax Grid View With Insert Edit Delete

I found an excellent article on internet.

http://ramanisandeep.wordpress.com/2008/11/16/gridview-insert-update-delete/

Thursday, December 3, 2009

Disadvantages in content editor web part in sharepoint

Unfortunately there are several serious issues with Content Editor :

  1. Content Editor Web Part content isn’t versioned. You can create as many versions the web part page as you like, the actual content – which is contained within the Content Editor Web Part – isn’t versioned. This is a wider problem with web parts in general, but especially of note when attempting to provide web content management.
  2. Content Editor Web Part content can’t be searched. Yes, this is as bad as it seems. Add your content to the Content Editor Web Part and it can’t be seen by the WSS Search.

There is another issue with the Content Editor Web Part; whenever you re-open the web part to update content it turns all server-relative URLs into absolute URLs. Therefore if you have your content accessible from different addresses (when you have an extranet and an intranet for example) any linked content will be broken for one of them as soon as anyone updates the content. The only way around this is to edit the HTML directly. Hardly suitable for non-technical users.

Solution

In a nutshell: create a Content Type to contain the web content within the page itself and make use of the superior Telerik RadEditor Lite content editor.

Thursday, November 26, 2009

Advantages of storing images in database over file system

  • If the images binary data is stored in a database table, we have all the data required to make the image any size we want, and it will always look like the orginal image

  • If the images binary data is stored in a database table, when we back the database up, we have also backed up all the users images

  • We can store meta data corresponding to the images that we store

Tuesday, November 17, 2009

How to Add & Retrieve Images from a SQL database using LINQ in c#

Today I received an email from a friend, asking how to save a binary file in to the database using LINQ to SQL. This was the second time a person had asked me the same question, So I thought of having a blog entry about it.

Assume that we need to upload a file and save its name, and the file in the database table. so lets see how we do it.

This is my Table

CREATE TABLE [dbo].[Files2](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FileName] [varchar](50) NOT NULL,
[FileSource] [image] NOT NULL,
)
GO
And The Following Stored Procedure is used to Insert the Value:
 
CREATE PROCEDURE [dbo].[ADDFILE]
(
@FILENAME VARCHAR(50),
@FILESOURCE image
)
AS
SET NOCOUNT ON

INSERT INTO Files([FileName],[FileSource])
VALUES(@FILENAME,@FILESOURCE)


1.Storing Images

The following code is used to upload and save the file using web form with a text box for file name, and a file upload control to upload the file. on the click event of a button this code is called.

protected void Button1_Click(object sender, EventArgs e)
{

if (FileUploader.HasFile && FileUploader.PostedFile.ContentLength > 0)
{
string filename = txtFileName.Text;
//Read the file in to a byte Array.
byte[] filebyte = FileUploader.FileBytes;

System.Data.Linq.Binary fileBinary = new System.Data.Linq.Binary(filebyte);
MyDataDataContext MyData = new MyDataDataContext();

MyData.ADDFILE(filename, fileBinary);
lblStatus.Text = "File Uploaded Successfully!";

}
}

The Main thing to remember here is that we need to pass the FileUploader.FileBytes to the constructor of System.Data.Linq.Binary.

2.Rerieving Images

context.Response.ContentType = "image/jpeg";

MyDataDataContext ctx = new MyDataDataContext();

//This part os for to getting the image file from data base
Img img = ctx.Imgs.SingleOrDefault(c => c.id == 2);
byte[] ret = img.image.ToArray();

context.Response.BinaryWrite(ret);



Monday, November 16, 2009

How to Add FreeTextBox - Rich Text Editor - in C#

This tutorials explains how we can add custom controls to our project, and how to programmtically access the control's properties and methods. C# version.

ASP.NET's built-in controls are very useful, but unfortunately do not provide everything we want. Thankfully, ASP.NET allows us to create custom controls. This tutuorial will focus on how we can implement these custom controls for use in our projects.

We start by adding a Bin folder to our project. To do this, right-click the main project in the Solution Explorer and choose Add ASP.NET Folder > Bin. Once the Bin folder appears in the Solution Explorer, we can right-click this and then choose Add Existing Item. We can then simply browse to the location of the assembly file (.dll or .pdb). In this example, we are using the FreeTextBox control which can be downloaded from www.freetextbox.com and is the no.1 choice for a free HTML editor in ASP.NET Custom Controls. Once we have added the FreeTextBox.dll to our project, we can use it.

We can also add this to our toolbox for dragging & dropping like other controls, by right-clicking a blank area of the toolbox and choosing Choose Items. If FreeTextBox is not in the list, we can click on the Browse button to locate it. Once in the list, make sure it is selected (ticked).

Once you see the icon in the toolbar, drag it onto the page you want it to be displayed. Doing this will add the following to the top of your page:

<%@ Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>

I just signed up at Server Intellect and couldn't be more pleased with my Windows Server! Check it out and see for yourself.

And you will also see the following where we want the FreeTextBox custom control to be placed:

<"FTB:FreeTextBox ID="FreeTextBox1" runat="server"> '<'/FTB:FreeTextBox'>

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

This is all that is needed for us to use the control within our page. However, if we want to interact with the control programmatically, we will have to add the assembly reference to the code-behind:

using FreeTextBoxControls;

The above code will allow us to reference the FreeTextBox in our code, and also allow us to access its properties and methods. However, if we are using a naming container such as a MasterPage, we will need to use the FindControl method as well. This will be done by writing code similar to this:

FreeTextBox myFreeTextBox = (FreeTextBox)Master.FindControl("FreeTextBox1");


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeTextBoxControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FreeTextBox1.Height = 150;
FreeTextBox1.Text = "We are using the <:b>Custom Control FreeTextBox<:/b> and changing its Text attribute programmatically.";
}
}


We migrated our web sites to Server Intellect over one weekend and the setup was so smooth that we were up and running right away. They assisted us with everything we needed to do for all of our applications. With Server Intellect's help, we were able to avoid any headaches!

Or if we had to use FindControl, it would look something like this:



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeTextBoxControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FreeTextBox myFreeTextBox = (FreeTextBox)Master.FindControl("FreeTextBox1");
myFreeTextBox.Height = 150;
myFreeTextBox.Text = "We are using the <:b>Custom Control FreeTextBox<:/b> and changing its Text attribute programmatically.";
}
}

How To Add a Rich Text Box To Your ASP.net - C# -Web Site

You can use FCKEditor for your purpose.

I found a good link & like to share with.

http://www.codedigest.com/Articles/ASPNET/208_Integrating_FCKeditor_in_ASPNet_Websites_%E2%80%93_Part_1.aspx

http://www.codedigest.com/Articles/ASPNET/217_Integrating_FCKeditor_in_ASPNet_Websites_%E2%80%93_Part_2.aspx

Thursday, November 12, 2009

Exporting GridView to Excel Without installing Microsoft Office On The Server

In this code snippet, I will show how you can export data from a GridView control to a Microsoft Excel spreadsheet.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}

private void BindData()
{
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}

private string ConnectionString
{
get { return @"Server=localhost;Database=NorthWind;Trusted_Connection=true"; }

}
protected void BtnExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";

// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}


In the above listing, the GridView control will be populated with the data from the Categories table of the Northwind database. You will have to give the appropriate Server name or IP instead of localhost as server name in the above connection string.

If you use this code and try to export the GridView control, you will see an error message saying that the GridView control must be placed inside the form tags with the runat = server attribute.

This is pretty confusing, since your GridView is already inside the form tags and also contains the runat = server attribute. You can easily resolve this error by adding the following lines.

Listing 3: Overiding VerifyRenderingInServerForm Method

public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */

}

Yup, that’s it. Now, when you click the button, the GridView control will be exported correctly. It will prompt you either to open the file as it is or to save it elsewhere.

Get further details & download the sample here

Wednesday, November 11, 2009

Visual Studio 2008 code snippet for adding a new property

Now if you type prop and hit "tab" twice, this will bring the Automatic property not the conventional property declaration.

Thursday, November 5, 2009

Configure Search On sharepoint

The following procedures step you through the process of configuring Office SharePoint Server 2007 search services, creating a Web application for the SSP, creating the SSP, and configuring indexing settings.



Start and configure the Search service

1.On the SharePoint Central Administration home page, click the Operations tab on the top navigation bar.

2.On the Operations page, in Topology and Services, click Servers in farm.

3.On the Servers in Farm page, click the server on which you want to configure the search service.

4.Click Start next to Office SharePoint Server Search.

5.On the Office SharePoint Server Search Settings page, in the Query and Indexing section, make sure that the Use this server for indexing content and Use this server for serving search queries check boxes are selected.

6.In the Default Catalog Location section, type a path to a physical folder to store the index files, or use the default location that is specified.

7.In the Contact E-Mail Address section, specify a valid e-mail address.

8.In the Service Account section, click Configurable, and in User name and Password, type the user name and password for the user account under which you want the Search service to run. The user account must be a member of the Administrators group on the computer that is running the Search service. If you want to use the principle of least privilege and select a unique user account that does not have administrative rights on your front-end servers or on your back-end database servers, see the Known Issues/Readme for Office SharePoint Server 2007 Beta 2. The user name must be in the format DOMAIN\username.

9.In the Web Front End And Crawling section, do one of the following:
If you are configuring the search service on a server that provides Web services and renders Web content, click No dedicated Web front-end computer for crawling
If you are configuring the search service on a server that is a standalone search server that does not provide Web services and render Web content, click Use a dedicated web front end computer for crawling, and then, in Select a web front end computer, click the computer you want to use for crawling.

10.Click Start.

Start the Windows SharePoint Services Web Application service

You must start the Windows SharePoint Services Web Application service on every computer that you want to act as a Web server and was set up using the Complete option during Setup. This service is started by default on servers that were set up using the Web Front End option. To enhance security, you can leave this service turned off on application servers that do not provide Web content to client computers. Also, you do not need to turn this service on to use SharePoint Central Administration on a server.

1.On the SharePoint Central Administration home page, click the Operations tab on the
top navigation bar.

2.On the Operations page, in Topology and Services, click Servers in farm.

3.On the Servers in Farm page, click the server on which you want to start the Windows SharePoint Services Web Application service.

4.Click Start next to Window SharePoint Services Web Application.


Create the Shared Services Provider

1.On the SharePoint Central Administration home page, click the Application Management tab on the top navigation bar.

2.On the Application Management page, in the Office SharePoint Server Shared Services section, click Create or configure this farm's shared services.

3.On the Manage this Farm's Shared Services page, click New SSP. Important: If you have not created a Web application for the SSP administration site, you need to create one before you create the SSP. If you have already created a Web application for the SSP administration site, skip to step 14.

4.On the New Shared Services Provider page, click Create a new Web application.

5.On the Create New Web Application page, in the IIS Web Site section, click Create a new IIS web site, and do not modify the default settings in this section.

6.In the Security Configuration section, under Authentication provider, select the appropriate option for your environment, and do not modify the default settings in the remainder of this section.

7.In the Load Balanced URL section, do not modify the default settings.

8.In the Application Pool section, click Create new application pool.

9.In Application pool name, enter the name of your application pool or use the default name.

10.Click Configurable, and in User name and Password, type the user name and password for the user account under which you want the application pool to run. The user account does not have to be a member of any particular security group. It is recommended that you use the principle of least privilege and select a unique user account that does not have administrative rights on your front-end servers or on your back-end database servers. You can use the user account that you specified as the Office SharePoint Server 2007 service account; however, if that user account is a member of a security group that has administrative rights on your front-end servers or your back-end database servers, you will not be following the principle of least privilege. The user name must be in the format DOMAIN\username.

11.In the Database Name and Authentication section, verify the database information and make sure that Windows Authentication (recommended)is selected.

12.In the Search Server section, do not modify the default settings.

13.Click OK. Upon successful creation of the Web application, the New Shared Services Provider page appears.

14.In the SSP Name section, in Web Application, select the Web application that you created for the SSP, and do not modify any of the default settings in this section.

15.In the My Site Location section, do not modify any of the default settings.

16.In the SSP Service Credentials section, in User name and Password, type the user name and password for the user account under which you want the SSP to run. The user account does not have to be a member of any particular security group. It is recommended that you use the principle of least privilege and select a unique user account that does not have administrative rights on your front-end servers or on your back-end database servers. You can use the user account that you specified as the Office SharePoint Server 2007 service account; however, if that user account is a member of a security group that has administrative rights on your front-end servers or your back-end database servers, you will not be following the principle of least privilege. The user name must be in the format DOMAIN\username.

17.In the SSP Database section, you can either accept the default settings (recommended), or specify your own settings for the database server, the database name, or the SQL authentication credentials.

18.In the Search Database section, you can either accept the default settings (recommended), or specify your own settings for the search database server, the database name, or the SQL Server authentication credentials.

19.In the Index Server section, in Index Server, click the server on which you configured the Search service. Note: If there is no index server listed in the Index Server section, then no server in your farm has been assigned the index server role. To assign the index server role to a server in your farm, follow the instructions in the "Configure the Search service" section earlier in this topic.

20.In the SSL for Web Services section, click No.

21.Click OK. Upon successful creation of the SSP, the Success page appears.

22.On the Success page, click OK to return to the Manage this Farm's Core Services page.

Configure indexing settings

1.On the SharePoint Central Administration home page, click the Application Management tab on the navigation bar.

2.On the Application Management page, in the Office SharePoint Server Shared Services section, click Create or configure this farm's shared services.

3.On the Manage this Farm's Shared Services page, click SharedServices1.

4.On the Shared Services Administration page, in Search, click Search Settings.

5.On the Configure Search Settings page, in the Crawl Settings section, click Default content access account.

6.In the Default content access account section, in Account, Password, and Confirm Password, type the user name and password for the user account that you want to use to crawl content on your sites. This account must be a domain user account. It is recommended that you use the principle of least privilege and select a unique user account that cannot modify content and does not have administrative rights on your front-end servers or on your back-end database servers. You can use the user account that you specified as the Office SharePoint Server 2007 service account; however, if that user account is a member of a security group that has administrative rights on your front-end servers or your back-end database servers, you will not be following the principle of least privilege. The user account that you specify will be added to the Web application Full Read policy for your farm. The user name must be in the format DOMAIN\username.

7.Click OK.

8.In the Crawl Settings section, click Content sources.

9.On the Manage Content Sources page, click Local Office SharePoint Server sites.

10.On the Edit Content Source page, in the Crawl Schedules section, under Full Crawl, click Create schedule.

11.In the Manage Schedules dialog box, configure schedule settings for full crawls of your content, and then click OK.

12.In the Crawl Schedules section, under Incremental Crawl, click Create schedule.

13.In the Manage Schedules dialog box, configure schedule settings for incremental crawls of your content, and then click OK.

14.In the Start Full Crawl section, select the Start full crawl of this content source check box, and then click OK.


You are done!

Thursday, October 8, 2009

how to shuffle records when querying from database

If we want to have records shuffled in a random manner then
you need to add the "ORDER BY NEWID()" as follows.

SELECT p.*,c.*
FROM dbo.tblPartnerInfo AS p
LEFT JOIN dbo.tblCountry AS c
ON p.CountryID=c.CountryID
WHERE p.CountryID=@CountryID
ORDER BY NEWID()

How to add multiple QueryString parameters to the ASP .NET SiteMapNode web.sitemap &

Only thing you have to do is index.aspx?Disclaimer=true&id=30

replace the "&" with "&". Otherwise you will get the following
error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: The XML sitemap config file web.sitemap could not be loaded. An error occurred while parsing EntityName

Thursday, October 1, 2009

How to use alerts in asp.net without affecting the layout

If you want to add alerts in your asp.net c# application, don't use the method
using "Response.Write("your alert script");".Use the follownig method.Otherwise
you may lose your styles and layout may go mad.

Thursday, September 24, 2009

Find the control that raised postback event on a page in c#

Using this method you may find the control that raised the PostBack event on a page.

Code in C#:

public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
if ((ctl.LastIndexOf(".x") > 0) || (ctl.LastIndexOf(".y") > 0))
{
control = page.FindControl(ctl.Substring(0, ctl.Length - 2));
break;
}
/*control = page.FindControl(ctl);
if ((control is System.Web.UI.WebControls.Button))
{
break;
}*/

}
}
return control;
}

Sunday, September 6, 2009

Using Named Anchor Tags To Move To a Different Section In Web Pages

The name Attribute

When the name attribute is used, the "a" element defines a named anchor inside a HTML document.

Named anchor are not displayed in any special way. They are invisible to the reader.

Named anchor syntax:


The link syntax to a named anchor:



The # in the href attribute defines a link to a named anchor.

Example:

A named anchor inside an HTML document:




A link to the Useful Tips Section from the same document:





A link to the Useful Tips Section from another document:

Monday, August 31, 2009

Drop down list styles in different operating systems

A question that is frequently asked in forums like the css-discuss mailing list is how to style form controls in a consistent way across platforms. Most of the time, the question is asked by someone who has just tried to do that, and noticed the difference in rendering across browsers and operating systems.

The short answer is probably disappointing to many: you can’t. Some also argue that you shouldn’t, since doing so may reduce usability. My opinion on that is that light, sensible styling of some form controls can be OK, as long as you don’t overdo it. But what if we don’t think about usability, and just want to see what actually can be styled? I’ve made a few examples that make up a longer answer to the question about styling form controls.

Find more dtails visit these urls

http://www.456bereastreet.com/archive/200409/styling_form_controls/

http://www.456bereastreet.com/lab/form_controls/select/

SharePoint 2007: Excel Services - A Quick Introduction

First of all i found a great video tutorial from the microsoft site.Please have a look it'll show you how to enable the excel services in sharepoint.



Excel Services is a new cool thing that came out of MSFT as something that comes bundled with MOSS 2007. Excel is arguably one of the top used tools for the information worker (whoaa! Information worker, now I'm talking like MSFT marketing). I utilize Excel very very frequently. If it wasn't for excel, I'd be dead. Let me put it this way, given a choice between excel and gmail, it's like choosing between pizza and hamburgers - please god, may I never see a day when I have to choose between either. Funnily enough, it's not just me, a lot of others use Excel too. And suddenly, these excel sheets that contain valuable information collect on user's desktops and start acting as mini-databases with very valuable calcuations in them. Microsoft realized this as a potential for improvement, so they bundled up Excel Services in SharePoint 2007. This basically gives you a server side version of Excel, and a tad bit more, but a tad bit less also. First of all, Excel Services is NOT like Google Spread. Not at all. In fact, you don't have a web based UI to start editing your excel sheets, and all user's concurrency issues are taken care of - none of that happens. You get some interactivity, in the shape of some standard excel features transporting over such as grouping, pivot tables, filtering etc. and the ability to parameterize your excel sheets. You can even write .NET UDFs to extend the functionality of an Excel sheet. In short, it is a great BI & data presentation tool, but it is not a great data entry tool for the web. Excel Services can be broadly split into two halves - a) What you see and use through a browser, this looks and feels a bit like using Excel, but through a browser. b) The web service API for Excel services. The advantages of Excel Services versus Desktop Excel are obvious Sheets are automatically versioned, a "god" copy is maintained - no more versions in emails and hard drives. Backups of all this important data are easy to do. You gain the capability of securing workbooks, so certain users with limited rights can see the data, but not edit the data. Also, you can establish rules such as "Show only this worksheet to anonymous users" etc. It is possible to create snapshots of the workbook and take them with you for that trip you had been waiting for. You get a major portion of the capability of Excel 2007 interactivity on a web based application. Thus, if you had colors, pie charts, filtering, you name it - a huge portion of that richness can work on a web front end. You can extend the excel sheet through .NET. Whoaaa!! You could do that through VSTO anyway right? Well, you could, but deploying those binaries and deploying updated versions to everyone's desktop is a royal bitch in any reasonable sized organization. The formulae in an excel sheet can now be subjected to the power of a huge and powerful server, running compute cluster, and thus this calculation load can be shared/distributed. And don't forget, these excel sheets are stored in a document library, so you can have workflows, rss feeds, alerts and everything else that comes out of a sharepoint document library. The disadvantages are: Not everything that works on a desktop excel sheet, may work on the web version. For instance, stuff with ActiveX controls, or stuff with add-ins will not work properly in excel services. Excel services are bundled with MOSS, so you gotta buy the nice shiny version of SharePoint to use this stuff. Stuff that you are used to in the desktop version, from a UI perspective, such as split/frozen panes, zooming, etc. won't work in excel services. Some features work in a "lite/diet" fashion. For instance, PivotChart/PivotTable reports functionality is limited to non-interactive, and limited interactivity respectively. You cannot seriously modify the workbook once it is on excel services. For instance, if you want to add a chart, you can't. You need to do that in desktop excel and republish. So, in this blogpost, I am going to create a simple excel sheet - put it on excel services, and demo how this stuff works. Here is the problem statement I am trying to solve - I am going to assume that I went to the MVP summit (though this year I didn't (too much work to do)), and over there as we go out and eat and drink, other MVPs are borrowing money from me, or I am borrowing money from them. I wish to track all this information in an excel sheet, since I tend to get drunk easily, and the tightwad that I am - I don't wanna loose track of this info. Now I'd like to use all the nice features of excel to get an idea of how much I owe, how much everyone owe's me, and use color coding/charts - all that shputz! But I want this information online, say using Excel services. Okay so Step #1 is, create an excel sheet. My Excel sheet with some sample data looks like this - As you can see, I have a simple workbook with 1 worksheet. I have a table with 3 columns, Person/Date/Amount. I am tracking who owes who what, and on what date was the $ loaned. Also, I have done a sum, and a funky 3D chart, and I am using conditional formatting and nice looking icons that appear automatically to make my data visually more meaningful and appealing. Step #2, is to go under SharedServices for the site you wish to put this excel sheet on, and under Excel Services settings, click on "Trusted File Locations". Go ahead and add the location you will put this excel sheet on. I put it on http://moss2007:10000 and I trusted all children. Step #3, is to go to the site, http://moss2007:10000 in my case, and create a document library. Go to the document library settings, advanced settings, and under "Open browser-enabled documents", choose "Display as web page". Step #4, Is to make the above excel sheet available via Excel services. If you are using a version of office that can publish to excel services, such as Office Ultimate 2007, go ahead and use OFFICEBUTTON->Publish->Excel Services, and publish to the document library created in step #3. Otherwise, just save it in that doc. lib :-). Publishing via Excel services unlocks the possibility of making available named cells as parameters to the excel sheet on the web. Named cells can be exposed as parameters by clicking on the "Excel Services Options" box in Office Excel Ultimate, during the publish process. Cells can be named using the DefineName thing on the Formula ribbon/bar. Also, if you wish to limit the publishing to specific sheets, or part of a sheet - you need to use a version of Office that has the ability to publish to Excel services. Step #5, is to go ahead and click on the excel sheet in SharePoint. What do you see? After a circular green progress circle thingie, the excel sheet is rendered as shown below - Note that I am running this in a browser :-). Even neater, check this out, the same worksheet in a WebPart - w00t!! Now, what do you see? A large portion of the functionality carried over, though Excel Services decided to turn my 3D chart into 2D (chee thanks! Lesson learnt, don't promise anything based on excel services to client, unless you've tried it yourself first). Plus, if you start playing with the above, you can clearly tell that this isn't exactly "Excel" like "Google Spread", in fact - that would be much like comparing apples to oranges. Google spread is a web based version of excel lite/diet, wheras excel services gives you the ability to put the various excel computations that business users code in an excel sheet, on a server quality machine. Then you can use stuff like Web Services to query, and UDFs to enhance. Plus, another thing you see is, Bill Ryan seems to owe me $95. WTF! Other cool things to do with Excel Services - - Play around a bit and see what stuff carries over to the web based version. Things get interesting with PivotTable and PivotChart, I recommend trying those out. - You could query the functionality embedded in excel sheets using a web service. Imagine, going up to your business user and telling them - hey man, why don't you code your complex calculations in Excel, let me know when you're done, and I'll give a web based version of it. Quite a punch IMO. - Extend this functionality using UDFs. - Use Excel to display stuff in either SQL Server BI or a SharePoint list, and use the data connection library + excel services to render this data in the browser.

Wednesday, August 26, 2009

Adding PDF icon in sharepoint

Follow the steps as mentioned below to get the PDF icon working in a sharepoint site.
1> Stop the IIS.
2> Install the Adobe IFilter from the below links -
http://www.adobe.com/support/downloads/detail.jsp?ftpID=2611 for 32 bit
http://www.adobe.com/support/downloads/detail.jsp?ftpID=4025 for 64 bit
3> Then copy/add the icon of the pdf to "c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES"
4> Then go to "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML" and edit the DOCICON.XML
5> Add the key that is mentioned below inside the above XML file.


6> Restart the IIS.
7> Then go to Central Administration page to add the file type. Go to the SSP,then search settings, then click on File types list.
8> Click on new file type. Type in PDF, then click OK.

Finally, you get to see the pdf icons for the PDF files that you have uploaded on the sharepoint site.

Wednesday, August 19, 2009

How to hide a sub site from table of contents web part in sharepoint

Here assume a sitauation that you dont want some of your subsite appear in your table
of contents web part.

You have go to
--> Site "Settings"
--> "Modify all site settings"
--> Click "Navigation" under "Look and Feel"
--> Go to Current Navigation
--> Select the sub site that you do not want
--> Click "Hide"
--> Click "OK"
--> Go to the page where you have the table of content web part & refresh

Now see your sub site won't there

Tuesday, August 18, 2009

How to add pagewise security in sharepoint

When you want to your page visible to a specific person or a user group you have to go to

--your page library
--Click the arrow and click on "Manage Permissions"
--add or remove permissions
--chekin the page

Then you are done :)

SPSecurity.RunWithElevatedPrivileges - while using it with SPContext.Current.Web in sharepoint

Normally we will use SPSecurity.RunWithElevatedPrivileges() to execute some code that has to be run under some higher privileges.



Whenever we use SPSecurity.RunWithElevatedPrivileges(), it will execute the code under the context of Application Pool identity. Now we can see a scenario where we will get the “Access denied” exception from the code block even if you use SPSecurity.RunWithElevatedPrivileges.



This was the code snippet that I have used initially inside a custom webpart to read XML content from of an InfoPath form which was uploaded in a document library. This code will throw an “Access denied” exception while calling the OpenBinaryStream() method whenever I execute it through an Anonymous user account.



SPSecurity.RunWithElevatedPrivileges(delegate()

{

SPWeb oWeb = SPContext.Current.Web;

SPList oList = oWeb.Lists["InfoPathLib"];

SPListItem oListItem = oList.Items[0];

Stream oStream = oListItem.File.OpenBinaryStream();

StreamReader oReader = new StreamReader(oStream);

string strLine = "";



strLine = oReader.ReadLine();



oReader.Close();

oStream.Close();



oReader.Dispose();

oStream.Dispose();



lblFileContent.Text = strLine;



this.Controls.Add(lblFileContent);

});





Here the problem was, whenever we take the SPWeb instance using

SPWeb oWeb = SPContext.Current.Web;, then SPWeb instance still running under anonymous account only , because we are taking it through the current web context in which the current user is running under anonymous account (IUSR_MachineName). That was the reason that we got that “Access Denied” exception. We need to remember this point all time whenever we use RunWithElevatedPrivileges under the web context.



So what we need to that, we have to take the current context outside the SPSecurity.RunWithElevatedPrivileges block and then create a new instance of SPSite and SPWeb inside the that block which will run under application pool identity.



SPWeb oWeb1 = SPContext.Current.Web; // taking the current SPWeb context running under the anonymous account

SPSecurity.RunWithElevatedPrivileges(delegate()

{

using (SPSite oSite = new SPSite(oWeb1.Site.Url))

{

// creating a new SPSite running under Application pool idenity

using (SPWeb oWeb = oSite.OpenWeb())

{



SPList oList = oWeb.Lists["InfoPathLib"];



SPListItem oListItem = oList.Items[0];



Stream oStream = oListItem.File.OpenBinaryStream();



StreamReader oReader = new StreamReader(oStream);



string strLine = "";



strLine = oReader.ReadLine();



oReader.Close();



oStream.Close();



oReader.Dispose();



oStream.Dispose();



lblFileContent.Text = strLine;



this.Controls.Add(lblFileContent);

}

}



});

The above code will work fine and we can read the InfoPath document. So, please do not forget to create a new instance of SPSite and SPWeb inside SPSecurity.RunWithElevatedPrivileges,while using it in a web context.



Another work-around to this paritcular requirement (read the file content) is - use GetFileAsString() method of the SPWeb directly. And here there is no need to use the SPSecurity.RunWithElevatedPrivileges. Since, I have enabled anonymous authentication on this SharePoint web application it will allow to read the file using the below method under the context of anonymous account.

string strXML = SPContext.Current.Web.GetFileAsString("/FannyDocLib/Form1.xml");

Sunday, August 16, 2009

How to print web page in sharepoint



Add the above script to the page you want to give print function.Then you are done.

Friday, August 14, 2009

System.IO.FileNotFoundException: The Web application at http://-.-.-.- could not be found. Verify that you have typed the URL correctly. solution

System.IO.FileNotFoundException: The Web application at http://203.143.39.19 could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

You can verify this error when you type the public url as http://xxx.xxx.xxx.xxx/ you can not access your your web site.

You may access it using your intranet access or local host.

Then go to Central Administration > Operations > Alternate Access Mappings

Then Edit Default and set your public IP as default.

Then gooooooo to http://xxx.xxx.xxx.xxx/

wow! you are there

How to hide global navigation tabs in application.master in sharepoint



Find the section (in the box in the image) in application.master (C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS).
Then add a div tag as shown including the above mentioned section and make it
visible false.Then you are done!

How to redirect to a custom search page from OSSearchResults.aspx search page


In SharePoint MOSS 2007, when you turn on the custom scope in site collection’s “Search Settings”, most of search results will be displayed at /SearchCenter/Pages/results.aspx. The exceptions are at the contextual search (This site, This List: Documents etc) and it always displays the search result in OSSearchResults.aspx page, which you can not customize through web parts (as you can do with /SearchCenter/Pages/restuls.aspx). This trick seems works very well (original post here):

Open OSSearchResult.aspx in layout folder, and add this block:



I added right after the stylesheet block and I guess you can remove some un-used code block since this page will not be used at all.

Hide "Sign in" Link from sharepoint pages for anonymous users



Hide the sign-in link on the Sharepoint sites except admin page
Did you want to hide the sign-in link on your SharePoint sites?
All you need to do is to locate the following code in your master page and hide or remove the tag:

Step 1:


This will hide the whole Welcome Panel when the page is displayed in the web browser. Donot remove the welcome.ascx control from the Controltemplate folder.
The welcome menu is part of the link itself. Its a whole functionality which is contained in welcome.ascx. So if you remove that, you will loose the menu too.

Step 2:

Create the ASPX for a admin user called adminlogin.aspx
Place the the following code in the ASPX page
The "Sign In" link available in the top-right corner of the Sharepoint site except
the admin page.

Configure sharepoint search for anonymous users - OSSSearchResults.aspx

If you have a public Sharepoint site (MOSS 2007 or WSS 3.0) that is accessible to anonymous users and you’re not using custom scopes, you probably already noticed that every time users try to search they get a user prompt. To get pass this prompt you must enter valid username, otherwise you’ll get famous “Access Denied” page. So much for anonymous access, right?

Anyway, the problem is with OSSSearchResults.aspx page, specifically with one of the inheritance reference that ASPX page. I’m talking about the part of the code that sets the inheritance of the page from the generic application page base class, which is not really required for this page to function properly.

To allow anonymous users to search your publicly available sites you need to remove that inheritance from the code, so find part of the code inside the Page tag that states “Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" and remove that part of the code (not the whole line, just the part that inhertis the application page base.) OSSSearchResults.aspx page is usually stored at C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS on your SharePoint server. Make sure you backup the file before making any changes!

Making those changes will not only allow anonymous users to search the SharePoint content, but also will keep the SharePoint search secure, meaning that anonymous users will only be able to search the part of the SharePoint they have permissions to view.

Thursday, July 30, 2009

Resizing images without loss of quality in sharepoint

Let’s see the code that makes clean resizing. This code doesn’t use GetThumbnailImage method and operates therefore on full size image. Also you can see that this code tries to save as much quality as possible.


--------------------------------------------------------------------------------

public string ResizeImage(Stream fromStream,string fileName,int newWidth, int newHeight )
{

System.Drawing.Image image = System.Drawing.Image.FromStream(fromStream);

Bitmap thumbnailBitmap = new Bitmap(newWidth, newHeight);


Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);

thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;

thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;

thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;



Rectangle imageRectangle = new Rectangle(0, 0, newWidth, newHeight);

thumbnailGraph.DrawImage(image, imageRectangle);



thumbnailBitmap.Save(Server.MapPath(@"/_layouts/images/" + fileName), ImageFormat.Jpeg);



thumbnailGraph.Dispose();

thumbnailBitmap.Dispose();

image.Dispose();

return "../../_layouts/images/" + fileName;

}
You have call your newly created method as follows
SPList lstEvents = web.Lists["Events"];
int id=10;
SPListItem item = lstEvents.GetItemById(id);

string path=ResizeImage(item.File.OpenBinaryStream(), "40_40_resized_image.jpg", 40, 40)

Monday, January 19, 2009

How to insert sharepoint user to a sharepoint user Group in c#

using Microsoft.SharePoint;


public void AddUserToSPGroup(String _UserName, string _GroupName)
{
try
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];

//SPUser spUser = web.AllUsers[domain + "\\" + userName];
SPUser spUser = web.AllUsers["ad:" + _UserName];

//Open group
SPGroup spGroup = web.SiteGroups[_GroupName];

//Add and update group with new user
web.AllowUnsafeUpdates = true;
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
}
catch (Exception ex)
{
lblUserList.Text = ex.Message.ToString();
}
}

Sunday, January 18, 2009

How to Send SMS - SMPP in c#

How to Read the Url of a Web page dynamically in c#

You can get the the url of the currently viewing web page using


HttpContext.Current.Request.ServerVariables["URL"].ToString() ;

How To Generate Random Numbers And Strings in c#

This function can be effectively used for Gnerating Random strings of any length


public string RandomStrings()
{

StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < 10; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}

return builder.ToString();

}


You can use The following code to generate random numbers

private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i==size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch);
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

How to change Active directory user properties in c#

// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();

domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();

user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;



if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}

if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}

if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}

if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}

user.CommitChanges();

if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();

}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}

// Clean up.
searcher.Dispose();
result = null;
user.Close();

How to insert Active directory users to an Active directory Group in c#

public void AddUserToADGroup(DirectoryEntry de,string _Group,string _UserName)
{
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(objectClass=user)";
ds.Sort.Direction = System.DirectoryServices.SortDirection.Ascending;
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.PageSize = 4000;

string name = "";
try
{
SortedList objSortedList = new SortedList();
foreach (SearchResult result in ds.FindAll())
{
DirectoryEntry deTemp = result.GetDirectoryEntry();
name = deTemp.Name;
try
{
name = deTemp.Properties["cn"].Value.ToString();
if (name.Equals(_UserName))
{
DirectoryEntry objGrp = de.Children.Find("CN=" + _Group);

//adding new user to group
if (objGrp.Name != "")
{
objGrp.Invoke("Add", new object[] { deTemp.Path.ToString() });
objGrp.CommitChanges();
deTemp.CommitChanges();
de.CommitChanges();
}
}
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
//FillGroup(ddlEmpName);
}
catch (Exception ex)
{
lblUserList.Text = ex.ToString();
}


}

How to update an Active Directory User in c#

// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.
Response.Write(_UserName);
// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();

domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();

user.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
user.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
user.AuthenticationType = AuthenticationTypes.Secure;



if (details[1] != "")
{
user.Properties["TelephoneNumber"].Value = details[1];
}

if (details[2] != "")
{
user.Properties["streetAddress"].Value = details[2];
}

if (details[3] != "")
{
user.Properties["Description"].Value = details[3];
}

if (details[4] != "")
{
user.Properties["mail"].Value = details[4];
}
if (details[8] != "")
{
user.Properties["sn"].Value = details[8];//last name
}
if (details[9] != "")
{
user.Properties["displayName"].Value = details[9];//display name
}
if (details[10] != "")
{
user.Properties["givenName"].Value = details[0];//1st name
}
if (details[11] != "")
{
user.Properties["physicalDeliveryOfficeName"].Value = details[11];//office phone
}
if (details[12] != "" && details[13] != "")
{
user.Properties["co"].Value = details[12];//country name
user.Properties["c"].Value = details[13];//country code
}

user.CommitChanges();

if (details[5] != "" & details[6] != "")
{
if (details[5].Equals(details[6]))
{
user.Invoke("SetPassword", new object[] { details[5] });
user.CommitChanges();

}
else
{
lblUserList.ForeColor = Color.Red;
lblUserList.Text = "Password Mismatch";
return false;
}
}

// Clean up.
searcher.Dispose();
result = null;
user.Close();

How To Add Users to a Sharepoint Group in c#

public void AddUserToSPGroup(String userName,string group)
{
try
{
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];

//SPUser spUser = web.AllUsers[domain + "\\" + userName];
SPUser spUser = web.AllUsers["ad:"+ userName];

//Open group
SPGroup spGroup = web.SiteGroups[group];

//Add and update group with new user
web.AllowUnsafeUpdates = true;
spGroup.AddUser(spUser.LoginName, spUser.Email, spUser.Name, "Added by UserControl");
spGroup.Update();
}
catch(Exception ex)
{
//Response.Write(ex.Message);
lblUserList.Text =ex.Message.ToString();
}
}

How To Delete a Sharepoint User in c#

you can effectively use this piece of code to remove existing users from the sharepoint site


First of all you have to import

using Microsoft.SharePoint;

Then use following code

public void RemoveUserFromSP(string _UserName)
{
SPSite site = new SPSite(ConfigurationManager.AppSettings["SITE_URL"].ToString());
SPWeb web = site.AllWebs[ConfigurationManager.AppSettings["WEB_SITE"].ToString()];

SPUserCollection userCollection = web.SiteUsers;

string domain = ConfigurationManager.AppSettings["DOMAIN"].ToString();

SPUser spUser;
try
{
spUser = web.AllUsers["ad:" + _UserName];
}
catch
{
spUser = web.AllUsers[domain + "\\" + _UserName]; ;
}
try
{
web.AllowUnsafeUpdates = true;
userCollection.Remove(spUser.LoginName);
}
catch (Exception ex)
{
//Response.Write(ex.Message);
//lblUserList.Text = ex.Message.ToString();
}

}

How to insert a sharepoint user in c#

We can insert active directory users using follwing code segment



public void AddUserToSP()
{
SPWeb spWeb = null;

try
{
//Open the SharePoint site
spWeb =site.AllWebs[(ConfigurationManager.AppSettings["WEB_SITE"].ToString())];

//Assign role and add user to site
//SPRoleAssignment spRoleAssignment =new SPRoleAssignment(details[0],details[1],details[2],details[3]);
string strInFormAuthenticaton = "Specify your LoginName Here";
strInFormAuthenticaton = "ad:"+strInFormAuthenticaton;

spWeb.SiteUsers.Add(strInFormAuthenticaton,"Specify your Name Here","Specify your Email Here","Specify your Notes Here");

//SPRoleAssignment spRoleAssignment = new SPRoleAssignment(strInFormAuthenticaton, details[1], details[2], details[3]);
////Using Contribute, might need high access
//SPRoleDefinition roleDefinition = spWeb.RoleDefinitions["Read"];
//spRoleAssignment.RoleDefinitionBindings.Add(roleDefinition);
//spWeb.AllowUnsafeUpdates = true;
//spWeb.RoleAssignments.Add(spRoleAssignment);
//spWeb.Update();

//Update site
//spWeb.Update();
}
catch (Exception)
{
}
finally
{
spWeb.Close();
}
}

How To Delete An Active Directory User in c#

public void RemoveUserFromAD(string _UserName)
{

// Create a DirectorySearcher object using the user name as the LDAP search filter. If using a directory other than Exchange, use sAMAccountName instead of mailNickname.
DirectorySearcher searcher = new DirectorySearcher("(cn=" + _UserName + ")");

// Search for the specified user.
SearchResult result = searcher.FindOne();

// Make sure the user was found.

// Create a DirectoryEntry object to retrieve the collection of attributes (properties) for the user.
DirectoryEntry user = result.GetDirectoryEntry();

DirectoryEntry parentEntry = user.Parent;
parentEntry.Children.Remove(user);

searcher.Dispose();
result = null;
user.Close();
parentEntry.Close();

}

How To Refresh an Update Panel in Asp.net AJAX C#

Hey everyone you can use triggers to refresh update panels.I'll Show how you can use
triggers to refresh.

You can use post back events such like click,Tick ,CheckChanged to refresh an update panel .













All thing you have to do is introducing a new tag as follows.




you can use the above timer to trigger








as follows you can use tick event of a timer to refresh a page in regular intervals.















The final code looks as above .It will refresh the update panel in every 30 seconds.

protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = " Refreshed at: " + DateTime.Now.ToLongTimeString();
}


You can specify your code in the tick event as above


c# Code to Zip a folder with data and download them

Hey you can use this piece of c# method to zip data folder effectively.


using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.IO.Compression;


public static void ZipFiles(string inputFolderPath, string outputPathAndFile, string password)
{
ArrayList ar = GenerateFileList(inputFolderPath); // generate file list
int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length;
// find number of chars to remove // from orginal file path
TrimLength += 1; //remove '\'
FileStream ostream;
byte[] obuffer;
string outPath = inputFolderPath + @"\" + outputPathAndFile;
ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream
if (password != null && password != String.Empty)
oZipStream.Password = password;
oZipStream.SetLevel(9); // maximum compression
ZipEntry oZipEntry;
foreach (string Fil in ar) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);

if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
}
}
oZipStream.Finish();
oZipStream.Close();
}//code for zipping files


Using the following code you can download zip files

private void Download(string _FilePath)//code for downloading files
{
Response.ContentType = "Application/Zip";
//string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";
//Response.WriteFile(FilePath);
Response.AppendHeader("Content-Disposition", "Lecturer BackUp; filename=Backup.zip");
Response.TransmitFile(_FilePath);
Response.End();
}

How To Write Data To An Excel Sheet in C# and how to download Excel sheets

You can use following method to write data into an excel sheet effetctively.

The accepts a dataset to be written to the excel sheet.Then saves it in the place that you specify.


using Microsoft.Office.Interop.Excel;
using System.IO;


public void ExportToExcel(DataSet dataSet, string outputPath)
{
// Create the Excel Application object
ApplicationClass excelApp = new ApplicationClass();
// Create a new Excel Workbook
Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);

int sheetIndex = 0;

// Copy each DataTable as a new Sheet
try
{
foreach (System.Data.DataTable dt in dataSet.Tables)
{
// Create a new Sheet
Worksheet excelSheet = (Worksheet)excelWorkbook.Sheets.Add(
excelWorkbook.Sheets.get_Item(++sheetIndex),
Type.Missing, 1, XlSheetType.xlWorksheet);

excelSheet.Name = dt.TableName;

// Copy the column names (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
try
{
excelSheet.Cells[1, col + 1] = dt.Columns[col].ColumnName;
}
catch {
Response.Write("1");
}
}

((Range)excelSheet.Rows[1, Type.Missing]).Font.Bold = true;

// Copy the values (cell-by-cell)
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
try
{
//string temp = dt.Rows[row].ItemArray[col].ToString();
excelSheet.Cells[row + 2, col + 1] = dt.Rows[row].ItemArray[col];
}
catch {//Response.Write("2");
}
}
}

}
}
catch { //Response.Write("3");
}
// Save and Close the Workbook
try
{
excelWorkbook.SaveAs(outputPath, XlFileFormat.xlWorkbookNormal, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excelWorkbook.Close(true, Type.Missing, Type.Missing);
//excelWorkbook

excelWorkbook = null;

// Release the Application object
excelApp.Quit();
excelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
catch {
}
// Collect the unreferenced objects


}



You can use execute the above method and download it as follows


string cellByCellFilePath = Server.MapPath("~/ExcelSheets/") + "DeleteDetails.xls";


// Get the DataSet

ds = (DataSet)Session["DataSet"];

File.Delete(cellByCellFilePath);

ExportToExcel(ds, cellByCellFilePath);

Response.ContentType = "application/vnd.ms-excel";

string FilePath = MapPath("~/ExcelSheets/") + "DeleteDetails.xls";

Response.TransmitFile(FilePath);

Response.End();

How To Track IP In ASP.net C#

You can use this piece of code to track the ip addresses of users who visit your web site
effectively.




using System.Configuration;
using System.Net;
using System.IO;


protected string TrackIP()
{

// Track Visitors

string ipAddress = IpAddress();

//To get the host name
//string hostName = Dns.GetHostByAddres(ipAddress).HostName;


//To add a log file
/*string hostName = "My Host";

StreamWriter wrtr = new StreamWriter(Server.MapPath("\\Log\\visitors.log"), true);

wrtr.WriteLine(DateTime.Now.ToString() + " | " + ipAddress + " | " + hostName + " | " + Request.Url.ToString());

wrtr.Close();*/

return ipAddress;
}

private string IpAddress()
{

string strIpAddress;

strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (strIpAddress == null)

strIpAddress = Request.ServerVariables["REMOTE_ADDR"];//Get remote IP address

return strIpAddress;

}

Friday, January 16, 2009

How To create Active Directory Users in c#

First of all import

using System.DirectoryServices;

To add a user to active directory(AD)

public void AddUserToAD(DirectoryEntry de, string[] details)
{
try
{
string oGUID = string.Empty;

domain = ConfigurationManager.AppSettings["DOMAIN"].ToString(); //
de.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
de.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();

DirectoryEntry newUser = de.Children.Add("CN=" + details[0], "user");
newUser.Properties["samAccountName"].Value = details[0];
newUser.Properties["givenName"].Value = details[0];
newUser.Properties["sn"].Value = details[0];

newUser.Username = domain + "\\" + ConfigurationManager.AppSettings["USERNAME"].ToString();
newUser.Password = ConfigurationManager.AppSettings["PASSWORD"].ToString();
newUser.AuthenticationType = AuthenticationTypes.Secure;

if (details[1] != "")
{
newUser.Properties["TelephoneNumber"].Value = details[1];
}
if (details[2] != "")
{
newUser.Properties["streetAddress"].Value = details[2];
}
if (details[3] != "")
{
newUser.Properties["Description"].Value = details[3];
}
if (details[4] != "")
{
newUser.Properties["mail"].Value = details[4];
}
newUser.CommitChanges();
oGUID = newUser.Guid.ToString();

newUser.Invoke("SetPassword", new object[] { details[5] });
newUser.CommitChanges();
EnableADUser(newUser);
newUser.Close();

}
catch (Exception ex){
Response.Write(ex.Message);
}
}

Error in Ajax Control Tool kit - Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b

"Could not load file or assembly 'vjslib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b "

If you get the above error all you have to do is download the J# redistributable and install .
Then you won't get the above error.

http://msdn2.microsoft.com/en-us/vjsharp/Bb188598.aspx