Monday, 4 June 2012

ASCX.CS(.ascx.cs)

STEP 1: Create a VisualWebPart like HealthAndWellness

STEP 2: Write a coding in HealthAndWellnessUserControl.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 Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace VCSB01.INTRANET.VCSBWebPart.HealthAndWellness
{
    public partial class HealthAndWellnessUserControl : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsSuperAdmin || IsAdmin || IsManager)
            {
                imgbtnHealthAdd.Visible = true;

            }
            else
            {
                imgbtnHealthAdd.Visible = false;

            }
        }

        protected void btnHealthSubmit_Click(object sender, EventArgs e)
        {

            if (!string.IsNullOrEmpty(txtHealthTitle.Text) && !string.IsNullOrEmpty(txtHealthDescription.Text) && !string.IsNullOrEmpty(fldHealth.FileName))
            {
                HealthAndWellnessBL healthAndWellnessBL = new HealthAndWellnessBL(txtHealthTitle.Text, txtHealthDescription.Text, fldHealth);
                if (healthAndWellnessBL.insert())
                {

                    //insert success
                }
                else
                {
                    //fail
                }
            }

            clear();
        }
      
        public void clear()
        {
            txtHealthTitle.Text = string.Empty;
            txtHealthDescription.Text = string.Empty;
        }

        protected void btnHealthClear_Click(object sender, EventArgs e)
        {
            clear();
        }
    }
}

ASCX(.ascx)

STEP 1: Create a VisualWebPart like PropellerStudio

STEP 2: Write a coding in PropellerStudioUserControl.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="PropellerStudioUserControl.ascx.cs" Inherits="VCSB01.INTRANET.VCSBWebPart.PropellerStudio.PropellerStudioUserControl" %>

 <%@ 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" />
<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="menu_bg_sd">
    <div class="menu_left_sd">
    </div>
    <div class="menu_right_sd">
    </div>
    <div class="add_side_left">
        <h4>
            Propeller Studio</h4>
    </div>
    <div class="add_side_right">
        <asp:ImageButton ID="imgbtnPropellerAdd" ImageUrl="/_layouts/Images/VCSB/plus_nor.gif"
            runat="server"  />
    </div>
</div>
<div class="menu_bg_sd_ind">
    <div class="menu_left_sd_ind">
    </div>
    <div class="menu_right_sd_ind">
    </div>
    <div class="box_inner_m2">
       <table>
       <tr>
       <td>
           <asp:GridView ID="grdPropeller"  Width="100%" runat="server" BorderStyle="None"
               AutoGenerateColumns="False" GridLines="None"
               ShowHeader="False">
               <Columns>
               <asp:TemplateField>
            <ItemStyle Width="150px"/>
            <ItemTemplate>
             <asp:HyperLink ID="HypFileImage" NavigateUrl='<%# Eval("FilePathUrl") %>' runat="server">
             <asp:Image ID="imgFileImage" ImageUrl='<%# Eval("FileImage")%>' Height="50px" Width="50px" runat="server" />
             </asp:HyperLink>
            </ItemTemplate>
              </asp:TemplateField>
                   <asp:TemplateField>
                       <ItemStyle Width="350px" />
                       <ItemTemplate>
                           <asp:HyperLink ID="HypTitle" NavigateUrl='<%# Eval("FilePathUrl") %>' runat="server"><%# Eval("Title") %></asp:HyperLink>                                                
                     
                       <br />
                          </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
       </td>
       </tr>
       </table>
    </div>   
    <div class="readmore">
        <asp:LinkButton ID="lnkbtnPropellerReadMore" PostBackUrl="/Pages/PropellerStudioReadMore.aspx" runat="server">Read more</asp:LinkButton>
    </div>
</div>

<div class="menu_bg_sd_bot">
                        <div class="menu_left_sd_bot">
                        </div>
                        <div class="menu_right_sd_bot">
                        </div>
                    </div>


