Wednesday, 20 June 2012

ASCX(.ascx)

STEP 1: Create a VisualWebPart like DepartmentImage

STEP 2: Write a coding in DepartmentImageUserControl.ascx


STEP 3:



<div class="menu_bg_sd_new">
    <div class="menu_left_sd_new">
    </div>
    <div class="menu_right_sd_new">
    </div>
</div>
<div class="menu_bg_sd_mid">
    <table width="100%" border="0" style="height: 10px;" cellspacing="0" cellpadding="0">
        <tr class="menu_bg_sd_mid">
            <td class="menu_left_sd_mid" width="2%">
                &nbsp;
            </td>
            <td width="95%" class="content_styleEdit" style="line-height: 10px !important;" align="right">
                <asp:ImageButton ID="ImageButton1" runat="server" Height="20" Width="20" ImageUrl="/_layouts/images/VCSB/note.png" />
            </td>
            <td class="menu_right_sd_mid" width="3%">
                &nbsp;
            </td>
        </tr>
    </table>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr class="menu_bg_sd_mid">
            <td class="menu_left_sd_mid" width="2%">
                &nbsp;
            </td>
            <td width="80%" class="content_style" align="center">
                <asp:ImageButton ID="imgFileImage" runat="server" ImageUrl="" Height="180" Width="511"
                    ImageAlign="Middle" />
            </td>
            <td class="menu_right_sd_mid" width="3%">
                &nbsp;
            </td>
        </tr>
    </table>
</div>
<div class="menu_bg_sd_bot">
    <div class="menu_left_sd_bot">
    </div>
    <div class="menu_right_sd_bot">
    </div>
</div>

ASCX.CS (ascx.cs)

STEP 1: Create a VisualWebPart like DepartmentImage

STEP 2: Write a coding in DepartmentImageUserControl.ascx.cs 


STEP 3:


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
using VCSB.INTRANET.BLL;
using VCSB.INTRANET.DAL;
using System.Linq;
using Microsoft.SharePoint.Utilities;

namespace VCSB01.INTRANET.VCSBWebPart.DepartmentImage
{
    public partial class DepartmentImageUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDepImage();
            }
        }
        private void BindDepImage()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {    
                      imgFileImage.ImageUrl= GetListAttachments().ToString();
                      
            });
         
        }

        private object GetListAttachments()
        {
            string URL = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite spsite= SPContext.Current.Site;
                SPWeb spWeb = spsite.OpenWeb();
                SPList spList = spWeb.Lists["DepartmentImage"];
                SPListItemCollection spListItems = spList.Items;             
                foreach (SPListItem item in spListItems)
                {
                    SPAttachmentCollection collAttachments = item.Attachments;
                        foreach (var attachment in collAttachments)
                        {
                            URL = (SPEncode.HtmlEncode(item.Attachments.UrlPrefix + attachment.ToString()));
                        }
                }

            });
            if (URL != null)
            {
                return URL;
            }
            else
            {

                return URL = @"~\_Layouts\Images\VCSB\photo_not_avl.png";
            }
        }

    }
}
 

Monday, 18 June 2012

ASCX.CS (ascx.cs)

STEP 1: Create a VisualWebPart like RecentlyViewedPages

STEP 2: Write a coding in RecentlyViewedPagesUserControl.ascx.cs 


STEP 3:


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using VCSB.INTRANET.BLL;

namespace VCSB01.INTRANET.RecentlyViewedPages
{
    public partial class RecentlyViewedPagesUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dtRecent=SiteHelper.GetRecentlyViewedPages();
                if (dtRecent != null && dtRecent.Rows.Count != 0)
                {
                    grdRecentPages.DataSource = dtRecent;
                    grdRecentPages.DataBind();
                }           
            }

        }
    }
}

ASCX(.ascx)

STEP 1: Create a VisualWebPart like RecentlyViewedPages

STEP 2: Write a coding in RecentlyViewedPagesUserControl.ascx


STEP 3:


<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ 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" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RecentlyViewedPagesUserControl.ascx.cs" Inherits="VCSB01.INTRANET.RecentlyViewedPages.RecentlyViewedPagesUserControl" %>






  <div class="menu_bg_sd">
                        <div class="menu_left_sd">
                        </div>
                        <div class="menu_right_sd">
                        </div>
                        <h4>
                            Most Recently Viewed Pages
                        </h4>
                    </div>
  <div class="menu_bg_sd_indtop">
                        <div class="menu_left_sd_indtop">
                        </div>
                        <div class="menu_right_sd_indtop">
                        </div>
                        <div class="box_inner_m">                   
                           <asp:GridView ID="grdRecentPages" GridLines="None" AutoGenerateColumns="false" runat="server">
                           <Columns>
                           <asp:TemplateField>
                           <ItemTemplate>
                           <asp:LinkButton ID="hypRecentPages" PostBackUrl='<%# Eval("Url")%>' runat="server"><%# Eval("Page")%></asp:LinkButton>            
                           </ItemTemplate>
                           </asp:TemplateField>
                           </Columns>
</asp:GridView>
                        </div>
                  
                    </div>
  <div class="menu_bg_sd_bot">
                        <div class="menu_left_sd_bot">
                        </div>
                        <div class="menu_right_sd_bot">
                        </div>
                    </div>
 

ASCX.CS(.ascx.cs)

STEP 1: Create a VisualWebPart like DepartmentNavigation

STEP 2: Write a coding in DepartmentNavigationUserControl.ascx.cs


STEP 3:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
using VCSB.INTRANET.BLL;
using System.Linq;

namespace VCSB01.INTRANET.VCSBWebPart.DepartmentNavigation
{
    public partial class DepartmentNavigationUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                BindDeptNavigationData();

            }
          
        }
        private void BindDeptNavigationData()
        {
           
            DataTable dt = new DataTable();
            dt.Columns.Add("PageUrl");
            dt.Columns.Add("PageName");
            DataRow row;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (VCSBINTRANETDataContext cont = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                    var quer = from navigationData in cont.Pages
                               orderby navigationData.Id descending
                               select navigationData;

                    if (quer != null)
                    {
                       foreach (SPListItem uitem in SPContext.Current.Web.Lists["Pages"].Items)
                        {
                            row = dt.Rows.Add();
                            row["PageUrl"] = Convert.ToString(SPContext.Current.Web.Url+"//"+uitem.Url);
                            string pagename =Convert.ToString(uitem.Name);
                            if (!string.IsNullOrEmpty(pagename))
                            {
                                string[] pagename1 = pagename.Split('.');
                                row["PageName"] = Convert.ToString(pagename1[0]);

//  row["PageName"] =Convert.ToString(pagename.Split('.').GetValue(0));
                            }
                        }
                    }
                }
            });
            grdDeptNavigation.DataSource = dt;
            grdDeptNavigation.DataBind();
        }
    }
}
 

ASCX(.ascx)

STEP 1: Create a VisualWebPart like DepartmentNavigation

STEP 2: Write a coding in DepartmentNavigationUserControl.ascx


STEP 3:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ 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" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DepartmentNavigationUserControl.ascx.cs" Inherits="VCSB01.INTRANET.VCSBWebPart.DepartmentNavigation.DepartmentNavigationUserControl" %>

<%@ Register Assembly="AjaxControlToolkit, Version=3.0.30512.20315, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
    Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <link href="/_layouts/Styles/VCSB/style.css" rel="stylesheet" type="text/css" />

<link href="/_layouts/Styles/VCSB/Blog.css" rel="stylesheet" type="text/css" />



