Friday, May 28, 2010

Applying a SharePoint Designer Workflow to multiple Lists

When using SharePoint Designer to create a workflow you are required to bind the workflow to a particular list:

The problem is that you cannot from this interface bind the workflow to other lists. You might be tempted to use the “Save List as Template” option in the List’s settings, and then create a new list based on this template to create a list that uses the workflow. The problem is that the workflow is still bound to the list from which the new list is based, and an error will probably be generated whenever you try to start an instance of the workflow – the steps will try to reference items etc. in the original list. In SharePoint Designer you can expand out the files associated with a workflow:
The “.xoml.wfconfig.xml” file contains information on the list the workflow is bound to using the List’s ID (a GUID): association XMLtag listid = 32bit GUID tasklistid=32bit GUID startmanually="true" The file “.xoml.rules” contains the ‘conditions’ you program for the workflow and the “.xoml” file contains the ‘actions’. The “.aspx” form is displayed when the workflow is started manually. To re-use a workflow in another list: Create a new workflow on the new list. Create at least one step, one condition and one action in this workflow. This ensures that the files shown above are created and they will be replaced by the next operations. From the original workflow open the .xoml file as XML and copy the entire contents to the clipboard. Open the .xoml file for the new workflow and replace the entire contents with the copy from (3). Repeat this operation for the xoml.rules file. Double click the .xoml file for the new workflow to open the workflow in the Workflow Designer and click Check Workflow to verify no errors and then click Finish to ensure the workflow is saved. Also, Once done with all the changes make sure the lookup items doesnt point to existing list. Just double click on it and will point to current list. http://vspug.com/agoodwin/2008/08/11/no-options-to-save-workflows-as-templates-in-sharepoint-designer/

Thursday, April 15, 2010

Delete ContentType from a Library

This is a Console Application. Build it and .exe file is generated. Can move to other environments with running .exe from where it is added. ChangeContentType.exe http://YourBox/ TempLib 1stContentType(Form) NewContentType DestinationLibrary static void Main(string[] args) { try { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(args[0])) //"http://YourBox/")) { using (SPWeb web = site.RootWeb) { //args[1] = TempLib //Create a temporary Library, where we move all the Destination Library list items. web.Lists.Add(args[1], args[1], SPListTemplateType.DocumentLibrary); SPList destLib = web.Lists[args[1]]; SPList list = web.Lists[args[1]]; //"DestinationLib"]; //Move all the list items from "DestinationLib" to "TempLib". int count = list.Items.Count; for (int j = count; j >0; j--) { SPFile file = list.Items[j-1].File; file.MoveTo(web.Url + "/" + args[1]+ "/" + file.Name); } try { //Remove "Form" 1st Content Type. args[2]="Form" SPContentType cTypeToBeRemovedForm = list.ContentTypes[args[2]]; //"1stContentType"]; list.ContentTypes.Delete(cTypeToBeRemovedForm.Id); //Remove "SecondContentType" Content Type. args[3] = SecondContentType SPContentType cTypeToBeRemoved = list.ContentTypes[args[3]]; //"SecondContentType"]; list.ContentTypes.Delete(cTypeToBeRemoved.Id); //Add "NewContentType" Content Type from the web. SPContentType cTypeToBeAdded = web.ContentTypes[args[3]]; //"ContentTypefromweb"; list.ContentTypes.Add(cTypeToBeAdded); list.Update(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Move all the list items from "TempLib" to "DestinationLib". // args[4]= DestinationLib int tempCount = destLib.Items.Count; for (int j = count; j > 0; j--) { SPFile file = destLib.Items[j-1].File; file.MoveTo(web.Url + "/" + args[4] + "/" + file.Name); } web.Lists[args[1]].Delete(); } } }); } catch (Exception e) { Console.WriteLine("Exception Message - " + e.Message + "\nInner Exception - " + e.InnerException + "\nStack Trace - " + e.StackTrace); } }

