RSS

Advance paging in SharePoint 2010 using Client Object Model and jQuery


In this tutorial I will show you new way of creating custom paging that work with SharePoint 2010 or SharePoint 2013 by using Cleint Object Model and jQuery.

Demo

Description

This demo is using custom paging approach but I’m injecting data on same page instead of navigating between pages by using jQuery.

Note: This code should work not only on lists but it can work with any different data source like document library ,Image Library and so on

Advantages

The are many advantages of this Advance Custom paging as follow

  • Work great with large lists because you do not need to navigate between pages.
  • It’s javascript which means is cleint side ,so need for post back each unlike standard custom paging.
  • Clean HTML tags because I’m using Table- less table by using DIV tag

Prerequisites

To run this code properly you need the following

  • Create Custom List and name it “Products”
  • Create New Cloumn in Products list and name it Company,so you have now two column Title and Company
  • Try to fill Products list with some data
  • How it work

    The idea is sample ,you just need to work with SharePoint Client Object Model but the most important thing to note is ListItemCollectionPosition and row limit as well.

     <script>
    var listItems;
    var query;
    var targetList;
    var clientContext;
    
    function LoadData() {
    
    $('#divPostsLoader').html('<img src="../../../_layouts/Images/AdvancePaging/ajax-loader.gif">');
    clientContext = new SP.ClientContext();
    targetList = clientContext.get_web().get_lists().getByTitle('Products');
    query = new SP.CamlQuery();
    var RowCount = 3;
    //Specifying the RowLimit will determine how many items will be fetched in one call to the server.
    query.set_viewXml("<View><RowLimit>"+RowCount+"</RowLimit></View>");
    listItems = targetList.getItems(query);
    clientContext.load(listItems);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    
    function onQuerySucceeded() {
    
    var title, company;
    var listEnumerator = listItems.getEnumerator();
    //Create Header
    $("#Result").append("<div class='div-table-row'><div class='div-table-col'>Title</div><div class='div-table-col'>Name</div>");
    $("#divPostsLoader").empty();
    while (listEnumerator.moveNext()) {
    title = listEnumerator.get_current().get_item("Title");
    company = listEnumerator.get_current().get_item("Company");
    //Create tableless using DIV
    $('#Result').append("<div class='div-table-row'>");
    $('#Result').append("<div class='div-table-col'>" + title + "</div><div class='div-table-col'>" + company + "</div>");
    $('#Result').append("</div>");
    }
    }
    
    function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
    }
    
    //Call the function after the sp.js is loaded.
    ExecuteOrDelayUntilScriptLoaded(LoadData, "sp.js");
    function loadMoreData() {
    $('#divPostsLoader').html('<img src="../../../_layouts/Images/AdvancePaging/ajax-loader.gif">');
    
    //Gets the id of the last element from the returned collection along with the query.
    var position = listItems.get_listItemCollectionPosition();
    
    if (position != null) {
    $("#LoadBtn").attr("disabled", "disabled");
    query.set_listItemCollectionPosition(position);
    listItems = targetList.getItems(query);
    clientContext.load(listItems);
    //Call the other function to load  data from list
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onLoadQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }
    else {
    $('#divPostsLoader').empty();
    $("#LoadBtn").attr("value", "No more data found");
    $("#LoadBtn").attr("disabled", "disabled");
    }
    }
    function onLoadQuerySucceeded() {
    var title, company;
    var listEnumerator = listItems.getEnumerator();
    while (listEnumerator.moveNext()) {
    title = listEnumerator.get_current().get_item("Title");
    company = listEnumerator.get_current().get_item("Company");
    $("#divPostsLoader").empty();
    //Create tableless using DIV
    $('#Result').append("<div class='div-table-row'>");
    $('#Result').append("<div class='div-table-col'>" + title + "</div><div class='div-table-col'>" + company + "</div>");
    $('#Result').append("</div>");
    }
    $("#LoadBtn").removeAttr("disabled");
    
    }
    
    </script>
    

    as you can see you need to specify the row list (3,4,..etc) then loading data.After that when you click the button it will return next rows and so on until position equal null.

    Source Code

    The Source code of this article can be found on the following link

    http://code.msdn.microsoft.com/Advance-paging-in-81934f2b

 
1 Comment

Posted by on September 29, 2012 in jquery, SharePoint

 

Tags: , , , , , , , ,

How to connect to the Oracle database using Business Connectivity Services (BCS) in SharePoint 2010


In this Step by Step article I will show you how to connect to the oracle database using BCS.

Note: Before we start I will assume that you are already have running and working oracle database.

Prerequisites

Table Name: Orders

Column Name Type Primary Key
Order_ID Number (5) Yes
Order_Name Varchar 2 (50) No
  • Add oracle connection string in tnsnames.ora as following

