Monday, December 18, 2006

saving an html file from a code behind - ASP.NET

However if you really need to generate HTML output from an ASPX page it canbe easily done by overriding the Render method and capturing the output from


Protected Overrides Sub Render(ByVal writer As HtmlTextWriter)

' *** Write the HTML into this string builder

Dim sb As StringBuilder = New StringBuilder()

Dim hWriter As HtmlTextWriter = New HtmlTextWriter(New StringWriter(sb)) MyBase.Render(hWriter)

' *** store to a string Dim PageResult As String = sb.ToString()

' *** Write it back to the server's HTTP Stream -

' *** skip this if you don't want to display the rendered content writer.Write(PageResult)

.... PageResult now hold the HTML content you can write to diskdo whatever you want to with.

End Sub

This example goes to string but you can use a StreamWriter instead of stringbuilder to dump the output directly to file if you wish.


Same in C#:


protected override void Render(HtmlTextWriter writer)
{
// *** Write the HTML into this string builder
StringBuilder sb = new StringBuilder();
HtmlTextWriter hWriter = new HtmlTextWriter(new StringWriter(sb));
base.Render(hWriter);
// *** store to a string
string PageResult = sb.ToString();
// *** Write it back to the server's HTTP Stream -// *** skip this if you don't want to display the rendered content
writer.Write(PageResult);
.... PageResult now hold the HTML content you can write out to diskdo whatever you want to with.
}

Looking for commercial use RSS weather feed by zipcode or alternative

Looking for commercial use RSS weather feed by zipcode or alternative

You can get the commercial use RSS from this website

http://www.hamweather.com/rss/

Using NotesSQL ODBC Driver and C# extract the .nsf file data

Using NotesSQL ODBC Driver and C# extract the .nsf file data to XML file format or any other format.

NoteSQL ODBC Driver Download Click Here

Sample Code:

public XmlDocument GetFromNSFdb(string strNSFdbName)

{

Domino.ISession session = new NotesSessionClass();

session.Initialize("");

Domino.NotesDatabase database = session.GetDatabase("", strNSFdbName, false); Domino.NotesNoteCollection noteCollecton = database.CreateNoteCollection(true); noteCollecton.SelectAllAdminNotes(true);

noteCollecton.SelectAllCodeElements(true);

noteCollecton.SelectAllDataNotes(true);

noteCollecton.SelectAllDesignElements(true);

noteCollecton.SelectAllFormatElements(true);

noteCollecton.SelectAllIndexElements(true);

noteCollecton.SelectForms = true;

noteCollecton.BuildCollection();

Domino.NotesDXLExporter exporter = (Domino.NotesDXLExporter session.CreateDXLExporter();

string strNsfXML = exporter.Export(noteCollecton);

// removes the string strDocrmv = strNsfXML.Replace("", "");

// removes the xmlns='http://www.lotus.com/dxl'

strDocrmv = strDocrmv.Replace("xmlns='http://www.lotus.com/dxl'", ""); XmlDocument xDocLoad = new XmlDocument();

xDocLoad.LoadXml(strDocrmv);

return xDocLoad;

}

Microsoft SecureWar Security Competition for India

Microsoft SecureWar Security Competition

Click Here to participate in this microsoft competition.

Monday, December 11, 2006

get the dimension of my document using JavaScript

to get the dimension of my document.

// javascript
var screen_width = null;
var screen_width = null;
screen_width = document.body.offsetWidth;
alert('Get IT');
screen_height = document.body.offsetHeight;
document.forms[0].txt_width.value = screen_width;
document.forms[0].txt_height.value = screen_height;

But the above script will fire only once the first time when the page is loaded.

do to execute this script every time the user resize window of the browser, use the following code part

if (self.innerWidth)
{
frameWidth = self.innerWidth;
frameHeight = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth)
{
frameWidth = document.documentElement.clientWidth;
frameHeight = document.documentElement.clientHeight;
}
else if (document.body)
{
frameWidth = document.body.clientWidth;
frameHeight = document.body.clientHeight;
}
else return;
if (self.screen.width < frameWidth *2 self.screen.height < frameHeight *2)
{
newWidth = self.screen.width/2;
newHeight = self.screen.height/2;
if (document.layers)
{
tmp1 = parent.outerWidth - parent.innerWidth;
tmp2 = parent.outerHeight - parent.innerHeight;
newWidth -= tmp1;
newHeight -= tmp2;
}
parent.window.resizeTo(newWidth,newHeight);
parent.window.moveTo(self.screen.width/4,self.screen.height/4);
}
else
{
alert('No resize necessary');
}

using ArrayList for Simple Scenario (Using C#)

Scenario:

I have 2 tables one has 6 textboxes, the other has 8 rows with one textbox per row.I need to insert into a table the values in the first 6 textboxesfrom table 1 plus value from textbox 1 row 1 to textbox 8 row 8 in table 2. altogether 8 insert queries, so I will need a for loopthat will attach the values form table 1 to each value in table 2 unless the value is null.can I create an array of texboxes in table 2 so then I could loop through the array?

Solution (Using C#):

//This code to implement
ArrayList list = new ArrayList();
list.Add(new Category("textbox1"),1);
list.Add(new Category("textbox2"),2);
list.Add(new Category("textbox3"),3);
list.Add(new Category("textbox4"),4);
list.Add(new Category("textbox5"),5);
list.Add(new Category("textbox6"),6);
list.Add(new Category("textbox7"),7);
list.Add(new Category("textbox8"),8);

foreach (Category cate in list)
{
try
{
sql = "INSERT INTO DB..tAble (col1, col2) VALUES ( ";
sql += "'" + cate.Type + "', " + "'" + cate.TypeCode + "');" ;
Insertdata(sql);
}
catch(Exception ex)
{
//msg
}
}

// add this class under same namespace
public class Category
{
public string Type;
public int TypeCode;

public Category()
{
}
public Category(string type, int tcode)
{
this.Type = type;
this.TypeCode = tcode;
}
}

protected void Insertdata(string sql)
{
// Your connection and query processing for database
}

Saturday, December 09, 2006

MOSS 2007 Site templates

MOSS 2007 Site templates:

MOSS 2007 Site templates we have four category of templates

1) Collaboration

2) Meetings

3) Enterprise