Monday, March 22, 2010

Code Snippets

Get list Items: /// Gets a collection of list items that match the query from the specified list, regardless of the permissions of the current user /// The server-relative path to the list /// The CAML query that has to be run against the list /// An SPListItemCollection object that represents the resulting list items public static SPListItemCollection GetSecuredListItems(string ListServerRelativePath, string CamlQuery) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); SPListItemCollection results = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList(ListServerRelativePath); SPQuery query = new SPQuery(); query.Query = CamlQuery; results = list.GetItems(query); } } }); return results; } Update List Item: /// Updates a single item for a single field on a list, even if the current user doesn't have the access /// The server-relative path to the list /// The internal ID of the item to be updated /// The display name of the field to be updated /// The new value that has to be applied for the field /// The SPListItem object that contains the list item that was updated public static SPListItem UpdateSecuredListItem(string ListServerRelativePath, string ID, string FieldName, string Value) { if (string.IsNullOrEmpty(ListServerRelativePath)) throw new ArgumentNullException("The server-relative path to the list is required for this function"); int id; if (!int.TryParse(ID, out id)) throw new ArgumentException("The ID specified is not valid (ID = " + ID + ")."); SPListItem result = null; string listAbsoluteURL = SPContext.Current.Site.MakeFullUrl(ListServerRelativePath); SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(listAbsoluteURL)) { using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; SPList list = web.GetList(ListServerRelativePath); SPField field = list.Fields[FieldName]; if (field == null) throw new ArgumentException("The FieldName specified (" + FieldName + ") is not valid for the List (" + list.Title + ")."); result = list.GetItemById(id); if (result != null) result[FieldName] = Value; else throw new ArgumentException("There is no listitem with the specified ID (ID = " + ID + ")."); result.Update(); web.AllowUnsafeUpdates = false; } } }); return result; } Delete List Permissions namespace DeleteListPermissions { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("\n\n Invocation: DeleteListPermissions "); return; } //Get SPWeb object SPSite Site = new SPSite(args[0]); //e.g., "http://myserver/mysite" SPWeb Web = Site.OpenWeb(); //Get SPListItem SPList List = Web.Lists[args[1]]; //e.g., "Announcements" Console.WriteLine("\n\nList " + args[1] + " found-- Starting Permission Deletion"); //Check for permission inheritance, and break if necessary if (!List.HasUniqueRoleAssignments) { List.BreakRoleInheritance(false); //pass true to copy role assignments from parent, false to start from scratch } List.Update(); Console.WriteLine("Done...."); } } }

Wednesday, March 17, 2010

STSADM Commands

Retract Solution: stsadm -o retractsolution -n YourWSP.wsp Remove Solution: stsadm -o deletesolution -n YourWSP.wsp Add Solution: stsadm -o addsolution -f YourWSP.wsp Deploy Solution: stsadm -o deploysolution -n YourWSP.wsp -allowgacdeployment -immediate at the End do: stsadm -o execadmsvcjobs iisreset pause

Monday, March 15, 2010

TimerJob, Feature Receiver, Feature and Batch Files to Install Timer Job

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace PubFormLibraryTimer {
public class FormLibraryTimerJob : SPJobDefinition
{
private const string Event_Source = "FormLibraryTimerJob";

 public FormLibraryTimerJob () : base() { }
  public FormLibraryTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType) : base (jobName, service, server, targetType) { }
public FormLibraryTimerJob(string jobName, SPWebApplication webApplication) : base (jobName, webApplication, null, SPJobLockType.ContentDatabase)
{ this.Title = jobName; }
public override void Execute(Guid targetInstanceId)
{
            DateTime fromTime = DateTime.Now.AddMinutes(-5);
DateTime toTime = DateTime.Now;
SPWebApplication webApplication = this.Parent as SPWebApplication;
SPContentDatabase contentDb = webApplication.ContentDatabases[targetInstanceId];
SPList formsLibraryList = contentDb.Sites[0].RootWeb.Lists["YourFormLibrary"];
            SPQuery oQuery = new SPQuery();
            oQuery.Query = "" + toTime + "" + "" + fromTime + "";
SPListItemCollection collListItems = formsLibraryList.GetItems(oQuery);
this.LogEventMessage(collListItems.Count);
}

  private void LogEventMessage(int count)
{
if (!EventLog.SourceExists(Event_Source))
{ EventLog.CreateEventSource(Event_Source, "Application"); }
EventLog.WriteEntry(Event_Source, "Your Form Library Modified Forms Count In Last 5 mins - " + count.ToString(), EventLogEntryType.Information);
}
}
}






