Tuesday 24 December 2013

People Picker control

People Picker control below User Interface :


Add below CSS
 .ms-inputuserfield
{
font-size: 8pt;
font-family: Verdana,sans-serif;
border: 1px solid #a5a5a5;
}
div.ms-inputuserfield a
{
color: #000000;
text-decoration: none;
font-weight: normal;
font-style: normal;
}
div.ms-inputuserfield
{
padding-left: 1px;
padding-top: 2px;
}




Ascx controlCoding :à

<SharePoint:PeopleEditor ID="peopleEditorRelegationDetailsSharedBy" runat="server"
AllowEmpty="true" SelectionSet="User" Width="400px" MultiSelect="false" validationgroup="Tr"
ValidatorEnabled="true" BorderColor="Black" BorderWidth="0px" />


.cs Coding :à
if (peopleEditorRelegationDetailsSharedBy.ResolvedEntities.Count> 0)
                 {
peopleEditorRelegationDetailsSharedBy.Validate();

if (peopleEditorRelegationDetailsSharedBy.IsValid)
                     {
RelegationDetailsSharedBy = peoplePickerData();
peoplepickervalue = true;
                     }                 

                 }
else
                 {
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('There are no recipients in Relegation Details SharedBy by')", true);
                 }



public string peoplePickerData()
        {
            #region Relegated By People Picker
stringSharedBy = string.Empty;
stringSharedByEmail = "";
if (peopleEditorRelegationDetailsSharedBy.Entities.Count> 0)
            {
for (inti = 0; i<peopleEditorRelegationDetailsSharedBy.ResolvedEntities.Count; i++)
                {
PickerEntity picker = (PickerEntity)peopleEditorRelegationDetailsSharedBy.ResolvedEntities[i];
if (peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Contains("GOINDIGO"))
                    {
if (SharedBy == string.Empty)
SharedBy = peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Split('\\')[1];
else
SharedBy = SharedBy + "," + peopleEditorRelegationDetailsSharedBy.Accounts[i].ToString().Split('\\')[1];
                    }                  
Hashtable hash = picker.EntityData;
stringstrRecEmail = Convert.ToString(hash["Email"]);
SharedByEmail += strRecEmail;
                }
            }
returnSharedByEmail;
            #endregion
        }

Sunday 22 December 2013

Export To Excel in SharePoint 2010

SharePoint postback to work after clicking on export to excel button
<asp:ImageButton ID="imagbtnExportToExcel" runat="server" 
                                ImageUrl="~/_layouts/images/CrewRelegationTracker/Excel.PNG" Width="35px" 
                                onclick="imagbtnExportToExcel_Click"  />



  protected void Page_Load(object sender, EventArgs e)
        {
            imagbtnExportToExcel.OnClientClick = "_spFormOnSubmitCalled = false;_spSuppressFormOnSubmitWrapper=true;";
}
  OR

You can use below script code if above code not working for postback to work after clicking on export to excel in sharepoint 2010

<script type="text/javascript" language="javascript">
    //sharepoint postback to work after clicking on export to excel button
    if (typeof (_spBodyOnLoadFunctionNames) != 'undefined' &&
                                           _spBodyOnLoadFunctionNames != null) {
        _spBodyOnLoadFunctionNames.push("supressSubmitWraper");
    }
    function supressSubmitWraper() {
        _spSuppressFormOnSubmitWrapper = true;
    }
</script>



  protected void imagbtnExportToExcel_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                DataTable dtExportData = new DataTable();
                var btnIDFlag = ((ImageButton)sender).ID;
                if (btnIDFlag == "imagbtnExportToExcel")
                    dtExportData = (DataTable)ViewState["PageIndexData"];
                else
                    dtExportData = (DataTable)ViewState["FinalCrewEntitlmentDetails"];
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.ClearHeaders();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");

                if (btnIDFlag == "imagbtnExportToExcel")

                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CrewRelegationTracker.xls");
                else
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=CrewRelegationTracker.xls");

                HttpContext.Current.Response.Charset = "utf-8";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
                HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
                HttpContext.Current.Response.Write("<BR><BR><BR>");
                HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
                  "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
                  "style='font-size:10.0pt; font-family:Calibri; background:white;'>");

                int columnscount = dtExportData.Columns.Count;
                HttpContext.Current.Response.Write("<TR>");
                for (int j = 0; j < columnscount; j++)
                {
                    HttpContext.Current.Response.Write("<Td style='background-color:#99CCCC'>");
                    HttpContext.Current.Response.Write("<B>" + dtExportData.Columns[j].ColumnName + "</B>");
                    HttpContext.Current.Response.Write("</Td>");
                }
                HttpContext.Current.Response.Write("</TR>");
                foreach (DataRow row in dtExportData.Rows)
                {
                    HttpContext.Current.Response.Write("<TR>");
                    for (int i = 0; i < dtExportData.Columns.Count; i++)
                    {
                        HttpContext.Current.Response.Write("<Td>");
                        HttpContext.Current.Response.Write(row[i].ToString());
                        HttpContext.Current.Response.Write("</Td>");
                    }
                    HttpContext.Current.Response.Write("</TR>");
                }
                HttpContext.Current.Response.Write("</Table>");
                HttpContext.Current.Response.Write("</font>");
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                objLogger.LogExceptions(ex, "btnSearch_Click");
                //Page.ClientScript.RegisterStartupScript(this.GetType(), "refresh", "ErrorMessage();", true);
            }
        }

