Wednesday, October 31, 2012

MD5Encryption in VB.NET windows application


Imports System.Security.Cryptography
Imports System.Text

Public Class MD5Encryption
    Private EncStringBytes() As Byte
    Private Encoder As New UTF8Encoding
    Private MD5Hasher As New MD5CryptoServiceProvider


    'Encrptes the string in MD5 when passed as a string

    Public Function Encrypt(ByVal EncString As String) As String
        'Variable Declarations

        Dim RanGen As New Random
        Dim RanString As String = ""
        Dim MD5String As String
        Dim RanSaltLoc As String

        'Generates a Random number of under 4 digits

        While RanString.Length <= 3
            RanString = RanString & RanGen.Next(0, 9)
        End While

        'Converts the String to bytes

        EncStringBytes = Encoder.GetBytes(EncString & RanString)

        'Generates the MD5 Byte Array

        EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)

        'Affixing Salt information into the MD5 hash

        MD5String = BitConverter.ToString(EncStringBytes)
        MD5String = MD5String.Replace("-", Nothing)

        'Finds a random location in the string to sit the salt

        RanSaltLoc = CStr(RanGen.Next(4, MD5String.Length))

        'Shoves the salt in the location

        MD5String = MD5String.Insert(CInt(RanSaltLoc), RanString)

        'Adds 0 for values under 10 so we always occupy 2 charater spaces

        If CDbl(RanSaltLoc) < 10 Then
            RanSaltLoc = "0" & RanSaltLoc
        End If

        'Shoves the salt location in the string at position 3

        MD5String = MD5String.Insert(3, RanSaltLoc)

        'Returns the MD5 encrypted string to the calling object

        Return MD5String
    End Function

    'Verifies the String entered matches the MD5 Hash

    Public Function Verify(ByVal S As String, ByVal Hash As String) As Boolean
        'Variable Declarations

        Dim SaltAddress As Double
        Dim SaltID As String
        Dim NewHash As String

        'Finds the Salt Address and Removes the Salt Address from the string

        SaltAddress = CDbl(Hash.Substring(3, 2))
        Hash = Hash.Remove(3, 2)

        'Finds the SaltID and removes it from the string

        SaltID = Hash.Substring(CInt(SaltAddress), 4)
        Hash = Hash.Remove(CInt(SaltAddress), 4)

        'Converts the string passed to us to Bytes

        EncStringBytes = Encoder.GetBytes(S & SaltID)

        'Encryptes the string passed to us with the salt

        EncStringBytes = MD5Hasher.ComputeHash(EncStringBytes)

        'Converts the Hash to a string

        NewHash = BitConverter.ToString(EncStringBytes)
        NewHash = NewHash.Replace("-", Nothing)

        'Tests the new has against the one passed to us
        Dim val As Boolean
        If NewHash = Hash Then
            val = True
        ElseIf NewHash <> Hash Then
            val = False
        End If
        Return val
    End Function
End Class


 Dim md5 As New MD5Encryption()
Password = md5.Encrypt(txtPassword.Text.Trim())

md5.Verify(txtPassword.Text, password)

DataGridView Printing in VB.NET windows application


