If somebody like the post and its helpful in your work then, add comments.

Thursday, August 27, 2009

Hiding “Open with Windows Explorer” from the Actions Menu

Refer following link

Friday, August 21, 2009

Updating the SharePoint User Profile in SSP Programmatically

The User Profile Database in SharePoint is a great centralized location for storing all the information about the users of your SharePoint Portal.

To import the AD profiles in SharePoint then we have use UserProfileConfigManager class.

Add following references in solution:

using Microsoft.SharePoint;
using
Microsoft.Office.Server.UserProfiles;
using
Microsoft.Office.Server;
using
System.Web;

and the following code


SPSite HomeSite = new SPSite("http://mossvs2008");

           UserProfileConfigManager SPUserProfileConfigManager = new UserProfileConfigManager(ServerContext.GetContext(HomeSite));

           if (SPUserProfileConfigManager.IsImportInProgress() == false)

               SPUserProfileConfigManager.StartImport(true);


Sunday, August 9, 2009

WordProcessingML : How to update Table of Content in MS Word Document

To update the Table of content in the Microsoft word document first we have 
to create a table of content in first of document. Then write below code to
update the table of content updation.
class Program 
{
public static XNamespace ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

static void Main(string[] args)
{
using (WordprocessingDocument WorDocument = WordprocessingDocument.Create(@"C:\TestDocuments\TOCDocument.docx", WordprocessingDocumentType.Document))
{
// Add a new main document part.
MainDocumentPart mainPart = WorDocument.AddMainDocumentPart();
//Create Document tree for simple document.
mainPart.Document = new Document();
//Create Body (this element contains other elements that we want to include
Body body = new Body();

//Save changes to the main document part.
mainPart.Document.Append(body);

XDocument xmlXdocument = XDocument.Parse(mainPart.Document.InnerXml);
IEnumerable<XElement> xmlelement = xmlXdocument.Descendants(ns + "sdt");
XElement TOCRefNode = xmlelement.First();
GenerateTOC(xmlXdocument, TOCRefNode);

mainPart.Document.InnerXml = xmlXdocument.ToString();

mainPart.Document.Save();
WorDocument.Close();

}
}

#region TOC Creation

/// <summary>
///
returns title paragraphs of genereated doc fro creating toc hyperlink
/// </summary>
private static IEnumerable<XElement> TitleParagraphsElements(XDocument mainDocument)
{
IEnumerable<XElement> results = mainDocument.Descendants().Where
(
tag =>
tag.Name == ns + "p" &&
tag.Descendants(ns + "t").Count() > 0 &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
(
tag2.Attribute(ns + "val").Value == "Head1" ||
tag2.Attribute(ns + "val").Value == "Head2" ||
tag2.Attribute(ns + "val").Value == "Head3" ||
tag2.Attribute(ns + "val").Value == "Head4" ||
tag2.Attribute(ns + "val").Value == "Head5" ||
tag2.Attribute(ns + "val").Value == "Head6"
)
).Count() > 0
);

return results;
}

private static void GenerateTOC(XDocument xmlMainDocument, XElement TOCRefNode)
{
int bookMarkIdCounter = 0;
int maxHeading = 1;
int tempheading = 1;

// sdtContent, will contain all the paragraphs used in the TOC
XElement sdtContent = new XElement(ns + "sdtContent");
String strContentHdr = "";
XElement xContentHdr = TOCRefNode.Elements(ns + "sdtContent").First().Descendants().Where(
tag =>
tag.Name == ns + "p" &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
tag2.Attribute(ns + "val").Value == "TOCHeading"
).Count() > 0
).FirstOrDefault();

if (xContentHdr != null)
strContentHdr = xContentHdr.Descendants(ns + "t").FirstOrDefault().Value;

// some information regarding the attributes of the TOC
xContentHdr.Add(

new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "begin"))),
new XElement(ns + "r",
new XElement(ns + "instrText",
new XAttribute(XNamespace.Xml + "space", "preserve"),
"TOCLIMIT")),
new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "separate"))));
sdtContent.Add(new XElement(xContentHdr));