<div class="d_mysite">
    <div class="menu_bg_sd">
        <div class="menu_left_sd">
        </div>
        <div class="menu_right_sd">
        </div>
        <h6>
            MY LINK</h6>
    </div>
    <div class="menu_bg_sd_mid">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr class="menu_bg_sd_mid">
                <td class="menu_left_sd_mid" width="2%">
                    &nbsp;
                </td>
                <td width="95%" class="menu_bg_sd_mid_inner">
                    <div class="side_menu">
                        <asp:GridView ID="grdDeptNavigation" Width="100%" runat="server" BorderStyle="None"
                            AutoGenerateColumns="False" GridLines="None" ShowHeader="False">
                            <Columns>
                                <asp:TemplateField>
                                    <ItemStyle Width="85%" CssClass="ql" />
                                    <ItemTemplate>
                                    <asp:LinkButton ID="lnkbtnUrl"  CausesValidation="false" PostBackUrl='<%# Eval("PageUrl")%>' runat="server">
                                        <%# Eval("PageName")%>
                                       </asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                        <div class="clear">
                        </div>
                    </div>
                </td>
                <td class="menu_right_sd_mid" width="3%">
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    <div class="menu_bg_sd_bot">
        <div class="menu_left_sd_bot">
        </div>
        <div class="menu_right_sd_bot">
        </div>
    </div>
</div>
 

Message Helper

STEP 1: Create a class file like MessageHelper.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VCSB.INTRANET.BLL
{
   public class MessageHelper
    {
        #region Message
        /// <summary>
        /// Messge Helper
        /// </summary>
        /// <param name="MessageMode"></param>
        /// <returns></returns>

        public static string Message(MessageMode MessageMode)
        {

            switch (MessageMode)
            {
                case MessageMode.Success: return "The user group has been added successfully.";
                case MessageMode.Fail: return "failure";
                case MessageMode.CommonErrorMessage: return "Sorry! Unexpected Error Occured";
                default: return "no-message";
            }
        }
        #endregion
    }
   #region Enum
   public enum MessageMode : int
   {
       Success = 0,
       Fail,
       CommonErrorMessage
      
   }
   #endregion
}


Error Helper

STEP 1: Create a class file like ErrorHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace VCSB.INTRANET.BLL
{
   public class ErrorHelper
    {
        #region LoginName
        /// <summary>
        /// Get Currnet user Loginame
        /// </summary>
        public static string LoginName
        {
            get
            {
                SPSite spSite; SPWeb spWeb;
                using (spSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (spWeb = spSite.OpenWeb())
                    {
                        SPUser sUser = spWeb.CurrentUser;
                        //string str = sUser.Name + sUser.LoginName + sUser.Email + sUser.Groups.Count;
                        return sUser.LoginName;
                    }
                }
            }
        }
        #endregion

        #region Add
        public static void Add(string message, string stacktrace)
        {
            try
            {
                SPSite spSite; SPWeb spWeb; SPList spList;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (spSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        spSite.AllowUnsafeUpdates = true;
                        using (spWeb = spSite.OpenWeb())
                        {
                            spWeb.AllowUnsafeUpdates = true;
                            SPWeb objweb = spSite.OpenWeb();
                            spList = spWeb.Lists.TryGetList("ErrorLog");
                            if (spList != null)
                            {
                                SPListItem spListItem = spList.Items.Add();
                                spWeb.AllowUnsafeUpdates = true;
                                spListItem["ErrorMessage"] = Convert.ToString(message);
                                spListItem["StackTrace"] = Convert.ToString(stacktrace);
                                spListItem["LoginName"] = Convert.ToString(LoginName);
                                spListItem.Update();
                            }

                        }
                        spWeb.AllowUnsafeUpdates = false;
                    }
                    spSite.AllowUnsafeUpdates = false;
                });
            }
            catch { }
        }
        #endregion
    }
}
 

Site Helper

 STEP 1: Create a class file like SiteHelper.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using System.Xml;
using System.Data;

namespace VCSB.INTRANET.BLL
{
    public class SiteHelper
    {
        public static string SiteUrl
        {
            get { return SPContext.Current.Web.Url; }
        }
       