Go to C: or D: –>App-> Your User Name->product->11.2.0->client_1->Network->Admin.

after going to Admin folder you will find to files (sqlnet.ora,tnsnames.ora)image

Note:if you did not find those files go to sample folder and copy both files and past it in Admin Folder.

  • Now open tnasnames.ora file and add connection string of your oracle DataBase similar to the following syntax

image

Creating a BCS External Content Type

1- Open Visual Studio and create new sharepoint 2010 project as following and select Deploy as a farm solution

image

image

2- After Creating project add new SharePoint Item (SPI) with type Business Data Connectivity Modelimage

3-Now Remove Entity1, Entity1.cs and Entity1Service.cs

image

image

4-Now add new Entity with Orders Name and add identifier with Order_ID name and type System.Int32

image

image

5- Create New class with Order Name

image

6- Open Order.cs and the following code

image

7- Add Oracle.DataAccess.dll reference from the following path

D:\app\yourusername\product\11.2.0\client_1\odp.net\bin\2.x

8- Now it’s time to Create Method for insert,update,delete,retrive.

9-Click on Order Entity on BDC Diagram and add the following Methods.

image

10- now the BDC will be looking to the following diagram

image

11- Now Go to BDC explorer to make sure the Orders identity have the correct Type descriptors for each method as following

image

Note: Make sure to set identifier property  for each Order_ID on each method to Order_ID identifier

image

Note:For Update Method you need to set Pre-Update Field prperty to True for Order_ID in parameter section.

image

12- Open Order.cs and write the following code .


public partial class OrdersService
{
static string connectionString = "Data Source=dotnetfinder;User ID=ahmed; Password=sharepoint";
public static Orders ReadItem(int order_ID)
{

Orders SelectedOrder=new Orders();;
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select * from orders where order_id=:order_id", connection);

connection.Open();
cmd.Parameters.Add(":order_id", order_ID);
OracleDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
SelectedOrder.Order_ID = Convert.ToInt32(Reader["Order_ID"]);
SelectedOrder.Order_Name = Reader["Order_Name"].ToString();
}
}
return SelectedOrder;
}

public static IEnumerable<Orders> ReadList()
{

List<Orders> OrderList = new List<Orders>();
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select * from orders", connection);
connection.Open();
OracleDataReader Reader = cmd.ExecuteReader();
while (Reader.Read())
{
Orders SelectedOrder = new Orders();
SelectedOrder.Order_ID = Convert.ToInt32(Reader["Order_ID"]);
SelectedOrder.Order_Name = Reader["Order_Name"].ToString();
OrderList.Add(SelectedOrder);
}
}
return OrderList;
}

public static Orders Create(Orders newOrders)
{

using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("insert into orders (order_id,order_name) values (:order_id,:order_name)", connection);
connection.Open();
cmd.Parameters.Add(":order_id", newOrders.Order_ID);
cmd.Parameters.Add(":order_name", newOrders.Order_Name);

cmd.ExecuteNonQuery();
}
return newOrders;
}

public static void Update(Orders orders, int parameter)
{

using (OracleConnection connection = new OracleConnection(connectionString))
{

OracleCommand cmd = new OracleCommand(string.Format("update orders set order_name=:order_name where order_id={0}",parameter), connection);
connection.Open();

cmd.Parameters.Add(":order_name", orders.Order_Name);

cmd.ExecuteNonQuery();
}
}
}

13-Deploy your solution Now and create New External List and pick up our external content type that we have created in this article

Configure Business Data Connectivity access rights:

1. Go to Central Administration -> Application Management -> Manage Service Applications.

17

2. Click on Business Data Connectivity Service.

3. In the top Ribbon click on Manage.
4. In Service Application Information check the External Content Type Orders

5. In the top Ribbon click the Site Object Permissions.

6. Site Object Permissions wizard will pop up add the account (Group or Users) and assign the permissions.

Creating an External List in the SharePoint Site:

1. Open the SharePoint Site.

2. Go to Site Actions => More Options.
3. On the Create Wizard, from the Installed Templates Select List.

4. In the List Type select External List and click Create.

5. Enter the Name as BCS for OracleDB and choose the External Content Type as shown below.

image

6-Now you can find the external list with data populated from Oracle Database

image

Try now to Create,Update,Delete and Retrieve items and Every Thing should work fine Open-mouthed smile

You can download Source Code from here

 
1 Comment

Posted by on August 27, 2012 in C#, SharePoint, VB.NET

 

Tags: , , , , , , , ,

Microsoft Community Contributor Award


image

I’ve received a mail from Microsoft and this is what mail was said

Congratulations! We’re pleased to inform you that your contributions to Microsoft online technical communities have been recognized with the Microsoft Community Contributor Award.
The Microsoft Community Contributor Award is reserved for participants who have made notable contributions in Microsoft online community forums such as TechNet, MSDN and Answers. The value of these resources is greatly enhanced by participants like you, who voluntarily contribute your time and energy to improve the online community experience for others.

