Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

SharePoint Add Users To SharePoint Group

Saturday, December 7, 2013



//Add User in SharePoint Groups
public void addUserToGroup(string groupName, string useName)
{
    string strUrl = "http://MySites:9091/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser spUser = web.EnsureUser[userName];

                if (spUser != null)
                {
                    SPGroup spGroup = web.Groups[groupName];
                    if (spGroup != null)
                    spGroup.AddUser(spUser);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}

ensure that user have permission to execute this method.

Helpful Link and Ref:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.ensureuser.aspx
http://msdn.microsoft.com/en-us/library/office/ms414400.aspx
http://gallery.technet.microsoft.com/office/Bulk-remove-Unique-bddd8764

Sunday, June 2, 2013

Report Generating and long Operation Module Dailog

 



        ///


        /// Start Long Operation
        ///
        protected void OperationStart()
        {
            try
            {
                using (SPLongOperation longOp = new SPLongOperation(this.Page))
                {
                    ///title for loading Window
                    longOp.LeadingHTML = "Long Operation Title";
                    //Decp or Message for wait
                    longOp.TrailingHTML = "This may take few seconds.";
                    //Window Start
                    longOp.Begin();
                    //--------------------------
                    //code for long running operation is here
                    //---------------------
                    System.Threading.Thread.Sleep(99999);
                    EndOperation(longOp);
                }
            }
            catch (ThreadAbortException) { /* Thrown when redirected */}
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(ex.ToString());
            }
        }
        ///
        /// On Operation End  Hendler Perfrom action on Operation completed
        ///
        ///
        protected void EndOperation(SPLongOperation operation)
        {
            HttpContext Currentcontext = HttpContext.Current;
            if (Currentcontext.Request.QueryString["IsDlg"] != null)
            {
                //do you work here
                Currentcontext.Response.Write("");
                Currentcontext.Response.Flush();
                Currentcontext.Response.End();
            }
            else
            {
               
                //
                string SiteURL = SPContext.Current.Web.Url;
                operation.End(SiteURL, SPRedirectFlags.CheckUrl, context, string.Empty);
            }
        }

SharePoint 2010 Close Module Dialog through code







Close Module Dialog SharePoint from server side Code and javascript

Javascript



C#


//current Context
HttpContext Currentcontext = HttpContext.Current;
//Checking  dialog is  open on this page or not
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
//executing javascript for closing pop on runtime;
Currentcontext.Response.Write("");
Currentcontext.Response.Flush();
Currentcontext.Response.End();

}


from update panel

///


/// Call Runtime Javascript Functions
///
/// type Complete Function and js Code
private void CallJavaScriptMethods(string Script)
{
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), Guid.NewGuid().ToString(), Script, true);
}


ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), Guid.NewGuid().ToString(), "window.frameElement.commitPopup();", true);

Retrieve files from a sub folder SharePoint document library with CSOM

Saturday, June 1, 2013

public static void GetAllListItemsInFolder()
{
            ClientContext clientContext = new ClientContext("http://xxxxxx:000");
            List list = clientContext.Web.Lists.GetByTitle("MainLib");
            CamlQuery camlQuery = new CamlQuery();
            camlQuery.ViewXml = @"
                                   
                                   
                               
";            camlQuery.FolderServerRelativeUrl = "/MainLib/HR";
            ListItemCollection listItems = list.GetItems(camlQuery);
            clientContext.Load(listItems);
            clientContext.ExecuteQuery();
            ListItem itemOfInterest = listItems[0];
            string Itemcreator = itemOfInterest.FieldValues["Created_x0020_By"].ToString();
            string Itemtitle = itemOfInterest.FieldValues["Title"].ToString();
        }

SHAREPOITN 2010 Event Receivers Tip

Monday, April 8, 2013

don't  instantiate  SPWeb,SPSite,SPlist or SPListItem Objects with in event reciver. instantiating these Objects in side the event Receiver can cost you  more roundtrips to the database.



