Searching in a list with one keyword across two columns

We have a document list with 2 columns. One is a text column and other is a lookup column

The requirement was that, user should be able to search across two columns, where the condition being, search should match with either of the column. The following url format works for this particualr scenario.

http://server/sites/site1/sitePages/DocumentSearchPage.aspx?k= &r=Column1:”query*” OR Column2:”query*”&cs=This List&u=http://server/sites/site1/library1

Note:

DocumentSearchPage.aspx has a Search Core Results webpart.

The parameer “k” is not required. But sometime without this parameter search result is blank. Hence “k” will have a empty character as string.

cs=This List is a query paramter which helps in searching a particular library. This depends on the parameter “u” explained in next line.

u=http://server/sites/site1/library1 is the library from which search result should come.

Setting password for Managed Account

Password for Managed Account in SharePoint 2010 can be set in the following ways.

Set a new password for Managed Account

#If there is only one managed account, the following line could be written as: 
#$inputManagedAcct = Get-SPManagedAccount

$inputManagedAcct = Read-Host "Enter managed account as Domain\User"

#Input the desired new password
$inputPasswd = Read-Host "Enter new password for managed account" –AsSecureString 

#Change the password for the managed account to the new value Set-SPManagedAccount -Identity $inputManagedAcct -NewPassword $inputPasswd

To update the account password to a new automatically generated value, from the Windows PowerShell command prompt, type the following:

Set-SPManagedAccount –Identity domain\user -AutoGeneratePassword $true

Update the password for a Managed Account that has already been reset through Active Directory

If the password for a managed service account has been manually changed outside of SharePoint (such as directly in Active Directory), you can update the password to the new value in SharePoint 2010 as follows

#If there is only one managed account, the following line could be written as: 
#$inputManagedAcct = Get-SPManagedAccount

$inputManagedAcct = Read-Host "Enter managed account as Domain\User:" 
#Input the Managed Account $inputPasswd = Read-Host "Enter password from Active Directory for managed account:" –AsSecureString 

#Change the password in SharePoint for the managed account to the new value 
Set-SPManagedAccount -Identity $inputManagedAcct -ExistingPassword $inputPasswd –UseExistingPassword $true

To update the account password to a already changed password, from the Windows PowerShell command prompt, type the following:

Set-SPManagedAccount -Identity domain\user -UseExistingPassword

For more information look at http://blogs.technet.com/b/seanearp/archive/2011/01/25/updating-passwords-on-sharepoint-2010.aspx

Access Denied – SharePoint code execution

When doing certain code operations in SharePoint like getting list of templates will lead to “Access Denied” exceptions. For such instances we can wrap the code within the following lines to execute code with elevated privileges.

SPSecurity.RunWithElevatedPrivileges(delegate()
{
        //Code goes here
});

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

We were developing a Server Object Model based functionality in SharePoint involving site creation using template. During development we use to get the following error in quick watch window.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

To solve this issue we added the following code before the actual statement and issue was solved.

SPSecurity.CatchAccessDeniedException = false;

 

Deleting a file from library using SharePoint ASMX web service

The following is the code for deleting a particular file from a library using SharePoint ASMX web service.
The technique involves identifying the document ID using “GetListItems” of the file and then executing “UpdateListItems”