Feature Receiver:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace YourFormLibraryTimer
{

public class FormsLibraryTimerJobFeatureReceiver : SPFeatureReceiver
{
private const string LOGGER_JOB_NAME = "FormLibraryTimerJob"; public override void FeatureInstalled (SPFeatureReceiverProperties properties) { } public override void FeatureUninstalling (SPFeatureReceiverProperties properties) { } public override void FeatureActivated (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } FormLibraryTimerJob loggerJob = new FormLibraryTimerJob(LOGGER_JOB_NAME, site.WebApplication); SPMinuteSchedule schedule = new SPMinuteSchedule(); schedule.BeginSecond = 0; schedule.EndSecond = 59; schedule.Interval = 5; loggerJob.Schedule = schedule; loggerJob.Update(); } public override void FeatureDeactivating (SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) { if (job.Name == LOGGER_JOB_NAME) job.Delete(); } } } } Feature: ?xml version="1.0" encoding="utf-8" ? Feature Id="{DD1D417C-746B-4793-BA4E-A95F156E1E30}" Title="Form Library Timer Job" Description="Installs Form Library Timer Job" Version="1.0.0.0" Scope="Site" ReceiverAssembly="YourFormLibraryTimer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=68d32dec24dfb1a9"ReceiverClass="YourFormLibraryTimer.FormsLibraryTimerJobFeatureReceiver" xmlns="http://schemas.microsoft.com/sharepoint/" / Installing Timer Job in Batch Files: @SET TEMPLATEDIR="c:\program files\common files\microsoft shared\web server extensions\12\Template" @SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm" @SET GACUTIL="C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\gacutil.exe" Echo Installing PubFormLibraryTimer.dll in GAC %GACUTIL% -if bin\debug\YourFormLibraryTimer.dll Echo Copying files to TEMPLATE directory xcopy /e /y TEMPLATE\* %TEMPLATEDIR% %STSADM% -o installfeature -filename FormLibraryTimerJob\feature.xml -force %STSADM% -o activatefeature -filename FormLibraryTimerJob\feature.xml -force -url http://localhost:91IISRESET

Thursday, March 4, 2010

Adding Columns to a List Programatically