It’s great honor to me and I want to see I could do not done it without you.

Thanks’ to everyone who helped me to reach to this point and I will try my best as much as I can

Regards.

 
Leave a comment

Posted by on March 31, 2012 in General

 

Tags: , , , ,

Import data from Excel to SQL Server


in this article I’m going to show you how to import data from Excel to SQL Server in few steps but first take a look to import/export screen

image

As you can see the screen is so simple it’s have three controls

  • FileUpload control to help you to find the location of your Excel file.
  • Button to import data from Excel and save it in SQL Server.
  • Label control which is just message to tell of operation result(Success or Fail)

Steps to make application run successfully

Note: before start reading the steps I want let you to know that I haven’t test this sample either on ASP.NET 3.5 or 32-bit MS Office,so may be you do not need the step 1 and step 2.

  1. Create an IIS web site
  2. Change .Net Framework to 4.0 for Application Pool of this site
  3. Create Excel file and make sure that file contain the column name as following image

image

4.Create Table in SQL Server and make sure has the same Columns name with appropriate columns data type.

image

The following code snippet will show you how upload file in import data from it and save it to SQL Server.

In C#

// if you have Excel 2007 uncomment this line of code
//  string excelConnectionString =string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0",path);

string ExcelContentType = "application/vnd.ms-excel";
string Excel2010ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (FileUpload1.HasFile)
{
//Check the Content Type of the file
if(FileUpload1.PostedFile.ContentType==ExcelContentType || FileUpload1.PostedFile.ContentType==Excel2010ContentType)
{
try
{
//Save file path
string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName);
//Save File as Temp then you can delete it if you want
FileUpload1.SaveAs(path);
//string path = @"C:\Users\Johnney\Desktop\ExcelData.xls";
//For Office Excel 2010  please take a look to the followng link  http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/0f03c2de-3ee2-475f-b6a2-f4efb97de302/#ae1e6748-297d-4c6e-8f1e-8108f438e62e
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);

connection.Open();

// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{

// SQL Server Connection String
string sqlConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True";

// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Employee";
bulkCopy.WriteToServer(dr);
Label1.Text = "The data has been exported succefuly from Excel to SQL";
}
}
}
}

catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}

in VB.NET

'if you have Excel 2007 uncomment this line of code
'  string excelConnectionString =string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0",path);
'Define the content type
Dim ExcelContentType As String = "application/vnd.ms-excel"
Dim Excel2010ContentType As String = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
If FileUpload1.HasFile Then
If FileUpload1.PostedFile.ContentType = ExcelContentType Or FileUpload1.PostedFile.ContentType = Excel2010ContentType Then
Try
'Save file path
Dim path As String = String.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName)
'Save File as Temp then you can delete it if you want
FileUpload1.SaveAs(path)
'For Office Excel 2010  please take a look to the followng link  http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/0f03c2de-3ee2-475f-b6a2-f4efb97de302/#ae1e6748-297d-4c6e-8f1e-8108f438e62e
Dim excelConnectionString As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path)

' Create Connection to Excel Workbook
Using connection As New OleDbConnection(excelConnectionString)

Dim Command As OleDbCommand = New OleDbCommand("Select * FROM [Sheet1$]", connection)

connection.Open()

'Create DbDataReader to Data Worksheet
Using reader As DbDataReader = Command.ExecuteReader()

' SQL Server Connection String
Dim sqlConnectionString As String = "Data Source=.\sqlexpress;Initial Catalog=ExcelDB;Integrated Security=True"

' Bulk Copy to SQL Server
Using bulkCopy As New SqlBulkCopy(sqlConnectionString)

bulkCopy.DestinationTableName = "Employee"
bulkCopy.WriteToServer(reader)
Label1.Text = "The data has been exported succefuly from Excel to SQL"
End Using
End Using
End Using
Catch ex As Exception
Label1.Text = ex.Message
End Try
End If
End If

Run and test Application

after following the above steps you can run web and click on the browse then select Excel file then click import to save Excel file data on SQL Server side.

Download the sample

You can download code from the following link ( Please do not forget to rate it)

http://code.msdn.microsoft.com/Imoprt-Data-from-Excel-to-705ecfcd

References

I hope you find this sample useful and i will be happy to answer your questions.

Regards.

 
1 Comment

Posted by on March 20, 2012 in ASP.NET, C#, VB.NET

 

Tags: , , , ,

Infinite Scroll images Like Bing and Google


Introduction

One of the must annoying thing when working with large data is how to loading this data to your page?

The common solution is paging but paging itself will not help too much you can end with hundred or thousands of page numbers.So new solution now is on the surface and it’s called “Infinite Scroll”.Infinite Scroll allow you to load chunk of data when you scroll down of the page and inject it inside the page, it will load data each time you scrolling down on the page.