// for each title found it in the document, we have to wrap the run inside of it,
// with a bookmark, this bookmark will have an id which will work as an anchor,
// for link references in the TOC
foreach (XElement titleParagraph in TitleParagraphsElements(xmlMainDocument))
{
string bookmarkName = "_TOC" + bookMarkIdCounter;
XElement bookmarkStart =
new XElement(ns + "bookmarkStart",
new XAttribute(ns + "id", bookMarkIdCounter),
new XAttribute(ns + "name", bookmarkName));
XElement bookmarkEnd =
new XElement(ns + "bookmarkEnd",
new XAttribute(ns + "id", bookMarkIdCounter));

// wrap the run with bookmarkStart and bookmarkEnd
titleParagraph.AddFirst(bookmarkStart);
titleParagraph.Add(bookmarkEnd);

// get the name of the style of the parapgraph of the title, and for each one,
// choose a style to add in the paragraph inside the TOC
string referenceTitleStyle = "";
switch (titleParagraph.Descendants(ns + "pStyle").First().Attribute(ns + "val").Value)
{
case "Head1":
{
referenceTitleStyle = "TOC1";
tempheading = 1;
break;
}
case "Head2":
{
referenceTitleStyle = "TOC2";
tempheading = 2;
break;
}
case "Head3":
{
referenceTitleStyle = "TOC3";
tempheading = 3;
break;
}
case "Head4":
{
referenceTitleStyle = "TOC4";
tempheading = 4;
break;
}
case "Head5":
{
referenceTitleStyle = "TOC5";
tempheading = 5;
break;
}
case "Head6":
{
referenceTitleStyle = "TOC6";
tempheading = 6;
break;
}
}


string entryContent = "";
IEnumerable<XElement> owTList = titleParagraph.Descendants(ns + "t");
foreach (XElement entryElement in owTList)
{
entryContent += (entryElement == null ? string.Empty : entryElement.Value);
}

XElement TOCElement = null;
XElement tempTOCElement = TOCRefNode.Elements(ns + "sdtContent").First().Descendants().Where(
tag =>
tag.Name == ns + "p" &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "pStyle" &&
tag2.Attribute(ns + "val").Value == referenceTitleStyle
).Count() > 0
).FirstOrDefault();

if (tempTOCElement != null)
{
if (maxHeading < tempheading)
maxHeading = tempheading;

TOCElement = new XElement(tempTOCElement);
//delete instrText which contains TOC 1-n
XElement instrTextTOC = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "r" &&
tag.Descendants().Where(
tag2 =>
tag2.Name == ns + "instrText" &&
tag2.Value.Contains(@"TOC \o ")
).Count() > 0

).FirstOrDefault();
if (instrTextTOC != null)
{
instrTextTOC.ElementsAfterSelf(ns + "r").Remove();
instrTextTOC.ElementsBeforeSelf(ns + "r").Remove();
instrTextTOC.Remove();
}

//get hyperlink node
XElement hyperlink = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "hyperlink"

).FirstOrDefault();
//update anchor attribute value
hyperlink.Attribute(ns + "anchor").Value = bookmarkName;

//get entry content node
XElement contentNode = hyperlink.Descendants().Where(
tag =>
tag.Name == ns + "r" &&
tag.Descendants().Where(
tag2 =>
tag2.Name == ns + "rStyle" &&
tag2.Attribute(ns + "val").Value == "Hyperlink"
).Count() > 0 &&
tag.Elements(ns + "t").Count() > 0

).FirstOrDefault().Elements(ns + "t").FirstOrDefault();

contentNode.Value = entryContent;

//update PAGEREF value
XElement instrText = TOCElement.Descendants().Where(
tag =>
tag.Name == ns + "instrText" &&
tag.Value.Contains("PAGEREF ")
).FirstOrDefault();
if (instrText != null)
{
instrText.Value = " PAGEREF " + bookmarkName + @" \h ";
}

sdtContent.Add(TOCElement);
bookMarkIdCounter++;
}


}

sdtContent.Descendants().Where(
tag =>
tag.Name == ns + "instrText"
&&
tag.Value.Contains("TOCLIMIT")
).FirstOrDefault().Value = String.Format(@"TOC \o ""1-{0}"" \h \z \u ", maxHeading);

