Saturday 24 June 2017

SQL Query Optimization Technique.



1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than '*'.

For Example: Write the query as

SELECT id, first_Emp_name, last_Emp_name, age, subject_Name FROM student_Info_details;

Instead of:

SELECT * FROM student_Info_details;



2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as

SELECT subject_Name, count(subject_Name)
FROM student_Info_details
WHERE subject_Name != 'Science'
AND subject_Name != 'Maths'
GROUP BY subject_Name;

Instead of:

SELECT subject_Name, count(subject_Name)
FROM student_Info_details
GROUP BY subject_Name
HAVING subject_Name!= 'Vancouver' AND subject_Name!= 'Toronto';



3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as

SELECT name
FROM employee_Info
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_Info_details)
AND deptpartment = 'Electronics';

Instead of:

SELECT name
FROM employee_Info
WHERE salary = (SELECT MAX(salary) FROM employee_Info_details)
AND age = (SELECT MAX(age) FROM employee_Info_details)
AND emp_deptpartment = 'Electronics';



4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.

For Example: Write the query as

Select * from product_Detail p
where EXISTS (select * from order_items o
where o.product_Detail_id = p.product_Detail_id)

Instead of:

Select * from product_Detail p
where product_Detail_id IN
(select product_Detail_id from order_items



5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as

SELECT d.deptpartment_id, d.deptpartment
FROM deptpartment d
WHERE EXISTS ( SELECT 'X' FROM employee_Info e WHERE e.deptpartment = d.deptpartment);

Instead of:

SELECT DISTINCT d.deptpartment_id, d.deptpartment
FROM deptpartment d,employee_Info e
WHERE e.deptpartment = e.deptpartment;



6) Try to use UNION ALL in place of UNION.
For Example: Write the query as

SELECT id, first_Emp_name
FROM student_Info_details_class10
UNION ALL
SELECT id, first_Emp_name
FROM sports_team;

Instead of:

SELECT id, first_Emp_name, subject_Name
FROM student_Info_details_class10
UNION
SELECT id, first_Emp_name
FROM sports_team;



7) Be careful while using conditions in WHERE clause.
For Example: Write the query as

SELECT id, first_Emp_name, age FROM student_Info_details WHERE age > 10;

Instead of:

SELECT id, first_Emp_name, age FROM student_Info_details WHERE age != 10;

Write the query as

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE first_Emp_name LIKE 'Chan%';

Instead of:

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE SUBSTR(first_Emp_name,1,3) = 'Cha';

Write the query as

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE first_Emp_name LIKE NVL ( :name, '%');

Instead of:

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE first_Emp_name = NVL ( :name, first_Emp_name);

Write the query as

SELECT product_Detail_id, product_Detail_name
FROM product_Detail
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)

Instead of:

SELECT product_Detail_id, product_Detail_name
FROM product_Detail
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)

Write the query as

SELECT id, name, salary
FROM employee_Info
WHERE deptpartment = 'Electronics'
AND location = 'Surat';

Instead of:

SELECT id, name, salary
FROM employee_Info
WHERE deptpartment || location= 'ElectronicsSurat';

Use non-column expression on one side of the query because it will be processed earlier.

Write the query as

SELECT id, name, salary
FROM employee_Info
WHERE salary < 25000;

Instead of:

SELECT id, name, salary
FROM employee_Info
WHERE salary + 10000 < 35000;

Write the query as

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE age > 10;

Instead of:

SELECT id, first_Emp_name, age
FROM student_Info_details
WHERE age NOT = 10;

8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as

SELECT id FROM employee_Info
WHERE name LIKE 'Bhavdip%'
and location = 'Surat';

Instead of:

SELECT DECODE(location,'Surat',id,NULL) id FROM employee_Info
WHERE name LIKE 'Bhavdip%';

9) To store large binary objects, first place them in the file system and add the file path in the database.

10) To write queries which provide efficient performance follow the general SQL standard rules. 

Improve SQL Query Performance

