RSS

Category Archives: VB.NET

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: , , , , , , , ,

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: , , , , , , , , ,