<div id="propellerdiv" 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;Propeller Studio</td>
            <td class="bg_pop_uphead">
                <asp:ImageButton ID="imgbtnPropellerClose" runat="server" Height="20px"
                    ImageUrl="/_layouts/images/VCSB/closebtn.png"  />
            </td>
        </tr>
        <tr>
            <td align="right" valign="top">
                Title</td>
            <td align="left" valign="top">

                <asp:TextBox ID="txtPropellerTitle" Width="280px" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td align="right" valign="top">
                Description</td>
            <td align="left" valign="top">
                <asp:TextBox ID="txtPropellerDescription" Width="280px" runat="server" TextMode="MultiLine"></asp:TextBox>
            </td>
        </tr>
        <tr>
            <td align="right" valign="top">
                Upload Documents</td>
            <td align="left" valign="top">
                <asp:FileUpload ID="fldPropeller" runat="server" />
            </td>
        </tr>
        <tr>
            <td align="right" valign="top">
                &nbsp;</td>
            <td align="left" valign="top">
                <asp:Button ID="btnPropellerSubmit" runat="server" CssClass="bg_pop_up_btn"
                    Text="Submit" onclick="btnPropellerSubmit_Click" />
                <asp:Button ID="btnPropellerClear" runat="server" CssClass="bg_pop_up_btn"
                    Text="Clear" onclick="btnPropellerClear_Click" />
            </td>
        </tr>
        <tr>
            <td align="right" valign="top">
                &nbsp;</td>
            <td align="left" valign="top">
                &nbsp;
            </td>
        </tr>
    </table>
</div>

<cc1:ModalPopupExtender ID="mpePropeller" TargetControlID="imgbtnPropellerAdd" BackgroundCssClass="modalBackground" PopupControlID="propellerdiv" CancelControlID="imgbtnPropellerClose" PopupDragHandleControlID="header" runat="server">
</cc1:ModalPopupExtender>

ASCX.CS (ascx.cs)

STEP 1: Create a VisualWebPart like PropellerStudio

STEP 2: Write a coding in PropellerStudioUserControl.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 Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace VCSB01.INTRANET.VCSBWebPart.PropellerStudio
{
    public partial class PropellerStudioUserControl : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            try
            {        
            if (!IsPostBack)
            {
                if (IsSuperAdmin || IsAdmin || IsManager)
                {
                    imgbtnPropellerAdd.Visible = true;

                }
                else
                {
                    imgbtnPropellerAdd.Visible = false;

                }
                BindPropellerstudioData();
              
            }
           }
catch (Exception ex)
            {
                ErrorHelper.Add(Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace));
                SPUtility.TransferToErrorPage(MessageHelper.Message(MessageMode.CommonErrorMessage));
            }
        }

        private void BindPropellerstudioData()
        {
            PropellerStudioBL objpropData = new PropellerStudioBL();
            grdPropeller.DataSource = objpropData.GetPropellerData();
            grdPropeller.DataBind();
        }
      
      
        protected void btnPropellerSubmit_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPropellerTitle.Text) && !string.IsNullOrEmpty(txtPropellerDescription.Text) && !string.IsNullOrEmpty(fldPropeller.FileName))
            {
                PropellerStudioBL propellerStudioBL = new PropellerStudioBL(txtPropellerTitle.Text, txtPropellerDescription.Text, fldPropeller);
                if (propellerStudioBL.insert())
                {

                    BindPropellerstudioData();
                    //insert success
                }
                else
                {
                    //fail
                }
            }

            clear();
        }
        public void clear()
        {
            txtPropellerTitle.Text = string.Empty;
            txtPropellerDescription.Text = string.Empty;
        }

        protected void btnPropellerClear_Click(object sender, EventArgs e)
        {
            clear();
        }
    }
}

DL(DAL)

STEP 1: Create a class file like PropellerStudioDL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VCSB.INTRANET.BLL;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;
using System.Web.UI.WebControls;
using System.Data;


namespace VCSB.INTRANET.DAL
{
    public class PropellerStudioDL
    {
       