1. Use EXISTS instead of IN to check existence of data.
2. Avoid * in SELECT statement. Give the name of columns which you require.
3. Choose appropriate Data Type. E.g. To store strings use varchar in place of text data type. Use text data type, whenever you need to store large data (more than 8000 characters).
4. Avoid nchar and nvarchar if possible since both the data types takes just double memory as char and varchar.
5. Avoid NULL in fixed-length field. In case of requirement of NULL, use variable-length (varchar) field that takes less space for NULL.
6. Avoid Having Clause. Having clause is required if you further wish to filter the result of an aggregations.
7. Create Clustered and Non-Clustered Indexes.
8. Keep clustered index small since the fields used in clustered index may also used in non-clustered index.
9. Most selective columns should be placed leftmost in the key of a non-clustered index.
10. Drop unused Indexes.
11. Better to create indexes on columns that have integer values instead of characters. Integer values use less overhead than character values.
12. Use joins instead of sub-queries.
13. Use WHERE expressions to limit the size of result tables that are created with joins.
14. Use TABLOCKX while inserting into a table and TABLOCK while merging.
15. Use WITH (NOLOCK) while querying the data from any table.
16. Use SET NOCOUNT ON and use TRY- CATCH to avoid deadlock condition.
17. Avoid Cursors since cursor are very slow in performance.
18. Use Table variable in place of Temp table. Use of Temp tables required interaction with TempDb database which is a time taking task.
19. Use UNION ALL in place of UNION if possible.
20. Use Schema name before SQL objects name.
21. Use Stored Procedure for frequently used data and more complex queries.
22. Keep transaction as small as possible since transaction lock the processing tables data and may results into deadlocks.
23. Avoid prefix “sp_” with user defined stored procedure name because SQL server first search the user defined procedure in the master database and after that in the current session database.
24. Avoid use of Non-correlated Scalar Sub Query. Use this query as a separate query instead of part of the main query and store the output in a variable, which can be referred to in the main query or later part of the batch.
25. Avoid Multi-statement Table Valued Functions (TVFs). Multi-statement TVFs are more costly than inline TVFs.

Sunday 18 June 2017

Demo Project