Public Class GridViewPrintHelper

    Private strFormat As StringFormat
    Private iCellHeight, iCount, iTotalWidth, iHeaderHeight As Integer
    Public Property FirstPage As Boolean
    Public Property NewPage As Boolean
    Private arrColumnLefts As New List(Of Integer)
    Private arrColumnWidths As New List(Of Integer)

    Public Sub BeginPrint(dgvList As DataGridView, Optional unwantedColsFromStartingPos As Integer = 0)
        strFormat = New StringFormat()
        strFormat.Alignment = StringAlignment.Near
        strFormat.LineAlignment = StringAlignment.Center
        strFormat.Trimming = StringTrimming.EllipsisCharacter

        arrColumnLefts.Clear()
        arrColumnWidths.Clear()
        iCellHeight = 0
        iCount = 0
        FirstPage = True
        NewPage = True

        If unwantedColsFromStartingPos < 0 Then unwantedColsFromStartingPos = 0
        ' Calculating Total Widths
        iTotalWidth = 0

        If unwantedColsFromStartingPos >= dgvList.ColumnCount Then
            Throw New Exception("Invalid column count - From GridViewPrint: unwantedColsFromStartingPos param in BeginPrint")
        End If

        For i = unwantedColsFromStartingPos To (dgvList.ColumnCount - 1)
            iTotalWidth += dgvList.Columns(i).Width
        Next
       
    End Sub

    Public Sub PrintPage(ByVal dgvList As DataGridView, ByVal e As System.Drawing.Printing.PrintPageEventArgs, Optional ByVal unwantedColsFromStartingPos As Integer = 0, Optional ByVal Heading As String = "Summary")
        Dim iLeftMargin As Integer = e.MarginBounds.Left
        'Set the top margin
        Dim iTopMargin As Integer = e.MarginBounds.Top
        'Whether more pages have to print or not
        Dim bMorePagesToPrint As Boolean = False
        Dim iTmpWidth As Integer = 0

        'For the first page to print set the cell width and header height
        Dim neg As Integer = -1

        If FirstPage Then
            For Each GridCol As DataGridViewColumn In dgvList.Columns
                neg = neg + 1
                If neg < unwantedColsFromStartingPos Then
                    Continue For
                End If

                iTmpWidth = CInt(Math.Floor(CDbl(CDbl(GridCol.Width) / CDbl(iTotalWidth) * CDbl(iTotalWidth) * (CDbl(e.MarginBounds.Width) / CDbl(iTotalWidth)))))

                iHeaderHeight = CInt(e.Graphics.MeasureString(GridCol.HeaderText, GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11

                ' Save width and height of headers
                arrColumnLefts.Add(iLeftMargin)
                arrColumnWidths.Add(iTmpWidth)
                iLeftMargin += iTmpWidth
            Next
        End If
        Dim iRow As Integer = 0
        'Loop till all the grid rows not get printed
        While iRow <= dgvList.Rows.Count - 1
            Dim GridRow As DataGridViewRow = dgvList.Rows(iRow)
            'Set the cell height
            iCellHeight = GridRow.Height + 5
            Dim iCount As Integer = 0
            'Check whether the current page settings allows more rows to print
            If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
                NewPage = True
                FirstPage = False
                bMorePagesToPrint = True
                Exit While
            Else
                If NewPage Then
                    'Draw Header
                    e.Graphics.DrawString(Heading, New Font(dgvList.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString(Heading, New Font(dgvList.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)

                    Dim strDate As [String] = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString()
                    'Draw Date
                    e.Graphics.DrawString(strDate, New Font(dgvList.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDate, New Font(dgvList.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary", New Font(New Font(dgvList.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)

                    'Draw Columns                
                    iTopMargin = e.MarginBounds.Top
                    neg = -1
                    For Each GridCol As DataGridViewColumn In dgvList.Columns
                        neg = neg + 1
                        If neg < unwantedColsFromStartingPos Then
                            Continue For
                        End If

                        e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))

                        e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight))

                        e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iHeaderHeight), strFormat)
                        iCount += 1
                    Next
                    NewPage = False
                    iTopMargin += iHeaderHeight
                End If
                iCount = 0
                'Draw Columns Contents        
                neg = -1
                For Each Cel As DataGridViewCell In GridRow.Cells
                    neg = neg + 1
                    If neg < unwantedColsFromStartingPos Then
                        Continue For
                    End If
                    If Cel.Value IsNot Nothing Then
                        e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CInt(arrColumnLefts(iCount)), CSng(iTopMargin), CInt(arrColumnWidths(iCount)), CSng(iCellHeight)), strFormat)
                    End If
                    'Drawing Cells Borders
                    e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CInt(arrColumnLefts(iCount)), iTopMargin, CInt(arrColumnWidths(iCount)), iCellHeight))
                    iCount += 1
                Next
            End If
            iRow += 1
            iTopMargin += iCellHeight
        End While
        'If more lines exist, print another page.
        If bMorePagesToPrint Then
            e.HasMorePages = True
        Else
            e.HasMorePages = False
        End If

    End Sub