        public static bool insert(PropellerStudioBL propellerStudioBL)
        {
          
            bool insert = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                    PropellerStudioItem propellerStudioItem = new PropellerStudioItem()
                    {
                        Title = propellerStudioBL.Propellertitle,
                        Description = propellerStudioBL.Description,

                    };
                    context.PropellerStudio.InsertOnSubmit(propellerStudioItem);
                    context.SubmitChanges();

                    if (propellerStudioItem.Id > 0)
                    {
                        insert = true;
                        if (propellerStudioBL.FilePath.FileName != null && propellerStudioBL.FilePath.FileName != string.Empty)
                        {
                            if (InsertAttachment(Convert.ToInt32(propellerStudioItem.Id), propellerStudioBL.FilePath))
                            {
                                insert = true;
                            }
                        }
                        else
                        {
                            insert = true;
                        }
                    }
                }
            });
            return insert;
        }

        private static bool InsertAttachment(int listid, FileUpload fldupload)
        {
           
                SPWeb oWeb = SPContext.Current.Site.RootWeb;
                SPList oList = oWeb.Lists["PropellerStudio"];
                SPListItem item = oList.GetItemById(listid);

               
                string[] chkimage = fldupload.FileName.ToString().Split('.');
               
                    if (chkimage[1] == "doc" || chkimage[1] == "docx" || chkimage[1] == "xls" || chkimage[1] == "xlsx" || chkimage[1] == "ppt" || chkimage[1] == "pptx" || chkimage[1] == "txt" || chkimage[1] == "pdf")
                    {
                        item.Attachments.Add(fldupload.FileName, fldupload.FileBytes);
                        item.Update();
                        return true;
                    }
                   
                else
                {
                    return false;
                }
              
        }
        public static bool update(PropellerStudioBL propellerStudioBL)
        {
            bool update = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
           {
                using (VCSBINTRANETDataContext datacontxt = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                   

                     var itemUpdate = (from updateequery in datacontxt.PropellerStudio
                                       where updateequery.Id == Convert.ToInt32(propellerStudioBL.ID)
                                       select updateequery).First();

                     itemUpdate.Title = propellerStudioBL.Propellertitle;
                     itemUpdate.Description = propellerStudioBL.Description;
                     datacontxt.SubmitChanges();
                     if (!string.IsNullOrEmpty(Convert.ToString(propellerStudioBL.FilePath)))
                     {
                         string imagepath = Convert.ToString(GetListAttachmentsFile(Convert.ToInt32(propellerStudioBL.ID)));
                         DeleteAttachment(Convert.ToInt32(propellerStudioBL.ID), imagepath);
                         if (InsertAttachment(Convert.ToInt32(propellerStudioBL.ID), propellerStudioBL.FilePath))
                         {
                             update = true;
                         }
                     }   
                }
           });

            return update;
        }

        public static bool DeleteAttachment(int listid, string imagepath)
        {
            SPWeb oWeb = SPContext.Current.Site.RootWeb;
            SPList oList = oWeb.Lists["PropellerStudio"];
            SPListItemCollection oListItems = oList.Items;
            foreach (SPListItem item in oListItems)
            {
                if ((int)item["ID"] == Convert.ToInt32(listid))
                {
                    SPAttachmentCollection collAttachments = item.Attachments;
                    if (collAttachments.Count > 0)
                    {
                        foreach (var attachment in collAttachments)
                        {
                            item.Attachments.Delete(attachment.ToString());
                            if (collAttachments.Count == 0)
                            {
                                break;
                            }

                        }
                        item.Update();
                    }
                }
            }

            return true;

        }
        public static System.Data.DataTable GetAllListItem(PropellerStudioBL propellerStudioBL)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Title");
            dt.Columns.Add("FileImage");
            dt.Columns.Add("Description");
            dt.Columns.Add("FilePathUrl");

            DataRow row;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                    var quer = from propellerda in context.PropellerStudio
                               orderby propellerda.Id descending
                               select propellerda;

                    if (quer != null)
                    {
                        foreach (PropellerStudioItem item in quer)
                        {
                            row = dt.Rows.Add();
                            row["ID"] = item.Id.ToString();
                            row["Title"] = item.Title.ToString();
                            row["Description"] = item.Description.ToString();
                            row["FileImage"] = GetListAttachments(Convert.ToInt32(item.Id));
                            row["FilePathUrl"] = GetListAttachmentsFile(Convert.ToInt32(item.Id));
                        }
                    }
                }
                //grd.DataSource = dt;
                //grd.DataBind();
            });
            return dt;
        }


        public static System.Data.DataTable GetPropellerData(PropellerStudioBL propellerStudioBL)
        {
            DataTable dt = new DataTable();
              dt.Columns.Add("Title");
               dt.Columns.Add("FileImage");
               dt.Columns.Add("FilePathUrl");
                DataRow row;
                SPSecurity.RunWithElevatedPrivileges(delegate()
              {
                  using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                  {
                      var quer = from propellerda in context.PropellerStudio
                                 orderby propellerda.Id descending
                                 select propellerda;

                      if (quer != null)
                      {
                          foreach (PropellerStudioItem item in quer.Take(3))
                          {
                              row = dt.Rows.Add();
                              row["Title"] = item.Title.ToString();
                              row["FileImage"] = GetListAttachments(Convert.ToInt32(item.Id));
                              row["FilePathUrl"] = GetListAttachmentsFile(Convert.ToInt32(item.Id));
                          }
                      }
                  }
              });
            return dt;
        }
     
        private static object GetListAttachmentsFile(int listid)
        {
            string URL = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWeb oWeb = SPContext.Current.Site.RootWeb;
                SPList oList = oWeb.Lists["PropellerStudio"];
                SPListItemCollection oListItems = oList.Items;
                foreach (SPListItem item in oListItems)
                {
                    if ((int)item["ID"] == Convert.ToInt32(listid))
                    {
                        SPAttachmentCollection collAttachments = item.Attachments;
                        foreach (var attachment in collAttachments)
                        {
                            string[] chkimage = attachment.ToString().Split('.');
                            if (chkimage[1] == "doc" || chkimage[1] == "docx" || chkimage[1] == "xls" || chkimage[1] == "xlsx" || chkimage[1] == "ppt" || chkimage[1] == "pptx" || chkimage[1] == "txt" || chkimage[1] == "pdf")
                            {
                                URL = (SPEncode.HtmlEncode(item.Attachments.UrlPrefix + attachment.ToString()));
                            }
                        }
                    }
                }
            });
                if (URL != null)
                {
                    return URL;
                }
                else
                {
                    return URL = "";
                }
           
        }

        private static object GetListAttachments(int listid)
        {
            string URL = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWeb oWeb = SPContext.Current.Site.RootWeb;
                SPList oList = oWeb.Lists["PropellerStudio"];
                SPListItemCollection oListItems = oList.Items;
                foreach (SPListItem item in oListItems)
                {
                    if ((int)item["ID"] == Convert.ToInt32(listid))
                    {
                      
                        SPAttachmentCollection collAttachments = item.Attachments;
                        foreach (var attachment in collAttachments)
                        {
                            string[] chkimage = attachment.ToString().Split('.');
                            if (chkimage[1] == "doc" || chkimage[1] == "docx")
                            {
                                URL = @"~\_Layouts\Images\VCSB\doc.png";
                                //URL = (SPEncode.HtmlEncode(item.Attachments.UrlPrefix + attachment.ToString()));
                            }
                            else if (chkimage[1] == "pdf")
                            {
                                URL = @"~\_Layouts\Images\VCSB\pdf.png";
                            }
                            else if (chkimage[1] == "xls" || chkimage[1] == "xlsx")
                            {
                                URL = @"~\_Layouts\Images\VCSB\xls.png";
                            }
                            else if (chkimage[1] == "ppt" || chkimage[1] == "pptx")
                            {
                                URL = @"~\_Layouts\Images\VCSB\ppt.png";
                            }
                            else if (chkimage[1] == "txt")
                            {
                                URL = @"~\_Layouts\Images\VCSB\txt.png";
                            }
                        }
                       
                    }
                }
            });
            if (URL != null)
            {
                return URL;
            }
            else
            {

                return URL = @"~\_Layouts\Images\VCSB\doc_not_av2.png";
            }
        }
        public static bool delete(PropellerStudioBL propellerStudioBL)
        {
          
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (VCSBINTRANETDataContext datacontxt = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                     var itemDelete = (from deletequery in datacontxt.PropellerStudio
                                       where deletequery.Id == Convert.ToInt32(propellerStudioBL.ID)
                                       select deletequery).First();

                     datacontxt.PropellerStudio.DeleteOnSubmit(itemDelete);
                     datacontxt.SubmitChanges();
                }
            });
            return true;
        }

        public static System.Data.DataTable GetSingleRowListItem(PropellerStudioBL propellerStudioBL)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("ID");
            dt.Columns.Add("Title");
            dt.Columns.Add("Description");
            dt.Columns.Add("FileImage");
            dt.Columns.Add("FilePathUrl");
            DataRow row;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {
                    var quer = from PropellerStudioData in context.PropellerStudio
                               where PropellerStudioData.Id == propellerStudioBL.ID
                               select PropellerStudioData;

                    if (quer != null)
                    {
                        foreach (PropellerStudioItem item in quer)
                        {
                            row = dt.NewRow();
                            row["ID"] =Convert.ToString(item.Id);
                            row["Title"] =Convert.ToString(item.Title);
                            row["Description"] = Convert.ToString(item.Description);
                            row["FileImage"] = GetListAttachments(Convert.ToInt32(item.Id));
                            row["FilePathUrl"] = GetListAttachmentsFile(Convert.ToInt32(item.Id));
                            dt.Rows.Add(row);

                        }
                    }
                }
            });
            return dt;
        }
    }
}

