Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, June 24, 2014

Menggunakan ADO.NET Parameter

Seringkali saya menjumpai developer menggunakan string concatenation seperti ini untuk melakukan query ke database.

conn.Open();
using(var cmd = conn.CreateCommand())
{
  cmd.CommandText = "select * from employee where kode='" + txtUserName.Text + "'";
  var reader = cmd.ExecuteReader();
  if(reader.Read()) 
  {
     //bla bla bla
  }
}
Code di atas (untuk kondisi tertentu) memang dapat dijalankan dengan baik, dan saya akui kadang sayapun melakukan hal tersebut (karena kepepet deadline).

Sebenarnya code di atas punya celah keamanan yang kurang baik, yaitu sangat rentan dengan serangan SQL Injection.  Selain itu code di atas tidak dapat menerima input pada txtUserName.Text yang mengandung single quote.

Saya tidak akan membahas lebih detail tentang SQL Injection di sini, melainkan saya mengajukan solusi untuk menghindari penggunaan string concatenation seperti contoh di atas, yaitu dengan menggunakan ADO.NET Parameter.

 

Keuntungan penggunaan ADO.NET Parameter ini adalah:

1. Code yang kita tulis terbebas dari celah keamanan SQL Injection

2. Input parameter dapat berupa teks yang mengandung single quote (‘) maupun double quote(“).

 

Cara penggunaan ADO.NET Parameter, adalah dengan menggunakan collection property Parameters dari object Command.

Berikut contoh di atas yang ditulis ulang dengan menggunakan ADO.NET Parameter:

 


conn.Open();
using(var cmd = conn.CreateCommand())
{
  cmd.CommandText = "select * from employee where kode=@kodeuser";
  cmd.Parameters.AddWithValue("@kodeuser", txtUserName.Text);
  var reader = cmd.ExecuteReader();
  if(reader.Read())
  {
    // bla bla bla
  }
}

Perhatikan penggunaan method AddWithValue pada contoh di atas:


  1. Parameter pertama dari method tersebut adalah nama parameter yang digunakan di dalam query SQL, dan parameter kedua adalah value yang ingin diberikan ke dalam query.

  2. Setiap parameter di dalam query menggunakan prefix @

Kita dapat memberikan lebih dari 1 parameter dalam sebuah query, asalkan semua nama parameter diawali dengan simbol @.

Sunday, January 5, 2014

Extract PDF file from K2 PDF SmartObject

In K2 workflow, we can create PDF file using PDF SmartObject, located in System node:

image

PDF Converter is a built-in SmartObject in K2 to create PDF and save it in PDF File SmartOject. The PDF is saved as BLOB. Actually it is a column contains XML and in the XML contains PDF as binary content.

The problem is, I have to extract the PDF and copy it to the file server using Windows File Sharing. K2 does not have built-in feature to extract PDF to physical file, thus I have to create it.

The following code utilizes SmartObject Client API to communicate with PDF File SmartObject in K2 Blackpearl server.

   1:  public void ExtractPDFWithSmartObject(int snapshotID, string fileName)
   2:  {
   3:      var smartObjServer = new SmartObjectClientServer();
   4:   
   5:      using (var connection = smartObjServer.CreateConnection())
   6:      {
   7:          connection.Open(k2WorkflowServer);
   8:          //smartObjServer.Connection.Open();
   9:   
  10:          var pdfSmartObj = smartObjServer.GetSmartObject("PDFFile");
  11:          pdfSmartObj.MethodToExecute = "Load";
  12:          pdfSmartObj.Properties["ID"].Value = snapshotID.ToString();
  13:   
  14:          var result = smartObjServer.ExecuteScalar(pdfSmartObj);
  15:          var file = (SmartFileProperty)pdfSmartObj.Properties["PDF"];
  16:          byte[] data = Convert.FromBase64String(file.Content);
  17:          File.WriteAllBytes(fileName, data);
  18:      }
  19:  }



Add reference to SourceCode.HostClientAPI.dll and SourceCode.SmartObjects.Client.dll


