Saturday, November 27, 2010

Response.Redirect with try, catch, and finally Blocks and using Statements

Response.Redirect with try, catch, and finally Blocks and using Statements

The finally block executes after calls to Response.Redirect in the try block. Response.Redirect ultimately generates a ThreadAbortException exception. When this exception is raised, the runtime executes all finally blocks before ending the thread. However, because the finally block can do an unbounded computation or cancel the ThreadAbortException, the thread will not necessarily end. Therefore, before any redirection or transfer of processing can occur, you must dispose the objects. If your code must redirect, implement it in a way similar to the following code example.

String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;

try
{
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);

str = oSPWeb.Title;
if(bDoRedirection)
{
if (oSPWeb != null)
oSPWeb.Dispose();

if (oSPSite != null)
oSPSite.Dispose();

Response.Redirect("newpage.aspx");
}
}
catch(Exception e)
{
}
finally
{
if (oSPWeb != null)
oSPWeb.Dispose();

if (oSPSite != null)
oSPSite.Dispose();
}


Because a using statement instructs the run time to create a finally block,
whenever you use Response.Redirect within a using statement,
ensure that objects are disposed properly. The following code example shows how you can do this.

using (SPSite oSPSite = new SPSite("http://server"))
using (SPWeb oSPWeb = oSPSite.OpenWeb(..))
{
if (bDoRedirection)
Response.Redirect("newpage.aspx");
}


Thursday, November 25, 2010

How do I create shared assemblies



How do I create shared assemblies ?


How to install an assembly in the Global Assembly Cache in Visual Basic .NET or in Visual Basic 2005?

A shared assembly is one that is used by multiple applications on the machine. A shared assembly must have a name that is globally unique. The .NET Framework supports these naming requirements through a technique called strong names.

Shared assemblies must have a "strong name" consisting of the name of the assembly, the version, a 64 bit hash of a public key (called a ´token´) and the culture.

To create a strong name for an assembly (that is, to generate a public/private key pair), you'll have to use another utility called sn.exe.

In this article, we will create a Visual Basic 2005 component called myGAC. We will also create a key file named mykeys.key. We will sign our component with this key file and place it in

Global Assembly Cache

To create a Component we have to create a Class Library project by using Visual Studio .NET.

Step 1 : Open Visual Studio .NET


Create a new Class Library project named myGAC in Visual Studio .NET or in Visual Basic 2005.
Here is the code for the component. It just includes one method which returns a string.

imports system

namespace BuildGAC
public class HelloClass
public function GetData() as string
return ´hello, how are you doing!´
end function
end class
end namespace

Step 2 : Generating Cryptographic Key Pair using the tool SN.Exe


Now, we will use the SN tool to generate the cryptographic key pair, which is located in the \bin subdirectory, where the .NET Framework Solution Developer Kit (SDK) is installed. We will open the DOS prompt. The command-line statement format is:

sn -k "C:\[DirectoryToPlaceKey]\[KeyName].key"


Next, create a directory named mykeys in C:\ so that you can easily locate the key and access the key from the command prompt.

NOTE:

For most users, the .NET tools are located in C:\Program Files\Microsoft.NET\FrameworkSDK\Bin.

Type the following at the command prompt.

sn -k "C:\mykeys\mykeys.key"

Step 3 : Sign the component with the key


A key is generated, but it is not yet associated with the project's assembly. To establish the association, double-click the AssemblyInfo.vb file in the Visual Studio .NET or Visual Studio 2005 Solution Explorer. Add the following to the list of assembly attributes that are included in this file by default when a project is created in Visual Studio .NET or in Visual Studio 2005:


<Assembly: AssemblyKeyFile("C:\mykeys\mykeys.key")>


Now recompile the project and the assembly will be signed.

Below is a listing of the complete code of assembly AssemblyInfo.vb

Imports System.Reflection

Imports System.Runtime.InteropServices

<Assembly: AssemblyTitle("")>

<Assembly: AssemblyDescription("")>

<Assembly: AssemblyCompany("")>

