Saturday, November 17, 2012

How to restrict the '/_layouts/viewlsts.aspx' page from anonymous users in SharePoint 2010

Reference Links:
Locking down Office SharePoint Server sites
C:\inetpub\wwwroot\wss\VirtualDirectories\1234\web.config
<location path="_layouts/viewlsts.aspx">
            <system.web>
                  <authorization>
                       <allow users="domainname\user1,domainname\user2"/>
                        <deny users="?" />
                        <deny users="*" />
                  </authorization>
            </system.web>
      </location>
Inline image 1

Saturday, October 20, 2012

Update Shared Document Custom Fields Using Server Object Model in SharePoint 2010 Timer Job

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Workflow;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Collections;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Publishing;

namespace SP2010_TimerJob
{
    class SP2010_TimerJob
    {
    }

    public class SP2010_Timer_Job : SPJobDefinition
    {
        DateTime today = DateTime.Now;
        public string[] strArray;
        StringBuilder sbwfIds = new StringBuilder();
        StringBuilder sbResignationID = new StringBuilder();
        public bool isWFRunning;
        public string conString;

        public string name, passport, dept, nationality;

        #region Sql Variables
        public SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter sqlDa;
        DataTable dt;
        #endregion

        public const string JOB_DEFINITION_NAME = "SP2010_TimerJob";
        public const string JOB_DEFINITION_TITLE = "SP2010 TimerJob";

        public SP2010_Timer_Job()
        {
            Title = JOB_DEFINITION_TITLE;
        }

        public SP2010_Timer_Job(SPWebApplication webApplication)
            : base(JOB_DEFINITION_NAME, webApplication, null, SPJobLockType.Job)
        {
            Title = JOB_DEFINITION_TITLE;
        }

        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            SPWebApplication webApp = WebApplication;
            try
            {
                using (var site = new SPSite(webApp.Sites[0].ID))
                {
                    using (var oWebsite = site.OpenWeb())
                    {
                        //SPListCollection collLists = oWebsite.Lists;
                        SPList oList = oWebsite.Lists["Shared Documents"];
                        if (oList.Title == "Shared Documents")
                        {
                            if (oList.BaseType == SPBaseType.DocumentLibrary)
                            {
                                SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oList;

                                if (!oDocumentLibrary.IsCatalog && oList.BaseTemplate != SPListTemplateType.XMLForm)
                                {
                                    SPFolder folder = oWebsite.GetFolder(System.Web.Configuration.WebConfigurationManager.AppSettings["PassportCopyUrl"].ToString());
                                    if (folder.Exists)
                                    {
                                        SPFileCollection collFile = folder.Files;
                                        oWebsite.AllowUnsafeUpdates = true;
                                        foreach (SPFile oFile in collFile)
                                        {

                                            if (!Convert.ToBoolean(oFile.Item["Refiled"]))
                                            {
                                                if (oFile.Item["Employee_x0020_ID"] != null)
                                                {
                                                    PassportCopy(Convert.ToInt32(oFile.Item["Employee_x0020_ID"].ToString()));

                                                    if (!string.IsNullOrEmpty(name))
                                                    {
                                                        oFile.Item["Employee_x0020_Name"] = name.ToString().Trim();
                                                    }
                                                    oFile.Item["Refiled"] = System.Web.Configuration.WebConfigurationManager.AppSettings["Refiled"].ToString();
                                                    oFile.Item.Update();
                                                    oDocumentLibrary.Update();
                                                    oWebsite.Update();
                                                }
                                            }
                                        }
                                    }
                                    oWebsite.AllowUnsafeUpdates = false;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }


        #region Sql Connection
        public void SqlConnection()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                con = new SqlConnection(System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"].ToString());

                if (con != null)
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                }
            });
        }
        #endregion


        #region Stored Procedure PassportCopy

        public void PassportCopy(int EmpID)
        {
            try
            {
                SqlConnection();
                cmd = new SqlCommand("sp_PassportCopy", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@userid", EmpID); //.DbType = DbType.Int32;
                sqlDa = new SqlDataAdapter(cmd);
                dt = new DataTable();
                sqlDa.Fill(dt);
                if (dt != null)
                {
                    if (dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["AAA"] != null)
                        {
                            name = dt.Rows[0]["AAA"].ToString();
                        }
                        if (dt.Rows[0]["BBB"] != null)
                        {
                            passport = dt.Rows[0]["BBB"].ToString();
                        }
                        if (dt.Rows[0]["CCC"] != null)
                        {
                            dept = dt.Rows[0]["CCC"].ToString();
                        }
                        if (dt.Rows[0]["DDD"] != null)
                        {
                            nationality = dt.Rows[0]["DDD"].ToString();
                        }
                    }
                }
            }
            catch (Exception obj)
            {

            }

            finally
            {
                con.Close();
            }
        }
        #endregion
    }
}


after that go to --> C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\OWSTIMER.EXE.CONFIG  and edit and change as follows.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
  </runtime>
<appSettings>
<add key="ConnectionString" value="Data Source=Trainingsql2k8;Initial Catalog=SP2010_PRODUCTION;Trusted_Connection=True" />
<add key="PassportCopyUrl" value="/shared documents/Passport Copy" />
<add key="Refiled" value="1" />
</appSettings>
</configuration> 

note: after add above configuration file mate sure restart the SharePoint timer job service in services (start -> run -> services.msc)

following code is SharePoint 2010 timer job code

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Linq;

namespace SP2010_TimerJob.Features.SP2010_TimerJob_Feature
{
    /// <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("327dbb7a-1dcb-4c80-8c61-96d276660370")]
    public class SP2010_TimerJob_FeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp == null) throw new Exception("webApp");

