Thursday 17 December 2015

Get Printer List of System in c# Self Host WCF with Window Service

 public string GetPrinter()
        {
            try
            {
                // USING WMI. (WINDOWS MANAGEMENT INSTRUMENTATION)
                StringBuilder cmbPrinterList = new StringBuilder();
                System.Management.ManagementScope objMS =
                    new System.Management.ManagementScope(ManagementPath.DefaultPath);
                objMS.Connect();

                SelectQuery objQuery = new SelectQuery("SELECT * FROM Win32_Printer");
                ManagementObjectSearcher objMOS = new ManagementObjectSearcher(objMS, objQuery);
                System.Management.ManagementObjectCollection objMOC = objMOS.Get();

                foreach (ManagementObject Printers in objMOC)
                {
                    if (Convert.ToBoolean(Printers["Local"]))       // LOCAL PRINTERS.
                    {
                        cmbPrinterList.Append(Printers["Name"] + ",");
                    }
                    if (Convert.ToBoolean(Printers["Network"]))     // ALL NETWORK PRINTERS.
                    {
                        cmbPrinterList.Append(Printers["Name"] + ",");
                    }
                }
                if (!string.IsNullOrEmpty(cmbPrinterList.ToString()))
                    return cmbPrinterList.ToString().Remove(cmbPrinterList.ToString().Length - 1);
                else
                    return string.Empty;
            }
            catch (Exception ex)
            {
                EventLog e = new EventLog("Print Error");
                e.WriteEntry("Failed in GetPrinter, Reason:" + ex.Message);
                throw new FaultException(ex.ToString());
            }
        }

memory release on close of window application c#

Put Below code inside Form Closing Event

Please use the   Environment.Exit(0); in Form Closing Event.


        /// <summary>
        /// Form Close Event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DCDFormat_FormClosing(object sender, FormClosingEventArgs e)
        {
            ///For exit from application
            Environment.Exit(0);
        }

Swap Place in a Array C#

  static void SwapPlace(string[] resultArray, int startPos, int endPos)
        {
            try
            {
                string tempswap;
                tempswap = resultArray[startPos];
                resultArray[startPos] = resultArray[endPos];
                resultArray[endPos] = tempswap;
            }
            catch
            {
                throw;
            }
        }

Get Ascii value in c#

byte asciiValue = Convert.ToByte('The Value which you want to convert into ascii');

Convert 0 to ascii

Example.

byte result = Convert.ToByte('0');

Android equilvalent of c# AES decryption

 public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
        {
            byte[] AESKey = new byte[] {  };
            KeyParameter par = new KeyParameter(AESKey);
            // SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IBufferedCipher cipher = CipherUtilities.GetCipher("AES/ECB/NoPadding");
            cipher.Init(false, par);
            // Gives me "pad block corrupted" error
            byte[] output = new byte[cipher.GetOutputSize(encryptedData.Length)];
            int len = cipher.ProcessBytes(encryptedData, 8, encryptedData.Length - 8, output, 0);
            cipher.DoFinal(output, len);
            // byte[] output = cipher.DoFinal(encryptedData);
            return output;
        }

Java equivalent of C# AES Decryption

 public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
        {
            byte[] AESKey = new byte[] {  };
            KeyParameter par = new KeyParameter(AESKey);
            // SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IBufferedCipher cipher = CipherUtilities.GetCipher("AES/ECB/NoPadding");
            cipher.Init(false, par);
            // Gives me "pad block corrupted" error
            byte[] output = new byte[cipher.GetOutputSize(encryptedData.Length)];
            int len = cipher.ProcessBytes(encryptedData, 8, encryptedData.Length - 8, output, 0);
            cipher.DoFinal(output, len);
            // byte[] output = cipher.DoFinal(encryptedData);
            return output;
        }

Getting exception of Invalid length in decryption from AES Algorithm

Getting exception of Invalid length in decryption from AES Algorithm

 public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
        {
            byte[] AESKey = new byte[] {  };
            KeyParameter par = new KeyParameter(AESKey);
            // SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IBufferedCipher cipher = CipherUtilities.GetCipher("AES/ECB/NoPadding");
            cipher.Init(false, par);
            // Gives me "pad block corrupted" error
            byte[] output = new byte[cipher.GetOutputSize(encryptedData.Length)];
            int len = cipher.ProcessBytes(encryptedData, 8, encryptedData.Length - 8, output, 0);
            cipher.DoFinal(output, len);
            // byte[] output = cipher.DoFinal(encryptedData);
            return output;
        }