<Assembly: AssemblyProduct("")>

<Assembly: AssemblyCopyright("")>

<Assembly: AssemblyTrademark("")>

<Assembly: CLSCompliant(True)>

<Assembly: AssemblyKeyFile("C:\mykeys\mykeys.key")>

<Assembly: Guid("E3492A62-5389-4286-94A3-1331CC29EA6D")>

<Assembly: AssemblyVersion("1.0.*")>


The next step is to install the assembly into the Global Assembly Cache.

Step 4 : Host the signed assembly in Global Assembly Cache


There are two ways to install an assembly into the global assembly cache:


Using Microsoft Windows Installer 2.0



This is the recommended and most common way to add assemblies to the global assembly cache. The installer provides reference counting of assemblies in the global assembly cache, plus other benefits.


Using the Global Assembly Cache tool (Gacutil.exe)


You can use Gacutil.exe to add strong-named assemblies to the global assembly cache and to view the contents of the global assembly cache.

Note:

Gacutil.exe is only for development purposes and should not be used to install production assemblies into the global assembly cache.

Syntax to install a strong-named assembly into the global assembly cache

You can install the .dll file by using the Gacutil Tool or by dragging the .dll file into the appropriate directory. If you use the Gacutil Tool, you can use the following command:

At the command prompt, type the following command:

gacutil ­I <assembly name>

In this command, assembly name is the name of the assembly to install in the global assembly cache.

The following example installs an assembly with the file name myGAC.dll into the global assembly cache.

gacutil -I "C:\[PathToBinDirectoryInVSProject]\myGAC.dll"

After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there.

Step 5 : Test the assembly


Once you've installed the assembly into the GAC, you can use it from other programs by creating a reference.

Now, we will create a sample client application which uses our shared assembly.

In our sample clientGACTest project, expand the project and then right-click on the References item. Select "Add Reference" from the popup menu, and the Add Reference dialog box is displayed.

To refer an assembly in the GAC, just click on the Browse button and browse to the directory (myGAC/bin/debug) that contains the assembly (myGAC.dll). Locate the assembly, select it, and click OK.

Click on the myGAC reference in Solution Explorer and then examine the Properties pane. You'll see that the Copy Local property is set to False, Strong Name is true, and that the assembly version is 1.0.2369.37199
Just create a sample code as listed below :
You can now compile and run the clientGAC program.
Imports System

Imports myGAC.BuildGAC

Public Class SampleTest

Shared Sub main()

Dim x As New HelloClass()

Dim s As String = x.GetData()

Console.WriteLine(s)

End Sub

End Class
Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly.

Summary:

This article describes how to generate a strong name for an assembly and to install a .dll file in the Global Assembly Cache. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications. The GAC is automatically installed with the .NET runtime. Components are stored in C:\WINNT\Assembly.


Disable the Anchor Tag Using JavaScript

function DisableTheAnchorTag()
{
var btnA= document.getElementById("name of the a tag");
if(btnA!= null)
{
btnA.onmouseover=function y(){this.style.cursor='default'}
btnA.setAttribute('onclick', "void(0);");
}
}

Tuesday, November 16, 2010

Get Current Logged On user using JavaScript

<script language="javascript" type="text/javascript">
_spBodyOnLoadFunctionNames.push("GetCurrentLoggedOnUserName");
function GetCurrentLoggedOnUserName()
{
var Loginname = document.getElementById("zz8_Menu").innerHTML ;
var end = Loginname.indexOf("<");
var nameOnly = Loginname.substring(8, end);
alert(nameOnly);
}
</script>

Jquery In SharePoint page

<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("GetAlert");

$(document).ready(function GetAlert() {
var thisUser = 'test';
alert(thisUser);
});

</script>

Monday, November 15, 2010

Getting Query parameters using Javascript

<script language='JavaScript'>
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};

