Tuesday, April 23, 2013

WCF with REST


What is REST

“Representational State Transfer”. RESTS highlight things like separation of concerns and layers, statelessness, and caching. Using REST, you can get those benefits interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."
REST usage is different than the normal WSDL based SOAP web service usage. Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style such as JSON.
REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource
What is the Key benefits using REST
·         Reduce the overhead.
·         Less duplication
·         Standardized
·         Great Readability
Let’s Create Restful WCF Service
First open the Visual Studio and create a new WCF Service Application


You can view the file hierarchy as below. Highlighted files are Service file and Interface file.




You can remove the default Service file or you can add your own WCF Service file.



After that, you can define the required service method definition in Service interface as follows.



You have two different methods, one method will return as xml format and other will return as json.

[OperationContract]
        [WebInvoke(Method="Get",ResponseFormat =WebMessageFormat.Xml,
        BodyStyle=WebMessageBodyStyle.Wrapped,UriTemplate="xml/{id}")]
        string GetNamexml(string _id);

        [OperationContract]
        [WebInvoke(Method = "Get", ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}")]
        string GetNamejson(string _id);

 
You can pass multiple parameters as follows,
[OperationContract]
[WebInvoke(Method = "Post", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "json/{id}/{name}/{address}")]
string SaveDatajson(string _id,string _name,string _address);

Now you are going to implement the Service method in your WCF Service file.

public class SampleRest : ISampleRest
    {

        public string GetNamexml(string _id)
        {
            return "This is my Xml type result " + _id; 
        }

        public string GetNamejson(string _id)
        {
            return "This is my json type result " + _id; 
        }


        public string SaveDatajson(string _id, string _name, string _address)
        {
           //save data to db
            return "ok";
        }
    }





Sunday, December 23, 2012

How to Convert Your Winform as PDF Report

First you have to download the pdfSharp dll from sourceforge and add as a reference DLL to your desired project. Main objective of this solution is to overcome the complexity of building runtime complex reports and developer has a liberty to make her/his own design for the report.One more thing,no need to make the merge modules such as crystal and other reports.



Screen Capturing Class 

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace SyncClient.Reports
{
    public enum CaptureMode
    {
        Screen, Window
    }

    public class ScreenCapture
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

        [StructLayout(LayoutKind.Sequential)]
        private struct Rect
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetDesktopWindow();

        /// Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file. 
        /// Filename.
        /// * If extension is omitted, it's calculated from the type of file
        /// * If path is omitted, defaults to %TEMP%
        /// * Use %NOW% to put a timestamp in the filename
        /// Optional. The default value is CaptureMode.Window.
        /// Optional file save mode.  Default is PNG
        public void CaptureAndSave(string filename, CaptureMode mode, ImageFormat format)
        {
            mode = CaptureMode.Window;
            format = null;
            ImageSave(filename, format, Capture(mode));
        }

        /// Capture a specific window (or control) and save it to a specified file. 
        /// Filename.
        /// * If extension is omitted, it's calculated from the type of file
        /// * If path is omitted, defaults to %TEMP%
        /// * Use %NOW% to put a timestamp in the filename
        /// hWnd (handle) of the window to capture
        /// Optional file save mode.  Default is PNG
        public void CaptureAndSave(string filename, IntPtr handle, ImageFormat format)
        {
            format = null;
            ImageSave(filename, format, Capture(handle));
        }

        /// Capture a specific window (or control) and save it to a specified file. 
        /// Filename.
        /// * If extension is omitted, it's calculated from the type of file
        /// * If path is omitted, defaults to %TEMP%
        /// * Use %NOW% to put a timestamp in the filename
        /// Object to capture
        /// Optional file save mode.  Default is PNG
        public void CaptureAndSave(string filename, Control c, ImageFormat format)
        {
            format = null;
            ImageSave(filename, format, Capture(c));
        }
        /// Capture the active window (default) or the desktop and return it as a bitmap
        /// Optional. The default value is CaptureMode.Window.
        public Bitmap Capture(CaptureMode mode)
        {
            mode = CaptureMode.Window;
            return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());
        }

        /// Capture a .NET Control, Form, UserControl, etc.
        /// Object to capture
        /// Bitmap of control's area
        public Bitmap Capture(Control c)
        {
            return Capture(c.Handle);
        }


        /// Capture a specific window and return it as a bitmap
        /// hWnd (handle) of the window to capture
        public Bitmap Capture(IntPtr handle)
        {
            Rectangle bounds;
            Rect rect = new Rect();
            GetWindowRect(handle, ref rect);
            bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
            CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);

            Bitmap result = new Bitmap(bounds.Width, bounds.Height);
            using (Graphics g = Graphics.FromImage(result))
                g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);

            return result;
        }

        /// Position of the cursor relative to the start of the capture

        public Point CursorPosition;


        /// Save an image to a specific file
        /// Filename.
        /// * If extension is omitted, it's calculated from the type of file
        /// * If path is omitted, defaults to %TEMP%
        /// * Use %NOW% to put a timestamp in the filename
        /// Optional file save mode.  Default is PNG
        /// Image to save.  Usually a BitMap, but can be any
        /// Image.
        void ImageSave(string filename, ImageFormat format, Image image)
        {
            format = format ?? ImageFormat.Png;
            if (!filename.Contains("."))
                filename = filename.Trim() + "." + format.ToString().ToLower();

            if (!filename.Contains(@"\"))
                filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);

            filename = filename.Replace("%NOW%", DateTime.Now.ToString("yyyy-MM-dd@hh.mm.ss"));
            image.Save(filename, format);
        }
    }
}




