Tuesday, November 6, 2007

Send Email thru SQL

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[usp_sendMail]
(
@chMailFrom VARCHAR(100), @chMailTo VARCHAR(100), @chMailSubject VARCHAR(500),
@chMessage VARCHAR(8000), @chMailCC VARCHAR(1000)=NULL, @chMailBCC VARCHAR(1000)=NULL,
@chAttachedFile VARCHAR(1000)=NULL, @chAttachFile VARCHAR(1000)=NULL, @chAttachFile3 VARCHAR(1000)=NULL)
AS
DECLARE @Object INT, @HResult INT, @varerror INT
EXEC @HResult = dbo.sp_OACreate 'CDONTS.NEWMAIL',@Object OUT
EXEC @HResult = sp_OASetProperty @Object, 'BodyFormat', 0
EXEC @HResult = sp_OASetProperty @Object, 'MailFormat', 0
EXEC @HResult = sp_OASetProperty @Object, 'From', @chMailFrom
EXEC @HResult = sp_OASetProperty @Object, 'To', @chMailTo
EXEC @HResult = sp_OASetProperty @Object, 'Subject', @chMailSubject
EXEC @HResult = sp_OASetProperty @Object, 'body', @chMessage
IF REPLACE(isNull(@chMailCC,''),' ','') <> ''
EXEC @HResult = sp_OASetProperty @Object, 'CC', @chMailCC
IF REPLACE(isNull(@chMailBCC,''),' ','') <> ''
EXEC @HResult= sp_OASetProperty @Object, 'BCC', @chMailBCC
IF REPLACE(isNull(@chAttachedFile,''),' ','') <> ''
EXEC @HResult = sp_OAMethod @object, 'AttachFile', NULL, @chAttachedFile
IF REPLACE(isNull(@chAttachFile,''),' ','') <> ''
EXEC @HResult = sp_OAMethod @object, 'AttachFile', NULL, @chAttachFile
IF REPLACE(isNull(@chAttachFile3,''),' ','') <> ''
EXEC @HResult = sp_OAMethod @object, 'AttachFile', NULL, @chAttachFile3
EXEC @HResult = sp_OAMethod @Object, 'Send'
-- SELECT @varerror = @@error
-- IF @varerror != 0
-- PRINT 'E R R O R W H I L E S E N D I N G M A I L'
EXEC @HResult = sp_OAdestroy @Object

Thursday, November 1, 2007

Visual Studio .NET