            var FCJOB = from SPJobDefinition job in webApp.JobDefinitions
                        where job.Name == SP2010_Timer_Job.JOB_DEFINITION_NAME 
                        select job;
            if (FCJOB.Count() > 0)
                FCJOB.First().Delete();


            var DailySchedule = new SPDailySchedule
            {
                BeginHour = 0,
                BeginMinute = 0,
                BeginSecond = 0,
                EndHour = 2,
            };

            var myJOb = new SP2010_Timer_Job(webApp)
            {
                Schedule =  DailySchedule,
                IsDisabled = false
            };

            myJOb.Update();
        }


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

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            var webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp == null) throw new Exception("webApp");

            var FCJOB = from SPJobDefinition job in webApp.JobDefinitions
                        where job.Name == SP2010_Timer_Job.JOB_DEFINITION_NAME
                        select job;
            if (FCJOB.Count() > 0)
                FCJOB.First().Delete();
        }


        // 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)
        //{
        //}
    }
}



Update Shared Document Custom Fields Using Client Object Model in SharePoint 2010


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;

namespace MYItemUpdate
{
    class Program
    {
        static void Main(string[] args)
        {
            getfiles();
        }

        private static void getfiles()
        {
            ClientContext clientContext = new ClientContext("http://server-sp:6677/sites/HRDocuments/");
            clientContext.Credentials = new System.Net.NetworkCredential("username1""pass@1234","myDomineName1");
            List list = clientContext.Web.Lists.GetByTitle("Shared Documents");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"<View Scope='Recursive'></View>";

            camlQuery.FolderServerRelativeUrl = "/sites/HRDocuments/Shared Documents/Pay Slips";

            SP.ListItemCollection listItems = list.GetItems(camlQuery);
            clientContext.Load(listItems);
            clientContext.ExecuteQuery();

            SP.ListItem itemOfInterest = listItems[0];
            Console.WriteLine(itemOfInterest["Employee_x0020_ID"].ToString());
            itemOfInterest["Employee_x0020_ID"] = "66";
            itemOfInterest.Update();
            clientContext.ExecuteQuery();

            listItems = list.GetItems(camlQuery);
            clientContext.ExecuteQuery();

        }
    }
}

Tuesday, August 14, 2012

Windows Commutation Foundation Day 1

.Net Support for Distributed Programming:-
        As of today using .net have 3 different choices for developing distributed applications.