Reference Form 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.IO;

namespace SyncClient.Reports
{
    public partial class AdvanceReport : Form
    {

        ScreenCapture capScreen = new ScreenCapture();
        public string  ISBN { get; set; }
        public string  Dept { get; set; }
        public string  Cat { get; set; }
        public string  Imprint { get; set; }
        public string  Binding { get; set; }
        public string  NoofPages { get; set; }
        public string  RetailPrice { get; set; }
        public string  CoverImage { get; set; }
        public string  Title { get; set; }
        public string  Auth { get; set; }
        public string  AuthInfo { get; set; }

        public AdvanceReport()
        {
            InitializeComponent();
        }

        private void AdvanceReport_Load(object sender, EventArgs e)
        {
            lblisbn.Text = ISBN;
            lblDept.Text = Dept;
            lblCat.Text = Cat;
            lblimprint.Text = Imprint;
            lblbinding.Text = Binding;
            lblnopage.Text = NoofPages;
            lblRetprice.Text = RetailPrice;
            lbltitle.Text = Title;
            lblauth.Text = " By " + Auth;
            txtAuthInfo.Text = AuthInfo;
            //txtHide.Focus(); 
            try
            {
                imgcover.BackgroundImage = Image.FromFile(CoverImage);  
            }
            catch (FileNotFoundException err)
            {
           
            }

          

        }

        private void MakeReport()
        {

            capScreen.CaptureAndSave(@"C:\tempImage\test.png", CaptureMode.Window, ImageFormat.Png);
            // Create new pdf document and page
            
            PdfDocument doc = new PdfDocument();
            PdfPage oPage = new PdfPage();

            // Add the page to the pdf document and add the captured image to it
            doc.Pages.Add(oPage);
            XGraphics xgr = XGraphics.FromPdfPage(oPage);
            XImage img = XImage.FromFile(@"C:\tempImage\test.png");
            xgr.DrawImage(img, 0, 0);

            saveFileDialog.Filter = ("PDF File|*.pdf");
            DialogResult btnSave = saveFileDialog.ShowDialog();
            if (btnSave.Equals(DialogResult.OK))
            {
                doc.Save(saveFileDialog.FileName);
                doc.Close();
            }

            // I used the Dispose() function to be able to
            // save the same form again, in case some values have changed.
            // When I didn't use the function, an GDI+ error occurred.
            img.Dispose();

       
        }

        private void AdvanceReport_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar.ToString().ToUpper() == "P")
            {
                MakeReport();
            }
            else if (e.KeyChar.ToString().ToUpper() == "C")
            {
                this.Close(); 
            }
        }

    }
}






Sample



Sunday, April 24, 2011

Generate Http Request through SQLserver 2008 R2 Proc

This Article has used to execute/visit the http request via Sqlserver 2008 R2 stored proc.Sometimes we need to call some external WS service/Http Url inside the backend objects.I think this will helpfull to resolve this kind of queries.

Before the creation we nedd to Grant permision to following system object under desired sqlserver user.

sp_OASetProperty
sp_OAMethod
sp_OAGetErrorInfo
sp_OADestroy
sp_OAStop
sp_OACreate
sp_OAGetProperty

Sqlserver Stored Procedure

Create procedure [dbo].[HTTP_DB_ALERT]( @sUrl varchar(2000), @response varchar(8000)
out)
As
Declare
@obj int
,@hr int
,@status int
,@msg varchar(255)


