Saturday, June 19, 2010

Progmatically Using Colums from PageLayout Tab

Progrmatically using Colum from page layout from Word2007 with C#
Add Video
Requirement:-

Visual Studio 2008
Vsto

Let start:-

What we do Normally do when we want to use colum in word.

Normal Word

Selection of Colum


When we click on Colum divide in 2 part.

Now We do same think in C#

Image 1 Remain same
Code do the Colum in C#

public void Pagesetuptest()
{


if (this.ActiveWindow.View.SplitSpecial != WdSpecialPane.wdPaneNone)
{
this.ActiveWindow.Panes[2].Close();
}
if (this.ActiveWindow.View.Type != WdViewType.wdPrintView)
{
this.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView;
}


Selection mysel = this.ActiveWindow.Selection;
mysel.PageSetup.TextColumns.SetCount(2);
mysel.PageSetup.TextColumns.EvenlySpaced = -1;
mysel.PageSetup.TextColumns.LineBetween = -1;
}



Output




Sunday, June 13, 2010

Ribbion XML and window for

Loading Winform from ribbion Xml in vsto2007

So Let Start...

Requirement :-
Vs2008(vsto)
and Bit of interest

Start:-

For simple Ribbion customization in Vsto..

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

Chk The above link.

Know we will START with loading a WIN FORM ribbion and do the same functionality as in above link.


Know Once u ad Modify the Follwing Files MyRibbon.xml,MyRibbon.cs,ThisAddIn.cs

MyRibbion.xml

>?xml version="1.0" encoding="UTF-8"?&lft
>customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="Ribbon_Load">
>ribbon>
>tabs>
>tab idMso="TabAddIns">
>group id="ContentGroup" label="Content">
>button id="Loadform" label="Load Form"
screentip="Load Form"
onAction="LoadForm"
supertip="Load Form "/>

>/group>
>/tab>

>/tabs>
>/ribbon>
>/customUI>


