Saturday, July 7, 2012

The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. in webpart

ow to correct: The security validation for this page is invalid (FormDigest) April 23, 2011 Leave a comment How to correct the security error on a custom SharePoint web page: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. Short Answer: Use SPUtility.ValidateFormDigest() and do not use AllowUnsafeUpdates. A Less Desirable Solution (but more commonly used) One way to get around this issue is to set the web’s (SPWeb) AllowUnsafeUpdates property to true. This is not ideal, especially when there is a more secure option. A Better Solution I needed to implement this recently and could not remember exactly what corrective code was needed, so I’m posting it here for easy recall. A co-worker (Jim Blanchard) originally tracked this solution down a good while back. This solution configures the web page to properly cache and revalidate the necessary credentials preventing the “security validation” error noted above. And, there is no need to set the AllowUnsafeUpdate spweb property to true. Coding Steps: Register the SharePoint web controls assembly in your aspx. Place this at the top of the .aspx file: <%@ Register TagPrefix=“SharePoint” Namespace=“Microsoft.SharePoint.WebControls” Assembly=“Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c“ %> Place the FormDigest control on the .aspx page (I place it near the end of the page): Note: To resolve the SPUtility class you will need to add a namespace reference to your .cs file like so: using Microsoft.SharePoint.Utilities In your page code-behind, call the ValidateFormDigest() method during the page OnInit() event to revalidate the page security. It is important the ValidateFormDigest method is called as early as possible in the page cycle. protected override void OnInit(EventArgs e) { if (Page.IsPostBack) SPUtility.ValidateFormDigest(); base.OnInit(e); } That’s it. Your custom SharePoint page should now successfully pass the security validation. It is also important to remember that you will need to also add the FormDigest control and call the ValidateFormDigest method in any custom user controls that are performing updates to SharePoint data.

Friday, March 4, 2011

Deleting Document Versions in Sharepoint


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Collections;

namespace DelDocVer_Console
{
    public class DelDocVersions
    {
        static string UserID = ConfigurationSettings.AppSettings["UserID"].ToString();
        static string Password = ConfigurationSettings.AppSettings["Password"].ToString();
        static string Domain = ConfigurationSettings.AppSettings["Domain"].ToString();
        static string Site = ConfigurationSettings.AppSettings["Site"].ToString();
        static spVersions.Versions VersionsService = new spVersions.Versions();



        static void Main(string[] args)
        {
            if (args[0] != null)
            {
                ListService.Lists objService = new ListService.Lists();
                objService.Timeout = 1500000;


                WebCollService.Webs webObjService = new WebCollService.Webs();
                webObjService.Timeout = 1500000;
                webObjService.Url = Site + "/_vti_bin/webs.asmx";
                webObjService.Credentials = new System.Net.NetworkCredential(UserID, Password, Domain);

                XmlNode webCollNode = webObjService.GetAllSubWebCollection();

                XName Root = "Webs";
                XmlReader reader = XmlReader.Create(new StringReader(webCollNode.OuterXml));



                var _webNodes = from c in XElement.Load(reader).Elements()
                                select new
                                {
                                    SiteUrl = c.Attributes("Url").ToList()[0].Value
                                };

                foreach (var _webUrl in _webNodes)
                {


                    objService.Url = _webUrl.SiteUrl + "/_vti_bin/lists.asmx";
                    objService.Credentials = new System.Net.NetworkCredential(UserID, Password, Domain);
                    XmlNode listCollnode = objService.GetListCollection();


                    XmlReader Listreader = XmlReader.Create(new StringReader(listCollnode.OuterXml));
                    var _ListNodes = from c in XElement.Load(Listreader).Elements()
                                     where c.Attributes("ServerTemplate").ToList()[0].Value == "101"
                                     select new
                                     {
                                         ListName = c.Attributes("Title").ToList()[0].Value
                                     };

                    foreach (var list in _ListNodes)
                    {
                        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                        XmlElement query = xmlDoc.CreateElement("Query");
                        XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
                        XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
                        viewFields.InnerXml = "";
                        queryOptions.InnerXml = "";
                        queryOptions.InnerXml = "";

                        XmlNode nodeListItems =
                            objService.GetListItems(list.ListName, null, query, viewFields, "100000", queryOptions, null);


                        XmlReader Nodereader = XmlReader.Create(new StringReader(nodeListItems.OuterXml));
                        XName ItemVersions = "ows_EncodedAbsUrl";
                        var _encodedNode = from e in XElement.Load(Nodereader).Elements().Elements()

                                           select new
                                           {
                                               EnodedURL = e.Attributes("ows_EncodedAbsUrl").ToList()[0].Value
                                           };
                        //add version service and write the code.
                        VersionsService.Credentials = new System.Net.NetworkCredential(UserID, Password, Domain);
                        VersionsService.Url = _webUrl.SiteUrl + "/_vti_bin/Versions.asmx";
                        foreach (var version in _encodedNode)
                        {
                            XmlNode versions = VersionsService.GetVersions(version.EnodedURL);
                            DeleteVerions(versions, args[0], version.EnodedURL);
                        }

                    }
                }

            }
        }

