Monday, April 27, 2015

Update memory stream contains Zip file using .NET 4.5 and above OR Unzip memory stream using Zip Archive .NET 4.5.

I am showing one example below where I have to update my zip file in the WCF service and return back with modified zip file to end user.  Microsoft .NET 4.5 frame work, IO compression library can be used to Zip and Unzip files.

Requirement

I have one zip file contains 5 or more images, I have to use  those images and generate one HTML file, add into same zip file and return back zip file with one extra file.

Workflow to understand steps


C# Client Code

Namespace

using System.IO;

Constants

//Input file contain 5 image file
const string inputFile = @"C:\TEMP\Test.zip";

//Output file will contain 5 image and 1 Html file
const string outputFile = @"C:\TEMP\TestModified.zip";

Button event Code

private void button1_Click(object sender, EventArgs e)
{
   //create date object to count time taken in second
   DateTime dt1 = DateTime.Now;

   //Convert file into byte array
   byte[] docOutPut = File.ReadAllBytes(inputFile);

   //create WCF service instance
   var client = new ServiceReference1.Service1Client();

   //Call WCF service method and get byte array
   byte[] returnModifiedZipFile = client.UpdateZipFile(docOutPut);

   //convert byte array into memory stream
   Stream stream = new MemoryStream(returnModifiedZipFile);
         
   //Create new zip file and write memory stream into it
   using (var fileStream = new FileStream(outputFile, FileMode.Create))
   {
      stream.Seek(0, SeekOrigin.Begin);
      stream.CopyTo(fileStream);
    }

      lblHTML.Text = (DateTime.Now - dt1).Seconds + " Seconds";
 }

WCF Service method code

Namespace

using System.IO;
using System.IO.Compression;

Add Reference to your WCF project

System.IO.Compression.FileSystem

WCF Method Code

public byte[] UpdateZipFile(byte[] ZipFileInputFile)
{
   //open Memory Stream
   using (var memoryStream = new MemoryStream())
   {

//Write byte array into memory stream to avoid “Memory Stream exception–Memory //stream is not expandable” error

      memoryStream.Write(ZipFileInputFile, 0, ZipFileInputFile.Length);
      //use Zip Archive and open memory stream in update mpde
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Update, true))
      {
          //create new file
          var outPutFile = archive.CreateEntry("NewFile.html");
          //open new file to write
          using (var entryStream = outPutFile.Open())                   
          //create stream writer and write content into new file
          using (var streamWriter = new StreamWriter(entryStream))
          {
             streamWriter.Write("<html>");
             streamWriter.Write("<body>");
             // read files how many files present into the zip file
             for (int entry = 0; entry < archive.Entries.Count - 1; entry++)
             {
                //use file name present into the zip file
streamWriter.Write(string.Format("<img src= \"{0}\" width=\"100%\" />", archive.Entries[entry].FullName));
                     streamWriter.Write("<p/>");
             }
                streamWriter.Write("</body>");
                streamWriter.Write("</html>");
          }
       }
           //convert memory stream into array and retun
           return memoryStream.ToArray();
   }
}

To configure config file please see below article
https://www.blogger.com/blogger.g?blogID=7638493#allposts/postNum=0

References

To know more about Zip Archive and other IO Compression utility see below

Error:Cannot write configuration file, Visual Studio 2013


Friday, April 17, 2015

Understand Dependency Injection with C# code example

Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. It can be implemented by constructor injection, setter injection or method injection.
To understand DI you need to understand how and why DI pattern introduced. Following terms are the main factor for complete understanding of DI.  
  • Dependency
  • Dependency Inversion Principle
  • Inversion of Control (IoC)
Below diagram will depicts the differences between these terms, it's pros and cons and complete journey. C#.net code will help to understand this patterns easily.



Main advantages of using DI patterns
  • Create loosely couple class, reduces class coupling
  • Improves application testing, Classes can be tested individually, Class can be mock easily.,  
  • Increases code re-usability
  • Improves code maintainability
  • Increase application scalability
Dependency injection can be done in three ways.
  • Constructor injection
  • Method injection
  • Property injection