MyRibbon.cs
namespace NewRibbionTest
{
[ComVisible(true)]
public class MyRibbon : Office.IRibbonExtensibility
{
private Office.IRibbonUI ribbon;

public MyRibbon()
{
}

/// This Functin is called from Ribbion and Load the win form
public void LoadForm(Office.IRibbonControl control) { MyTable mytable = new MyTable(); mytable.ShowDialog(); }




#region IRibbonExtensibility Members

public string GetCustomUI(string ribbonID)
{
return GetResourceText("NewRibbionTest.MyRibbon.xml");
}

#endregion

#region Ribbon Callbacks
//Create callback methods here. For more information about adding callback methods, select the Ribbon XML item in Solution Explorer and then press F1

public void Ribbon_Load(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}

#endregion

#region Helpers

private static string GetResourceText(string resourceName)
{
Assembly asm = Assembly.GetExecutingAssembly();
string[] resourceNames = asm.GetManifestResourceNames();
for (int i = 0; i < resourcereader =" new" style="font-weight: bold;">ThisAddIn.cs

protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return new MyRibbon();
}

Now addding Window form in project and some code

Code Below:-


private void button1_Click(object sender, EventArgs e)
{
object missing = System.Type.Missing; Range currentRange = Globals.ThisAddIn.Application.Selection.Range; Table newTable = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add( currentRange, 3, 4, ref missing, ref missing); // Get all of the borders except for the diagonal borders. Microsoft.Office.Interop.Word.Border[] borders = new Border[6]; borders[0] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft]; borders[1] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight]; borders[2] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop]; borders[3] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom]; borders[4] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal]; borders[5] = newTable.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical]; // Format each of the borders. foreach (Border border in borders) { border.LineStyle = WdLineStyle.wdLineStyleSingle; border.Color = WdColor.wdColorBlue; } this.Hide();

}

private void button2_Click(object sender, EventArgs e)
{
Range currentRange = Globals.ThisAddIn.Application.Selection.Range; currentRange.Text = "This text was added by the Win form."; this.Hide();
}

When you click On Insert Ribbion Button You will get the follwing output












Creating Water Mark using TextBox In word2007

Code :-

private void AddWatermark(string WatermarkText)
{
object missing = System.Type.Missing;






Word.Template mytemplate = (Word.Template)Globals.ThisAddIn.Application.ActiveDocument.get_AttachedTemplate();

// Word.Document mydoc = (Word.Document)Globals.ThisAddIn.Application.ActiveDocument;

Word.Selection Selection = mytemplate.Application.Selection;


Word.Shape wmShape;

//Select the section

// mytemplate.Application.Selection.Range.Select();

mytemplate.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader ;


//Create the watermar shape

string strXml = Selection .get_XML(false);


int totallenght = WatermarkText.Length;

wmShape = Selection.HeaderFooter.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationVertical, 0, 0, 0, 0, ref missing);


//Set all of the attributes of the watermark
string strName = "";



object shapeName = "AvinashTiwari";
string strname = "";
try
{
strname = Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Name;

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();
}
catch (Exception ex)
{
}


wmShape.Select(ref missing);

wmShape.Name = "AvinashTiwari";



wmShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;



//U may Use // wmShape.TextFrame.TextRange.Text = WatermarkText;
//TextRange also


// wmShape.Fill.Solid();
wmShape.TextFrame.TextRange.FormattedText.Text = WatermarkText;

wmShape.TextFrame.TextRange.FormattedText.Font.Name = "Arial";
wmShape.TextFrame.TextRange.FormattedText.Font.Bold = 1;
wmShape.TextFrame.TextRange.FormattedText.Font.Size = 14;
wmShape.TextFrame.TextRange.FormattedText.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkRed;

// wmShape.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorDarkRed;




float worddocheight = wmShape.Height;

wmShape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Height = mytemplate.Application.InchesToPoints(worddocheight);

wmShape.Width = mytemplate.Application.InchesToPoints(12.0f);

wmShape.WrapFormat.AllowOverlap = -1; //true

wmShape.WrapFormat.Side = Word.WdWrapSideType.wdWrapBoth;

wmShape.WrapFormat.Type = Word.WdWrapType.wdWrapNone; //3

wmShape.RelativeHorizontalPosition = Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionRightMarginArea;

wmShape.RelativeVerticalPosition = Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;

wmShape.Left = (float)Word.WdShapePosition.wdShapeLeft ;

//set focus back to document

mytemplate.Application.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;



}

Saturday, June 12, 2010

Reading Header part in Vsto

Code Snippet..


public void XMLRead()
{
try
{
const string mydoc = @"E:\s\WordDocument2.docx";

string xmlstring = "";

using (WordprocessingDocument wdDoc =
WordprocessingDocument.Open(mydoc, false))
{
foreach (HeaderPart hp in wdDoc.MainDocumentPart.HeaderParts)
{
XElement ele = XElement.Load(
XmlReader.Create(hp.GetStream())
);
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
// Console.WriteLine(ele.Descendants(w + "tbl").Count().ToString());
// Console.WriteLine(ele.ToString());
xmlstring = ele.ToString();

}
}

// Console.WriteLine(xmlstring);

StringBuilder output = new StringBuilder();




String xmlString = xmlstring;


string Id = "";
string txtpathvaslue = "";

// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("v:shape");
// reader.MoveToFirstAttribute();
Id = reader.GetAttribute("id");
output.AppendLine("The genre value: " + Id);


reader.ReadToFollowing("v:textpath");
txtpathvaslue = reader.GetAttribute("string");
output.AppendLine("Content of the title element: " + txtpathvaslue);
}

Console.WriteLine("Id " + Id + " = TxtPath " + txtpathvaslue);



/**********Same thing using Linq to Xml***************/

TextReader tr = new StringReader(xmlString);

TextReader tr2 = new StringReader(xmlString);

XDocument doc = XDocument.Load((new XmlTextReader(tr)));
var query = doc.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Attributes("id");

foreach (XAttribute result in query)
Console.WriteLine(result.Name + " = " + result.Value);



XDocument doc1 = XDocument.Load((new XmlTextReader(tr2)));
var query1 = doc1.Element("whdr")
.Element("wp")
.Element("wr")
.Element("wpict")
.Element("vshape")
.Element("vtextpath")
.Attributes("string");

foreach (XAttribute result1 in query1)
Console.WriteLine(result1.Name + " = " + result1.Value);



/***************************************************/


}
catch (Exception e1)
{
Console.Write(e1.Message);
}

Console.Read();

}

Thursday, June 10, 2010

Watermarking Using Vsto

I found this very Intersting Code about water marking in Word using C#.

I found the code on Net So I like to It modfided for My requirement and I am shareing..

Dnot ask link it was some were in MSDN Blog or some where...


Let The Code start:-

private void AddWatermark(string WatermarkText)
{

Word.Selection Selection = ThisApplication.Selection;

Word.Shape wmShape;

//Select the section

this.Sections[1].Range.Select();

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekCurrentPageHeader;

//Create the watermar shape

wmShape = Selection.HeaderFooter.Shapes.AddTextEffect(

Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,

WatermarkText, "Times New Roman", 1,

Microsoft.Office.Core.MsoTriState.msoFalse,

Microsoft.Office.Core.MsoTriState.msoFalse,

0, 0, ref missing);

//Set all of the attributes of the watermark
string strname ="";

try
{
strname = Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Name;

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();
}
catch (Exception ex)
{
}


wmShape.Select(ref missing);

wmShape.Name = "Avinash Tiwari";

wmShape.TextEffect.NormalizedHeight = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;

wmShape.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Fill.Solid();

wmShape.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorGray25;

wmShape.Fill.Transparency = 0.5f;

wmShape.Rotation = 90.0f;

wmShape.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue;

wmShape.Height = ThisApplication.InchesToPoints(2.82f);

wmShape.Width = ThisApplication.InchesToPoints(5.64f);

wmShape.WrapFormat.AllowOverlap = -1; //true

wmShape.WrapFormat.Side = Word.WdWrapSideType.wdWrapBoth;

wmShape.WrapFormat.Type = Word.WdWrapType.wdWrapNone; //3

wmShape.RelativeHorizontalPosition =

Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionRightMarginArea;

wmShape.RelativeVerticalPosition =

Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionPage
;

wmShape.Left = (float)Word.WdShapePosition.wdShapeCenter;

wmShape.Top = (float)Word.WdShapePosition.wdShapeCenter;



//set focus back to document

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekMainDocument;

}



private void DeleteWatermark()
{

Word.Selection Selection = ThisApplication.Selection;

//Select the section

this.Sections[1].Range.Select();

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekCurrentPageHeader;

object shapeName = "PowerPlusWaterMarkObject1";

Selection.HeaderFooter.Shapes.get_Item(ref shapeName).Delete();

//set focus back to document

ActiveWindow.ActivePane.View.SeekView =

Word.WdSeekView.wdSeekMainDocument;

}



private void AddWM_Click(object sender, EventArgs e)
{

try
{

AddWatermark("Hello World");

}

catch (Exception ex)
{

MessageBox.Show(ex.Message);

}

}



private void DeleteWm_Click(object sender, EventArgs e)
{

try
{

DeleteWatermark();

}

catch (Exception ex)
{

MessageBox.Show(ex.Message);

}

}

Sunday, June 6, 2010

Writing Autotext Entries in Vsto

Finding AutoText Enties from word2007 and Writing on Selected Range
Requirement:-
Vs2oo8(Vsto)
Word
and Bit of Interest

Let Start :-


Go to -- Insert Tab -- Quick parts -- Building Block and U will See some What Image Like That


Know Double Click on Name --- U will See The window note Down Name
Know put the Code


Code:-

Word.Template template = (Word.Template)this.Application.ActiveDocument.get_AttachedTemplate();

//Adding name property of AutoText in This cas I have "Word_auto_text_Avinash"
//and Output would be "Avinash"
object agendaObj = "Word_auto_text_Avinash";
object richText = true;

Word.Range range2 = this.Paragraphs[1].Range;

Word.AutoTextEntry agenda = template.AutoTextEntries.get_Item(ref agendaObj);
agenda.Insert(range2, ref richText);

Output:-

Saturday, June 5, 2010

Acessing Buliding Block in for Word2007

Acessing Building Block in word 2007

Requriement :-
vs2008
Word2007
and Bit of interest

Code:-

Public void GetBuildingBlock()
{
// Declare variables to hold references to the Word objects.
ApplicationClass wordApplication = null;
Document wordDocument = null;
Template wordTemplate;
BuildingBlock wordBuildingBlock;

// Declare a variable for the path of the new document.
object paramDocPath = @"G:\ALL_TRAINING_MATERIAL\OpenXML\WordTemp\Test.docx";

// Declare variables for the building block properties.
WdBuildingBlockTypes paramBBType = WdBuildingBlockTypes.wdTypeWatermarks;

//Category
// object paramBBCategory = "Building Block Tests";
object paramBBCategory = "Urgent";

//Name
// object paramBBName = "Header Test";
object paramBBName = "ASAP 2";

// Declare variables to help with methods that accept optional
// and by reference parameters.
object paramMissing = Type.Missing;
object paramTemplateIndex = 1;
object paramFalse = false;

try
{
// Start an instance of Word.
wordApplication = new ApplicationClass();

// Create a new document.
wordDocument = wordApplication.Documents.Add(ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing);

// Load the "Building Blocks.dotx" template.
// After calling LoadBuildingBlocks Building Blocks.dotx will be Templates(1).
wordApplication.Templates.LoadBuildingBlocks();
wordTemplate = wordApplication.Templates.get_Item(ref paramTemplateIndex);

// Access the "Header Test" custom headers building block
// through its type, category, and name.
wordBuildingBlock =
wordTemplate.BuildingBlockTypes.Item(paramBBType)
.Categories.Item(ref paramBBCategory)
.BuildingBlocks.Item(ref paramBBName);

// Insert the building block into the primary header of the first
// section of the document.
wordBuildingBlock.Insert(wordDocument.Sections[1]
.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,
ref paramMissing);

// Save the document.
wordDocument.SaveAs(ref paramDocPath, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
ref paramMissing, ref paramMissing);
}
catch (Exception ex)
{
// Respond to the error.
Console.WriteLine(ex.Message);
}
finally
{
// Release references to the Word objects.
wordBuildingBlock = null;
wordTemplate = null;

// Close and release the Document object.
if (wordDocument != null)
{
((_Document)wordDocument).Close(ref paramFalse, ref paramMissing, ref paramMissing);
wordDocument = null;
}

// Quit Word and release the ApplicationClass object.
if (wordApplication != null)
{
wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
wordApplication = null;
}

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}

Sunday, May 16, 2010

Simple Linq Sample in Word Vsto

Using Linq In Word Vsto The Below Sample Shows very Basic use of Linq with VSTO word.

Requirement:-

Vs 2008
Vsto

Code:-

private void ThisDocument_Startup(object sender, System.EventArgs e)
{
Linquse_InWord_Vsto("Avinash Tiwari Linq Sample");
}

public void Linquse_InWord_Vsto(String strText)
{

var qChars = from c in strText select c;
int charCount = qChars.Count();

List textWords = new List(strText.Split(new char[] { ' ' }));
var qLetterWords = textWords.FindAll(x => (x.Length >= 2));

this.Application.Selection.InsertAfter("\n Character Count: " + charCount + "\n Word Count: " + qLetterWords.Count);

this.Application.ActiveDocument.Content.InsertBefore(strText);


}

Output:-



Saturday, May 15, 2010

Simple Database Binding In Vsto2007

Database Binding in VSTO with Word..

Requirement:-

Vs(2008)
Vsto Tool
Sqlserever
and Interest


Create Database Myprofiletest having Follwing Fileds..

Srno
Name
Sex
Address
Profession

Know Let Start With Visual Studio

1}


Create Simple Table in word which have Name,Address,Sex,Profession and put as header in Table TD.


2}


