Thursday, June 28, 2012

Conditional Statement example in SharePoint workflow.

In SharePoint workflow, when we are using the if/else activities, the if/ else methods contains Event argument called ConditionalEventArgs.
if you set e.Result=true, then if block will executes,
if you set e.Result=false, then else block will executes.
private void IfMethod(object sender, ConditionalEventArgs e)
{
if (isTrue)
e.Result = true;
else
e.Result = false;
}
private void ElseMethod(object sender, ConditionalEventArgs e)
{
if (!isTrue)
e.Result = true;
else
e.Result = false;
}
depending on the boolean variable “isTrue”, the if/else blocks will executes…
In the above case, i am setting “isTrue” variable depending on my logic, before calling if/else statements.
For while activity also, same logic applies.
if you set e.Result=true, it will iterate until you set e.Result=false.

To access html control without runat=”server” in C# code.

In ASP.NET coding, I don't think it is needed to create or declare only ASP.NET server-side controls. Some cases, to make our page more efficient and faster we can write HTML controls by adding runat="server" to access them on server side code [C#].

But, there are some special requirements where we need to create HTML controls dynamically in c# and add them in a string and write the string to a page. And whenever some event raised like button click event, on server side code, we need to retrieve the values of those HTML controls. As it is not declared as runat="server" on the page, we can't take the values very simple. In that type of scenarios, this solution works. Please follow the solution below to get the values of the HTML controls which doesn't have runat="server" attribute defined.

Example:
HTML declaration:
<input type="text" name="txtName" />

C# Code:
string strValue = Page.Request.Form["name of the control"].ToString();

Note:
To get the values in server side code of HTML control, we need to follow below points.
  • The tag should have an attribute called NAME. Because it is used as key in form[].
  • The form method should be of type POST.

How to write your own functions in JQuery

This post is also part of learning jquery. When I was new to learn Jquery, I was facing lot of problems in creating my own functions in JQuery. Because I want to create one function at one place and use it everywhere by calling directly JqueryObject.function(). After got some experience then I started writing my own Jquery functions and using them in my projects.

Syntax of how we can create a new function is as below.
jQuery.fn.myownfunction = function() {
var currentObject = $(this) ; //currentObject holds the current object.
};

Example function for centering an element is shown below.

jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", ( $(window).height() - this.height() ) / $(window).scrollTop() + "px");
this.css("left", ( $(window).width() - this.width() ) / $(window).scrollLeft() + "px");
return this;
}

How to call it?
$("#popupDiv").center();

Access IFrame content using Jquery

This is really helpful post for so many people who are using frames in their pages and want to access content inside it from main[parent] page. I really faced so many problems to read the data inside a frame and use it on the current page. So, it's simple and nice to know this tip for JQuery lovers.
HTML:
In Parent file, for example iFrame is declared as below.
<iframe id="uploadIFrame" scrolling="no" frameborder="0" hidefocus="true" style="text-align: center;vertical-align: top; border-style: none; margin: 0px; width: 100%; height: 60px;" src="IFrameExample.htm"></iframe>
In IFrameExample.htm, assume there is a hidden control as shown below.
<input type="hidden" id="hiddenExample" name="hiddenExample" />
So, now I will tell you how to set the "hiddenExample" hidden control value from the parent file. Because, we can’t directly access it through java script/HTML. We need to use below logic to get it working.
var $currentIFrame = $('#uploadIFrame');
$currentIFrame.contents().find("body #hiddenExample").val("Value from parent file.");

That's it!!! You are done with assigning some value to hidden variable inside IFrame. And in that iFrame you can access this hidden control on server side[C# or VB etc..] too. For it, you need to follow my other post. Very simple, but hard to find. Below is the nice explanation of above code. [How it will work.]
So, we are using Jquery, you know how to define JQuery object and use it in DOM. I created a variable[Object] currentIFrame which holds the whole IFrame reference. And in the second line, I am using the contents() method, which actually returns me all the HTML code of the frame. So, as we already know, find is the method we need to use to find out any element in a given scope/context. So, it tries to find out the occurrence of given criteria in current frame. I think you understood well how it works. If you are having multiple IFrames then you can define class for <iframe> instead of id and you can catch it in Jquery by using "." operator instead of "#"

ASP.NET Checkboxlist get values in client side [JQuery]