        static void DeleteVerions(XmlNode versions, string args, string encodedURL)
        {
            try
            {

              
                XName xname = "version";
                XmlReader Nodereader = XmlReader.Create(new StringReader(versions.OuterXml));            
                XmlElement versionsElement = (XmlElement)versions;            

                var versionCount = (from v in XElement.Load(Nodereader).Descendants()
                                    where v.Attribute(xname) != null
                                    select v).ToArray().OrderByDescending(a => !a.Attribute(xname).Value.Contains("@"));


                int count = versionCount.Count();
                foreach (var v in versionCount)
                {
                    if (count > 5)
                    {
                       XmlNode Result = VersionsService.DeleteVersion(encodedURL, v.Attribute(xname).Value);
                        count--;
                    }
                    else
                    {
                        break;
                    }

                }




            }
            catch(Exception ex)
            {
            }
        }
    }
}

Tuesday, November 9, 2010

Uploading the Attachments using the WebService to Sharepoint List

                             XmlNode return_node = listService.UpdateListItems(ListName, batchElement);
                             var id= return_node.SelectSingleNode("//@ows_ID").Value;
                             string srcUrl = "E:\\ASLog.txt";
                            FileStream fStream = File.OpenRead(srcUrl);
                            string fileName = fStream.Name.Substring(3);
                            byte[] contents = new byte[fStream.Length];
                            fStream.Read(contents, 0, (int)fStream.Length);
                            fStream.Close();
                            listService.AddAttachment(ListName, id, fileName, contents);

Monday, September 27, 2010

SharePoint Jokes.

Light travels faster than sound. This is why some SharePoint consultants appear bright until you hear them speak.


A good SharePoint consultant is someone who can tell you to go to hell in such a way that you look forward to the trip.


SharePoint work is something you do that nobody notices until you don't do it.


I should've known it wasn't going to work out between my ex-girlfriend and me. After all, I'm a SharePoint and she's a Documentum.


Kerberos with SharePoint is sort of like a bird, it's pretty cute until it shits on your head.


The secret to success as a SharePoint consultant is knowing who to blame for your failures.


SharePoint Consultant to client - 'We don't have a SharePoint performance problem; You have a perception problem.'


SharePoint analyst to programmer: "You start coding. I'll go find out what they want."


The first half of my life was ruined by my parents, and the second half by SharePoint.


TIP: If you are a SharePoint admin and you think nobody cares if you're alive, try missing a couple of SharePoint service packs.


I want to die peacefully in my sleep, like my grandfather.. Not screaming and yelling like SharePoint end users.


I like SharePoint, It fascinates me. I sit and look at it for hours.


What did one sharepoint site say to another sharepoint site?  
    Hey, aren't we called webs?


What did the end user say to the developer?
    Oh, I didn't create that column, I was smart, I just renamed the "title" column!


What did one sharepoint web developer say to the asp.net developer?
    Why me?


What did the production portal say to the author portal?
    I'm sorry, I can't seem to find your object!


What did the parent content type say to the child content type?
    I won't give you my jeans, but I'll buy you another pair just like them and we can share! 


How many people does it take to create a web part?
    two, one to write the code, another to figure out the permissions problem in production!


How many times does it take to create a Shared Service Provider?
    3, one time to screw it up without knowing it, twice to do it because sharepoint won't do right the second time and
the third after you have blown away everything and started over!


What did the server admin say to the sharepoint web developer?
    Why can't we just do this with static html?


what did the sharepoint 2003 environment tell the sharepoint 2007 environment?
    Don't worry, reboot will still fix everything.


What did the sharepoint admin do to fix an "Unexpected Error has occured"
    Delete sharepoint and start again!


What did one w3wp process say to the other?
    Hey, can I borrow one of your SPSite's?  You have plenty!        


