Tuesday, August 20, 2013

Some SQL Query:Taken from net
nth salary in a table
SELECT * /*This is the outer query part */
FROM SPTestTable Emp1
WHERE (n-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM SPTestTable Emp2
WHERE Emp2.Salary > Emp1.Salary)

3rd highest salary
SELECT TOP 1 salary
FROM (
SELECT DISTINCT TOP 3 salary
FROM SPTestTable 
ORDER BY salary DESC) a

ORDER BY salary

Delete duplicate rows from a table.
select distinct * into #temp from SPTestTable truncate table SPTestTable insert SPTestTable select * from #temp drop table #temp

Timer Job

Timer Job

Here is an example of TimerJob where the requirement is to update Manager name in the sharePoint List as per another list where project and project name is there.
I modified the following code from CodeProject.com

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.IO;
namespace TimerJobForMyEffort
{
    class MyTimerJob : SPJobDefinition
    {
        string username = string.Empty;
        string projectname = string.Empty;
        SPSite site;
        SPWeb web;
        SPList ManagerDetail;
        string pm_Myefforts;
        string CurrentStatus_Myefforts = string.Empty;
        string title_Myefforts = string.Empty;

        public const string jobName = "MyTimerJob";
        public MyTimerJob()
            : base()
        {

        }

        public MyTimerJob(string jobName, SPService service,
               SPServer server, SPJobLockType lockType)
            : base(jobName, service, server, lockType)
        {
            this.Title = "MyTimerJob";
        }

        public MyTimerJob(string jobName, SPWebApplication webapp)
            : base(jobName, webapp, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "MyTimerJob";
        }
        #region execute
        public override void Execute(Guid targetInstanceId)
        {
            try
            {
                SPWebApplication webApp = this.Parent as SPWebApplication;
                SPContentDatabase contentDb = webApp.ContentDatabases[targetInstanceId];

                // SPList list = contentDb.Sites[0].RootWeb.Lists["Products"];

                //   SPWebApplication webApp = this.Parent as SPWebApplication;
                site = webApp.Sites["/"];
                web = webApp.Sites["/"].AllWebs["MyIntranet"];
                SPList list = web.Lists.TryGetList("MyEfforts");

                web = site.AllWebs["MyIntranet"];
                web.AllowUnsafeUpdates = true;
                // SPList list = web.Lists["MyEfforts"];
                ManagerDetail = web.Lists["MyProjectDetail"];
                //SPListItem item = properties.ListItem;
                SPQuery query = new SPQuery();
                query.Query = "<Query></Quyery>";
                SPListItemCollection itemcoll_My = list.GetItems(query);
                foreach (SPListItem item in itemcoll_My)
                {
                    username = item["User"].ToString();
                    projectname = Convert.ToString(item["ProjectName"]);
                    if (projectname != string.Empty)
                    {
                        string pm_name = GetManagerDetail("");
                        if (username != pm_name)
                        {
                            item["Manager"] = pm_name;
                            item.Update();
                            string CurrentStatus = Convert.ToString(item["CurrentStatus"]);
                        }
                        else
                        {
                            string rm = GetRMfromMasterTable("");
                            item["Manager"] = rm;
                            item.Update();
                        }
                        pm_Myefforts = Convert.ToString(item["Manager"]);
                        title_Myefforts = Convert.ToString(item.Title);
                        CurrentStatus_Myefforts = GetStusFromWeeklyEffortsDetail("");
                        item["CurrentStatus"] = CurrentStatus_Myefforts;
                        item.SystemUpdate();

                    }

                }
                web.Dispose();
                site.Dispose();


            }
            catch (Exception ex)
            { System.Diagnostics.EventLog.WriteEntry("Execute", ex.Message); }

        }
        #endregion execute



        #region GetCurrentStatus
        private string GetStusFromWeeklyEffortsDetail(string CurrentStatus)
        {
            string[] strArr = null;
            string user_name = string.Empty;
            string str = username;
            string strspecialchar = "#";

            if (str.Contains(strspecialchar))
            {

                char[] splitchar = { '#' };

                strArr = str.Split(splitchar);

                for (int i = 0; i <= strArr.Length - 1; i++)
                {
                    user_name = Convert.ToString(strArr[strArr.Length - 1]);
                }
            }
            string[] strArr_pm = null;
            string pm_name = string.Empty;
            string str_pm = pm_Myefforts;
            string strspecialchar_pm = "#";

            if (str_pm.Contains(strspecialchar_pm))
            {

                char[] splitchar_pm = { '#' };

                strArr_pm = str_pm.Split(splitchar_pm);

                for (int i = 0; i <= strArr_pm.Length - 1; i++)
                {
                    pm_name = Convert.ToString(strArr_pm[strArr_pm.Length - 1]);
                }
            }

            SPList list_WeeklyEffortsDetail = web.Lists["WeeklyEffortsDetails"];

            SPQuery query_WeeklyEffortsDetail = new SPQuery();
            query_WeeklyEffortsDetail.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + title_Myefforts + "</Value></Eq><And><Eq><FieldRef Name='User' /><Value Type='User'>" + user_name + "</Value></Eq><Eq><FieldRef Name='Project_x0020_Manager' /><Value Type='User'>" + pm_name + "</Value></Eq></And></And></Where>";
            SPListItemCollection itemcoll_WeeklyEffortsDetail = list_WeeklyEffortsDetail.GetItems(query_WeeklyEffortsDetail);
            if (itemcoll_WeeklyEffortsDetail.Count != 0)
            {
                SPListItem item_WeeklyEffortsDetail = itemcoll_WeeklyEffortsDetail[0];
                CurrentStatus = Convert.ToString(item_WeeklyEffortsDetail["CurrentStatus"]);
            }
            return CurrentStatus;
        }
        #endregion GetCurrentStatus

