Thursday, December 30, 2010

How to replace required words in Word document Template with asp.net webapplication ?

Requirement:To change some worde of a word document template and save it at my document of the user.
By this application you can change the word application by selecting the gridview and the document template from the dropdownlist.


using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office;
using Microsoft.Office.Interop.Word;
using System.IO;
using System.Data;
using System.Data.SqlClient;
namespace ProjectForReplaceWord
{
   public partial class _Default : System.Web.UI.Page
   {
       Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
       Microsoft.Office.Interop.Word.Document wordDoc = null;
       string Vendor = string.Empty;
       string TenderNo = string.Empty;
       string TenderDatedOn = string.Empty;
       //int ddlindex = string.Empty;
       string VendorAddress = string.Empty;
       string ProductType = string.Empty;
       string DueOn = string.Empty;
       string ValidFrom = string.Empty;
       string ValidUpTo = string.Empty;
       string SenderName = string.Empty;
       string Designation = string.Empty;
       string ToAddress = string.Empty;
       string Subject = string.Empty;

       protected void Page_Load(object sender, EventArgs e)
       {
           if (!IsPostBack)
           {

               string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=SSPI";//window aunthentication
               SqlConnection cnn = new SqlConnection(connectionString);
               SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM [DataBaseName].[dbo].[TableName]", cnn);
               DataSet ds = new DataSet();
               da.Fill(ds);
               GridView1.DataSource = ds;
               GridView1.DataBind();
               ddlTemplate.Items.Insert(0, "-Select-");
               ddlTemplate.Items.Add("AuthorisationLetter");
               ddlTemplate.Items.Add("Revised Text_Exclusive Dist agreement");
               ddlTemplate.Items.Add("SampleDOc");
               ddlTemplate.DataBind();

           }
       }
       protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
       {
           GridViewRow row = GridView1.SelectedRow;
           int index = row.RowIndex;
           Vendor = row.Cells[1].Text;
            TenderNo = row.Cells[2].Text;//Label4.Text;
          TenderDatedOn = row.Cells[3].Text;
           int ddlindex=ddlTemplate.SelectedIndex;
           VendorAddress = row.Cells[4].Text;
           ProductType = row.Cells[5].Text;
           DueOn = row.Cells[6].Text;
           ValidFrom = row.Cells[7].Text;
           ValidUpTo = row.Cells[8].Text;
           SenderName = row.Cells[9].Text;
           Designation = row.Cells[10].Text;
           ToAddress = row.Cells[11].Text;
           Subject = row.Cells[12].Text;
           string TemplateDoc = ddlTemplate.SelectedItem.ToString();
         string  NewDoc = TemplateDoc+ "_"+Vendor +Designation+ ".docx";


         CreateWordDocument(Server.MapPath("~/DocumentFolderName/" + TemplateDoc + ".docx"), NewDoc);



       }