Thursday 5 December 2013

Get value from Document Library in sharepoint 2013

Get value from Document Library in sharepoint 2013

<script type="text/javascript">
    function OpenDialogSubReport(URL, Title) {

        var NewPopUp = SP.UI.$create_DialogOptions();
        NewPopUp.url = URL;
        NewPopUp.autoSize = true;
        NewPopUp.title = Title;
        NewPopUp.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
        SP.UI.ModalDialog.showModalDialog(NewPopUp);
        return false;
    }
</script>



<asp:GridView ID="gvDocuments" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
    <Columns>
       <%-- ItemStyle-CssClass="hide" ControlStyle-CssClass="hide" HeaderStyle-CssClass="hide"--%>
        <asp:BoundField HeaderText="ID" DataField="ID"  />
        <asp:BoundField HeaderText="Type" DataField="DocIcon" />
        <asp:HyperLinkField HeaderText="Name" DataTextField="LinkFilename" DataNavigateUrlFields="EncodedAbsUrl" DataNavigateUrlFormatString="{0}" Target="_blank" />
        <asp:BoundField HeaderText="Modified" DataField="Modified" />
        <asp:BoundField HeaderText="Modified By" DataField="Editor" />
        <asp:TemplateField ItemStyle-Width="70px" ItemStyle-CssClass="EditIcon MlstEdit">
            <ItemTemplate>
                <%--<a id="Share"  href="javascript:void(0);" onclick="OpenPopUpPage('/_layouts/15/ShareDoc.aspx?forSharing=1&List={91A30FF8-FBF1-4DC3-ABE4-817507EEA64E}&obj={91A30FF8-FBF1-4DC3-ABE4-817507EEA64E},<%# Eval("ID") %>,DOCUMENT');">Share</a>--%>
                 <%--<a id="Share"  href="javascript:void(0);" onclick="OpenPopUpPage('http://sharepoint:8888/Pages/Shared.aspx');">Share</a>--%>
                <a id="Share"  href="javascript:void(0);" onclick='<%# Eval("ID", "OpenPopUpPage(\"/Pages/Shared.aspx?ID={0}\")") %>'>Share</a>
           
                <%--<asp:LinkButton ID="lnkShare" runat="server" OnClick="lnkShare_Click" Text="Share"></asp:LinkButton>--%>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>




 protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    this.BindGridview();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void BindGridview()
        {
            try
            {
                SPSite oSite = null;
                SPWeb oWeb = null;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    oSite = SPContext.Current.Site;
                    using (oSite = new SPSite(oSite.Url))
                    {
                        using (oWeb = oSite.OpenWeb())
                        {
                            SPDocumentLibrary lst = (SPDocumentLibrary)oWeb.Lists.TryGetList("Documents");
                            if (lst != null)
                            {
                                SPQuery sQuery = new SPQuery();
                                sQuery.Query = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
                                sQuery.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='DocIcon' /><FieldRef Name='Editor' /><FieldRef Name='EncodedAbsUrl' /><FieldRef Name='LinkFilename' /> <FieldRef Name='FileLeafRef' /><FieldRef Name='Modified' />";                                
                                sQuery.ViewAttributes = "Scope='Recursive'";
                                sQuery.ViewFieldsOnly = true;
                                SPListItemCollection myColl = lst.GetItems(sQuery);
                                if (myColl.Count > 0)
                                {
                                    gvDocuments.DataSource = myColl.GetDataTable();
                                    gvDocuments.DataBind();
                                }
                            }
                        }

                    }

                });
            }


            catch (Exception)
            {

                throw;
            }

        }

        protected void lnkShare_Click(object sender, EventArgs e)
        {

            string SiteUrl = SPContext.Current.Site.Url;            
            string url = SiteUrl + "/_layouts/15/ShareDoc.aspx?forSharing=1&List={91A30FF8-FBF1-4DC3-ABE4-817507EEA64E}&obj={91A30FF8-FBF1-4DC3-ABE4-817507EEA64E},2,DOCUMENT";
            HttpContext.Current.Response.Redirect(url);
           //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), Guid.NewGuid().ToString(), "javascript:OpenDialogSubReport('" + url + "','" + Title + "')", true);
        }