using OrderDemoMODEL;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OrderDemoREPOSITORY
{

    public class MST_OrderNoRepository : MST_OrderNo_IRepository
    {
        private OrderDemoEntities Context;

        public MST_OrderNoRepository(OrderDemoEntities _Context)
        {
            this.Context = _Context;
        }
        public string getOrderNo()
        {
            return Context.Get_Order_no().First().ToString();
        }
        public List<Get_Recored_Result> getOrderRecored()
        {
            return Context.Get_Recored().ToList();
        }
        public int InsertUpdate(String Str, string Detal, out int ReturnValue)
        {
            ReturnValue = 0;
            var OutParam = new ObjectParameter("ReturnValue", typeof(int));
            Context.insertupdate(Str, Detal, OutParam);
            return Convert.ToInt16(OutParam.Value);
        }

        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    Context.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
*****************************************************************************
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    @Styles.Render("~/bundles/Content/css")
    @Scripts.Render("~/bundles/Content/Js")


    <style>
        .error {
            border: 1px solid red;
        }

        .hide {
            visibility: hidden;
        }
    </style>
</head>

<body>
    <div class="Container panel-group">
        <div class="row panel panel-default" style="margin-top: 10px;">
            <div class="col-sm-3 panel-body">
                <label>Order No :</label><input id="OrderNo" type="text" class="Required" value="@ViewBag.OrderNo" />
            </div>
            <div class="col-sm-3 panel-body">
                <label>Order Date :</label>
                <input type="text" id="datepicker" class="Required">
            </div>
            <div class="col-sm-3 panel-body">
                <label>Party Name :</label><input id="Orderparty" type="text" class="Required" />
            </div>
            <div class="col-sm-3 panel-body">
                <input type="button" id="SaveID" value="Save" />
                <input type="button" id="ClearID" value="Clear" />
            </div>
        </div>
        <table id="example" class="display nowrap dataTable dtr-inline" cellspacing="0" width="100%" role="grid" aria-describedby="example_info" style="width: 100%;">
            <thead>
                <tr role="row">
                    <td>OrderDetail ID</td>
                    <td>Order ID</td>
                    <td>OrderItemNo</td>
                    <td>Order OrderNo</td>
                    <td>Order Quntity</td>
                    <td style="display: none">Orderdate</td>
                    <td style="display: none">TotalAmt</td>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <td>OrderDetail ID</td>
                    <td>Order ID</td>
                    <td>OrderItemNo</td>
                    <td>Order Amt</td>
                    <td>Order Quntity</td>
                    <td style="display: none">Orderdate</td>
                    <td style="display: none">TotalAmt</td>
                </tr>
            </tfoot>

        </table>
    </div>
</body>

</html>
<script>
    $(function () {

        $("#datepicker").datepicker().datepicker("setDate", new Date());
    });
</script>
<script type="text/javascript">

    $("#SaveID").click(function () {
        var Flag = true;
        $(".Required").each(function () {
            if ($(this).val().length === 0) {
                $(this).addClass('error');
                Flag = false;
            }
        });
        if (Flag) {
            debugger
            var StrXml = { "OrderNo": $("#OrderNo").val(), "OrderID": 0, "OrderDate": $("#datepicker").val(), "OrderQuntity": "1", "OrderAmt": "1400" }

            var StrDetail = { "OrderDetailID": 0, "OrderID": 0, "OrderAmt": "500", "OrderQuntity": "2", "OrderItemNo": $("#OrderNo").val() }
            $.ajax({
                type: "POST",
                url: '@Url.Action("SetDate", "Home")',
                data: JSON.stringify({ StrXml: StrXml, StrDetail: StrDetail, Odate: $("#datepicker").val() }),
                contentType: 'application/json; charset=utf-8',
                success: function (Result) {
                    //alert(Result);
                }
            });

        }
    });
    $(".Required").blur(function () {
        if ($(this).val().length != 0) {
            $(this).removeClass("error")
        }

    });

    $(document).ready(function () {

        Display();
    });
    function Display() {

        var oTable = $('#example').dataTable({
            responsive: true,
            "processing": true,
            "serverSide": true,
            "bSort": false,
            "sAjaxSource": "@Url.Action("getData", "Home")",
            "iDisplayLength": 10,
            "aLengthMenu": [5, 10, 50, 100, 200],
            "bDestroy": true,
            "bInfo": true,
            "sEmptyTable": "Loading data from server",
            "searching": false,
            "bLengthChange": true,
            "bFilter": true,
            "bPaginate": true,
            "autoWidth": true,
            "sScrollY": "400px",
            "sScrollX": "100px",
            "bScrollCollapse": true,
            "sPaginationType": "simple_numbers",
            "paging": true, "fnServerData": function (sSource, aoData, fnCallback) {

                aoData.push(
                   { "name": "SearchCritearea", "value": "" });

                $.ajax({
                    "dataType": 'json',
                    "type": "POST",
                    "url": sSource,
                    "data": aoData,
                    "success": fnCallback
                }).done(function (json) {

                    //$(".dataTables_scrollFootInner").find("#Request_Cr").html(json.TotalRequestCr);
                    //$(".dataTables_scrollFootInner").find("#Request_Cnt").html(json.TotalRequestCnt);;

                    //$('#loading-indicator').hide();
                });
            },
            "fnInitComplete": function (oSettings, json) {
                //$(".dataTables_scrollFootInner").find("#Request_Cr").html(json.TotalRequestCr);
                //$(".dataTables_scrollFootInner").find("#Request_Cnt").html(json.TotalRequestCnt);;

            },
            "columns": [

                          {
                              "sClass": " OrderDetailID",
                              "render": function (data, type, row, meta) {
                                  return row[0];
                              }
                          },
                          {
                              "sClass": " OrderID",
                              "render": function (data, type, row, meta) {
                                  return row[1];
                              }
                          },
                          {
                              "sClass": " OrderItemNo",
                              "render": function (data, type, row, meta) {
                                  return row[2];
                              }
                          },
                          {
                              "sClass": " OrderNo",
                              "render": function (data, type, row, meta) {
                                  return row[3];
                              }
                          },
                           {
                               "sClass": "Center OrderQuntity",
                               "render": function (data, type, row, meta) {
                                   return row[4];
                               }
                           },
                           {
                               "sClass": "hide OrderQuntity",
                               "render": function (data, type, row, meta) {
                                   return row[5];
                               }
                           },
                           {
                               "sClass": "hide OrderQuntity",
                               "render": function (data, type, row, meta) {
                                   return row[6];
                               }
                           }

            ]
        });
    }
</script>
*********************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;

namespace OrderDemo.App_Start
{
    public class BundleConfig
    {
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new StyleBundle("~/bundles/Content/css").Include("~/Content/css/bootstrap.css", "~/Content/css/jquery-ui.css", "~/Content/css/jquery.dataTables.min.css"));

            bundles.Add(new ScriptBundle("~/bundles/Content/Js").Include("~/Content/js/jquery-3.2.1.js", "~/Content/js/bootstrap.js", "~/Content/js/jquery-ui.js", "~/Content/js/jquery.dataTables.min.js"));

            BundleTable.EnableOptimizations = true;
        }
    }
}
*********************************************************************************
using OrderDemoMODEL;
using OrderDemoREPOSITORY;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;