Note:Before you start you can download code from here ( Please do not forget to rate it)

Infinite Scroll images Like Bing and Google

Demo

(Click on the image to see the result)

IScroll

Description

As I told you in the introduction Infinite Scroll is becoming more and more popular it’s in everywhere starting with Bing,Google,Facebook,Twitter,Linkedin.etc.

The idea of infinite scrolling is so simple and it can be summarized in the following diagram which is part of Scott Hanselmen Article

Infinite Scroll WebSites via AutoPagerize – Hacky, but the beginning of something cool

My Sample will show you how to Display a list of images like Bing and Google but this is not the only thing,you can take the advantage of idea behind infinite scrolling and implement the same concept everywhere.

The following code snippet will be called when you scroll to the last of the page

[WebMethod]
public static string LoadImages(int Skip, int Take)
{
System.Threading.Thread.Sleep(2000);
StringBuilder GetImages = new StringBuilder();
string Imagespath = HttpContext.Current.Server.MapPath("~/Images/");
string SitePath = HttpContext.Current.Server.MapPath("~");
var Files = (from file in Directory.GetFiles(Imagespath) select new { image = file.Replace(SitePath, "") }).Skip(Skip).Take(Take);
foreach (var file in Files)
{
var imageSrc = file.image.Replace("\\","/").Substring(1); //Remove First '/' from image path
GetImages.AppendFormat("<a>");
GetImages.AppendFormat("<li>");
GetImages.AppendFormat(string.Format("<img src='{0}'>", imageSrc));
GetImages.AppendFormat("</li>");
GetImages.AppendFormat("</a>");

}
return GetImages.ToString();
}

VB.Net part

<WebMethod()> _
Public Shared Function LoadImages(Skip As Integer, Take As Integer) As String
System.Threading.Thread.Sleep(2000)
Dim GetImages As New StringBuilder()
Dim Imagespath As String = HttpContext.Current.Server.MapPath("~/Images/")
Dim SitePath As String = HttpContext.Current.Server.MapPath("~")
Dim Files = (From file In Directory.GetFiles(Imagespath) Select New With { _
Key .image = file.Replace(SitePath, "") _
}).Skip(Skip).Take(Take)
For Each file As Object In Files

Dim imageSrc = file.image.Replace("\", "/").Substring(1) 'Remove First '/' from image path
GetImages.AppendFormat("<a>")
GetImages.AppendFormat("<li>")
GetImages.AppendFormat(String.Format("<img src='{0}'/>", imageSrc))
GetImages.AppendFormat("</li>")
GetImages.AppendFormat("</a>")
Next
Return GetImages.ToString()
End Function

JavaScript part

$(document).ready(function () {
var Skip = 49; //Number of skipped row
var Take = 14; //
function Load(Skip, Take) {
$('#divPostsLoader').html('&lt;img src="ProgressBar/ajax-loader.gif"&gt;');

//send a query to server side to present new content
$.ajax({
type: "POST",
url: "Grid.aspx/LoadImages",
data: "{ Skip:" + Skip + ", Take:" + Take + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {

if (data != "") {
$('.thumb').append(data.d);
}
$('#divPostsLoader').empty();
}

})
};
//Larger thumbnail preview

//When scroll down, the scroller is at the bottom and fire the Load ()function
$(window).scroll(function () {

if ($(window).scrollTop() == $(document).height() - $(window).height()) {
Load(Skip, Take);

//Any number you want
Skip = Skip + 14;
}
});
})

Summery :

Infinite scroll is every where now ,this sample show give good starting point.It’s not only loading images you can load any thing you want start from images,text data and even load pages inside the page.

I hopefully you like the sample and really appreciate your comments and feedback
.

Regards.

 
2 Comments

Posted by on February 26, 2012 in ASP.NET, C#, jquery, VB.NET

 

Tags: , , , , , , , , ,

SharePoint 2010 Twitter Web Part


It’s been a while time since my last post here.Today I’m going to talk about Building Twitter web part in SharePoint 2010 as seen below.

image

Note:Before you start you can download code from here ( Please do not forget to rate it)

SharePoint 2010 Twitter Web Part

SharePoint 2010 Twitter Web Part Features

  • Allow you to display Profile or search with include replies and include retweets when you select Profile mode
  • you can specify numbers of tweets or status(1,2,..etc)
  • The Status will be updated during specific time(10,15,30,45,16) asynchronously (no need to refresh page).
  • It’s Free Open-mouthed smile

Twitter Web Parts important things to know

1- Define and pass custom parameters to Visual web part.

if you look to the following image you will see that I’m using custom properties to initialize web part,this is easy in normal web part but not in visual web part

image

To get rid this issue you need to follow this steps

  • Open your web part class that inherits from ASP,Net WebPart class
  • Add custom properties let say Profile
public class TwitterWepPart : WebPart
{
public enum TwitterMode
{
Profile,
Search
}
[DefaultValue(TwitterMode.Profile)]
[Description("Select a category from the dropdown list.")]
[WebDisplayName("Twitter Mode")]
[WebBrowsable(true)]
[Personalizable(PersonalizationScope.User)]
[Category("Twitter Settings")]
public TwitterMode Mode
{
get;
set;
}

……

}

as you can see I’m using Enum to display the value in DropDown List

  • After Defining the whole custom properties you need to define a property of TwitterWebPart in user control
public partial class TwitterWepPartUserControl : UserControl
{

public TwitterWepPart PropertiesWebPart;

…….

}
  • The final step is to pass the custom properties within CreateChildControls method
public class TwitterWepPart : WebPart
{

…..

// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = @"~/_CONTROLTEMPLATES/SPTwitter/TwitterWebPart/TwitterWebPartUserControl.ascx";

protected override void CreateChildControls()
{
TwitterWebPartUserControl control = Page.LoadControl(_ascxPath) as TwitterWebPartUserControl;
control.PropertiesWebPart = this;
Controls.Add(control);
}

}

….

}