        #region GETRM
        private string GetRMfromMasterTable(string rm)
        {

            string[] strArr = null;
            string user_name = string.Empty;
            string str = username;
            string strspecialchar = "#";

            if (str.Contains(strspecialchar))
            {

                char[] splitchar = { '#' };

                strArr = str.Split(splitchar);

                for (int i = 0; i <= strArr.Length - 1; i++)
                {
                    user_name = Convert.ToString(strArr[strArr.Length - 1]);
                }
            }
            SPList list_mastertable = web.Lists["MasterTable"];
            SPQuery query_mastertable = new SPQuery();
            //query_mastertable.Query = "<Where><Eq><FieldRef Name='User' /><Value Type='User'>" + username + "</Value></Eq></Where>";
            query_mastertable.Query = "<Where><Eq><FieldRef Name='Emp_x0020_Name' /><Value Type='User'>" + user_name + "</Value></Eq></Where>";
            SPListItemCollection itemcoll_mastertable = list_mastertable.GetItems(query_mastertable);
            if (itemcoll_mastertable.Count != 0)
            {
                SPListItem item_mastertable = itemcoll_mastertable[0];
                rm = Convert.ToString(item_mastertable["MyManager"]);
            }
            return rm;
        }
        #endregion GETRM
        private string GetManagerDetail(string pmname)
        {
            SPQuery query = new SPQuery();
            query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + projectname + "</Value></Eq></Where>";
            SPListItemCollection itemcoll = ManagerDetail.GetItems(query);
            if (itemcoll.Count != 0)
            {
                SPListItem item_podetails = itemcoll[0];
                pmname = Convert.ToString(item_podetails["Manager"]);
            }
            return pmname;
        }

    }
}

Feature Receiver for TimerJob
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace TimerJobForMyEffort.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("3df123c8-0874-4ddb-9f1b-2345034bf97f")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        const string JobName = "MyTimerJob";
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            DeleteJob(site); // Delete Job if already Exists

            CreateJob(site); // Create new Job

        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            DeleteJob(properties.Feature.Parent as SPSite); // Delete the Job

        }
        private static void DeleteJob(SPSite site)
        {
            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
                if (job.Name == JobName)
                    job.Delete();
        }

        private static void CreateJob(SPSite site)
        {
            TaskWeekTimerJob job = new TaskWeekTimerJob(JobName, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.BeginSecond = 0;
            schedule.EndSecond = 5;
            schedule.Interval = 5;

            job.Schedule = schedule;
            job.Update();
        }



        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}


Monday, August 19, 2013

Connectable WebPart in SharePoint

Connectable WebPart in SharePoint:
Note: I got the following code somewhere in net and tested it on my system.It works fine.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace customProject

{

    public interface IProject

    {

        int Id { get; }

        string Name { get; }

    }

}

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using customProject;

namespace ProviderClass

{

    public class Provider:System.Web.UI.WebControls.WebParts.WebPart,IProject

    {

        DropDownList _projectPicker = null;

        #region IProject Members

 

        public int Id

        {

            get

            {

                return int.Parse(_projectPicker.SelectedValue);

                //throw new NotImplementedException();

            }

        }

 

        public string Name

        {

            get

            {

                return _projectPicker.SelectedItem.ToString();

                //throw new NotImplementedException();

            }

        }

 

        #endregion

        protected override void CreateChildControls()

        {

            try

            {

                _projectPicker = new DropDownList();

                using (SPSite spSite = new SPSite(SPContext.Current.Web.Url)) using (SPWeb spWeb = spSite.OpenWeb())

                {

                    SPList projectsList = spWeb.Lists["Projects"];

                    foreach (SPListItem project in projectsList.Items)

                    {

                        _projectPicker.Items.Add(new ListItem(project.Title, project.ID.ToString()));

                        _projectPicker.AutoPostBack = true;

                        this.Controls.Add(_projectPicker);

                    }

                }

            }

            catch (Exception ex)

            {

                this.Controls.Clear();

                this.Controls.Add(new LiteralControl(ex.Message));

                base.CreateChildControls();

            }

        }

        [ConnectionProvider("Project Name and ID")]

        public IProject NameDoesNotMatter() { return this; }

    }

}

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using ProviderClass;

using customProject;

namespace Customerclass

{

    public class Consumer : System.Web.UI.WebControls.WebParts.WebPart

    {

        IProject _provider = null;

      

        Label _lbl=null ;

        [ConnectionConsumer("Project Name and ID")]

        public void ThisNameDoesNotMatter(IProject providerInterface)

        {

            _provider = providerInterface;

 

        }

 

        protected override void CreateChildControls()

        {

            try {

              _lbl = new Label();

                if (_provider != null)

              

                {

                    _lbl.Text = _provider.Name.ToString() + " was selected.";

                }

                else

                {

                    _lbl.Text = "Nothing was selected.";

                }

                this.Controls.Add(_lbl); }

            catch (Exception ex)

            {

                this.Controls.Clear(); this.Controls.Add(new LiteralControl(ex.Message));

                base.CreateChildControls();

            }

       

        }

      

     

    }

}