Interface


STEP 1: Create a class file like IVCSBIntranetBL.CS


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

namespace VCSB.INTRANET.BLL
{
    interface  IVCSBIntranetBL
    {

        #region variables
        int ID
        {
            get;
            set;
        }
        string Title
        {
            get;
            set;
        }
        #endregion

        #region Methods

        bool insert();
        bool update();
        bool delete();

        DataTable GetAllListItem();      
        void GetSingleRowListItem(int id);

        #endregion

    }
}

BL(BLL)



STEP 1: Create the class file like PropellerStudioBL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VCSB.INTRANET.DAL;
using System.Web.UI.WebControls;
namespace VCSB.INTRANET.BLL
{
    public class PropellerStudioBL:IVCSBIntranetBL
    {

        //empty constructor
        int _listId;

        string _title = string.Empty, _description = string.Empty; FileUpload _filePath;
        string _propellertitle;

        public string Propellertitle
        {
            get { return _propellertitle; }
            set { _propellertitle = value; }
        }
        public FileUpload FilePath
        {
            get { return _filePath; }
            set { _filePath = value; }
        }

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }

     
        public PropellerStudioBL()
        {

        }
        public PropellerStudioBL(int listId)
        {
          
            this.ID = listId;
           
        }
        public PropellerStudioBL(string propellertitle, string description, FileUpload filePath)
        {
            this.Propellertitle = propellertitle;
            this.Description = description;
            this.FilePath = filePath;
        }