namespace OrderDemo.Controllers
{
    public class HomeController : Controller
    {
        MST_OrderNo_IRepository _MST_OrderNo_IRepository = new MST_OrderNoRepository(new OrderDemoEntities());
        //
        // GET: /Home/

        public ActionResult Index()
        {
            ViewBag.OrderNo = _MST_OrderNo_IRepository.getOrderNo();
            return View("Index");
        }
        [HttpPost]
        public JsonResult SetDate(TRN_ORDER_MASTER StrXml, TRN_ORDER_DETAILS StrDetail, string Odate)
        {
            var SuccessFlag = 0;
            string xml = "<TRN_ORDER_MASTER><OrderID>" + StrXml.OrderID + "</OrderID><OrderNo>" + StrXml.OrderNo + "</OrderNo><OrderDate>" + StrXml.OrderDate + "</OrderDate><OrderQuntity>" + StrXml.OrderQuntity + "</OrderQuntity><OrderAmt>" + StrXml.OrderAmt + "</OrderAmt></TRN_ORDER_MASTER>";

            string xmlDetail = "<TRN_ORDER_DETAILS><OrderDetailID>" + StrDetail.OrderDetailID + "</OrderDetailID><OrderID>" + StrDetail.OrderID + "</OrderID><OrderQuntity>" + StrDetail.OrderQuntity + "</OrderQuntity><OrderAmt>" + StrDetail.OrderAmt + "</OrderAmt><OrderItemNo>" + StrDetail .OrderItemNo+ "</OrderItemNo></TRN_ORDER_DETAILS>";
            
            SuccessFlag = _MST_OrderNo_IRepository.InsertUpdate(xml, xmlDetail, out SuccessFlag);
            
            return Json(SuccessFlag, JsonRequestBehavior.AllowGet);
        }

        public static string Serialize(object dataToSerialize)
        {
            if (dataToSerialize == null) return null;

            using (StringWriter stringwriter = new System.IO.StringWriter())
            {
                var serializer = new XmlSerializer(dataToSerialize.GetType());
                serializer.Serialize(stringwriter, dataToSerialize);
                return stringwriter.ToString();
            }
        }

