Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

SpPreviledges Sample Code

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;

namespace TestCode.TestCode
{
[ToolboxItemAttribute(false)]
public class TestCode : WebPart
{
string strError = string.Empty;
TextBox txtUserName, txtPassWord;
Button btnsave;
protected override void Render(HtmlTextWriter writer)
{
writer.Write(strError);
try
{
txtUserName.RenderControl(writer);
writer.Write("
");
txtPassWord.RenderControl(writer);
writer.Write("
");
btnsave.RenderControl(writer);
}
catch (Exception ex)
{
strError += ex.ToString();
}
}
protected override void CreateChildControls()
{
try
{
txtUserName = new TextBox();
this.Controls.Add(txtUserName);

txtPassWord = new TextBox();
this.Controls.Add(txtPassWord);

btnsave = new Button();
btnsave.Text = "Save Record...!";
btnsave.Click += new EventHandler(btnsave_Click);
this.Controls.Add(btnsave);
}
catch (Exception ex)
{
strError += ex.ToString();
}
}

void btnsave_Click(object sender, EventArgs e)
{
try
{
SPWeb currentWeb = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(currentWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPListItemCollection mycoll = web.Lists["Login"].Items;
SPListItem item = mycoll.Add();
item["Title"] = txtUserName.Text;
item["Password"] = txtPassWord.Text;
item.Update();
txtUserName.Text = "";
txtPassWord.Text = "";
strError += "Record Saved Succesfully";
}

}
});
}
catch (Exception ex)
{
strError += ex.ToString();
}
}
}
}

No comments:

Post a Comment