       protected void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApplication, object findText, object replaceWithText)
       {
           object matchCase = true;
           object matchwholeWords = true;
           object matchWildCards = false;
           object matchSoundlike = false;
           object nmatchAllWordForms = false;
           object forward = true;
           object format = false;
           object matchKashida = false;
           object matchDiacritics = false;
           object matchAlefHamza = false;


           object matchControl = false;
           object readOnly = false;
           object visible = true;
           object replace = 2;
           object wrap = 1;
           wordApplication.Selection.Find.Execute(ref findText, ref matchCase, ref matchwholeWords, ref matchWildCards, ref matchSoundlike, ref nmatchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
       }
       private void CreateWordDocument(object filename, object SaveAs)
       {
           object missing = System.Reflection.Missing.Value;


           if (File.Exists((string)filename))
           {
               DateTime today = DateTime.Now;
               object readOnly = false;
               object isVisible = false;
               wordApp.Visible = false;
               wordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing,
                   ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
               wordDoc.Activate();
               this.FindAndReplace(wordApp, "<Subject>", Subject);
               this.FindAndReplace(wordApp, "<tender no>", TenderNo);
               this.FindAndReplace(wordApp, "<tender Date>", TenderDatedOn);
               this.FindAndReplace(wordApp, "<due date>", DueOn);
               this.FindAndReplace(wordApp, "<Vendor>", Vendor);
               this.FindAndReplace(wordApp, "<Start Date> ", ValidFrom);
               this.FindAndReplace(wordApp, "<End Date>", ValidUpTo);
               this.FindAndReplace(wordApp, "<Distributor Address>", VendorAddress);
               this.FindAndReplace(wordApp, "<Product Type> ",ProductType);
               this.FindAndReplace(wordApp, "<Sender Name>", SenderName);
               this.FindAndReplace(wordApp, "<Designation>", Designation);
               this.FindAndReplace(wordApp, "<XYZ Private Limited>", Vendor);

               wordDoc.SaveAs(ref SaveAs, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                 ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
             //see MyDocument of the User.

 //wordDoc.Close(ref missing, ref missing, ref missing);

               //   wordDoc.Save();

           }
           else
           {
            
               TextTemplate.Text = "File is not exist";//label1.text="File not exist";
           }


First document say :AuthorisationLetter.docx
Sub    :  <Subject>.
Ref      : Tender No. <tender no>Dated<tender Date>Due on<due date>
.
           

Dear Sir

1.         We ABC Pvt. Ltd, hereby confirm that M/s. <Vendor>, a company having its principal place of business at Distributor Address is an authorized independent distributor of our company, in which capacity it may bid, negotiate and conclude the contract with you for ProductType traded by us.

2.         No company or firm or individual, other than M/s. <Vendor>,  are entitled to bid, negotiate and conclude the contract in regard to this business in such a capacity for the specific Tender.

3.         This distribution arrangement is valid from <Start Date>to<End Date>.


Thanking you,

Yours faithfully
<SenderName>
<Designation>
ABC Private Limited

 Second Document say:Revised Text_Exclusive Dist agreement.docx:

EXCLUSIVE DISTRIBUTION AGREEMENT         Between   <XYZ Private Limited>  And ABC Private Limited     

Here, the words to be changed is in< >.

Note:I got the code from one url at internet and as per that I wrote this new approach.



Thanks & Regards
Pradeep
Bangalore





















Wednesday, December 29, 2010

How to access webservice through SharePoint workflow?How to update database by adding a list item in a sharepoint site with the help of webservice?

Hi,
This my first Blog .Here,I tried to update database by a workflow with help of webservice.
1.How to create a webservice to update a database?
2. How to access a webservice url by workflow?
1.How to create a webservice to update a database?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.UI.MobileControls; 
using System.Data; 
using System.Data.SqlClient; 

namespace ConnnecttoDBWS 
{ 
/// <summary> 
/// Summary description for Service1 
/// </summary> 
[WebService(Namespace = " http://tempuri.org/ ")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService] 
public class Service1 : System.Web.Services.WebService 
{

[WebMethod] 
public List<string> UpdateDB(string FirstName, string LastName, string MailId) 
{ 

List<string> list = new List<string> { FirstName, LastName, MailId }; 

string connectionString = null; 
SqlConnection cnn; 
connectionString = "Data Source=ServerName;Initial Catalog=MyTestDB;Integrated Security=SSPI";  
cnn = new SqlConnection(connectionString); 

if (cnn.State == ConnectionState.Open) 
{ cnn.Close(); } 
cnn.Open(); 

string strcmd = "Insert into [dbo].[MyTestTable](FirstName,LastName,MailId) values ('" + FirstName + "','" + LastName + "','" + MailId + "' )"; 
SqlCommand cmd = new SqlCommand(strcmd, cnn); 

string rowsaffected = cmd.ExecuteNonQuery().ToString(); 

return list; }

 }

}
//put the dll file of the project into GAC.

2.How to update a Database by adding a list item in a SharePoint List with the help of workflow activity and webservice?

Let, the webservice url is:
You can create a Proxyclass file by MicroSoftVisualStudio Command Prompt by following command:

You can change the name of myProxyclass.cs file name and the class name .

Now click on SharePoint2007SequntialWorkflow template and create a workflow.
Now add an Code activity under workflow activity in workflow design page and double click on the code activity.
Now go to the SolutionExplorer .Then, rightclick on Projectfolder and add an existing item to add the myProxy.cs file.After adding the myProxy.cs file click add as Service reference on project folder.There put the webservice url and press ok.
Now, the code is something like given below.

using System.Collections; 
using System.Drawing; 
using System.Linq; 
using System.Workflow.ComponentModel.Compiler; 
using System.Workflow.ComponentModel.Serialization; 
using System.Workflow.ComponentModel; 
using System.Workflow.ComponentModel.Design; 
using System.Workflow.Runtime; 
using System.Workflow.Activities; 
using System.Workflow.Activities.Rules; 
using Microsoft.SharePoint; 
using Microsoft.SharePoint.Workflow; 
using Microsoft.SharePoint.WorkflowActions; 
using Microsoft.Office.Workflow.Utility; 


namespace MyWorkflowforWS 
{ 
public sealed partial class Workflow1 : SequentialWorkflowActivity 
{ 
Service1 webser = new Service1(); //the class name of added .cs file.


public Workflow1() 
{ 
InitializeComponent(); 
} 


public Guid workflowId = default(System.Guid); 
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties(); 


private void codeActivity1_ExecuteCode(object sender, EventArgs e) 
{ 
string title = string.Empty; 
string FirstName = string.Empty; 
string LastName = string.Empty; 
string MailId = string.Empty; 


string strcmd = string.Empty; 




SPSite mysite = workflowProperties.Site; 
SPWeb myweb = mysite.OpenWeb(); 
SPList list = myweb.Lists["UsersList"]; //"UsersList" is List name

SPQuery query = new SPQuery(); 


query.Query = "<Where><And><Contains><FieldRef Name='Title' /><Value Type='Text'>" + title + "</Value></Contains><Contains><FieldRef Name= " + FirstName + " /><Value Type='Text'>something</Value></Contains></And></Where>"; 



SPListItemCollection itemcoll = list.GetItems(query); 


SPListItem item = workflowProperties.Item; 

FirstName = item["FirstName"].ToString(); 
LastName = item["LastName"].ToString(); 
MailId = item["MailId"].ToString(); 


string[] iResult;


iResult = webser.UpdateDB(FirstName, LastName, MailId); 


} } 


} 

//Go to the Project property and in debug place the url of the sharepoint site.
Now, build the workflow. and deploy it.Now open the List on SharePoint Site and add this workflow .
Now add an item an activate the workflow and see the result.

Hope, this blog help you .
Please, give some comments and suggestion on this blog.

Thanks & Regards
Pradeep
Bangalore