Thursday, November 12, 2009

WebPart Creation & Deployment

Custom Web Part Creation and Deployment

Creating Web User Control in VS2005 or VS2008.
Step 1: Create new project (Web application Project)
Note: Do not use new Web Site when creating project.
Step 2: Name the Project with good name. Since this becomes our DLL.
Step 3: Create Web User Control, with complete UI and Logic.
Step 4: Build the project. Which will create a DLL.

Create Web Part Project Library:
This project is our Web part Library. Usually we will create only one Library project for all the web parts we develop.
Step 1: Open new dev VS2005. Create New Library Project.
Step 2: Name the project with Good name. (This becomes Dll)
Step 3: Add a reference system.web to the project. This contains all the related name space for web part to work in share point.
Step 4: Add a Class. Name it. This becomes the WebPart.
Step 5: Import below name space.
using System.Web.UI.WebControls.WebParts;
Step 6: Inherit WebPart Class.

namespace BasicWebParts
{
public class HelloWorld:WebPart
{

}
}
Step 6: Override Create control method .And modify the code to reflect the user control file name.



Example class code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;

namespace BasicWebParts
{
public class UserControlWebPart:WebPart
{
Control cntrl;
protected override void CreateChildControls()
{
this.cntrl = this.Page.LoadControl(@"~/usercontrols/ucDisplay.ascx");
this.Controls.Add(this.cntrl);
}
}
}

Change only the ucDisplay.ascx only to your user control.

Step 7: (Important)
Add the below line to AssemblyInfo file located under Properties folder .
[assembly: System.Security.AllowPartiallyTrustedCallers]
Better Add it at the end.

Information: This related to security issue while inporting the Webpart by sharepoint.

Step 8: Creating snk file.
1.Open Application Properties as shown below Image.



2. Click on signing  Choose Strong name key  as shown in below.



3. Enter Project Name as snk file name and uncheck the Protect my key file with password.
4. Click ok. And save the changes. snk file got created.

Step 9: Build the Project. Get the Dll.
Step 10: Extract public Key token.
Open visual studio 2005 command prompt.
Enter sn –T “Path of the dll”
Example: sn -T “C:\Project1\bin\debug\Test.dll”
Note the Public Key Token: it will be like example “fa29fd297c3b296b”
Step 11:
Add Safe Control Tag in Web.config of the site. To find web.config go to IIS server virtual directory and explore the same.
By Default Location is like : C:\inetpub\wwwroot\wss\virtualdirectories\siteport
Open Web.config . Copy paste one safe control tag from their and modify the Assembly PublicKey token, Namespace.
Example:


Step 12: Deploy dlls and supporting files.
1. Deploying User Control s
2. Create a folder “usercontrol s” in the site root .
Assume 1001 is the site port we created. Create the directory like below
C:\inetpub\wwwroot\wss\virtualdirectories\1001\usercontrols.
Step 13: Place ASCX controls to this folder.
Step 14: Place WebpartDlls, WebUserControl dlls created from above steps into bin folder.

Adding web part to the site:

Step 1: Open site - Click Site Actions - Site Settings - Webparts  Webpart gallery will open
Step 2: Click New . New ly created webpart are displayed. Check the web part to add into current site.
Step 3: Add web part from web part pane to any webpart page.

Note:
rest of the activities whatever functionality/design we can change as it Usercontrols update to reference folder.

SharePoint Architecture

Server Architecture:


1. The SPFarm object is the highest object within the Windows SharePoint Services object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
2. Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
3. Each SPService object represents a logical service or application installed in the server farm. A service object provides access to server farm-wide settings of the load-balanced service that a respective service instance implements. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, Microsoft SQL Server, the database service, etc. and also objects for Web services, such as Windows SharePoint Services or services in the Microsoft Office system.
4. An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.
5. An SPDatabaseServiceInstance object represents a single instance of a database service running on the server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
6. Each SPWebApplication object represents a load-balanced Web application based in Internet Information Services (IIS). The SPWebApplication object provides access to credentials and other server farm wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property collection of content databases used in the Web application. The SPWebApplication class replaces the obsolete SPVirtualServer class; but it can still be helpful to think of a SPWebApplication object as a virtual server; that is, a set of one or more physical servers that appear as a single server to users.
7. An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a SharePoint Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
8. An SPSiteCollection object represents the collection of site collections within the Web application. The Item property or indexer gets a specified site collection from the collection, and the Add method creates a site collection within the collection.
Site Architecture



1. Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The Microsoft.SharePoint.SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
2. Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
3. Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
4. Each SPField object has members that contain settings for the field.
5. Each SPListItem object represents a single row in the list.

Wednesday, November 11, 2009

Culture Specifcation, Activate PageworkFlow

1) To enable the culture, activate pageworkFlow





2).cs file
using System;
using System.Web.UI.WebControls;
using Telerik.Workflow;
using System.Collections.Generic;
using Telerik.Workflow.WebControls;
using Telerik.Cms.Engine;
using System.Net.Mail;
using Telerik.Cms;
using Telerik.Security;



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