1. What is Visual Studio .NET 2005?
The release of Visual Studio 2005 and the .NET Framework 2.0 will make strides in all dimensions of application development. First, Visual Studio 2005 will set a new bar for developer productivity by tailoring the software development experience to the needs of the individual developer. This "personalized productivity" will deliver features across the development environment and .NET Framework class libraries to help developers overcome their most pressing challenges in minimal time. Second, Visual Studio 2005 will enable developers to apply existing skills across a broader range of application development scenarios through improved integration with the Microsoft Office System and SQL Server 2005. Finally, Visual Studio 2005 will deliver a new set of tools and functionality that will help satisfy the application development needs of today's large-scale enterprises.
2. what are the Basic of Visual Studio .NEt 2005 ?
o Edit and Continue:
Visual Basic has always been about Rapid Application Development (RAD). One key feature is the ability to fix runtime errors on the fly. With Visual Basic .NET 1.0 and Visual Basic .NET 1.1, this powerful feature wasn't included. This feature is on-board for Whidbey. If you run into an exception at runtime, you get an exception helper that provides tips for fixing common errors, but more importantly, you can edit the code, select F5, and it continues right where you left off. Edit and Continue is VB .NET only feature
o ClickOnce
ClickOnce make it easy to install applications and provide ongoing updates (Self-Updating), rather than forcing to distribute new versions of application, can just deploy the portion of the application which has changed. In the .NET Framework 1.0 and 1.1, href-exes were not able to solve many deployment issues. Href-exes are also known as no-touch deployment, or zero impact deployment. Essentially, with versions 1.0/1.1, you can deploy an application to a Web server, allowing users to browse to the URL for the exe.When the user clicks the link, the application downloads to their Internet files cache and runs. To keep this from being a huge security hole, the application permissions are restricted based on the URL (Intranet applications get different permissions than Internet applications, for example), or other factors. This means that some applications no longer need to be deployed in the traditional sense; no more setup.exe or MSI
o SmartTags
This provides access to information and common tasks without forcing you to constantly navigate away from your work area
o Code Snippets
With code snippets, you can insert generic "template" code that requires only that you fill in the blanks. You can access code snippets by right-clicking in the code editor and navigating in the context menu to Insert Snippets.
3. What is Refactoring?
Making changes to your code like, "pulling a large stretch of inline code into its own method" or "converting a field to be a property." The Refactoring support makes this easy to do The key tenet of Extreme Programming created by Kent Beck is constant Refactoring. Under this programming model, you are developing code rapidly and iteratively, but to keep your code from becoming a jumbled mess, you must constantly Refactor. Refactoring is a C# only feature
o Extract Method
This is to split a method into many fine grained methods which are reusable.
o Rename
This is used to rename an identifier i.e. field, variable, method etc
o Encapsulate Fields
Creating a property to encapsulate a field
o Extract Interfaces
Creating an interface which is implemented by current class.
o Add Using Unbound Types
Automatic inclusion of namespace for an unbound type.
4. What are Visual studio 2005 Solution and Project related Features?
o Test Projects
This option is very useful for experimenting etc. User can just create a temporary project and start coding without saving it.
o Simplified Build
This option provides build option similar to Visual Basic 6.0. This is a useful option for VB programmers.
o Stand-alone projects
This is applicable for solution which has only one project. User will not see the solution in the Solution Explorer as well as the commands that act on solutions. However the solution files are still created.
o Project Properties
This is the central location for all project properties and settings. This provides improved access to resources and strong-name signing within the IDE.
o Visual Studio Conversion Wizard
Using this option, developers can convert their projects in Visual Studio .NET 2002 or Visual Studio .NET 2003 to Visual Studio 2005. While converting, this provides an option to create a backup of the solution or project.
o Projects and Solutions options
This feature contains separate pages for General and Build and Run options.
o Custom Project and Project Item Templates
This feature allows creation or modification of custom template for projects or project items. These custom templates appear in the New Project dialog box and Add New Item dialog box. These templates contain a project file, code files and an XML file containing metadata for the template, which is used by Visual Studio to define how to display and create the project in the development environment. These files are compressed in a .zip file so that it can easily be shared with others.
5.What are Visual Studio Project Building Features?
o Building VS 2005 introduces a new xml based transparent build system for all managed client application called MS.Net Build Engine (MSBuild). Developers can specify the as what to build and how to build under different platforms and configurations in the XML file associated with the build engine. Also they can author re-usable rules to achieve consistent builds across projects. The MSBuild build process is defined by atomic units of build operation (tasks) which can be re-authored by the developers in any .Net languages. However MSBuild cannot be used to build Web projects, deployment projects, and Visual C++ projects.
6. What are Visual Studio Debugging Features?
o Edit and Continue
This feature is only supported in VB.Net. This allows the developer to edit the code while debugging the application (Like in Visual Basic).
o Visualizers
This is a very useful feature. It can be launched from a Watch window or from the new enhanced DataTips and enables viewing of data in an intuitive and natural format i.e. now a string can be viewed as an HTML or an XML document. Also developers can write their own visualizers.
o Tracepoints and Improved Breakpoint UI
Tracepoints are a new way of using breakpoints to perform a custom action i.e. displaying a messagebox or executing a Visual Studio automation macro to determine whether to break or continue when it hits a tracepoint. The user interface is also enhanced to set these breakpoints easier and faster.
o Better Tools for Multiprocess Debugging
Now developers can see all processes attached to for debugging in the Processes window. Breakpoint can be attached to a specified processes, threads, and machines. Attach to Process dialog box is simplified and attached processes information is moved from the dialog box to the Processes window.

.NET Remoting

1. What is .NET Remoting?
.NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication.
2. What’s a Windows process?
It’s an application that’s running and had been allocated memory.
3. What are the consideration in deciding to use .NET Remoting or ASP.NET Web Services?
Remoting is a more efficient communication exchange when you can control both ends of the application involved in the communication process. Web Services provide an open-protocol-based exchange of informaion. Web Services are best when you need to communicate with an external organization or another (non-.NET) technology.
4. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
5.
What security measures exist for .NET Remoting in System.Runtime.Remoting?
None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
6. What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
7. Can you configure a .NET Remoting object via XML file?
Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
8. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs?
Binary over TCP is the most effiecient, SOAP over HTTP is the most interoperable.
9. How do you define the lease of the object?
By implementing ILease interface when writing the class code.
10. What’s SingleCall activation mode used for?
If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.

