Wednesday, October 24, 2012

Image load Tracking in Google Analytics


Image tracking is provided by default with GA, to achieve this we can use Event Tracking for images.


Example:
So if you have an image “Mritunjay.jpg”

<img src="images/Mritunjay.jpg" />
<img src="images/Mritunjay.jpg" onload="_gaq.push(['_trackEvent','Image Tracking','Mritunjay']);" />


‘Image Tracking’ represents the Category
‘Mritunjay’ represents the Action

Thursday, October 18, 2012

Code Blocks are not allowed in this file - Performance Point part 2

As discussed in the previous post how we can fix the Code block error for performance Point, now lets find the reason why the error occurs on the PPSample.aspx and how we can eliminate it at the time of writing the Feature for Masterpage.

The main reason for this error is the the page is updated with the property "customized" this can be checked by the file property "CustomizedPageStatus" in the document library.


following is the code to check if the file is customized/unghosted.

void WriteCustomizedAndNone(object sender, EventArgs e)
        {
            string myResult = '';
            string myListName = txt1.Text;
            SPList myList = SPContext.Current.Web.Site.RootWeb.Lists[myListName];
            if (!Directory.Exists('C:\\Unghosted Files\\'))
            {
                Directory.CreateDirectory('C:\\Unghosted Files\\');
            }
            myResult += 'Status of items<br><br>';
            myResult += '<table style='border:solid 1px gray;'>';
            myResult += '<tr>' + '<td>' + 'Name' + '</td>' + '<td>' + 'Setup Path' + '</td>' + '<td>' + 'is customized' + '</td>' + '</tr>';
            foreach (SPListItem anItem in myList.Items)
            {
                myResult += '<tr>' + '<td >' + anItem.Name + '</td>' + '<td >' + anItem.File.Properties['vti_setuppath'] + '</td>'  + '<td>' + anItem.File.CustomizedPageStatus + '</td>' + '</tr>';
                if (anItem.File.CustomizedPageStatus.ToString() != 'Uncustomized')
                {
                    byte[] myBytes = anItem.File.OpenBinary();
                    System.IO.File.WriteAllBytes('c:\\Unghosted Files\\' + anItem.File.Name, myBytes);
                }
            }
            myResult += '</table>';
            result.Text = myResult;
        }/*Thanks to my friend Siva for this code*/


Note: The page gets updated with the property with Customized if there is any update happens on the page after/during the feature activation, make sure there is no changes happening during the feature activation. 

Any change in the master page will result in UnGhosting which will update the file property to "Customized" and will result in the issue with Performance point "Code Blocks are not allowed in this file".




Wednesday, October 3, 2012

Code Blocks are not allowed in this file - Performance Point



After the customization of the master page in SharePoint 2010, we sometimes get the following error
"Code Blocks are not allowed in this file"

There are two solution for this
1. Add the Page Parser Path in web.config
<PageParserPaths>
       <PageParserPath VirtualPath="/BICenter/Pages/ppssample.aspx" CompilationMode="Always" AllowServerSideScript="true" />
     </PageParserPaths>

2. Modify the PerformancePoint site template by updating the /BICenter/Pages/ppssample.aspx

Replace the following
var siteCollection = "<%=SPHttpUtility.UrlPathEncode(siteCol.Value,false,true)%>";
var siteLocation = "<%=SPHttpUtility.UrlPathEncode(site.Value,false,true)%>";

with
var siteCollection = "/";
var siteLocation = "/BICenter/";

Monday, September 24, 2012

Flyout control for Win8 Metro App

A flyout control is a popup control appear on an event.

The code to create flyout pop-up from Settings Page



args.Request.ApplicationCommands.Add(
new SettingsCommand("settings", "Application Settings",
    a =>
    {
     int width = 500;
     _settingsPopup = new Popup();
     _settingsPopup.Closed += OnPopupClosed;
     Window.Current.Activated += OnWindowActivated;
     _settingsPopup.IsLightDismissEnabled = true;
     _settingsPopup.Width = width;
     _settingsPopup.Height = Window.Current.Bounds.Height;
     AppSettingsFlyoutPopup mypane = new AppSettingsFlyoutPopup();
     mypane.Width = width;
     mypane.Height = Window.Current.Bounds.Height;
     _settingsPopup.Child = mypane;
     _settingsPopup.SetValue(Canvas.LeftProperty, Window.Current.Bounds.Width - mypane.Width);
     _settingsPopup.SetValue(Canvas.TopProperty, 0);
     _settingsPopup.IsOpen = true;
     this.layout.Opacity = .3;
     _settingsPopup.Closed += (e, s) => this.layout.Opacity = 1;
    }));

 
 