1. .Net Remoting Architecture [Broker architecture]
2. Asp.Net web services
3. WCF (Windows Communication Foundation)

SOA (Service Oriented Application):-
  A Service means Program Written for other Programmers (not for end users)

Today Best Service:-
       which is consumable to all and also consumable in most simple method.

.Net Remoting:-
     with .Net Remoting we can build distributed application between two .Net environment. that is CLR to CLR communication.
Remoting is set of libraries to distribute other .Net environment [CLR]

System.Net:- all Network classed available
Channel:- it is carrier, convert request to format. it is carry data as stream.
Dispatcher:- it takes 'deserilized' data and gave to 'Int Add(int x, int y) as a local request.

SOAP (Simple Object Access Protocol):-
  SOAP is a one type of formatter.
  1. public formatter
  2. XML based formatter

Binary:- this is another type formatter:- 
1. CLR won formate
2. Only understand by CLR

note: .Net remoting architecture support only two formatter as follows
1. SOAP  [ in network firewall will not block, firewall friendly]
2. Binary (Proporty Protocol) [in network firewall will be block, firewall not friendly]

.Net Remoting Architecture Support 3 channels:
1. HTTP [slow] [does have format like header, body, footer]
2. TCP [second fast] [any where we can use] [does not have format like header, body, footer]
3. IPC [fast] [Inter Program Communication]

HTTP:-[Hyper Text Transfer Protocol]
  Built top of 'TCP' protocol
  firewall friendly, will not block by firewall
  HTTP have format like header/body/footer/plain text

TCP:- [Transmission Control Protocol]
  No format required like header, body, footer
  TCP block by firewall
--------------------------------------------------------------------------------------
Below image getting form Facebook, nice to share this


Monday, July 23, 2012

Programming with Content Types in SharePoint 2010

// Programming with Content Types.
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Linq;
namespace SPHOL302_Ex2.Features.Feature1
{  
    [Guid("8c019752-8354-430b-ba1c-bed7daac7c48")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType newAnnouncement = spWeb.ContentTypes.Cast<SPContentType>().FirstOrDefault(c => c.Name == "New Announcements");
                if (newAnnouncement != null)
                {
                    newAnnouncement.Delete();
                }
                SPField newField = spWeb.Fields.Cast<SPField>().FirstOrDefault(f => f.StaticName == "Team Project");
                if (newField != null)
                {
                    newField.Delete();
                }
                SPContentType myContentType = new SPContentType(spWeb.ContentTypes["Announcement"], spWeb.ContentTypes, "New Announcements");
                myContentType.Group = "Custom Content Types";
                spWeb.Fields.Add("Team Project", SPFieldType.Text, true);
                SPFieldLink projFeldLink = new SPFieldLink(spWeb.Fields["Team Project"]);
                myContentType.FieldLinks.Add(projFeldLink);
                SPFieldLink companyFieldLink = new SPFieldLink(spWeb.Fields["Company"]);
                myContentType.FieldLinks.Add(companyFieldLink);
                spWeb.ContentTypes.Add(myContentType);
                myContentType.Update();
            }
        }
        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType myContentType = spWeb.ContentTypes["New Announcements"];
                spWeb.ContentTypes.Delete(myContentType.Id);
                spWeb.Fields["Team Project"].Delete();
            }
        }
        // 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)
        //{
        //}
    }
}
----------------------------------------------------------------------------------------------------------------------

ECM(Enterprise Content Management) Create Taxonomy Programatically in SharePoint 2010