BizTalk

1. What is BizTalk?
Biztalk is a messaging based integration tool.Bonus:It consists of several different pieces including Business Processes (Orchestrations), BAM, Rules Engines, and HAT.
2. What is a Message Type (i.e. BTS.MessageType) and how is it used in BizTalk?
Message Type is a BizTalk System property that is promoted inside a Pipeline. It is made up of Document Name Space # Root Node Name.
3. What is the default mapping for Auto Mapping?
The default is by structure.This can be change to by node name on the map properties.
4. How do you call a Non-Serializable .Net helper class inside an Expression Shape?
o Add a reference to that class.
o Make sure your Orchestration is Long Running transactional.
o Add an Atomic scope.
o Create an Orchestration variable of that class inside the scope.
o Create an instance on that object inside the scope.
o Call the method.
o Bonus: Mention the class must be strongly signed and in the GAC.
5. What if the class is Serializable?
No transactional Orchestration or Atomic scope is needed.
6. What does the Value Mapping Functoid do?
Returns the second parameter if the first parameter is true
7. What is the difference between a Distinguished field and a Promoted Property?
o Distinguished fields are light weight and can only be used inside an Orchestration.
o Promoted Properties are defined inside a property schema, are tracking in SQL, can be tracked in HAT, and can be used for content based routing.
8. How do you achieve First-In-First-Out message processing of messages received from multiple sources using an Orchestration?
o Use a Sequential Convoy to process the messages in the order they are received into the Message Box.
o Make sure Ordered Delivery is set to True inside the Orchestration Receive Port.
9.
At high level, what do Receive Ports and Orchestration Send Port really do in terms of messaging? What about Send Ports and Orchestration Receive Ports?
o Receive Ports and Orchestration Send Port are both publishers.
o Ports and Orchestration Receive Ports are both subscribers.
10. When working with Schemas, Maps, Pipelines, and Orchestrations how should the projects be structured?
o Schemas and Maps in its own project.
o Or Schemas and Maps together in its own project.
o Orchestrations in its own project.
o Pipelines in it own project.
11. What is direct binding?
o Direct binding has three types: direct to message box, self correlating, and partner ports.
o Used to route message between the message box and Orchestrations without using bindings or from one Orchestration to another Orchestration.
12. What is BAM used for?
BAM is used to monitor business milestones and key metrics in near real-time throughout a process in BizTalk.
13. What is the Rules Engine?
Rules are used to provide highly efficient, easily changeable business rules evaluation to Business Processes. This allows rules to be changed without rebuilding and redeploying .net assemblies. The Business Rules Engine (BRE) can also be called from any .net component through the API’s
14. What are Persistence Points and what causes them?
o Persistence is when the state of a running Orchestration is stored into SQL.
o It is good enough to know various shape and actions cause persistence. More specifically, it occurs: end of a transactional scope, at a send shape, at a start Orchestration shape, during dehydration, if the system shuts down expectedly or unexpectedly, or the business process suspends or ends.
15. What group does a user need to belong to in order to submit messages to the message box?
The user needs to be a member of the hot group or isolated host group (assuming a default installation).
16. What user rights to you need to perform most actions in HAT?
o BizTalk Server Administrator
When installing Biztalk in a multi-server configuration with a remote SQL and Analysis Services

Database Architecture