Know select Datasource from Data menu from Top.

3}

When u Click datasource u will see 3 option

4}

Know select Database and complete Procedure to Connecting and Creating Connection String

5}

Once u connected properly u Given Oprtion Select select Table u have Created

6}

U will Filed in Datasoursce Tab it will map it self with control example if text it will Give Text and datTime then Picker Control.. Etc

7}

Drag and Drop The filed where u want

8}


When u Run Output u will See..

9}

if want Chk Some and put message and on Event of That

private void plainTextContentControl2_Entering(object sender, Microsoft.Office.Tools.Word.ContentControlEnteringEventArgs e)
{
// Display the dialog window for the edit operation
System.Windows.Forms.DialogResult myResult = new DialogResult();
// Message with Yes/No option to proceed
myResult = MessageBox.Show("Do you want to UnLock?", " Address?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, MessageBoxOptions.DefaultDesktopOnly, false);
// If you select the no it will remain in lock mode and display the content
if (myResult == DialogResult.Yes)
plainTextContentControl2.LockContentControl = false;
}

chk the above code










VSTo WORD 2007 WITH WORD ADDIN

Using Simple Task pane in Word Addin Sample..

Requirement:-

Interest
Vs2008
and Vsto

Code:-

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
AddinSample1();
}


//Initlizating the customtaskpane object of the current application
private Microsoft.Office.Tools.CustomTaskPane PacktTaskPaneControl = null;

