Uncategorized


After migrating from MOSS 2007 to Sharepoint 2010/2013, sometimes for some lists/libraries the libraries/list control disappears, this is a fix to adress such issues.

In MOSS 2007, sometimes we added Content Editor Web Part in Allitems.aspx, to add some text or insert some logic/customizations.
However MOSS 2007 version did not have the ribbon control which was introduced from Sharepoint 2010 onwards.
In SharePoint 2010, if you have more than one web part on a web part page, the ribbon disappears because SharePoint doesn’t know which web part to display the ribbon for, because the ribbons are obviously different for the two and SharePoint needs to know which web part to display the ribbon for.
Once you select a web part (by clicking on it) the selected web part will become “active” and the correct ribbon will show up.

To automatically set the correct ribbon,we can use javascript to point the ribbon for the lists/library.

<title>
To automatically set the correct ribbon,we can use javascript to point the ribbon for the lists/library.
</title>
<other>
Add a content editor webpart to insert the below javascript in the allitems page.
Go to Site Actions >> Edit Page and you will see a web part zone where a CEWP can be addedin the page
</other>
function SelectWP(){
//select first webpart
var wp = document.getElementById(“_wpSelected”);
if (wp != null){
wp.value =”MSOZoneCell_WebPartWPQ2″;
SelectRibbonTab(‘Ribbon.Document’, true)
}
}
ExecuteOrDelayUntilScriptLoaded(SelectWP, “sp.ribbon.js”);

Advertisements

StyleCOP

 

What is it

 

It is a source analysis tool for C#. It can be used for analyzing source code as opposed to compiled assemblies which is the area for FxCop. StyleCop analyzes C# code with a set of rules to check whether the code follows the rules. It is a Microsoft tool (run from inside of Visual Studio or integrated into an MSBuild project).

 

Where to find

 

It can be downloaded from http://stylecop.codeplex.com/

 

Why to use

 

StyleCop is a light weight source code analysis tool which fills in the necessary gap. One of the benefits of StyleCop can be realised while conducting code reviews.

 

How to use

 

If you click on the downloads section, you will see three setups, one is the StyleCop setup which actually installs the software and the other two are CHM help files. One help file talks about the rules and the other about the API exposed by StyleCop.

Once you install StyleCop, nothing will be seen as in start menu. When you open any project of C# and right click on the project, you should see two menus in the project as shown in the figure below – one which helps us select the rules, i.e. the Stylecop settings menu and the other which runs these rules on the C# project.

 

If you just run the stylecop, you should see broken rules in output window as shown in the figure below:

 

 

Depending on your style or your coding standards, you will either agree or disagree with detected violations. For example in the result above I do not agree with rule SA1200 “All using directives must be placed inside of the namespace”. I have never declared my using statements inside the namespace and I do not intend to do so in future. So what can I do? I can easily modify the rule set. Let’s see how we can do this.

Right click the project and go to StyleCop Settings.

I can turn off rule SA1200 “All using directives must be placed inside of the namespace” and then if I run analysis again, my result set will not show it as a rule violation.

 

As you can see from screenshots above that rules are categorised into different categories such as Documentation Rules, Layout Rules, Naming Rules etc. This makes is easy work with rules in a logical way.

 

I have a webpart which renders a html as below:

<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td id="MSOZoneCell_WebPartWPQ8" vAlign="top"><table TOPLEVEL border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td valign="top"><div WebPartID="a0d356f1−3e14−45bf−a1f1−9f3d2a5eff00" HasPers="false" id="WebPartWPQ8" width="100%" class="ms−WPBody" allowDelete="false" style="height:425px;overflow:auto;" >

<i f rame frameBorder="0" border="0" width="100%" height="100%" overflow−x="visible" marginwidth="0" marginheight="0" marginTop="100px" scrolling="no" src="http://css.override.com/countup_flash.html">
<div class="UserGeneric">The current browser does not support Web pages that contain the IFRAME element. To use this Web Part, you must use a browser that supports this element, such as Internet Explorer version 5 or later.</div>
</iframe></div></td>
</tr>
</table></td>
</tr>
</table>


