Saturday, 13 July 2013

Walkthrough: Getting Started with WCF

You can see lot of wcf uses and definition in the online, here I am not going to say anything about that a simple example how to write wcf service.

Follow the below instruction and images to write a simple wcf service and hosting it and calling in client.

Step .1 Creating WCF Application


  • Open visual studio and create new wcf project as shown

  • In the Iservice.cs interface add the below [Operation Contracts] declaration as below.




  • In the service.cs file add the definition for the [Operation Contracts]. Here I am doing some arithmetic operations like adding, sub ration, multiplying and dividing.


  • Now right click in the app.config and click on the 'Edit WCF Configuration' .


  • A WCF Editor window will appear and default the endpoints will be 'http' there are many end points in wcf, you can see that by Binding row. Here we are going have net.tcp binding to do that expand service tree and then your project tree and then click on the end point 1 and change as below image.

  • Then click on the end point 2 and change the binding row as 'mex tcp binding'

  • Now expand the advance node and make http enable as false from the service behavior meta data like below.

  • Now change the URL from 'Http' to 'TCP' url like below image.

  • Save the window and close now open your app.config it will be like below. note if you change the class names in the application it should changes in your app.config file also


  • Now Run your WCF application you will see the running notification like below.



    • Now you will see a window like below which has all the function you have written. you can test the function like below.


    Step. 2 Hosting The WCF Application in Windows Services

    • Add New Windows Service Project.

    • In windows service click on the Service.cs file and add installer then you will see project installer file with serviceprocessinstaller1 and serviceprocessor. change the property of serviceprocessorinstaller1 Account to 'NetworkService'. refer below images.



    • Now Refer the WCF Project to your window service and system.servicemodel under reference in your application like below image.




    • Now add using system.servicemodel in you service.cs code behind. and command the codes in the program.cs file and create your service.cs like below images. this code will start the wcf service which we refer in the windows service.


    • Now our WCF host is ready.
    Step .3 Create Installer for WCF Host

    • Add new Setup Project like below and refer our wcf host windows service to it..Add Primary output and custom action. follow below image to do that.







    • Now Right click on the Setup Project and click on the 'Install' then follow the install instruction and complete the installation.

    • Now go to service.msc and start the window service normally it will be service.1 if you didn't change the service name and right clikc on it and start now our wcf service starts.
    Step. 4 Creating Client application calling the WCF service

    • Create any client application and here I have created winform application with client window like below.

    • Now add Service Reference using the URL we provided in WCF application. follow the below images.


    • Now call your wcf service function like below code behind here I added on all button click.




    • Test Your application.


    • .Cheers ;-)
    Thus you created a WCF service using net.tcp protocol.



    Tuesday, 14 May 2013

    WPF - Tab Control - Selected Tab Item Header To Bold


    private void tabControl1_SelectionChanged_1(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
                try
                {
                    for (int i = 0; i <= 3; i++)
                    {
                        System.Windows.Controls.TabItem tab1 = tabControl1.Items.GetItemAt(i) as System.Windows.Controls.TabItem;
                        tab1.FontWeight = FontWeights.Normal;
                    }

                    System.Windows.Controls.TabItem tab = tabControl1.SelectedItem as System.Windows.Controls.TabItem;

                    tab.FontWeight = FontWeights.Bold;
                }
                catch (Exception)
                {
                }
            }

    Wednesday, 1 May 2013

    Print Datagridview in WinForms - VB.Net,Multiple page,Landscape.

    Result 

    Overview
    1.  This post help to print data from datagridview.
    2.  Landscape,A4,Multiple page,no of copies are available.
    3.  'dgDatagrid' is datagridview name.
    Code With Explanation

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
            'Creating PrintDocument
            Dim gridViewDoc As New Printing.PrintDocument
            'Adding Custom Print event
            AddHandler gridViewDoc.PrintPage, AddressOf GridView_Print
            'Setting Number of copies
            gridViewDoc.PrinterSettings.Copies = 2
            'Setting Landscape mode
            gridViewDoc.DefaultPageSettings.Landscape = True
            'Invoke event 
            gridViewDoc.Print()
      End Sub

        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            connectionString = "Data Source=servername; Initial Catalog=databasename; User ID=sa; Password=password"
            cnn = New SqlConnection(connectionString)
            cnn.Open()
            sqlAdp = New SqlDataAdapter("SELECT *  FROM [RamTables].[dbo].[StudentDetails]", cnn)
            cnn.Close()

            sqlAdp.Fill(ds)

            dgDatagrid.DataSource = ds.Tables(0)
        End Sub


        Private Sub GridView_Print(ByVal sender As Object, ByVal e As PrintPageEventArgs)
            'Calling the methodw with graphic to draw lines and string which looks like table
            PrintGridView(e.Graphics)
            'For Printing more pages if e.Morepages = true this method will start creating new pages
            If printPending = True Then
                e.HasMorePages = True
            Else
                e.HasMorePages = False
            End If
        End Sub


        Private Sub PrintGridView(ByVal print As Graphics)
            'To fill backgroud of header
            FillHeaders(print)
            'To create header row
            DataGridViewHeader(print)
            'To create all row in datagrid
            DataGridViewRow(print)
            'To draw a border for the table
            DataGridViewBox(print)
        End Sub

        Private Sub FillHeaders(ByVal print As Graphics)
            'draw a rectangle with gray background to attach in header row
            Dim rectangle As New Rectangle(CInt(12.5), dgDatagrid.Top + 50, CInt(dgDatagrid.Width * 1.367),   CInt(dgDatagrid.Rows(0).Height - 4.3))
            Dim brush As New SolidBrush(Color.LightGray)
            print.FillRectangle(brush, rectangle)
        End Sub

        Private Sub DataGridViewHeader(ByVal print As Graphics)
            Dim cellText As String = String.Empty
            Dim startTop As Integer = dgDatagrid.Top + 50
            Dim title As String = String.Empty
            Dim printfont As New Font(New FontFamily("Arial"), 7, FontStyle.Bold)
            Dim titlefont As New Font(New FontFamily("Arial"), 12, FontStyle.Bold)
            Dim colIndex As Integer = 0
            Dim startLeft As Integer = 12
            Dim center As Integer
            Dim size As SizeF
            Dim headerWidth As Integer
            title = "List Of Subscribers"
            print.DrawString(title, titlefont, Brushes.Black, 310, 8)
            For Each printcolumn As DataGridViewColumn In dgDatagrid.Columns
                'Read the header column text and calculate the centre position of teh cell and write it
                Using measure As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
                    size = measure.MeasureString(dgDatagrid.Columns(colIndex).HeaderText, New Font("Arial", 10, FontStyle.Regular, GraphicsUnit.Point))
                End Using
                headerWidth = CInt(Math.Floor(Convert.ToDecimal(CType(size.Width, String), CultureInfo.CurrentCulture)))
                For calculate As Integer = 0 To dgDatagrid.Columns(colIndex).Width
                    Dim firsthalf As Integer = calculate
                    Dim secondhalf As Integer = dgDatagrid.Columns(colIndex).Width - (calculate + headerWidth)
                    If firsthalf = secondhalf Then
                        center = calculate
                        Exit For
                    ElseIf (firsthalf = secondhalf - 1) Then
                        center = calculate
                        Exit For
                    End If
                Next
                startLeft = CInt(startLeft * 1.1)
                cellText = printcolumn.HeaderText
                'Write the header text
                print.DrawString(cellText, printfont, Brushes.Black, startLeft + center, startTop + 5)
                'Draw line that seprate each column
                print.DrawLine(Pens.Black, startLeft, startTop, startLeft, startTop + CInt(dgDatagrid.Rows(0).Height - 4.3))
                startLeft += dgDatagrid.Columns(colIndex).Width - 20
                colIndex += 1
            Next
            'Draw line that seprate each row
            print.DrawLine(Pens.Black, 13, startTop + CInt(dgDatagrid.Rows(0).Height - 4.3), CInt(dgDatagrid.Width * 1.4), CInt(startTop + dgDatagrid.Rows(0).Height - 4.3))
        End Sub



        Private Sub DataGridViewRow(ByVal print As Graphics)
            Dim rowIndex As Integer = 1
            Dim printFont As New Font(New FontFamily("Arial"), 7, FontStyle.Bold)
            While printPending = True
                'Get each cell text in row and write it as in grid
                For pointedIndex = pointedIndex To dgDatagrid.Rows.Count - 1
                    Dim starttop As Integer = dgDatagrid.Top + CInt(rowIndex * (dgDatagrid.Rows(pointedIndex).Height - 4.3)) + 50
                    Dim colIndex As Integer = 0
                    Dim startLeft As Integer = 12

                    For Each printCell As DataGridViewCell In dgDatagrid.Rows(pointedIndex).Cells
                        startLeft = CInt(startLeft * 1.1)
                        Dim cellText As String = String.Empty
                        If (Not IsDBNull(printCell.Value)) Then cellText = CStr(printCell.Value)
                        print.DrawString(cellText, printFont, Brushes.Black, startLeft, starttop + 5)
                        print.DrawLine(Pens.Black, startLeft, starttop, startLeft, starttop + CInt(dgDatagrid.Rows(pointedIndex).Height - 4.3))
                        startLeft += dgDatagrid.Columns(colIndex).Width - 20
                        colIndex += 1
                    Next
                    print.DrawLine(Pens.Black, 12, starttop + CInt(dgDatagrid.Rows(pointedIndex).Height - 4.3), CInt(dgDatagrid.Width * 1.4), starttop + CInt(dgDatagrid.Rows(pointedIndex).Height - 4.3))
                    rowIndex += 1
                    rowInPage = rowIndex
                    'Exit when 20 rows is written, so that we can have 20 row in each page  
                    If rowIndex = 20 Then
                        pointedIndex = pointedIndex + 1
                        Exit While
                    End If
                    'If still data is pending to print keep printPrinting variable as false so that other data can come in next page
                    If pointedIndex = dgDatagrid.Rows.Count - 1 Then
                        printPending = False
                    End If
                Next
            End While
        End Sub

        Private Sub DataGridViewBox(ByVal print As Graphics)
            'Draw a rectangle border for the  lines so that it forms a table
            Dim gridviewRect As New Rectangle(CInt(12.5), dgDatagrid.Top + 50, CInt(dgDatagrid.Width * 1.368), CInt((dgDatagrid.Rows(0).Height - 4.3) * rowInPage))
            print.DrawRectangle(Pens.Black, gridviewRect)
        End Sub

    Thursday, 11 April 2013

    SSRS - Stacked Column Chart With Positive and Negative values


    Data-set for Graph(Inputs)

                                  

    Result



    Solution

    Step 1.
    •  Add new SSRS project
    • Right click on the Report then click -> Insert - > chart below screen will appear

    • Click on the stacked column chart and click on
    • Cancel if datasource screen appears
    • You chart will look like below
                                                 


    Step 2

    • Edit your data source add two column with logic of positive and negative value with center x axis value. for example see below query for this post
                                         

    • Now your dataset will look like below with two extra column
                               
    • Follow  below images to add new dataset for your report
                                Right click on the dataset and click on 'Add Dataset'


    Dataset property window will appear click new for add new datasource


    Datasource property window will appear click on edit to provide credentials


    Provide all credential and test the connection


    click ok in connection property and data source property and add the query we created in dataset property window and click on ok


    Now expand the dataset you can see the all columns


    Now right click on the chart and click on property and add the dataset.


    Step 3
    • Click on the '+' in the E values in chart data and add two columns you added like below image



    After adding it will look like below


    • Delete existing in category group and add the x axis column you want.
    Final result will look like below
    if you run your report will look like below
    Step 4

    • click on the Blank column in 'Chart data', open it property and change color to 'No color'

    • Now right click on the another column field and click on the 'series property'

    • Click on the fill and click on the expression


    • The following expression will display "green' for above 50 and 'Red' for below 50


    Step 5
    • Right click on the major line property, A property window will appear like below

    New window will appear and click on 'Grid interval' expression


    Enter 50 to show line on 50 in y axis


    Step 6
    • Now in y axis property make min value as 0 and max as 100 and interval as 10

    • Give title for chart 
    • now run your report will look like below