How to call SP.UI.Status in visual webpart - sharepoint

I have a scenario where i need to display an Alert banner with the title column in my list.
Below is the code which iam trying to use . But it is not displaying correctly. Can any one let me know Errorl
<script type="text/ecmascript" language="ecmascript">
var strStatusID;
function showInfo(strMessage) {
alert("Code sucess");
strStatusID = SP.UI.Status.addStatus(strMessage, true);
alert(strMessage.toString());
SP.UI.Status.setStatusPriColor(strStatusID, "yellow");
}
</script>
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="lblScripter" runat="server" Visible="false"></asp:Label>
</asp:Panel>
public void LoadGrid()
{
//System.Diagnostics.Debugger.Break();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
}
// strStatusID = SP.UI.Status.addStatus(strMessage, true);
lblScripter.Text = "<Script language='javascript;>showInfo('" + MessageShow + "');</script>";
}
else
{
lblScripter.Visible = false;
}
}
<asp:Timer runat="server" ID="UpdateTimer" Interval="6000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
System.Diagnostics.Debugger.Break();
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Alertlist"];
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Neq><FieldRef Name='NoOfDays' /><Value Type='Calculated'>0:00</Value></Neq></Where>";
SPListItemCollection _AlertListCollection = oSpList.GetItems(oQuery);
DataTable Table_Calendar = _AlertListCollection.GetDataTable();
if (Table_Calendar != null)
{
foreach (SPListItem item in _AlertListCollection)
{
MessageShow = item["Title"].ToString();
Enddate = DateTime.Parse(item["EndDate"].ToString());
}
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>";
if (Currenttime >= Enddate)
{
lblScripter.Text = "hi after date tim refreshed";
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {removeAllInfos();}, 'sp.js');</script>";
}
}
//else
//{
// lblScripter.Visible = false;
//}
}

Try to set :
lblScripter.Text = #"<script type=""text/javascript"">SP.SOD.executeOrDelayUntilScriptLoaded(function() {showInfo('" + MessageShow + "');}, 'sp.js');</script>"
Most likely this will solve your problem of calling the SP.UI.Status javascript functions before they have been loaded.

I Have solved this PFB code in order to acheive this. Thanks to my friend Hameed who has helped me to acheive the same
<script type="text/ecmascript" language="ecmascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(RegisterMethods);
function RegisterMethods() {
showInfo();
RemoveLastStatus();
}
function showInfo() {
var strMessage = document.getElementById('<%= Message.ClientID %>').value;
var strstatus = document.getElementById('<%= StartStatus.ClientID %>').value;
if (strMessage != null) {
if (strstatus != "false") {
var strStatusID;
strStatusID = SP.UI.Status.addStatus(strMessage);
SP.UI.Status.setStatusPriColor(strStatusID, "red");
document.getElementById('<%= StartStatus.ClientID %>').value = "false";
document.getElementById('<%= StatusId.ClientID %>').value = strStatusID;
}
}
}
function RemoveLastStatus() {
var statusId = document.getElementById('<%= StatusId.ClientID %>').value;
var stopStatus = document.getElementById('<%= StopStatus.ClientID %>').value;
if (statusId != null) {
if (stopStatus == "true") {
SP.UI.Status.removeStatus(statusId);
statusId = '';
}
}
}
</script>
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="DateStampLabel" />
<asp:Label ID="lblScripter" runat="server" Visible="True"></asp:Label>
<asp:HiddenField ID="StartStatus" runat="server" />
<asp:HiddenField ID="StopStatus" runat="server" />
<asp:HiddenField ID="Message" runat="server" />
<asp:HiddenField ID="StatusId" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
CODEBEHIND.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Globalization;
using System.Data;
using System.Linq;
using Microsoft.SharePoint.Utilities;
namespace ITBANNER
{
public partial class ITOpsBannerUserControl : UserControl
{
String MessageShow = string.Empty;
DateTime Enddate, starttime;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItemCollection items = oSpList.Items;
SPListItem item;
for (int i = 0; i < items.Count; i++)
{
item = items[i];
Console.WriteLine("Index = {0} ID = {1}", i, item.ID);
}
SPListItem item = oSpList.GetItemById(3);
Message.Value = item["Title"].ToString();
starttime = DateTime.Parse(item["StartDate"].ToString());
if (Currenttime >= starttime)
{
StartStatus.Value = "true";
StopStatus.Value = "false";
}
}
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
DateTime Currenttime = DateTime.Parse(DateStampLabel.Text.ToString());
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["AlertList"];
SPListItem item = oSpList.GetItemById(3);
Enddate = DateTime.Parse(item["EndDate"].ToString());
if (Currenttime >= Enddate)
{
StopStatus.Value = "true";
}
}
//public void HideStatusBar()
//{
// string script = "document.onreadystatechange=fnRemoveAllStatus; function fnRemoveAllStatus(){removeAllStatus(true)};";
// this.Page.ClientScript.RegisterClientScriptBlock(typeof(Type), "statusBarRemover", script, true);
//}
}
}

