the error i get is
The security validation for this page is invalid. Click Back in your Web browser, refresh the page and try the operation again.
i am using moss 2007
protected void btnSubmit_Click(Object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite mySite = new SPSite(_sLibUrl))
{
TextBox txtFirstName = (TextBox)usercontrol.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)usercontrol.FindControl("txtLastName");
TextBox txtPhone = (TextBox)usercontrol.FindControl("txtPhone");
TextBox txtEmail = (TextBox)usercontrol.FindControl("txtEmail");
TextBox txtSubject = (TextBox)usercontrol.FindControl("txtSubject");
TextBox txtContant = (TextBox)usercontrol.FindControl("txtContant");
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.AllWebs[WebName].Lists[_sLibName].Items;
SPListItem item = listItems.Add();
item["FirstName"] = txtFirstName.Text;
item["LastName"] = txtLastName.Text;
item["Phone"] = txtPhone.Text;
item["Email"] = txtEmail.Text;
item["Subject"] = txtSubject.Text;
item["Contant"] = txtContant.Text;
item.Update();
mySite.AllowUnsafeUpdates = false;
mySite.AllWebs[WebName].Lists[_sLibName].Update();
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmail.Text = string.Empty;
txtSubject.Text = string.Empty;
txtContant.Text = string.Empty;
}
Label lblMessage = (Label)usercontrol.FindControl("lblMessage");
// lblMessage.Text = "טופס נשלח בהצלחה";
});
}
catch (Exception ex)
{
Label lbl = (Label)usercontrol.FindControl("lblMessage");
lbl.Text = ex.Message;
}
}
Try putting mySite.AllowUnsafeUpdates = false; after mySite.AllWebs[WebName].Lists[_sLibName].Update();
i found the solution what i need to do is to remove the
mySite.AllowUnsafeUpdates = true;
and
mySite.AllowUnsafeUpdates = false;
and it works
I work with this solution always
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//add, update and etc. programatically crud operations with lists
web.AllowUnsafeUpdates = false;
}
Related
I am new to SharePoint programming.
Can anyone tell me how I can export list data to Excel using a timer job with some custom code?
Please go through the below link for creating timer jobs in sharepoint.
This article is contain the detailed process.
https://www.mssqltips.com/sqlservertip/3801/custom-sharepoint-timer-job/
The below code will help you to export the list data.
public void Export(List<int> ids)
{
DataTable table = new DataTable();
try
{
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteE = new SPSite(site.ID))
{
using (SPWeb webE = siteE.OpenWeb(web.ID))
{
webE.AllowUnsafeUpdates = true;
SPList list = webE.Lists["Stationery"];
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Quantity", typeof(Decimal));
DataRow newRow;
GridView gv = new GridView();
foreach (SPListItem item in list.Items)
{
if (ids.Contains(Convert.ToInt32(item["ID"].ToString())) && (item["Status"].ToString() == "New"))
{
newRow = table.Rows.Add();
newRow["Product"] = item["Product"].ToString();
newRow["Quantity"] = Convert.ToDecimal(item["Quantity"].ToString());
item["Status"] = "Exported";
item.Update();
}
}
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = "Product";
boundField.DataField = "Product";
gv.Columns.Add(boundField);
boundField = new SPBoundField();
boundField.HeaderText = "Quantity";
boundField.DataField = "Quantity";
boundField.ControlStyle.Width = new Unit(120);
gv.Columns.Add(boundField);
gv.AutoGenerateColumns = false;
gv.DataSource = table.DefaultView;
gv.DataBind();
gv.AllowSorting = false;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
string attachment = "attachment; filename=export" + "_" + DateTime.Now.ToShortTimeString() + ".xls";
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/Excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
webE.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HttpContext.Current.Response.Write(ex.ToString());
}
I m uploading file to Sharepoint online dcoument librar from byte array and on execution getting error "File Not found"
public static bool UploadFile(SP sp, string folderName, string fileNameWithExtension, byte[] fileContent, TraceWriter log)
{
bool result = false;
try
{
SecureString securePwd = new SecureString();
char[] pwdarray = sp.pwd.ToCharArray();
foreach (var item in pwdarray)
{
securePwd.AppendChar(item);
}
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(sp.id, securePwd);
using (ClientContext clientContext = new ClientContext(sp.url))
{
log.Info("UploadToSharePoint 1");
clientContext.Credentials = creds;
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = clientContext.Web;
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = fileContent;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = fileNameWithExtension;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle("All Attachments");
docs.RootFolder.Folders.Add(folderName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
clientContext.ExecuteQuery();
return result = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
Please help spent 2 days but not finding a solution :(
Below sample code works for me.
using (var context = new ClientContext("https://domain.sharepoint.com/sites/Developer"))
{
Console.ForegroundColor = ConsoleColor.Green;
string password = "pw";
SecureString sec_pass = new SecureString();
Array.ForEach(password.ToArray(), sec_pass.AppendChar);
sec_pass.MakeReadOnly();
context.Credentials = new SharePointOnlineCredentials("lee#domain.onmicrosoft.com", sec_pass);
string fileName = "C:\\Lee\\test.docx";
FileStream stream = System.IO.File.OpenRead(fileName);
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = fileBytes;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = "test.docx";
Microsoft.SharePoint.Client.List docs = context.Web.Lists.GetByTitle("MyDoc3");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
context.ExecuteQuery();
Console.WriteLine("done");
Console.ReadKey();
}
I am uploading a document to Document library. Along with this I am creating a field called 'FieldID' by combining 2 values. However I am unable to see this field in the document library and hence unable to query the document with this field.How can I see this field or how can I retrieve documents using this 'FieldID'. This is the code.
if (UploadFile.PostedFile != null || (UploadFile.PostedFile.ToString() != string.Empty))
{
String fileName = UploadFile.PostedFile.FileName.ToString();
string userLogin = SPContext.Current.Web.CurrentUser.LoginName;
Guid siteID = SPContext.Current.Site.ID;
SPDocumentLibrary exposureLibrary = null;
SPList listDoc = null;
SPFolder myLibrary = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(siteID))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
// exposureLibrary
try
{
// Check if the document library already exists
exposureLibrary = (oWeb.Lists[SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME] as SPDocumentLibrary);
exposureLibrary.ContentTypesEnabled = false;
exposureLibrary.EnableAttachments = false;
exposureLibrary.EnableFolderCreation = false;
exposureLibrary.EnableVersioning = true;
exposureLibrary.NoCrawl = true;
exposureLibrary.OnQuickLaunch = false;
/* create a Text field for ID */
SPFieldText field = (exposureLibrary.Fields["FILEID"] as SPFieldText);
// Check if the field is available
if (field == null)
{
SPFieldText fldID = (SPFieldText)exposureLibrary.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
exposureLibrary.Fields.Add(fldID);
}
//exposureLibrary.Update();
myLibrary = exposureLibrary.RootFolder;
}
catch
{
// Determine the GUID of the document library
Guid ExposureDocumentLibraryId = oWeb.Lists.Add(SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_NAME, SharepointCommon.Constants.USERINTERFACECUSTOMIZATIONSFEATURERECEIVER_EXPOSURE_DOCUMENTLIBRARY_DESCRIPTION, SPListTemplateType.DocumentLibrary);
listDoc = oWeb.Lists[ExposureDocumentLibraryId];
/* create a Text field for ID */
SPFieldText fldID = (SPFieldText)listDoc.Fields.CreateNewField(
SPFieldType.Text.ToString(), "FILEID");
fldID.Required = true;
fldID.MaxLength = 100;
fldID.Hidden = false;
listDoc.Fields.Add(fldID);
// Set properties of the document library
listDoc.ContentTypesEnabled = false;
listDoc.EnableAttachments = false;
listDoc.EnableFolderCreation = false;
listDoc.EnableVersioning = true;
listDoc.NoCrawl = true;
listDoc.OnQuickLaunch = false;
listDoc.Update();
myLibrary = listDoc.RootFolder;
}
// Prepare to upload
Boolean replaceExistingFiles = true;
// Upload document
SPFile spfile = myLibrary.Files.Add(UploadFile.FileName + "(" + ViewState[UIConstants.CUSTOMERID].ToString() + " - "+ViewState[UIConstants.MondiPlantID].ToString()+ ")", UploadFile.FileContent, replaceExistingFiles);
//spfile.Item["FILEID"]= ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
//myLibrary.Item["ID"] = ViewState[UIConstants.CUSTOMERID].ToString() + " _ " + ViewState[UIConstants.MondiPlantID].ToString();
spfile.Item.Update();
oWeb.AllowUnsafeUpdates = false;`enter code here`
// Commit
myLibrary.Update();
// Update the document library
oWeb.Update();
}
}
});
}
exposureLibrary.Fields.Add(fldID); //after this step
//exposureLibrary.Update();
you need to uncomment this, because after a field is created in try block, list/library is not being updated
My requirement is to select a value from a drop down and fetch the corresponding three fields and drop down must have the selected value in it.
However my code it fetches the corresponding three fields and sets the drop down selected value to first value.
Please tel me how to solve this issue.
Below are my code at page load and corresponding methods:
public partial class RegisterWebPartUserControl : UserControl
{
string titleid;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
titleid = ddlDrop.SelectedValue;
ddlDrop.DataBind();
}
protected void ddlDrop_SelectedIndexChanged(object sender, EventArgs e)
{
FetchReadOnlyFields(titleid);
}
public void FetchReadOnlyFields(string titleID)
{
string oStartDate = null;
string oEndDate = null;
string oPrerequisite = null;
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
SPListItemCollection oItemCollection = oSPList.Items;
SPListItem ospListItem = oItemCollection.Add();
SPList oSPList1 = oSPWeb.Lists["Scheduled Courses"];
SPListItemCollection oItemCollectionCourse = oSPList1.Items;
SPFieldCalculated titleIDCourse = (SPFieldCalculated)oItemCollectionCourse.Fields["TitleID"];
SPField fieldStartDate = oItemCollectionCourse.Fields["Start Date"];
SPField fieldEndDate = oItemCollectionCourse.Fields["End Date"];
foreach (SPListItem ospListItemCourse in oItemCollectionCourse)
{
string value = titleIDCourse.GetFieldValueAsText(ospListItemCourse["TitleID"]);
if (titleID == value)
{
oPrerequisite = ospListItemCourse["Prerequisite"].ToString();
TxtPrerequisite1.Text = SPHttpUtility.ConvertSimpleHtmlToText(oPrerequisite, oPrerequisite.Length);
oStartDate = ospListItemCourse["Start Date"].ToString();
TxtStartDate.Text = oStartDate;
oEndDate = ospListItemCourse["End Date"].ToString();
TxtEndDate.Text = oEndDate;
break;
}
}
}
}
Hope to seek your help.
Thank you
This code
ddlDrop.DataBind();
Should be called only once. On the first load of the page.
Try
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){ // this is what has changed
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
ddlDrop.DataBind();
}
titleid = ddlDrop.SelectedValue;
}
I want to be able to create a KPI List on my MOSS 2007 installation via the object model. Is this possible?
using (SPWeb web1 = properties.Feature.Parent as SPWeb)
{
using (SPSite objSite = new SPSite(web1.Site.ID))
{
using (SPWeb web = objSite.OpenWeb(web1.ID))
{
SPListTemplate template = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
template = t;
break;
}
}
Guid gG = Guid.Empty;
SPList list = null;
string sListTitle = "Status List";
SPSecurity.RunWithElevatedPrivileges(delegate
{
try
{
web.AllowUnsafeUpdates = true;
gG = web.Lists.Add(sListTitle, sListTitle, template);
list = web.Lists[gG];
}
catch
{
// exists
list = web.Lists[sListTitle];
}
SPContentType ct =
list.ContentTypes["SharePoint List based Status Indicator"];
//declare each item which u want to insert in the kpi list
SPListItem item1 = list.Items.Add();
SPFieldUrlValue value1 = new SPFieldUrlValue();
item1["ContentTypeId"] = ct.Id;
item1.SystemUpdate();
item1["Title"] = "Project Specific Doc.Lib.Rating";
value1.Url = web.Url + "/Lists/Project Specific Documents";
item1["DataSource"] = value1;
item1["Indicator Goal Threshold"] = "3";
item1["Indicator Warning Threshold"] = "3";
item1["Value Expression"] =
"Average;Average_x0020_Rating:Number";
item1.SystemUpdate();
}
}
}
average is the calculation value and the column is Average_x0020_Rating.
http://alonsorobles.com/2010/03/17/important-custom-sharepoint-list-template-notes/
I found that the Template ID for a Status Indicator (KPI List) is 432. Google for this to find some info on creating a new list. I'm needing to read up what properties I can set on this list.
this is work for me:
private void CreateKPIDocumentLibrary(List<PageStructure> list)
{
SPListTemplate kpi = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
kpi = t;
break;
}
}
foreach (PageStructure st in list)
{
bool find = false;
string[] periodType = st.tag.Split('_');
string name = periodType[0] + "-" + st.effdate + "-" + st.template;
SPListCollection lstCol = site.OpenWeb().GetListsOfType(SPBaseType.GenericList);
foreach (SPList l in lstCol)
{
string title = l.Title;
if (title == name)
{
find = true;
break;
}
}
if (find == false)
{
Guid docLibID = web.Lists.Add(name, "", kpi);
}
SPList itemList = web.Lists[name];
SPListItem item = itemList.Items.Add();
SPFieldUrlValue value = new SPFieldUrlValue();
item["Title"] = st.tag;
value.Url = st.docUrl;
item["DetailLink"] = st.url;
item["DataSource"] = value;
item["Indicator Goal Threshold"] = "2";
item["Indicator Warning Threshold"] = "1";
item["View Name"] = "All Documents";
item.SystemUpdate();
web.Update();
KpiObject kp = new KpiObject(name, SPContext.Current.Site.Url + itemList.DefaultViewUrl);
this.kpiList.Add(kp);
}
}