Sunday, October 31, 2010

Add Technorati tags in blog posts

How to Add Technorati Tags to a Blog:

Technorati is an Internet search engine for searching blogs. You can increase your blog traffic by adding Technorati tags at the end of your blog posts. This will put your post into the list of posts searchers find on Technorati when searching for the tags you used. Everyday, thousands of visitor search for information through it.

If your blog is registered in Technorati, a bigger chance it will be seen by visitors.
This can increase your SEO Blog rank.
To register in Technorati, follow below simple steps:



1. Sign In on Technorati, if not register, please Join on Technorati, follow below simple steps:

2. Click your account (your userID), it's near signout link.
3. Click Claimed Blogs tab.
4. Click Claim a new blog link below.
5. Enter your Blog URL then click Begin Claim Button.


Now, your blog is registered in technorati.

In the next step, i will discuss about how to add technorati tag on every posting.

1. Login to BLOGGER, go to: "Settings > Template > Edit HTML"
2. Click on 'Expand Widget Templates'
3. Search for class='post-footer-line post-footer-line-2'
4. After below mention code:





5. Now add following code:






6. Now, your every blog post display Technorati tags as belw:



Share:

Friday, October 22, 2010

Add Web Part to page using C# code in SharePoint

Add Web Part to page using C# code in SharePoint:

In MOSS 2007 or WSS 3.0 sites we can add or remove the web part from SharePoint page, using the options available in site. We can also add web part into a page using SharePoint Object Model. To add web part into a page, we will use SPLimitedWebPartManager class.

SPLimitedWebPartManager class:

Provides a limited set of Web Part operations that can be performed in our object model scenarios when there is no HttpContext and no Page object is instantiated.


Example 1: Add web part to a page by passing page Url, webPart Name, zoneID and zoneIndex:-


Using Microsoft.Sharepoint;
Using System.Web.UI.WebControls.WebParts;


public static string AddWebPartToPage(
SPWeb web,
string pageUrl,
string webPartName,
string zoneID,
int zoneIndex)
{
using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
using (WebPart webPart =

CreateWebPart(web, webPartName, webPartManager))
{
webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}

public static WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager)
{
SPQuery qry = new SPQuery();
qry.Query = String.Format(CultureInfo.CurrentCulture,
"{0}",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(qry);

XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMsg;
WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);

return webPart;
}


Example 2: Add Content Editor web part to a page by passing site Url and page relative URL:-





public static string AddWebPartToPage(
string siteURL,
string pageRelativeUrl,
)
{




using (SPSite site = new SPSite(siteURL))
{
SPWeb web = site.RootWeb;
SPFile page = web.GetFile(pageRelativeUrl);
page.CheckOut();
using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
XmlElement p = new XmlDocument().CreateElement("p");
p.InnerText = "Hello World";
ContentEditorWebPart cewp = new ContentEditorWebPart();
cewp.Content = p;
wpmgr.AddWebPart(cewp, "Header", 0);
}
page.CheckIn(String.Empty);
}


}



References for this article:

http://www.dhirajranka.com/?p=78
Share:

SharePoint Rich Text Box (InputFormTextBox) Control

Use of Rich Text Box (InputFormTextBox) Control in SharePoint:


Objective:

In this article, I am going to explain use of RichTextField (InputFormTextBox) control in SharePoint.

Requirement:

Take an example of one requirement: We need to create newsletter on the basis of user input. The user input can be a normal text or html format text.

Resolution:

In this scenario, we can use SharePoint Rich Text Box (InputFormTextBox) control in a custom webpart/usercontrol. Check the screen shot below:





Ways of using SharePoint Rich Text Box (InputFormTextBox) control:

1. The following code illustrates how to use SharePoint Rich Text Box (InputFormTextBox) control in user control:

i. Add the required directive at the top of the ascx page (if you're using a web user control):


<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" Namespace="Microsoft.SharePoint.WebControls" TagPrefix="AmitKumarSPControls" %>


ii. For creating instance of SharePoint Rich Text Box (InputFormTextBox) control in your ascx (if you're using a web user control):










2. You can also create this type of control completely in code:

i. This is available under Microsoft.SharePoint.WebControls namespace (if you're using a custom web part):



InputFormTextBox richMessage = new InputFormTextBox();
richMessage.RichText = true;
richMessage.RichTextMode = SPRichTextMode.FullHtml;


You may also use following useful properties:


richMessage.AllowHyperlink = true;
richMessage.TextMode = TextBoxMode.MultiLine;
richMessage.Wrap = true;
richMessage.Rows = 10;
richMessage.Width = System.Web.UI.WebControls.Unit.Percentage(100);



There are a number of properties/attributes that you can set:

•ID: control id.
•Text: the string within the control.
•ErrorMessage: you can define a custom error message that will be displayed when an error occurs.
•ErrorMessageLabelControl: you can specify a control id of a control on the page in which the error message will be rendered.
•TextMode: accepts a value of type TextBoxMode. Possible values are MultiLine, SingleLine and Password. The default is SingleLine.
•Columns: indicates the width of the text box.
•Rows: indicates the number of rows that will be displayed. This is only applied if the TextMode property is set to MultiLine.
•RichText: indicates if a normal text box or a rich text box will be displayed. The default value is false. The text box will only be rendered as a rich text box if the TextMode property is set to MultiLine.
•RichTextBoxMode: accepts a value of type SPRichTextMode. Possible values are Compatible, FullHtml and HtmlAsXml. The default value is Compatible. this property only applies if the RichText property is set to true.
•AllowHyperlink: this property only applies if the RichtText property is set to true. The necessary controls to insert hyperlinks and images will be added to the tools pane.
•Direction: This orders the controls in the tools pane from left to right or from right to left. The value is of type ContentDirection having values NotSet, LeftToRight, RightToLeft. The default value is NotSet. This property only applies if the RichText property is set to true.





Example:

The following code illustrates how to use SharePoint Rich Text Box (InputFormTextBox) control in user control. In this example, I am also validating, value in SharePoint Rich Text Box (InputFormTextBox) control is empty or not using JavaScript.

RichTextBoxControl.ascx Code:



<%@ Control Language="C#" AutoEventWireup="true" CodeFile="RichTextBoxControl.ascx.cs" Inherits="RichTextBoxControl" %>
<%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
Namespace="Microsoft.SharePoint.WebControls" TagPrefix="AmitKumarSPControls" %>



















 
Rich Text Box Control




















Enter Text:*






RichText="true" RichTextMode="FullHTML" Rows="21" Style='height: 270px; width: 700px;'
TextMode="MultiLine" Width="700px">






 


 







RichTextBoxControl.ascx.cs Code:




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Microsoft.SharePoint;

public partial class RichTextBoxControl : System.Web.UI.UserControl
{

#region Render Controls and Handle Controls Event


#region Handle Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetAttibutes();
}
}
#endregion

#region Handle Display Button Click Event
protected void btnDisplay_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtNotes.Text))
{
SetMessage(txtNotes.Text.Trim(), lblMessage);
}

}
#endregion


#endregion

#region Helper

#region set controls attributes
private void SetAttibutes()
{
//Add JS to the Display button
btnDisplay.Attributes.Add("OnClick", "return TextBoxMessageCheck('" + txtNotes.ID + "','" + txtNotes.ClientID + "');");
//


}
#endregion

#region Show message on the screen
///
/// This method makes the lblMessage object visible to the page and set its Text property to the message provided.
///

/// The string value assigned to the Text property of the lblMessage object.
private void SetMessage(string message, Label lblMessage)
{
if (lblMessage != null)
{
lblMessage.Visible = true;
lblMessage.Text = message;
}
else
{
Page.Response.Write(message);
}
}
#endregion

#endregion
}






You can deploy custom user control in SharePoint with the help of SonofSmartPart Web part.


References for this article:

http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.inputformtextbox.aspx

http://smartpart.codeplex.com/releases/view/10697
Share:

Friday, October 15, 2010

Export/Import a sharepoint list/document library

Content Import/Export:

The Microsoft.SharePoint.Deployment APIs in Windows SharePoint Services 3.0 provide a flexible set of tools for migrating content between Windows SharePoint Services Web sites. Windows SharePoint Services uses the concept of the content migration package, which can include either single or multiple XML files, and then provides a flexible set of APIs to enable exporting and importing the migration packages. The content import/export feature of the deployment object model allows you to export not only Web site content but also existing dependencies, like security features, user roles, versioning data, workflows, and other metadata.

Content Migration Using the Deployment Object Model:

The import/export features of the Microsoft.SharePoint.Deployment object model uses two key objects:

Microsoft.SharePoint.Deployment.SPImport and
Microsoft.SharePoint.Deployment.SPExport.
However, before you run the import or export operations using these objects, you must first specify your import or export settings using Microsoft.SharePoint.Deployment.SPImportSettings and Microsoft.SharePoint.Deployment.SPExportSettings objects. Then you simply call the Run() method on the SPImport or SPExport object, as appropriate.

Example:

The following code illustrates how to use the deployment object model to export a SharePoint list from a source location and import it to a destination location.




using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Deployment;
using Microsoft.SharePoint.Administration;
using System.Net.Mail;
using System.Windows.Forms;

