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.