//Inializing the Usercontrol
UserControl PacktUsercontrol = new UserControl();


public void AddinSample1()
{
//add the TextBox control to the CustomTaskPaqne
//The PacktUserControl parameter sets the title to search
PacktTaskPaneControl = this.CustomTaskPanes.Add(PacktUsercontrol, "Sample Avinash Search");

// Set the CustomTaskPane to visible
PacktTaskPaneControl.Visible = true;



}

Output:-





Word addin with task pane






Code :-

User Control



WordAddIn1.ThisAddIn newtest = new WordAddIn1.ThisAddIn();

int mytestvalue = 0;
mytestvalue = Convert.ToInt16(textBox1.Text) + Convert.ToInt16(textBox2.Text);
string Myvalue = "";
Myvalue = Convert.ToString(mytestvalue);

MessageBox.Show(Myvalue);


Addin Control...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Tools.Word.Extensions;
using System.Windows.Forms;

namespace WordAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
AddinSample1();
}

private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}

//Initlizating the customtaskpane object of the current application
private Microsoft.Office.Tools.CustomTaskPane PacktTaskPaneControl = null;

//Inializing the Usercontrol
UserControl PacktUsercontrol = new UserControl();


public void MyTest(string Mytest)
{
// this.Content.InsertAfter(Mytest);

}