        public static string CurrentUserRoleType()
        {
            string Curntroletype = string.Empty;
            using (SPSite site = new SPSite(SPContext.Current.Web.Url))
            {
                site.AllowUnsafeUpdates = true;

                using (SPWeb spweb = site.OpenWeb())
                {
                    spweb.AllowUnsafeUpdates = true;
                    SPGroupCollection groupCollection = spweb.Groups;
                    foreach (SPGroup grp in spweb.CurrentUser.Groups)
                    {
                        foreach (SPGroup group in groupCollection)
                        {
                            if (grp.Name.Equals(group.Name))
                            {

                                SPContext.Current.Site.CatchAccessDeniedException = false;

                                // Retrieve all user roles assigned for the current user for the current web.
                                SPRoleDefinitionBindingCollection userRoles =SPContext.Current.Web.AllRolesForCurrentUser;
                                string xml = userRoles.Xml;
                                XmlDocument doc = new XmlDocument();
                                doc.LoadXml(xml);
                                foreach (XmlNode item in doc.DocumentElement.ChildNodes)
                                {
                                    //Check If Role Type == Reader - Do something
                                    if (item.Attributes["Type"].Value.Equals(SPRoleType.Reader.ToString()))
                                    {
                                        Curntroletype= SPRoleType.Reader.ToString();
                                    }
                                    //Administrators access - Full Control - Do something
                                    else if (item.Attributes["Type"].Value.Equals(SPRoleType.Administrator.ToString()))
                                    {
                                        Curntroletype= SPRoleType.Administrator.ToString();
                                    }
                                    //Contributor access - Contribute - Do something
                                    else if (item.Attributes["Type"].Value.Equals(SPRoleType.Contributor.ToString()))
                                    {
                                       Curntroletype= SPRoleType.Contributor.ToString();
                                    }
                                    //Web Designer access - Design rights- Do something
                                    else if (item.Attributes["Type"].Value.Equals(SPRoleType.WebDesigner.ToString()))
                                    {
                                        Curntroletype= SPRoleType.WebDesigner.ToString();
                                    }
                                    //Limited access - Do something
                                    else if (item.Attributes["Type"].Value.Equals(SPRoleType.Guest.ToString()))
                                    {
                                       Curntroletype= SPRoleType.Guest.ToString();
                                    }
                                    //No access on Current Web- Do something
                                    else if (item.Attributes["Type"].Value.Equals(SPRoleType.None.ToString()))
                                    {
                                        Curntroletype = SPRoleType.Guest.ToString();
                                    }
                                    else
                                    {
                                        Curntroletype = SPRoleType.None.ToString();
                                    }
                                    break;
                                }

                            }
                            //Get Role Assignments for Current User - If he has been directly assigned permissions
                            try { }
                            catch (Exception) {/*Best attempt to catch Exceptions*/}

                            finally
                            {
                                SPContext.Current.Site.CatchAccessDeniedException = true;

                            }
                        }
                    }
                    spweb.AllowUnsafeUpdates = false;
                } site.AllowUnsafeUpdates = false;
            } return Curntroletype;
           
        }

        #region GetCurrentUserGroup
        public static string GetCurrentUserGroup()
        {
            string GroupName = "";
         
            using (SPSite site = new SPSite(SiteUrl))
            {
                site.AllowUnsafeUpdates = true;

                using (SPWeb spweb = site.OpenWeb())
                {
                    spweb.AllowUnsafeUpdates = true;
                    SPGroupCollection groupCollection = spweb.Groups;
                    foreach (SPGroup grp in spweb.CurrentUser.Groups)
                    {
                        foreach (SPGroup group in groupCollection)
                        {
                            if (grp.Name.Equals(group.Name))
                            {                               
                                GroupName = grp.Name; break;
                            }
                            //Get Role Assignments for Current User - If he has been directly assigned permissions
                            try { }
                            catch (Exception) {/*Best attempt to catch Exceptions*/}

                        }
                    }
                    spweb.AllowUnsafeUpdates = false;
                } site.AllowUnsafeUpdates = false;
            }
            return GroupName;
        }

        #endregion