Related

Controlling cart with session

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
</div>
<br /><br />
<input id="updatecart" type="submit" value="update Cart" />
}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

My Shopping Cart is not working as expected in ASP.NET MVC 5

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

asp gridview export to excel hide column

Can someone please take a look at my code? this code works perfectly but i want to remove the 1st and 2nd column when the data exported to excel. i try GridView1.Columns[0].Visible = false; but its not working.
here's my aspx
<%# Page Title="VRQ" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="EmployeePage.aspx.cs" Inherits="EmployeePage"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('innerdata').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
function OpenFile(KEYW) {
window.open("ResumePage.aspx?bid=" + KEYW, "ResumeContext");
}
</script>
<asp:Button ID="btnbacksearch" runat="server" Text="Back to Search"
Width="127px" OnClick="btnbacksearch_Click" CssClass="plainbutton" />
<asp:Button ID="btnExportToExcel" runat="server" OnClick="btnExportToExcel_Click"
Text="Export Results to Excel" Width="174px" CssClass ="plainbutton" />
<asp:Button
ID="btnGenerateSF" runat="server" OnClick="btnGenerateSF_Click"
Text="Generate Resume" Width="137px" CssClass ="plainbutton"
Visible="False" />
<asp:DropDownList ID="ddStatus" runat="server"
onselectedindexchanged="ddStatus_SelectedIndexChanged" AutoPostBack="True"
Visible="False" Width="150px">
<asp:ListItem Selected="True" Value="Active">Active Personnel</asp:ListItem>
<asp:ListItem Value="Inactive">Inactive Personnel</asp:ListItem>
</asp:DropDownList>
<div style="font-size: 11pt; font-family: Tahoma; text-align:center "><strong>
SEARCH SUMMARY</strong></div>
<div style="font-size: 10pt; font-family: Tahoma; text-align:center ">
<asp:Label ID="LabelCaption" runat="server" Text="Label"></asp:Label>
</div>
<div id = "innerdata" style="size: landscape;" >
<asp:GridView ID="GridView1" runat="server"
CellPadding="4" DataSourceID="SqlDataSource1"
onrowcreated="GridView1_RowCreated"
AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
DataKeyNames="IDNo" AllowSorting="True" Width="100%"
PageSize="30" EmptyDataText="No Existing Records." CssClass="GridView"
onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False"
onsorted="GridView1_Sorted" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkSelect" Text="View" CommandName ="Select" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkPrintRep1" Text="Project Selection" CommandName ="PrintSF330" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="70px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="fullname" HeaderText="Name" ReadOnly="True"
SortExpression="fullname" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="YearsExperience" HeaderText="Experience"
SortExpression="YearsExperience" >
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Job" HeaderText="Position" SortExpression="Job" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Search Results" SortExpression ="SearchDetails">
<ItemTemplate>
<%# HighlightText(Convert.ToString(Eval("SearchDetails"))) %> </ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
<RowStyle CssClass="GridRowStyle"/>
<PagerStyle HorizontalAlign="Center" />
<SelectedRowStyle CssClass="GridSelected" />
<HeaderStyle CssClass="GridHeader" Height="10px" />
<PagerStyle CssClass="GridFooterStyle"/>
</asp:GridView></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HRIS_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:HRIS_ConnectionString.ProviderName %>"
SelectCommand="select i.IDNo,concat(lastname,', ',firstname,' ',middlename) as fullname,e.tYrsExperience as YearsExperience,p.Description as Job,'' as SearchDetails FROM employeesinfo i inner join ecd e on e.empid=i.idno
left outer join Position p on p.idno = e.presentjob">
</asp:SqlDataSource>
<vt:MessageBox ID="MessageBox1" runat="server"></vt:MessageBox>
</asp:Content>
and here's my aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
public partial class EmployeePage : System.Web.UI.Page
{
string sqry = ""; string scolumn = "";
string origQry = String.Empty;
public string keyword = "";
public string curAlpha = "";
public int iCtr = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["QRY_CONDITIONS"] == null) Response.Redirect("Default.aspx");
scolumn = Session["QRY_DETAIL"].ToString();
sqry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user == null) return;
if (user.IsSuperAdmin && sqry == "ALL")
{
ddStatus.Visible = true;
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") ;
}
else if(sqry == "ALL")
{
ddStatus.Visible = false;
sqry = " where ifnull(i.activestatus,0) = 1 ";
}
origQry = sqry;
if (Request.QueryString["keyword"] != null) keyword = Request.QueryString["keyword"].ToString().TrimEnd().TrimStart();
if (!IsPostBack)
{
if (keyword == "")
{
sqry = sqry + " and i.lastname like 'A%' ";
Session["QRY_alpha"] = " and i.lastname like 'A%' ";
curAlpha = "A";
}
LoadStates();
BindData();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
curAlpha = (string)ViewState["curAlpha"];
}
protected override object SaveViewState()
{
ViewState["curAlpha"] = curAlpha;
return base.SaveViewState();
}
private void BindData()
{
modPublic myMod = new modPublic();
SqlDataSource1.SelectCommand = "SELECT distinct i.idno,concat(i.lastname,', ',i.firstname,' ',i.middlename) as fullname,e.tYrsExperience as YearsExperience,e.Position as Job," + scolumn + " as SearchDetails FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + sqry + " order by i.lastname,i.firstname";
SqlDataSource1.Select(new DataSourceSelectArguments());
object o = myMod.ExecuteScalar("select count(distinct i.idno) as ctr FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + origQry + " ");
LabelCaption.Text = o.ToString() + " Record(s) found";
if (keyword == "")
{
GridView1.AllowPaging = false;
GridView1.Columns[5].Visible = false;
}
else
{
GridView1.Columns[5].Visible = true;
}
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AlphaPaging")
{
curAlpha = e.CommandArgument.ToString();
sqry = sqry + " and i.lastname like '" + e.CommandArgument + "%'";
Session["QRY_alpha"] = " and i.lastname like '" + e.CommandArgument + "%'";
GridView1.AllowPaging = false;
BindData();
SaveStates();
//this.SqlDataSource1.SelectCommand = "Select * from [Table_1] WHERE theName LIKE '" + e.CommandArgument + "%'";
}
if (e.CommandName == "PrintSF330")
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=" + e.CommandArgument.ToString() + " ");
}
else if (e.CommandName == "Select")
{
SaveStates();
loadECD(e.CommandArgument.ToString());
}
}
//protected override object SaveViewState()
//{
// ViewState["alphacond"] = alphacond;
// return base.SaveViewState();
//}
//protected override void LoadViewState(object savedState)
//{
// if (Page.IsPostBack)
// {
// base.LoadViewState(savedState);
// alphacond = ViewState["alphacond"].ToString();
// }
//}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// e.Row.Attributes.Add("OnClick", "javascript:" + Page.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
if (keyword == "")
{
if (e.Row.RowType == DataControlRowType.Footer)
{
GridViewRow grv = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
this.GridView1.Controls[0].Controls.Add(grv);
TableCell cell = new TableCell();
grv.Cells.Add(cell);
if (keyword == "")
cell.ColumnSpan = 5;
else
cell.ColumnSpan = 6;
for (int i = 65; i <= (65 + 25); i++)
{
string s = Char.ConvertFromUtf32(i);
if (s == curAlpha)
{
Label lt = new Label();
lt.Text = "[" + s + "]";
lt.Font.Bold = true;
lt.Font.Size = new FontUnit(12);
lt.Style["text-align"] = "middle";
cell.Controls.Add(lt);
}
else
{
LinkButton lb = new LinkButton();
lb.Text = s + " ";
lb.CommandArgument = s;
lb.CommandName = "AlphaPaging";
cell.Controls.Add(lb);
}
}
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
GridView1.Columns[0].Visible = false;
GridView1.AllowPaging = false;
BindData();
GridView1.DataBind();
GridViewExportUtil.Export("ReportResultsPage.xls", this.GridView1);
GridView1.AllowPaging = true;
BindData();
GridView1.Columns[0].Visible = false;
}
private void SaveStates()
{
if (Session["QRY_alpha"] == null) Session["QRY_alpha"] = "";
sqry = Session["QRY_CONDITIONS"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user.IsSuperAdmin && sqry == "ALL")
{
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") + Session["QRY_alpha"].ToString();
origQry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0");
}
else if (sqry == "ALL")
{
sqry = " where ifnull(i.activestatus,0) = 1 " + Session["QRY_alpha"].ToString();
origQry = " where ifnull(i.activestatus,0) = 1 ";
}
else
{
sqry = Session["QRY_CONDITIONS"].ToString() + Session["QRY_alpha"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
}
string tmp = "";
tmp = sqry + "|" +
scolumn + "|" +
keyword + "|" +
GridView1.SelectedIndex.ToString() + "|" +
GridView1.PageIndex.ToString() + "|" +
ddStatus.SelectedIndex.ToString() + "|" +
curAlpha + "|" +
origQry;
Session["PrevState"] = tmp;
}
public void LoadStates()
{
string tmp = (string)Session["PrevState"];
if (tmp == null)
{
return;
}
string[] arr = tmp.Split(new char[] { '|' });
sqry = arr[0];
scolumn = arr[1];
keyword = arr[2];
GridView1.SelectedIndex = Convert.ToInt32(arr[3]);
GridView1.PageIndex = Convert.ToInt32(arr[4]);
ddStatus.SelectedIndex = Convert.ToInt32(arr[5]);
curAlpha = arr[6];
origQry = arr[7];
}
void loadECD(string _idno)
{
SaveStates();
Response.Redirect("~/ECDMain.aspx?i=" + _idno);
}
protected void btnbacksearch_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
protected void btnGenerateSF_Click(object sender, EventArgs e)
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=ALL&EmpIDs=" + GetEmpID());
}
private string GetEmpID()
{
string temp = ""; string empIDs = "";
foreach (GridViewRow gRow in GridView1.Rows)
{
temp = GridView1.DataKeys[gRow.RowIndex].Value.ToString();
empIDs = (empIDs == "" ? empIDs : empIDs + ",") + temp;
}
return "(" + empIDs + ")";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && keyword !="")
e.Row.Cells[5].Text = e.Row.Cells[5].ToString().Replace(keyword,"<span style=//background-color: #FFFF00;//>" + keyword + "</span>");
}
public string HighlightText(string InputTxt)
{
// This function is called whenever text is displayed in the FirstName and LastName
// fields from our database. If we're not searching then just return the original
// input, this speeds things up a bit
if (string.IsNullOrEmpty(keyword))
{
return InputTxt;
}
else
{
// Otherwise create a new regular expression and evaluate the FirstName and
// LastName fields against our search string.
Regex ResultStr = default(Regex);
ResultStr = new Regex(keyword.Replace(" ", "|"), RegexOptions.IgnoreCase);
return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));
}
}
public string ReplaceWords(Match m)
{
// This match evaluator returns the found string and adds it a CSS class I defined
// as 'highlight'
return "<span class=highlight>" + m.ToString() + "</span>";
}
//protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
//{
// if ((e.Row.RowType == DataControlRowType.DataRow))
// {
// //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
// ((LinkButton)e.Row.FindControl("lnkResume")).Attributes.Add("onclick", "javascript:OpenFile('" + GridView1.DataKeys[e.Row.RowIndex].Value + "-" + keyword + "')");
// }
//}
protected void btnGenWord_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridViewExportUtil.ExportWord("ReportResultsPage.doc", this.GridView1);
GridView1.AllowPaging = true;
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
BindData();
}
protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e)
{
sqry = sqry + " and i.lastname like '" + curAlpha + "%'";
BindData();
}
}
Please can someone help me. Thanks in advance
You need to rebind the gridview after using the RemoveAt()
GridView1.Columns.RemoveAt(0);
GridView1.DataBind();
When user clicks on export to excel you can disable the delete button, export it and re-enable once exported
GridView1.AutoGenerateDeleteButton = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");