Microsoft® SQL Server™ 2000 data is stored in databases. The data in a database is organized into the logical components visible to users. A database is also physically implemented as two or more files on disk.
When using a database, you work primarily with the logical components such as tables, views, procedures, and users. The physical implementation of files is largely transparent. Typically, only the database administrator needs to work with the physical implementation.
Each instance of SQL Server has four system databases (master, model, tempdb, and msdb) and one or more user databases. Some organizations have only one user database, containing all the data for their organization. Some organizations have different databases for each group in their organization, and sometimes a database used by a single application. For example, an organization could have one database for sales, one for payroll, one for a document management application, and so on. Sometimes an application uses only one database; other applications may access several databases.
It is not necessary to run multiple copies of the SQL Server database engine to allow multiple users to access the databases on a server. An instance of the SQL Server Standard or Enterprise Edition is capable of handling thousands of users working in multiple databases at the same time. Each instance of SQL Server makes all databases in the instance available to all users that connect to the instance, subject to the defined security permissions.
When connecting to an instance of SQL Server, your connection is associated with a particular database on the server. This database is called the current database. You are usually connected to a database defined as your default database by the system administrator, although you can use connection options in the database APIs to specify another database. You can switch from one database to another using either the Transact-SQL USE database_name statement, or an API function that changes your current database context.
SQL Server 2000 allows you to detach databases from an instance of SQL Server, then reattach them to another instance, or even attach the database back to the same instance. If you have a SQL Server database file, you can tell SQL Server when you connect to attach that database file with a specific database name.

Wednesday, October 31, 2007

SharePoint: Does the user have permissions?