        #region VCSBSiteAdmin
        public static bool IsSiteAdmin()
        {
            SPContext currentContext;
            try
            {
                //Getting the current context         
                currentContext = SPContext.Current;
            }
            catch (InvalidOperationException)
            {
                currentContext = null;
            }
            if (currentContext != null && currentContext.Web.CurrentUser != null)
            {
                if (SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region CurrentUserLoginName
        public static string CurrentUserLoginName()
        {
            string userName = "NA";
            SPContext currentContext;
            try
            {
                //Getting the current context         
                currentContext = SPContext.Current;
            }
            catch (InvalidOperationException)
            {
                currentContext = null;
            }
            if (currentContext != null && currentContext.Web.CurrentUser != null)
            {
                SPSite spSite;
                SPWeb spWeb;
                using (spSite = new SPSite(SiteUrl))
                {
                    using (spWeb = spSite.OpenWeb())
                    {
                        userName = spWeb.CurrentUser.LoginName;
                    }
                }
            }
            return userName;
        }
      
        #endregion

        public static DataTable GetCurrentSiteGroup()
        {
            DataTable dtGroups = new DataTable();
            dtGroups.Columns.Add("GroupName");
            dtGroups.Columns.Add("Url");
          

            using (SPSite site = new SPSite(SiteUrl))
            {
                site.AllowUnsafeUpdates = true;

                using (SPWeb spweb = site.OpenWeb())
                {
                    spweb.AllowUnsafeUpdates = true;
                    SPGroupCollection groupCollection = spweb.Groups;
                    if (groupCollection.Count != 0 && groupCollection != null)
                    {
                        foreach (SPGroup group in groupCollection)
                        {
                            DataRow dr = dtGroups.NewRow();
                            dr["GroupName"] = group.Name;
                            dr["Url"] = group.ID;

                            dtGroups.Rows.Add(dr);

                        }
                    }
                    spweb.AllowUnsafeUpdates = false;
                } site.AllowUnsafeUpdates = false;
            }
            return dtGroups;
        }

        public static DataTable GetMyTeamSites()
        {
            DataTable dtDept = new DataTable();

            dtDept.Columns.Add("SiteName");
            dtDept.Columns.Add("SiteUrl");

            SPWebCollection UserDepartments = SPContext.Current.Site.RootWeb.GetSubwebsForCurrentUser();
            if (UserDepartments.Count != 0 && UserDepartments != null)
            {
                foreach (SPWeb item in UserDepartments)
                {
                    SPWebCollection MyTeamSites = SPContext.GetContext(item).Web.GetSubwebsForCurrentUser();
                    foreach (SPWeb Teamsite in MyTeamSites)
                    {
                        if (item.Name != "PressReleases" && item.Name != "Search")
                        {
                            DataRow dr = dtDept.NewRow();

                            dr["SiteName"] = Convert.ToString(Teamsite.Name);
                            dr["SiteUrl"] = Convert.ToString(Teamsite.Url);
                            dtDept.Rows.Add(dr);
                        }
                    }
                   
                }

            }
            return dtDept;
        }


        public static DataTable GetRecentlyViewedPages()
        {
            DataTable dt = SPContext.Current.Web.GetUsageData(Microsoft.SharePoint.Administration.SPUsageReportType.url, Microsoft.SharePoint.Administration.SPUsagePeriodType.lastMonth);
            dt.DefaultView.Sort = "Recent Month DESC";
            DataView dv = dt.DefaultView;
            dv.Sort = "Recent Month DESC";

            DataTable dtRecent = new DataTable();
            dtRecent.Columns.Add("Page");
            dtRecent.Columns.Add("Url");
            dtRecent.Columns.Add("Hits");
            dtRecent.Columns.Add("RecentDate");
            int i = 0;

            foreach (DataRow item in dv.ToTable().Rows)
            {
                if (i < 5 && Convert.ToString(item["Folder"]) == "pages")
                {
                    DataRow dr = dtRecent.NewRow();
                    dr["Page"] = Convert.ToString(item["Page"]);
                    dr["Url"] = Convert.ToString(SPContext.Current.Site.Url + "/" + item["Folder"] + "/" + item["Page"]);
                    dr["Hits"] = Convert.ToString(item["Recent Month"]);
                    dr["RecentDate"] = Convert.ToString(item["Most Recent Day"]);
                    dtRecent.Rows.Add(dr);
                    i++;
                }

            }
            return dtRecent;

        }
    }
}

ASCX.CS(.ascx.cs)

STEP 1: Create a VisualWebPart like QuickLinks

STEP 2: Write a coding in QuickLinksUserControl.ascx.cs 


STEP 3:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using VCSB.INTRANET.BLL;
using System.Data;
using Microsoft.SharePoint.Utilities;


namespace VCSB01.INTRANET.VCSBWebPart.QuickLinks
{
    public partial class QuickLinksUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindQuickLinksData();
                }
            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }
        private void BindQuickLinksData()
        {
            QuickLinksBL objquickData = new QuickLinksBL();
            grdQuickLinks.DataSource = objquickData.GetAllListItem();
            grdQuickLinks.DataBind();
        }