Wednesday, September 5, 2012

Feature Stapling in SharePoint 2010


Feature stapling helps us to enable the feature at following scope
1. Web
2. Site
3. Web application
4. Farm

Stapling required atleast two features
1. Feature that needs to be stapled
2. Feature to staple at different scope.
Obviously the stapler scope should be above the feature being stapled.

To activate the feature for type of sites in web application, we need to associate stapling a feature to global site definition(TemplateName=" GLOBAL") and blank site (TemplateName=" STS#1").

Elements file of Stapler feature will look like

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<FeatureSiteTemplateAssociation   Id="c4386b61-3aa0-4017-98c4-0feb17a97cb5" TemplateName=" GLOBAL" />
<FeatureSiteTemplateAssociation   Id="c4386b61-3aa0-4017-98c4-0feb17a97cb5" TemplateName=" STS#1" />
</Elements>



Solution example


Dialog box Styling in SharePoint 2010

SharePoint 2010 has two important classes to control the dialog display
.s4-notdlg
.ms-dialog


s4-notdlg
Apply the class to any div which is not required to disply

ms-dialog
This class is added to the tag of dialog, so we can modify the css of any class in the dialog.
e.g.
.ms-dialog .ms-cui-topBar2
{
   height:0px;
}

Friday, August 10, 2012

allowunsafeupdates, is really to safe



Using AllowUnsafeUpdates can be done in 2 ways
1. Get request :
2. Post request

Get request
It opens the gateway for the cross-site scripting, if we cannot switch to POST request then in that case we can go ahead with allowunsafeupdates, but make sure the property is set to false. Even though the property automatically sets to false after the use, but in case of exception we might end up in a situateion the property is true.


Eg. on how to use allowunsafeupdates

using (SPSite spsite = new SPSite(SPContext.Current.Site))
{
using (SPWeb spWeb = spsite.OpenWeb())
{
 try
 {
  SPFolder spfolder = spWeb.Folders[spWeb.Url + "/LibName/"];
  byte[] content = System.Text.Encoding.UTF8.GetBytes(strcontent);
  string filenname = "Upload" + DateTime.Now.ToString() + ".html";
  spWeb.AllowUnsafeUpdates = true;
  SPFile spfile = spfolder.Files.Add(filenname, content, true);
 }
 catch(Exception exp)
 { throw new exception(exp.message()) }
 finally
 {   spWeb.AllowUnsafeUpdates = false;  }
 }
}


Post request
In case of POST request we should go with SPUtility.ValidateFormDigest(), but this uses the digest value which can expire and will give the security validation exception.
Eg. on how to use allowunsafeupdates