exec @hr = sp_OACreate 'MSXML2.ServerXMLHttp', @obj OUT
if @hr <> 0 begin Raiserror('sp_OACreate MSXML2.ServerXMLHttp.3.0
failed', 16,1) return end

exec @hr = sp_OAMethod @obj, 'open', NULL, 'POST', @sUrl, false
if @hr <>0 begin set @msg = 'sp_OAMethod Open failed' goto eh end

exec @hr = sp_OAMethod @obj, 'setRequestHeader', NULL, 'Content-Type',
'application/x-www-form-urlencoded'
if @hr <>0 begin set @msg = 'sp_OAMethod setRequestHeader failed' goto
eh end

exec @hr = sp_OAMethod @obj, send, NULL, ''
if @hr <>0 begin set @msg = 'sp_OAMethod Send failed' goto eh end

exec @hr = sp_OAGetProperty @obj, 'status', @status OUT
if @hr <>0 begin set @msg = 'sp_OAMethod read status failed' goto
eh
end

if @status <> 200 begin set @msg = 'sp_OAMethod http status ' +
str(@status) goto eh end

exec @hr = sp_OAGetProperty @obj, 'responseText', @response OUT
if @hr <>0 begin set @msg = 'sp_OAMethod read response failed' goto
eh end

exec @hr = sp_OADestroy @obj
return
eh:
exec @hr = sp_OADestroy @obj
Raiserror(@msg, 16, 1)
return

Thursday, March 18, 2010

XML Explicit Serialization

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Data.SqlTypes;
using DataAccessLayer;


namespace BusinessLayer
{
public class clsSalesHistory
{
public Messagers.Response TransferData(string strShop_ID,string strShop_Group_ID,string strSan_ID,string[] strISBN, double[] dUnit_Price, double[] dCost_Price,
double[] dSelling_Price,double[] dRR_Price,double[] dDiscount,double[] dSales_Tax,double[] dQuantity_Sold)
{
string strXML;
SqlParameter Param;
List ParamCollection = new List();
UTF8Encoding encoding = new UTF8Encoding();
MemoryStream mem = new MemoryStream();
XmlTextWriter xWriter = new XmlTextWriter(mem, Encoding.UTF8);

xWriter.Formatting = Formatting.Indented;
xWriter.WriteProcessingInstruction("xml", "version=\"1.0\" ");

GenerateInfo[] PassCollect = new GenerateInfo[strISBN.Length];

clsDbConnectivity objDataAccess = new clsDbConnectivity();

Messagers.Response objResponse = new BusinessLayer.Messagers.Response();

try
{
for (int i = 0; i <= strISBN.Length - 1; i++)
{
PassCollect[i].ISBN = strISBN[i];
PassCollect[i].Unit_Price = dUnit_Price[i];
PassCollect[i].Cost_Price = dCost_Price[i];
PassCollect[i].Selling_Price = dSelling_Price[i];
PassCollect[i].RR_Price = dRR_Price[i];
PassCollect[i].Discount = dDiscount[i];
PassCollect[i].Sales_Tax = dSales_Tax[i];
PassCollect[i].Quantity_Sold = dQuantity_Sold[i];

}

XmlSerializer xSerializer = new XmlSerializer(typeof(GenerateInfo[]));
XmlSerializerNamespaces xSeNameSpace = new XmlSerializerNamespaces();
xSeNameSpace.Add(string.Empty, string.Empty);

xSerializer.Serialize(xWriter, PassCollect,xSeNameSpace);
mem = (MemoryStream)xWriter.BaseStream;
strXML = encoding.GetString(mem.ToArray());
mem.Close();

Param = new SqlParameter("@vcShop_ID", SqlDbType.VarChar, 100);
Param.Value =strShop_ID;
ParamCollection.Add(Param);

Param = new SqlParameter("@vcShop_Group_ID", SqlDbType.VarChar, 100);
Param.Value =strShop_Group_ID;
ParamCollection.Add(Param);

Param = new SqlParameter("@vcSan_ID", SqlDbType.VarChar, 100);
Param.Value =strSan_ID;
ParamCollection.Add(Param);

Param = new SqlParameter("@xmlParam", SqlDbType.NText);
Param.Value = strXML;
ParamCollection.Add(Param);

objDataAccess.CommandName = "spSaveSalesBulkInfo";
objDataAccess.CommandParamCollection = ParamCollection;


if (objDataAccess.ExecuteSqlCommand())
{
objResponse.Acknowledgment = true;
}
else
{
objResponse.Acknowledgment = false;
}
}
catch
{
objResponse.Acknowledgment = false;
objResponse.AckMessage = objDataAccess.AcknowledgmentMsg;
}

return objResponse;

}


public struct GenerateInfo
{
public string ISBN;
public double Unit_Price;
public double Cost_Price;
public double Selling_Price;
public double RR_Price;
public double Discount;
public double Sales_Tax;
public double Quantity_Sold;

}


}

Calling SSL Enable URL using UTL_HTTP Package in Oracle

To access an SSL website using the utl_http package and PL/SQL is easy once you come to grips with the concept of a Wallet. The wallet stores all the encryption keys that the database needs to access the SSL site. But before looking at wallet config, lets review the PL/SQL code:

1. Declare some variables:req utl_http.req;resp utl_http.resp;rw varchar2(32767);

2. Define the location of the wallet:

UTL_HTTP.SET_WALLET ( 'file:' 'p:\wallet', 'mypassword' );

Where 'file:' is they keyword to state that the wallet is a file. 'p:\wallet' is the windows directory of the wallet. For unix, this might be '/u01/wallet'. 'mypassword' is the password required to open the wallet.

The disadvantage is that the password to the wallet is stored in clear text. Its recommended then that you create a wallet that only contains public keys from SSL sites, information which is publically available and will not pose a security risk.

You can store multiple wallets in different locations if you are paranoid about security.The disadvantage of wallets is that you need to know in advance each SSL site you will be accessing and extract its public key certificate. This isn't as flexible as a web browser, which does this for you.

3. Now access the SSL site. There are lots of ways of doing this, the following is just one:

req := utl_http.begin_request( 'https://www.amazon.com');
utl_http.set_header(req, 'User-Agent', 'Mozilla/4.0');
resp := utl_http.get_response(req);

4. And then you can process the data that comes back using a simple loop:
loopbegin rw := null;
utl_http.read_line(resp, rw, TRUE); -- process rwexception when others then exit;end;end loop;
utl_http.end_response(resp);

5. To configure the wallet go into IE and retrieve the certificate of the SSL site (haven't been able to do this in firefox yet, which shows you that IE still has some uses).You can either click on the certificate icon if it appears, or go to file-properties and retrieve it as follows.

And then choose the Base-64 encoded option to save it. Save it to a local directory.Keep in mind the SSL certificates can be hierarchical, in that the certification of a site might be dependent on its parent (authorising) site also approving it.So it might require extracting a couple of certificates to correctly authorise a site.Once saved, create an Oracle wallet. There are similar options to the ones shown below in Linux and even if you only have apache installed. The java program is called: owm.cl

as p:\wallet (or whatever directory is suitable for your database). Remember that the database has to be able to access the wallet, not your computer. So its best located on the same server as the database.

Then import the certificate you have just created

directory as the wallet, so I have a physical trail of all the certificates.Don't forget to save the wallet. You will find that the program creates an ewallet.p12 file in the directory. Leave it as is, this is an important file.

The certificate is now installed. Your PL/SQL program can now access the SSL site

Friday, May 15, 2009

Distributed Transaction(DTC) using .Net

Add the below reference to the disired Project
System.Transactions

(Using is key word in C# it'll release to garbage collection after usage)


private void button1_Click(object sender, EventArgs e)
{
using (TransactionScope objScope = new TransactionScope())
{
string conString1 = "Data Source=sfa_dev;Persist Security Info=True;User ID=ez;Password=ez;Unicode=True";
string conString2 = "Data Source=CHANDIMA\\SQLEXPRESS;Initial Catalog=Exam;Integrated Security=True";
using (OracleConnection Con1 = new OracleConnection(conString1))
{
OracleCommand ocmd = new OracleCommand();
ocmd.CommandText ="Insert into dtctest values (1,'Test Adddress')";
Con1.Open();
ocmd.ExecuteNonQuery();
Con1.Close();
}
using(SqlConnection con2=new SqlConnection(conString2))
{
SqlCommand scmd=new SqlCommand();
scmd.CommandText ="Insert into tbl_Student values (3,'chandima W','Test Add1',1,'~/Test')";
con2.Open();
scmd.ExecuteNonQuery();
con2.Close();
}
objScope.Complete();
}
}

Wednesday, May 6, 2009

Pass Data in Compression and Decompression Mode

Compression

private byte[] ConvertToStram(DataSet ds)
{
MemoryStream memStream = new MemoryStream();
GZipStream zipStream = new GZipStream(memStream, CompressionMode.Compress);
ds.WriteXml(zipStream, XmlWriteMode.WriteSchema);
zipStream.Close();
byte[] data = memStream.ToArray();
memStream.Close();
ds.Dispose();
return data;
}

Decmpression

public DataSet ConvertStreamToDS(byte[] DataInfo)
{
MemoryStream memStream = new MemoryStream(DataInfo);
GZipStream unzipStream = new GZipStream(memStream, CompressionMode.Decompress);
DataSet ds = new DataSet();
ds.ReadXml(unzipStream);
memStream.Close();
unzipStream.Close();
return ds;
}