A common task in SharePoint programming is writing security code. One of the great things about the object model is that it is security trimmed, so you can usually just ask for items that the user has permissions for. However, there may be items that the user can access but the user still doesn't have access to perform a specific task-- which is a great reason to check for permissions before attempting an operation. I'm pretty sure I've blogged about this before... but I've heard this question several times lately.
To check for permissions on an item, the SPSecurableItem interface defines 2 methods for checking security. The DoesUserHavePermissions method returns a bool speccifying if the user can access the item, where the CheckUserHasPermissions method will throw a security exception, which causes a 401 http status if the current SPSite's CatchAccessDeniedException property isn't set to false. Also note that you call these using the SPBasePermissions value which specifies the task you want to check permissions for-- and you don't use the overloaf
The following sample shows how to check permissions on the SPWeb level:
SPWeb web = SPContext.Current.Web ;if (web.DoesUserHavePermissions(SPBasePermissions.ViewListItems){ // do something, like Enumerate lists}
The SPList is also an ISecurableObject, which means that you can apply the same principlesto check permissions on lists. To check the user’s permission to view list items within aspecific list, call the list’s DoesUserHavePermissions method as follows:foreach(SPList list in web.lists){ if (list.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { /* Process the list */ }}
Likewise, the same method is available in other objects, such as the SPListItem class, whichcan be used to ensure that the user has permissions to the item or document:foreach(SPListItem item in list.Items){ if (item.DoesUserHavePermissions(SPBasePermissions.ViewListItems)) { {/* Process the list item */ } }
You can also check if the anonymous user has access to an item like this, in the case where the current user is anonymous:if ((list.AnonymousPermMask64 & SPBasePermissions.ViewListItems) == SPBasePermissions.ViewListItems)
{ // Do something here... }
You can also get the subwebs for the calling user using the method, which will return a security trimmed collection of webs:
SPContext.Current.Web.GetSubwebsForCurrentUser();

What We’ve Learned about AJAX Code in SharePoint

In “Inside WSS” we did a chapter on using ASP.NET AJAX technologies within SharePoint. There are a few things we’ve learned since writing the book that we’d like to clear up, and a few ASP.NET techniques that we’d recommend avoiding in favor of more stable methods, as well as some additional tips and tricks for coding AJAX applications in the portal. We’ve been proving these technologies both in the classroom and through commercial applications for close to a year now, refined some methods and established the supportable development story. I'll add this to an official errata for the book, but these tips will be useful to any ajax developer working in SharePoint.
First off, we would not recommend using the WebResource and ScriptResource technologies. We talk about this in the Web Parts chapter as well as the Ajax chapter, but in commercial applications we’ve decided to deploy resources to the “_layouts” vdir which is easier to debug and avoids a bug with the SharePoint runtime, in which the call to compiled script resources sometimes fails when accessed by a non-administrator. This can be a difficult bug to track down in your application, especially if you develop as an administrative account on your dev box (but, something you can totally avoid when using Windows server 2008 as your dev box!) What we do recommend and what is fully supported is deploying resources to a folder for your application in the Layouts application (http://localhost/_layouts/[your app name].)
So instead of the following code:

string xsl = this.Page.ClientScript.GetWebResourceUrl(typeof(FeedListWebPart),@"LitwareAjaxWebParts.Resources.OPML.xslt");this.XsltUrl = SPContext.Current.Web.Url + @"/" + xsl;

We would simply use:

this.XsltUrl = @"/_layouts/litware/rss.xslt";
ASP.NET AJAX ScriptReferences are simplified as well. Instead of compiling in the resource and adding the required assembly attribute before adding the script reference by fully qualified type name, we recommend adding a script reference with the URL:

this.AtlasScriptManager.Scripts.Add(new ScriptReference("/_layouts/Litware/ListViewWebPart.js"));
Another point of failure we've found is the ASP.NET AJAX JavaScript proxy generator. We've found that in most scenarios, the reference to foo.asmx/js fails when the calling user is not the administrator. So instead of creating a ServiceReference with the ASP.NET Script Manager, we instead save the asmx/js endpoint to a JavaScript file that we deploy with our other scripts. When calling web services that use the site context, it is also necessary to set the proxy's url before each call, or you'll be calling the webservice from the root web site's context. Because of this, we include the spWebUrl property in the SharePoint Ajax Toolkit, which writes the current SPWeb's Url to the window.spWebUrl property. To do this, use the set_path method of your web service proxy, like this, immediately before the call:

Litware.WikiWebService.set_path(window.spWebUrl+'/_vti_bin/Litware/WikiWebService.asmx');
Another thing that we’ve done in the SharePoint Ajax Toolkit is add a cache key, which is generated on each build. You can then append this cache key to script resources, or even output it as JavaScript to use on the client, to ensure that scripts and xslt resources are cached (and NOT cached) properly between builds. You really don’t want to have to tell your users to clear their cache after each load—that’s just embarrassing! The following code will generate an arbitrary string to append in a query for each url, which will cause the browser to cache the resource uniquely per build.
public readonly static string CacheKey = Assembly.GetExecutingAssembly().ManifestModule.ModuleVersionId.GetHashCode().ToString(CultureInfo.InvariantCulture);
You would then use this in code like this: this.XsltUrl = @"/_layouts/litware/rss.xslt?" + Utility.CacheKey;
We've also added many refinements to the SharePoint AJAX Toolkit at NewsGator in our product lifecycles, so be sure to grab the latest code from www.codeplex.com/sharepointajax.

Copying a SQL Server Database to Another Environment

A couple of weeks ago I was troubleshooting a performance problem with the variations feature in MOSS 2007 and I needed to copy the content database to another environment for further analysis and testing. An easy (an unobtrusive) way to "snapshot" a database and copy it to another environment is to create a backup with the COPY_ONLY option:
BACKUP DATABASE [WSS_Content]
TO DISK = N'H:\WSS_Content.bak'
WITH NOFORMAT, NOINIT
, NAME = N'WSS_Content-Full Database Backup'
, SKIP, NOREWIND, NOUNLOAD, STATS = 10
, COPY_ONLY
From SQL Server 2005 Books Online:
Taking a backup normally changes the database, in turn affecting other backups and how they are restored. Sometimes, however, a backup must be taken for a special purpose that should not affect the overall backup and restore procedures for the database.

A data backup is normally a base backup for one or more differential backups taken after it. Microsoft SQL Server 2005 introduces support for creating copy-only backups, which do not affect the normal sequence of backups. Therefore, unlike other backups, a copy-only backup does not impact the overall backup and restore procedures for the database.
In other words, by using the COPY_ONLY option I avoided screwing up the scheduled differential backups on the database.
However, there are a couple of issues with this approach:
You cannot specify the COPY_ONLY option through the UI in SQL Server Management Studio, but this is no big deal -- you can start by configuring most of the backup options using the UI, script the action to generate the corresponding SQL, and then add the COPY_ONLY option as shown above
You cannot restore a backup created using the COPY_ONLY option through the UI in SQL Server Management Studio; in the Restore Database dialog, when you select the From device option and then specify the backup file previously created with the COPY_ONLY option, no backup sets are displayed
The second problem was puzzling to me. After specifying my backup file, when I attempted to change to the Options page, I encountered the following error:
You must select a restore source.
When I first encountered this problem, I thought I had a corrupt backup file. However, by once again reverting to SQL instead of the UI, I was able to verify the backup was, in fact, valid:
RESTORE FILELISTONLY
FROM DISK = N'E:\NotBackedUp\Temp\WSS_Content.bak'
To restore from a COPY_ONLY backup, use a command similar to the following:
RESTORE DATABASE [WSS_Content_TEST]
FROM DISK = N'E:\NotBackedUp\Temp\WSS_Content.bak'
WITH FILE = 1
, MOVE N'WSS_Content'
TO N'E:\Microsoft SQL Server\MSSQL.1\MSSQL\Data\WSS_Content_TEST.MDF'
, MOVE N'WSS_Content_Log'
TO N'L:\Microsoft SQL Server\MSSQL.1\MSSQL\Data\WSS_Content_TEST_Log.LDF'
, NOUNLOAD, STATS = 10

How many ways to represent True and False

I was recently serializing data from both the database and user input, and it made me reflect on how many ways you can represent a boolean value as a literal string. For an English-language app (no globalization), here are several ways to represent a boolean:

TRUE / FALSE - converting from a literal string.
T / F - users who only want to enter the first character.
Yes / No - non-technical users who want "friendly" terms.
Y / N - again, users who want to only enter the first character.
1/0 - A bit, such as how SQL Server stores booleans.

And of course, the first three options can be case insensitive and trimmed white space (i.e. "tRUe" becomes "TRUE").

I had talked about using Convert.ToString to convert different objects to string, so I'd initially look at it's related method: Convert.ToBoolean. But one quickly sees that that won't handle all the cases (and with good reason).
The only literal string it takes from this group is "true"/"false". For example, it would handle converting the integer 1, but not the literal string "1".
Having a single function that just converts these different inputs to a boolean is a nice convenience.
Here's a sample:
public static bool ConvertToBoolean(string strVal)
{
if (string.IsNullOrEmpty(strVal))
return false;
strVal = strVal.ToUpper().Trim();
if (strVal == "TRUE" strVal == "T" strVal == "1" strVal == "YES" strVal == "Y") return true; else if (strVal == "FALSE" strVal == "F" strVal == "0" strVal == "NO" strVal == "N")
return false;
else
throw new ArgumentException("Cannot convert '" + strVal + "' to Boolean.");}

Adding an Event to a User Control (Code Sample)

I had talked about how to trigger an event from a UserControl.
This ability has many benefits, such as with refactoring. For example, suppose a UserControl is hosted on many different pages, and each page requires that the control have slightly different validation that incorporates values from the host page. One way to do this is to have the UserControl call a validation method on the host page.
Here's a code snippet you can download that shows how to have a UC call a method on its parent. The idea is to add an event member to the control, and hook it up with a delegate. (I had initially seen this technique from an article on MSDN several years ago).
This specific example has four files:
A UserControl - RecordNav.ascx and RecordNav.ascx.cs
A host page - HostRecordNav.aspx and HostRecordNav.aspx.cs
The UserControl contains an event "UpdateDate" and the host page adds a method to handle the event: RecordNav1_UpdateData.
RecordNav1.UpdateData += new AspxDemo_Events_RecorNav.UpdateDataEventHandler(RecordNav1_UpdateData);

The difference between array and ref array

Sometimes you'll want to pass an object (like an array) into a method, and have that method update the object. For an array, the common ways to do this are using the ref keyword, or modifying a member of an array. It's easy to confuse these two approaches because if you're just updating a member, they appear to have the same affect. However they're actually fundamentally different - passing in an array by ref lets you modify the array reference itself, such as changing it to a new array with a new length. The code snippet below illustrates this:


#region Normal Array [TestMethod]
public void TestMethod1()
{ //Normal array changes individual member
string[] astr = new string[]{"aaa"};
ModifyArray1(astr);
Assert.AreEqual("bbb", astr[0]);
} [TestMethod]

public void TestMethod2()
{ //Non-ref array doesn't change array itself
string[] astr = new string[] { "aaa" };
ModifyArray2(astr); Assert.AreEqual(1, astr.Length);
Assert.AreEqual("aaa", astr[0]);
}
public static void ModifyArray1(string[] astr)
{
astr[0] = "bbb";
}
public static void ModifyArray2(string[] astr)
{ astr = new string[] { "ccc", "ccc" };
} #endregion

#region Ref Array [TestMethod]
public void TestMethodRef1()
{
string[] astr = new string[] { "aaa" };
ModifyArrayRef1(ref astr);
Assert.AreEqual("bbb", astr[0]);
}
[TestMethod]
public void TestMethodRef2()
{ //Ref array can change the array itself, like giving it a new length
string[] astr = new string[] { "aaa" };
ModifyArrayRef2(ref astr);
Assert.AreEqual(2, astr.Length);
Assert.AreEqual("ccc", astr[0]);
}
public static void ModifyArrayRef1(ref string[] astr)
{
astr[0] = "bbb";
}
public static void ModifyArrayRef2(ref string[] astr)
{ astr = new string[] { "ccc", "ccc" };
} #endregion

Save the Grid Item

foreach(DataGridItem dgItem in dg_ProposedExp.Items)
{
Label Sno=(Label)dgItem.Cells[0].FindControl("Lbl_Sno");
Label Description =(Label)dgItem.Cells[1].FindControl("Lbl_Description");
Label Unit = (Label)dgItem.Cells[2].FindControl("Lbl_Unit");
Label Qty = (Label)dgItem.Cells[3].FindControl("Lbl_Qty");
Label Rate = (Label)dgItem.Cells[4].FindControl("Lbl_Rate");
Label Amount = (Label)dgItem.Cells[5].FindControl("Lbl_Amount");
PE_save="Insert into Proposed_Expenditure values('"+IE_ID+"','"+Sno.Text+"','"+Description.Text+"','"+Unit.Text+"','"+Qty.Text+"','"+Rate.Text+"','"+Amount.Text+"')";
SqlCommand sqlcmd_dg=new SqlCommand(PE_save,sqlcon_save);
sqlcmd_dg.ExecuteNonQuery();
}

Save Grid to the Data Table

private void DataSave(DataTable Dt)
{
if (!(ViewState["__Data"]==null))
{
ViewState["__Data"] = Dt;
}
else
{
ViewState.Add("__Data", Dt);
}
}
public bool DataExists()
{
if(!(ViewState["__Data"]==null))
return true;
else
return false;
}
private DataTable DataRetrieve()
{
DataTable Dt ;
if ((ViewState["__Data"] == null))
{
return datb;
}
else
{
Dt = ((DataTable)(ViewState["__Data"]));
return Dt;
}
}

get the value from dataset

int j=0;
while(j
{
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
//DateTimeFormatInfo dateTimeFormatInfo1 = new DateTimeFormatInfo();
string fromdate=dateTimeFormatInfo.GetAbbreviatedMonthName((Convert.ToDateTime(ds.Tables[0].Rows[j][0]).Month)).ToString();
string todate=dateTimeFormatInfo.GetAbbreviatedMonthName((Convert.ToDateTime(ds.Tables[0].Rows[j][1]).Month)).ToString();
string year=Convert.ToDateTime(ds.Tables[0].Rows[j][1].ToString()).Year.ToString();
string AppraisalPeriod=String.Concat(String.Concat (fromdate,todate),year);
string tempDistinctAppraisalRecord = AppraisalPeriod + "$" + ds.Tables[0].Rows[j][0].ToString() + "$" + ds.Tables[0].Rows[j][1].ToString();
distinctAppraisalRecord.Add(tempDistinctAppraisalRecord);
//Label3.Text=AppraisalPeriod;
appdroplist.Items.Add(AppraisalPeriod);
j++;
}
appdroplist.DataBind();

To Upload Documents in C#

if (Charge_To == "CISCO")
{
if((Upload.PostedFile != null)&& (Upload.PostedFile.ContentLength > 0))
{
strFile_Name=Upload.PostedFile.FileName;
strFile_Extn=System.IO.Path.GetExtension(strFile_Name);
File_Name = IE_ID + strFile_Extn;
upload_loc = Server.MapPath("Upload") + "...." + File_Name; //@"http://localhost/PurchaseOrder/Upload/";
Web_loc = ConfigurationSettings.AppSettings["FilePath"].ToString() + File_Name;
try
{
Upload.PostedFile.SaveAs(upload_loc);
//Response.Write("The File has been uploaded");
}
catch(Exception ex)
{
Response.Write("Error: " + ex.Message);
}
StringBuilder buildUpload=new StringBuilder();
buildUpload.Append("insert into PO_Upload values('"+IE_ID+"','"+File_Name+"','"+Requested_by+"','"+Requested_Date+"','"+Web_loc+"')");
SqlCommand sqlcmdUpload=new SqlCommand(buildUpload.ToString(),sqlcon_save);
sqlcmdUpload.ExecuteNonQuery();
}
}