In below diagram I have described the Constructor injection, other example can be seen in below links
Microsoft provide better framework called unity 3.0 (latest )to develop DI pattern, this can be downloaded by below link
Dependency Injection using unity framework, C# code example can be seen in below link
There are reasons for not using it in your application, some of which are summarized in this section.

  • Dependency injection can be overkill an application, introducing additional complexity and requirements that are not appropriate or useful. this has to be used properly after good analysis of all aspects.

Thursday, March 12, 2015

Find out the 'Text', saved in any database table, SQL Server

There is Stored Procedure which will help to find any 'Text' in any database table, any database table columns in SQL Server database. in short, find the text inserted into which database table.

Ex: If you have to find 'Testing DBA' word in database table and you don't know which table name, which column name where this data saved then find it in below way

Execute
Exec  SearchDataInAllTables 'Testing DBA'

Stored Procedure
CREATE PROC SearchDataInAllTables
(
    @SearchStr nvarchar(100)
)
AS
BEGIN

DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT ColumnName, ColumnValue FROM @Results
END

Ref: http://stackoverflow.com/questions/436351/how-do-i-find-a-value-anywhere-in-a-sql-server-database

Find text in any database objects

If you want to search any hard coded text, or table name or column name used in any of the SP, Triggers, Functions or View, you can use following query to find your expected Text..

SELECT DISTINCT
       o.name AS Object_Name,
       o.type_desc
  FROM sys.sql_modules m
       INNER JOIN
       sys.objects o
         ON m.object_id = o.object_id

 WHERE m.definition Like '%Employee_Testing%'

Find column name in any database table.

Ex: Find 'EmployeeID' column name in any table in database.

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%EmployeeID%'
ORDER BY schema_name, table_name;

Ref: http://blog.sqlauthority.com/2008/08/06/sql-server-query-to-find-column-from-all-tables-of-database/

Wednesday, February 11, 2015

.NET APIs To Convert PDF document to HTML document

If you want to build WCF service using C# or VB.NET then you require some .NET code or inbuilt APIs where you can pass PDF document in byte array format and return back byte array in HTML format. writing .NET code looks very difficult and time consuming until unless you are developing conversion product itself. you can also try iTextSharp open source APIs but this is not 100% suitable for graphics objects,Images, tables borders, logos, font style and format etc.
  
There are multiple inbuilt APIs available and they are capable to do PDF to multiple format conversion like : PDF to HTML, PDF to DOC/DOCX. PDF to RTF, PDF to JPG etc.
All below options require License to use.

C#.net code to to use these APIs and build WCF service, I have done couple of conversion (PDF to HTML) using trial version of APIs and conversion result looks very promising. if you have such kinds of requirement try these options and below are some C#.NET code for quick development

Using SautinSoft APIs

using SautinSoft;
using System.IO;

public byte[] PDFToHTML(byte[] inputFilePDF)
{
        PdfFocus pdfFocusObject = new PdfFocus();
        pdfFocusObject.OpenPdf(inputFilePDF);
        byte[] outPutHtmlByte= null;

        if (pdfFocusObject.PageCount > 0)
        {
            pdfFocusObject.HtmlOptions.IncludeImageInHtml = true;
            pdfFocusObject.HtmlOptions.Title = "Simple text";
            string html = pdfFocusObject.ToHtml();
            outPutHtmlByte = GetBytes(html);
        }
        return outPutHtmlByte;
}

public byte[] PDFToDoc(byte[] inputFilePDF)
{
        PdfFocus pdfFocusObject = new PdfFocus();
        pdfFocusObject.OpenPdf(inputFilePDF);
        byte[] outPutDocByte = null;

        if (pdfFocusObject.PageCount > 0)
        {
           string word=  pdfFocusObject.ToWord();
           outPutDocByte = GetBytes(word);
        }
        return outPutDocByte;
    }

    private byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

Using Aspose APIs

using Aspose.Pdf;
using System.IO;