4) Publishing

Collaboration:

Team Site: A site for teams to quickly organize, author, and share information. It provides a document library, and lists for managing announcements, calendar items, tasks, and discussions.

Blank Site: A blank site for you to customize based on your requirements.

Document Workspace: A site for colleagues to work together on a document. It provides a document library for storing the primary document and supporting files, a tasks list for assigning to-do items, and a links list for resources related to the document.

Wiki Site: A site for a community to brainstorm and share ideas. It provides Web pages that can be quickly edited to record information and then linked together through keywords

Blog: A site for a person or team to post ideas, observations, and expertise that site visitors can comment on.

Meetings

Basic Meeting Workspace: A site to plan, organize, and capture the results of a meeting. It provides lists for managing the agenda, meeting attendees, and documents.

Blank Meeting Workspace: A blank meeting site for you to customize based on your requirements.

Decision Meeting Workspace: A site for meetings that track status or make decisions. It provides lists for creating tasks, storing documents, and recording decisions.

Social Meeting Workspace: A site to plan social occasions. It provides lists for tracking attendees, providing directions, and storing pictures of the event.

MultiPage Meeting Workspace: A site to plan, organize, and capture the results of a meeting. It provides lists for managing the agenda and meeting attendees in addition to two blank pages for you to customize based on your requirements.

Enterprise

Document Center: A site to centrally manage documents in your enterprise.

Records Center: This template creates a site designed for records management. Records managers can configure the routing table to direct incoming files to specific locations. The site prevents records from being modified after they are added to the repository.

Site Directory: A site for listing and categorizing important sites in your organization. It includes different views for categorized sites, top sites, and a site map.

Report Center: A site for creating, managing, and delivering Web pages, dashboards, and key performance indicators that communicate metrics, goals, and business intelligence information.

Search Center With Tabs: A site for delivering the search experience. The welcome page includes a search box with two tabs: one for general searches, and another for searches for information about people. You can add and customize tabs to focus on other search scopes or result types.

My Site Host: A site used for hosting personal sites (My Sites) and the public People Profile page. This template needs to be provisioned only once per Shared Service Provider, please consult the documentation for details.

Search Center: A site for delivering the search experience. The site includes pages for search results and advanced searches.

Publishing

Collaboration Portal: A starter site hierarchy for an intranet divisional portal. It includes a home page, a News site, a Site Directory, a Document Center, and a Search Center with Tabs. Typically, this site has nearly as many contributors as readers and is used to host team sites.

Publishing Portal: A starter site hierarchy for an Internet-facing site or a large intranet portal. This site can be customized easily with distinctive branding. It includes a home page, a sample press releases subsite, a Search Center, and a login page. Typically, this site has many more readers than contributors, and it is used to publish Web pages with approval workflows.

Reference from msdn

What is the Ribbon in Office 2007

The Ribbon replaces the current system of layered menus, toolbars, and task panes with a simpler system of interfaces optimized for efficiency and discoverability.

The 2007 release of Office provides two ways to customize the RibbonX UI using XML markup:
Using valid Open XML Formats files that contain XML markup. Using COM add-ins that contain XML markup.

One of the nice article i gone through in the MSDN is ...

Code:
public void OnActionCallback(Office.IRibbonControl control, bool isPressed)
{
if (control.Id == "checkBox1")
{
MessageBox.Show("You clicked " + control.Id);
}
else
{
MessageBox.Show("You clicked a different control.");
}
}

using VSTO for visual studio 2005 we do these kind of C# coding in ribbon or add-on development for office 2007.

Demo Video for VSTO 2005 -- Visual Studio 2005 Tools for the 2007 Microsoft Office System

Demo of Visual Studio 2005 Tools for the 2007 Microsoft Office System, Second Edition

Andrew Whitechapel gives a brief demo of the new VSTO 2005 Second Edition in this video, reviewing key developer features such as new default templates, Ribbon customization, creating custom task panes, and more.

Microsoft Visual Studio 2005 Tools for Office Second Edition Runtime (VSTO 2005 SE) (x86)

The Microsoft Visual Studio 2005 Tools for Office Second Edition (VSTO 2005 SE) redistributable package installs the Visual Studio Tools for Office runtime, which is required to run solutions built using VSTO 2005 or VSTO 2005 SE.

http://www.microsoft.com/downloads/details.aspx?familyid=f5539a90-dc41-4792-8ef8-f4de62ff1e81&displaylang=en

The Microsoft Visual Studio 2005 Tools for Office Second Edition (VSTO 2005 SE) redistributable package installs the Visual Studio Tools for Office runtime, which is required to run solutions built using VSTO 2005 or VSTO 2005 SE. This runtime supports solutions built for Microsoft Office 2003 or the 2007 Microsoft Office system.For information about Visual Studio 2005 Tools for Office Second Edition, see the Microsoft Office Developer Center.

Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System

Install VSTO 2005 SE to create new application-level add-ins for six applications in the 2007 Microsoft Office system and five in Microsoft Office 2003. Use managed code to customize task panes and the Ribbon in the 2007 Microsoft Office system applications.

http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86CAB3-6FD6-4955-B979-E1676DB6B3CB&displaylang=en

VSTO 2005 SE includes support for Microsoft Office InfoPath 2007 form template projects, previously available as a separate product known as the Microsoft Office InfoPath 2003 Toolkit for Visual Studio 2005. You can now design InfoPath 2007 form solutions right in the Visual Studio 2005 environment if you have InfoPath 2007 installed on your computer.

For more click here

Thursday, December 07, 2006

Tuesday, December 05, 2006

Microsoft presents the “Microsoft BlogStars” contest


