Posts

Showing posts from 2015

Featured Post

Smart Product designer

Image
download and purchase link: https://alkanyx.com/item/49/Smart+Product+designer

Live preview : http://smartproductdesigner.000webhostapp.com/

Smart Product Designer is a  tool to create your own product and get directly from your website. It is well documented, very easy to customize and use. It is build using most advance technologies including javascript, jQuery and html5.
Features Choose different product from collectionAdd custom texts to product.Change text colorChange the size and font of the TextLet the user drag, move or remove elementsAdd images to product selected from art gallery or browse it from systemDesign both frontside and back-sideShows preview while designingDownload designVery easy to customize and useHere is the purchase link : https://alkanyx.com/item/49/Smart+Product+designer

Reading RAW Images in .NET applications using C#

Sometimes the photos captured from cameras are saved in a raw format. The RAW files are not ready for editing with any bitmap editor. By default GDI+ in windows application do not support RAW file formats. So while reading a RAW image file in .NET we can get exceptions like "Out of memory". Here we will discuss method to read RAW image file in C# application.

Using DCRaw

dcraw is an open-source computer program which is able to read numerous raw image formats, typically produced by high-end digital cameras. dcraw converts these images into the standard PPM and TIFF image formats. Here is the sample in C# to extarct image from RAW file using DCRaw executable


string PathToDcRawExecutable = "C:\\DcRaw\\dcraw-ms.exe";
var _sourceImage = (Bitmap)Image.FromStream(GetImageFromRaw("c:\\testimage.ORF", PathToDcRawExecutable));

public Stream GetImageFromRaw(string inputFile, string dcRawExe)
{
    var startInfo = new ProcessStartInfo(dcRawExe)
    {
        Argumen…

Any CPU Type configuration in .NET project using C++ DLL

Any CPU Type configuration in .NET project using C++ DLL

Sometimes application is memory hungry like application for image processing etc. In this case we need a 64-bit OS where application can use higher amount of memory. Also we want that our application should remain compatible with 32-bit OS. To satisfy both these condition with single exe we can use Any CPU configuration to build our project.

Here are the steps to set Any CPU configuration open in Visual Studio -

1. Go to Build -> Configuration Manager
2. From Active solution platform click <New...>
3. From New Solution Platform select Any CPU
4. Click OK

Build the project. The exe created will be compatible on both OS (64-bit and 32-bit).

In case if we have a C++ dll used by the code and loaded at run-time as interop service. Since C++ project do not have Any CPU configuration, so in this case we build this C++ DLL in both configuration (64-bit and 32-bit) and then load DLL according to the type of system. Also we need…

Calling another case from one case in Switch statement using C#

Sometimes it might be possible that we need to call some another case of switch statement after some processing in one case. In that case we can use either falling through switch cases or goto case statement.

Here is the example of falling through -

Falling through switch-cases can be achieved by having no code in  case (see case 0 and 1):
switch (/*...*/) {
    case 0: // shares the exact same code as case 2
    case 1:// shares the exact same code as case 2
    case 2:
        // do something else
        break;
    default:
        // do something entirely different
        break;}

Both case 0 and 1 will execute code of case 2.


Using special goto case in switch statement -
 switch (/*...*/) {
    case 0:
        //do something
        break;

    case 1:
       //do something
       break;

    case 2:
        if(condition1)
            goto case 1;
        else
            goto case 2;

        break;
    default:
        // do something entirely different
        break;}

Here in the …

Pass byte array from C# to C++ and vice-versa

Pass byte array from C# to C++                          If you want to pass a byte array to native DLL as parameter, you can use the Intptr to do this, please check the demo below.
/C++ API code: TestDLL_API voidTestArrayPara(BYTE * pArray, int nSize) { for (int i=0; i<nSize; i++) printf("%d\n", pArray[i]); } //C# code:classTestClass { [DllImport(@"TestDll.dll")]publicstaticexternvoidTestArrayPara(IntPtr pArray, int nSize); publicstaticvoidTest() { byte[] array = newbyte[16]; for (int i = 0; i < 16; i++) { array[i] = (byte)(i + 97); } int size = Marshal.SizeOf(array[0]) * array.Length; IntPtr pnt = Marshal.AllocHGlobal(size); try { // Copy the array to unmanaged memory. Marshal.Copy(array, 0, pnt, array.Length); } finally {…

Some image operations in C#.NET

Flip ImageUsing the Image.RotateFlip method, we can rotate the image by 90/180/270-degrees or flip the image horizontally or vertically. The parameter of RotateFlip is System.Drawing.RotateFlipType, which specifies the type of rotation and flip to apply to the image. Code Snippet:

//Specifies a 180-degree rotation without flipping
pictureBox1.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
//Specifies no rotation followed by a horizontal flip
pictureBox1.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);

//Specifies a 90-degree rotation followed by a horizontal and vertical flip pictureBox1.Image.RotateFlip(RotateFlipType.Rotate90FlipXY);

Join Two Images
Bitmap bitmap = new Bitmap(image1.Width + image2.Width, Math.Max(image1.Height, image2.Height));
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.DrawImage(image1, 0, 0);
        g.DrawImage(image2, image1.Width, 0);
    }