As you can see  Page.LoadControl is used to load the control of type Control but in our case we want LoadControl to return TwitterWebUserControl instead of Control,so we can read the values of Custom Properties of this web part from usercontrol.

var Tweets = GetProfile(PropertiesWebPart.Name, PropertiesWebPart.Count, PropertiesWebPart.Retweet, PropertiesWebPart.Replies);

We are able now read value from Custom Properties like count,including Retweets ..etc,

2- Using Twitter API to display the results

For user Mode you need to pass the following parameters to twitter

  • User name with or without @
  • Number of status to display
  • Include Replies (optional)
  • Include Retweets (Optional)

you will then Create Get request as following

http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=amdnaji&count=5&include_rts=1&exclude_replies=1

For Search Mode you only need the following Parameters

  • Search Name
  • Number of status to display

The request will be like this

http://search.twitter.com/search.atom?q=ajax&rpp=5

Start working on web part

1- Open the project on Visual studio 2010 –>Deploy

Note:You need to change Site Url before deploy web part.

2- Open your site then add web part to the page.

3- Click on Edit Web Part and go to Twitter Settings Section

image

Let us select Profile as Twitter Mode and in the name let us type Dr oz account @DrOz and Count will be 3.

Click ok to close web part panel and save the page then you will find the following results

image

Now Let us change the mode to Search and select SharePoint 2010 as a name of this Search.

image

References

I hope you like this web part and really appreciate your comments and feedback

Regards.

 
13 Comments

Posted by on January 17, 2012 in SharePoint

 

Tags: , , , ,

SharePoint 2010 – How to use Audio and Video Webpart


Video and Audio Web Part [a.k.a Media Web Part] is one of the new cool web parts in SharePoint 2010, so in this article I am going to show you the way to add this web part in your page.
To add Media web part to the page you must activate those two features
1- SharePoint Server Publishing Infrastructure Feature in Site Collection features

2- SharePoint Server Publishing Feature in Site features

After that edit page then click on Insert tab in SharePoint Ribbon then select Video and Audio

Now the Media Web Part in the page


Click on the Media Web Part and you will find Options Tab in the Ribbon

As you can see in the Options tab there are Chang Media button allow you to select the video and Chang Image button to change the image of web part and Styles (Dark, Light)
Click on Change Media to select the Media file.

From Computer opens up the Upload media so you can upload the video and display it.

Once you click ok and saving the page. Click on play button and enjoy tour video

 
13 Comments

Posted by on November 8, 2010 in SharePoint

 

Tags: , , , ,

اللقاء الأول لمجموعة مستخدمي الشيربوينت في مكة المكرمة


MSPUGتم بحمد الله وكرمه الأنتهاء من اللقاء الأول يوم الأربعاء الموافق 10/28/2010 لمجموعة مستخدمي شيربوينت في مكة المكرمة  وقد كان الحديث حول الشيربوينت  في إصدارها الاخير 2010  وكان المتحدث الرسمي هو المهندس على خواجة خبير إستشاري شركة مايكروسوفت وقد تحدث مشكورا عن المنصة الجديدة للشيربوينت 2010 وعن الإضافات الجديدة. وأستمر الحديث قرابة الساعتين وكان الحديث والنقاش البناء من الحضور الكريم في غاية الروعة والفائدة للجميع والحمد لله رب العالمين

طبعا أنا لن أضع الدروس والصور الخاص باللقاء  في مدونتي ولكننا بصدد إنشاء موقع كامل بحول الله وقوته عن المجموعة وسوف يحتوي على مقالات ,دروس فيديو الكثير من الفوائد إن شاء الله تعالى