Add Columns / Fields Programmatically to a SharePoint List You can think of a SharePoint List somewhat similar to a table present within a Database. As tables consist of different columns, a SharePoint List also comprises of different columns / fields and these fields can indeed have different attributes associated to it (like "Required field check", "Max Length", "Display Formats", etc). We can use SharePoint API to create these fields and associate the corresponding attributes programmatically within an existing List. Provided below is a code snippet in C#.Net describing the same. using (SPSite oSPsite = new SPSite("http://Web-URL")) { oSPsite.AllowUnsafeUpdates = true; using (SPWeb oSPWeb = oSPsite.OpenWeb()) { oSPWeb.AllowUnsafeUpdates = true; /* get the SPList object by list name*/ SPList lst = oSPWeb.Lists["EmpList"]; /* create a Numeric field for EmpID */ SPFieldNumber fldEmpID = (SPFieldNumber)lst.Fields.CreateNewField( SPFieldType.Number.ToString(), "EmpID"); fldEmpID.Required = true; fldEmpID.DisplayFormat = SPNumberFormatTypes.NoDecimal; /* create a Text field for Name */ SPFieldText fldName = (SPFieldText)lst.Fields.CreateNewField( SPFieldType.Text.ToString(), "Name"); fldName.Required = true; fldName.MaxLength = 50; /* create a Date field for Dob*/ SPFieldDateTime fldDob = (SPFieldDateTime)lst.Fields.CreateNewField( SPFieldType.DateTime.ToString(), "Dob"); fldDob.DisplayFormat = SPDateTimeFieldFormatType.DateOnly; /* create a Currency field for Salary */ SPFieldCurrency fldSal = (SPFieldCurrency)lst.Fields.CreateNewField( SPFieldType.Currency.ToString(), "Salary"); fldSal.Currency = SPCurrencyFieldFormats.UnitedStates; fldSal.DisplayFormat = SPNumberFormatTypes.TwoDecimals; /* add the new fields to the list */ lst.Fields.Add(fldEmpID); lst.Fields.Add(fldName); lst.Fields.Add(fldDob); lst.Fields.Add(fldSal); /* finally update list */ lst.Update(); oSPWeb.AllowUnsafeUpdates = false; } oSPsite.AllowUnsafeUpdates = false; } Adding Hyperlink Column to a SharePoint List Example 1: Set the url field of a link Use the SPFieldUrlValue class to create an object that holds the url to link to, and the title to display: SPList list = web.Lists["Links"]; SPListItem newLink = list.Items.Add(); SPFieldUrlValue value = new SPFieldUrlValue(); value.Description = "Click Me"; value.Url = "http://www.microsoft.com/sharepoint"; newLink["URLColumn"] = value; //URLColumn that we have added on the list newLink.Update(); Example 2: Get the url field of a link Use the SPFieldUrlValue class to create an object that gets the url and description: SPList list = web.Lists["Links"]; SPListItem existingLink = list.Items[0]; SPFieldUrlValue value = new SPFieldUrlValue(existingLink["URL"].ToString()); string linkTitle = value.Description; string linkURL = value.Url; Example 3: Add Choice Column to a List or Document Library programatically Considering lstCustomList is your list object and you have set AllowUnsafeUpdate() to true for the web object. We are adding two choices in the choice column. First we will add choice column itself to the list and then we will add the choices in that column and update the field. The main point to taken in to consideration is that it is SPFieldChoice not the SPField. lstCustomList.Fields.Add("ABC", SPFieldType.Choice, false); lstCustomList.Update(); SPFieldChoice objChoiceCol = (SPFieldChoice)lstCustomList.Fields["ABC"]; string[] strdata = new string[2]; strdata[0] = "Open"; strdata[1] = "Close"; objChoiceCol.Choices.Add(strdata[0]); objChoiceCol.Choices.Add(strdata[1]); objChoiceCol.Update(); lstCustomList.Update();

Wednesday, March 3, 2010

Return Items from a List

