Hi
I am trying to use SPClaimsUtility for au8thenticating my user as per http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.identitymodel.spclaimsutility.authenticateformsuser.aspx .
But I get error 'Microsoft.SharePoint.IdentityModel.SPClaimsUtility' does not contain a definition for 'AuthenticateFormsUser'
in my object browser for the 'Microsoft.SharePoint.IdentityModel.dll I am not able to find the def for this static function.
What could be the possible cause?
Cheers-hemant
we could not solve above problem but I used below mentioned code for FBA authentication finally:
Authenticate returns true or false according to user is authenticated or not .
private SecurityToken GetSecurityToken(string loginName,string psswrd)
{
return SPSecurityContext.SecurityTokenForFormsAuthentication(newUri(SPContext.Current.Site.Url),"memebershipprovidername","roleprovidername",loginName,psswrd);
}
private bool Authenticate(string loginName, string psswrd)
{
bool flag = false;
SecurityToken securityToken = null;
if (loginName==null && psswrd==null)
{
throw new ArgumentException("Please provide username and password");
}
using (new SPMonitoredScope("Retrieve security token and establish session."))
{
securityToken =
this.GetSecurityToken(loginName,psswrd);
if (securityToken == null)
{
flag =
false;
}
else
{
this.EstablishSessionWithToken(securityToken);
flag =
true;
}
}
return flag;
}
internal void EstablishSessionWithToken(SecurityToken securityToken)
{
if (securityToken == null)
{
throw new ArgumentNullException("securityToken");
}
Microsoft.SharePoint.IdentityModel.
SPFederationAuthenticationModule fam = this.Context.ApplicationInstance.Modules["FederatedAuthentication"] asMicrosoft.SharePoint.IdentityModel.SPFederationAuthenticationModule;
if (fam == null)
{
throw new ArgumentException(null, "FederationAuthenticationModule");
}
//Microsoft.SharePoint.Utilities
// .SecurityContext.RunAsProcess(delegate
//{
fam.SetPrincipalAndWriteSessionToken(securityToken,
true, SPSecurityTokenServiceManager.Local.UseSessionCookies);
//});
}
this function is not available in beta version of sharepoint 2010. in licensed version dll , the reference is there.
further the alternative code mentioned above has minor change wrt licensed version of new dll:
fam.SetPrincipalAndWriteSessionToken(securityToken);
instead of
fam.SetPrincipalAndWriteSessionToken(securityToken,
true, SPSecurityTokenServiceManager.Local.UseSessionCookies);
further we may like to have our own custom sign out:-
protected void lnkBtnSignOut_Click(object sender, EventArgs e)
{
HttpContext httpCntxt = HttpContext.Current;
//Signing out
FormsAuthentication.SignOut();
//Request.Cookies.Clear();
// nullifies current context
HttpContext.Current =
null;
//refills current context
HttpContext.Current = httpCntxt;
//abandons user's session
Session.Abandon();
//Clears authentication cookies if present
if (Response.Cookies.Count > 0)
{
if(Response.Cookies["FedAuth"] != null)
Response.Cookies[
"FedAuth"].Expires = DateTime.Now.AddDays(-1);
if (Response.Cookies[".ASPXAUTH"] != null)
Response.Cookies[
".ASPXAUTH"].Expires = DateTime.Now.AddDays(-1);
}
//Redirects to login page
FormsAuthentication.RedirectToLoginPage();
}
Reply 1 by http://social.technet.microsoft.com/profile/shantha%20kumar/?ws=usercard-mini
Hi,
This error occurs because of, you didn't have the Microsoft.SharePoint.IdentityModel.dll as a reference in your project.
If you need that, Search for that dll under installation drive (C:\Windows)
For me, that dll appears under (C:\Windows\Installer\$PatchCache$\Managed\00004109410100000100000000F01FEC\14.0.4763 )
Copy that dll and paste it some where, add this dll as a reference in your project.
I hope, this will help for you.
Shantha Kumar T - MCTS
Monday, August 9, 2010
Monday, July 5, 2010
SharePoint publishing behaviour related to expiration - approved documents not set to draft sometimes
Hi
query 1:-
Ours is a publishing portal. Max time it works, but there are instances when it does not work.
There are few documens in our doc library for which expiration date is less than current date, still they moderation status is approved!!!!
Could you please suggest what may be the reason for this ?
query 2:-
to expire few pages with our code, we shedule the page to current time + 1 minute by a timer job. max times it works fine, but there are few instances for which page file keep checked out by system account infinitely.sample code:-
/// <summary>
/// Expires the page by setting the Scheduled End Date to Current Time + 1 minute
/// </summary>
/// <param name="item">SPListItem that needs to be scheduled to expire</param>
/// <param name="pagesLibraryUrl">Pages Library URL in the Site Collection</param>
private static void ExpireExistingPage(SPListItem item)
{
try
{
ScheduledItem scheduledItem = null;
if (ScheduledItem.IsScheduledItem(item))
{
scheduledItem = ScheduledItem.GetScheduledItem(item);
if (scheduledItem.ListItem.Properties["PublishingExpirationDate"] == null || DateTime.Parse(scheduledItem.ListItem.Properties["PublishingExpirationDate"].ToString()) > DateTime.Now)
{
if (CheckOutPage(item.File))
{
scheduledItem.EndDate = DateTime.Now.AddMinutes(1);
scheduledItem.ListItem.Update();
scheduledItem.Schedule();
string expireSuccessfullMsg = string.Format(EXPIRE_SUCCESSFULLY_MSG, item.ContentType.Name, item.Title);
LogInFile(expireSuccessfullMsg, CommonEnums.LogEntryType.Information);
}
}
}
}
catch (Exception ex)
{
LogInFile(ex.Message, CommonEnums.LogEntryType.Exception);
}
}
Reply1 by http://social.technet.microsoft.com/profile/aryan30/?ws=usercard-mini
Hi Hemant,
Possible reason of some pages not expiring could be that you might have been setting the wrong time in End Date field and doing System Update after that.
Can you try by updating (using System Update)the end date in past say 1 day before and check whether sharepoint expires that page.
Another reason could be some particular field within sharepoint didn't got updated during updation of time (due to some async moss event or something like that).
Can you try by removing all other code from your code except setting of end date. Do you still find some pages which didn't expired?
Seems to be some trick of asynchronus moss events which are overlapping with each other. Trying giving sleep time b/w these events and check if Checked out error gets solved.Sleep time should vary from 1-4 secs.
query 1:-
Ours is a publishing portal. Max time it works, but there are instances when it does not work.
There are few documens in our doc library for which expiration date is less than current date, still they moderation status is approved!!!!
Could you please suggest what may be the reason for this ?
query 2:-
to expire few pages with our code, we shedule the page to current time + 1 minute by a timer job. max times it works fine, but there are few instances for which page file keep checked out by system account infinitely.sample code:-
/// <summary>
/// Expires the page by setting the Scheduled End Date to Current Time + 1 minute
/// </summary>
/// <param name="item">SPListItem that needs to be scheduled to expire</param>
/// <param name="pagesLibraryUrl">Pages Library URL in the Site Collection</param>
private static void ExpireExistingPage(SPListItem item)
{
try
{
ScheduledItem scheduledItem = null;
if (ScheduledItem.IsScheduledItem(item))
{
scheduledItem = ScheduledItem.GetScheduledItem(item);
if (scheduledItem.ListItem.Properties["PublishingExpirationDate"] == null || DateTime.Parse(scheduledItem.ListItem.Properties["PublishingExpirationDate"].ToString()) > DateTime.Now)
{
if (CheckOutPage(item.File))
{
scheduledItem.EndDate = DateTime.Now.AddMinutes(1);
scheduledItem.ListItem.Update();
scheduledItem.Schedule();
string expireSuccessfullMsg = string.Format(EXPIRE_SUCCESSFULLY_MSG, item.ContentType.Name, item.Title);
LogInFile(expireSuccessfullMsg, CommonEnums.LogEntryType.Information);
}
}
}
}
catch (Exception ex)
{
LogInFile(ex.Message, CommonEnums.LogEntryType.Exception);
}
}
Reply1 by http://social.technet.microsoft.com/profile/aryan30/?ws=usercard-mini
Hi Hemant,
Possible reason of some pages not expiring could be that you might have been setting the wrong time in End Date field and doing System Update after that.
Can you try by updating (using System Update)the end date in past say 1 day before and check whether sharepoint expires that page.
Another reason could be some particular field within sharepoint didn't got updated during updation of time (due to some async moss event or something like that).
Can you try by removing all other code from your code except setting of end date. Do you still find some pages which didn't expired?
Seems to be some trick of asynchronus moss events which are overlapping with each other. Trying giving sleep time b/w these events and check if Checked out error gets solved.Sleep time should vary from 1-4 secs.
Monday, June 21, 2010
Microsoft.SharePoint.WebPartPages.ToolPart , page needs a refresh to apply changes back to web part
Hi
I have a problem with custom tool part. The page needs a refresh before the changes are actually visible in the web part.
Either user have to hit apply then OK in Tool Part, or after directly hitting Ok he needs to refresh the page.
Seems to be create child control of web part being called before applychanges of tool part.
Any pointers ?
Reply 1
This is a common issue with custom properties in SharePoint webpart.
Just try call the method that modifies your custom property in the PreRender event.
For more check these links:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/6445d939-05da-4ce9-a2cf-3e9fe28b98ee
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/5b85a5dc-37aa-49d7-a741-d40c7bd2bd0c
BR, PM
Reply 2
Hi
Thanks for you guidance,
I had to use a property from custom tool part to a script in the usercontrol( inside our web part).
calling my RegisterStartUpScript inside OnPreRender in user control solved my problem.
Thanks
Reply 3
Awesome news!!
BR, PM
I have a problem with custom tool part. The page needs a refresh before the changes are actually visible in the web part.
Either user have to hit apply then OK in Tool Part, or after directly hitting Ok he needs to refresh the page.
Seems to be create child control of web part being called before applychanges of tool part.
Any pointers ?
Reply 1
This is a common issue with custom properties in SharePoint webpart.
Just try call the method that modifies your custom property in the PreRender event.
For more check these links:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/6445d939-05da-4ce9-a2cf-3e9fe28b98ee
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/5b85a5dc-37aa-49d7-a741-d40c7bd2bd0c
BR, PM
Reply 2
Hi
Thanks for you guidance,
I had to use a property from custom tool part to a script in the usercontrol( inside our web part).
calling my RegisterStartUpScript inside OnPreRender in user control solved my problem.
Thanks
Reply 3
Awesome news!!
BR, PM
Friday, June 11, 2010
How can i find the currently login user of extended web application through ASP.Net code?
i have created a web application http://spserver:19578 and then i extend a web application http://spserver:19579 from it.
Now i am currently login as ali to http://spserver:19579. i write the following code
SPSite sitecollection = new SPSite("http://spserver:19579");
SPWeb web = sitecollection.AllWebs["/"];
SPUser user = web.CurrentUser;
lblUser.Text = user.Name;
but it returns System Account. and when i used LoginName instead of Name then it returns SharePoint\system.
Note: I am using form based authentication in http://spserver:19579 and windows authentication in http://spserver:19578.
Reply 1
hey try using SPContext .Current .Web .CurrentUser
Now i am currently login as ali to http://spserver:19579. i write the following code
SPSite sitecollection = new SPSite("http://spserver:19579");
SPWeb web = sitecollection.AllWebs["/"];
SPUser user = web.CurrentUser;
lblUser.Text = user.Name;
but it returns System Account. and when i used LoginName instead of Name then it returns SharePoint\system.
Note: I am using form based authentication in http://spserver:19579 and windows authentication in http://spserver:19578.
Reply 1
hey try using SPContext .Current .Web .CurrentUser
thumbnail word, pdf, excel etc in wss 3.0
does anyone know of a way to create thumbnails for documents in sharepoint services? what i would like to happen is provide a new column that would allow the end user to hover a icon that would provide a 200X200 popup thumbnail. this would give my endusers a quick look at the doc with out having to open.
i tried this link but can't get it to work. it's date for 2005
http://msdn.microsoft.com/en-us/library/aa289172(VS.71).aspx
thanks for any help
reply 1
use aspose pdf kit
i tried this link but can't get it to work. it's date for 2005
http://msdn.microsoft.com/en-us/library/aa289172(VS.71).aspx
thanks for any help
reply 1
use aspose pdf kit
Friday, March 19, 2010
State Managements in .NET
State Management Techniques in ASP.NET
Developer is forced to implement various state management techniques when developing applications which provide customized content and which “remembers” the user.Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let’s start with exploring client side state management options.
Client side State management Options:
ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let’s discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.
Cookie:
A cookie is a small piece of text stored on user’s computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Let’s see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = “Dear” + Request.Cookies["UserId"].Value + “, Welcome to our website!”;
else
lbMessage.text = “Guest,welcome to our website!”;
If you want to store client’s information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
* Simplicity
Disadvantages:
* Cookies can be disabled on user browsers
* Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
* Inappropriate for sensitive data
Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It’s just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
//to assigns a value to Hidden field
Hidden1.Value=”Create hidden fields”;
//to retrieves a value
string str=Hidden1.Value;
Advantages:
* Simple to implement for a page specific data
* Can store small amount of data so they take less size.
Disadvantages:
* Inappropriate for sensitive data
* Hidden field values can be intercepted(clearly visible) when passed over a network
View State:
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don’t need state. (Data grid usually doesn’t need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 – encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;
//Reading items from ViewState
Response.Write(ViewState["myviewstate"]);
Advantages:
* Simple for page level data
* Encrypted
* Can be set at the control level
Disadvantages:
* Overhead in encoding View State values
* Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let’s assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
* Simple to Implement
Disadvantages:
* Human Readable
* Client browser limit on URL length
* Cross paging functionality makes it redundant
* Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control’s contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage
of sessions object for state management can create load on server causing performance degradation
Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It’s a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]=”mydata”;
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session’s data on web server in different ways. Session state can be configured using the section in the application’s web.config file.
Configuration information:
cookieless = <”true” | “false”>
timeout =
sqlconnectionstring =
server =
port =
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user’s session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes
SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.
Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.
Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
* In process mode (in-memory)- State information is stored in memory of web server
* Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
* Database mode – session state is maintained on a SQL Server database.
In process mode:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
sqlConnectionString=”data source=server;user id=freelance;password=freelance”
cookieless=”false” timeout=”20″ />
Advantages:
* Fastest mode
* Simple configuration
Disadvantages:
* Session data will be lost if the worker process or application domain recycles
* Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:
StateConnectionString=”tcpip=127.0.0.1:42424″
sqlConnectionString=”data source=127.0.0.1;user id=freelance; password=freelance”
cookieless=”false” timeout=”20″/>
Advantages:
* Supports web farm and web garden configuration
* Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
* Out-of-process mode provides slower access compared to In process
* Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework’s installed directory
C:\\microsoft.net\framework\. Running this utility will create a database which will manage the session state.
Configuration Information:
sqlConnectionString=”data source=server;user id=freelance;password=freelance”
cookieless=”false” timeout=”20″ />
Advantages:
* Supports web farm and web garden configuration
* Session state is persisted across application domain recycles and even IIS restarts when session is maintained on different server.
Disadvantages:
* Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.
Ref : http://dhondiyals.wordpress.com/2010/03/19/state-managements-in-net/
Tuesday, November 24, 2009
query on datagrid
Hi
I want to query a datagrid on the page. possibly using Linq.
My purpose is to extract data of a column into an IList:-
currently doing like:-
for each(raddatagriditem item in radgrid.items)
{
lst.add(item["uniquecolumnname"].text);
}
but Due to performance concerns, I want to use Linq directly to populate "uniquecolumnname" string values to another Ilist<string>.
please suggest how to query a datagrid item collection directly.
Cheers-Hemant
+919555798309
email removed
Reply 1
Hi hemantrhtk,
Do you mean get all the values of “uniquecolumnname” from DataGridView (You have said Linq, so it might be DataGridView not DataGrid, right?)?
If my understanding is correct, you can use this code to get value
foreach (DataGridViewRow dgvRow in myDataGridView1.Rows)
{
lst.Add(dgvRow.Cells["uniquecolumnname"].Value);
}
If I misunderstood you, please feel free to tell me.
Sincerely,
Kira Qian
Reply 2
Hi,
You can also use DataTable.Select(filterExpression) instead.
With best regards, Yasser Zamani
I want to query a datagrid on the page. possibly using Linq.
My purpose is to extract data of a column into an IList:-
currently doing like:-
for each(raddatagriditem item in radgrid.items)
{
lst.add(item["uniquecolumnname"].text);
}
but Due to performance concerns, I want to use Linq directly to populate "uniquecolumnname" string values to another Ilist<string>.
please suggest how to query a datagrid item collection directly.
Cheers-Hemant
+919555798309
email removed
Reply 1
Hi hemantrhtk,
Do you mean get all the values of “uniquecolumnname” from DataGridView (You have said Linq, so it might be DataGridView not DataGrid, right?)?
If my understanding is correct, you can use this code to get value
foreach (DataGridViewRow dgvRow in myDataGridView1.Rows)
{
lst.Add(dgvRow.Cells["uniquecolumnname"].Value);
}
If I misunderstood you, please feel free to tell me.
Sincerely,
Kira Qian
Reply 2
Hi,
You can also use DataTable.Select(filterExpression) instead.
With best regards, Yasser Zamani
Subscribe to:
Posts (Atom)