في الختام

أردت فقط في هذه الأسطر البسيطة أن أعبر لكم عن مدى سعادتي بوجود هذه المجموعة من المستخدمين في مكة المكرمة أحب البقاع إلى الله عز وجل .وإن شاء الله سوف تكون اللقاءات القادمة للمجموعة أجمل وأفضل . بارك الله في المهندس على خواجة لحضوره وبارك الله جميع الحضور وأتمنى أن شاء الله في اللقاءات القادمة حضور أكبر من مبرمجي مكة المكرمة وعشاق البرمجة تحت إطار عمل دوت نت

 
3 Comments

Posted by on October 28, 2010 in MSPUG

 

Tags: , , , ,

Building a Database Driven Hierarchical Menu using ASP.NET and SooperFish Jquery Plugin


Click on the Image To see the Demo


Introduction

In this article I will show you how to build database driven hierarchical multi-column dropdown menus using SooperFish jquery Plugin. But why SooperFish Plugin ?
Feature of SooperFish PlugIn jquery
•  Automatic dual or triple columns based on number of child menu items
•  Optional delay before hiding menu on mouse-out
•  Optional automatic indicator arrows (in black or white)
•  Configurable show AND hide animations
•  Custom easing supported
•  Works with jQuery backlava plugin (optionally)
•  Works fine with Javascript disabled
•  Comes with several free themes to demonstrate styling
•  3.65kb uncompressed
•  2.01kb minified

To me the preceding feature very nice but why SooperFish

Because to build animated meun using SooperFish you need only three HTML Tags (ul,li and a), so that’s way I like very much SooperFish PlugIn .See  image 2

Steps to build a Database Driven Hierarchical Menu using ASP.NET and SooperFish Jquery Plug in

Note: Thanks to Michael Libby for his nice article Building a Database Driven Hierarchical Menu using ASP.NET 2.0

Step 1 – create self-join Table and fill it with some data


The simplest way to build hierarchical data is create  self-join table  which parent Menu and Child Menu in the same table .the child menu will use ParentID  to establish a relationship with MenuID in parent Row
Figure 3:  self-join Table

Self Join

Fill the table with some data see –Figure 4


Figure 4 : Parent, Child Relationships

Step 2 : retrieve Data and Create Nested Relationship using DataSet


The DataSet() is perfect  for  retrieve the  data and create relational data and convert it into xml format see the following code

public string GenerateXmlFormat()
    {
        string SqlCommand;
        DataSet DbMenu;
        DataRelation relation;

        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {

            SqlCommand = "Select MenuID, Name,Url, ParentID from MenuTable";

            DbMenu = new DataSet();

            SqlDataAdapter Adapter = new SqlDataAdapter(SqlCommand, conn);

            Adapter.Fill(DbMenu);

            Adapter.Dispose();
        }

        DbMenu.DataSetName = "Menus";

        DbMenu.Tables[0].TableName = "Menu";

        //create Relation Parent and Child
        relation = new DataRelation("ParentChild", DbMenu.Tables["Menu"].Columns["MenuID"], DbMenu.Tables["Menu"].Columns["ParentID"], true);

        relation.Nested = true;

        DbMenu.Relations.Add(relation);

        return DbMenu.GetXml();
    }

The most important points in the previous code are
•  The DataRelation Class, which allow you to create relation between Parent and Child Column.
•  Nested property  ,which allow you to build Hierarchical data .
•  GetXml() function ,represent the retrieved  data as xml format.
The result after calling DbMenu.GetXml()  shown in the next Figure

Figure 5 : Hierarchical data in Xml Format after calling GetXml() method.

Step 3 – using XSLT to convert XML data to HTML format


After generating data as xml (Figure 5) we need to convert this XML or reformate it to HTML Markups .So we need an XSLT to convert xml format to HTML .
First of all create new XSLT file and then write this code

<!-- Find the root node called Menus then convert it to <UL> </UL> HTMLTags
       and call MenuListing for its children -->
  <xsl:template match="/Menus">
    <ul>
      <xsl:attribute name="class">
        <xsl:text>sf-menu</xsl:text>
      </xsl:attribute>
      <xsl:attribute name="id">
        <xsl:text>nav</xsl:text>
      </xsl:attribute>
      <xsl:call-template name="MenuListing" />
    </ul>
  </xsl:template>

  <!-- Allow for recusive child node processing -->
  <xsl:template name="MenuListing">
    <xsl:apply-templates select="Menu" />
  </xsl:template>

  <xsl:template match="Menu">
    <li>
      <a>
      <!-- Convert Menu child elements to <li> <a> html tags  and attributes inside a tag -->
      <xsl:attribute name="href">
        <xsl:value-of select="Url"/>
      </xsl:attribute>
        <xsl:value-of select="Name"/>
      </a>
      <!-- Recursively call MenuListing for child menu nodes -->

      <xsl:if test="count(Menu) > 0">
        <ul>
        <xsl:call-template name="MenuListing" />
        </ul>
      </xsl:if>
    </li>
  </xsl:template>