sdtContent.Add(
new XElement(ns + "p",
new XElement(ns + "r",
new XElement(ns + "fldChar",
new XAttribute(ns + "fldCharType", "end")))));

// Finish the xml construction of the TOC
XElement TOC =
new XElement(ns + "sdt",
new XElement(ns + "sdtPr",
new XElement(ns + "docPartObj",
new XElement(ns + "docPartGallery",
new XAttribute(ns + "val", "Table of Contents")),
new XElement(ns + "docPartUnique"))),
sdtContent);

// add it to the original document
IEnumerable<XElement> tocNodes = xmlMainDocument.Descendants().Where
(
tag =>
tag.Name == ns + "sdt" &&
tag.Descendants(ns + "sdtContent").Count() > 0 &&
tag.Descendants().Where
(
tag2 =>
tag2.Name == ns + "p" &&
tag2.Descendants().Where
(
tag3 =>
tag3.Name == ns + "pStyle" &&
(
tag3.Attribute(ns + "val").Value == "TOCHeading"
)
).Count() > 0

).Count() > 0
);

TOCRefNode.ReplaceWith(TOC);

}

#endregion
Solution is provided by open xmldeveloper.org at following
link

Download Solution

Thursday, August 6, 2009

WordprocessingML : Insert page number in the word document in center bottom of MS Word Document

Their are 3 things required for the inserting page number;

1. Footer.xml
2. Footnotes.xml
3. EndNotes.xml

And Section Properties to append in the document.

Sample code for that

                Footer footer = new Footer(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Footer" })));
                var footerPart1 = mainPart.AddNewPart<FooterPart>("rid110");
                Footer1().Save(footerPart1);
                body.Append(footer);

                Footnotes footnotes = new Footnotes(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Footnotes" })));
                var footnodeinpage = mainPart.AddNewPart<FootnotesPart>("rid111");
                PageFootNote().Save(footnodeinpage);
                body.Append(footnotes);

                Endnotes endnotes = new Endnotes(new Paragraph(new ParagraphProperties(new ParagraphStyleId() { Val = "Endnotes" })));
                var endnodeinpage = mainPart.AddNewPart<EndnotesPart>("rid112");
                PageEndNote().Save(endnodeinpage);
                body.Append(endnotes);

                body.Append(PageSectionProperties());


Methods

#region Page Number
private static Endnotes PageEndNote()
{
var element =
new Endnotes(
new Endnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new SeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.Separator, Id = 0 },
new Endnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new ContinuationSeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 1 });
return element;
}

private static Footer Footer1()
{
var element =
new Footer(
new SdtBlock(
new SdtProperties(
new SdtId() { Val = 538536024 },
new DocPartObjectSdt(
new DocPartGallery() { Val = "Page Numbers (Bottom of Page)" },
new DocPartUnique())),
new SdtContentBlock(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" },
new Justification() { Val = JustificationValues.Center }),
new SimpleField(
new Run(
new RunProperties(
new NoProof()),
new Text("6") ->Total Page Number in document
) { RsidRunAddition = "00E906EE" }
) { Instruction = " PAGE \\* MERGEFORMAT " }
) { RsidParagraphAddition = "00EA1D8B", RsidRunAdditionDefault = "002E7045" })),
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" })
) { RsidParagraphAddition = "00EA1D8B", RsidRunAdditionDefault = "00EA1D8B" });
return element;
}

private static Footnotes PageFootNote()
{
var element =
new Footnotes(
new Footnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new SeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.Separator, Id = 0 },
new Footnote(
new Paragraph(
new ParagraphProperties(
new SpacingBetweenLines() { After = (UInt64Value)0UL, Line = 240, LineRule = LineSpacingRuleValues.Auto }),
new Run(
new ContinuationSeparatorMark())
) { RsidParagraphAddition = "00670250", RsidParagraphProperties = "00EA1D8B", RsidRunAdditionDefault = "00670250" }
) { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 1 });
return element;
}