Wednesday 2 October 2013

Java Script usefull method

1. JavaScript for Date and Time Formating
//function for the getting the formatted date and time 
// current output June 26, 2012 4:04 PM

function formattedUTCDateTime(d) {

    // code for the year
    var 
m_names = new Array("January", "February", "March",
    "April", "May", "June", "July", "August", "September",
    "October", "November", "December");

//    var 
d = new Date();
    var 
curr_date = d.getUTCDate();
    var 
sup = "";


else if (
curr_date == 3 || curr_date == 23) {
        
sup = "rd";
    }

    if (
curr_date == 1 || curr_date == 21 || curr_date == 31) {
        
sup = "st";
    }
    else if (
curr_date == 2 || curr_date == 22) {
        
sup = "nd";
    }
 
    else {
        
sup = "th";
    }

    var 
curr_year = d.getUTCFullYear();
    var 
curr_month = d.getUTCMonth();


    //code for the time  
    var 
hours = d.getUTCHours()
    var 
minutes = d.getUTCMinutes()

    var 
suffix = "AM";
    if (
hours >= 12) {
        
suffix = "PM";
        
hours = hours - 12;
    }
    if (
hours == 0) {
        
hours = 12;
    }

    if (
minutes < 10)
        
minutes = "0" + minutes;

    var 
datetimevalue = (m_names[curr_month] + " " + curr_date + ", " + curr_year + "  " + hours + ":" + minutes + " " + suffix);
    return datetimevalue;

}



How to: Display a page as a Modal Dialog Box Use Webpart Visual 2010

http://mstechsharing.blogspot.in/2012/03/how-to-display-page-as-modal-dialog-box.html


Open sharepoint site, create new Custom List name is Employees
Change Title Field to EmployeeID
Create new Field FirstName, LastName
Add new some data to list
Open Visual studio 2010 | New Project | Empty Sharepoint Project | name is SanboxPopup
Choose “Deploy as a sandboxed solution”
Create Module: you can reference at here
Right click to solution | add new item | Module template | Name is Scripts
Appear Sample.txt in Scripts then rename Sample.txt to jsFunction.js
After change, result as follows
In the Module element, add a Url ="_catalogs/masterpage" RootWebOnly="TRUEList="116" attribute value
Delete Url Script/
In the File element, copy  Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" and paste to below
Open file jsFunction.js and delete content
Paste code below to content of file jsFunction.js
Expand Features treeview, rename Feature1 to ScriptsFeature
Double-click the ScriptsFeature node to open the Feature Designer.
In the Feature Designer, set the feature scope to Site.
In the Items in the Solution pane, click the Scripts module and Click the right arrow button to add the module to the feature. This moves the feature to the Items in the Feature pane (if Feature pane don’t appear)
Create new Webpart: Right click Project | Add new item | Webpart template | name is DialogDemo
Using library as follows:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
Declare code as follows
const string jsScriptURL = "/_catalogs/masterpage/jsFunctions.js";

Copy code and paste to method CreateChildControls()
HtmlGenericControl scriptInclude = new HtmlGenericControl("script");
scriptInclude.Attributes.Add("src",SPContext.Current.Site.RootWeb.Url + jsScriptURL);
Controls.Add(scriptInclude);
HyperLink link = new HyperLink();
link.Text = "View Employees";
link.NavigateUrl = string.Concat("javascript: ShowDialog('",SPContext.Current.Site.RootWeb.Url,"/Lists/Employees/AllItems.aspx')");
this.Controls.Add(link);
In Solution Explorer, double-click the ScriptsFeature node to open the Feature Designer. Make sure that theDialogDemo Web Part is added to the feature.
Upload file  wsp and active it, you can reference how to way deploy sandbox at here, then add webpart and click to link below
Result as follows