Once my colleague was getting an error “The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again” while trying to move documents from one document library to another document library.

His piece of code was,

public void MoveDocument(string filePath,string destinationList)
{
try
{
SPWeb ospWeb = SPContext.Current.Web;
SPList destList = ospWeb.Lists[destinationList];
SPFile ospFile = ospWeb.GetFile(filePath);
ospFile.MoveTo(ospWeb.Url + "/" + destList.RootFolder + "/" + ospFile.Name);
}
catch (Exception ex)
{
throw ex;
}
}

After some amount of searching in the net, it was found that the error is caused due the security validation in sharepoint. So, there should be a method we turn  off the security validation:

One method to turn off security validation is,
Central Administration—>application management—->web application general settings–>”turn security validation off”

but,it is dangerous to do….as it could potentially leave your site open to malicious code.

Ideally, the security validation should be turned off only long enough for your own code to execute and should be turned back on again as soon as the code finishes execution.

So, the code needs to be recoded as,
public void MoveDocument(string filePath,string destinationList)
{
try
{
SPWeb ospWeb = SPContext.Current.Web;
Microsoft.SharePoint.Administration.SPWebApplication webApp = ospWeb.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
SPList destList = ospWeb.Lists[destinationList];
SPFile ospFile = ospWeb.GetFile(filePath);
ospFile.MoveTo(ospWeb.Url + “/” + destList.RootFolder + “/” + ospFile.Name);
webApp.FormDigestSettings.Enabled = true;
}
catch (Exception ex)
{
throw ex;
}
}

We often see sites which has a text box with some default value, mostly in grey and when we click inside the textbox, the default value disappears and we can type in, similarly if we click elsewhere in the page the default value again re-appears.

This can be achieved very simply using javascript where we display the default data on onblur event and it disappears on onfocus event, see the illustration below:

Suppose I have a html textbox as follows,

<input id=”txtBizFocus” runat=”server” name=”txtBizFocus” autocomplete=”off” type=”text”  enableviewstate=”true”/>

 Now, I have to check whether txtBizFocus is empty or not, if it is empty include the default value in grey color. Now, if the user clicks inside the textbox txtBizFocus, the default value should disappear and the user should be able to type inside in font-color black.

 if (txtBizFocus.Value == “”)

txtBizFocus.Value = “<type here or select>”;

if (txtBizFocus.Value == “<type here or select>”)