using (SPSite spsite = new SPSite(SPContext.Current.Site))
{
using (SPWeb spWeb = spsite.OpenWeb())
{
 try
 {
  SPFolder spfolder = spWeb.Folders[spWeb.Url + "/LibName/"];
  byte[] content = System.Text.Encoding.UTF8.GetBytes(strcontent);
  string filenname = "Upload" + DateTime.Now.ToString() + ".html";
  SPUtility.ValidateFormDigest();
  SPFile spfile = spfolder.Files.Add(filenname, content, true);
 }
 catch(Exception exp)
 { throw new exception(exp.message()) }
}



Reference : http://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/

Getting the SMTP name for Web app


In place of explicitly hardcoding the SMTP name in the SharePoint to send mail, its always better to get the SMTP configured for the Web App, so that in future if due to any reason its getting changes, there will not be any impact on the application


private string GetSmtpServer()
{
 SPWebApplication parentWebAppp = SPContext.Current.Site.WebApplication;
 if (parentWebAppp != null)
 {
   return parentWebAppp.OutboundMailServiceInstance.Server.Address;
 }
return string.Empty;
}

Wednesday, April 11, 2012

Issue by enabling HTTPOnlyCookies on sharepoint site

HTTPOnlyCookie is enabled by default for Authentication and Sessions cookies in ASP.NET 2.0 but not for manually issued cookies. To enable it for manual issued cookie we need to add following in the web.config.
<httpCookies httpOnlyCookies="true" />

Once we enable the HTTPOnlyCookie on the SharePoint, few things like the default approval workflow for the list will give problem while enablind. We can notice it will add one extra parameter(Infopath_Sentinel=1) in the URL querystring. I am not sure what it is used for, but we cannot create the workflow.

So to avoid this we need te make sure the HTTPOnly cookie need not be enabled from the web.config.

Tuesday, April 10, 2012

Reading RSS feed

Recently while reading the data from the RSS feed, we faced an issue with the RSS not getting updated because of the Header cache. After analysis we found that its because of the caching on client server, we are not able to get the updated data.

To solve this we have tried many options, but the easiest option is to embed the querystring with GUID, which will make sure its always the fresh request.

Following is the sample code

string sSiteUrl = sFeedURL;
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
Guid guid = Guid.NewGuid();
sSiteContent = webClient.DownloadString(sSiteUrl+"?guid="+guid.ToString());
webClient.Dispose();

Tuesday, November 15, 2011

Changing Site Collection URL

There are no out-of-the-box command in SharePoint to rename a site collection URL, to change the URL we need to recreate the site collection with new URL and restore the previous site collection
Source site Collection URl : http://sharepointdev/sites/Mritunjay
Source site Collection URl : http://sharepointdev/sites/mritunjay

Steps to Change the site collection URL
  1. stsadm –o backup –url http://sharepointdev/sites/Mritunjay -filename backup.dat
  2. stsadm –o deletesite –url http://sharepointdev/sites/Mritunjay
  3. stsadm –o restore –url http://sharepointdev/sites/mritunjay -filename backup.dat

Tuesday, October 4, 2011

Cannot complete this action as the Secure Store Shared Service is not responding. Please contact your administrator.

While configuring the performance point 2010 I got the following issue
Cannot complete this action as the Secure Store Shared Service is not responding. Please contact your administrator.

After trying many approaches, I found the solution
1. Make sure the SecurityTokenServiceApplicationPool is running.
2. Go to System Settings -> Manage services on server
Following services should be enabled
PerformancePoint Service
Secure Store Service
Claims to Windows Token Service
3. Go to Application Management -> Manage service applications
4. Check the Secure Store is started
5. Go to App-pool and make sure the the associated App pool is running
6. Reset the IIS






Tuesday, August 2, 2011

Execute query with string

Today, I got a strange requirement to have the query as query string to execute, and tried various ways and found that the simplest way to do this is

Declare @temp Varchar(500)
Set @temp = ‘Select * From Employees’
Exec (@temp)

the above code will help us in adding or removing the clause from the query

Monday, July 25, 2011

FullTextSqlQuery Search Queries with URL

Recently I was working with Full Text SQL Search Queries and found a strange issue while filtering with the URL in the query. If the URL contains special characters its giving me the exception improper query.

My Old Query was
SELECT ArticleDate, URL FROM SCOPE()
WHERE CONTAINS(URL, 'http://mritunjay.com/sites/the site/docs/URLTest @/')

after few encoding I tried to embed the URL in the " I was able to get the correct output

SELECT ArticleDate, URLFROM SCOPE()
WHERE CONTAINS(URL, '"http://mritunjay.com/sites/the site/docs/URLTest !@$/"')

Wednesday, June 29, 2011

Windows Process Activation Service(WAS) stopped

Application pools cannot be started unless the windows Process Activation Service(WAS) is running

this error happens because of following reasons
1. Drive is out of space.
2. Folders deleted from the Inetpub : there is a great article by Scott which explains in details how to resolve. click here

Wednesday, June 22, 2011

List Throttling

List Throttling is a new feature in SharePoint 2010, it allows us to set the limit of how many rows of data can be retrieved from a list at a time. By default the list throttles to 5000 items. Let’s consider we have a list with 50000 entries and a user comes and creates a view with all the entries, then the SharePoint will return either error or the first set of results up to the number put in the list throttle.
The throttle can be set on the lookups in a list, and we can limit the lookup columns. If we have too many lookups the performance will suffer. As we limit maximum throttle for the user, we can override the same on the Object Model if we have the sufficient privilege.

using (SPSite site = new SPSite("http://mysite"))
{
using (SPWeb web = site.RootWeb)
{
try
{
SPList list = web.Lists["Shared Documents"];

SPQuery qry = new SPQuery();
qry.QueryThrottleMode = SPQueryThrottleOption.Override;

SPListItemCollection coll = list.GetItems(qry);
}
catch(SPQueryThrottledException)
{
// Throttle exception
}
}
}

Wednesday, April 6, 2011

Passing filter to View from Querystring

To pass the filter to the share point list view we can use FilterField1 and FilterValue1

FieldFilter : Column Name
FilterValue : Value of the Field

Sample
URL?FilterField1=Title&FilterValue1=Mritunjay

we can add more than one filters by just adding the FilterField2 and FilterValue3 in the querystring.

Tuesday, January 25, 2011

Adding Dropdown to Sharepoint Webpart Properties

Adding Dropdown to Sharepoint Webpart Properties

Create a Webpart and add custopm property
[WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
public string SearchPath
{
get { return _searchPath; }
set { _searchPath = value; }
}


Create a class and extend it from ToolPart

protected override void CreateChildControls()
{
webpart = this.WebPartToEdit as WebpartClass;
toolPanel = new Panel();
toolPanel.CssClass = "ms-ToolPartSpacing";
toolPanel.Controls.Add(GetToolPanel());
this.Controls.Add(toolPanel);
base.CreateChildControls();
}

public override void ApplyChanges()
{
webpart = this.WebPartToEdit as WebpartClass;
webpart.SearchPath = ddl.SelectedValue;
base.ApplyChanges();
}


Other functions in the extended class of ToolPart
private Control GetToolPanel()
{
toolPanelTable = new Table();
toolPanelTable.CellPadding = 0;
toolPanelTable.CellSpacing = 0;
toolPanelTable.Style["border-collapse"] = "collapse";
toolPanelTable.Attributes.Add("width", "100%");
toolPanelTable.Rows.Add(GetUseDropDown());
toolPanelTable.Rows.Add(GetSeperatorRow());
return toolPanelTable;
}
private TableRow GetUseDropDown()
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.Controls.Add(new LiteralControl("<div ><b>DropDownName</b></div>"));
cell.Controls.Add(new LiteralControl("<div ><div <nobr>"));
ddl = RecursiveParse(); //return the Dropdown List
cell.Controls.Add(ddl);
cell.Controls.Add(new LiteralControl("</nobr></div></div>"));
row.Cells.Add(cell);
return row;
}

private TableRow GetSeperatorRow()
{
TableRow row = new TableRow();
TableCell cell = new TableCell();
cell.Controls.Add(new LiteralControl("<div style='width:100%' ></div>"));
row.Cells.Add(cell);
return row;
}

Friday, January 21, 2011

Create a Custom View for Survey List

Work around to create Views for survey


1. Go to Settings of the Survey. And copy the List ID from URL
Example : ListID=%7BF2141E9F%2D8EA2%2D42EE%2DA965%2D52F1D7362066%7D
2. Open the View creation Page of sameSite
Example : http://SiteURL/_layouts/ViewType.aspx?List=ListID&Source=SurveyListURL
3. Then choose a view as we choose for other lists
4. Type Custom View Name.
5. Expand style tab, choose a style Basic Table
6. press OK and view is ready.

Friday, January 14, 2011

Sharepoint Search using Metadata Properties

Sharepoint Search using Metadata Properties

Creation of Metadata Property
1. Go to Shareod Services
2. Open Metadata Property mapping
3. Click on the New Managed Property
4. Fill in the details and add to Crawled Properties
5. Make sure to wait till the next crawl completes

Search Component

FullTextSqlQuery kwQuery = new FullTextSqlQuery(siteObject);
StringBuilder queryText = new StringBuilder();
queryText.Append("SELECT Title, ArticleDetails, URL "); //ArticleDetails is managed Property
queryText.Append("FROM SCOPE() WHERE ");
queryText.Append(" CONTAINS(URL , 'NEWS') AND NOT CONTAINS(URL , 'Forms') AND ");
queryText.Append(" \"scope\" = 'IntranetRelatedArticle' AND ");
queryText.Append("( FREETEXT(DEFAULTPROPERTIES, 'Mritunjay Chourasia')");
queryText.Append(" ORDER BY Rank Desc");

kwQuery.RowLimit = 5;
kwQuery.QueryText = queryText.ToString();
kwQuery.ResultTypes = ResultType.RelevantResults;
ResultTableCollection results = kwQuery.Execute();
ResultTable relevantResults = results[ResultType.RelevantResults];
while (relevantResults.Read())
{
//Search Data computation
}