Convert Bitmap to byte[] and vice-versa using C#Here is the function to convert bitmap to byte[] in C#…

Convert Bitmap to byte[] and vice-versa using C#

Here is the function to convert bitmap to byte[] in C# using ImageConverter class. ImageConverter class is present in System.Drawing.dll.


public static byte[] BitmapToByteArray(Bitmap bitmap)
        {
            ImageConverter converter = new ImageConverter();
            return (byte[])converter.ConvertTo(bitmap, typeof(byte[]));

        }

Here is the code to convert byte[] to bitmap in C#

public static Bitmap ByteArrayToBitMap(byte[] imageData)
        {
Bitmap bmp;
            using (var ms = new MemoryStream(imageData)){
            bmp = new Bitmap(ms);}  
                     return bmp;         }



Add Combo box in a cell of DataGridView at Run Time - C#.NET Windows Form

In DataGridView control of windows form we can set the column type "DataGridViewComboBoxColumn" to show combo box in the cells of the column. Sometimes we need to show only a single or few cells having combo box. For this we need to add Combo box to the required cell on run time. Here is the sample code to do the same -


//to get the correct cell get value of row and column indexs of the cell  ColIndex = 1;  RowIndex = 1;
 DataGridViewComboBoxCell ComboBoxCell = new DataGridViewComboBoxCell();  ComboBoxCell.Items.AddRange("XYZ", "ABC", "PQR");  ComboBoxCell.Value = "XYZ";  datagridview1[ColIndex, RowIndex] = ComboBoxCell;


From the above code DataGirdCell at the location (1,1) will be converted to a "DataGridViewComboBoxCell" and combo box will be shown in the cell.


It might be possible that to dropdown the combo box multiple mouse clicks are required. To activate combo box on single click following steps are required -

1. Set ReadOn…

Drawing Custom Border Color on a Control in C#.NET Windows Form Application

Sometimes we need to change the border color of a control to match its color with UI. Visual studio designer only allows us to choose borderStyle. To change border color of controls (like panel, DataGrid etc.) we need to write custom code to set the border color of control. Here is the custom code -

  private void ControlBorder_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                Control ctrl = sender as Control;
                ControlPaint.DrawBorder(e.Graphics, ctrl.ClientRectangle,                   Color.FromArgb(130, 135,144), ButtonBorderStyle.Solid);              
            }
            catch (Exception ex)
            {
                  //write log
            }
        }



Use above paint function in the paint event for the control which requires custom border color.

Create a Custom Tooltip dialog from a Form C# Windows Form Application