I know, this is the question most of the ASP.NET developers will ask or look for an answer on why there is no value attribute set for check box when it generates from the ASP.NET checkbox list? Where as the Radio button list, Drop down list and other controls has this value attribute set when you set the data source for them. But why there is no value attribute set for check box list control. Below is the nice explanation and will help you to understand the concept well.
If we assign some data source to the check box list control, then the HTML output is with two controls for each check box as input control with type checkbox and another is label with the text. So, This is the problem. How to get the value of the checkbox in client side using some javascript library? Here we need to think a way of how to set a attribute which holds the value for each checkbox and how to get it.
Below is the solution I found. In your C# code, after you bind the data source for the checkbox list, then need to add extra piece of code below to get our problem solved.
C# code:


  1. foreach (ListItem li in checkBoxList.Items)  
  2. li.Attributes.Add("someValue", li.Value);  
So, What happening here is, I am just adding extra attribute "someValue" for each check box in a check box list[checkBoxList] and looping through them and assign the actual value to that custom attribute. So that HTML for each checkbox on the page will render like this.
HTML rendered output:

  1. <span somevalue="8"><input id="ctl00_cpB_checkBoxList_0" name="ctl00$cpB$checkBoxList$0" type="checkbox"><label for="ctl00_cpB_checkBoxList_0">Testing</label></span>  
If you observe, there is an extra parent control for each check box control named <SPAN> with the attribute we have set in c# code for each checkbox. Now you have some value set with each checkbox and you can get it on client side easily. [There is no change in C# code accessing values.]
How to access the values on client side?
I am using JQuery, so I will give an example of how to get the values using the JQuery.
To get all checkboxes which are checked under a checkbox list are accessed as follows.
JQuery code:

  1. $("#<%=checkBoxList.ClientID %> input[type=checkbox]:checked").each(function() {  
  2. var currentValue= $(this).parent().attr('someValue');  
  3. if(currentValue != '')  
  4. values += currentValue + ",";  
  5. });  
So, values is the string which holds all the selected checkbox values in a check box list which are selected with comma separated

Check/Uncheck all checkboxes in Jquery

This is simple, but want to show you how to get it working in simple and efficient way. Usually we have a parent check box and then some child checkboxes. Depends on the parent check box selection, all the child checkboxes should behave exactly same. So, below is the Jquery function which will do that magic for you.

  1. function CheckUncheckAllCheckBoxes(objID, checkedValue) {  
  2. if (objID == null || objID == undefined )  
  3. return;  
  4.   
  5. $(objID + " input[type=checkbox]").each(function() {  
  6. this.checked = checkedValue;  
  7. });  
  8. }  
If you observe, I am using two parameters for the function named objID and checkedValue. objID is the parameter for knowing which checkbox group or list we need to check or uncheck? Like, on a page we may have many checkboxes and groups or lists. So, we need a way to find out which group or list we need to check or uncheck? For this reason I added a parameter for the function to check only the checkboxes under that ID or Class. Possible values for the objID are
  1. #parent Control ID of the element which has the check boxes declared. Example: #ageList
  2. .parent control class of the element under which all the check boxes defined. Example: .edit
And second parameter, it is for passing the parent selected check box value. If it is ON, then logic will loop through and set the each checkbox to checked otherwise unchecked.

Usage - How to call this method:
Code for check/Uncheck all in ASP.NET

  1. $("#<%=cbAllStates.ClientID %>").click(function() {  
  2.    CheckUncheckAllCheckBoxes("#<%=cblState.ClientID %>"this.checked);  
  3. });  
Note: cblAllStates is the parent ASP.NET check box which is controlling child. cblState is the asp.net checkboxlist and in our terms child check boxes.

Code for Check/Uncheck all in HTML:

  1. $("#cbAllStates").click(function() {  
  2.    CheckUncheckAllCheckBoxes("#divChilds"this.checked);  
  3. });  
Note: cbAllStates is the parent check box control and divChilds is the division <DIV< tag which has all the child check boxes present in it.

**UPDATED** 06/22/2010
This is the small update for the check/uncheck the all check box depends on the child check box selection. If any of the child check box is unchecked or the all child check boxes are selected then the all check box will toggle depends on it. Below is the work around.

Example:
Code for  Toggling the all check box depends on the child check boxes:

  1. function ToggleSelectAllCheckBox(allCheckBox, checkedValue, obj) {  
  2.     if (allCheckBox == null || allCheckBox == undefined)  
  3.         return;  
  4.     if (!checkedValue)   
  5.         $(allCheckBox).attr("checked"false);  
  6.     else {  
  7.         var areAllChecked = true;  
  8.         $(obj + " input[type=checkbox]").each(function() {  
  9.             if (!this.checked) {  
  10.                 areAllChecked = false;                  
  11.             }  
  12.         });  
  13.         $(allCheckBox).attr("checked", areAllChecked);  
  14.     }  
  15. }  