protected void Page_Load(object sender, EventArgs e)
{
if (this.workflow.Controls.Count > 0)
notificationArea.Visible = true;

workflow.Command += new CommandEventHandler(PageWorkflowMenu_Command);

}

void PageWorkflowMenu_Command(object sender, CommandEventArgs e)
{


WorkflowInstance workflow = ((WorkflowMenu)sender).GetWorkflow();

if (workflow != null)
{

List commands = new List();

this.LoadCommands(commands, workflow.Activity.Activities);

int idx = int.Parse((string)e.CommandArgument);


string strRole = string.Empty;


Telerik.Cms.CmsManager manager = new Telerik.Cms.CmsManager();

Telerik.Cms.ICmsPage page = manager.Provider.GetPageByWorkflow(workflow.ID);

System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();


mailMsg.IsBodyHtml = true;

switch (idx)
{


case 0:
mailMsg.Subject = "page pending approval";
strRole = "administrators";
string relativeurl = page.DefaultUrl.Url;
mailMsg.Body += String.Format("The '{0}' page has been sent for approval. Comments:" + hiddenTextArea.Value + " To approve the page, please go to URL: http://{1}{2}?cmspagemode=edit", page.Name, System.Web.HttpContext.Current.Request.Url.Host, relativeurl.Substring(1));
break;

case 1:

mailMsg.Subject = "page approved";
strRole = "Content Editor";
mailMsg.Body += String.Format("The '{0}' page has been approved. Comments:" + hiddenTextArea.Value + " To approve the page, please go to URL: http://{1}/Sitefinity/Admin/Pages.aspx", page.Name, System.Web.HttpContext.Current.Request.Url.Host);

break;

case 2:

mailMsg.Subject = "page declined";
strRole = "Content Editor";
mailMsg.Body += String.Format("The '{0}' page has been declined. Comments:" + hiddenTextArea.Value + " ", page.Name, System.Web.HttpContext.Current.Request.Url.Host);

break;


}


if (!mailMsg.Subject.Equals(string.Empty))
{

string[] usernames = Telerik.Security.UserManager.Default.GetUsersInRole(strRole);
//For every user, send him or her an e-mail
foreach (string username in usernames)
{
System.Web.Security.MembershipUser user = Telerik.Security.UserManager.Default.GetUser(username);
mailMsg.To.Add(user.Email);
}

// Init SmtpClient and send
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (mailMsg.To.Count <= 0)
mailMsg.To.Add(mailMsg.From);

smtpClient.Send(mailMsg);
}




}

}



private void LoadCommands(List commands, IList activities)
{

foreach (Activity act in activities)
{

if (act is EventActivity)

commands.Add((EventActivity)act);

this.LoadCommands(commands, act.Activities);

}

}

}

Adding Control to Module & Data Fetch

If you would like to add the key value. in any inbuilt sitefinity module
say for example. active check box on the module. while fetching a value based on the check pull the data.

1)


2) while fetching the data to your userControl

Namespace
using Telerik.Cms;
using Telerik.Newsletters;
using Telerik.Notifications.Newsletters;
using System.Collections;
using Telerik.Cms.Engine;
using Telerik.Cms.Web;



3).cs

void GetAllNews()
{

NewsManager objnewsManager = new NewsManager("News");
IMetaSearchInfo[] filters = new IMetaSearchInfo[4];
filters[0] = new MetaSearchInfo(MetaValueTypes.DateTime, "Expiration_Date", DateTime.Now, SearchCondition.GreaterOrEqual);
filters[1] = new MetaSearchInfo(MetaValueTypes.ShortText, "Category", ConfigurationManager.AppSettings["NewsandPressrelease"].ToString());
filters[2] = new MetaSearchInfo(MetaValueTypes.Boolean, "Active",true);
filters[3] = new MetaSearchInfo(MetaValueTypes.Boolean, "English", false);
IList lstListOfNewsItems = objnewsManager.Content.GetContent("Publication_Date DESC", filters);
DataTable dtNewsValue = new DataTable();
dtNewsValue.Columns.Add("MoreURL");
dtNewsValue.Columns.Add("Publication_Date");
dtNewsValue.Columns.Add("Title");
dtNewsValue.Columns.Add("Thumbnail");
int icnt = 0;
QFCLib objQFCLib = new QFCLib();

try
{

if (lstListOfNewsItems.Count > 0)
{
foreach (IContent ICntNews in lstListOfNewsItems)
{
string strImageURL = "";

if (ICntNews.GetMetaData("Thumbnail").ToString() != "" && ICntNews.GetMetaData("Thumbnail").ToString() != null)
{
strImageURL = objQFCLib.GetThumbnailURL(ICntNews.GetMetaData("Thumbnail").ToString()) + "?width=87&height=79&proportional=false&decreaseOnly=true";
}
DateTime strPDate = Convert.ToDateTime(ICntNews.GetMetaData("Publication_Date"));
if (strPDate < DateTime.Now)
{
icnt = icnt + 1;
dtNewsValue.Rows.Add(ConfigurationManager.AppSettings["NewsDetails"].ToString() + "?sNewsID=" + ICntNews.ID, strPDate.ToString("MM.dd.yyyy"), ICntNews.GetMetaData("Title"), strImageURL);

}
if (icnt == 5) break;
}
}

if (dtNewsValue.Rows.Count > 0)
{
repeater.DataSource = dtNewsValue;
repeater.DataBind();
dtNewsValue.Dispose();

}
else
{
lblMsg.Text = Resources.ARCommonResource.NoDataFound;
}
}
catch (Exception ex)
{
AppLogger.LogError("GetAllNews Mediacenter() " + ex.Message, AppLogger.Severity.Error);
}

}

4) protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
HtmlGenericControl newsThumbnailImgContainer = (HtmlGenericControl)e.Item.FindControl("newsThumbnailImgContainer");

if (((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[3].ToString() != "")
{
newsThumbnailImgContainer.Visible = true;
}
}
}
catch (Exception ex)
{
AppLogger.LogError("DataBound MediaArchive() " + ex.Message, AppLogger.Severity.Error);
}

}
5)if the content level if any images to get the image
Add to the cs file
#region " Sitefinity Method GetItemUrl "
public string GetItemUrl(string provider, Guid id, bool resolveAsAbsoluteUrl)
{
if (ContentManager.Providers.ContainsKey(provider))
{
IContent cnt = ContentManager.Providers[provider].GetContent(id);
if (cnt != null)
return VirtualPathUtility.ToAbsolute(cnt.UrlWithExtension, HttpContext.Current.Request.ApplicationPath);
}
else
{
ICmsUrlContext urlContext = UrlHelper.GetUrl(id);
if (urlContext != null)
{
SiteMapNode node = urlContext.GetSiteMapNode();
if (node != null)
return VirtualPathUtility.ToAbsolute(node.Url,HttpContext.Current.Request.ApplicationPath);
}
}
return String.Concat("Item not found: [", provider, "]", id);
}
#endregion

#region " Get Thumbnail URL "
public string GetThumbnailURL(string pstrThumbnail)
{

string[] strImage = pstrThumbnail.Split(']');
string strImageURL=string.Empty;
if (strImage.Length == 2)
{
Guid idImage = new Guid(strImage[1]);
strImageURL = GetItemUrl(strImage[0].Substring(1).ToString(), idImage, true);
}
else
{
return pstrThumbnail.Replace("~","");
}
return strImageURL;
}
#endregion
strImageURL = objQFCLib.GetThumbnailURL(ICntNews.GetMetaData("Thumbnail").ToString()) + "?width=87&height=79&proportional=false&decreaseOnly=true";


6) Upload the above ascx on the page leve add controls via and drag.

Sitefinity Admin Tools

Telerik Sitefinity is an ASP.NET 2.0-based Content Management System (CMS) that enables the construction of dynamic, fully editable Web sites.
Sitefinity's out-of-the-box functionality, creating custom modules, and incorporating any ASP.NET 2.0 component in the site could be achieved by using Sitefinity APIs in the Visual Studio development environment.

Default Modules provided by them we can edit add our own controls in the tools.

Adding a Tools(Nothing but an customized module): our own control
1) Create a table in the DB access the link via.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[QFC_Module](
[ModuleID] [int] IDENTITY(1,1) NOT NULL,
[ModuleName] [nvarchar](255) NULL, -- UserMangement
[ModulePath] [nvarchar](500) NULL, -- /ApplicationPath/Folder/UserList.aspx
[Priority] [int] NULL, -- sequence
CONSTRAINT [PK_QFC_Module] PRIMARY KEY CLUSTERED
(
[ModuleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

2) Add a Values manually
ex; 1, UserMangement, /ApplicationPath/Folder/UserList.aspx, Order
customized all modules admin would like to get in a CMS when login.

3)Write sp to get the Modules.



4).cs back based on the role also we can hide the link position. should control in DB level

if (!IsPostBack)
{
QFCLib objQFCLib = new QFCLib();
DataTable dtModules = objQFCLib.GetModules();
string strhtml = "";
try
{
if (dtModules.Rows.Count > 0)
{
foreach (DataRow dr in dtModules.Rows)
{
string strModuleName = dr["ModuleName"].ToString();
Telerik.WebControls.RadWindow rw = new Telerik.WebControls.RadWindow();
rw.Title = strModuleName;
rw.ID = "RW" + dr["ModuleID"].ToString();
rw.Height = Unit.Pixel(600);
rw.Width = Unit.Pixel(800);
rw.VisibleStatusbar = false;
RadWindowManager1.Windows.Add(rw);
strhtml += "

  • " + strModuleName + "
  • ";

    }
    }
    }
    catch (Exception ex)
    {
    AppLogger.LogError("PageLoad ModuleBinding() " + ex.Message, AppLogger.Severity.Error);
    }
    dtModules.Dispose();
    ul_container.InnerHtml = strhtml;

    }
    5)Drag and drop the Usercontrol on sitefinity tools.aspx page. just deactivate all controls placed on the Page.

    Copyright © 2009 Angel