Tuesday, June 18, 2013

Custom Errors Handling in SharePoint (Handling Errors in SharePoint )

Custom Errors Handling in SharePoint(Handling Errors in SharePoint) 


System.Diagnostics.EventLog.WriteEntry("My Errors: Webpart Error Report", ex.Message);

Lookup: Adding data into SharePoint Lookup column Programatically

Adding data into SharePoint Lookup column Programatically:


Logic:
For Updating Lookup field Item, it takes ID only.
Not a string type value:

Here CountryLookup is lookup field in UploadExcelData List:
Pic:1


It is Taking the values from Country List with field is Country.
Pic:2

Pic:3
Pic:4

=====================================================
 SPList lstExamStatus = web.Lists.TryGetList("Country");
            SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item["Country"].ToString() == itemname)
                {
                    id = item.ID;
                    break;
                }
            }

 if (ID != 0)
  {
         addNewItem["CountryLookup"] = ID;
   }
----------------------------------------------------------------------------------------------------------------------
Note: itemname (India, England France). If you want to update India. itemname= "India";
===========================================================


========================================================
===========================@============================

Another Case:

Source List: ExamStatus: Title having columns (Pass, Fail...)
Destination: SureStep: Status Lookup field (from Exam Status).

  string lstExamStatus = "ExamStatus";
            string examStatusField_Title = "Title";                                   
            SPListItemCollection lstItemColl = web.Lists["SureStep"].Items;
            SPListItem item = lstItemColl.Add();
            item["Title"] = "FirstName-Ravikumar1"; // Optional not neccesary

        // get_ID() method to retrive perticular Id.

            int ID = get_ID(web, lstExamStatus, examStatusField_Title, "Pass"); //Pass (Item Name) Selected value from drop down
            if (ID != 0)
                item["Status"] = ID;
            item.Update();



        public static int get_ID(SPWeb web, string list, string field, string itemname)
        {
            int id = 0;
           SPList lstExamStatus = web.Lists.TryGetList("ExamStatus");
           SPListItemCollection lstItemColl = lstExamStatus.Items;
            foreach (SPListItem item in lstItemColl)
            {
                if (item.DisplayName == itemname)
                {
                    id = item.ID;
                    break;
                }
            }
            return (id);

SharePoint Form Disabled users to csv file. (Export data to .CSV)

 Export All Disabled users in a SharePoint Form:

Add App.Config files for All web Applications:
App.config: 

 <appSettings>
    <add key="WebAppsName"  value="http://WebappUrl1|http://web01:81|http://communities|http://Sp2010"/>
  </appSettings> 



string EmailID = string.Empty; string siteUrl = string.Empty; string fullname = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                try
                {
                  
                           // For CSV.
                    StreamWriter SW;
                    SW = File.AppendText("c:\\UserInfoListReport.csv");                   
                    SW.WriteLine("Site collection URL,  User, Full Name,  E-Mail");
                       // Reading Webapplication url's from config file
                    String ConfigValues = ConfigurationSettings.AppSettings["WebAppsName"];

                    String[] ObjWebapps = ConfigValues.Split('|');
                    foreach (String WebappsName in ObjWebapps)
                    {
                        SPWebApplication webapp = SPWebApplication.Lookup(new Uri(WebappsName));
                        foreach (SPSite site in webapp.Sites)
                        {
                            foreach (SPWeb web in site.AllWebs)
                            {
                                siteUrl = web.Url;

                                SPSite Objsite = new SPSite(siteUrl);
                                SPWeb objweb = Objsite.OpenWeb();
                                SPGroupCollection ObjAllGrps = objweb.Groups;

                               
                                String ObjUsername = String.Empty;
                                SPUser ValidsUser = null;
                                foreach (SPGroup ObjUsers in ObjAllGrps)
                                {
                                    foreach (SPUser Objuser in ObjUsers.Users)
                                    {
                                        try
                                        {
                                            String ObjLoginName = Objuser.LoginName;
                                            EmailID = Objuser.Email;
                                            fullname = Objuser.Name;
                                            if (ObjLoginName.Contains("|"))
                                            {
                                                ObjUsername = ObjLoginName.Split('|')[1].ToString();
                                            }
                                            else
                                            {
                                                ObjUsername = ObjLoginName;
                                            }
                                            ValidsUser = objweb.EnsureUser(ObjUsername);
                                        }
                                        catch (Exception ex)
                                        {

                                            if (ObjUsername.Contains(@"\"))
                                            {
                                                      // Writing into CSV file
                                                SW.WriteLine(Objsite.Url.Replace(",", " ") + "," + ObjUsername + "," + fullname + "," + EmailID);                                           
                                            }
                                            else
                                            {
                                            }

                                        }
                                    }
                                }

                            }
                        }                       
                    }

                 
                    SW.Close();
                
                }
                catch (Exception ex)
                {                   
                } 
            
            });

Thursday, May 23, 2013

Model dialogues,Refresh Parent, Pop-Up Window for SharePoint


Add New Items:

hyperLink.NavigateUrl = "javascript:SP.UI.ModalDialog.ShowPopupDialog('" + url + "')";



Dialog with Parent page refresh while closing Popup:


function openDialog() {
        var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
        var libOrFolderURL = document.getElementById("<%=lblBreadCrumb.ClientID %>").innerHTML;
        var completeUrl = siteUrl + "/" + libOrFolderURL;            
        if (typeof libOrFolderURL !== 'undefined' && libOrFolderURL != "") {
            var options = {
                url: completeUrl,
                allowMaximize: true,
                width: 800,
                height: 700,
                title: "Upload, add, Edit, Apply category..",
                dialogReturnValueCallback: function (completeUrl) {                                   
                location.reload();
                }
            };
            SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
        }
        return false;

    }




====================@===============================




Message Box:
  string script = "<script language='javascript'>alert('Field are emply ')</script>";
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "Register", script);
(or)