//Application Management -> Service Applications -> Manage service applications -> Managed Metadata Service
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.SharePoint.WebControls;
namespace ECM_CreateTaxonomy.Layouts.ECM_CreateTaxonomy
{
    public partial class CreateTaxonomy : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void createTaxonomyButton_Click(object sender, EventArgs e)
        {
            SPSite currentSite = SPContext.Current.Site;
            TaxonomySession session = new TaxonomySession(currentSite);
            TermStore termstore = session.TermStores["Managed Metadata Service"];
            Group plantsGroup = termstore.CreateGroup("Plants");
            TermSet flowersTermSet = plantsGroup.CreateTermSet("Flowers");
            Term tulipsTerm = flowersTermSet.CreateTerm("Tulips", 1033);
            Term orchidsTerm = flowersTermSet.CreateTerm("Orchids", 1033);
            Term daffodilsTerm = flowersTermSet.CreateTerm("Daffodils", 1033);
            Term vanillaTerm = orchidsTerm.CreateTerm("Vanilla", 1033);
            vanillaTerm.SetDescription("A common orchid whose pods are used in desserts", 1033);
            vanillaTerm.CreateLabel("Vanilla planifolia", 1033, false);
            vanillaTerm.CreateLabel("Flat-leaved vanilla", 1033, false);
            try
            {
                termstore.CommitAll();
                resultsLabel.Text = "Taxonomy created successfully";
            }
            catch (Exception ex)
            {
                resultsLabel.Text = "There was an error: " + ex.Message;
            }
        }
    }
}
-------------------------------------------------------------------------------------------------------------------------

Create Document Set Programatically In SharePoint 2010





CreateDocumentSet.aspx
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ 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" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateDocumentSet.aspx.cs" Inherits="ECM_CreateDocumentSet.Layouts.ECM_CreateDocumentSet.CreateDocumentSet" DynamicMasterPageFile="~masterurl/default.master" %>
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    <h1>Document Set Creation Demo</h1>
    <p>
        This page creates a new document set in the Shared Documents folder. Document
        sets enable you to manage multiple documents as one. For example, you can submit
        an entire document set as a record in a single operation. You can also apply
        metadata and permissions to every document in the set.  Before you
        can create and use document sets, you must enable the Document Sets feature at
        the site collection level. Then add the Document Set content type to the document
        library where you want to use them.
    </p>
    <p>
        Name: <asp:TextBox ID="nameTextbox" runat="server"></asp:TextBox>
    </p>
    <p>
        Description: <asp:TextBox ID="descriptionTextbox" runat="server"></asp:TextBox>
    </p>
    <asp:Button ID="createDocSetButton" OnClick="createDocSetButton_Click" runat="server" Text="Create Document Set" />
    <asp:Label ID="resultLabel" runat="server" Text=""></asp:Label>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    ECM Document Set Creation
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    ECM Document Set Creation
</asp:Content>
---------------------------------------------------------------------------------------------------------------
CreateDocumentSet.aspx.cs
using System;
using System.Collections;
using Microsoft.Office.DocumentManagement.DocumentSets;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace ECM_CreateDocumentSet.Layouts.ECM_CreateDocumentSet
{
    /// <summary>
    /// This application page creates a document set based on the default document set
    /// content type.
    /// </summary>
    /// <remarks>
    /// You must have enabled the site collection level Document Sets feature, and added
    /// the Document Set content type to the document library, before you can create
    /// document sets.
    /// </remarks>
    public partial class CreateDocumentSet : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void createDocSetButton_Click(object sender, EventArgs e)
        {
            //Get the Shared Documents document library
            SPWeb currentWeb = SPContext.Current.Web;
            SPDocumentLibrary sharedDocsLib = (SPDocumentLibrary)currentWeb.Lists["Shared Documents"];
            //You can use a hashtable to populate properties of the document set
            Hashtable docsetProperties = new Hashtable();
            docsetProperties.Add("Name", nameTextbox.Text);
            docsetProperties.Add("DocumentSetDescription", descriptionTextbox.Text);
            //Create the document set
            try
            {
                DocumentSet newDocSet = DocumentSet.Create(sharedDocsLib.RootFolder,
                    nameTextbox.Text, sharedDocsLib.ContentTypes["Document Set"].Id,
                    docsetProperties, true);
                resultLabel.Text = "Document set created";
            }
            catch (Exception ex)
            {
                resultLabel.Text = "An error occurred: " + ex.Message;
            }
        }
    }
}
-------------------------------------------------------------------------------------------------------------------

Featured Post

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API Every Copilot Studio agent is a row in the Dataverse bot t...

Popular posts