Microsoft presents the “Microsoft BlogStars” contest – hunt for the best developer bloggers in India.Create greater impact in the vibrant developer blogger community, showcase your thoughts and experiences around Microsoft technologies and technology in general.Register for the contest, start BLOGGING! and be the first ever Microsoft Blogstars!

http://www.microsoft.com/india/blogstars/

Note: Currently registration is closed

Thursday, November 30, 2006

Community Credit topper...

One among the top 10 in September 2005

One among the top 10 in November 2005
One among the top 10 in October 2005
One among the top 10 in December 2005
One among the top 10 in March 2005
One among the top 10 in February 2005


http://www.community-credit.com/



Wednesday, November 29, 2006

'Microsoft.VisualStudio.Tools.Applications.Adapter, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

Error 1 Assembly 'Microsoft.VisualStudio.Tools.Applications.Adapter, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' uses 'Microsoft.VisualStudio.Tools.Applications.Contract, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' which has a higher version than referenced assembly 'Microsoft.VisualStudio.Tools.Applications.Contract, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' c:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.Tools.Applications.Adapter.dll Test



When i got this error i tried to uninstall the Visual Studio 2005 SDK Feb release from my system. Now the problem get solved.



For more check out these articles.
http://msdn2.microsoft.com/en-us/library/zdc263t0.aspx
http://www.summsoft.com/blogs/garyvsta/default.aspx

Saturday, November 18, 2006

New Technology discussion group in MSN - Join Now

Here is one of the best interactive community for All Technologies. All technology lovers and programmers come lets add power to your technical skill.

Join Now

http://groups.msn.com/DevelopersParadise

Thursday, November 16, 2006

Unsafe Code in C#

Unsafe code is formally denoted as unmanaged code .NET. Unmanaged codes as the possibility to use the pointers in the .NET managed code. Basically .NET hides most of the memory management; it makes all the .NET programmer and developers easier for development. Commonly there is need to use the unsafe code in our application while using Microsoft .NET.

When and why should we need this unsafe or unmanaged code in .NET? The answer is if you want to access memory mapped devices or if you want to create an application that to interface with your operation system, while using pointer to increase your application performance, External functions, in some cases you might need to write an application that analyzes another application process and memory etc, we need this unmanaged code, it will be more advantageous when we use this in those situations.

Some of the main advantages about the unsafe code in .NET are performance and flexibility, compatibility like DLLImport, memory addresses.

Some of the notable disadvantages about the unmanaged code in .NET are Complex to implement in C#, you should be more careful while using pointers in .NET application, miss use of pointer will cause many problems like stack overflow, overwrite existing or other variables, unauthorized access to memory areas, simple mistake in using pointers might lead your application to crash randomly and unpredictably, using pointers will cause the code to fail in the .net type-safety checks.

Sample unmanaged code snippet:

DllImport("shell32.dll", SetLastError = true)]
extern public static bool
ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
public const uint SW_NORMAL = 1;
static void OpenAs(string file)
{
ShellExecuteInfo sei = new ShellExecuteInfo();
sei.Size = Marshal.SizeOf(sei);
sei.Verb = "openas";
sei.File = file;
sei.Show = SW_NORMAL;
if (!ShellExecuteEx(ref sei))
throw new System.ComponentModel.Win32Exception();
}


For more reference

Sunday, November 12, 2006

Show/Hide a row in ASP.NET DataGrid

In this article i'm goin to explain you how to show or hide a certain row in the ASP.NET datagrid using JavaScript. First populate your datagrid with some records. Here in this example i have populated my datagrid with one sample XML file.

Sample XML document structure:

<movies>

<movie movieid="1000">

<moviename>Dr.No</moviename>
<artist>James Bond</artist>
<year>1970</year>
<language>English</language> <image>anne_hathaway90x80.jpg</image>
</movie>
<movie movieid="1001">
<moviename>Raja</moviename>
<artist>Raja</artist>
<year>1990</year>
<language>Hindi</language> <image>dogsfri90x80.jpg</image>
</movie>
</movies>

After populating the grid, my grid shows like this...



The following code part is used for populating my datagrid in my ASP.NET page. autoGenerateColumns is set to False in order to manipulate the columns manually.

string SampleDataToPopulate = Server.MapPath("sampledatafile.xml");
DataSet dataSet = new DataSet();
dataSet.ReadXml(SampleDataToPopulate);
dgShowHide.DataSource = dataSet;
dgShowHide.DataBind();

and with DataBinder.Eval in the ItemTemplate of the datagrid, i'm populating my data.


JavaScript to do Show/Hide in ASP.NET Datagrid:

The javascript function loops through the arguments and sets up an element object to change the visibility to hidden or visible for the datagrid table row.

JavaScript Fuction:

function chgTextDetails(link)
{
link += "link";
linkText = document.getElementById(link);
linkText.firstChild.nodeValue;
if (linkText.firstChild.nodeValue == "Hide")
{
linkText.firstChild.nodeValue = "Show";
}
else
{
linkText.firstChild.nodeValue = "Hide";
}
}

After implementing all these part of code and we will get the complete solution for show hide operation in the ASP.NET Datagrid. After implementing the grid looks like. The screen clips as follows.


Here is the completed and running solution is aatached. Download The SourceCode

Saturday, November 11, 2006

C# to VB.NET and VB.NET to C#

Some important and usefull links for .NET programmers. Here in this blog you can get some of the usefull C# to VB.NET and VB.NET C# online code conversion websites.

C# to VB.NET Links:

http://www.kamalpatel.net/ConvertCSharp2VB.aspx

VB.NET to C# Links:

http://www.carlosag.net/Tools/CodeTranslator/Default.aspx

http://www.developerfusion.co.uk/utilities/convertvbtocsharp.aspx

Tuesday, November 07, 2006

"LoaderLock was detected" Error when debugging my .NET DirectX code sample:

When tried to develop a video player in .NET 2.0 and Visual Studio 2005 Team Suite using DirectX SDK I was stuck with this error. I tried the same code in .NET1.1 and Visual Studio 2003, the code runs fine, no "LoaderLock was detected" error. Then I started exploring about the error I got while using Visual Studio 2005.

Check this original error message:

LoaderLock was detected
DLL 'C:\WINDOWS\assembly\GAC\Microsoft.DirectX\1.0.2902.0__31bf3856ad364e35\Microsoft.DirectX.dll' is attempting managed execution inside OS Loader lock. Do not attempt to run managed code inside a DllMain or image initialization function since doing so can cause the application to hang.

Managed Debugging Assistants is also referred as MDA, MDA work with the Common Language Runtime (CLR) to provide information on runtime state. They generate information about runtime events. Load Lock is one of the MDA available in .NET framwork, the code part which exist in all Managed DirectX 1.1 assemblies, is the reason to MDA firing. The most common failure when executing code inside the operating system's loader lock is that threads will deadlock when attempting to call other Win32 functions that also require the loader lock.

The only thing that seems to hold this situation is simply to turn off the MDA for LoaderLock, which is not recommended solution.

Global registry key which is used to turn on/off MDA.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
"MDA"="1"

Better options to work around this problem are...

Look at the stack trace for the thread that has activated this MDA. The thread is attempting to illegally call into managed code while holding the operating system's loader lock. You will probably see a DLL's DllMain or equivalent entry point on the stack. The operating system's rules for what you can legally do from inside such an entry point are quite limited. These rules preclude any managed execution.

To go back to Visual Studio 2003 and .NET 1.1 . Else disable the loader lock Managed Debugging Assistants. Debug/Exceptions, Open the Managed Debugging Assistants tree node and uncheck Loader Lock. This setting is per solution so it will only affect this solution.

Tips:

In VS2005, go to the Debug->Exceptions menu. Within the Exceptions dialog expand the "Managed Debugging Assistants" node. Look for LoaderLock and uncheck the "Thrown" column.
Note: Do not disable all MDAs by setting MDA="0" in the registry as it causes problems.

Mixed managed/unmanaged C++ assemblies built for .NET Framework versions 1.0 or 1.1 generally attempt to execute managed code inside the loader lock unless special care has been taken. .NET 1.1 Managed DirectX assemblies when used with Visual Studio 2005 and .Net 2.0.

Learn About MDA:

Diagnosing Errors with Managed Debugging Assistants

Microsoft Helps related to this problem:

Managed Debug Assistants (MDAs) are cool.

Microsoft Visual Studio 2005 to debug a Microsoft Foundation Classes (MFC) class library application

Mixed DLL Loading Problem

Sunday, November 05, 2006

Using C#.NET play multimedia files - Using Multimedia Control Interface(MCI)

Multimedia is the best way to enhance the user interface of any application. In .NET there is many ways to play an Audio using any .NET technology supporting languages. One of the simple way to acheive is Multimedia Control Interface, shirtly we call it as MCI, wrapping high-level system components, such as Windows Media Player to play our audio files.

About Media Control Interface (MCI):

The Media Control Interface (MCI) provides standard commands for playing resource files. MCI's standard commands are a generic interface to almost all kind of multimedia devices. Media Control Interface provides applications with device-independent capabilities for controlling audio. MCI - High level multimedia control functions, Has commands common to all multimedia hardware. Possible since most use record/play metaphor Open a device for input or output If input, record; If output, play When done, close.

There are two different forms of MCI, one is Send command messages (like Windows messages) to MCI (need to include bit-encoded flags and C data structures) and another one is Send text strings to MCI Good for use from scripting languages with string functionality and simple to use MCI converts them to command messages.

Sending Strings to MCI:

error = mciSendString(sCmd , sRetStr, iReturn, hCallback);
· sCmd--themci command string (specifies command & device)
· sRetStr--return string buffer (NULL if none used)
· iReturn--size of return string buffer (0 if none used)
· hCallback--Handle to Callback window (NULL if none used)
– Returns 0 if command is successful, error code if not
· Can be used as a parameter to mciGetErrorString()
– Many command strings possible
– mciSendString, mciGetErrorString
– MCI Command Strings

For more details or help check the MSDN.

When Using Win32 Functions From .NET

Important note, MCI is not directly accessible from .NET, also mciSendString() is C++, not C#, but still you can use MCI and other Win32 API functions from .Net languages. The key is to use “Platform Invocation Services” “Interop Services” A generalized mechanism that allows calling functions that are imported from DLLs.

Must include: System.Runtime.InteropServices namespace; And then prefix any declarations of Win32 API functions to be used.

Example:
[DllImport("winmm.dll")]
private static extern long mciSendString(
string strCommand,
StringBuilder strReturn,
int iReturnLength,
IntPtr oCallback);


For MCI functions that DLL is winmm.dll, And then use equivalent .NET language data types for the parameters and for the type returned by the function.

Some of the disadvantages to be notes:

Code is no longer managed code and it’s no longer platform independent.

mciSendString() in .NET Unmanaged Code:

Corresponding C# parameter types would be:
– string, string, uint, intPtr
– In C# DWORD is implemented as an int

strCommand - Pointer to a null-terminated string that specifies an MCI command string.
strReturn - Pointer to a buffer that receives return information. If no return information is needed, this parameter can be null.
iReturnLength - Size, in characters, of the return buffer specified by the strReturn parameter. hwndCallback - Handle to a callback window if the "notify" flag was specified in the command string.

Some MCI Command String Commands:
· open -- initializes a multimedia device
· play– starts playing an open device
· stop -- stops playing from an open device
· record -- starts recording to a device
· seek -- move to a specified position on device
· save -- saves an MCI file
· close -- closes a device and associated resources
· set -- establish control settings for the device
· status -- returns information in 2nd parameter

However, most of these libraries are designed in such a way that they cannot be used to manipulate audio samples on the fly because they do not give you access to the actual sound data.




