Tuesday 7 May 2013

Connect Chart Web Part to SQL database in Sharepoint 2010

1. This blog shows you how to provide data for OOB Charting Web part in Sharepoint 2010. First insert the chart web part into you page as shown in fig. below









2. Create custom web part and specify the database connection as I am retrieving chart data from sql server 2008 database. Copy paste following code into webpart and deploy web part to site collection

[ToolboxItemAttribute(false)]
    [Serializable]
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class ChartDataProviderWebPart : WebPart, IWebPartTable
    {

        SqlDataAdapter sda;
        Timer _timer;
        DataTable _table;
        Label _lblMessage;
        string databaseConnectionString = "Data Source=.;Initial Catalog=Demo_Database;user id=username;password=yourpassword;"; // Change setting

        protected override void CreateChildControls()
        {
// Timer control added to refresh chart after every 30 second
            _timer = new Timer();
            this._timer.Interval = 30000;
            this._timer.Tick += new EventHandler<EventArgs>(_timer_Tick);
            this._timer.Enabled = true;
            this.Controls.Add(this._timer);
            this.Controls.Add(this._lblMessage);
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            this._lblMessage.Text = string.Format("Last updated @ {0} ", DateTime.Now.ToString());
        }

        public ChartDataProviderWebPart()
        {
            try
            {
                _table = new DataTable();
                this._lblMessage = new Label();
                this.sda = new SqlDataAdapter("select * from tblData order by name", new SqlConnection(this.databaseConnectionString));
                this.sda.Fill(this._table);
            }
            catch (Exception ex)
            {
                this._table.Columns.Add(new DataColumn("Name"));
                this._table.Columns.Add(new DataColumn("Value"));
            }
        }

        public void GetTableData(TableCallback callback)
        {

            callback(_table.Rows);
        }

        public PropertyDescriptorCollection Schema
        {
            get
            {
                return TypeDescriptor.GetProperties(this._table.DefaultView[0]);
            }
        }

        public bool ConnectionPointEnabled
        {
            get
            {

                object o = ViewState["ConnectionPointEnabled"];
                return (o != null) ? (bool)o : true;
            }
            set
            {
                ViewState["ConnectionPointEnabled"] = value;
            }
        }

        [ConnectionProvider("Table", typeof(DataTableProviderConnectionPoint), AllowsMultipleConnections = true)]
        public IWebPartTable GetConnectionInterface()
        {
            return new ChartDataProviderWebPart();
        }


    }
    public class DataTableProviderConnectionPoint : ProviderConnectionPoint
    {
        public DataTableProviderConnectionPoint(MethodInfo callbackMethod, Type interfaceType, Type controlType, string name, string id, bool allowsMultipleConnections)
            : base(callbackMethod, interfaceType, controlType, name, id, allowsMultipleConnections)
        {

        }

        public override bool GetEnabled(Control control)
        {
            return ((ChartDataProviderWebPart)control).ConnectionPointEnabled;
        }

    }

3. Go to page where you inserted chart web part, insert above deployed webpart on same page. Click on Data & Appearance from chart web part -> Click on Connect Chart To Data





4. After clicking on Connect Chart To Data you got Step by Step Data Connection Wizard
  • Step 1: Choose Connect to another web part option for this step and click on Next button
  • Step 2: Connect to another Web Part in drop down you found the name of web part that you deployed now
  • Step 3: On retrieve data step select  Table as source data format in data format dropdown and click on next button

  • Go Es her
  •   
  • Step 4: On Bind Chart to Data, set Y Field to  "Value" and X Field to "Name" as shown in fig. below and click on Finish

An exception occurred when trying to issue security token in SharePoint 2010