(1)The following example returns all the items for a specified Events list. It assumes the existence of a text box that can be used to type the name of an Events list. SPWeb mySite = SPContext.Current.Web; SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items; for (int i=0;i"); } (2)You can also use one of the GetItems methods of the SPList class to return a subset of items from a list. The following example returns only Title column values where the Stock column value surpasses 100. SPWeb mySite = SPContext.Current.Web; SPList list = mySite.Lists["Books"]; SPQuery query = new SPQuery(); query.Query = "100"; SPListItemCollection myItems = list.GetItems(query); foreach (SPListItem item in myItems) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); } (3)Cross-List Queries You can perform cross-list queries to query more efficiently for data across multiple Web sites. The following example uses the SPSiteDataQuery class to define a query, and then uses the GetSiteData method to return items where the Status column equals "Completed". SPWeb webSite = SPContext.Current.Web; SPSiteDataQuery query = new SPSiteDataQuery(); query.Lists = ""; query.Query = "" + "Completed"; System.Data.DataTable items = webSite.GetSiteData(query); foreach (System.Data.DataRow item in items) { Response.Write(SPEncode.HtmlEncode(item["Title"].ToString()) + " "); }

Wednesday, February 24, 2010

What's New in Infopath 2010

Link Referred: http://blogs.msdn.com/infopath/archive/2009/07/15/what-s-new-in-infopath-2010.aspx Microsoft InfoPath 2010 makes it easier than ever to design electronic forms. InfoPath now includes the Office Fluent UI and allows the creation of powerful, interactive forms, without having to write any code. With a few clicks, Office users can customize SharePoint list forms, add custom layouts and rules to validate the data, and take them offline in SharePoint Workspace. IT professionals can create custom forms for document workflows and Office Business Applications that include managed code, digital signatures and that connect to line of business data. In InfoPath 2010, we’ve made some big investments to make it much easier to build rich forms-based applications on top of the SharePoint Server 2010 platform. Quickly Design Forms with Easy-to-Use Tools New features to help you quickly and easily create forms include our new Fluent UI, pre-built layout sections, out-of-the-box rules, improved rules management, and varied styles. The New tab in the Designer Backstage presents you with the available form templates that you can choose from. Most templates start you off with a default layout table. Stay tuned for more details on our new and improved form design features! Layout your Forms Using Pre-built Page and Section Layouts Laying out your form and making it look more attractive is now easier than ever. Insert one of our pre-built page layouts to give your form structure. Then, insert some section layouts into the page layout to start building your form. Page and Section Layouts in InfoPath Designer:
New and Improved Controls We’ve added some new controls and narrowed the feature gap between client and browser forms, ensuring a more consistent form filling experience for all our users.
New controls in InfoPath 2010 include: Picture buttons – Instead of the default gray button, use any image as a button in your form. Hyperlink capabilities –Allow users to insert their own hyperlinks when filling out forms. Date and time picker – Allow users to insert dates and times in their forms Person/Group pickers – Updated! This is now a first class control and is included by default in the Controls gallery. Signature Line (Editor Only) – Allow users to digitally sign a form Controls and functionality that are now supported in browser forms include: Bulleted, numbered, and plain lists, multiple selection list boxes, Combo boxes, Choice group and sections, and Filtering functionality. Add Rules to your Forms With our new out-of-the-box rules (or quick rules) and improved rules management UI, you can easily add rules to validate data, format your form, or perform other actions with just a couple of clicks, and without any code. Quick Rules in InfoPath Designer: Publish Forms Quickly Our new “quick” publish functionality allows you to publish forms in a single click (no more clicking through the Publishing Wizard every time you want to make an update to your forms!) Create Forms for SharePoint Lists Using InfoPath, you can now extend and enhance the forms used for creating, editing and viewing items in a SharePoint list. In a browser, simply navigate to a SharePoint list, and on the SharePoint Ribbon under List Tools, choose the Customize Form option. This will automatically generate a form which looks very similar to the default out-of-the-box SharePoint list form. You can then customize and enhance this form by modifying the layout, creating additional views or pages, and adding rules to validate your data, show or hide sections of the form or set a fields value (to name just a few of the options). Example of Customized SharePoint List Form: Stay tuned for more details on SharePoint List Customization! We recommend using a form associated with a SharePoint list when possible. This provides the most straightforward design and form management experience. However, there are more complex scenarios where using a form associated with a form library is preferred e.g. if your form has a complex schema or if you need to add code to your form. Create SharePoint Applications With InfoPath 2010, SharePoint Server 2010, and SharePoint Designer 2010, you can easily create powerful team, departmental or enterprise applications on top of SharePoint Server. Form-based applications: InfoPath forms can be integrated with components such as workflow, reporting, and custom Web pages to create rich form-based applications. Document Workflows: InfoPath can be used to design custom workflow initiation and task forms that drive document management processes. Business Connectivity Services: Integrating with BCS, it is straightforward to design InfoPath forms that create, read, update, and delete business data from a back-end system. Stay tuned for more details on creating SharePoint applications! Create Mashups using the InfoPath Form Web Part Now, without writing a single line of code, you can host your InfoPath browser forms in Web pages by simply adding the InfoPath Form Web Part to a Web Part page. You can also connect it to other Web Parts on the page to send or receive data. Stay tuned for more details on the InfoPath Form Web Part! Build Forms with Code Using Visual Studio Tools for Applications, you can add managed code to your forms. Stay tuned for more details on programming with InfoPath! InfoPath Editor The InfoPath 2010 Editor Fluent user interface provides a much improved, simpler user experience for filling out forms. Form opened in InfoPath 2010 Editor: SharePoint Workspace InfoPath 2010 is the forms technology used by SharePoint Workspace 2010 for creating and filling out forms. InfoPath Forms Services Administration and Management We have invested in many improvements to make it easier to manage your InfoPath Forms Services as a component of Microsoft SharePoint Server 2010.

Tuesday, February 23, 2010

Batch Files to Retract, Deploy WSPs

All-Retr-Depl-Sol @Echo on @Echo Installing all solutions @Echo. @Echo. for %%i in (*.wsp) do call Retr-Depl-Sol %%i for %%i in (*.wsp) do call Feature-Deac-Act %%~ni Retr-Depl-Sol @Echo on @Echo Retracting Solution %1 stsadm -o retractsolution -name %1 -immediate stsadm -o execadmsvcjobs @Echo Deleting Solution %1 stsadm -o deletesolution -name %1 @Echo Adding Solution %1 stsadm -o addsolution -filename %1 @Echo Deploying Solution %1 stsadm -o deploysolution -name %1 -immediate -allowgac -force stsadm -o execadmsvcjobs stsadm -o execadmsvcjobs Feature-Deac-Act @echo On stsadm -o deactivatefeature -filename %1\feature.xml -url http://Server/ -force stsadm -o activatefeature -filename %1\feature.xml -url http://Server/ -force iisreset popd

Monday, February 22, 2010

Count Forms in each List in a Document Library

Code Writes output a Directory with a file name in C:\\ public string ListCount() { string logFileName = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString(); logFileName = logFileName.Replace("/", "-"); logFileName = logFileName.Replace(":", "-"); logFileName = "C:\\Document Library Items Count - " + logFileName + ".csv"; SPSite mySite = new SPSite(SPContext.Current.Site.Url); SPWeb myWeb = mySite.OpenWeb(); StringBuilder tempTitle = new StringBuilder(""); StringBuilder tempItemCount = new StringBuilder(""); foreach (SPList list in myWeb.Lists) { string BTemplate = list.BaseTemplate.ToString(); if (list.BaseType == SPBaseType.DocumentLibrary && BTemplate == "XMLForm") { int FolderCount = list.Folders.Count; tempTitle.Append(list.Title + ","); tempTitle.Append("\t"); tempTitle.Append((list.ItemCount - FolderCount)); tempTitle.AppendLine(); if (FolderCount != 0) { list.RootFolder.SubFolders.Count.ToString(); foreach (SPListItem myList in list.Folders) { string FolderName = myList.DisplayName.ToUpper(); tempTitle.Append(" ( Folder: " + FolderName + " in " + myList.Folder.ParentFolder.Name + " )"); SPFolder folder = myWeb.GetFolder(myList.DisplayName); string folderItemsCount = myList.Folder.Files.Count.ToString(); tempTitle.Append(" Number of Forms : " + folderItemsCount); tempTitle.AppendLine(); } } } } StreamWriter logWriter = File.CreateText(logFileName); logWriter.WriteLine(""); logWriter.WriteLine("DOCUMENT LIBRARY NAME" + "," + "NUMBER OF FORMS"); logWriter.WriteLine(""); logWriter.WriteLine(tempTitle); logWriter.Close(); return (tempTitle.ToString()); }

Create New Sharepoint Web Service

The Post referred http://msdn.microsoft.com/en-us/library/ms464040.aspx (1)Basic Steps for Creating a Web Service Create an ASP.NET Web service in Microsoft Visual Studio 2005. Create a class library within the Web service that defines the programming logic for the Web service. Generate and edit a static discovery file and a Web Services Description Language (WSDL) file. Deploy the Web service files to the _vti_bin directory. Create a client application to consume the Web service.

(2)To create an ASP.NET Web service

a)In Visual Studio, click File, point to New, and then select Web Site. b)In the Templates box of the New Web Site dialog box, select ASP.NET Web Service, select File System in the Location box, select a programming language and location for the project, and then click OK.