public void AddinSample1()
{
//add the TextBox control to the CustomTaskPaqne
//The PacktUserControl parameter sets the title to search
PacktTaskPaneControl = this.CustomTaskPanes.Add(new UserControl1(), "Sample Cal Search");

// Set the CustomTaskPane to visible
PacktTaskPaneControl.Visible = true;



}


#region VSTO generated code

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}

#endregion
}
}









ACTION PANE IN VSTO 2007 (Word)

Some Simple Code Snippet Which I have learned in process of Learing Vsto .

Requirment:-

Interest
Vs2008
and Vsto


Code :-

private void ThisDocument_Startup(object sender, System.EventArgs e)
{
CreateActionPane();
}



//Initlizating the TextBox control to use in Action pane
TextBox VstoTextBox = new TextBox();
public void CreateActionPane()
{

//set text property for TextBox Control

VstoTextBox.Text = "Avinash in Action Pane User";

//Add the TextBox control to ActionPane
ActionsPane.Controls.Add(VstoTextBox);

//On document load ActionPane is shown
ActionsPane.Show();
}

OutPut:-


//Adding DatePicker in Action Pane

Code :-

//initalizing the datetimepicker control
DateTimePicker _packtdatetimer = new DateTimePicker();
public void datetimepickersample()
{
this.ActionsPane.Controls.Add(_packtdatetimer);
}



void _packtdatetimer_ValueChanged(object sender, EventArgs e)
{
//Read content and inseret the value after the paragraph
this.Content.InsertParagraphAfter();

//Insert value from the DateTimepicker select value..
this.Content.InsertAfter(_packtdatetimer.Value.ToString());
}

//Modify Internal Start Up

private void InternalStartup()
{
//value chnaged event registration in the internalStartup of the application

this._packtdatetimer.ValueChanged += new EventHandler(this._packtdatetimer_ValueChanged);

this.Startup += new System.EventHandler(ThisDocument_Startup);
this.Shutdown += new System.EventHandler(ThisDocument_Shutdown);
}



OutPut:-






Some Simple Code Snippet for Vsto 2007 (Word)

While Learning Vsto With Word I have came Some simple Code snippet which may come handy.
When The Real programming Begins ..

Requirment :-

Interest with
Vs2008
and Vsto

Let Start

1} Inserting Text in Word 2007


InsertAfter method inserts text at the end of the active range or selection, whereas InsertBefore inserts text at the start of the active range or selection.

Code :-

// Using InsertBefore method inserts text
this.Application.ActiveDocument.Content.InsertBefore("Avinash @ The Start-");

//using Insert method insert text
this.Application.ActiveDocument.Content.InsertAfter(" - Avinash @ the End ");

Same Opertion Can be Performed using Selection Object

// Using Selection Object inserting text after the text
this.Application.Selection.InsertAfter("Avinash @ The End");

// Using Selection Object inserting text before the text

this.Application.Selection.InsertBefore("Avinash @ The Start");

2} Selecting text in a Word 2007 document


///Intializing the range object
Word.Range PackRangeSelect;
////check the sentence count
if (this.Sentences.Count >= 1)
{
////set the start and end point has object
object pktStartfrom = this.Sentences[2].Start;
object pktStopHere = this.Sentences[5].End;
////assign the selection range
PackRangeSelect = this.Range(ref pktStartfrom, ref pktStopHere);

////select the sentence using select() Method
PackRangeSelect.Select();
}
else
{
return;
}

OutPut



3} Creating Table in Word



//Object instance
object pktMissing = System.Type.Missing;