        public static T Deserialize<T>(string xmlText)
        {
            if (String.IsNullOrWhiteSpace(xmlText)) return default(T);

            using (StringReader stringReader = new System.IO.StringReader(xmlText))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
        }
        [HttpPost]
        public JsonResult getData(JQueryDataTable aoData)
        {
            List<Get_Recored_Result> _List = _MST_OrderNo_IRepository.getOrderRecored();
            var Result = from c in _List
                         select new[]
                         {
                             c.OrderDetailID.ToString(),c.OrderID.ToString(),c.OrderItemNo.ToString(),c.OrderNo.ToString(),c.OrderQuntity.ToString(),c.TotalAMt.ToString(),c.OrderDate.ToString()           
            };

            return Json(new
            {
                aaData = Result
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
********************************************************************************

Saturday 17 June 2017

Datatable To Pdf using ITextsharp in Webservice

Document pdfDoc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20);
            String newfile = "";
            String newappfile = "";
            try
            {
                newappfile = DateTime.Now.ToString("MMddyyyy") + "_" + DateTime.Now.ToString("hhmmss") + ".pdf";
                newfile = HttpContext.Current.Server.MapPath("~/ExportPdfFile/" + newappfile);
             

                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(newfile, FileMode.Create));
                //PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
                //PdfWriter.GetInstance(pdfDoc, new FileStream(HttpContext.Current.Server.MapPath("~/ExportPdfFile/"  + DateTime.Now.ToString("MMddyyyy") + "_" + DateTime.Now.ToString("hhmmss") + ".pdf"), FileMode.Create));
                pdfDoc.Open();
                //Chunk c = new Chunk("" + System.Web.HttpContext.Current.Session["CompanyName"] + "", FontFactory.GetFont("Verdana", 11));

                //Paragraph p = new Paragraph();
                //p.Alignment = Element.ALIGN_JUSTIFIED_ALL;

                //p.Add(c);
                //pdfDoc.Add(p);

                //--- Add Logo of PDF ----
                string Page = pdfDoc.PageNumber.ToString();
                string imageFilePath = "";  //System.Web.HttpContext.Current.Server.MapPath("~/img/bluestar_logo.png");
                //iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

                //Resize image depend upon your need
                //jpg.ScaleToFit(120f, 100f);
                //Give space before image
                //jpg.SpacingBefore = 0f;
                //Give some space after the image
                //jpg.SpacingAfter = 1f;
                //jpg.Alignment = Element.HEADER;
                //pdfDoc.Add(jpg);
                iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7);
                //--- Add new Line ------------
                Phrase phrase1 = new Phrase(Environment.NewLine);
                pdfDoc.Add(phrase1);

                //-------------------------------

                DataTable dt = myDataTable;//Datatable Object
                if (dt != null)
                {
                    //---- Add Result of DataTable to PDF file With Header -----
                    PdfPTable pdfTable = new PdfPTable(dt.Columns.Count);
                    //relative col widths in proportions - 1/3 and 2/3



                    pdfTable.TotalWidth = 830f;
                    //fix the absolute width of the table
                    pdfTable.LockedWidth = true;
                    //relative col widths in proportions - 1/3 and 2/3
                    //float[] widths = new float[] { 2.5f, 2f, 2f, 2f, 2f, 2f, 2.5f, 3f, 3f, 3f, 2f, 2f, 2.5f, 3f, 3f, 2f, 2f , 2.5f, 2f, 2f };
                    //pdfTable.SetWidths(widths);


                    pdfTable.DefaultCell.Padding = 3;
                    pdfTable.WidthPercentage = 100; // percentage
                    pdfTable.DefaultCell.BorderWidth = 1;
                    pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                    foreach (DataColumn column in dt.Columns)
                    {
                        //pdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#b4ceec"));
                        //pdfTable.AddCell(FormatHeaderPhrase(column.ColumnName));
                        if (column.ColumnName == "STONEID")
                        {
                            pdfTable.AddCell(new PdfPCell(new Phrase(column.ColumnName, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#003e7e"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3, BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#D4E1F0")) });
                        }
                        else
                        {
                            pdfTable.AddCell(new PdfPCell(new Phrase(column.ColumnName, FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#003e7e"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3, BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#D4E1F0")) });
                        }
                    }
                    pdfTable.HeaderRows = 1; // this is the end of the table header
                    pdfTable.DefaultCell.BorderWidth = 1;

                    //foreach (DataRow row in dt.Rows)
                    //{
                    //    foreach (object cell in row.ItemArray)
                    //    {
                    //        //assume toString produces valid output

                    //        pdfTable.AddCell(FormatPhrase(cell.ToString()));
                    //    }
                    //}
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (i % 2 == 0)
                            {
                                if (j == 7 || j == 8 || j == 9)
                                {
                                    pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_RIGHT, BorderWidth = 1, Padding = 3 });
                                }
                                else
                                {
                                    if (j == 1 || j == 2)
                                    {
                                        pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3 });
                                    }
                                    else
                                    {
                                        pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3 });
                                    }
                                }
                            }
                            else if (i % 2 != 0)
                            {
                                if (j == 7 || j == 8 || j == 9)
                                {
                                    pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_RIGHT, BorderWidth = 1, Padding = 3, BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#D3D3D3")) });
                                }
                                else
                                {
                                    if (j == 1 || j == 2)
                                    {
                                        pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3, BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#D3D3D3")) });
                                    }
                                    else
                                    {
                                        pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3, BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#D3D3D3")) });
                                    }
                                }
                            }

                            else
                            {
                                pdfTable.AddCell(new PdfPCell(new Phrase(dt.Rows[i][j].ToString(), FontFactory.GetFont(FontFactory.HELVETICA, 8, new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#000000"))))) { HorizontalAlignment = Element.ALIGN_CENTER, BorderWidth = 1, Padding = 3 });
                            }

                        }
                    }

                 
                    pdfDoc.Add(pdfTable);
                }
                pdfDoc.Close();

                //String stReturnFileName = HttpContext.Current.Server.MapPath(Common.GetConfigValue("PdfRootFolder")) + Convert.ToString(HttpContext.Current.Session["party_id"]) + "\\" + DateTime.Now.ToString("MMddyyyy") + "_" + DateTime.Now.ToString("hhmmss") + ".pdf";

                //HttpContext.Current.Response.ContentType = "application/pdf";
                //HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
                //System.Web.HttpContext.Current.Response.Write(pdfDoc);
                //HttpContext.Current.Response.Flush();
                ////HttpContext.Current.Response.End();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();

                //HttpContext.Current.Response.Clear();
                //HttpContext.Current.Response.ContentType = "application/pdf";
                //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + DateTime.Now.ToString("MMddyyyy") + "_" + DateTime.Now.ToString("hhmmss") + ".pdf");
                ////HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath("~/ExportPdfFile/" + DateTime.Now.ToString("MMddyyyy") + "_" + DateTime.Now.ToString("hhmmss") + ".pdf"));
                //byte[] byteArray = File.ReadAllBytes(newfile);

                //HttpContext.Current.Response.BinaryWrite(byteArray);



            }
            catch (DocumentException de)
            {
                //System.Web.HttpContext.Current.Response.Write(de.Message);
            }
            catch (IOException ioEx)
            {
                //System.Web.HttpContext.Current.Response.Write(ioEx.Message);
            }
            catch (Exception ex)
            {
                //System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
            return newappfile; //Pdf File Path

Saturday 10 June 2017

How To Encrypt and Decrypt Data using Sql Server

2.1 ) For get how many certificate and symetric key

select * from sys.certificates
select * from sys.symmetric_keys

2.2)  now one by one remove it

drop symmetric key SymmetricKey1
drop certificate Certificate1
drop master key

2.3) now cretae first master key

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'PassWord';

2.4) cretae certificate and symertic key
2.4.1) GO
CREATE CERTIFICATE Certificate1
WITH SUBJECT = 'Protect Data';
2.4.2)
CREATE SYMMETRIC KEY SymmetricKey1
 WITH ALGORITHM = AES_128
 ENCRYPTION BY CERTIFICATE Certificate1;