C) Within the new Web service solution, create a separate class library project to contain the Web service logic.

[ To create the project, click File, point to New, and then select Project.] In the New Project dialog box, select a language in the Project types box, select Class Library in the Templates box, provide a name and location for the project, select Add to Solution in the Solution box, and then click OK.

D)Add a reference to the System.Web.Services namespace in the class library project. And also Microsoft.SharePoint

E)Replace the default class file in the class library project with the default service class file that Visual Studio provides in the App_Code folder of the Web service. [To replace the class file with the service class file ] In Solution Explorer, drag Service.cs or Service.vb to the top node in the class library project. Delete the Class1.cs or Class1.vb file, and also delete the Service.cs or Service.vb file that remains in the App_Code folder.

F)Create a strong name for the class library: In Solution Explorer, right-click the class library project, and then click Properties. In the Properties dialog box, click Signing, select Sign the assembly, and then select in the Choose a strong name key file list. In the Create Strong Name Key dialog box, provide a file name for the key, clear the Protect my key file with a password check box, and then click OK.

G) To build only the class library project, right-click the project in Solution Explorer, and then click Build.

H) To add your assembly to the global assembly cache (GAC), you can either drag the assembly into the % windows%\assembly directory using 2 instances of Windows Explorer, or use the command line utility gacutil.exe that is installed with the Microsoft .NET Framework SDK 2.0. To use gacutil.exe to copy the class library DLL into the GAC To open the Visual Studio command prompt, click Start, point to All Programs, point to Microsoft Visual Studio 2005, point to Visual Studio Tools, and click Visual Studio 2005 Command Prompt. At the command prompt type a command in the following form, and press ENTER: gacutil.exe -if "".