        public PropellerStudioBL(int propellerID,string propellertitle, string description, FileUpload filePath)
        {
            this.ID = propellerID;
            this.Propellertitle = propellertitle;
            this.Description = description;
            this.FilePath = filePath;
        }
       
        public string Title
        {
            get
            {
                return _title;
            }
            set
            {
                value = _title;
            }
        }

        public bool insert()
        {
           
          
           return PropellerStudioDL.insert(this);
        }

        public bool update()
        {
            return PropellerStudioDL.update(this);
        }

        public bool delete()
        {
            return PropellerStudioDL.delete(this);
          
        }

        public System.Data.DataTable GetAllListItem()
        {
           return PropellerStudioDL.GetAllListItem(this);
          
        }


        public System.Data.DataTable GetPropellerData()
        {
          
           return PropellerStudioDL.GetPropellerData(this);
        }

        public System.Data.DataTable GetSingleRowListItem()
        {
           
            return PropellerStudioDL.GetSingleRowListItem(this);
        }
       
        public int ID
        {
            get { return _listId; }
            set { _listId = value; }
        }


        public void GetSingleRowListItem(int id)
        {
            throw new NotImplementedException();
        }
    }
}

Friday, 27 April 2012

Weather Webpart


STEP 1:

Create EmptySharePoint project

STEP 2:

Create the simple webpart like weatherwebpart(Not Visualwebpart)



STEP 3:

Create one class file like (condition.cs) and paste the coding

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

namespace WeatherWebPart.WeatherWebPart
{
    class Conditions
    {
        string city = "No Data";
        string dayOfWeek = DateTime.Now.DayOfWeek.ToString();
        string condition = "No Data";
        string tempC = "No Data";
        string tempC1 = "No Data";
        string humidity = "No Data";
        string wind = "No Data";
        string high = "No Data";
        string low = "No Data";
        string icon = "No Data";

        public string TempC1
        {
            get { return tempC1; }
            set { tempC1 = value; }
        }
        public string City
        {
            get { return city; }
            set { city = value; }
        }
        public string DayOfWeek
        {
            get { return dayOfWeek; }
            set { dayOfWeek = value; }
        }

        public string Condition
        {
            get { return condition; }
            set { condition = value; }
        }

        public string TempC
        {
            get { return tempC; }
            set { tempC = value; }
        }
        public string Humidity
        {
            get { return humidity; }
            set { humidity = value; }
        }
        public string Wind
        {
            get { return wind; }
            set { wind = value; }
        }
        public string High
        {
            get { return high; }
            set { high = value; }
        }
        public string Low
        {
            get { return low; }
            set { low = value; }
        }
        public string Icon
        {
            get { return icon; }
            set { icon = value; }
        }
    }
}



STEP 4:

Select weatherwebpart.cs --> paste the coding

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.Xml;
using System.Collections;
using System.Collections.Generic;

namespace WeatherWebPart.WeatherWebPart
{
    [ToolboxItemAttribute(false)]
    public class WeatherWebPart : WebPart
    {
        private String _location = null;
        [WebBrowsable(),
        Personalizable(),
        System.ComponentModel.Category("Configuration"),
        WebDisplayName("Location:")]
        public String Location
        {
            get { return _location; }
            set { _location = value; }
        }
        private XmlDocument xmlDoc = new XmlDocument();
        private Conditions currentCondition;
        private List<Conditions> forecastCondition;