        protected void grdQuickLinks_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            DataTable dt = new DataTable();
            hdnValue.Value = e.CommandArgument.ToString();
            if (e.CommandName == "edit")
            {
                QuickLinksBL quickLinksBL = new QuickLinksBL(Convert.ToInt32(hdnValue.Value));
                dt = quickLinksBL.GetSingleRowListItem();
                txtQuickTitle.Focus();
                txtQuickTitle.Text = Convert.ToString(dt.Rows[0]["Title"]);
                txtQuickUrl.Text = Convert.ToString(dt.Rows[0]["Url"]);
            }
           
            mpeQuickLinks.Show();
        }

        protected void btnQuickSubmit_Click1(object sender, EventArgs e)
        {
            try
            {
                string id = hdnValue.Value;
                QuickLinksBL quickLinksBL = new QuickLinksBL(Convert.ToInt32(id), txtQuickTitle.Text, txtQuickUrl.Text);
                quickLinksBL.update();
                BindQuickLinksData();
            }
            catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }

        protected void grdQuickLinks_RowEditing(object sender, GridViewEditEventArgs e)
        {

        }
       
    }
}
 

ASCX(.ascx)

STEP 1: Create a VisualWebPart like QuickLinks

STEP 2: Write a coding in QuickLinksUserControl.ascx


STEP 3:


<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ 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" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="QuickLinksUserControl.ascx.cs" Inherits="VCSB01.INTRANET.VCSBWebPart.QuickLinks.QuickLinksUserControl" %>

     <%@ Register Assembly="AjaxControlToolkit, Version=3.0.30512.20315, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"
    Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <link href="/_layouts/Styles/VCSB/style.css" rel="stylesheet" type="text/css" />

<link href="/_layouts/Styles/VCSB/Blog.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    function ClearTextboxes() {
        $('#<%=txtQuickTitle.ClientID%>').val('');
        $('#<%=txtQuickUrl.ClientID%>').val('');
    }
    function trimstring(ctrl, Key) {

        if (Key.charAt(0) == " ") {
            document.getElementById(ctrl).value = document.getElementById(ctrl).value.trim();

        }
    }
</script>

<style type="text/css">
    .modalBackground
    {
        position: absolute;
        z-index: 100;
        top: 0px;
        left: 0px;
        background-color: #000;
        filter: alpha(opacity=60);
        -moz-opacity: 0.6;
        opacity: 0.6;
    }
</style>
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</asp:ScriptManagerProxy>
<div class="d_mysite">
    <div class="menu_bg_sd">
        <div class="menu_left_sd">
        </div>
        <div class="menu_right_sd">
        </div>
        <h6>
            Quick links</h6>
    </div>
    <div class="menu_bg_sd_mid">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr class="menu_bg_sd_mid">
                <td class="menu_left_sd_mid" width="2%">
                    &nbsp;
                </td>
                <td width="85%" class="menu_bg_sd_mid_inner">
                    <table cellpadding="0" cellspacing="0" width="100%" border="0">
                        <tr>
                            <td width="92%" class="edit">
                           
                                <asp:GridView ID="grdQuickLinks" Width="100%" runat="server" BorderStyle="None" AutoGenerateColumns="False"
                                    GridLines="None" ShowHeader="False" OnRowCommand="grdQuickLinks_RowCommand"  OnRowEditing="grdQuickLinks_RowEditing">
                                    <Columns>
                                        <asp:TemplateField>
                                            <ItemStyle Width="85%" CssClass="ql" />
                                            <ItemTemplate>
                                          
                                            <%# Eval("Title") %>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField>
                                            <ItemStyle Width="15%" CssClass="edit" />
                                            <ItemTemplate>
                                                <asp:ImageButton ID="imgbtnedit" runat="server" CommandName="edit" CommandArgument='<%# Eval("ID") %>'
                                                    ImageUrl="/_layouts/images/VCSB/note.png" CausesValidation="false" />
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                    </Columns>
                                </asp:GridView>
                            </td>
                        </tr>
                    </table>
                </td>
                <td class="menu_right_sd_mid" width="3%">
                    &nbsp;
                </td>
            </tr>
        </table>
    </div>
    <div class="menu_bg_sd_bot">
        <div class="menu_left_sd_bot">
        </div>
        <div class="menu_right_sd_bot">
        </div>
    </div>
