ListViewByQuery Webpart in SharePoint 2010

This is a quick post on writing a custom ListViewByQuery WebPart on a designated SharePoint 2010 site. By using a ListViewByQuery Control, developers can easily create a default looking ListView Webpart with added bespoke functionality as they have the luxury of rendering desired caml query to pull data out from an existing list. Perhaps the biggest advantage is that you can present ListViewByQuery WebPart on a different site especially when you want to work within the confines of your SharePoint permission security layer.

I have deployed the ListViewByQuery WebPart inside a custom webpart. I would recommend you to use Visual Studio 2010Empty SharePoint Project (then) – Add New Item – Web Part (Template) for this solution. This will give you all the mapped folders and files etc so nothing for you to worry about. Open your UserControl.ascx File and add the following.


<SharePoint:ListViewByQuery runat="server" id="LVWP" />

Now open the UserControl.ascx.vb file and add the following.


LVWP.List = SPContext.Current.Web.Lists("Some List")
Dim caml As SPQuery = New SPQuery(LVWP.List.DefaultView)
caml.Query = "<caml>Desired CAML Syntax</caml>"
LVWP.Query = caml

This is it, now your ListViewByQuery WebPart is ready to be used on the page. For full access to its properties and methods follow the link.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.listviewbyquery.aspx

Noteworthy Anomalies

I have found ListViewByQuery WebPart known for not having:

a)    SharePoint 2010 Ribbon being activated when you click on the List Item.

b)    No Access to DataSheet View.

c)    No ‘Add New Item’ option either.

Needless to say, it is a good reporting tool. Please continue on Google Trails or MSDN SharePoint 2010 Development & Programming Forum if you want to further investigate the above.

Advertisements

Checkboxlist Validation in Asp.Net

In this post, I would like to illustrate a simple requirement of Checkboxlist Validation. It is a common requirement to validate if a user has selected at least one item from available choice of items in an Asp Checkboxlist Control. Although, there are ways using Javascript etc. but I like to keep a strict control so this solution uses a Asp Custom Validator Control.

Here is a Checkboxlist; for sake of simplicity I have bound this to a DataSource, you can bind to either a datasource or a static set of options.


<asp:CheckBoxList ID="cblChoices" DataValueField="ChoiceID" DataTextField="Title" RepeatDirection="Horizontal" RepeatColumns="2" RepeatLayout="Table" CellPadding="1" CellSpacing="5" runat="server" />

Now, add a Custom Validator Control that works in conjunction with the above.


<asp:CustomValidator ID="CheckboxChoiceRequiredValidator" runat="server" ErrorMessage="Please opt in by selecting at least one choice" ValidationGroup="MyValGroup" Font-Bold="true" ForeColor="Red" OnServerValidate="CheckboxChoiceRequiredValidator_ServerValidate">