I) Now you are ready to modify the assembly information in the default Service.asmx file of the Web service with information for the DLL from the GAC. To get information from the GAC, open the %windows% \assembly directory in Windows Explorer, right-click your assembly, and click Properties.

J) To open Service.asmx in Solution Explorer, right-click the file and click Open. Remove the CodeBehind attribute from the page directive in Service.asmx, and modify the contents of the Class attribute so that the directive matches the following format, where the assembly name "NewAssembly" and the public key token are values specified in the Properties dialog box that you opened in step 10: <%@ WebService Language="C#" Class="Service,NewAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8f2dca3c0f2d0131" %>

K)Rename your .asmx file appropriately, and then save your changes.

3)Generate Static discovery and WSDL files.

In Windows Explorer, copy the .asmx file of your Web service to \\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS.

4)Reset IIS for the DLLs in assembly to take effect.

5)Type in http://Server/_layouts/Service.asmx for the Service and its methods in it.

Tuesday, June 26, 2007

Infopath Trips and Tricks

Phone Number (Format ): 1. Add a rule to your textbox control with the following conditions (make sure to select "and" operator): a. field "does not match pattern" Phone number b. the expression: string-length(translate(., "()- ", "")) = 10 c. the expression: string-length(translate(., "()- 0123456789", "")) = 0 2. Add action to the rule: a. Set a field's value b. Select your textbox field c. Insert formula for the value (click the fx button): concat("(", substring(translate(., "()- ", ""), 1, 3), ") ", substring(translate(., "()- ", ""), 4, 3), "-", substring(translate(., "()- ", ""), 7, 4)) Email Address Data Validation ( Infopath ) Email Address doesnot match pattern: ( custom pattern ) ([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?) ScreenTip & Validation message: Please Enter a Valid Email ID : abc@xxxx.com Date Validation : Enter a Date where past date doesn’t exceed 5 weeks There is the addDays() function in Infopath 2007. To use this in data validation, right click on the field you wish to validate, select Data Validation and select Add to open a new condition. Leave the first box set to your field, set the second box to is less than or equal to, and in the third box, select Use a formula. In the formula editor, insert the function addDays. The first argument should be your date field and the second should be -35 (to subtract 5 weeks): addDays(today(), -35) Add your screen tip as appropriate. If you want your date between a range, you can add a second condition. Should not be able to Enter a Future Date : Field less than or equal to today(), Retrieving values into expression box based on People picker control: (Like Email & Phone Here..) Limit amount of repeating table rows that can be created ( For Ex: SampleXSN Form make it 18) Steps: (1) Save your form ( SampleXSN) as source files. (2) Open the schema with a text editor (if you created it yourself, starting with a blank form in IP, it will be named myschema.xsd) and find the element bound to your repeating table. (3) You'll see the 'maxOccurs' is set to unbounded. Change that to 18 ( here ). (4) Save the file myschema.xsd. (5) Open the manifest or form file and publish it. (6) With this approach if they try to exceed the limit ( say 18 here ) End User will get a message “New item could not be inserted. In this Form only a max of 18 items allowed.” Users will still be able to add and delete rows in repeating table till they try to reach the limit set ( 18 here ). Note: After you saved as source files, close the Form if the Form is still open, it will be using the Form files like the schema and the schema which you open will be read only. Auto Numbering Repeating Section : (Ex: repeating section 1, repeating section 2…..) Use the function : count(preceding-sibling::*/ResolvedYes) + 1 ProblemOccurenceDetail is the Repeating Section: ResolvedYes is a section inside the repeating section. Where ResolvedYes is any field/group in the Repeating Section. Field16 is a test field on which we add the Logic Dynamically controlling the number of rows in a Repeating Table: Tip: Use the Count function. Count = Count(RepeatingTable) Under Conditional Formatting in a RepeatingTable If Count >= Condition(Dynamically set ) then Don’t allow the Users to add or delete rows. A value in the form may be used to specify the file name. If you know the value in the form that specifies the file name, revise it and try again. Otherwise, contact the author of the form template You need to make the changes in the share point submit data connection. The following steps will walk you through 1. Open form in Design Form 2. Go to Tools in menu bar 3. Select data connection 4. Select the Dta connection name that you had used to submit the form to Share Point 5. Click on 'Modify' button 6. Check 'Allow overwrites if file exists' check box 7. click on 'Next' button 8. Click on 'Finish' button 9. Click on 'Close' button 10. Save the form and republish the form to Your form Library Validating a group of checkboxes If the fields for your checkboxes Booleans? If so, you can set them so they have a value of 0 if cleared and 1 if checked. You can add another field and set its default value to the sum of the fields associated with your checkboxes (you don't have to connect it to your control or show it on your form anywhere). Then, for each of your checkboxes, your data validation condition can be if the field with the sum of the values is equal to zero, show an error..... Multiple DataConnection Submits ( EmailSubmit, DC Submit ) : Form has been closed. On the Button(Rules) (1) Switch to Email Submit View & Submit Email (2) Also submit to Form Library (3) Switch to View which you are initially on ( This is the View where your button is ) (4) Close the Form : No Prompt & It Works... What happens is it might be losing the link to URL to what you are supposed to go when you switch to Email View. When you change views back to original view you are on...It regains its URL and closes the Form with redirect URL. Also, Form has been closed error also occurs if any data-connection query fetch results in error : Ex: cannot find List.