</div>


<div id="quicklinks" class="bg_pop_up" style="display:none";>
    <table align="center" border="0" cellpadding="5" cellspacing="0" width="100%">
        <tr style="height:40px;">
            <td class="bg_pop_uphead" colspan="2">
                &nbsp;Quick Links</td>
            <td class="bg_pop_uphead">
                <asp:ImageButton ID="imgbtnQuickClose" ImageAlign="Right" runat="server" Height="20px" ToolTip="Close"
                    ImageUrl="/_layouts/images/VCSB/closebtn.png"  />
            </td>
        </tr>
        <tr>
            <td align="right" valign="top" width="30%">
            <span style="color: #FF0000">*</span>
                Title</td>
            <td align="left" valign="top" width="30%">
                <asp:TextBox  ID="txtQuickTitle" Width="280px"  runat="server" MaxLength="50" onKeyUp="trimstring(this.id,this.value);"></asp:TextBox>
                  <cc1:FilteredTextBoxExtender ID="flttxtTitle" TargetControlID="txtQuickTitle" InvalidChars="<,>" ValidChars="(,),-, "  FilterType="Custom,LowercaseLetters,UppercaseLetters,Numbers" Enabled="True"  runat="server">
        </cc1:FilteredTextBoxExtender>
                <asp:RequiredFieldValidator ID="reqQuickTitle" runat="server" ControlToValidate="txtQuickTitle" ValidationGroup="QuickLinks"  ErrorMessage="Please enter the title"></asp:RequiredFieldValidator>
                </td>
        </tr>
        <tr>
            <td align="right" valign="top">
            <span style="color: #FF0000">*</span>
                Url</td>
            <td align="left" valign="top" >
                <asp:TextBox ID="txtQuickUrl" Width="280px" runat="server" MaxLength="50" onKeyUp="trimstring(this.id,this.value);"></asp:TextBox>
                <asp:RequiredFieldValidator ID="reqQuickUrl" runat="server" ControlToValidate="txtQuickUrl" ValidationGroup="QuickLinks" ErrorMessage="Please enter the url"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td align="right" valign="top">
                &nbsp;</td>
            <td align="left" valign="top">
                <asp:Button ID="btnQuickSubmit" runat="server" CssClass="bg_pop_up_btn" ToolTip="Submit"
                    ValidationGroup="QuickLinks"
                    Text="Submit" onclick="btnQuickSubmit_Click1" />
                    <%--<asp:Button ID="btnQuickClear" runat="server" CssClass="bg_pop_up_btn" ValidationGroup="QuickLinks" ToolTip="Clear"
                     OnClientClick="javascript:ClearTextboxes();" Text="Clear" />--%>
            </td>
        </tr>
       
    </table>
</div>

<cc1:ModalPopupExtender ID="mpeQuickLinks" TargetControlID="hdnedit" BackgroundCssClass="modalBackground" PopupControlID="quicklinks" CancelControlID="imgbtnQuickClose" PopupDragHandleControlID="header" runat="server">
</cc1:ModalPopupExtender>

<asp:HiddenField ID="hdnedit" runat="server" />

<asp:HiddenField ID="hdnValue" runat="server" />

SharePoint online - Get List-item attachments and Display to div

Step 1 : Create a List ex: TestList and attach few images Step 2 : Copy and Pastet the below coding in App.js var  Items =  null ; ...