In the above function param1 is the all child check boxes, param2 is the current child check box selection and param3 is the all check box selector.

How to use:
ASP.NET Checkbox list:

  1. $("#<%=cblAge.ClientID %> input[type=checkbox]").click(function() {  
  2.                 ToggleSelectAllCheckBox("#<%=cbAllAges.ClientID %>"this.checked, "#<%=cblAge.ClientID %>");  
  3.  });  
Note: cblAges is the check box list id and the cblAge is the all check box for the age group. So, the click event is for the all check boxes inside the check box list.

HTML Check boxes:

  1. $(".ageGroup  input[type=checkbox]").click(function() {  
  2.                 ToggleSelectAllCheckBox(".ageGroup"this.checked,  "#allAgeCheckbox");  
  3.  });  
Note: ".ageGroup" is the div or some parent element which holds all the checkboxes in HTML. "#allAgeCheckbox" is the id of the all checkbox for that age group.

Jquery intellisense in Visual Studio 2008

This is a small tip I want to tell to my readers. I know, most of the dev's think like if Jquery intellisense is available in visual studio then that will be good :). So, this post will help you to solve that problem.
Below are the steps we need to follow to get the intellisense working in Visual studio 2008. Before start with the steps I will tell you how it helps us.

  • Learn more and implement more: Because of having this intellisense support in vs 2008, we can solve so many problems and can implement so much in JQuery. It will be very difficult for everyone to remember all the functions and members for the Jquery objects. So, This will give more support to learn more and implement more.
  • Fast and rapid development of the client side scripting. Until you don't know what methods and properties it has you can't write program fast and efficient.
  • Time saving: Complete documentation for all Jquery objects, methods and properties. The inline description is more than enough to understand it well. Till these days, every time need to go to Jquery documentation site and need to search for what we need and read about them. But, now everything is in visual studio. Big time saving here.
  • Load time: I know, at this point you may think how it will effect load time by adding the Jquery documentation file to page. By adding the vsdoc file [~188Kb] to the page won't increase the page size or won't effect the load time at all. We will refer the documentation file while coding or at development time only but it won't render on the client side. How? I will explain it later in this post.
Requirements:
  • Install Visual Studio SP1.
  • We need to download the vsdoc file from here.
  • Install the hotfix for visual studio before proceed.
Steps to refer the documentation file(vsdoc):

  • Refer the documentation file to js file: If you need jquery intellisense on the js file then you need to write the below declaration as the first line of your js file.
/// <reference path="jquery-1.3.2-vsdoc.js" />
Note: the path value is the actual path of the vsdoc file.
  • Refer documentation file in ASPX page: This is what we need most of the times for writing inline scripting on the page. So, add below code to the <head> tag of the page for JQuery intellisense.
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<% if (false) { %>
<script src="jquery-1.3.2.min-vsdoc.js" type="text/javascript"></script>
<% } %>

Note: The Jquery file reference should always be the top of the Jquery documentation file reference. And if you install Visual studio SP1 and the hot fix then there is no need to place the complete IF block from the above code. And the vsdoc file should be in the same folder where the jquery file is.
Note: The short cut for the update intellisense in Visual Studio is Ctrl + Shift + J. So, once reference added please done it once to update the intellisense.

How, Jquery intellisense work in Visual Studio?
It's simple. What JQuery –vsdoc.js file contains? Nothing but the description text for all the defined methods and properties. So, when you refer the vsdoc file in js file, it will load that file into memory and set the meta data for the Jquery methods and properties. If you refer the vsdoc file in ASPX pages, then it will set the metadata as follows.
First, Visual studio will look for the JQuery file, example jquery-1.3.2.js. And then it will look for the file which has the format jquery-1.3.2-vsdoc.js. If it matches then only visual studio loads the meta data and intellisense will work, otherwise not. So, your jquery file and documentation file should be having the same name with –vsdoc at end of the documentation file name.
Note: Jquery file: jquery-1.3.2.js and Jquery visual studio documentation file name: jquery-1.3.2-vsdoc.js
Lastly, I want to explain about the load time from above mentioned bullet. If you observe the code I have given, it has some server-side code integrated in it. I wrote if condition which always fails to execute the code inside the if block because I am passing false always to it. So, it never runs the code inside the if block and nothing loads on the client side related to vsdoc file. At the time of development, server-side code won't run but all the meta data will load because there is a script tag on the page. So, at development time, the vsdoc file will load, but when you browse the page, vsdoc file won’t render.