Here in this article i have covered some basics about the MCI in .NET. You can explore more in MSDN or in any other resource centre.

>>Download The Sample Code>>

Wednesday, October 25, 2006

File Properties using C#

File Name of your file:

When reviewing or opening a file, to get its name, the FileInfo class is equipped with the Name property. Here is an sample code:


FileInfo oFileInfo = new FileInfo(strFilename);
MessageBox.Show("My File's Name: \"" + oFileInfo.Name + "\"");


Date and Time a File Created

The Operating System takes care to keep track of the date and time of a file was created. To find out what those date and time values are, you can access the File System Information property using.

DateTime dtCreationTime = oFileInfo.CreationTime;
MessageBox.Show("Date and Time File Created: " + dtCreationTime.ToString());

Find your file extension:

When you access a file or when the user opens one, to know the extension of the file, you can access the value of the FileSystemInfo.Extension property.

MessageBox.Show("myFile Extension: " + oFileInfo.Extension);

Find file size using C#:

One of the routine operations the operating system performs consistly for all the file is calculating the size of files it holds.

MessageBox.Show("myFile total Size: " + oFileInfo.Length.ToString());

a

Tuesday, October 24, 2006

Community for .NET Technology

Here is one of the best interactive community for .NET Technology. All .NET technology lovers and programmers come lets add power to your .NET skill.

Click Here To Join The Community

Monday, October 23, 2006

Creating System Tray Applications in Windows Forms .NET 2.0

This simple article explains how to implement the common features and functionalities required for a notification-based application in Windows Forms: starting up a Windows Forms application without showing a Form, using the NotifyIcon, bringing an existing Form to the front of the desktop, and closing the Form on minimize.

Create Icons At Runtime For The System Tray in .NET

This simple way of creating Icons for system tray at runtime using .NET. Here is the code sample for creating the Icon for sytem tray.

String TaskBarLetter;
// Create a graphics instance that draws to a bitmap
Bitmap bitmap = new Bitmap(16, 16);
SolidBrush brush = new SolidBrush(fontDialog1.Color);
Graphics graphics = Graphics.FromImage(bitmap);
// Draw then number to the bitmap using the user selected font
if (i != -1)
TaskBarLetter = i.ToString();
else
TaskBarLetter = "V";
graphics.DrawString(TaskBarLetter, fontDialog1.Font, brush, 0, 0);
// Convert the bitmap into an icon and use it for the system tray icon
IntPtr hIcon = bitmap.GetHicon();
Icon icon = Icon.FromHandle(hIcon);
notifyIcon1.Icon = icon;
//GetHicon creates an unmanaged handle which must be manually destroyed
DestroyIcon(hIcon);


For this application, we’ll need to create a new NotifyIcon, ContextMenuStrip, and a few MenuItems for the ContextMenuStrip. The icon is set, and the NotifyIcon is set to Visible = true. The NotifyIcon.Text property is used in order to display a ToolTip on mouse hover. when you want to get the application out of the System Tray you have to use a Context Menu. First you must associate both the form and the Notify Icon with this context Menu. Just go into the properties for both of those items and set the ContextMenuStrip property to the name of your ContextMenuStrip(in this case contextMenuStrip1).



Download The Sample Sourcecode>>

Monday, October 16, 2006

Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System Beta

Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System Beta (also known as “Visual Studio 2005 Tools for Office Second Edition Beta” or “VSTO 2005 SE Beta”) is an add-on to Microsoft Visual Studio 2005 that enables you to build application-level add-ins for the 2007 Microsoft Office system as well as the Microsoft Office 2003 Editions.

Download VSTO 2005 SE

This contains application level add-in project template for six applications in Office System 2007. One exception is the InfoPath 2007 form project template. If the InfoPath 2003 Toolkit is installed, VSTO 2005 SE Beta replaces it with the new InfoPath 2007 form project template.

VSTO 2005 is the technology that brings the power and productivity of Visual Studio .NET and the .NET Framework to business solutions built on Microsoft Word 2003, Microsoft Outlook 2003, Microsoft Excel 2003 or Microsoft InfoPath 2003.

Microsoft Visual Studio 2005 Tools for the Microsoft Office System (VSTO 2005) Redistributable Package (x86) - Download

The VSTA SDK is installed as part of the Visual Studio SDK. Download Visual Studio 2005 SDK - February 2006

Wednesday, October 04, 2006

Creating Files using ASP.NET code behind VB.NET -- Save a file to a specific directory

In ASP.NET we can create a file and save it in a particular directory, to do the operation we have two different ways. One is using Response.Write("STRING") and another one is filestream.

First let me give you the sample code using Response.Write("STRING").

Code Sample using Response.Write("STRING"):

Imports System
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient

Public Class WebForm1
Inherits System.Web.UI.Page

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim filename As String
Dim dr As SqlDataReader
Dim i As Integer
Dim sb As System.Text.StringBuilder

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button1.Click
cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
filename = "products.csv"
cmd = New SqlCommand("select * from products ", cn)
cmd.Connection.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
sb = New System.Text.StringBuilder


'For field Names
For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1) Then

sb.Append(Chr(34) & dr.GetName(i) & _ Chr(34) & ",")
Else
sb.Append(Chr(34) &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;
dr.GetName(i) & _ Chr(34) & vbCrLf)
End If Next