for(var i=0;i {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}

// print all querystring in key value pairs
for(var i in queryStringList)
document.write(i+" = "+queryStringList[i]+"<br/>");
</script>

Connection String File

1. Create a text file.
2. Change a file extension as UDL
3. Now Double Click the file and Test connection string.
4. close
5. Open a file with notepad
6. We can have connection string

Friday, November 12, 2010

Find the userId from a people picke

<script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Find the userId from a people picker in DispForm
var userIdRaw = $(fields['client']).find('.ms-formbody a').attr('href');
var userId = userIdRaw.substring(userIdRaw.indexOf('=')+1);
// Here is the userId for the person in the people picker
alert(userId);

function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>

Wednesday, November 10, 2010

"Append changes to existing text" feature of a multi-line textbox

How to work around the "append changes to existing text" feature of a multi-line textbox

Tags:

I love to use the multi-line text field in a SharePoint list or library. It is great for things like comments, status updates, notes and any other type of data that might require several lines of text. This column type even has a really cool feature that allows you to “Append Changes to Existing Text”. This feature will store ALL the changes to the field and display a historical list on the Edit or View pages.

clip_image002

Pretty cool! Right? Not so fast. This feature has some annoying drawbacks as well.

The Downside

There are two major side effects to turning the “Append Changes…” feature on.

1. It records all updates even blanks. If you edit the list item and only make a change to any field other than the multi-line text field it will store a blank in the history.

clip_image004

2. It will not display the current text in a list view. You only see a link that reads “View Entries…”.

clip_image006

A Common Approach

A common way I have seen this issue tackled is by creating a XSLT data view in SharePoint Designer. I will not cover this approach in detail, but the basic steps are:

1. Create a new Web Part page.

2. Add the desired list web part to the page.

3. In SharePoint Designer convert the web part into an XSLT Data View.

clip_image008

I do not care for this solution because it only address one of my gripes. It does show the most recent value entered into the multi-line textbox (Issue #2), but if that entry happens to be blank (Issue #1) it will display that as well. See the pictures above. Test Entry 2 displays the text that was entered, but Test Entry 1 shows blank. I want it to retain all the changes I have made and in the list view only display the last text that was entered.

My Solution

My approach utilizes a custom workflow to check for changes, but before we create the workflow we need to make some changes to your list.

1. Add a second multi-line textbox column. Call this one “Current Status” and make sure that the “Append Changes..” option is set to NO. Also, ensure that the “add to default view” is not checked.

2. Mark the new column as hidden. (This will prevent it from showing up in the Add / Edit / View pages)

a. Go to List Settings >> Advanced Settings and make sure the “Allow management of content types?” is YES.

b. In the List Settings page click on the content type to access its settings page.

c. Under the Column section click on “Current Status”.

d. Change the Column Settings to Hidden (Will not appear in forms).

3. Change the default view to show the “Current Status” column in place of the “Status” column.

a. Under the List Settings go to the Views section and click on the default view.

b. Uncheck “Status” and check the box next to “Current Status”. (You can also change the column order if needed)

Now that the list is configured properly we can create the new workflow.

1. Open SharePoint Designer to the desired site and click File >> New >> Workflow.

2. Name the workflow “Update Current Status” and select our list.

3. In the workflow start options ensure that only the boxes for “when a new item is created” and “whenever an item is changed” are checked.

clip_image010

4. Click Next.

5. On the next screen click Variables.

6. Add a new string variable named vRegExp.

clip_image012

7. In the Step Name field rename “Step 1” to “Initialize Variable”.

8. Leave the Conditions section blank.

9. Under Actions select “Build Dynamic String”.

10. Set our newly created variable “vRegExp” to the string “

.+
” (no quotes and it is case sensitive).

clip_image014

11. On the right hand column click the link to “Add workflow step”.

12. In the Step Name field rename “Step 2” to “Update Status”.

13. Under Condition select “Compare Test fields”.

14. Set the condition to “If Status matches regular expression Variable: vRegExp”.

15. Under the Actions select “Set Field in Current Item”.

16. Set the action to “Set Current Status to Status”.

clip_image016

17. Click Finish and exit out of SharePoint Designer.

Now try and update your list items and see what happens. If you enter a status then it will show up in the list view. If you update the item and don’t enter a status then the list view retains the last entry.

Conclusion

This solution uses the Status field with it’s “Append Changes…” feature in the Add / Edit / View forms, and uses the Current Status field for the list view to display the most recent update. A custom workflow was created in SharePoint Designer to check when the Current Status field needed to be updated.

**NOTE: It can take a few seconds for the workflow to run and update the field

Wednesday, November 3, 2010

Create Update List Item to value of people/user field

Create Update List Item to value of people/user field


Resolution:
1. Install Windows SharePoint Services February Cumulative Update:
http://support.microsoft.com/kb/961750.

Workaround:
If you are unable to install the SharePoint February CU, then here is a workaround:
1. Create a string variable in the workflow, and call it UserID.
2. Add the workflow action "Set Workflow Variable". Set the UserID variable to whatever user type column you are interested in (example: "Created By").
3. Add the workflow action "Build Dynamic String". In the dynamic string dialog, type "-1;#" (without quotes). Then, click "Add Lookup" to the workflow variable UserID. Click OK.
4. Still on the build a dynamic string action, set the variable to store in as UserID.
5. Change the workflow action to use the variable UserID when updating or setting the Person or Group type field.
NOTE: the same workaround works for FBA (forms based authentication) providers, as well.



Reference :

http://social.msdn.microsoft.com/Forums/en-US/sharepointworkflow/thread/9410ed52-e68b-4f5f-8acf-1b90e01d8556/

In SharePoint Designer, use a Dynamic String on your Person or Group field to insert "-1;#" to the beginnning of the field. I'm guessing this is due to some sort of error that occurs when SP parses a Person/Group list

http://social.msdn.microsoft.com/Forums/en-IE/sharepointworkflow/thread/81ed5261-3b0e-4d9c-be32-35900bb841a6http://mohd-shamim.blogspot.com/2009/02/spd-workflow-error-updating-list-item.html

Search Text:Create New Item Workflow Fails If people/user field error updating list item.

Sunday, October 31, 2010

Single space Using XSLT

<?xml:namespace prefix = xsl /> <xsl:text escaping="yes" > &nbsp;</xsl:text>

Adding a list item to Document library through c# in SharePoint 2007

1. string fileName = fileUpload.PostedFile.FileName;
2. using (SPSite site = new SPSite("http://sharepointserver"))
3. {
4. using (SPWeb web = site.OpenWeb("/"))
5. {
6. try
7. {
8. web.AllowUnsafeUpdates = true;
9. using (FileStream fs = File.Open(fileName, fileMode.Open))
10. {
11. SPList list = web.Lists["Documents"];
12. Hashtable metaData = new Hashtable();
13. for (int i = 0; i < keys.Count; i++)
14. {
15. metaData.Add(keys[i], values[i]);
16. }
17. SPFile destfile = list.RootFolder.Files.Add(fileName.Substring(fileName.LastIndexOf("\\") + 1),
18. fs, metaData, true);
19. if (destfile == null)
20. lit.Text = "Error in adding file";
21. }
22. }
23. catch
24. { }
25. finally
26. {
27. web.AllowUnsafeUpdates = false;
28. }
29. }
30. }

Saturday, October 30, 2010

How to select the Inner Most Element

Today I was working on new category browser UI for the project I am working. I had to select the innermost element and append some more content into it. Basically, I had an HTML like this:

<div>Outermost element 
<div>Some Text
<div>Evenmore text
<div>Who cares anymore?
<div>Innermost Element</div>
</div>
</div>
</div>

</div>

So I needed to select the innermost div and append another div to it. There is no jQuery selector but you can use selectors that exist to achieve this goal. The innermost element would be the last div with the only-child.

$('div:only-child:last'); 
// Change background color to gray
$('div:only-child:last').css('background-color',"#ccc");

Functions in JQuery

Functions in JQuery
$.fn.myFunction = function() {
return $(this).addClass('changed');
}
And now, use it like this:
$('.changePlease').myFunction();
And that is all there is :)

How to know logged in user information

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getWebUserData, "sp.js");
var context = null;
var web = null;
var currentUser = null;
function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args) {
var userObject = web.get_currentUser();
alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());
}
function onFaiureMethod(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Retrieving the logged-in user of a sharepoint site using Java Script

<script language="javascript"  type="text/javascript">

   var Loginname = document.getElementById("zz9_Menu").innerHTML ;  

   var end = Loginname.indexOf("<");

   var nameOnly = Loginname.substring(8, end);

   alert(nameOnly);   

  </script>

Friday, October 29, 2010

Server Variables in the DataForm WebPart

Variable Description
ALL_HTTP Returns all HTTP headers sent by the client. Always prefixed with HTTP_ and capitalized
ALL_RAW Returns all headers in raw form
APPL_MD_PATH Returns the meta base path for the application for the ISAPI DLL
APPL_PHYSICAL_PATH Returns the physical path corresponding to the meta base path
AUTH_PASSWORD Returns the value entered in the client’s authentication dialog
AUTH_TYPE The authentication method that the server uses to validate users
AUTH_USER Returns the raw authenticated user name
CERT_COOKIE Returns the unique ID for client certificate as a string
CERT_FLAGS bit0 is set to 1 if the client certificate is present and bit1 is set to 1 if the cCertification authority of the client certificate is not valid
CERT_ISSUER Returns the issuer field of the client certificate
CERT_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
CERT_SECRETKEYSIZE Returns the number of bits in server certificate private key
CERT_SERIALNUMBER Returns the serial number field of the client certificate
CERT_SERVER_ISSUER Returns the issuer field of the server certificate
CERT_SERVER_SUBJECT Returns the subject field of the server certificate
CERT_SUBJECT Returns the subject field of the client certificate
CONTENT_LENGTH Returns the length of the content as sent by the client
CONTENT_TYPE Returns the data type of the content
GATEWAY_INTERFACE Returns the revision of the CGI specification used by the server
HTTP_ Returns the value stored in the header HeaderName
HTTP_ACCEPT Returns the value of the Accept header
HTTP_ACCEPT_LANGUAGE Returns a string describing the language to use for displaying content
HTTP_COOKIE Returns the cookie string included with the request
HTTP_REFERER Returns a string containing the URL of the page that referred the request to the current page using an tag. If the page is redirected, HTTP_REFERER is empty
HTTP_USER_AGENT Returns a string describing the browser that sent the request
HTTPS Returns ON if the request came in through secure channel or OFF if the request came in through a non-secure channel
HTTPS_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
HTTPS_SECRETKEYSIZE Returns the number of bits in server certificate private key
HTTPS_SERVER_ISSUER Returns the issuer field of the server certificate
HTTPS_SERVER_SUBJECT Returns the subject field of the server certificate
INSTANCE_ID The ID for the IIS instance in text format
INSTANCE_META_PATH The meta base path for the instance of IIS that responds to the request
LOCAL_ADDR Returns the server address on which the request came in
LOGON_USER Returns the Windows account that the user is logged into
PATH_INFO Returns extra path information as given by the client
PATH_TRANSLATED A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping
QUERY_STRING Returns the query information stored in the string following the question mark (?) in the HTTP request
REMOTE_ADDR Returns the IP address of the remote host making the request
REMOTE_HOST Returns the name of the host making the request
REMOTE_USER Returns an unmapped user-name string sent in by the user
REQUEST_METHOD Returns the method used to make the request
SCRIPT_NAME Returns a virtual path to the script being executed
SERVER_NAME Returns the server’s host name, DNS alias, or IP address as it would appear in self-referencing URLs
SERVER_PORT Returns the port number to which the request was sent
SERVER_PORT_SECURE Returns a string that contains 0 or 1. If the request is being handled on the secure port, it will be 1. Otherwise, it will be 0
SERVER_PROTOCOL Returns the name and revision of the request information protocol
SERVER_SOFTWARE Returns the name and version of the server software that answers the request and runs the gateway
URL Returns the base portion of the URL