How can I programmatically get Approval Status in SharePoint?

I wanted to programmatically get SharePoint Page Approval Status, I tried as below
public string GetApprovalStatus(string url, string listName, string fileref)
{
string result = string.Empty;
string caml = #"
" + fileref + #"
";
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listName];
SPQuery query = new SPQuery();
query.Query = caml;
SPListItemCollection myItems = list.GetItems(query);
if (myItems != null && myItems.Count > 0)
{
DataTable dt = myItems.GetDataTable();
result = dt.Rows[0]["_ModerationStatus"].ToString();
dt.Dispose();
}
}
}
return result;
}
And I return a number, how can I get the Approval Status in text?
Appreciate any help, thank you in advanced
The following code is from the MSDN article for SPModerationInformation.Status:
using (SPSite oSiteCollection = new SPSite("http://localhost"))
{
SPWebCollection collWebsites = oSiteCollection.AllWebs;
foreach (SPWeb oWebsite in collWebsites)
{
SPListCollection collLists = oWebsite.Lists;
foreach (SPList oList in collLists)
{
if (oList.BaseType == SPBaseType.DocumentLibrary)
{
SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oList;
if (!oDocumentLibrary.IsCatalog && oDocumentLibrary.EnableModeration ==
true)
{
SPQuery oQuery = new SPQuery();
oQuery.ViewAttributes =
"ModerationType='Moderator'";
SPListItemCollection collListItems =
oDocumentLibrary.GetItems(oQuery);
foreach (SPListItem oListItem in collListItems)
{
if (oListItem.ModerationInformation.Status ==
SPModerationStatusType.Pending)
{
Console.WriteLine(oWebsite.Url + "/" +
oListItem.File.Url);
oListItem.ModerationInformation.Comment =
"Automatic Approval of items";
oListItem.ModerationInformation.Status =
SPModerationStatusType.Approved;
oListItem.Update();
}
}
}
}
}
oWebsite.Dispose();
}
}
You can use the SPModerationStatusType enum SPModerationStatusType Enum - MSDN to get the text values that you want.
More info: http://spuser.blogspot.com.br/2011/03/how-to-programmatically-get-content.html
Here is the full code that gets and sets (optional) approval status (Possible values for this.oListItem.get_item('_ModerationStatus'): 0 - "Approved", 1 - "Denied", 2- "Pending"):
<script type="text/javascript" src="/jquery-1.10.2.min.js"></script>
<script src="/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });
function loadConstants() {
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
//get current (selected) list item id
var docurl = document.URL;
var beginindex = docurl.indexOf('?ID=') + 4;
var endindex = docurl.indexOf('&Source=');
var itemid = docurl.substring(beginindex, endindex);
var ctx = new SP.ClientContext("your site url");
var oList = ctx.get_web().get_lists().getByTitle('your list name');
this.oListItem = oList.getItemById(itemid);
var appStatus = "";
ctx.load(this.oListItem);
ctx.executeQueryAsync(Function.createDelegate(this, function () {
//get approval status
appStatus = this.oListItem.get_item('_ModerationStatus');
//set approval status to Approved (0)
this.oListItem.set_item('_ModerationStatus', 0);
this.oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}), function (sender, args) { alert('Error occured' + args.get_message());});
}
function onError(error) {
alert("error");
}
}
</script>