'For field Values
While dr.Read()
For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1)
Then
sb.Append(Chr(34) & _ dr.GetValue(i).ToString & Chr(34) & ",")
Else
sb.Append(Chr(34) & _ dr.GetValue(i).ToString & Chr(34) & vbCrLf)
End If Next
End
While dr.Close()
cn.Close()
Response.ContentType = "Application/x-msexcel" Response.AddHeader _ ("content-disposition", "attachment; filename=""" & _ filename & """")

'Write the file directly to the HTTP output stream.

Response.Write(sb.ToString)
Response.End()
End Sub
End Class

Code Sample using filestream:

Imports System
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Public Class WebForm1
Inherits System.Web.UI.Page

Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim filename As String
Dim dr As SqlDataReader
Dim i As Integer
Dim sb As System.Text.StringBuilder


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
cn = New SqlConnection("server=localhost;uid=sa;pwd=;database=northwind")
filename = "products.csv"
cmd = New SqlCommand("select * from products ", cn)
cmd.Connection.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
sb = New System.Text.StringBuilder

'For field Names
For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1)

Then
sb.Append(Chr(34) & dr.GetName(i) & Chr(34) & ",")
Else sb.Append(Chr(34) &amp;amp;amp;amp;amp;amp;amp;
dr.GetName(i) & Chr(34) & vbCrLf)
End If
Next
'For field Values
While dr.Read()
For i = 0 To dr.FieldCount - 1
If i < (dr.FieldCount - 1)
Then
sb.Append(Chr(34) & dr.GetValue(i).ToString & Chr(34) & ",")
Else
sb.Append(Chr(34) & dr.GetValue(i).ToString & Chr(34) & vbCrLf)
End If
Next
End While
dr.Close()
cn.Close()
// FileStream to create files
Dim fs As New FileStream("c:\products0.csv", FileMode.Create, FileAccess.Write)
Dim s As New StreamWriter(fs)
s.BaseStream.Seek(0, SeekOrigin.End)
s.WriteLine(sb.ToString) s.Close()
End Sub
End Class


These are the two simple ways to create files using VB.NET.

Friday, September 29, 2006

Visual Studio 2005 Web Deployment Projects

In Visual Studio 2005 there no option exist for build deployment DLL for your web application by default. We need to install Visual Studio 2005 Web Deployment Projects to enable this deployment option in your visual studio 2005. A Web Deployment Project creates and maintains an MSBuild project file, and is associated in a solution with a Web Site Project or Web Application Project. Here is the download link for "Visual Studio 2005 Web Deployment Projects".

After installing select your website in your solution explorer.













After that go to Build menu and select Add Web Deployment Project.











The Web Deployment property will be added to your website.


Then double click on the Web Deployment property you added to your website, the property window opens, in that you can set whatever deployment property to set for your solution.




learn more about Visual Studio 2005 Web Deployment Projects in the follow link. Learn more>>

Friday, September 22, 2006

System.Data.SqlClient.SqlParameterCollection.Add(string, object)' is obsolete: 'Add(String parameterName, Object value) has been deprecated.

For all .NET programmers who are using this

SqlCommand.Parameters.Add("@MyValue","Value");

code in ADO.NET 2.0 will get a deprecation message. Instead of using this code, you need to use the following code

SqlCommand.Parameters.AddWithValue("@MyValue","Value");

this " SqlCommand.Parameters.Add("@MyValue","Value"); " is a ADO.NET 1.1 way of coding, if you are still using this code in ADO.NET 2.0, you will get the following warning message.

" 'System.Data.SqlClient.SqlParameterCollection.Add(string, object)' is obsolete: 'Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value). http://go.microsoft.com/fwlink/?linkid=14202' C:\Documents and Settings\501597\My Documents\Visual Studio 2005\WebSites\mytool\MyFirstPage.aspx.cs 149 10 C:\...\doc\ "

This is because of some other API changes in the framework. Checkout the list of obsolete changes in the following links
http://msdn.microsoft.com/netframework/programming/obsoleteapi/ObsByAssembly.aspx
http://www.gotdotnet.com/team/changeinfo/default.aspx

Tuesday, September 19, 2006

XML and XSLT transformation using C#.NET

With XML Document you can illustrate data hierarchically without caring about the later output format, and with XSL-Transformations you have the ability to convert the data content of that XML document into various formats such as text, xml, html etc. XSLT, the extensible style sheet language for transformations, is a language that provides the mechanism to transform and manipulate XML data. It is used to transform XML documents into another documents, for example other XML document, HTML document or text document. XSLT processors parse the input XML document, as well as the XSLT style sheet and then process the instructions found in the XSLT style sheet, using the elements from input XML document.

Here in this sample I have explained you the XML and XSLT transformation using C#.NET 2.0.
C#.NET 2.0. Before transformation my tool will look like this...








After you select your XSLT and XML files when you click on the preview button the output is displayed as HTML in the webBrowser control.



For more see the sample code...


XPathDocument xmlFileDoc = new XPathDocument(txtxmlfilepath.Text.ToString());
XmlTextWriter myWriter = new XmlTextWriter("result.html", null);
XslCompiledTransform XSLpreview = new XslCompiledTransform();
XSLpreview.Load(txtxslfilepath.Text.ToString());
XSLpreview.Transform(xmlFileDoc, null, myWriter);
myWriter.Close();
webBrowser1.Navigate(@"C:\result.html");

Download The Sample Solution

Monday, September 04, 2006

How to store errors in the trace.axd

Using Trace.xsd in asp.net applications is a nice feature to log errors. To get this work you have to create a web.config which must reside in the application root folder.

The web.config looks like this:

Now whenever an error occurs it is logged and can be accessed via the following url: http://localhost/urapplication/trace.axd

I use the user name "superuser" for illustration only. You could also say .

Depending on if you are using Forms authentication or Windows authentication, you'd either use a user/role name that you've defined, or one that Windows defines such as "USER\Administrators" or DOMAIN\youraccount

Features enriched in Visual Studio 2005 Team Suite

Visual Studio 2005 Team System is a productive, integrated, and extensible suite of lifecycle tools that expands the Visual Studio product line to enable greater communication and collaboration among software development teams. With Visual Studio 2005 Team Suite organizations can ensure greater predictability and quality early and often throughout the development process.

Key features enriched in VSTS:

Automatic and Manual Conflict Resolution Tool: The Automatic and Manual Conflict Resolution Tool handles issues caused by multiple users working on different versions of the same file.

Atomic Checkins: Team Foundation Server enforces atomic check-in to help maintain the integrity of files under source control.

Auto-Using: The Visual Studio 2005 Integrated Development Environment (IDE) includes Smart Tag support for auto-using statements.

Branching: Branching allows the creation of multiple similar code bases.

Bug List: With Visual Studio Team System (VSTS), you can easily find, track, and view bugs by using the Bug List report.

Better ASP .NET Source Code Editing: With the Visual Studio 2005 source code editor, Intellisense and new features for formatting, navigating and validating your HTML markup are available throughout your files.

Built-in SQL Server 2005 Express Support: You can develop and debug database objects for your application in Visual Studio 2005, even if you don't have access to SQL Server 2005.
Caching Improvements: Team Foundation Server is ideal for geographically distributed teams because of its server-based nature.

Check-in Notes: With Team Foundation Server Check-in Notes, administrators may collect data from users during the check-in process.

Check-in Policy: Team Foundation Server check-in policies provide a way for administrators to enforce development practices across a development team.

Thursday, August 17, 2006

Microsoft Office 2003: Microsoft InfoPath 2003 Performance tuning

Overview of the solution:

The Solution here highlights how a Microsoft technology is used in critical business problems using solutions built with the Microsoft Office System. Microsoft InfoPath 2003 is one of the new office tools available with Microsoft Office 2003. Microsoft InfoPath 2003 gather information flexibly and efficiently in rich, dynamic forms and more effectively share, reuse, and repurpose information throughout your team or organization. InfoPath 2003 helps improve collaboration and decision-making to positively impact your business. While developing solutions using InfoPath 2003 most of the developers will face this performance issues and struggle to overcome from it, here in this article I provide some of the valuable tips and tricks that will definitely increase your InfoPath 2003 solution’s performance.

InfoPath 2003 Performance tuning tips and tricks:

If the view contains many controls, and especially if they are repeating controls such as repeating tables and repeating sections, you should separate the view into multiple views to reduce the amount of HTML rendering that InfoPath is required to do.

Always try to Use Expression Box to display calculated value, if you don't need to storethat value. If you have business logic to trigger all the calculation, pleaseonly trigger necessary calculation. Triggering large amount of calculationsis costly process.

Rules: About the form XSL, and XSF, anything in the XSF is extremely slow,anything in the XSL is acceptable, or fast, so when we develop a form, we have toreview these files frequently, for example, the conditional formatting goesto the XSL, it is ok, the speed is acceptable. But rules are going to the XSF, then we try to find a way to convert them to C# code, some of the things we do can become C# some not, once it is C# (with the custom event handlers), the speed increases dramatically.

Views: About the multiple views in a form, we found that if the form have one or10 views, does not matter, unless that increases the size of the XSF, then thespeed goes down.

NOTE: Not all the things in the XSF are slow; some of the items are fast

xml DOM: Be cautious while using replace node function on the xml DOM in the C#code, replacing large amount of nodes is very slow, it seams a DOM problem,talking about a 1MB of xml, ironically, loading 10MB of xml in the DOMusing the DOM function is extremely fast, so the speed is different perfunction.

Avoid using more number of tables (data or layout) in any single view. Avoid large repeating data structures that can grow too many pages. Avoid complex nesting of optional and repeatable sections. These are quite complicated to layout and also can quickly cause a single view to become very large.

Be aware of exactly what your business logic does. For example, onAfterChange can fire multiple times for a single edit.

Try to avoid querying data at the form load event. Rather than querying for all the data then having InfoPath just show a small amount, refine your query and only bring the data you plan on displaying into InfoPath. Don’t pre-populate data sources that aren't necessary on load. Don't set up un-used data source. Merge static xml data sources into one if you have multiple xml data connections.

Limit the number of drop-down list boxes that contain many items, especially within repeating controls. Internet Explorer renders each drop-down list box with its own window handle (HWND), and the HTML representation of a drop-down list box with many items is significant.

Friday, August 04, 2006

Adding Custom ToolBar Button in your InfoPath 2003 Form

Adding Custom ToolBar Button in your InfoPath 2003 Form. Open the Manifest.xsf file.
Find the xsf:mainpane tag in the manifest file and then Insert the following code after the xsf:mainpane tag in the manifest

<xsf:toolbar caption="myToolbar" name="myToolbar">

<xsf:button name="tlbSave" caption="Save Data"> </xsf:button>

</xsf:toolbar>


Finally You must create an event handler for the OnClick event associated with each of these buttons for them to be functional. This will show you button with "Save" Text return on it.

Displaying HTML content in any of the InfoPath 2003 form’s control

Displaying HTML content in any of the InfoPath 2003 form’s control – the Rich Text Box control can be used to copy and paste any content except the HTML content.

Open corresponding XSL file of your InfoPath Template and select the field in which your going to use the HTML as input. Your control element will be like this

<xsl:value-of select="my:field1" >

What you have to so is just add one attribute called “disable-output-escaping”. And set that attribute to yes.

<xsl:value-of select="my:field1" disable-output-escaping="yes">

Hiding a control through code - InfoPath 2003

Hiding a control through code in infopath

public bool ControlProperty()
{
return true;
}


In the property window of your InfoPath control, select Display tab, Click on conditional formatting button, then click add button, select Expression box in the 1st drop down box, and add the code xdExtension:ControlProperty() in the text box and select the property you want to set for that control and click ok.

Setting Focus on Controls - InfoPath 2003

Setting Focus on Controls in your infopath forms.

// Code For Setfocus
IXMLDOMNode nodeSelText = thisXDocument.DOM.selectSingleNode("/my:myFields/my:field1");
thisXDocument.View.SelectText(nodeSelText,Type.Missing);

Custom save Code in InfoPath 2003

To enable or disable save functionality

In the design mode of InfoPath, on the Tools menu, click Form Options. Click Open and Save. Click Open and Save. In the Enable Features section, select the options appropriate for your form. In the Save behavior section, you have a check box option called Save using custom code. If you select this option and click Edit, you create the OnSaveRequest callback function in your form code.

public void OnSaveRequest(SaveEvent e)
{
if (thisXDocument.IsNew == true e.IsSaveAs == false)
{
e.IsCancelled = e.PerformSaveOperation();
e.ReturnStatus = true;
}
else
{
thisXDocument.UI.Alert("The 'Save As' functionality is disabled for forms that are not new.");
}
}
  • ReturnStatus = true, IsCancelled = true The form is not saved, but the OnSaveRequest function is successful.
  • ReturnStatus = true, IsCancelled = false The form is saved, and the OnSaveRequest function is successful.
  • ReturnStatus = false, IsCancelled = true The form is not saved, an error is thrown, and an error message appears to the user.
  • ReturnStatus = false, IsCancelled = false The form is not saved, an error is thrown, and an error message appears to the user.

Wednesday, August 02, 2006

Columns hide in Winforms Datagrid

This code is to hide the columns in the DataGrid in WinForms Application.

DataGridTableStyle ColHidStyle = new DataGridTableStyle();
ColHidStyle.MappingName = "HideTest";
dataGrid1.TableStyles.Add(ColHidStyle);
ColHidStyle.GridColumnStyles["Modifier"].Width = 0;

or other way is

objDs.Tables["myTableName"].Columns["myColumnName"].ColumnMapping = MappingType.Hidden;

custom number formatting in C#

One of the painful things about good old ASP was string formatting; VBScript simply didn't have anything useful. C# do, but MSDN doesn't provide a quick reference to the formatting options. So here's a quick reference. The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you're not passing in a buffer there's no chance of a buffer overflow.

string outputString = String.Format("At loop position {0}.\n", i);

The ToString method can accept a string parameter which tells the object how to format itself. In the call to String.Format , the formatting string is passed after the position, for example, "{0:##}". The text inside the curly braces is {argumentIndex[,alignment][:formatString]}. If alignment is positive, the text is right-padding to fill the specified field length, if it's negative, it's left-padded.custom number formatting

specifier type format output
(double 1234.56)
0 zero placeholder {0:00.000} 1234.560
# digit placeholder {0:#.##} 1234.56
. decimal point placeholder {0:0.0} 1234.6
, thousand separator {0:0,0} 1,235
% percentage {0:0%} 123456%


Some of the code i tried...

//decimal stingDate = Convert.ToDecimal( "79798797987.96999797696");
//string stgDate = String.Format("{0:$#,##0.00;($#,##0.00);Nothing}", stingDate);
//string stingDate = String.Format("{0:$#,##0.00;($#,##0.00);Nothing}", str);
//MessageBox.Show(stgDate);

string stingDat = System.DateTime.Today.Date.ToShortDateString();
int day = DateTime.Parse(stingDat.ToString()).Day;
MessageBox.Show(day.ToString());
int month = DateTime.Parse(stingDat.ToString()).Month;
MessageBox.Show(month.ToString());
int year = DateTime.Parse(stingDat.ToString()).Year;
MessageBox.Show(year.ToString());
DateTime curSysDate = new DateTime(year, month, day);
MessageBox.Show(curSysDate.ToShortDateString().ToString());

Calling the Open With dialog box from your application, using C#

This article is to introduce shell programming with C# for beginners in .NET. The Shell namespace organizes the file system and other objects managed by the Shell into a single tree-structured hierarchy. Conceptually, the Shell namespace is essentially a larger and more inclusive version of the file system. The Shell namespace objects include file system folders and files, along with "virtual" objects, such as the Recycle Bin and Printers folders. One of the primary responsibilities of the Shell is managing and providing access to the wide variety of objects that make up the system. Here, I have created a sample for demonstrating how to call the Open with dialog box in your Windows system.

Here in this article, I have developed a simple image viewer application to demonstrate the Open with dialog box in Windows, using C#. It’s really hard to explain the Shell concepts. This application is developed using Microsoft Visual C# Express Edition.
A struct-declaration consists of an optional set of attributes, followed by an optional set of struct-modifiers, followed by the keyword struct and an identifier that names the struct, followed by an optional struct-interfaces specification, followed by a struct-body, optionally followed by a semicolon. And the Serializable keyword indicates that a class can be serialized. This class cannot be inherited.

[Serializable]
public struct ShellExecuteInfo
{
public int Size;
public uint Mask;
public IntPtr hwnd;
public string Verb;
public string File;
public string Parameters;
public string Directory;
public uint Show;
public IntPtr InstApp;
public IntPtr IDList;
public string Class;
public IntPtr hkeyClass;
public uint HotKey;
public IntPtr Icon;
public IntPtr Monitor;
}
// Code For OpenWithDialog Box
[DllImport("shell32.dll", SetLastError = true)]
extern public static bool
ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
public const uint SW_NORMAL = 1;
static void OpenAs(string file)
{
ShellExecuteInfo sei = new ShellExecuteInfo();
sei.Size = Marshal.SizeOf(sei);
sei.Verb = "openas";
sei.File = file;
sei.Show = SW_NORMAL;
if (!ShellExecuteEx(ref sei))
throw new System.ComponentModel.Win32Exception();
}

Tuesday, May 30, 2006

ConfigurationSettings.AppSettings["SQLConnString"]; -- Become Obsolete in .NET 2.0

Recently when I tried to create a data access component for my web application in .NET 2.0 I found that ConfigurationSettings class as become obsolete. In .Net 2.0 ConfigurationManager class that replaces ConfigurationSettings.

“System.Configuration.ConfigurationSettings.AppSettings["SQLConnString"]; this method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings"

The System.Configuration.ConfigurationSettings.AppSettings["SQLConnString"];
Will give your warning that this “this method was obsolete”. What to do in order to use ConfigurationManager class? System.Configuration.dll - ensure you add a reference to this assembly. In .NET 2.0 all configuration functionality is in this separate assembly now.

ASP.NET MVC - Sport Facility Booking system

  The project relies on some external service providers. Thus accessing them via their API requires authentication. An API Key need to be su...