One day a user called the helpdesk, no one answered.  Being that he was in the helpdesk office he walked down and asked the admin why they weren't answering. 
She simply stated, they quit when they heard we were implementing sharepoint!


A consultant was asked to build an estimate for a SharePoint two layer approval workflow with SharePoint Designer.  
The consultant never replied.  When asked "why", he simply stated, "Impossible".


Updating the data from XML to Sharepoint List

With the use of Sharepoint List Webservice i am going to populate the xml data into the list. for this you need to create a list and also the columns. with nodes in the XML.

In this i m a  going to hard the Webservice Url, but you can add the app.config and can adda new key and value . which it reference in the code using Cofiguration Settings.by inheriting the System.Configuration.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Net;
using System.IO;

namespace XMLtoSPList
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                ReferenceToWebService.Lists ListsService = new ReferenceToWebService.Lists();
                ListsService.Credentials = new NetworkCredential("XXXX", "YYYYYY", "ZZZZZZ");
                //ListsService.Credentials = System.Net.CredentialCache.DefaultCredentials;

                string _listservURL = string.Empty;
                Console.WriteLine("Enter the SiteCollection Url :", _listservURL);
                _listservURL = Console.ReadLine();
                ListsService.Url = "http://servername/_vti_bin/lists.asmx";

                //ListsService.Url = "http://myserver:6580/Docs/_vti_bin/lists.asmx";
                XmlTextReader textReader = new XmlTextReader("C:\\myxml.XML");
                textReader.Read();



                XmlDocument doc = new XmlDocument();


                XmlElement batch = doc.CreateElement("Batch");

                batch.SetAttribute("OnError", "Continue");
                batch.SetAttribute("ListVersion", "1");


                XmlDocument doc1 = new XmlDocument();
                doc1.Load("C:\\Duplicate Vendor Additions.XML");
                int i = 1;
                try
                {
                    ListsService.GetList("RECORDS");
                    System.Xml.XmlNode ndListView = ListsService.GetListAndView("RECORDS", "");
                    XmlNode node1 = ndListView.ChildNodes[1];
                    XmlNode node2 = node1.ChildNodes[1];
                    XmlNodeList node3 = node2.ChildNodes;
                    int count = 0;
                  
                  
                    string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
                    foreach (XmlNode nd in doc1.DocumentElement.SelectNodes("RECORD"))
                    {
                        try
                        {
                            string Duplicates = nd.ChildNodes[0].InnerText;
                            batch.InnerXml = "" +
                                "" + i.ToString() + "" +
                                "" + nd.ChildNodes[0].InnerText.Trim() + "" +
                                   "" + nd.ChildNodes[1].InnerText.Trim() + "" +
                                     "" + nd.ChildNodes[2].InnerText.Trim() + "" +
                                       "" + nd.ChildNodes[3].InnerText.Trim() + "" +
                                         "" + nd.ChildNodes[4].InnerText.Trim() + "" +
                                 "" + nd.ChildNodes[5].InnerText.Trim() + "" +
                                 "" + nd.ChildNodes[6].InnerText.Trim() + "" +
                                 "";
                        }
                        catch (Exception ex)
                        {
                            Trace(DateTime.Now.ToString() + " A record with " );
                            Trace(nd.InnerXml);
                            Trace("is not inserted.");
                        }
                        //ListsService.UpdateListItems(strListID, batch);


                        Console.WriteLine(nd.ChildNodes[0].InnerText);
                        i++;
                    }
                }
                catch(Exception ex)
                {
                   Trace(DateTime.Now.ToString()+"---No List Found.");
                }
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            Console.WriteLine("Done");
            string exit = string.Empty;

            Console.WriteLine("Press X to exit"+exit);
            if (exit == "x")
            {
                exit = "exit";
                exit = Console.ReadLine();
            }
            Console.Read();


        }
    }
}

Hiding Sharepoint Controls in the List

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

public partial class hellol : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void CreateChildControls()
{
foreach (Control ctrl in this.Page.Controls)
{
CheckControl(ctrl);
}
base.CreateChildControls();
}

private void CheckControl(Control ParentControl)
{
try
{
foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = false;
break;
}
CheckControl(childControl);
}
foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.SettingsMenu".ToUpper())
{
SettingsMenu Menu = (SettingsMenu)childControl;
Menu.Visible = false;
}
if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.NewMenu".ToUpper())
{
NewMenu Menu = (NewMenu)childControl;
Menu.Visible = false;
}
CheckControl(childControl);
}

}

catch { }

}

}