byte[] resultHtmlAsBytes;
public byte[] PDFToHTML(byte[] inputFileByteArray)
 {
        Document doc = new Document(new MemoryStream(inputFileByteArray));
        HtmlSaveOptions newOptions = new HtmlSaveOptions();
        newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
        newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
        newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml;
        newOptions.LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
        newOptions.PagesFlowTypeDependsOnViewersScreenSize = false;
        newOptions.RemoveEmptyAreasOnTopAndBottom = true;
        newOptions.SplitCssIntoPages = false;
        newOptions.CustomHtmlSavingStrategy = new HtmlSaveOptions.HtmlPageMarkupSavingStrategy(SavingToStream);
        string outHtmlfile = "Test.html";
        doc.Save(outHtmlfile, newOptions);
        return resultHtmlAsBytes;
    }

    private void SavingToStream(HtmlSaveOptions.HtmlPageMarkupSavingInfo htmlSavingInfo)
    {
        resultHtmlAsBytes = new byte[htmlSavingInfo.ContentStream.Length];
        htmlSavingInfo.ContentStream.Read(resultHtmlAsBytes, 0, resultHtmlAsBytes.Length);
    }

Using RasterEdge APIs:



Call above functions from client

using System;
using System.IO;

private string inputFile = "C:\Test.pdf"; 
private string outputFile = "C:\Test.html"; 

byte[] outputFileByteArray = client.PDFToHTML(File.ReadAllBytes(inputFile));
File.WriteAllBytes(outHtmlfile, outputFileByteArray);

client: Create instance of WCF proxy object and use.

Wednesday, December 31, 2014

Visual Studio 2015 Improvements for .NET, works with new .NET framework 4.6

Below are some new features of Visual Studio 2015
  • PerfTips
              PerfTips allow you to quickly and easily see performance bottlenecks as you are debugging your application.
  • Intuitive Breakpoint Settings
            The new and intuitive breakpoint settings make it a lot easier to change the behavior of breakpoints.
  • Setting breakpoints on auto-implemented properties
              Debug support for auto-implemented properties
  • Lambdas in the debugger windows
              Lambdas are now supported in debugger windows
  • Core IDE and Editing Improvements
              New enhanced core IDE and editing experiences for C# and Visual Basic

.NET 2015 also trying to remove some known differences of VB and C#.NET and bring the two languages closer. It is really good initiative to remove differences between languages, specially between VB and C#.Net

Thursday, December 18, 2014

Error: WCF - Cannot find the X.509 Certificate using the following search criteria...

I was getting this error when I have below lines of code on my WCF web.config file

"serviceCertificate findValue="WCfServer" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName""

I have installed Server and Client certificate into MMC >> Personal and Trusted People but still when I try to browse my service from IIS I am getting same 'X.508 certificate...' error.

Solution

I found the issues, My app pool account in IIS was running under "ApplicationPoolIdentity" but since on my web.config and certificate installation done using "Current User",  So it is important to run your app pool account under your local Identity user Id. So I just change App pool account in IIS to run under my local window credential and it works for me. 

.NET New Feature, SOLID Principal and WCF Security

.NET Framework 4.5 new Features
  • Async and await (code markers)
  • Zip facility (Zip compression)
  • Regex timeout (TimeOut)
  • Profile optimization (Improved startup performance)
  • Garbage collector (GC background cleanup)


SOLID Architecture Principal
  • “S” - SRP (Single responsibility principle)
  • “O” - Open closed principle
  • “L”- LSP (Liskov substitution principle)
  • “I” - ISP (Interface Segregation principle)
  • “D” - Dependency inversion principle.


WCF Security
  • WCF Security Transport vs Message using BasicHttpBinding and wcHttpBinding
  • Difference between Transport and Message Security
  • Difference between BasicHttpBinding and wcHttpBinding Binding
  • How to create certificates
  • Example C# code to implement Transport based security and Message based Security
  • Eenable Windows authentication on WCF using ‘BasicHttpBinding’

Tuesday, November 18, 2014

Update your Window phone (Samsung Focus SGH-i197) to from Window 7.5 to 7.8 (7.10.8862.144)

Update your Window phone (Samsung Focus SGH-i197) to from Window 7.5 to 7.8 (7.10.8862.144)