//Adding the section properties in the document
public static SectionProperties PageSectionProperties()
{
var element =
new SectionProperties(
new FooterReference() { Type = HeaderFooterValues.Default, Id = "rid110" },
new PageSize() { Width = (UInt64Value)12240UL, Height = (UInt64Value)15840UL },
new PageMargin() { Top = 1440, Right = (UInt64Value)1440UL, Bottom = 1440, Left = (UInt64Value)1440UL, Header = (UInt64Value)720UL, Footer = (UInt64Value)720UL, Gutter = (UInt64Value)0UL },
new Columns() { Space = (UInt64Value)720UL },
new DocGrid() { LinePitch = 360 }
) { RsidRPr = "007024C7", RsidR = "000B6998", RsidSect = "006040EE" };
return element;
}

#endregion

Also find on openxmldeveloper.org Link

Monday, August 3, 2009

SpreadsheetML: Updating a range in the Excel Sheet

The below code update the cell rane in the excel sheet.

#region Approch 1

#region Calculate Sum of Cell Range

private static void CalculateSumOfCellRange(string docName, string worksheetName, string resultCell)
{
// Open the document for editing.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
{
IEnumerable sheets = document.WorkbookPart.Workbook.Descendants().Where(s => s.Name == worksheetName);
if (sheets.Count() == 0)
{
// The specified worksheet does not exist.
return;
}

WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
Worksheet worksheet = worksheetPart.Worksheet;

#region Insert Cell Values
Cell result1 = InsertCellInWorksheet(GetColumnName("B4"), GetRowIndex(resultCell), worksheetPart);
Cell result2 = InsertCellInWorksheet(GetColumnName("C4"), GetRowIndex(resultCell), worksheetPart);
Cell result3 = InsertCellInWorksheet(GetColumnName("D4"), GetRowIndex(resultCell), worksheetPart);
Cell result4 = InsertCellInWorksheet(GetColumnName("E4"), GetRowIndex(resultCell), worksheetPart);
Cell result5 = InsertCellInWorksheet(GetColumnName("F4"), GetRowIndex(resultCell), worksheetPart);
Cell result6 = InsertCellInWorksheet(GetColumnName("G4"), GetRowIndex(resultCell), worksheetPart);
Cell resultSum = InsertCellInWorksheet(GetColumnName("J4"), GetRowIndex(resultCell), worksheetPart);

result1.DataType = new EnumValue(CellValues.Number);
result1.CellValue = new CellValue("1000");

result1.DataType = new EnumValue(CellValues.Number);
result1.CellValue = new CellValue("20000");

result2.DataType = new EnumValue(CellValues.Number);
result2.CellValue = new CellValue("100000");

result3.DataType = new EnumValue(CellValues.Number);
result3.CellValue = new CellValue("145000");

result4.DataType = new EnumValue(CellValues.Number);
result4.CellValue = new CellValue("301200000");

result5.DataType = new EnumValue(CellValues.Number);
result5.CellValue = new CellValue("440000");

result6.DataType = new EnumValue(CellValues.Number);
result6.CellValue = new CellValue("400000");

resultSum.CellFormula = new CellFormula("=sum(B4:G4)");
#endregion


worksheetPart.Worksheet.Save();
document.Close();
}
}

#endregion

#region Get Row Index in Sheet
// Given a cell name, parses the specified cell to get the row index.
private static uint GetRowIndex(string cellName)
{
// Create a regular expression to match the row index portion the cell name.
Regex regex = new Regex(@"\d+");
Match match = regex.Match(cellName);

return uint.Parse(match.Value);
}

#endregion

#region Get Column Name in Sheet
// Given a cell name, parses the specified cell to get the column name.
private static string GetColumnName(string cellName)
{
// Create a regular expression to match the column name portion of the cell name.
Regex regex = new Regex("[A-Za-z]+");
Match match = regex.Match(cellName);

return match.Value;
}

#endregion

#region Insert a Cell into a Worksheet
// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
// If the cell already exists, returns it.
private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild();
string cellReference = columnName + rowIndex;

// If the worksheet does not contain a row with the specified row index, insert one.
Row row;
if (sheetData.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements().Where(r => r.RowIndex == rowIndex).First();
}
else
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}

// If there is not a cell with the specified column name, insert one.
if (row.Elements().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
{
return row.Elements().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements())
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}

Cell newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);

worksheet.Save();
return newCell;
}
}
#endregion

#endregion

I leverage the msdn link for to update cell range in the excel sheet.