Selected Item getting lost on post back (Sharepoint wss3.0 webpart)

I am new Sharepoint developer and trying to create search webpart in window Sharepoint service 3.0 [Free edition], so far I can select multiple item from list box but when i trying to display selected item into textbox it getting lost.
Below is my code:
using System;
using System.Runtime.InteropServices;
using System.Data;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Xml.Serialization;
using System.Collections;
namespace Filter_WebPart
{
[Guid("6641a7a3-d2c4-4fda-9ef5-89596845bd6e")]
public class Filter_WebPart : System.Web.UI.WebControls.WebParts.WebPart
{
protected DataSet _dataset;
protected ListBox lstRegion;
protected ListBox lstMaterial;
protected HtmlButton btnSubmit;
protected HtmlInputText txtDisplay;
private string myExceptions = "";
//private int[] Index1;
protected override void CreateChildControls()
{
try
{
//Region Table / DataSet
lstRegion = new ListBox();
lstRegion.ID="lstRegion";
lstRegion.SelectionMode = ListSelectionMode.Multiple;
//lstRegion.EnableViewState = true;
//lstRegion.SelectedIndex = 0;
//Material Table / DataSet
lstMaterial = new ListBox();
lstMaterial.SelectionMode = ListSelectionMode.Multiple;
lstMaterial.EnableViewState = true;
btnSubmit = new HtmlButton();
btnSubmit.InnerText = "Filter";
btnSubmit.ServerClick += new EventHandler(btnSubmit_Click);
txtDisplay = new HtmlInputText();
//CommandButton
this.Controls.Add(lstRegion);
this.Controls.Add(lstMaterial);
this.Controls.Add(btnSubmit);
this.Controls.Add(txtDisplay);
}
catch(Exception ChildControlException)
{
myExceptions += "ChildControlException:" + ChildControlException.Message;
}
finally
{
//base.CreateChildControls();
}
}
protected override void OnPreRender(EventArgs e)
{
if(!this.Page.IsPostBack)
{
lstMaterial.DataSource = GetMaterialList();
lstMaterial.DataTextField = "Material Name";
lstMaterial.DataValueField = "Material Name";
lstMaterial.DataBind();
lstRegion.DataSource = GetRegionList();
lstRegion.DataTextField = "Region Name";
lstRegion.DataValueField = "Region Name";
lstRegion.DataBind();
txtDisplay.Value="1 time";
}
base.OnPreRender(e);
}
void btnSubmit_Click(object sender, EventArgs e)
{
string tmpStr="";
int k=0;
//int i=0;
lstMaterial.DataBind();
lstRegion.DataBind();
//int[] indx = lstRegion.GetSelectedIndices();
//for(i=0;i<indx.Length;i++)
//{
// tmpStr = tmpStr+","+lstRegion.Items[indx[i]].Text;
//}
//if(lstRegion.SelectedIndex >=0 )
//{
//for(i=0;i < lstRegion.Items.Count;i++)
//{
// //if(i==5 || i==10)
// //{
// // lstRegion.Items[i].Selected = true;
// //}
// if(lstRegion.Items[i].Selected)
// {
// tmpStr = lstRegion.Items[i].Text;
// }
// k=k+1;
//}
//}
foreach(ListItem RgItem in lstRegion.Items)
{
if(RgItem.Selected == true)
{
tmpStr = tmpStr +","+RgItem.Text;
k=k+1;
}
}
//for(i=0;i<lstRegion.Items.Count;i++)
//{
// if(lstRegion.Items[i].Selected == true)
// {
// txtDisplay.Value = txtDisplay.Value +","+lstRegion.Items[i].Text;
// k=k+1;
// }
//}
if(tmpStr != "" )
{txtDisplay.Value = tmpStr;}
else{
txtDisplay.Value = k.ToString();
btnSubmit.InnerText = "Done";}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
private DataSet GetRegionList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Region Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Service Area"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Region Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
private DataSet GetMaterialList()
{
_dataset = new DataSet();
DataTable _tbl = new DataTable();
DataColumn _tblcol = new DataColumn("Material Name");
_tbl.Columns.Add(_tblcol);
SPWeb web = SPContext.Current.Site.RootWeb;
SPList myList = web.Lists["Material Master"];
SPQuery query = new SPQuery();
query.Query = "";
SPListItemCollection items = myList.GetItems(query);
foreach (SPListItem item in items)
{
DataRow _row = _tbl.NewRow();
_row[0] = SPEncode.HtmlEncode(item["Material Name"].ToString());
_tbl.Rows.Add(_row);
}
_dataset.Tables.Add(_tbl);
return _dataset;
}
protected override void RenderContents(HtmlTextWriter output)
{
try
{
this.EnsureChildControls();
lstRegion.RenderControl(output);
lstMaterial.RenderControl(output);
btnSubmit.RenderControl(output);
output.Write("<br>");
txtDisplay.RenderControl(output);
//base.RenderContents(output);
}
catch (Exception RenderContentsException)
{
myExceptions += "RenderException:" + RenderContentsException.Message;
}
finally
{
if (myExceptions.Length > 0)
{
output.WriteLine(myExceptions);
}
}
}
}
}
This should be working. I've tried your code on my 2010 farm and it works fine (should also work for WSS3).
Did you forget to do an iisreset after updating the assembly ?
Your best chance to finding a solution is to use the debugger. You can attach the debugger to the right w3wp.exe process. If you don't know which one, select them all. Then set a breakpoint on your event handler and check where you lose your selection.
You don't need to override OnInit, you can put EnsureChildControls() in btnSubmit_Click.

Resources