How to detect tab key is pressed in javascript?

document.onkeydown = keydown;

function keydown(event) {
        var code;
        var e;
        if (document.all) {
            if (!event) {
                var e = window.event;
                code = e.keyCode;
            }
        }
        else if (event.which) {
        code = event.which;
        e = event;
        }
        if (code == 9) {//Write some logic
        }
    }

Wednesday, June 27, 2012

How to detect clicked on outside of a particular div?

document.onclick = clickEvent;
function clickEvent(e) {
    var targ;
    if (!e) var e = window.event;

    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;

    //if (targ.nodeType == 3) // defeat Safari bug

        if (targ.nodeName != "HTML") {
        while (targ.nodeName != "BODY") {
            if (targ.id && targ.id == 'divGrid') {
                return false;
            } else {
                targ = targ.parentNode;
            }
        }
    }    //This is the place where you need to write code when you click outside of the div.
}

Request format is unrecognized for URL unexpectedly ending in methodname

This is the exception I am getting when I try to access web services from my web site. I just created a web service and tried to access the service from the browser using the get request. But I got the invalid operation exception. See complete exception details below:
System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/MethodName'
So, Before we will go to know the solution for it, I want to explain the reason behind this.
A .NET web service supports three protocols named HTTPGET, HTTPPOST and SOAP. When .NET released I mean, ASP.NET v1.0 all these three protocols enabled by default. So, any requests which made from the browser which belongs to a web service will be responded without any issues. But when come to ASP.NET 1.1 version the protocols HTTPGET and HTTPPOST are disabled by default. The only reason is SECURITY issue. So until you explicitly enable them no web service request will be processed if you call them in the format domain/webservice.asmx/methodname [Get/Post].
But, where as if you call direct web service from browser using SOAP request that will work and will give result what you need. But, if you make any GET or POST request then only the problem will come. 
RESOLUTION:
To enable these protocols in the application level simply we need to change the application config file. Web.config. Add below lines to the web.config to enable these protocols.
 
<configuration>
     <system.web> 
    <webservices>      
  <protocols>       
  <add name="HttpGet"></add>  
           <add name="HttpPost"></add>     
     </protocols>     
 </webservices>     
 </system.web>
  </configuration>  
So, this webservices tag will go inside the <system.web> namespace. With the above lines, the protocols enabled and they listen the request and respond accordingly for that application. Sometimes you may need to enable these protocols in system level. I mean to all applications in the server should have these protocols enabled. Then below is the solution for it.
Find machine.config file and open it in nice editor like visual studio. Before do any changes please take a backup of the file. Now find the protocols section and add the below lines if they are not already there.
 
<protocols>   
<add name="HttpSoap"></add> 
 <add name="HttpPost"></add>   
<add name="HttpGet"></add> 
 </protocols> 

How to get the current row in the grid view command event

This is what I faced a small problem when using GridView. I have a LinkButton element in the gridview and my goal is when user clicks on the button, I need to raise the grid view command event and in that event, I need to get the row values. But, the questions is how to get the current row in the grid view command event?  Below is the solution for it.
GridViewRow row = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
Note: Remember LinkButton class I used in the above code is assuming that the command event raised when clicked on the LinkButton control. If your requirement is not linkbutton then please place the corresponding control name.
Most of the times and most of the developers never use the property available to each and every object named NamingContainer. But, there are lot of advantages with this property. Especially when we write and render controls to page dynamically then this property will help a lot. And there are many properties which will help us to solve so many problems. Use the intellisense and try to know most of the properties available for a .NET control.

How to get or access master page in user control

My requirement is I want to get the reference to the master page and access the public property of a master page in user control. As we know that master page is also inherited from the user control, I can say this is simple and we can easily get the reference.
I am using master page in my web application and all pages are using that master page. And there are user controls in the application and my requirement is how to access the master page property inside a user control. Below is the solution how I resolved the problem.
In user control ASCX file declare the below line to establish the reference to the master page.
<%@ Reference Control="~/DefaultMaster.Master" %>
IN the ASCX.CS file, we need to fill the master page object to access it's properties. For this,
  • Declare a master page class variable as the user control class variable as shown below.
DefaultMaster masterpage = null;
NOTE: Remember the DefaultMaster is the class of DefaultMaster.master class.
  • In Page_Load event of user control, fill the masterpage object as shown.