Security Token Service Application Error:
Problems:  Unable to Login with Claim base authentication to SharePoint 2010 Site
Errors
An exception occurred when trying to issue security token: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.
Or
WebHost failed to process a request.
 Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/15688314
 Exception: System.ServiceModel.ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation.  The exception message is: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.. ---> System.MissingMethodException: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.BuildExtendedProtectionPolicy(ExtendedProtectionTokenChecking tokenChecking, ExtendedProtectionFlags flags, List`1 spnList)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.GetExtendedProtectionPolicy(ConfigurationElement element)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.ProcessWindowsAuthentication(String siteName, String virtualPath, HostedServiceTransportSettings& transportSettings)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.CreateTransportSettings(String relativeVirtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetTransportSettings(String virtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetAuthenticationSchemes(String virtualPath)
   at System.ServiceModel.Channels.HttpChannelListener.ApplyHostedContext(VirtualPathExtension virtualPathExtension, Boolean isMetadataListener)
   at System.ServiceModel.Channels.HttpTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHost.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)
 Process Name: w3wp
 Process ID: 4780

Solution: Uninstall Security Update No. - KB2756920

Sunday 10 February 2013

Using PowerShell Command for Visual Upgrade

Upgrade Visual from SharePoint 2007 to SharePoint 2010 after restoring Content Database on SharePoint 2010 Server.

When we restore content database in SharePoint 2010 from SharePoint 2007, it required to upgrade the Visual to Version 4. Following command will update all the site and sub-sites for provided content database.


$ContentDatabaseName = Get-SPContentDatabase WSS_Content_SharePoint_Database_Restore

$ContentDatabaseName.Sites | Get-SPWeb -limit all | ForEach-Object {$_.UIversion = 4; $_.UIVersionConfigurationEnabled = $false; $_.update()}

SPLongOperation error for ItemAdding Event In SharePoint 2010

We recently upgrade one of our project from SharePoint 2007 to SharePoint 210. In that project we user event handler for list. In ItemAdding event we use to create new site which takes times for creation. So we use SPLongOperation to handle it  but in SharePoint 2010 its same code gives error for "Object reference null" for SPLongOperation being statement.
So we had following workaround for this problem.

Create Web Part with following Code and add this web part to publishing Page

protected override void CreateChildControls(){
 if (this.Page.Request.QueryString["Processid"] != null)
            {           

                using (SPLongOperation ctx = new SPLongOperation(this.Page))
                {
                    try
                    {
                        ctx.LeadingHTML = "Please wait while your operation is being executed.";
                        ctx.TrailingHTML = "Site is being created. Please wait....";
                        ctx.Begin();

                        System.Threading.Thread.Sleep(5000);
                        string eid = this.Page.Request.QueryString["Processid"].ToString();
                        int count = 1;
                        while (true)
                        {
                            using (SPWeb web = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ID))
                            {
                                if (web.Properties[eid].ToString() != "Completed" && count < 18)
                                {

                                    System.Threading.Thread.Sleep(5000);
                                    count++;
                                }
                                else
                                    break;
                            }
                        }
                        ctx.End(this.Page.Request.QueryString["h"].ToString());
                    }
                    catch (Exception ex)
                    {
                        this.lbl.Text = ex.Message.ToString() + Environment.NewLine + ex.StackTrace.ToString() ;
                    }
                }
            }
}

In event handler modify ItemAdding event as follows

 public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            string guid
                = string.Format("ProcessId{0}_{1}", DateTime.Now.ToString("MMddyyyy"), Guid.NewGuid().ToString());
            Thread thread = new Thread(() => FunctionName(properties,guid));
            thread .Start();

            properties.Status = SPEventReceiverStatus.CancelNoError;
            properties.Cancel = true;
            SPUtility.Redirect({Url of page on which out put above webpart}, SPRedirectFlags.Default, _currentContext,string.Format ("Processid={0}&h={1}",guid , properties.RelativeWebUrl));
        }

Hope this work for you also

How to open hyperlinks into modal dialog box in SharePoint 2010


SharePoint 2010 provides new feature "Modal dialog box". In this blog we shows how to open hyperlinks in modal dialog box using simple jquery selector.

Declaration syntax for modal dialog box is as follows

//Using the DialogOptions class.
var options = SP.UI.$create_DialogOptions();

options.title = "Dialog box title";
options.width = 300;
options.height = 500;
options.url = "PageUrl";

SP.UI.ModalDialog.showModalDialog(options);


//Using a generic object.
var options = {
    title: "Dialog box title",
    width: 300,
    height: 500,
    url: "PageUrl" };
SP.UI.ModalDialog.showModalDialog(options);


Now we put above modal dialog syntax in jquery selector

$("[href(selection attributes)'Condition']").click ( function () {
                                                                   var options = {
                                                                   title: "Dialog box title",
                                                                   width: 300,
                                                                   height: 500,
                                                                   url: $(this).attr('href')
                                                                 };
                                                                   return false;// required to override default behavior of hyperlink tag
                                                                });

We have to open link which contains the query string parameters "ShowInDialog=1", then selection condition for it
$("[href*='ShowInDialog=1']")

Attribute for selection 
!= is not equal
^= is starts with
$= is ends with
*= is contains



Example for selecting hyper links which contains query string parameter "ShowInDialog=1" 
$("[href*='ShowInDialog=1']").click ( function () {

                                                                   var options = {
                                                                   title: "Dialog box title",
                                                                   width: 300,
                                                                   height: 500,
                                                                   url: $(this).attr('href')
                                                                 };
                                                                   return false;// required to override default behavior of hyperlink tag
                                                                });

Hide Sign in as Different User in SharePoint 2010


Open WelCome.ascx file in visual studio. you found this file in controltemplates folder. We want to show only sign out option for welcome menu. Remove menu templates as per your required and save as "Custom_Welcome.ascx"



<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Control Language="C#" Inherits="Microsoft.SharePoint.WebControls.Welcome,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c"   AutoEventWireup="false" compilationMode="Always" %>  <SharePoint:PersonalActions accesskey="<%$Resources:wss,personalactions_menu_ak%>" ToolTip="<%$Resources:wss,open_menu%>" runat="server" id="ExplicitLogout" Visible="false"> <CustomTemplate> <SharePoint:FeatureMenuTemplate runat="server" FeatureScope="Site" Location="Microsoft.SharePoint.StandardMenu" GroupId="PersonalActions" id="ID_PersonalActionMenu" UseShortId="true" > <SharePoint:MenuItemTemplate runat="server" id="ID_Logout" Text="<%$Resources:wss,personalactions_logout%>" Description="<%$Resources:wss,personalactions_logoutdescription%>" MenuGroupId="200" Sequence="300" UseShortId="true" />   </SharePoint:FeatureMenuTemplate> </CustomTemplate></SharePoint:PersonalActions><SharePoint:ApplicationPageLink runat="server" id="ExplicitLogin" ApplicationPageFileName="Authenticate.aspx" AppendCurrentPageUrl="true" Text="<%$Resources:wss,login_pagetitle%>" style="display:none" Visible="false" />



Open site master page on page search for register tag of  welcome control

<%@ Register TagPrefix="wssuc" TagName="Welcome" src="~/_controltemplates/Welcome.ascx" %>
replace with src="~/_controltemplates/Custom_Welcome.ascx" %>

Refresh the page and get happy...

An exception occurred when trying to issue security token

Security Token Service Application Error:
Problems:  Unable to Login with Claim base authentication to SharePoint 2010 Site
Errors
An exception occurred when trying to issue security token: The requested service, 'http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc' could not be activated. See the server's diagnostic trace logs for more information.
Or
WebHost failed to process a request.
 Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/15688314
 Exception: System.ServiceModel.ServiceActivationException: The service '/SecurityTokenServiceApplication/securitytoken.svc' cannot be activated due to an exception during compilation.  The exception message is: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.. ---> System.MissingMethodException: Method not found: 'System.String System.ServiceModel.Activation.Iis7Helper.ExtendedProtectionDotlessSpnNotEnabledThrowHelper(System.Object)'.
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.BuildExtendedProtectionPolicy(ExtendedProtectionTokenChecking tokenChecking, ExtendedProtectionFlags flags, List`1 spnList)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.WebConfigurationManagerWrapper.GetExtendedProtectionPolicy(ConfigurationElement element)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.ProcessWindowsAuthentication(String siteName, String virtualPath, HostedServiceTransportSettings& transportSettings)
   at System.ServiceModel.WasHosting.MetabaseSettingsIis7V2.CreateTransportSettings(String relativeVirtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetTransportSettings(String virtualPath)
   at System.ServiceModel.Activation.MetabaseSettingsIis.GetAuthenticationSchemes(String virtualPath)
   at System.ServiceModel.Channels.HttpChannelListener.ApplyHostedContext(VirtualPathExtension virtualPathExtension, Boolean isMetadataListener)
   at System.ServiceModel.Channels.HttpTransportBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.MessageEncodingBindingElement.InternalBuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BinaryMessageEncodingBindingElement.BuildChannelListener[TChannel](BindingContext context)
   at System.ServiceModel.Channels.BindingContext.BuildInnerChannelListener[TChannel]()
   at System.ServiceModel.Channels.Binding.BuildChannelListener[TChannel](Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, BindingParameterCollection parameters)
   at System.ServiceModel.Description.DispatcherBuilder.MaybeCreateListener(Boolean actuallyCreate, Type[] supportedChannels, Binding binding, BindingParameterCollection parameters, Uri listenUriBaseAddress, String listenUriRelativeAddress, ListenUriMode listenUriMode, ServiceThrottle throttle, IChannelListener& result, Boolean supportContextSession)
   at System.ServiceModel.Description.DispatcherBuilder.BuildChannelListener(StuffPerListenUriInfo stuff, ServiceHostBase serviceHost, Uri listenUri, ListenUriMode listenUriMode, Boolean supportContextSession, IChannelListener& result)
   at System.ServiceModel.Description.DispatcherBuilder.InitializeServiceHost(ServiceDescription description, ServiceHostBase serviceHost)
   at System.ServiceModel.ServiceHostBase.InitializeRuntime()
   at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceHost.InitializeRuntime()
   at System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout)
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   --- End of inner exception stack trace ---
   at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
   at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath)
 Process Name: w3wp
 Process ID: 4780
Solution: Uninstall Security Update No. - KB2756920
http://blogs.technet.com/b/praveenh/archive/2013/01/15/issue-found-with-net-framework-3-5-1-security-update-kb2756920.aspx