End Class

Private _gridPrintHelper As New GridViewPrintHelper

Private Sub prntDoc_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles prntDoc.BeginPrint
        Try
            _gridPrintHelper.BeginPrint(dgvList, 1)
        Catch ex As Exception
            Utils.LogHandler.HandleError(ex)
        End Try
    End Sub

    Private Sub prntDoc_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles prntDoc.PrintPage
        Try
            _gridPrintHelper.PrintPage(dgvList, e, 1)
        Catch ex As Exception
            Utils.LogHandler.HandleError(ex)
        End Try
    End Sub

Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
       
        Try
            'Open the print dialog
            Dim printDialog As New PrintDialog()
            printDialog.Document = prntDoc
            printDialog.UseEXDialog = True
            'Get the document
            If DialogResult.OK = printDialog.ShowDialog() Then
                prntDoc.DocumentName = "Staff List"
                prntDoc.Print()
            End If
          
        Catch ex As Exception
            Utils.LogHandler.HandleError(ex)
        End Try
    End Sub

AutoPrint using AutoPrinter Class in VB.NET windows application


Imports System.IO
Imports System.Data
Imports System.Text
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.Collections.Generic
Imports Microsoft.Reporting.WinForms
Public Class AutoPrinter
    Implements IDisposable
    Private m_currentPageIndex As Integer = 0
    Private m_streams As IList(Of Stream) = Nothing
    Private m_LocalReport As LocalReport = Nothing
    Private m_ServerReport As ServerReport = Nothing
    Private m_PrinterName As String = ""
    Private m_Width As Double = 0
    Private m_Height As Double = 0
    Private m_TopMargin As Double = 0
    Private m_LeftMargin As Double = 0
    Private m_RightMargin As Double = 0
    Private m_BottomMargin As Double = 0
    Public RequestResult As String = ""
    Dim MimeType As String = ""
    Dim Encoding As String = ""
    Dim Extension As String = ""
    Dim m_Streamids As String() = Nothing
    Dim m_Streamid As String = ""

    Public Sub New(ByVal LocalReport As LocalReport, _
            ByVal Width As Double, _
            ByVal Height As Double, _
            ByVal TopMargin As Double, _
            ByVal LeftMargin As Double, _
            ByVal RightMargin As Double, _
            ByVal BottomMargin As Double, _
            ByVal PrinterName As String)
        m_LocalReport = LocalReport
        m_Height = Height
        m_Width = Width
        m_TopMargin = TopMargin
        m_LeftMargin = LeftMargin
        m_RightMargin = RightMargin
        m_BottomMargin = BottomMargin
        m_PrinterName = PrinterName
        RequestResult = ""
    End Sub
    Public Sub New(ByVal ServerReport As ServerReport, _
            ByVal Width As Double, _
            ByVal Height As Double, _
            ByVal TopMargin As Double, _
            ByVal LeftMargin As Double, _
            ByVal RightMargin As Double, _
            ByVal BottomMargin As Double, _
            ByVal PrinterName As String)
        m_ServerReport = ServerReport
        m_Height = Height
        m_Width = Width
        m_TopMargin = TopMargin
        m_LeftMargin = LeftMargin
        m_RightMargin = RightMargin
        m_BottomMargin = BottomMargin
        m_PrinterName = PrinterName
        RequestResult = ""
    End Sub
    Public Sub PrintReport()
        Export_Report()
        m_currentPageIndex = 0
        Print_Report()
    End Sub
    Private Sub Export_Report()
        Dim DeviceInfo As String = _
          "<DeviceInfo>" + _
          "  <OutputFormat>EMF</OutputFormat>" + _
          "  <PageWidth>WWWW</PageWidth>" + _
          "  <PageHeight>HHHH</PageHeight>" + _
          "  <MarginTop>TTTT</MarginTop>" + _
          "  <MarginLeft>LLLL</MarginLeft>" + _
          "  <MarginRight>RRRR</MarginRight>" + _
          "  <MarginBottom>BBBB</MarginBottom>" + _
          "</DeviceInfo>"
        DeviceInfo = DeviceInfo.Replace("WWWW", m_Width.ToString("0.00in"))
        DeviceInfo = DeviceInfo.Replace("HHHH", m_Width.ToString("0.00in"))
        DeviceInfo = DeviceInfo.Replace("TTTT", m_Width.ToString("0.00in"))
        DeviceInfo = DeviceInfo.Replace("LLLL", m_Width.ToString("0.00in"))
        DeviceInfo = DeviceInfo.Replace("RRRR", m_Width.ToString("0.00in"))
        DeviceInfo = DeviceInfo.Replace("BBBB", m_Width.ToString("0.00in"))
        Dim warnings() As Warning = Nothing
        m_streams = New List(Of Stream)()
        If m_LocalReport IsNot Nothing Then
            m_LocalReport.Render("Image", DeviceInfo, AddressOf CreateStream, _
               warnings)
        End If
        If m_ServerReport IsNot Nothing Then
            Dim myStream As New MemoryStream( _
            m_ServerReport.Render("Image", DeviceInfo, MimeType, _
                Encoding, Extension, m_Streamids, warnings))
            m_streams.Add(myStream)
            Dim myImage As Byte()
            For Each m_Streamid As String In m_Streamids
                myImage = m_ServerReport.RenderStream("Image", m_Streamid, _
                     Nothing, Nothing, Nothing)
                myStream = New MemoryStream(myImage)
                m_streams.Add(myStream)
            Next
        End If
        Dim Stream As Stream
        For Each stream In m_streams
            stream.Position = 0
        Next
    End Sub
    Private Function CreateStream(ByVal name As String, _
           ByVal fileNameExtension As String, _
           ByVal encoding As Encoding, ByVal mimeType As String, _
           ByVal willSeek As Boolean) As Stream
        Dim stream As New MemoryStream
        m_streams.Add(stream)
        Return stream
    End Function
    Private Sub Print_Report()
        If m_streams Is Nothing Or m_streams.Count = 0 Then
            Return
        End If
        Dim PrintDoc As New PrintDocument()
        'The following line removes the printing page ?? of ?? messagebox
        PrintDoc.PrintController = New System.Drawing.Printing.StandardPrintController()
        PrintDoc.PrinterSettings.PrinterName = m_PrinterName
        If Not PrintDoc.PrinterSettings.IsValid Then
            Dim msg As String = String.Format( _
                "Can't find printer ""{0}"".", m_PrinterName)
            Console.WriteLine(msg)
            Return
        End If
        AddHandler PrintDoc.PrintPage, AddressOf PrintPage
        PrintDoc.Print()
    End Sub
    Private Sub PrintPage(ByVal sender As Object, _
            ByVal ev As PrintPageEventArgs)
        Dim PageImage As New Metafile(m_streams(m_currentPageIndex))
        ev.Graphics.DrawImage(PageImage, ev.PageBounds)
        Debug.Print(m_currentPageIndex.ToString)
        m_currentPageIndex += 1
        ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
    End Sub
    Public Overloads Sub Dispose() Implements IDisposable.Dispose
        If Not (m_streams Is Nothing) Then
            Dim stream As Stream
            For Each stream In m_streams
                stream.Close()
            Next
            m_streams = Nothing
        End If
    End Sub
End Class



        Dim ReportViewer1 As New ReportViewer
        ReportViewer1.ProcessingMode = ProcessingMode.Local
        ReportViewer1.LocalReport.ReportPath = "..\..\Report\Address.rdlc"
        ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource(ReportViewer1.LocalReport.GetDataSourceNames()(0), dt))
        Dim AP As New AutoPrinter(ReportViewer1.LocalReport, 11.69, 8.27, 0.5, 0.5, 0.5, 0.5, ps.PrinterName)
        AP.PrintReport()
        AP.Dispose()
        ReportViewer1.RefreshReport()
        ReportViewer1.LocalReport.Refresh()

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...