Parameter snapshotID is an ID created by Create* method of PDF Converter and parameter fileName is a physical file name to be created in file system.


In line 7, we have to create string variable named k2WorkflowServer, this variable will be populated as connection string to K2 Blackpearl server.


The complete code can be downloaded from here, it is a .NET DLL file and can be referenced from K2 workflow.


 


Call this DLL from K2 Workflow



To use this DLL (PDFHelper.dll), open your K2 workflow (.kprx) using K2 Designer for Visual Studio, add Code Reference Event and add reference to PDFHelper.dll


In Code Reference Event, add call constructor and pass the K2 Connection String as parameter.
image


then call instance method ExtractPDFWithSmartObject and pass snapshot ID and filename as parametersOpen-mouthed smile:


image




Do I have to use Visual Studio to use this DLL in my K2 workflow?


If I use K2 Studio to add reference to this workflow, strangely I cannot call constructor and call instance method, it seems K2 Studio cannot load PDFHelper.dll. But if I use Visual Studio, I can add reference, call constructor, and call instance method smoothly.

Wednesday, November 20, 2013

How to Create CLR Stored Procedure

Since SQL Server 2005, developers can write stored procedures using .NET languages. In this post, I will show you how to create stored procedure using C# using SQL Server 2008 R2 and Visual Studio 2012. If you use newer version of SQL Server, the solution should also be applied. I will create factorial function as applied in Math such as:

5! = 5 * 4 * 3 * 2 * 1 = 12

First, we have to download SQL Server Data Tools (SSDT). At this time of writing, I use SSDT for Visual Studio 2012 October Release which can be downloaded from here.

Then, launch SSDT setup and wait until finished.

Launch Visual Studio 2012, create new project, select SQL Server template, and select SQL Server Database Project.

image

Since I’m using SQL Server 2008R2, I have to change target framework to .NET Framework 3.5. Change the name to SPFaktorial and click OK to create the project, Visual Studio 2012 will create the Database Project for you.

In Solution Explorer, right click in project, click AddNew Item, select SQL CLR C#, then select SQL CLR C# User Defined Function.

image

Change the name to Faktorial and click Add, Visual Studio will create a C# file contains some dummy codes. We can change this code to our factorial function:

   1:  using System;
   2:  using System.Data;
   3:  using System.Data.SqlClient;
   4:  using System.Data.SqlTypes;
   5:  using Microsoft.SqlServer.Server;
   6:   
   7:  public partial class Matematika
   8:  {
   9:      [Microsoft.SqlServer.Server.SqlFunction]
  10:      public static SqlInt64 Faktorial(int f)
  11:      {
  12:          if (f == 1)
  13:              return f;
  14:   
  15:          return f * Faktorial(f - 1);
  16:      }
  17:  }



Our factorial function is a recursive function, it will call itself until the factorial number turns 1.


Let’s build the project! Select Build menu, then select Build Solution. If you see in project folder, Visual Studio will create Debug folder which contains compiled .NET assembly inside.


Actually, we can directly deploy our project to SQL Server, but in this post I will show you how to manually deploy our .NET assembly to SQL Server.


Lets launch the SQL Server Management Studio and connect to the Database Engine and open New Query window, then issue this command:

exec sp_configure 'clr enabled', 1
go
reconfigure
go



The command above will enabling CLR feature (which is disabled by default).


At this point, we are ready to deploy the .NET assembly to SQL Server using CREATE ASSEMBLY:

create assembly SPFaktorial
from 'D:\Docs\visual studio 2012\Projects\SPFaktorial\SPFaktorial\bin\Debug\SPFaktorial.dll'



Press F5 to run the command, then we have to create T-SQL function to wrap the CLR method:

create function Faktorial(@i int) returns bigint
as external name SPFaktorial.Matematika.Faktorial



Press F5 to run the command.


At this point, the .NET assembly has been deployed successfully to SQL Server, the next step is to test it:


image


Voilla….our C# method has been successfully executed inside SQL Server.


The sample code can be downloaded from here.