I need to change the css (remove outlining border) only from that webpart without touching any other webpart on the page.
This can be done by overriding css for that particular webpart, as shown below:

#MSOZoneCell_WebPartWPQ8 div.ms-WPBody{
{
border-left:none !important;
border-top:none !important;
border-right:none !important;
border-bottom:none !important;
padding-left:0px !important;
padding-top:8px !important;
padding-right:0px !important;
background-color:#ffffff !important;
}

The export to spreadsheet link was not visible in a particular list and we had an urgent request to export data from list to an excel.

So we created a windows application to take care of it.

Added web reference http://extranet/sites/sis-forum/_vti_bin/lists.asmx to the project and named it Sisforum.

Added a textbox txtSiteUrl  in the Windows form…and added the url of the site from where we wanted to export a list to excel e.g https://test-web.domain.org/sites/isago/_vti_bin/lists.asmx , in another textbox txtListName ,gave the name of the list we wanted to export,say “UserManagement Task” and a textbox txtFilepath  for putting the filepath like “c:\test.xls”.

 

            StringBuilder strExcel = new StringBuilder();
            StringBuilder strHtml = new StringBuilder();
            System.Net.NetworkCredential credential = new System.Net.NetworkCredential(“username”, “password”);
            XmlDocument xdoc = new XmlDocument();
            XmlNode allFields = xdoc.CreateElement(“ViewFields”);
            XmlNode QueryOpt = xdoc.CreateElement(“QueryOptions”);
            XmlNode Query = xdoc.CreateElement(“Query”);
            XmlNode xmlResults;
            try
            {
               SisForum.Lists lsts = new ExporttoExcelFile.SisForum.Lists();
                lsts.Credentials = credential;
                lsts.Url = txtSiteUrl.Text+”/_vti_bin/lists.asmx”;
                xmlResults = lsts.GetListItems(txtListName.Text, null, null, null, “1000000”, null, null);
                //Get Header Row
                foreach (XmlNode node in xmlResults)
                {
                    if (node.Name == “rs:data”)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            strExcel.Append(“\n”);
                           strHtml.Append(“”);
                           if (node.ChildNodes[i].Name == “z:row”)
                            {
              for (int j = 0; j < node.ChildNodes[i].Attributes.Count; j++)
                                {
                                    if (node.ChildNodes[i].Attributes[j] != null)
                                    {
                     string name = node.ChildNodes[i].Attributes[j].Name;
                                        name = StripHTML(name);
                   strExcel.Append(name.Substring(name.IndexOf(‘#’) + 1));
                                        strExcel.Append(“\t”);
                                    }
                                }
                            }
                        }
                    }
                }

                //Get List Items
                foreach (XmlNode node in xmlResults)
                {
                    if (node.Name == “rs:data”)
                    {
                        for (int i = 0; i < node.ChildNodes.Count; i++)
                        {
                            strExcel.Append(“\n”);
                            strHtml.Append(“”);
                            if (node.ChildNodes[i].Name == “z:row”)
                            {  
                                //get list items
          for (int j = 0; j < node.ChildNodes[i].Attributes.Count; j++)
                                {
                                    if (node.ChildNodes[i].Attributes[j] != null)
                                    {
        string name = node.ChildNodes[i].Attributes[j].Value;
                                        name = StripHTML(name);
                   strExcel.Append(name.Substring(name.IndexOf(‘#’) + 1));
                                        strExcel.Append(“\t”);
                                    }
                                }
                            }
                        }
                    }
                }
               WritetoFile(strExcel,”xls”);
               MessageBox.Show(“Completted”);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

public void WritetoFile(StringBuilder str,string Format)

        {

            string filename = txtFilepath.Text;

            TextWriter tw = new StreamWriter(filename);

            tw.Write(str);

            tw.Close();

        }

Now the string that we get from the xml by calling GetListItems needs to be formatted.We need to remove HTML development formatting, replace line breaks with space because browsers insert spaces,remove all scripts etc. The below functio takes care of that:

public string StripHTML(string source)

        {

            try

            {

                string result;

                // Remove HTML Development formatting

                // Replace line breaks with space

                // because browsers inserts space

                result = source.Replace(“\r”, ” “);

                // Replace line breaks with space

                // because browsers inserts space

                result = result.Replace(“\n”, ” “);

                // Remove step-formatting

                result = result.Replace(“\t”, string.Empty);

                // Remove repeating spaces because browsers ignore them

result = System.Text.RegularExpressions.Regex.Replace(result,  @”( )+”, ” “);

// Remove the header (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result, @”<( )*head([^>])*>”, “<head>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  @”(<( )*(/)( )*head( )*>)”, “</head>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  “(<head>).*(</head>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

// remove all scripts (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result,    @”<( )*script([^>])*>”, “<script>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,  @”(<( )*(/)( )*script( )*>)”, “</script>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);         

result = System.Text.RegularExpressions.Regex.Replace(result,   @”(<script>).*(</script>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

// remove all styles (prepare first by clearing attributes)

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*style([^>])*>”, “<style>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,    @”(<( )*(/)( )*style( )*>)”, “</style>”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, “(<style>).*(</style>)”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*td([^>])*>”, “\t”,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags

result = System.Text.RegularExpressions.Regex.Replace(result,    @”<( )*br( )*>”, “\r”,                          System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*li( )*>”, “\r”,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place

                // if <P>, <DIV> and <TR> tags

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*div([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”<( )*tr([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”<( )*p([^>])*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,

                // comments etc – anything that’s enclosed inside < >

result = System.Text.RegularExpressions.Regex.Replace(result, @”<[^>]*>”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:

result = System.Text.RegularExpressions.Regex.Replace(result,   @” “, ” “,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&bull;”, ” * “,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”&lsaquo;”, “<“,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&rsaquo;”, “>”,     System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&trade;”, “(tm)”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&frasl;”, “/”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&lt;”, “<“,    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result, @”&gt;”, “>”,  System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,   @”&copy;”, “(c)”,    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&reg;”, “(r)”,   System.Text.RegularExpressions.RegexOptions.IgnoreCase);

result = System.Text.RegularExpressions.Regex.Replace(result,  @”&(.{2,6});”, string.Empty,                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                return result;

            }

            catch

            {

                return source;

            }

        }

Well, everyone has worked with datatables sometime or the other. In this article, I just wanted to illustrate the various usage and implementation of datatables.

The DataTable object represents tabular data as rows, columns, and constraints.Use the DataTable object to hold data in memory while performing disconnected data operations.Datatable consists of DataColumn and DataRow.
The DataTable object must contain DataColumn objects before any data can be added to the DataTable object.

In this example, we have a datatable with three columns, Name, Adress and Date of Joining(DOJ) which is a datetime column.

dtResults = new DataTable();
dtResults.Columns.Add(“Name”, Type.GetType(“System.String”));
dtResults.Columns.Add(“Department”, Type.GetType(“System.String”));
dtResults.Columns.Add(“DOJ”, Type.GetType(“System.DateTime”));

Adding row to datatable:
dtResults.Rows.Add(“Olyvia”, “Developer”, DateTime.Now);

Adding a datatacolumn to dtresults and populating it with default values

dcRec = new DataColumn(“Age”, typeof(int));
dcRec.DefaultValue = 23;
dtResults.Columns.Add(dcRec);

datatable Select
The DataTable Select method accepts a filter and sort argument to return an arry of DataRow objects that conform to the criteria in a FilterExpression.
DataRow[] drResultSet= dtResults.Select(“Age ’21′”);

To get the column name dynamically, see the example below:

DataRow[] drResultSet;
drResultSet = dtResults.Select(site.Fields[“ID”].InternalName + “='” + dtStore.Rows[i][“DocUniqueID”].ToString().Substring(0, dtStore.Rows[i][“DocUniqueID”].ToString().IndexOf(“.”)) + “‘ and ” + site.Fields[“Title”].InternalName + “='” + dtStore.Rows[i][“Title”] + “‘”);

How to remove duplicate rows from a datatable
If some rows of a some columns in the datatable are repititive and duplicate and you want to remove them, then see the example below:

DataColumn[] keyColumns = new DataColumn[] { dtStore.Columns[“DocUniqueID”], dtStore.Columns[“DocType”] };
//remove the duplicates
RemoveDuplicates(dtStore, keyColumns);

private static void RemoveDuplicates(DataTable tbl,DataColumn[] keyColumns)
{
int rowNdx = 0;
while (rowNdx 0)
{
foreach (DataRow dup in dups)
{
tbl.Rows.Remove(dup);
}
}
else
{
rowNdx++;
}
}
}

private static DataRow[] FindDups(DataTable tbl,int sourceNdx,DataColumn[] keyColumns)
{
ArrayList retVal = new ArrayList();
DataRow sourceRow = tbl.Rows[sourceNdx];
for (int i = sourceNdx + 1; i < tbl.Rows.Count; i++)
{
DataRow targetRow = tbl.Rows[i];
if (IsDup(sourceRow, targetRow, keyColumns))
{
retVal.Add(targetRow);
}
}
return (DataRow[])retVal.ToArray(typeof(DataRow));
}

private static bool IsDup(DataRow sourceRow,DataRow targetRow,DataColumn[] keyColumns)
{
bool retVal = true;
foreach (DataColumn column in keyColumns)
{
retVal = retVal && sourceRow[column].Equals(targetRow[column]);
if (!retVal) break;
}
return retVal;
}

How to edit a row in datatable

strName = “Gitolekha”;
drResultSet[0][“Name”] = strName.ToString();
dtResults.AcceptChanges();

Datatables have lots of features and functionality, I have just covered some of them, more will be covered next time.

I was trying to create a table and add rows and cells in it using c#.

And tried to hyperlink in a tablecell, tried to add styles in the hyperlink without touching the css class and open the hyperlink popup via navigateurl in a new window.

putting hyperlink on tablecell:

TableRow tr = new TableRow();
TableCell td = new TableCell();
HyperLink hyper1 = new HyperLink();
hyper1.NavigateUrl = “https://techolyvia.wordpress.com/category/technical/sharepoint/spgroup/&#8221;;
hyper1.Text = “SPGroup”;
td.Controls.Add(hyper1);
tr.Cells.Add(td);
tableOuterCtrl.Rows.Add(tr);

Using navigateurl to open in a new window:

hyper1.Target = “_blank”;

Add styles in hyperlink without modifying css classes.

hyper1.Style.Add(“font”, “normal 8pt Verdana;”);
hyper1.Style.Add(“color”, “black”);

full code goes like this:
tableOuterCtrl = new Table();
tableOuterCtrl.CellPadding = 0;
tableOuterCtrl.CellSpacing = 0;
Controls.Add(tableOuterCtrl);
TableRow tr;
TableCell td;
tr = new TableRow();
tr.Width = Unit.Percentage(100);
tableOuterCtrl.Rows.Add(tr);
td = new TableCell();
HyperLink hyper1 = new HyperLink();
td.Wrap = false;
td.Width = Unit.Percentage(100);
hyper1.Style.Add(“font”, “normal 8pt Verdana;”);
hyper1.Style.Add(“color”, “black”);
hyper1.NavigateUrl = “https://techolyvia.wordpress.com/2009/03/31/report-to-show-all-users-and-user-groups-in-sharepoint-site/&#8221;;
hyper1.Target = “_blank”;
hyper1.Text = “Displaying all users and groups through coding”;
td.Controls.Add(hyper1);
tr.Cells.Add(td);
tableOuterCtrl.Rows.Add(tr);
this.Controls.Add(tableOuterCtrl);

An user might want to email an url like the one given below:
http://gitolekha:82/default.aspx?ConnectSearch=good sharepoint blog

We need to do url encoding to send such links because often url’s contain characters outside the ASCII set, so URL encoding converts the url to valid ASCII sets.URL encoding replaces unsafe ASCII characters with “%” followed by two hexadecimal digits corresponding to the character values in the ISO-8859-1 character-set.

URLs cannot contain spaces. URL encoding normally replaces a space with a + sign or as %20.

To do url encoding with .NET,one usually uses System.WebHttpUtility.UrlEncode to encode the querystring.

I had to do this through javascript.There are methods like
escape(string) to do encoding, but it did not work for me.
So, what I chose is the replace mothod to replace all unsafe characters.
what I used is regular expression to replace all occurences of space in  string “good sharepoint blog” as encodestring.replace(/\\s+/g ,’$-*’);

A detailed explaination of the above is as follows,
/ = start pattern
, = pattern to look for in the string badtext
/ = end pattern
g = global (anywhere the pattern match occurs in the string)
“$-*” = what to replace the pattern with if found

So, the full code to send the encoded url in email is given below.

parent.location = ‘mailto:?body=” + HttpUtility.UrlEncode(SPContext.Current.Web.Url + “/default.aspx?ConnectSearch=”) + “‘+txtSearch.value.replace(/\\s+/g ,’$-*’)+’~-~User=’+txtTopicsSearch.value.replace(/\\s+/g ,’$-*’)+’~-~Place=’+txtDocTypeSearch.value.replace(/\\s+/g ,’$-*’)+’~-~Country=’+txtCountrySearch.value.replace(/\\s+/g ,’$-*’)+’&subject=site search link’

The mail has a subject line of ‘site search link’ as seen above.

This emails the encoded url as,
http://gitolekha:82/default.aspx?ConnectSearch=good$-*sharepoint$-*blog~-~User=gitolekha~-~Place=any$-*where/$-*in$-*India~-~Country=All$-*geographic$-*scopes

Now when the user types/paste the above url in the browser, we can use httphandler to make the application decode the above url in the desired format.
Now, we know that an ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. When users request an .aspx file, the request is processed by the page handler.An IHttpModule is registered in the Web.Config file and it is notified of every HTTP request.
IHttpModule is an interface defined in System.Web.dll. The interface contains only two method signatures: Init and Dispose. On the Init method wire up, the behavior—for example application events—that you want the IHttpModule to support and perform any clean up in the Dispose method.

using System.Web;
namespace Gitolekha.Sample.KnowledgeManagement
{
class CustomHandler : IHttpModule
{
public void Dispose()
{
//throw new Exception(“The method or operation is not implemented.”);
}
public void Init(HttpApplication context)
{
context.BeginRequest+=new EventHandler(context_BeginRequest);
}
public void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
string requestedPage = app.Request.RawUrl;
if (requestedPage.Contains(“?ConnectSearch=”))
{
string strurl = app.Request.Url.AbsoluteUri;
if (strurl .Contains(“$-*”))
{
strurl = strurl.Replace(“$-*”, ” “);
}
if (strurl.Contains(“~-~”))
{
strurl = strurl.Replace(“~-~”, “&”);
}
string strencode = HttpUtility.UrlEncode(strurl );
HttpContext.Current.Response.Redirect(strurl, true);
}}

This will do the required decoding for this url.
Possible scenarios/reasons for users wanting to send url might be Sometimes it is easy for users to email interesting links of a site to another user.To elaborate, suppose you have a document management system where the users like to share interesting and important links of documents to other users through emails.

Next Page »