don't code like that



  using (SPSite osite = new SPSite(properties.WebUrl))
    {
    using (SPWeb sweb = osite.OpenWeb())
        {
        SPList list = sweb.Lists[properties.ListId];
        SPListItem item = list.GetItemByUniqueId(properties.ListItemId);
     
        }
    }



Code like that

   // Retrieve SPWeb and SPListItem from SPItemEventProperties instead of

// from a new instance of SPSite.
SPWeb web = properties.OpenWeb();
// Operate on the SPWeb object.
SPListItem item = properties.ListItem;
// Operate on an item.

Elevation of Privilege Best Practice

  • Remember that All Elevated Objects Must Remain Inside a RunWithElevatedPrivileges Block.
  •  All Elevated object which created in side the RunWithElevatedPrivileges not  returned to outside of the RunWithElevatedPrivileges block. 
  • If the SPListItem object is passed outside of the RunWithElevatedPrivileges block, it retains its underlying SPRequest object and continues to be elevated. Code that expects to be running under the current user's credentials will have privilege elevation problems if it uses this SPListItem object.



example 

Do not Use RunWithElevatedPrivileges like that


SPSecurity.RunWithElevatedPrivileges(delegate() {

   SPSite osite = SPContext.Current.Site;   

   SPWeb oweb = SPContext.Current.Web;  

// here you need to use oweb object as system user.
      //oweb.CurrentUser.LoginName
 

        });//Close "SPSecurity.RunWithElevatedPrivileges" block




always use using block with SPSite ,SPWeb   like that



Guid GwebID = SPContext.Current.Web.ID;
Guid GsiteID = SPContext.Current.Site.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(GsiteID))
    {
try
{
        site.AllowUnsafeUpdates = true;
        using (SPWeb web = site.OpenWeb(GwebID))
        {
            web.AllowUnsafeUpdates = true;
          // Perform administrative actions
        }

}
catch
{
   // Handle or re-throw an exception.
}
finally
{
   site.AllowUnsafeUpdates = false;
}
         
    }
});


Reference :
http://msdn.microsoft.com/en-us/library/gg552614.aspx#bestpractice_elevpriv



Cool tool for FBA Management in SharePoint 2010

Wednesday, November 7, 2012

A forms based authentication pack for SharePoint 2010. It includes web parts for registering users, changing passwords and password recovery. It includes tools for managing users and roles and for approving registrations. This is a port of the CKS Forms Based Authentication Solution for SharePoint 2007


Features

User Management page allows you to Create, Edit, Delete and Search for users. Allows for password reset and user unlocking. Users can be assigned to SharePoint Groups or Roles.
Role Management page allows roles to be created and deleted.
Built in Change Password page and menu item.
Optionally review and moderate new membership requests.
Web parts can be completely customized using HTML templates. Simple customizations can be done with the web part properties.
User emails can be completely customized using XSLT templates.
Password Recovery web part allows look-ups by both username and email address.
Membership Request web part includes optional CAPTCHA, optional auto generate password, optional login registered user.

Completely localizable. Currently languages include English and Chinese.

Update people field in List SharePoint 2010

Sunday, October 7, 2012





using(SPSite mainsite=new SPSite("SPContext.Current.Site.Url"))
{
    using(SPWeb mainweb = site.OpenWeb())
    {
                                    //Custom List Name
        SPList list = mainweb.Lists["MyList"];

        // Add new listItem
        SPListItem item = list .AddItem();

                                                 // UserID with domain
        SPUser user = web.AllUsers["SharePoint\\Usama"];

        item["Person"] = user;
        item.Update();
    }
}


:)

Fixed ribbon and scroll bar issues.

Monday, October 1, 2012

The new Ribbon functionality in SharePoint 2010 can cause some frustration when creating custom master pages. The trick is to develop a master page with the ribbon always on top of your page without losing functionality and keep the content scrolling working correctly. Sometimes the scroll bars seems to grow outside the browser window leaving the end-user unable to scroll to the bottom of the page. Chances are that you forgot some HTML in the master page.

Source : Read Full Article