masterpage = this.Page.Master as DefaultMaster;
Now, you are all set to use master page object and access everything inside it. If you observed, everything is simple object model. I am just accessing the objects

Access web.config in SharePoint timer job

In SharePoint customization we have the requirements to write custom code for web parts, timer jobs etc. In this post I want to tell you some interesting things in SharePoint. I have written some timer jobs to deploy into my SharePoint server to match some requirements or to solve some problems.
My requirement is, I want to access the web application or web site configuration [web.config] file in the SharePoint timer job. But, the limitations in SharePoint stops me to access the configuration files in timer job. Below are the problems I faced.
  • SharePoint timer job is running in different process named OWSTIMER.EXE.
  • SharePoint web application or site will run with the help of process W3WP.EXE.
  • So, the application configuration file is associated with the W3WP.EXE, so there is no way to access the web.config file in the owstimer.exe process at all. The context is completely different and out of domain. So, we need to call or access the web.config file explicitly in timer job. How to?
  • Remember, always C# is completely object oriented and you can access everything through objects.
  • Usually the timer job installed as a feature. And all the logic of the timer job will go inside the Execute() method. So, write below statements in that method and access the complete web.config file. Below is the example of accessing appsettings. 
SPWebApplication webApplication = this.Parent as SPWebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);
String appValue = config.AppSettings.Settings["appSettingKey"].Value;

WebConfigurationManager is the class which is in the namespace Systen.Web.Configuration. This way, you can access the config settings from a web.config of a SharePoint web site

SharePoint timer job and settings or configuration file

I got a question that what is the case when a SharePoint timer job needs a configuration file? Because, I really need the configuration settings for a timer job which I deployed. Because I got a requirement where I need to use the web service in a timer job and it needs the httpBindings and the endpoints. I can't place them in web.config of the web site as I can't access it here. But, I can access the web.config file as I discussed it in my previous post. I can get all the bindings and endpoints from web.config and create a c# bindngs object. And for the web service I passed the binding and that didn't solve the problem. Somehow, I got the below exception.
WSE012: The input was not a valid SOAP message because the following information is missing: action.
So, I started thinking in different ways and out of box. Below is the way how I approached towards the solution.
  • Everyone knows that all the timer job runs with the help of the OWSTIMER.EXE.
  • If you take a look at the console application, c# project and if you add the app.config file to the project then in your bin folder, you will see two files like if it is c# project then projectname.dll and projectname.dll.config and if it is console application then projectname.exe and projectname.exe.config.
  • So, what you understood from it? for dll or exe there is associated config file if that project contains app.config file.
  • What will happens when we use the dll or try to run the exe, the related config file also loads into memory and you can use the config file in the dll or exe.
  • There my thought starts and I want to repeat the same concept for the OWSTIMER.EXE too. 
  • Find the location of where OWSTIMER.EXE is reside in. Generally, the location is at "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN\OWSTIMER.EXE". So, go to that location and create a file named OWSTIMER.EXE.CONFIG.
  • Open it in notepad and place all the settings code in it. Save it.
  • Now, it's time to restart the timer service. So, go to services and find SharePoint Timer Service. And restart it.
  • Now, run the timer service and you see everything is running successful. I mean all the settings will be loaded and run.
Note: Try to include all the settings in the config file within these tags.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

IIS 7 – Managed pipeline mode – Global.asax redirect not working