In the above, the most important attribute is OnServerValidate which listens to a method CheckboxChoiceRequiredValidator_ServerValidate which you need to have in the code behind. Lets, add the method in the code behind. [C# example; Use Tools to get Telerik Code Convertor for VB]

protected void CheckboxChoiceRequiredValidator_ServerValidate(object source, ServerValidateEventArgs args)

{

int cnt = 0;

for (int i = 0;i < cblChoices.Items.Count; i++)

{

if (cblChoices.Items[i].Selected) { cnt++; }

}

if (cnt == 0)

{

args.IsValid = false;

}

else

{

args.IsValid = true;

}

}

In the method above, a simple iteration to find out if there are selections made by user, and returning args as Boolean. Here I am using the if (cnt == 0) to check against zero but you can check for example (2) to ensure user have selected at least two choices. The main thing is of course, that Button Click event that checks for Checkboxlist Validation needs to have (see below) To ensure the Checkboxlist Validation is fired everytime a Button is clicked.

If (page.isValid) { }

Hope this was helpful.

SharePoint Group Permissions on SharePoint Site

In this post, I would like to discuss how to report on or retrieve SharePoint User Groups, SharePoint Users and Domain Groups on a given site or a site collection. Although this information is available to SharePoint Administrators by clicking on ‘Site Actions’ and ‘Site Permissions’, there are occasions when programmatically this information might be required.


Using site As New SPSite("http")
For Each _site As SPWeb In site.AllWebs
Using Web As SPWeb = _site

For Each ra As SPRoleAssignment In Web.RoleAssignments
' Site Groups
If TypeOf ra.Member Is SPGroup Then
‘ Business logic
ra.Member.Name

' Site Group Permissions
For Each rd As SPRoleDefinition In ra.RoleDefinitionBindings
‘ Business Logic
rd.Name
Next
End If

' Site Users / Domain Groups
If TypeOf ra.Member Is SPUser Then
‘ Business Logic
ra.Member.Name

' Site Users / Domain Groups Permissions
For Each rd As SPRoleDefinition In ra.RoleDefinitionBindings
‘ Business Logic
rd.Name
Next
End If

Next

End Using
Next

End Using

In the code above I am traversing through a site.allwebs to get the SharePoint Groups, Sharepoint Users and Domain Groups on the site. You can make this further interesting by finding out if site has unique permissions or not or if any list on site has unique permissions.

Also using the same code for a SPWeb instead of site.allWebs in a loop you can query the permissions to different groups on a single SharePoint site.

Google Captcha with Asp.Net

In this post I would like to discuss and share how I have integrated the Google’s prominent and renowned Captcha with Asp.Net. For more details on Google Captcha works in conjunction with websites and the advantages of using Captcha please visit the link below:

http://www.google.com/recaptcha/captcha

To begin with you will need to download reCAPTCHA ASP.Net Library at:

https://developers.google.com/recaptcha/docs/aspnet

On the link above are examples on the use of the API and illuminates Asp.Net developers on how they can easily integrate Google Captcha to their websites as and when required. Please ensure you have signed (with Google account) and obtain the Keys that will be required for the code examples below.

When you add the reference to your Website/ Web Application Project the .dll namely recaptcha.dll and recaptcha.dll.refresh will be added to your BIN folder. You can also manually copy the .dll and paste them to your BIN folder.

Now, let’s begin with writing some code. Following the line of API examples in the link above, I add the following reference to the page where you would like your Captcha to be working on.

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

Now, that the user control is registered, it can be used in the following way.

<recaptcha:RecaptchaControl ID="captcha" runat="server" PublicKey="YOUR_PUBLIC_KEY" PrivateKey="YOUR_PRIVATE_KEY"/>

As soon as you embed the control on the page, it is ready in action. In my case I have placed the captcha control inside the Asp Form Validation Group to makes it mandatory to be filled by end users.

Finally, there’s no guaranteeing your end users have entered the right text presented to them on the captcha. So this is where Asp CustomValidator comes handy.

<asp:CustomValidator ID="CaptchaValidator" runat="server" ErrorMessage="Please enter information correctly" Font-Bold="true" ForeColor="Red"       SetFocusOnError="true" Display="Dynamic" ValidationGroup="CaptchaValidationGroup"></asp:CustomValidator>

And finally the code behind for the CustomValidator above.

Protected Sub CaptchaValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CaptchaValidator.ServerValidate
captcha.Validate()
args.IsValid = captcha.IsValid
End Sub

There you have it, a fully working Google Captcha with your Asp.Net website. On a final note, here’s something interesting,

Captcha abbreviates to “Completely Automated Public Turing test to tell Computers and Humans Apart

Reference: http://support.google.com/a/bin/answer.py?hl=en-uk&hlrm=en-uk&hlrm=en&answer=1217728

Connection Strings Without Web Config in Asp.Net

In this post, I am writing how to employ and utilise Asp.Net Connection Strings in when you don’t have the all-important Web.Config file at your disposal and you are disabled from using the Asp.Net ConfigurationManager class to establish the connection string.

Please review the link below to ensure you are using right Connection String format fitting your development environment and SQL instance.

Reference: http://www.connectionstrings.com/sql-server-2008

For establishing SQL Server Connection, running SQL Query / Stored Procedure you would require a Connection String. The code below uses a declarative connection string where Web.Config is not available.


Dim SqlConnectionString As String = "Server=SQLSERVER;Database=DB;User ID=Username;Password=password"
Dim ConnStringSettingObj As ConnectionStringSettings = New ConnectionStringSettings("constr", SqlConnectionString)

Dim path As String = ConnStringSettingObj.ConnectionString
Dim conn As SqlConnection = New SqlConnection(path)

Dim cmdText As String = "StoredProcedure_OR_SQL_Query"
Dim cmd As SqlCommand = New SqlCommand(cmdText, conn)

cmd.CommandType = CommandType.StoredProcedure
Dim _Param As SqlParameter = New SqlParameter("_SqlArgumentIfAny", SqlDbType.VarChar)
_Param.Value = "something"

cmd.Parameters.Add(_Param)

' If data return is required / otherwise ignore
Dim adaptr As SqlDataAdapter
Dim ds As New DataSet

Try
conn.Open()
adaptr = New SqlDataAdapter(cmd)
adaptr.Fill(ds)
Catch ex As Exception
Throw New ConfigurationErrorsException
Finally
conn.Close()
End Try

Periodically Invoking Asp.Net Web Service

This is a quick post on a method that explains how to invoke Asp.Net Web Service(s) periodically. It is inevitable, that once in a while there will be a requirement where you will be pushing / pulling data via Asp.Net Web Services periodically. As much this is a common requirement, however there are several ways in which it can be engineered.

JQuery Call, JavaScript Timer based call, Asp ScriptManager control to invoke web service are some of the ways to name a few.

In the code below, I have used a Asp:Timer object to fire a desired web service periodically (every 1 minute or 60 seconds or 60,000 milliseconds). I don’t claim this is innovative way of doing this. Needless to say, this could be just one of the ways in which such a requirement can be achieved.

Declare your Asp:Timer control; requires a ScriptManager Control to work

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Timer ID="WebSvcPeriodInvoke" runat="server" Interval="60000"></asp:Timer>

Declare the native Tick() method for Asp.Timer; code-behind


Protected Sub WebSvcPeriodInvoke_Tick(sender As Object, e As System.EventArgs) Handles WebSvcPeriodInvoke.Tick

' Invoke WebService Programmatically

Dim WebSvcObj As NameOfWebService = New NameOfWebService
Dim _MethodCall As int = WebSvcObj.NameOfYourMethod(Arg1, Arg2)

' Do Something with _MethodCall Variable

End Sub

Using the method above, your .aspx page is now using a Asp:Timer control to invoke an Asp.Net Web Service periodically after every 1 minute. This is super handy, you can easily pass in parameters if required to Web Service and play with the result or be imaginative where required.