        protected override void Render(HtmlTextWriter writer)
        {
            if (Location == null)
            {
                writer.Write("Please specify a location in the web part editor.");
                return;
            }

            xmlDoc.Load(string.Format("http://www.google.com/ig/api?weather={0}", Location));
            currentCondition = getCurrentConditions();
            forecastCondition = getForecastedConditions();

            if (currentCondition == null)
            {
                writer.Write("There was an error making an API call.");
                return;
            }

            writer.Write("<div class=\"lft-weatherheader\">{0}</div>", Location);

            writer.Write("<table class=\"lft-weathertable\">");

            if (currentCondition.Icon.Equals("")) { writer.Write("<tr><td><img src=\"/_layouts/images/BLANK.GIF\" />"); } else { writer.Write("<tr><td><img src="+currentCondition.Icon+" />"); }
       
         

            writer.Write("</td><td>Now ");
            writer.Write("{0}&deg;F</td></tr>", currentCondition.TempC);
            writer.Write("</td><td>Now ");
            writer.Write("{0}&deg;C</td></tr>", currentCondition.TempC1);
            writer.Write("</td><td>Now ");
            writer.Write("{0}</td></tr>", currentCondition.Wind);
            writer.Write("</td><td>Now ");
            writer.Write("{0}</td></tr>", currentCondition.Humidity);


            foreach (Conditions fc in forecastCondition)
            {

                writer.Write("<tr><td><img src=\"http://www.google.com{0}\" /></div>", fc.Icon);
             
             

               // writer.Write("</td><td>{0} ", fc.DayOfWeek);
               // writer.Write("{0}&deg;C", fc.High);
                //writer.Write(" | ");
                //writer.Write("{0}&deg;C</td></tr>", fc.Low);

            }
            writer.Write("</table>");

        }

        private Conditions getCurrentConditions()
        {
            Conditions currentConditions = new Conditions();

            if (xmlDoc.SelectSingleNode("xml_api_reply/weather/problem_cause") != null)
            {
                currentConditions = null;

            }
            else
            {
                currentConditions.City = xmlDoc.SelectSingleNode("/xml_api_reply/weather/forecast_information/city").Attributes["data"].InnerText;
                currentConditions.Condition = xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/condition").Attributes["data"].InnerText;
                currentConditions.TempC1 =Convert.ToString(xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/temp_c").Attributes["data"].InnerText);
                currentConditions.TempC =Convert.ToString(convertcelsiustofahrenheit(Convert.ToDouble(xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/temp_c").Attributes["data"].InnerText)));
                currentConditions.Humidity = xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/humidity").Attributes["data"].InnerText;
                currentConditions.Wind = xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/wind_condition").Attributes["data"].InnerText;
                currentConditions.Icon = @"C:\Users\Administrator\Desktop\mostly_sunny.png"; //xmlDoc.SelectSingleNode("/xml_api_reply/weather/current_conditions/icon").Attributes["data"].InnerText;
            }

            return currentConditions;
        }

        private List<Conditions> getForecastedConditions()
        {
            List<Conditions> days = new List<Conditions>();

            if (xmlDoc.SelectSingleNode("xml_api_reply/weather/problem_cause") != null)
            {
                days = null;

            }
            else
            {
                XmlNodeList xnList = xmlDoc.SelectNodes("/xml_api_reply/weather/forecast_conditions");
                foreach (XmlNode xn in xnList)
                {
                    Conditions day = new Conditions();
                    //day.DayOfWeek = xn["day_of_week"].Attributes["data"].InnerText;
                   // day.Low = ConvertFahrenheitToCelsius(Double.Parse(xn["low"].Attributes["data"].InnerText)).ToString();
                    //day.High = ConvertFahrenheitToCelsius(Double.Parse(xn["high"].Attributes["data"].InnerText)).ToString();
                    //day.Icon = xn["icon"].Attributes["data"].InnerText;
                    //days.Add(day);
                }
            }

            return days;
        }

        public static int ConvertFahrenheitToCelsius(double f)
        {
            return Convert.ToInt32((5.0 / 9.0) * (f - 32));
         
        }

        public static int convertcelsiustofahrenheit(double d)
        {
            return Convert.ToInt32((d*9/5+32));
        }
    }
}

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 ; ...