Image
To show information on any button we can use a form and custom format it to show use it as a tooltip. For example to explain any functionality related to some section we have a long tooltip message. Here we can create a custom tooltip dialog that can show the message in more user friendly way.
To create a custom formatted dialog create a form with following settings -namespace Project1{publicpartialclass frmCustomToolTipDlg : Form {public frmCustomToolTipDlg() { InitializeComponent();this.FormBorderStyle = FormBorderStyle.None; this.BackColor = Color.FromArgb(50, 50, 50);this.Opacity = 0; fadeTimer = new Timer { Interval = 15, Enabled = true }; fadeTimer.Tick += new EventHandler(fadeTimer_Tick); }void fadeTimer_Tick(object sender, EventArgs e) {if (this.IsDisposed)return;this.Opacity += 0.04;if (this.Opacity >= 0.99) { fadeTimer.Enabled = false; } …

Create word documents in C#.NET using Spire.Doc .NET library

Create word documents in C#.NET using Spire.Doc .NET library
Sometimes in our application we need to create word documents where we can create different types of documents and can perform many operations them related to formatting, conversion etc. Spire.Doc is a .NET library where we can create, read, write, convert and print Word documents files using .NET platform (C#, B.NET, ASP.NET). Here we do not require Microsoft word to be installed on the system. But we will need MS Word viewer to view resultant document. Spire.Doc also gives us the functionlities to convert document files to XML, RYF, TXT, XPS, EPUB, EMF, HTML, PDF and vice versa.


Here we will discuss creating a word document using Spire.Doc library in  C#.NET forms and its conversion to PDF file format.
Setup of Spire.Doc can be downloaded from http://www.e-iceblue.com/Download/download-word-for-net-now.html. After installing Spire.Doc library add  SpireDoc.dll in reference of the project. Choose suitable dll as per the pro…

Access 64-bit HKLM\Software registry by 32-bit C#.NET application

Access 64-bit HKLM\Software registry by 32-bit C#.NET application


While running 32-bit windows application on a 64-bit windows OS their is a registry redirection. Here if 32-bit application try to read a key under HKLM\Software, then due to Registry redirection effective path becomes HKLM\Software\Wow6432Node. For example, we are running 64-bit and 32-bit application to read registry keys as HKLM\Software\xyz and HKLM\Software\Wow6432Node\xyz

So by default with an input of HKLM\Software, 64-bit application will read HKLM\Software\xyz while because of registry redirection 32-bit application will read HKLM\Software\Wow6432Node\xyz.

In C#, to read 64-bit HKLM\Software registry keys we can use RegistryKey.OpenBaseKey method. This method takes two arguments- RegistryHive and RegistryView. Here sperate registry views are present for 32-bit and 64-bit.

Here is the sample C# code to read AppPaths for 32-bit and 64-bit applications installed on the system -


try
                {
               …

Extract icons of Installed Windows Application using C#. NET

Icon of Installed Windows Applications

First we need to figure out the location of icon for the installed windows application. This information is stored in registry at following locations -
1. Key name - HEKY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
   Value    - DisplayIcon

2. Key name - HKEY_CLASSES_ROOT\Installer\Products\{productID}
   Value - ProductIcon


first try to get location of icon from HEKY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall. Here if the value of DisplayIcon is null then try to fetch location of icon from HKEY_CLASSES_ROOT\Installer\Products\{productID}


Here is the sample code to read the icon -


using system.Drawing //read HKEY_LOCAL_MACHINE Icon ProductIcon; privatevoid ReadIcon() { try { string uninstallKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"; using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(uninstallKey)) {������������������…

Continue executing code after calling ShowDialog() using C#

In  C# windows form application using ShowDialog() a user can show a form as modal dialog. Here we cannot access the rest application or continue execution of the code until the modal dialog is closed.

Sometimes we need to show modal dialog to user and we need to perform some background operations with parent form control without closing the dialog box. For example - we are doing some calculation and on the basis of these calculation we are moving the progress bar control on dialog box. Here is the c# code by which user can continue executing code after showing modal dialog using ShowDialog() -


ReaderWriterLockSlim ScanLock = new ReaderWriterLockSlim(); privatevoidForm1_Load(object sender, EventArgs e) { ScanLock.EnterWriteLock(); UIThread(()=> { WindowsFormsSynchronizationContext.Current.Post(_ => { Form2 frm = new Form2(); frm.ShowDialog(); …

Create Thumbnail of Image using C#

Thumbnail is the reduced sized image of the given image. We can use thumbnail where we need to display large number of images. Using  GetThumbnailImage method we can create thumbnail for any give image.

The basic syntax used to create thumbnail using C# is -

Image img = Image1.GetThumbnailImage(thumbnail.Height, thumbnail.Width, Image.GetThumbnailImageAbort callback, IntPtr callbackData)


Here is the example -

Bitmap testimage = (Bitmap)TestApplication.Properties.Resources.testimage.GetThumbnailImage(450,550, null, IntPtr.Zero);

JSON serialization

In JSON we must explicitly need to put an attribute before each field that needs to be serialized. Also we need to put [DataContract] attribute before the declaration of the class. Here is the sample code JSON serialization -
[DataContract] public class Employee { [DataMember] private int empId; [DataMember] public string empName; public void SetEmployeeId(int id) { empId = id; } } 
If you want to ignore any field then simply do not put [DataMember] attribute in front of that property. To serialize an object to JSON we can use DataContractJsonSerializer class from the namespace System.Runtime.Serialization.Json. Here is the sample code for JSON serialization -
Employee emp = new Employee(); emp.SetEmployeeId(1); emp.empName = "John"; Stream stream = new FileStream("Emp.json", FileMode.Create); DataContractJsonSerializer JsonSer = new  DataContractJsonSerializer(typeof(Employee)); JsonSer.WriteObject(stream, Employee); stream.Close(); The JSON for the employe object is : { "emp…