public string DeleteFileFromSharePoint(string siteUrl, string libraryName, string fileName, FileDeleteInput input)
    {
        Lists listService = new Lists(); //Web reference of http://<server>/sites/<site>/_vti_bin/lists.asmx
        listService.Url = "http://<server>/sites/<site>/_vti_bin/lists.asmx";
        listService.UseDefaultCredentials = true;
        string sourceUrl = fileName;
        string output = string.Empty;

        try
        {
            int fileId = GetFileIdFromList(siteUrl, libraryName, fileName, listService.Url);

            XmlDocument doc = new XmlDocument();
            XmlElement Batch = doc.CreateElement("Batch");
            Batch.SetAttribute("OnError", "Continue");
            Batch.SetAttribute("ListVersion", "1");
            Batch.SetAttribute("ViewName", "");
            string strBatch = "<Method ID='1' Cmd='Delete'>";
            strBatch += "<Field Name='ID'>" + fileId + "</Field>";
            strBatch += "<Field Name='FileRef'>" + siteUrl + libraryName + "/" + fileName + "</Field>";
            strBatch += "</Method>";
            Batch.InnerXml = strBatch;

            XmlNode returnvalue = listService.UpdateListItems(libraryName, Batch);

            if (returnvalue.InnerXml.Contains("0x00000000"))
            {
                output = "Success: File Deleted";
            }
            else if (returnvalue.InnerXml.Contains("Invalid file name"))
            {
                output = "Failure: No such file exists";
            }
            else if (returnvalue.InnerXml.Contains("Access denied"))
            {
                output = "Failure: No such file exists";
            }
            else
            {
                output = "Failure: File couldn't be deleted";
            }
        }
        catch (SoapException ex)
        {
            throw ex;
        }
        catch (Exception)
        {
            throw ex;
        }
        return output;
    }

    protected int GetFileIdFromList(string siteUrl, string libraryName, string fileName, string serviceUrl)
    {
        int id = 0;

        Lists listService = new Lists(); //Web reference of http://<server>/sites/<site>/_vti_bin/lists.asmx
        listService.Url = serviceUrl;
        listService.UseDefaultCredentials = true;

        // Build the CAML Query
        System.Text.StringBuilder queryStringBuilder = new System.Text.StringBuilder();
        queryStringBuilder.Append("     <Query>");
        queryStringBuilder.Append("         <Where>");
        queryStringBuilder.Append("             <Eq>");
        queryStringBuilder.Append("                  <FieldRef Name=\"FileLeafRef\" />");
        queryStringBuilder.Append("                  <Value Type=\"Text\">" + fileName + "</Value>");
        queryStringBuilder.Append("             </Eq>");
        queryStringBuilder.Append("        </Where>");
        queryStringBuilder.Append("    </Query>");

        XmlDocument query = new XmlDocument();
        query.LoadXml(queryStringBuilder.ToString());

        //Build the View Query 
        queryStringBuilder.Clear(); // Clear the string builder
        queryStringBuilder.Append("    <ViewFields>");
        queryStringBuilder.Append("    <FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" /><FieldRef Name=\"Name\" />");
        queryStringBuilder.Append("    </ViewFields>");

        XmlDocument viewFields = new XmlDocument();
        viewFields.LoadXml(queryStringBuilder.ToString());

        //Build the CAML Query Options
        queryStringBuilder.Clear(); // Clear the string builder
        queryStringBuilder.Append("    <QueryOptions>");
        queryStringBuilder.Append("         <Folder>" + libraryName + "/</Folder> />");
        queryStringBuilder.Append("    </QueryOptions>");

        XmlDocument queryOptions = new XmlDocument();
        queryOptions.LoadXml(queryStringBuilder.ToString());

        XmlNode listItems = listService.GetListItems(libraryName, null, query, viewFields, null, queryOptions, null);

        foreach (XmlNode outerNode in listItems.ChildNodes)
        {
            if (outerNode is XmlWhitespace)
                continue;
            else
            {
                if (outerNode.Name == "rs:data")
                {
                    foreach (XmlNode innerNode in outerNode.ChildNodes.OfType<XmlNode>())
                    {
                        if (innerNode is XmlWhitespace)
                            continue;
                        else
                        {
                            id = Int32.Parse(innerNode.Attributes["ows_ID"].Value.ToString());
                        }
                    }
                }
            }
        }

        return id;
    }

 

SharePoint Error – Code blocks are not allowed in this file

When I was adding an in-line code into master page I was getting the following error.

An error occurred during the processing of /sites/<collection>/SitePages/Welcome.master. Code blocks are not allowed in this file.

The fix is add the following code to the web.config of the web application which hosts the site collection.



Displaying Current User In SharePoint Master Page

One of the requirements while I was working in SharePoint 2010 was displaying the user name in the master page.

So the following are the 2 pieces of code.

Add the following code to the body tag inside master page. Make sure the below code is outside of any tag which has the runat=”server” property set.

<script type=”text/javascript”>var loginName = “<%= Microsoft.SharePoint.SPContext.Current.Web.CurrentUser.Name %>”;</script>

Now put the following code where ever required.

<span>Welcome, <script type=”text/javascript”>document.write(loginName);</script></span>

 

If you face the following error…check out the link https://blog.binarybits.net/?p=207

An unexpected error has occurred 

If you face the following error…check out the link https://blog.binarybits.net/?p=215

Code blocks are not allowed in this file

If you face the following error… check out the link https://blog.binarybits.net/?p=211

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).