{

    txtBizFocus.Style.Add(“color”, “#808080″);

 

}

else

{

    txtBizFocus.Style.Add(“color”, “black”);

}

 txtBizFocus.Attributes.Add(“onfocus”,   var txtBizFocus = document.getElementById(‘” + txtBizFocus.ClientID + “‘); if(txtBizFocus.value==’<type here or select>’){txtBizFocus.value=”; txtBizFocus.style.color=’black’;};”);

 

txtBizFocus.Attributes.Add(“onblur”,   var txtBizFocus = document.getElementById(‘” + txtBizFocus.ClientID + “‘); if(txtBizFocus.value==”){txtBizFocus.value=’<type here or select>’; txtBizFocus.style.color=’#808080′;};”);

 

 So, when the page loads, txtBizFocus comes with a default value “<Type here or select>” in grey color, the moment user clicks inside the textbox(onfocus) the writing disappears and becomes blank so that the user can type in black(this is checked in the above code, where we check if the value inside txtBizFocus is not the default value, change color to black).

 

We have observed in different cases, suppose we have a video file in a sharepoint library, if we click the file  it prompts for username/password. It is not very user friendly, as the password needs to be entered every time.

 

After some searches we found many people facing this problem so we suggested that we can open the video in a web page instead of opening it in Windows Media Player.

 

So, we created an aspx page in _layouts folder.

Now, whenever the user clicks to open a video file, we redirect it to the aspx page like,

 

http://gitolekha/_layouts/ad.aspx?lnk=http://gitolekha/Videos/sharepoint.wm

 

in ad.aspx we pass the name of the document library, here videos and the file name, here gito sharepoint.wm

 

here, we embed the video file in the aspx web page,

 

< OBJECT id="MediaPlayer" CLASSID="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95">

<PARAM NAME="SRC" VALUE=<%=strVal %>>

<PARAM NAME="AUTOSTART" VALUE="1><PARAM NAME="SHOWCONTROLS" VALUE="1"><param name="ShowStatusBar" value="1">

</OBJECT >

 

strVal is the name of the file which we get from the code behind,

 

if (Request.QueryString["lnk"] != null)

{

   string strVal = Request.QueryString["lnk"].ToString();

}

 Our job is done, we have embedded the video file in the webpage, so it dosen’t ask for username/password every time we try to open it as it was before when we opened it in Windows Media Player.

 

Now, how to download it?

We can always download from Sharepoint document library through some coding, but I am lazy, I want to leave it to the default download system of windows as right click -&gt; save as. How do we do that?

 

On top of the webpage I give a hyperlink as shown below, now I want to stop users from left clicking so that they are forced to right click -&gt; save target as.

 

<a href=<%=strVal %>; onMouseOver=’document.onmousedown=noLeftClick’ onMouseOut=’document.onmousedown=null’><b>Download File</b></a>;

 

 

<script language=”javascript”>

function noLeftClick()

{

   if (event.button==1)

   {

    alert(‘Please use the rightclick \”Save Target As\” Command to Download’)

    }

 }

<script>

 

Now, how do users send email of the link of the video to other users?

 

We send it as shown below to the same aspx page, however we need to encode it, here filename = gito sharepoint.wmv, so while encoding it is sent as below,

 

http://gitolekha/_layouts/ad.aspx?lnkftp=ftp://174.456.12.45/CPD%20sharepoint.wmv

 

see the code below,

void emailImage_DataBinding(object sender, EventArgs e)

{

 HyperLink mailImage = (HyperLink)sender;

mailImage.NavigateUrl = “mailto:?body=” + mailImage.Page.Server.UrlPathEncode(FinalLink + “&subject=Link to “ + fileTitle);

}

 

Here final link is the link shown above(http://gitolekha/_layouts/ad.aspx?lnkftp=ftp://174.456.12.45/gito%20sharepoint.wmv

) and final title is the title to be shown in the subject line of the mail.

 

We know that to open a pop-up we use window.open( [sURL] [, sName] [, sFeatures] [, bReplace]).

But, what if we want to open it as a modal window? We can use window.showModalDialog(sURL [, vArguments] [, sFeatures]).

But this approach has certain disadvantages, your client side script does not always behave the way it should otherwise.

So the best possible approach to open a modal pop-up window is,

From your page, open a normal popup as
window.open(‘/_layouts/OpenOpUp.aspx?Mode=New’, ‘pop1′,‘left=80, top=50, center=yes, height=480, width=450,status= no, resizable= no, scrollbars=yes, toolbar=no, location=no,menubar=no’); 

Now, in the modal popup window(here, OpenOpUp.aspx) in the body tag write,
<body onblur=”self.focus()”>
Your job is done, now it will behave as a modal popup window as it will have focus on itself and you have to close the page to get back to the parent page (either through javascript or by clicking the cross button at top) and all your client side scripts will work just fine.

Suppose we have a xml document, now we need to search for an item in it.
We can do this using SelectSingleNode method which is used to locate an element. The SelectSingle-Node method requires an XPath query to be passed into the method. See the sample xml document below,

<?xml version=”1.0″ encoding=”us-ascii” ?>
<TreeView>
<node text=”Topics”>
<node text=”Corporate”>
<node text=”Best Places to Work”>
<node text=”Health Fairs” />
</node>
<node text=”Pharma”>
<node text=”General Medicines”>
<node text=”Arthritis “>
<node text=”Osteoporosis” />
<node text=”Oral calcitonin” />
</node>
</node>
</TreeView>

So, if I want to find an item ‘Arthritis’ in the xml document, I have to do this,

string BzFocusxmlpath = @”C:\Program Files\ BizFocus.xml”;

 

string strParentVal = “”;       

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(BzFocusxmlpath);

XmlNode node;

node = xmlDoc.SelectSingleNode(“//node[@text='Arthritis']“);

string snode = node.OuterXml;

 

Now, snode will return a value <node text=\”Arthritis”><node text=\”Osteoporosis\” /><node text=\”Oral calcitonin\” /></node>
which is the value of all nodes under General medicines, so, how do we extract only “Arthritis”?
Here, some C# coding will help,

int intindex = snode.IndexOf(“>”);

string strsubstr = snode.Substring(0, intindex); //will return “<node text=\”Arthritis “”

string[] strstarray = strsubstr.Split(‘=’);

string strStoreBizVal = strstarray[1].ToString(); // will give “\”Arthritis 

string strStoreBizValParent = “”;

// For removing “\” and “/” characters from string

strStoreBizVal = strStoreBizVal.Replace(“\”", “”);

strStoreBizVal = strStoreBizVal.Trim();

if (strStoreBizVal.Contains(“/”))

{

    strStoreBizVal = strStoreBizVal.Replace(“/”, “”);

    strStoreBizVal = strStoreBizVal.Trim();

}

So, our strStoreBizVal now  contains, ‘Arthritis’.

 

Now, suppose we want the hierarchy of the item in the xml file, like,

‘Arthritis’ is under parent node ‘General Medicine’, ‘General Medicine’ is under ‘Pharma’ and that is under ‘Topics’.

So, what if we want to display the whole hierarchy as,

Topics|Pharma|General Medicines|Arthritis” ?

For this, we need to traverse the xml document to get the hierarchy of parent and child, we can do this using simple recursive C# code, refer to the above xml code where the top most node is <TreeView> so, we traverse the Parent nodes till we reach there, see below

while (node.ParentNode.OuterXml.StartsWith(“<TreeView>”) == false)

{

    strParentVal = node.ParentNode.OuterXml;

    int intindexParent = strParentVal.IndexOf(“>”);

    string strsubstrParent = strParentVal.Substring(0, intindexParent);

    string[] strstarrayParent = strsubstrParent.Split(‘=’);

    strStoreBizValParent = strstarrayParent[1].ToString();

    strStoreBizValParent = strStoreBizValParent.Replace(“\”", “”);

    strStoreBizValParent = strStoreBizValParent.Trim();

    if (strStoreBizValParent.Contains(“/”))

    {

strStoreBizValParent = strStoreBizValParent.Replace(“/”, “”);

strStoreBizValParent = strStoreBizValParent.Trim();

    }

    strStoreBizVal += “|” + strStoreBizValParent;

    node = node.ParentNode;

}

string strFinalBizVal = strStoreBizVal;

 

// Now we get “Arthritis|General Medicines|Pharma|Topics“, since we are traversing from below so the top most node appears last, so we have to reverse the string to get “Topics|Pharma|General Medicines|Arthritis

 

string strReverseBizVal = “”;

string[] strReverseBizValArr = strFinalBizVal.Split(‘|’);

for (int j = strReverseBizValArr.Length -1; j >= 0; j–)

{

    strReverseBizVal += strReverseBizValArr[j].ToString() + “|”;

}

strReverseBizVal = strReverseBizVal.Remove(strReverseBizVal.LastIndexOf(‘|’));

 

This will give me, “Topics|Pharma|General Medicines|Arthritis”

SQL Server 2005 Query Analyzer shortcuts.CTRL+E : Execute Query

F5 : Execute Query

ALT+BREAK : Cancel Query

CTRL+D : Display results in grid format

ALT+F1 : Database object info.

CTRL+F5 : Parse query and check syntax

CTRL+K : Display/hide execution plan

CTRL+L : Display execution plan

CTRL+N : New Query window

CTRL+SHIFT+F : Save results to file

CTRL+Delete : Delete through the end of the line

Some General Shortcuts

CTRL+A : Select All

CTRL+C : Copy

CTRL+V : Paste

CTRL+F : Find

CTRL+P : Print

CTRL+S : Save

CTRL+Z : Undo

CTRL+Y : Redo

CTRL+X : Delete

   To Serialize a datatable we can use the inbuilt function WriteXml. We have put in 3 parameters the filename,xmlwritemode,writehierarchy.

Giving a name to the datatable is a must or you might get an exception “Cannot serialize the DataTable. DataTable name is not set”. In this case we have used the name “dtDoctype” using  the TableName  property  of  datatable.

If you forget to mention the writemode, you might get other errors like “Root element is missing.” While trying to de-serialize it.

The parameter “Mode” is to identify if it is a new entry or an edit. The parameter “item” indicates which list the item is being fetched from.

String docxmlPath = @”C:\KMUserControl\docList.xml”;

if (!File.Exists(docxmlPath))

{

   DataTable dt = new DataTable();

               

   dt = adBuzLogic.PopulateInformationTypeDataTable(ref Mode, item);

   dt.TableName = “dtDocType”;

   dt.WriteXml(docxmlPath, XmlWriteMode.WriteSchema, true);

 

   ddlInfoType.DataSource = dt;

   ddlInfoType.DataBind();

   if (Mode.Equals(“Edit”))

   {

     if (item != null)

     {

 

     ddlInfoType.Items.FindByText(item.ParentList.Title).Selected = true;

       }

    }

 

}

else

{

 

   DataTable dt = new DataTable();

   dt.ReadXml(docxmlPath);

               

   ddlInfoType.DataSource = dt;

   ddlInfoType.DataTextField = dt.Columns[0].ToString();

   ddlInfoType.DataValueField = dt.Columns[0].ToString();

   ddlInfoType.DataBind();

   if (Mode.Equals(“Edit”))

   {

     if (item != null)

     {

 

     ddlInfoType.Items.FindByText(item.ParentList.Title).Selected = true;

       }

    }

}

 

In PopulateInformationTypeDataTable function, we simply return a datatable from items in a Sharepoint list. ———————-

public DataTable PopulateInformationTypeDataTable(ref string mode, SPListItem editItem)

{

    DataTable dt = new DataTable(); //Define a datatable.

    DataColumn column = new DataColumn(); //Define a datacolumn.Here only one column is added which is of type string.

    column.DataType = Type.GetType(“System.String”);

    column.ColumnName = “item”;

    dt.Columns.Add(column);

try

{

SPWeb ospWeb = SPContext.Current.Web;

foreach (SPList ospList in ospWeb.Lists)

{

if (((ospList.BaseTemplate == SPListTemplateType.DocumentLibrary) || (ospList.BaseTemplate == SPListTemplateType.PictureLibrary)) && (ospList.ContentTypes["New Document"] != null)) //filter condition,from where to read items to form a datatable.

 {

    DataRow dr = dt.NewRow(); //dynamically adding datarows by reading from Sharepoint lists.

    ListItem liInformationType = new ListItem(ospList.Title, ospList.RootFolder.Name);

     dr[0] = liInformationType; //assigning value to the datarow.

     dt.Rows.Add(dr[0]); //adding datarow to datatable.

    }

  }

}

 catch (Exception exception)

 {

      Throw exception;         

 

  }

  return dt;

}

It is very simple to implement tab control using hotmap.It is all with html and a bit of javascript. Refer to the images shown in Tab control without postback.
, where on clicking each tab the color of that tab had to change.

The image map was something like this,

<img id="imgHotmap" src="images/arrows_step_1.gif" width="342" height="34" border="0" usemap="#steps" />
<map name="steps" id="steps">
<area shape="poly" coords="253,1,330,1,342,17,331,34,252,34,264,17,254,3" href="#" alt="step4" onclick="changeImage(4);" />
<area shape="poly" coords="168,1,245,1,257,17,246,34,167,34,179,17,169,3" href="#" alt="step3" onclick="changeImage(3);" />
<area shape="poly" coords="0,0,77,0,88,16,77,32,0,32,1,1" href="#" alt="step1" onclick="changeImage(1);" />
<area shape="poly" coords="84,0,161,0,173,16,162,33,83,33,95,16,85,2" href="#" alt="step2" onclick="changeImage(2);" />
</map>

All, we did was to invoke a javascript for each area of the map i.e for each tab.
The job of the javascript was simple, it changed the image of “imgHotmap”.

function changeImage(opt)
{
if(opt == 1)
{
document.getElementById(‘imgHotmap’).src = ‘/_layouts/images/novartis/arrows_step_1.gif’;

}
if(opt == 2)
{
document.getElementById(‘imgHotmap’).src = ‘/_layouts/images/novartis/arrows_step_2.gif’;
}
if(opt == 3)
{
document.getElementById(‘imgHotmap’).src = ‘/_layouts/images/novartis/arrows_step_3.gif’;
}
if(opt == 4)
{
document.getElementById(‘imgHotmap’).src = ‘/_layouts/images/novartis/arrows_step_4.gif’;

}
}

We had to implement a functionality wherein we had a tab control with a peopleeditor in the first tab and we had to show the summary of all controls of the first tab in the second tab.

Initially,we were facing difficulties in fetching values in the peopleeditor, then we found out a way: Our people editor control had the id=pplContact

@ Register Tagprefix=”wssawc” Namespace=”Microsoft.SharePoint.WebControls” Assembly=”Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c” %> 

<wssawc:PeopleEditor id=”pplContacts” runat=”server” MultiSelect=”true” AllowEmpty=”false” PlaceButtonsUnderEntityEditor=”false” Width=”388px”/>
 

In the javascript for tab change, we included the following:

var users = null;
var  elem = document.forms[0].elements;
for(var i=0; i < elem.length; i++) {// look for the value we set the peopleeditor’s id to and “TextBox”
 
 
if(elem[i].id.indexOf(“pplOwner”) != -1 && elem[i].id.indexOf(“TextBox”) != -1) users = elem[i].value; }
 
Thus, we couls easily put the value of people editor pplOwner in a label on the next tab using:
document.getElementById(‘<%=lblOwner.ClientID %>’).innerHTML = users;
 
  

We had to implement a tab functionality without postback, wherein the image of each tab changed on being clicked . This could be done very easily by implementing javascript and showing an hiding of different <div> on being clicked.

We had four divs, country1, country2, country3, country4.

On first time load only country1 is displayed and the others are hidden, consecutively, on clicking the second image country2 is displayed and the others are hidden.

 

I had a table displaying all the images,

<table>

<tr>

<td>

<div style=”float:left”>

<a href=”#” rel=”tcontent1″ >

<img id=”Img1″ src=”/_layouts/images/basics_hover.gif” onclick=”return changeImage(1);” style=”border:0″ />

</a>

</div>

<div style=”margin-left:-8px; float:left”>

 <a href=”#” rel=”tcontent2″ >

<img id=”Img2″ src=”/_layouts/images/scope_active001.gif” onclick=”return changeImage(2);” style=”border:0″ />

</a>

</div>

<div style=”margin-left:-8px; float:left”>

 <a href=”#” rel=”tcontent3″ >

<img id=”Img3″ src=”/_layouts/images/kits_active001.gif” onclick=”return changeImage(3);” style=”border:0″ />

</a>

</div>

<div style=”margin-left:-8px; float:left”>

 <a href=”#” rel=”tcontent1″ >

<img id=”Img4″ src=”/_layouts/images/submit_active001.gif” onclick=”return changeImage(4);”  style=”border:0″ />

</a>

</div>

</td>

</tr>

</table>

 

 

 The javascript for doing the trick is given below,

function changeImage(opt)

    {

    //alert(opt);

    var currImage1=document.getElementById(“Img1″).src;

    var currImage2=document.getElementById(“Img2″).src;

    var currImage3=document.getElementById(“Img3″).src;

    var currImage4=document.getElementById(“Img4″).src;

   

    var rExp1 = /basics_hover.gif/gi;

    var newstring1 = new String(“basics_active001.gif”);

   

    var rExp2 = /scope_hover.gif/gi;

    var newstring2 = new String(“scope_active001.gif”);

   

    var rExp3 = /kits_hover.gif/gi;

    var newstring3 = new String(“kits_active001.gif”);

   

    var rExp4 = /submit_hover.gif/gi;

    var newstring4 = new String(“submit_active001.gif”);

   

    if (opt==1)

    {

    

       if (currImage1.indexOf(“basics_active001.gif”)!=-1)

       { 

        var rExp = /basics_active001.gif/gi;

        var newstring = new String(“basics_hover.gif”);

        var result = currImage1.replace(rExp, newstring);

       

        document.getElementById(“Img1″).src = result;  

       

        if(currImage2.indexOf(“scope_hover.gif”)!=-1)

        {

            var result = currImage2.replace(rExp2, newstring2);

            document.getElementById(“Img2″).src = result;

        }

        if(currImage3.indexOf(“kits_hover.gif”)!=-1)

        {

            var result = currImage3.replace(rExp3, newstring3);

            document.getElementById(“Img3″).src = result;

        }

        if(currImage4.indexOf(“submit_hover.gif”)!=-1)

        {

            var result = currImage4.replace(rExp4, newstring4);

            document.getElementById(“Img4″).src = result;

        }

       

        country4.style.display= “none”;

        country1.style.display = “block”;

        country2.style.display = “none”;

        country3.style.display = “none”;

        

        }

        else if(currImage1.indexOf(“basics_hover.gif”)!=-1)

       {

        var rExp = /basics_hover.gif/gi;

        var newstring = new String(“basics_active001.gif”);

        var result = currImage1.replace(rExp, newstring);

        document.getElementById(“Img1″).src = result;

       }

    }

   

    if (opt==2)

    {

    

       if (currImage2.indexOf(“scope_active001.gif”)!=-1)

       { 

        var rExp = /scope_active001.gif/gi;

        var newstring = new String(“scope_hover.gif”);

        var result = currImage2.replace(rExp, newstring);

        document.getElementById(“Img2″).src = result;

       

        if(currImage1.indexOf(“basics_hover.gif”)!=-1)

        {

            var result = currImage1.replace(rExp1, newstring1);

            document.getElementById(“Img1″).src = result;

        } 

      

        if(currImage3.indexOf(“kits_hover.gif”)!=-1)

        {

            var result = currImage3.replace(rExp3, newstring3);

            document.getElementById(“Img3″).src = result;

        }

        if(currImage4.indexOf(“submit_hover.gif”)!=-1)

        {

            var result = currImage4.replace(rExp4, newstring4);

            document.getElementById(“Img4″).src = result;

        }

       

        country4.style.display= “none”;

        country1.style.display = “none”;

        country2.style.display = “block”;

        country3.style.display = “none”;

       

        }

        else if(currImage.indexOf(“scope_hover.gif”)!=-1)

       {

      

       }

    }

    if (opt==3)

    {

        if (currImage3.indexOf(“kits_active001.gif”)!=-1)

        {

            var rExp = /kits_active001.gif/gi;

            var newstring = new String(“kits_hover.gif”);

            var result = currImage3.replace(rExp, newstring);

            document.getElementById(“Img3″).src = result;

           

            if(currImage1.indexOf(“basics_hover.gif”)!=-1)

            {

            var result = currImage1.replace(rExp1, newstring1);

            document.getElementById(“Img1″).src = result;

            }

            if(currImage2.indexOf(“scope_hover.gif”)!=-1)

            {

            var result = currImage2.replace(rExp2, newstring2);

            document.getElementById(“Img2″).src = result;

            }

            if(currImage4.indexOf(“submit_hover.gif”)!=-1)

            {

            var result = currImage4.replace(rExp4, newstring4);

            document.getElementById(“Img4″).src = result;

            }

           

            country4.style.display= “none”;

            country1.style.display = “none”;

            country2.style.display = “none”;

            country3.style.display = “block”;

           

        }

        else if(currImage.indexOf(“kits_hover.gif”)!=-1)

        {

           

        }

    }

    if (opt==4)

    {

   

        if (currImage4.indexOf(“submit_active001.gif”)!=-1)

        {

            var rExp = /submit_active001.gif/gi;

            var newstring = new String(“submit_hover.gif”);

            var result = currImage4.replace(rExp, newstring);

            document.getElementById(“Img4″).src = result;

           

            if(currImage1.indexOf(“basics_hover.gif”)!=-1)

            {

            var result = currImage1.replace(rExp1, newstring1);

            document.getElementById(“Img1″).src = result;

            }

            if(currImage2.indexOf(“scope_hover.gif”)!=-1)

            {

            var result = currImage2.replace(rExp2, newstring2);

            document.getElementById(“Img2″).src = result;

            }

            if(currImage3.indexOf(“kits_hover.gif”)!=-1)

            {

            var result = currImage3.replace(rExp3, newstring3);

            document.getElementById(“Img3″).src = result;

            }

           

            country4.style.display= “block”;

            country1.style.display = “none”;

            country2.style.display = “none”;

            country3.style.display = “none”;

           

        }

        else if(currImage.indexOf(“kits_hover.gif”)!=-1)

        {  

        } }}

 

« Previous PageNext Page »