Friday, October 28, 2011

Invoking Server Side method using Jquery

Hi All,

Recently we had a requirement of performing database operation on the click of a submit button of a web part. In order to avoid post back and trying to implement something new, we tried using jquery for the same.

We used jquery to invoke the server side methods. The methods were defined as web method on an application page (_layouts folder). The web method looked something like this :

[webmethod]
public static void AddNewData(string UserId,string favoriteName, string favoriteURL, string flagmovetoTop)
{
//some business logic
}

Then on the click of the submit button we invoked the java script method, where we performed the data base operations using "JSON". Below is the code snippet for the same.

$(document).ready(function () {
$.ajax({
type: "POST",
url: 'url of the method',
data: "{'userID':'" + userId + "', 'favoriteName':'" + favname + "', 'favoriteURL':'" + favUrl + "','flagmovetoTop':'" + ismovetoTop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var result = msg.d;
if (result >= 0) {
SubmitClicked();
}
else {

}
}, failure: function (msg) {
// alert(msg);
}
});
});


url : URL parameter is the url of the method used to perform the operation. As mentioned we defined the web methods on the application page so the URL parameter looks something as below :
/_layouts/FolderName/PageName.aspx/AddNewData

One thing which we should keep in mind that if the button is defined on an application page, we need to provide complete url of the method like "http://_layouts/FolderName/PageName.aspx/AddNewData".


data : The data parameter accepts the values of the variables which the web method accepts. The web method which we used accepts four parameters. One thing which we should note that 'UserID', 'favoriteName','favoriteURL' and 'flagmovetoTop' are the name of the parameters defined in the web method.

We were performing database operation and using stored procedure for the same. From the stored procedure we returned '0' if the operation is success else '-1'.

Depending the value returned from the method, the 'result' variable will have value in it. So if it is success (if result ==0) we perform some set of further operation.

Hope this helps.. :)

Monday, October 24, 2011

Passing arguments and handling return value in SP.UI.ModalDialog.showModalDialog

Hi All,

Recently I had a requirement to open a modal window using "SP.UI.ModalDialog.showModalDialog". Also on the modal window we were doing some database operations on the button click and after successful implementation we need to close the modal window and redirect the parent window to the home page of the application.

Also we need to pass some parameters from the parent to the modal window to perform the database operation.

In order to pass value to the modal window, I used the "args" option of the dialog. Also to handle the return value "dialogReturnValueCallback" was implemented. (The list of various options of the dialog can be found here)

Below is the code snippet which I had used to cater my business requirement.

var URLValue ="url of the page which needs to be shown as modal";
//parameters that needs to be passed to the modal window is defined in myArgs
var myArgs = {favoriteName:bookmarkTitle,favoriteURL:bookmarkUrl};
var options = {
url: URLValue,
title: 'Modal Window Test',
allowMaximize: false,
showClose: true,
width:600,
autoSize:true,
args:myArgs,
dialogReturnValueCallback: myDialogCallback
};
var dialogSP = SP.UI.ModalDialog.showModalDialog(options);
});
function myDialogCallback(result,response)
{
if(result ==1)
{
window.location.href = "url of the page where we are redirecting after successful operation";
}
}

The above snippet list down how to open a modal window, passing parameters and defining the return call back. Now we need to make sure that on the button click (submit,OK)on the modal window we pass respective values back to the parent page for further operations.

Below is the code snippet for the same.

function SubmitClicked() {
var results = {
message: "Submmited Successfully",
anothervalue: "Submit"
};
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, results);
}
On the code behind we can register this function like "Button.attributes.add("onclick",SubmitClicked())". This will pass value "1" in the result and we handle the same in the returncallback function "myDialogCallback".

Hope this helps you.. :)

Sunday, July 24, 2011

Sharepoint Provider Load Failure in Visual Studio 2010

Hi All,

Recently I had an issue while deploying Visaul Studio 2010 in the SharePoint environment. It was working fine and suddenly started giving issue saying :

"Sharepoint Provider Load Failure".

To resolve the issue, we need to just restart Windows Management Instrumentation.

Navigate to service.msc and locate "Windows Management Instrumentation". Restart the service and we are good to go again !!!!!!!!!!!! :)

Hope this helps..

Wednesday, May 4, 2011

Redirection from SharePoint Control to application page

I was recently working on a requirement where when user clicks on a link, we need to redirect the user to a SharePoint page in the layouts folder where we were doing further processing depending on the business requirement. The link was was embedded in the master page of the site so that it's globally available to the user.

Initially it looked to be a simple requirement and we thought of implementing it using SPControl. On the click of the link we need to pass some parameter to the application page for further processing.

When we implemented the code, and on the click of the link (we redirected using javascript) when we redirected user to the application page we got error related to the view state of the control. We realized that the simple redirect will not serve the purpose.

In order to achieve this requirement (thanks to my architect "Thiya" for suggesting this), we created a form using javascript and posted the same to the required url (application page). On the application page (.aspx) we defined a form. On the code behind we retrieved the value from the request from the previous page. Below is the code snippet for posting the form using javascript from the spcontrol.
I had written the below code in the render method (can be switched anywhere else as per convenience)

string id = this.Page.ClientID + "_ProfilebtnLink1";
writer.WriteLine("");


On the application page, define a form (in the page).
form id ="test"

In the code behind get the value which was posted as below (I did in teh apge laod event)
userName = Request["UID"];