I installed Windows 7 and I really like it. I migrated all my applications from my old machine to new. And my old machine is running WS 2003 [iis 6] and new machine is Windows 7 [IIS 7]. In all applications everything ran successful except one. I implemented exception handling in my application. I have Global.asax page and in the Application_Error event, I log the exception details and redirecting the user to the error page. Whenever there is an exception in my application the page never redirect to the error page, it stays there in the same page with exception details on the screen.
The same code ran very successful on my old server and in Windows 7 it's not. I just started thinking what could be the issue. The analysis went in this way. Code not changed, DB not changed and the only part changed is the IIS. Windows 7 has IIS7. So, The problem would be either the isapi dll or the application pool. So, started researching on those and found interesting points.
In IIS 7, application pool has a separate feature named "Managed pipeline mode". This will tell the pool the pipeline mode. [which is of type sint32 in c# and the possible values for it are 0 and 1.]
  • 0 is managed pipeline runs in integration mode.
  • 1 is managed pipeline runs in classic or ISAPI mode. [IIS 6].
In Classic mode, managed application events are executed by using ISAPI. In Integrated mode, ASP.NET request processing integrates directly into the IIS 7 request-processing pipeline. Integrated mode enables you to configure managed modules for Web sites that are developed with unmanaged code.
So, to work your logic correct, go to your site and see under what application pool your site running. Now, go to that application pool, properties and change the pipeline mode to classic mode. Now, you see everything works fine and the page starts redirecting to error page when any exception in your application.
For more details: http://msdn.microsoft.com/en-us/library/microsoft.web.administration.managedpipelinemode.aspx

Open all anchor links in new window

How many ways are there to implement this?
1. Make all links in web page open in new window.
2. Only some part of the web page links will be opened in new window.

I have two options: Number 1,
Open all links on the web page in new window: Default HTML supports this.

Add this line in the <head> tag of your HTML:  <base target='_blank' />

If I make all links needs to be opened in new window then home link, navigation links, search everything will opened in new window and it will frustrate user that whatever you click on the link it will open in new window. Dozens of windows in user system if you click 10-12 links. Not a good idea.

Option 2: Only specific region anchor links open in new window. This looks promising and good. But, how to. For example, in my blog, I like to open the content links only in new window.
I have a parent for all content inside a div with id='content'. Now, my goal is to add some logic to open all links in new window which are under content only.
 <script type='text/javascript'>  
 //<![CDATA[      
window.onload = function ()
 {   
    var links = document.getElementById('content').getElementsByTagName('a');         for (var i = 0; i < links.length; i++) 
          
 links[i].setAttribute('target''_blank'); 
         }     
 }
  //]]> 
 </script>

If you are in Jquery , then this as,
$('#content a[href^="http://"]').attr("target", "_blank");

How to change the values of 'CreatedBy' and 'ModifiedBy' fields in SharePoint list

Each SharePoint list by default has these fields 'Created By' and 'Modified By'. The type of these fields is "Person or Group".
Whenever a new list item is added, the value of the 'CreatedBy' column is automatically set to the Login Name of current user.  
And whenever a list item is modified, the value of the 'ModifiedBy' column is automatically set to the Login Name of current user.   
 
Note: If you try to modify or update the 'CreatedBy and 'ModifiedBy' Fields, you may get the below error like   "Invalid data has been used to update the list item. The field you are trying to update may be read only". 

 
Now the question is "why the hell one needs to modify the values of these fields?” The answer can be found in the "Advanced Settings" section of a SharePoint list. One can see, there is a 'Edit own items' permission which means a user can edit all list items which he/she has created, that is very nice and useful feature. But the problem is that it is linked with the 'Created By' field. So if I will create a list item then my login name will be stored in the "Created By" field and only I can modify this list item. But if there is a requirement to modify this list item by some other user then how I can achieve that. To achieve this, one need to modify the value of "Created By" field and set it to the login name of that user. But How? 
I was just stuck with this problem, but finally found a solution. The values of 'Created By' and 'Modified By' fields can be modified programmatically. Here is a code snippet to achieve this: 

Method1:
using (SPSite site = new SPSite("SharepointSiteURL"))
  using (SPWeb web = site.OpenWeb())
  {
    web.AllowUnsafeUpdates = true;
    SPList list = web.Lists["ListName"];
    foreach (SPListItem item in list.Items)
    {
      SPUser user = web.EnsureUser("User'sLoginName");
      //In the "Created By" and " Modified By" fields values are stored in this format      "ID;#LoginName", so create the same format.
 
      string userValue = user.ID + ";#" + user.Name;
      item["Author"] = userValue ;
       //InternalName of "Created By" field is "Author"
      item["Editor"]=userValue ; 
      //InternalName of "Modified By" field is "Editor"
      item.Update(); 
    }
    list.Update();
}
Method2:

using (SPSite site = new SPSite("SharepointSiteURL"))
  using (SPWeb web = site.OpenWeb())
  {
      web.AllowUnsafeUpdates = true;
      SPList list = web.Lists["ListName"];
      SPListitemCollection itemcollection=list.items;
      foreach (SPListItem item in itemcollection)
      {
         SPFieldUserValue user1=new SPFieldUserValue(web, web.CurrentUser.ID,
                                      web.CurrentUser.LoginName);
        Listitem[“Author”]=user1;
        Listitem[“Editor”]=user1;
     }
  }
}

Tuesday, June 26, 2012

Eventreceiver Deploying Issue in Sharepoint 2010

Error occurred in deployment step 'Activate Features': Operation is not valid due to the current state of the object in Event Reciever

Cause:Define the variables Globally so remove the global variables then Deployment will not interrupt.