</xsl:stylesheet>

The XSLT code will do the following
1.Find the root Node Called Menus and convert it to ul tags with 2 attributes class name and id (class will be used by SooperFish PlugIn and ID important for stylesheet).
2.Call MenuListing Template for nested or children Menu
3.Find the node Called Menu and convert it to li and a html tags with href attribute for a tag with Name or title (the value of href attribute come from Url node and same thing with title for a).
4.Recursively call MenuListing for child menu node but the most important thing we add <ul> tag before Calling MenuListing Template
Now the result will be as following

<ul class="sf-menu" id="nav">
      <li>
          <a href="#">Products</a>
            <ul>
             <li>
              <a href="#">Office</a>
            <ul>
                 <li>
                   <a href="#">Offiice2003</a>
                 </li>
                 <li>
                   <a href="#">Office2007</a>
                 </li>
                  <li>
                   <a href="#">Office2010</a>
                  </li>
           </ul>
     </li>
....
....
</ul>

Step 4 – Convert XML to HTML using XSLT in ASP.NET


To apply XSLT transformation we need an XML data returned by the  GenertateXmlFormat() Method also we need an XSLT file after that we will convert XML TO HTML Format and return the new format as string

public string ExecuteXSLTransformation()
    {
        string HtmlTags,XsltPath;
        MemoryStream DataStream = default(MemoryStream);
        StreamReader streamReader = default(StreamReader);

        try
        {
            //Path of XSLT file
            XsltPath = HttpContext.Current.Server.MapPath("XsltFormatFolder/TransformXSLT.xsl");

            //Encode all Xml format string to bytes
            byte[] bytes = Encoding.ASCII.GetBytes(GenerateXmlFormat());

            DataStream = new MemoryStream(bytes);

            //Create Xmlreader from memory stream

            XmlReader reader = XmlReader.Create(DataStream);

            // Load the XML
            XPathDocument document = new XPathDocument(reader);

            XslCompiledTransform XsltFormat = new XslCompiledTransform();

            // Load the style sheet.
            XsltFormat.Load(XsltPath);

            DataStream = new MemoryStream();

            XmlTextWriter writer = new XmlTextWriter(DataStream, Encoding.ASCII);

            //Apply transformation from xml format to html format and save it in xmltextwriter
            XsltFormat.Transform(document, writer);

            streamReader = new StreamReader(DataStream);

            DataStream.Position = 0;

            HtmlTags = streamReader.ReadToEnd();

            return HtmlTags;
        }
        catch (Exception ex)
        {
            ErrorMsg = ex.Message;
            return ErrorMsg;
        }
        finally
        {
            //Release the resources

            streamReader.Close();

            DataStream.Close();
        }

    }

Step 5 –Tied everything together


We are now in the last step ,we need just to add new aspx page and add the necessary jquery files including SooperFish Plugin  and style sheet  files as following

<link rel="stylesheet" type="text/css" href="Styles/sooperfish.css" media="screen"/>

<link rel="stylesheet" type="text/css" href="Styles/sooperfish-theme-large.css" media="screen"/>

<script type="text/javascript" src="Jquery/jquery-1.4.2.min.js"></script>

<script type="text/javascript" src="Jquery/jquery.easing-sooper.js"></script>

<script type="text/javascript" src="Jquery/jquery.sooperfish.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('ul.sf-menu').sooperfish();
        });
    </script>

After that add Literal control in your page and assign html format programmatically Page_Load as following

if (!IsPostBack)
 {
 SooperFish spoorfishMenu = new SooperFish();
 Literal1.Text = spoorfishMenu.ExecuteXSLTransformation();
 }

Advance SooperFish effects


SooperFish Allow you to animate your menu in many different ways see the following code

<script type="text/javascript">
    $(document).ready(function() {
      $('ul.sf-menu').sooperfish({
    dualColumn  : 6, //if a submenu has at least this many items it will be divided in 2 columns
    tripleColumn  : 8, //if a submenu has at least this many items it will be divided in 3 columns
    hoverClass  : 'sfHover',
    delay    : 500, //make sure menus only disappear when intended, 500ms is advised by Jacob Nielsen
    animationShow  : {width:'show',height:'show',opacity:'show'},
    speedShow    : 750,
    easingShow      : 'easeOutBounce',
    animationHide  : {width:'hide',height:'hide',opacity:'hide'},
    speedHide    : 300,
    easingHide      : 'easeInOvershoot',
    autoArrows  : true
      });
    });
    </script>

aslo when you download the plugin files you will find two more stylsheet with some html pages show you some other effects