namespace TreeView1
{
class ImportExport
{


#region Export Data
///
/// Export data into log folder
///

/// Source site url
/// Destination site url
/// List to be exported
/// Name of folder where we store exported data
/// Complete path of the exported data
///
public Boolean ExportData(string sourceSiteURL, string destinationSiteURL,
string listName, string folderPath, ref string folderName)
{
SPList sourceList = null;
Boolean isExportCompleted = false;

try
{
#region Try

try
{
#region Try of Source site object
using (SPSite sourceSite = new SPSite(sourceSiteURL))
{
#region Open Source site

try
{
#region Try of Source web object
using (SPWeb sourceWeb = sourceSite.OpenWeb())
{
#region Open Source Web object

#region Check list exist or not
if (CheckListExists(listName, sourceWeb, ref sourceList))
{
#region If list exist
//Create Export Object and update the Setting for the Export object
SPExportObject exportObject = new SPExportObject();
exportObject.Id = sourceList.ID;
exportObject.Type = SPDeploymentObjectType.List;

//Create the Export Setting object and update the setting properties.
SPExportSettings settings = new SPExportSettings();
settings.SiteUrl = sourceWeb.Url;
settings.ExportMethod = SPExportMethodType.ExportAll;
folderName = folderPath +
"\\" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_
" + DateTime.Now.Year.ToString() + "_
" + DateTime.Now.Hour.ToString() + "_
" + DateTime.Now.Minute.ToString() + "_
" + DateTime.Now.Second.ToString();
settings.FileLocation = folderName;
settings.FileCompression = false;
settings.IncludeSecurity = SPIncludeSecurity.All;
settings.ExcludeDependencies = true;

// Add the Export object to the ExportSetting Object
settings.ExportObjects.Add(exportObject);

// add the Export Settings to the SPExport object and Run the Export .
SPExport export = new SPExport(settings);
export.Run();
isExportCompleted = true;
#endregion

}
else
{
#region If list not exist
isExportCompleted = false;

#endregion
}
#endregion

#endregion

}
#endregion
}
catch (Exception ex)
{
#region Catch :: Source web object not exist
isExportCompleted = false;
#endregion
}

#endregion
}
#endregion
}
catch (Exception ex)
{
#region Catch :: source SiteURL not exist
isExportCompleted = false;
#endregion
}

// ("Successfully exported list=" + listName, Log.MessageType.Information);
#endregion
}
catch (AccessViolationException accException)
{
#region Catch for AccessViolationException
isExportCompleted = false;

#endregion
}
catch (Exception ex)
{
#region General Exception
isExportCompleted = false;
throw;
#endregion
}
return isExportCompleted;
}
#endregion

#region Import Data
///
/// This method will import the data to Destination Localtes
///

/// Source site url
/// Destination site url
/// list Name
/// Complete path of exported file
public static Boolean ImportData(string sourceSiteURL, string destinationSiteURL,
string listName, string folderName)
{
bool isImported = true;
try
{
#region Try

try
{
#region Try of Destination site
// Get the Site collection Url from the config file.
using (SPSite rootSiteColl = new SPSite(destinationSiteURL))
{
#region Open Destination site

SPWebApplication webApp = rootSiteColl.WebApplication;

// Set the Allow unsage update to true to import the content to the locale site
rootSiteColl.AllowUnsafeUpdates = true;
try
{
#region Try of Destination web object
using (SPWeb rootWeb = rootSiteColl.OpenWeb())
{
#region Open web object of Destination site

// Update the Below Setting to Import the Site
rootWeb.AllowUnsafeUpdates = true;
webApp.FormDigestSettings.Enabled = false;
webApp.FormDigestSettings.Expires = false;
// Create the Import settings object and update the setting to the object
SPImportSettings importSettings = new SPImportSettings();
importSettings.SiteUrl = rootSiteColl.Url;
importSettings.WebUrl = rootWeb.Url;
importSettings.FileLocation = folderName;
importSettings.FileCompression = false;
importSettings.RetainObjectIdentity = false;

//Add import setting object to the SPImport object and run the Import
SPImport import = new SPImport(importSettings);
import.Run();
isImported = true;

// Revert back Setting for SiteCollection,Webapplicaiton and Site
rootWeb.AllowUnsafeUpdates = false;
webApp.FormDigestSettings.Enabled = true;
webApp.FormDigestSettings.Expires = true;
rootWeb.Close();

#endregion
}
#endregion
}
catch (Exception ex)
{
#region Catch :: Destination web object not exist
isImported = false;
#endregion
}

rootSiteColl.AllowUnsafeUpdates = false;
#endregion
}
#endregion
}
catch (Exception ex)
{
#region Catch :: Destination url not exist
isImported = false;
#endregion
}

#endregion

}
catch (AccessViolationException accException)
{
#region Catch for AccessViolationException
isImported = false;
#endregion
}
catch (Exception ex)
{
#region General Exception
isImported = false;
#endregion
}
return isImported;
}
#endregion

#region Import List
private void ImportList(string sourceSiteURL, string destinationSiteURL, string listName)
{
#region Variables
string exportFolderName = string.Empty;
#endregion
try
{
#region Try


if (!string.IsNullOrEmpty(sourceSiteURL) && !string.IsNullOrEmpty(destinationSiteURL))
{
if (ExportData(sourceSiteURL,destinationSiteURL,listName, "
C:\\AMITKUMAR\\LogFiles", ref exportFolderName))
{
ImportData(sourceSiteURL,destinationSiteURL,listName, exportFolderName);
}

}



#endregion
}
catch (Exception ex)
{
throw ex;
}
}
#endregion


#region Check List exist or not
///
/// Check list exist or not
///

/// list name
/// pass SPWeb object
/// pass SPList object as a Ref, it will return the list ref if exist
///
private bool CheckListExists(string listName, SPWeb web, ref SPList list)
{
try
{
//---Check list exist or not
if (web.Lists[listName] != null)
{
//--Get list reference
list = web.Lists[listName];
return true;
}
return false;
}
catch (ArgumentException ex)
{
return false;
}
catch (Exception ex)
{
return false;

}
}
#endregion
}
}






Content Migration Using the Command-Line Tool STSADM:


The command-line tool STSADM.exe supports only basic import and export operations and is only useful when importing or exporting entire SharePoint Web sites or when reparenting a Web site. Content migrated using this tool will not retain object GUIDs. Note that you cannot use this utility to import or export individual items or lists.

Export Example:

The following example illustrates how to export the contents of a Web site using the command-line tool STSADM.exe.


stsadm.exe -o export
-url
-filename
[-overwrite]
[-includeusersecurity]
[-haltonwarning]
[-haltonfatalerror]
[-nologfile]
[-versions <1-4>
1 - Last major version for files and list items (default)
2 - The current version, either the last major or the last minor
3 - Last major and last minor version for files and list items
4 - All versions for files and list items]
[-cabsize ]
[-quiet]



Import Example:

The following example illustrates how to import the contents of a Web site using the command-line tool STSADM.exe.


stsadm.exe -o import
-url
-filename
[-includeusersecurity]
[-haltonwarning]
[-haltonfatalerror]
[-nologfile]
[-updateversions <1-4>
1 - Add new versions to the current file (default)
2 - Overwrite the file and all its versions (delete then insert)
3 - Ignore the file
4 - Terminate with conflicts]
[-quiet]


Reference : MSDN
Share:

Add Code Block in Blogs

If you want to put some HTML, JavaScript or code of any programming language in your blogger blog posts then entering that as a simple text will mix it with plain text and that would be pretty hard for readers to differentiate between plain text and code block. To make the code look different from plain text you need to highlight code block.

We can use SyntaxHighlighter tool to insert colored code snippets on a web page using client-side javascript only. This tool is useful for users of BLOGGER because we do not have server side resource to parse and highlight the code. For implementing this tool on blooger/blogspot site, we need to do some changes in the template of blog.


Below are the steps to setup:

1. Take the backup of existing template.

2. Download the files from SyntaxHighlighter.

3. Now extract the contents of the package and upload the Scripts and Styles folder to any host or website which can be linked from your blog.A free choice is, of course, Google Docs.

4. Login to BLOGGER, go to: "Settings > Template > Edit HTML", add the following code after the tag:

</div></div> <!-- end outer-wrapper -->

<!-- You need to replace "amitkumarmca04.blogspot.com" with your [YOUR HOST] address -->

<link href='http://amitkumarmca04.blogspot.com/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>
<script src='http://amitkumarmca04.blogspot.com/shCore.js' type='text/javascript'/>

<script src='http://amitkumarmca04.blogspot.com/shBrushCpp.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushCSharp.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushCss.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushJava.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushJScript.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushSql.js' type='text/javascript'/>
<script src='http://amitkumarmca04.blogspot.com/shBrushXml.js' type='text/javascript'/>

<script class='javascript'>

dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');

</script>



5. Now you are all done to start posting source codes. You can use the
 
to enclose your source-codes, and give the name="code" attribute and class="CSharp" for your CSharp source.

For example:



<pre name="code" class="CSharp">
public class AmitKumar {
public AmitKumar() {
Response.Write("SyntaxHighlighter Example");
}
}
</pre>


will look like:



Public class AmitKumar
{
public AmitKumar()
{
Response.Write("SyntaxHighlighter Example");
}
}


Another example of code classes are:
For C#(C Sharp) code: class="CSharp"
For Java code: class="java"
For Python code: class="python"
For C/C++ code: class="Cpp"
For Cascading Style Sheets code: class="CSS"
For Java Script code: class="JScript"
For Sql code: class="Sql"
For Xml code: class="Xml"

The list of supported languages and their aliases can be found at the syntaxhighlighter wiki

Note: If you are posting XML/HTML, anything which has < or >, replace them with < and >

Share:

Sitecore® Technology MVP 2019

Featured Post

Sitecore-Front-end performance tuning points

In the previous Sitecore Performance Tuning article, i tried to explain about that Sitecore website performance depends upon Front-end ...

Total Pageviews

State Counter

Popular

About Me

My photo
Based in Bangalore, INDIA, Amit is a Sitecore MVP and MCC. He has an MCA from the U.P.T.U., INDIA and holds certifications including Sitecore and SharePoint 2007/2010. He is an contributor to Sitecore/MSDN communities and http://amitkumarmca04.blogspot.com/. Amit have experience in Sitecore, ASP.Net with C#, MVC, SharePoint, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Follow me on Twitter