It works for me for my Samsung Focus SGH-i197. Be patient it may take around 45 min. it will restart your phone multiple times, update will start from 7.10.8112.7 and go till 7.10.8862.144 final version. you installation only complete when "Congratulation! you'r done!" message box pops up. then you can close the application.

Download below two files from below link and follow the given instruction

Sunday, November 16, 2014

Update your Samsung SGH-i197 window phone from 7.10.7720 to 7.10.8101.79 without Zune forcefully

Below steps works for me on my Window Phone (Samsung SGH-i197) having OS 7.10.7720

Step-1
Count Display Language in your phone, Go to Setting >> Language

Step-2
Download files based on language in your phone.
Here are the individual languages that you need to download to the same directory as the OS install files from above English (US) language pack Chinese (traditional), Chinese (simplified), GermanCzechFrenchEnglish – UK, Spanish, Danish, Greek, Finnish, Hungarian, Italian, Japanese, Korean, Dutch, Norwegian, Polish,Portuguese – (Brazil), Russian, Swedish, Portuguese – (Portugal)
If you need all 22 in one shot, just download this file. Do NOT install extra languages.
Step-3
Download the ZIP file here and keep in in your local PC drive (i.e. C:\Phone)

Step-3
Download and install the appropriate file based on your PC OS version
Step-4
Follow below steps
1.    Make sure your phone is charged to at least 50%
2.    Plug your phone via USB into your computer and close Zune Desktop (yes, close it)
3.    On your computer, navigate to where you extracted the OS update: Cab Sender --> Tools --> x86/x64(Choose one based off your system architecture)
4.    Run UpdateWP.exe (Note: you should see a DOS screen flash and disappear)
5.    Back out to your main directory and run WP7 Update Cab Sender.bat
6.    Choose 'B' (This will back up your device to Zune, then install the updates)

Reference Site: See below site for more details and troubleshoots

To update Window 7.5 to 7.8 (7.10.8862.144) please see below link
http://riteshkk2000.blogspot.com/2014/11/update-your-window-phone-samsung-focus.html

Thanks for
     

Saturday, November 15, 2014

Multiple ways to Export data into Excel using .net and SQL server

There are many ways to export data into excel, need to analyze following requirement before choosing any methods like:
  • Volume of data,
  • Dynamic behavior,
  • Schedule export or Manual export
  • Performance & Scalability
  • Security
  • Operating system, (32 or 64 bit etc.)

Based on above requirement you can decide best approach for export. I would suggest create proof of concept and do your entire requirement testing carefully before taking final decision.

1. Export data using Microsoft Office.Interop Library


Microsoft .NET provides Interop library to create excel object and export data table or data grid view into excel sheet, this object is very useful when you require designing fancy excel sheet using all excel features; like: cell design, formula, header & footer design etc.

           
Pros:
                    - Complete programming support to Excel via C#
                    - Integrated with to Visual studio

Cons:
                    -You must have Excel installed on your system for this code to run properly.
                    -To use COM interop, you must have administrator or Power User security permissions
                    -It is little slow to handle heavy data load and not enough to load large size of
dataset
. 
2. Export data using OpenXML SDK 2.0

Open XML SDK 2.0 lets developers be more productive by providing design-time capabilities such as IntelliSense support and a type-safe development experience. You can download from Download SDK.


Pros:
                 -Doesn't require Microsoft Office installed
                 -Made by Microsoft , decent MSDN documentation
                 -Just one .Net dll require to use in project
                 -SDK comes with many tools like diff, validator, etc.            
                 -The SDK is stable and it is supported by Microsoft.
                 -LINQ can be used to navigate data of excel file.
                 -It performs operations with just a few lines of code.

Cons:
                 -It supports only the documents created in Office 2007 or later (i.e. xlsx, docs etc)
                 -It cannot render Office functions. You can't do Excel calculations rendering on                       the server-side. 

3. Export data in CSV file using StreamWtiter

If you requirement to just export the data into plain excel file, single sheet, no column formatting needed then you should go with CSV file creation instead of Excel. This solution works very well with large size of data. Tested with 1 million rows with file size around 2 GB.