Note : you can know more about SooperFish here SooperFish Multi-Column Animated Drop-down

Download

AspSooperFish

Summary

This article show you how to build nice menus using SooperFish Jequery Plugin instead of using normal asp.net menu which generate table tags .All you have to do is create self-join table and generate xml using DataSet() after that convert it to html (ul,li and a) tags using XSLT.

Fill free to tell me about  AspSooperFishMenu

References

Building a Database Driven Hierarchical Menu using ASP.NET 2.0

What Is XSLT?

 
38 Comments

Posted by on September 14, 2010 in ASP.NET

 

Tags: , , , , , , ,

Creating Custom Timer Job in SharePoint 2010


In this post I will show you how to create Custom Timer Job in SharePoint 2010 but you must know this post is based on Creating Custom SharePoint Timer Jobs ,
Update [12/11/2011]
[
You can download the source code of this article from the following code (Please do not forget to rate it)
You do not need any things else just open it in Visual Studio 2010 and deploy it.That’s all
]
So let us start
Create Custom List and name it  ListTimerJob
Open Visual Studio 2010 >File > New >Project >SharePoint 2010>Empty SharePoint Project. >Name it Custom_TimerJob>Ok

Check Deploy as farm solution>Finish

create a class that inherits from the Microsoft.SharePoint.Administration.SPJobDefinition class. To implement this class, you need to create a few constructors and override the Execute() method as following
namespace DotnetFinder
{
    class ListTimerJob : SPJobDefinition
    {
         public ListTimerJob()

            : base()
        {

        }

        public ListTimerJob(string jobName, SPService service, SPServer server, SPJobLockType targetType)

            : base(jobName, service, server, targetType)
        {

        }

        public ListTimerJob(string jobName, SPWebApplication webApplication)

            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {

            this.Title = "List Timer Job";

        }

        public override void Execute(Guid contentDbId)
        {

            // get a reference to the current site collection's content database

            SPWebApplication webApplication = this.Parent as SPWebApplication;

            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database

            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];

            // create a new list Item, set the Title to the current day/time, and update the item

            SPListItem newList = Listjob.Items.Add();

            newList["Title"] = DateTime.Now.ToString();

            newList.Update();

        }
}
}

As you can see this job just add a new item to a ListTimerJob list every time it’s executed

Now that you have the job built> Right click on the Features >Add Feature

Right click on the Feature1 ” you can rename the Feature1 to any name” > Add Event Receiver

As you can see the event Receiver class inherits from the Microsoft.SharePoint.SPFeatureReceiver and This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade. But we only need FeatureActivated & FeatureDeactivated event handler to install/uninstall our custom timer job as following

namespace DotnetFinder.Features.Feature1
{
[Guid("9a724fdb-e423-4232-9626-0cffc53fb74b")]
public class Feature1EventReceiver : SPFeatureReceiver
    {
        const string List_JOB_NAME = "ListLogger";
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // make sure the job isn't already registered

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {

                if (job.Name == List_JOB_NAME)

                    job.Delete();

            }

            // install the job

            ListTimerJob listLoggerJob = new ListTimerJob(List_JOB_NAME, site.WebApplication);

            SPMinuteSchedule schedule = new SPMinuteSchedule();

            schedule.BeginSecond = 0;

            schedule.EndSecond = 59;

            schedule.Interval = 5;

            listLoggerJob.Schedule = schedule;

            listLoggerJob.Update();

        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            // delete the job

            foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
            {

                if (job.Name == List_JOB_NAME)

                    job.Delete();

            }

}

   }

Before Deploying you should select the right scope of the Feature in other words in which scope you will activate the Feature(Farm,Site,Web,WebApplication) in our case we will activate Feature1 on Site which is mean Site Collection.

Note : if you trying to activate the feature in the wrong scope will get the following error

Now let us deploy our custom timer job >Right Click on Custom_TimerJob project > Click Deploy

Open now your SharePoint site and select ListTimerJob List and you should see something similar to the following image


Our custom timer job is working fine now you can go and check it and modify the schedule as following
Go to SharePoint 2010 central administration >Monitoring >in the Timer Jobs Section Select Review Job Definitions
and you should See our Custom Timer Job

Click on it and you should see Edit Timer Job Page ,Modify Timer Job schedule based on your requirement
Note : you can also modify schedule of your custom Timer Job from the code but you need to add one of the following class in FeatureActviated Event Handler as following

After Specific Minutes use SPMinuteSchedule class
Hourly use SPHourlySchedule class
Daily use SPDailySchedule class
Weekly use SPWeeklySchedule class
Monthly use SPMonthlySchedule class

Updated [ 8/10/2011]
References
Regards.
 
139 Comments

Posted by on July 24, 2010 in SharePoint

 

Tags: , , , , , ,