string script = "<script language='javascript'>alert('" + errorMessage + "')</script>";
Page.ClientScript.RegisterClientScriptBlock(GetType(), "Register", script);

============================@============================




Add Link Under Personal Action:

<CustomAction
Id="By_RKU_ChangeMyPW_ActionsMenu"
    Title="Change Password"
Description="Change your Domain Password"
     GroupId="PersonalActions"
     Location="Microsoft.SharePoint.StandardMenu"

ImageUrl="~site/_layouts/images/SharePointFix/water.gif">
<UrlAction Url="javascript:(function () { var o = { url:'{SiteUrl}/_LAYOUTS/ChangePw/ChangePassword.aspx', title: 'Select List Item', dialogReturnValueCallback: SP.UI.ModalDialog.RefreshPage }; SP.UI.ModalDialog.showModalDialog(o); }) ();"/>

</CustomAction>


(Or)


 <CustomAction
   Id="By_RKU_ChangeMyPW_ActionsMenu"
   Title="Change Password"
   Description="Change your Domain Password"
   GroupId="PersonalActions"
   Location="Microsoft.SharePoint.StandardMenu"
    Sequence="1000">
   <UrlAction Url="_LAYOUTS/ChangePw/ChangePassword.aspx"/>  
  </CustomAction>

---------------------------------------------------------------------------------------------------


In SharePoint :


<CustomAction
    Id="{B0B5A0CB-7FBE-4dd6-9B2A-2B1E1321B8F9}"
    RegistrationType="List"
    RegistrationId="101"
Location="EditControlBlock"
Title="Change Password">
 <UrlAction Url="javascript: function onClose(){ } 
       var o = { 
  url: '{SiteUrl}/_layouts/ChangePw/ChangePassword.aspx',
 title: 'Password Rest Tool',
 allowMaximize: true,
 showClose: true,
 width: 400,
 height: 300,
 dialogReturnValueCallback: onClose
 };
 SP.UI.ModalDialog.showModalDialog(o);"/>
  </CustomAction>

Tuesday, May 7, 2013

Calculate column Conditions with marks grade.

Calculated Column in SharePoint
Student Percentage:


=IF([Percentage]>=0.95,"A",IF([Percentage]>=0.88,"B",IF([Percentage]>=0.81,"C",IF([Percentage]>=0.75,"D",IF([Percentage]>=0.74,"F")))))




==================================================
columns value (Questions) based  on another column (Role) selections:

If you select Developer, Question value should be 26.




=IF(Role="Architects",34,
IF(Role="Consultants",30,
IF(Role="Developers",26,
IF(Role="Engagement Managers",38,
IF(Role="Managers",28,
IF(Role="Project Managers",42,
IF(Role="Senior Sales Executives",26,0)))))))

Tuesday, April 30, 2013

Get All Users from Web Application programatically


static void Main(string[] args)
        {
            String ConfigValues = ConfigurationSettings.AppSettings["WebAppsName"];

            String[] ObjWebapps = ConfigValues.Split('|');

            foreach (String WebappsName in ObjWebapps)
            {
                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(WebappsName));
                int count = webApp.Sites.Count;
                foreach (SPSite ObjSites in webApp.Sites)
                {
                
                    AllUsers(ObjSites.Url);
                }
            }
           // AllUsers();
     
        }
        protected static void AllUsers(String SiteName)
        {
            using (SPSite site = new SPSite(SiteName))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    foreach (SPRoleAssignment roleAssignment in web.RoleAssignments)
                    {
                        if (roleAssignment.Member is SPGroup)
                        {
                           
                            foreach (SPRoleDefinition roleDefinition in roleAssignment.RoleDefinitionBindings)
                            {
                               // ("\t" + roleDefinition.Name);
                                if (roleDefinition.Name.Equals("Contribute"))
                                {
                                    var group = (SPGroup)roleAssignment.Member;
                                    foreach (SPUser user in group.Users)
                                    {
                                    //("Contribute Permission Level" + "----" + "User Name" + user.Name);
                                    }

                                  
                                }
                                if (roleDefinition.Name.Equals("Full Control"))
                                {
                                    var group = (SPGroup)roleAssignment.Member;
                                    foreach (SPUser user in group.Users)
                                    {
                                        //("Contribute Permission Level" + "----" + "User Name" + user.Name);
                                    }
                                }
                                if (roleDefinition.Name.Equals("Read"))
                                {
                                    var group = (SPGroup)roleAssignment.Member;
                                    foreach (SPUser user in group.Users)
                                    {
                                       //("Read Permission Level" + "----" + "User Name" + user.Name);
                                    }
                                }
                                if (roleDefinition.Name.Equals("View Only"))
                                {
                                    var group = (SPGroup)roleAssignment.Member;
                                    foreach (SPUser user in group.Users)
                                    {
                                        //("View Only Permission Level" + "----" + "User Name" + user.Name);
                                    }
                                }
                            }
                        }
                    }
                }
          
            }

        }

Thursday, March 14, 2013

SharePoint List items in Modal Dialog Popup from CQWW or XSLT


         SharePoint List items in Modal Dialog Popup from  

                CQWP or XSLT


Open list items in Modal dialog listed in Content Query Web Part.  

Steps to do
  1. Open  Site with in SharePoint designer and go to All items > Style library> XSL Style Sheets.
  2. Open ItemStyle.xsl file and edit it (CheckOut \ take the backup for safe)
  3. Paste below section to any of the  </xsl:template>

 <xsl:template name="ModalDialogPopUp" match="Row[@Style='ModalDialogPopUp']" mode="itemstyle">
        <xsl:variable name="SafeLinkUrl">
            <xsl:call-template name="OuterTemplate.GetSafeLink">
                <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
            </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="DisplayTitle">
            <xsl:call-template name="OuterTemplate.GetTitle">
                <xsl:with-param name="Title" select="@Title"/>
                <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
            </xsl:call-template>
        </xsl:variable>
        <div class="item link-item bullet">
            <xsl:call-template name="OuterTemplate.CallPresenceStatusIconTemplate"/>
            <a onclick="javascript:SP.UI.ModalDialog.ShowPopupDialog('{$SafeLinkUrl}'); return false;" onmouseover="javascript:this.style.cursor='hand';" title="{@LinkToolTip}">
                        <xsl:value-of select="$DisplayTitle"/>
            </a>
        </div>

    </xsl:template>  

4.      Save the file and check it in. 
5.      Edit CQWP, ==> Presents==> in the ItemStyle of CQWP Select from Dropdown as  ModalDialogPopUp and Click OK.