Decryption in AES c#

 public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
        {
            byte[] AESKey = new byte[] { };
            KeyParameter par = new KeyParameter(AESKey);
            // SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IBufferedCipher cipher = CipherUtilities.GetCipher("AES/ECB/NoPadding");
            cipher.Init(false, par);
            // Gives me "pad block corrupted" error
            byte[] output = new byte[cipher.GetOutputSize(encryptedData.Length)];
            int len = cipher.ProcessBytes(encryptedData, 0, encryptedData.Length , output, 0);
            cipher.DoFinal(output, len);
            // byte[] output = cipher.DoFinal(encryptedData);
            return output;
        }

Add two or more byte array in c#

  byte[] result = arrayResult1.Concat(arrayResult2).Concat(arrayResult3).Concat(arrayResult4).Concat(arrayResult5).Concat(arrayResult6).Concat(arrayResult7).
                                    Concat(arrayResult8).Concat(arrayResult9).Concat(arrayResult10).Concat(arrayResult11).Concat(arrayResult12).ToArray();

Monday 14 December 2015

How to read binary data in ado.net Sqlite

               SQLiteCommand fdCase = new SQLiteCommand("SELECT * FROM record", destination);
                SQLiteDataReader readerCase = fdCase.ExecuteReader();
                if (readerCase.HasRows)
                {
                    int icalc = 1;
                    while (readerCase.Read())
                    {
                        byte[] byteCase = (Byte[])readerCase["DATA"];

by this way you can read binary data

How to change or set service name in window services

In program.cs you can change or set  the service name.

  static void Main()
        {
                        ServiceBase[] ServicesToRun;
            SelfHostService _selfHostService = new SelfHostService();
//Below you can set the service name. In my case service name is PrintAPIHeartTest.
            _selfHostService.ServiceName = "PrintAPIHeartTest";
            ServicesToRun = new ServiceBase[]
            {
                _selfHostService
            };
            ServiceBase.Run(ServicesToRun);

        }


Decompress using GZipStream c#

 /// <summary>
        /// Decompress the Stream
        /// </summary>
        /// <param name="data">Compress data</param>
        /// <returns></returns>
        static byte[] Decompress(byte[] data)
        {
            try
            {
                using (var compressedStream = new MemoryStream(data))
                using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (var resultStream = new MemoryStream())
                {
                    zipStream.CopyTo(resultStream);
                    return resultStream.ToArray();
                }
            }
            catch
            {
                throw;
            }
        }

Request Entity Too Large Web API issue

Please put the below code on OnStart Method.

config.MaxReceivedMessageSize = 2147483647; // use config for this value

  protected override void OnStart(string[] args)
        {
            //while (!Debugger.IsAttached) Thread.Sleep(1000);

            var config = new HttpSelfHostConfiguration("http://localhost");
            config.MaxReceivedMessageSize = 2147483647; // use config for this value
            config.Routes.MapHttpRoute(
               name: "",
               routeTemplate: "{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

Read ByteData from txt file which contains binary data

  byte[] fileBytes = File.ReadAllBytes(@"D:\\byteCompress1.txt");

Web API calling c# with byte data

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost/");
            client.DefaultRequestHeaders.Accept.Add(
               new MediaTypeWithQualityHeaderValue("application/json"));
            byte[] fileBytes = File.ReadAllBytes(@"D:\\byteCompress1.txt");
            InPutData inp = new InPutData();
            inp.inputarray = fileBytes;
            inp.printerName = "GF Printer";
            inp.docName = "test";
            var response = client.PostAsJsonAsync("print/sendprint", inp).Result;
           if (response.IsSuccessStatusCode)
            {
                ///result is true
            }
            else
            {
              // result false
            }

Event logging in window services c#

 EventLog e = new EventLog("Get PrinterError");
 e.WriteEntry("Failed in getting Printerlist, Reason:" + ex.Message);

Web API validation on input field

 string results = "printerName can not be null or empty";
 var resp = new HttpResponseMessage(HttpStatusCode.BadRequest);resp.Content = new StringContent(results);
return resp;

Wednesday 9 December 2015

Find out which Tables are taking up the most space in a SQL Server 2005 Database



SELECT 
 t.NAME AS TableName,
i.name AS indexName,
SUM(p.rows) AS RowCounts,
SUM(a.total_pages) AS TotalPages,
 SUM(a.used_pages) AS UsedPages,
 SUM(a.data_pages) AS DataPages,
(SUM(a.total_pages) * 8) / 1024 AS TotalSpaceMB,
 (SUM(a.used_pages) * 8) / 1024 AS UsedSpaceMB,
 (SUM(a.data_pages) * 8) / 1024 AS DataSpaceMB
FROM
 sys.tables t
INNER JOIN 
 sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
 sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
 sys.allocation_units a ON p.partition_id = a.container_id
WHERE
 t.NAME NOT LIKE 'dt%' AND
i.OBJECT_ID > 255 AND 
 i.index_id <= 1
GROUP BY
 t.NAME, i.object_id, i.index_id, i.name
ORDER BY
 OBJECT_NAME(i.object_id)