// Range on the application selection

Word.Range PacktRangePresent = this.Application.Selection.Range;

// Using Table object add in the Word document

Word.Table PacktTable = this.Application.ActiveDocument.Tables.Add(PacktRangePresent, 3, 4, ref pktMissing, ref pktMissing);

// Border propety of the Table we are creating

Word.Border[] PacktBorder = new Word.Border[6];
PacktBorder[0] = PacktTable.Borders[Word.WdBorderType.wdBorderLeft];
PacktBorder[1] = PacktTable.Borders[Word.WdBorderType.wdBorderRight];
PacktBorder[2] = PacktTable.Borders[Word.WdBorderType.wdBorderTop];
PacktBorder[3] = PacktTable.Borders[Word.WdBorderType.wdBorderBottom];
PacktBorder[4] = PacktTable.Borders[Word.WdBorderType.wdBorderHorizontal];
PacktBorder[5] = PacktTable.Borders[Word.WdBorderType.wdBorderVertical];
// Border formatting of the Table
// Loop through the border and set color for table
foreach (Word.Border pktBorder in PacktBorder)
{
// Table line style propety
pktBorder.LineStyle = Word.WdLineStyle.wdLineStyleTriple;
// Table line color property
pktBorder.Color = Word.WdColor.wdColorGray30;
}

Output:-

Saturday, May 8, 2010

Open XML Hello World

Currently I am Involved In Open Xml project.. I was Hard to Find Some Good resource regarding OpenXml So I taught I Should Create My Own So I have..

Requirement (What I Have used):-

OpenXML SDK 2.0
Visual Studio 2008

Let Start:-

Add Some Assemblies

DocumentFormat.OpenXml
Window.Base
System.Xml
System.IO
System.IO.Packaging

Download OpenXMl SDK..



ADD
DocumentFormat.OpenXml

Window.Base
Assemblies




CODE WHAT I HAVE USED

Assemblies

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Packaging;
using System.IO;
using System.Xml;

Creating Package Method..

public void CreatePackage()
{
//File Would Create in D Drive With name Sample.docx
using (Package package = Package.Open("D://Sample.docx", FileMode.Create))
{

PackagePart mainPart = package.CreatePart(
new Uri("/Words/document.xml", UriKind.Relative),"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");

//This Method Which has Code Below
XMLFile(mainPart);


PackageRelationship mainRelationship = package.CreateRelationship(
mainPart.Uri,
TargetMode.Internal,
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");


}

}
XMLFile METHOD


public void XMLFile(PackagePart mainPart)
{
string xmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
using (XmlWriter writer = XmlWriter.Create(mainPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
{
writer.WriteStartDocument();
writer.WriteStartElement("w", "document", xmlNamespace);
writer.WriteStartElement("w", "body", xmlNamespace);
writer.WriteStartElement("w", "p", xmlNamespace);
writer.WriteStartElement("w", "r", xmlNamespace);
writer.WriteStartElement("w", "t", xmlNamespace);
writer.WriteString("Hello World");
writer.WriteEndDocument();
}

}

OutPut Of Code


Opening Docx File In WinRar

Extraction DOCX file in Folder


Word folder Is Created Becuause be Defined In code

new Uri("/Words/document.xml", UriKind.Relative)

Now Going To Document.xml


Now Checking Document.xml


This is all about OpenXMl Hello World
Hope It Helps Some Body To Understand






Sunday, April 25, 2010

Hello World Vsto And Deployment using word part2

Hi,

Now We will See How to Deploy VSTO project
In this Case Word is Going to Be deployed..

http://vsto2007.blogspot.com/2010/04/hello-world-vsto-using-word-part1.html

if u have Not Seen Hello Wordl Part1 Kindly Go through the above link It would Be helpfull


Requirement(What I am Using to Build)

Visual Studio(2008 professional)

Let Start

1} Publish The website
Right Click On Project --> select Publish


2} Select the Path Where u want Your Published File Shoule Be Kept



3} Put Your UNC Path example "\\Username\Somefolder"


4} Know Click Finish on the Screen


5} Published File on Specified Folder

6} Click On Vsto Or setup file once Setup is over u can use *.dotx file and use

7} Once you have deployed run The dotx file u will see the Message


8} Now Creating Updateable version setup




9}Project -->Propties -->Update


10} Selecting each Time Application Will Check Update evey time program Starts

11}Publish The Project


12}Now You Check folder u will get 2 version of Published


13} Modify Code i Have Just Chnaged ShortDate to Long