Hope this will help.. :)

Saturday, April 30, 2011

Form Authentication Sign Out in SharePoint

Recently, in one of the requirement we had to implement a sign-out of the user from form authentication programatically when user clicks on a link and login user back using some different credentials.

To set a back ground we had following environment :

1. SharePoint 2010 FBA enabled site.
2. Custom membership provider.
3. Custom login page for FBA.

Now when the user clicks on the link, we were deleting the FedAuth cookies and signin out user from Form authentication and redirecting user back to the custom login page. (Below code snippet).

However after doing all this when user was redirected back to login page we could still see the FedAuth cookie value in the header.


//some usiness logic here
if (HttpContext.Current.Request.Cookies["FedAuth"] != null)
{
HttpCookie requestCookie = new HttpCookie("FedAuth");
requestCookie.Secure = false;
requestCookie.Expires = DateTime.Now.AddYears(-1);
}
FederatedAuthentication.SessionAuthenticationModule.SignOut();
FormsAuthentication.SignOut();


To resolve this issue, we tried to delete cookies FedAuth,WSS_KeepSessionAuthenticated and .ASPXAUTH (both from request and response. I did for both and it worked for me).


{
//some usiness logic here
DeleteRequestCookies();
DeleteResponseCookies()
FederatedAuthentication.SessionAuthenticationModule.SignOut();
FormsAuthentication.SignOut();
}

private void DeleteRequestCookies()
{
for (int i = 0; i < HttpContext.Current.Request.Cookies.Count; i++)
{
string cookieName = string.Empty;
switch (HttpContext.Current.Request.Cookies[i].Name)
{
case "FedAuth":
cookieName = "FedAuth";
break;
case "WSS_KeepSessionAuthenticated":
cookieName = "WSS_KeepSessionAuthenticated";
break;
case ".ASPXAUTH":
cookieName = ".ASPXAUTH";
break;
}
if (HttpContext.Current.Request.Cookies[cookieName] != null)
{
HttpCookie requestCookie = new HttpCookie(cookieName);
requestCookie.Secure = false;
requestCookie.Expires = DateTime.Now.AddYears(-1);
}
}
}
private void DeleteResponseCookies()
{
for (int i = 0; i < HttpContext.Current.Response.Cookies.Count; i++)
{
string cookieName = string.Empty;
switch (HttpContext.Current.Response.Cookies[i].Name)
{
case "FedAuth":
cookieName = "FedAuth";
break;
case "WSS_KeepSessionAuthenticated":
cookieName = "WSS_KeepSessionAuthenticated";
break;
case ".ASPXAUTH":
cookieName = ".ASPXAUTH";
break;
}
if (HttpContext.Current.Response.Cookies[cookieName] != null)
{
HttpCookie requestCookie = new HttpCookie(cookieName);
requestCookie.Secure = false;
requestCookie.Expires = DateTime.Now.AddYears(-1);
}
}
}

Hope this will help you :)

Tuesday, April 12, 2011

Signout issue from Claim enabled Site in SharePoint 2010 with adfs 2.0

While working with ADFS claim aware site in SharePoint 2010, there is one issue regarding the sigout from the portal. Even if the user sign out from the portal, the cookie still persists and when user tries to login again he will be automatically signed in without prompted for re-authentication.

We can overcome this issue by implementing below steps :

1. Signout url -->
To correctly log out, we need to browse to the ADFS sign out url like
https://your_sts_server/adfs/ls/?wa=wsignout1.0

2. Setting the FedAuth cookie to be session based -->
In order to have correct sign out behaviour (even after setting the signout url as shown in step 1) we need to make the FedAuth cookies as session based. We can achieve this by running the following powershell command :

$sts = Get-SPSecurityTokenServiceConfig
$sts.UseSessionCookies = $true
$sts.Update()
iisreset

The details for the FedAuth cookie behaviour can be found here

Hope this post will be helpful to resolve the sign out issue.

Thursday, March 3, 2011

How to set up a Custom Attribute Store in ADFS 2.0

The custom attribute store provides the possibility to get claims from different sources like different databases, text files. In order to set up a custom attribute store is required to create an assembly that contains the classes with the methods that implements its functionality. The reference for this task is provided by MSDN .In order to set up the custom attribute store you have to take into account the following points:
.NET Framework 3.5
Make sure that you use the .NET Framework 3.5, the WIF references points to the 3.5 and the engine of ADFS does not support .NET Framework 4.0 yet. So if you use an earlier version you will get an error in the Event Viewer:
Error 149: Could not load file or assembly 'CustomAttributeStore' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
Register the assembly in the GAC (Global Assembly Cache)
Make sure that the assembly has a strong name, if you don’t do it, you will get an error in the command prompt that makes reference to this issue.
You can perform this task in visual studio going to Project Name > Properties >Signing > [Checkbox] Sign the assembly. Then choose a name for the key
Register the attribute store in the ADFS 2.0 Management Console
Open the ADFS 2.0 Management Console, and in the left pane open the folder of Trust Relationships and the select the folder of Attribute Stores.

(As shown in the first image)
Then, select in the right pane the option Add Custom Attribute Store. (As shown in the second image)
Then, it will prompt a window that requests the information of the store. Provide the full name, it means:
CustomAttributeStores.AttributeStore,AttributeStore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=.
Check that the attribute store is workingCheck in the event viewer for a 149 event id. If you don’t find it, it means that the attribute is ready.