Pros:
                -No Extra DLL require
                -Faster than creating excel file
                -Can handle large data size

Cons:
                -Creates single excel sheet only
                -No formatting support
                -Need to remove special char like: “’,” (Comma) 


Public string RemoveInvalidChar(string input)
{
  List<string> invalidItems = new List<string>()
  {
      ",", "/r", System.Environment.NewLine
  };

  foreach (string invalidItem in invalidItems)
  {
    input = input.Replace(invalidItem, "");
  }
   return input;
}

private void btnExport_Click(object sender, EventArgs e)
{
    int cols;
    //open file
    StreamWriter wr = new System.IO.StreamWriter(@"C:\PerformanceTest.csv", false, Encoding.UTF8);
    //Create datatable having huge rows and columns
    DataTable dt = GetDataTable();
    //determine the number of columns and write columns to file
    cols = dt.Columns.Count;
    for (int i = 0; i < cols; i++)
    {
        wr.Write(dt.Columns[i].ToString().ToUpper() + ",");
    }
        wr.WriteLine();
    //write rows to excel file
    for (int i = 0; i < (dt.Rows.Count); i++)
    {
      for (int j = 0; j < cols; j++)
      {
        if (dt.Rows[i][j] != null)
         {
           wr.Write(RemoveInvalidChar(dt.Rows[i][j].ToString()) + ",");
         }
         else
         {
          wr.Write(",");
         }
        }
        wr.WriteLine();
      }
      //close file
      wr.Close();
   }
 }

4. Export data using OLEDB provider

The basic format for the Microsoft.Jet.OLEDB.4.0 provider is: [32-bit SQL Server for Excel 2003]
Export:
INSERT INTO OPENROWSET ('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=c:\contact.xls;',
'SELECT * FROM [Sheet1$]')
SELECT TOP 5 doc_id,doc_name FROM document
Import:
SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
  'Excel 8.0;Database=C:\excel-sql-server.xls', [Sheet1$])
SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0',
  'Data Source=C:\excel-sql-server.xls;Extended Properties=Excel 8.0')...[Sheet1$]
The basic format for the Microsoft.ACE.OLEDB.12.0 provider is:[64-bit SQL Server for any Excel files or 32-bit SQL Server for Excel 2007]
Export:
INSERT INTO OPENROWSET ('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0;Database=c:\contact.xls;',
'SELECT * FROM [Sheet1$]')
SELECT TOP 5 doc_id,doc_name FROM document
Import:
SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
  'Excel 12.0;Database=C:\excel-sql-server.xlsx', [Sheet1$])
SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:\excel-sql-server.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

Note:     
   -Microsoft.Jet.OLEDB.4.0 and Microsoft.ACE.OLEDB.12.0 has to be registered.
   -Microsoft.ACE.OLEDB.12.0 provider work with SQL Server x64 for any Excel             version files.
How to registered OLEDB
#1: Manually register those DLLs.
  1. Go to Start->Run and type cmd
  2. this starts the Command Prompt
  3. (also available from Start->Programs->Accessories->Command Prompt)
  4. Type cd .. and press return
  5. Type cd .. and press return again (keep doing this until the prompt shows :\> )
  6. Now you need to go to a special folder which might be c:\windows\system32 or it might be c:\winnt\system32 or it might be c:\windows\sysWOW64

        try typing each of these e.g.
             cd c:\windows\sysWOW64
             (if it says The system cannot find the path specified, try the next one)
             cd c:\windows\system32
             cd c:\winnt\system32  
        When one of those doesn't cause an error, stop, you've found the correct                     folder
    7. Now you need to register the OLE DB 4.0 DLLs by typing these commands and           pressing return after each
  • regsvr32 Msjetoledb40.dll
  • regsvr32 Msjet40.dll
  • regsvr32 Mswstr10.dll
  • regsvr32 Msjter40.dll
  • regsvr32 Msjint40.dll

#2:  Open the project in Visual Studio then:
  • From the solution explorer right-click your project then click Properties
  • Click the Build tab
  • Change Platform target from: Any CPU to x86
  • Re-build your solution