-----------------------------Encrypt Data-----------------------------

OPEN SYMMETRIC KEY SymmetricKey1
DECRYPTION BY CERTIFICATE Certificate1;
GO
select EncryptByKey (Key_GUID('SymmetricKey1'),'Hello')

GO
-- Closes the symmetric key
CLOSE SYMMETRIC KEY SymmetricKey1;

---------------------------Decrypt data--------------------------------

OPEN SYMMETRIC KEY SymmetricKey1
DECRYPTION BY CERTIFICATE Certificate1;
SELECT  CONVERT(varchar, DecryptByKey(EncryptByKey (Key_GUID('SymmetricKey1'),'Hello') ))
CLOSE SYMMETRIC KEY SymmetricKey1

Saturday 3 June 2017

How to Increase Message Size Quota in REST Service.


<system.serviceModel>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  <services>
    <service  name="StockAPI.stock">
      <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="StockAPI.Istock" />
      <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
    </service>
  </services>
  <bindings>
    <webHttpBinding>
      <binding maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" >
        <readerQuotas maxDepth="2000000" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      </binding>
    </webHttpBinding>
  </bindings>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webBehavior">
        <webHttp helpEnabled="true" />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior name="">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

SqlDataBaseLibrary

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using AOS.Repository.Infrastructure; using S...