Translate

DataTable to C# Class List Converter

Monday, December 25, 2017 Category : , , 0

  public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                foreach (var row in table.AsEnumerable())
                {
                    T obj = new T();

                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);

                            var value = row[prop.Name];
                            if (value == DBNull.Value)
                            {
                                value = null;
                            }
                            //propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                            prop.SetValue(obj, value, null);
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }

Generate class from database table

Sunday, November 19, 2017 Category : 0

https://stackoverflow.com/questions/5873170/generate-class-from-database-table


declare @TableName sysname = 'TableName'
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

ASP.NET MVC , Datatables custom paging

Tuesday, October 3, 2017 Category : , 1

By default datatables load all record from database and then use search in client side. but it often cause problem in large data set, to load from database.

So i implement custom paging and searching using jqery Bootpag pagination
https://codepen.io/SitePoint/pen/jBWOMX

 HTML

 <div class="col-md-4">
        <input type="text" class="form-control" style="float:left;"
               placeholder="Search Style size,Barcode,Product" id="myInputTextField">
    </div>
    <div class="col-md-12" style="margin-top: -10px;">
        <div class="table-responsive" style="margin-top: 0px;">
            <table id="dlWarehouseStock" class="display" cellspacing="0" width="100%">
                <thead>
                    <tr>
                        <th>Barcode</th>
                        <th>Product</th>
                        <th>BrandType</th>
                        <th>Style</th>
                        <th>SupName</th>
                        <th>CPU</th>
                        <th>CS Balance</th>
                        <th>Options</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>

 JQeruy

$(document).ready(function () {


    $('#pagination-here').on("page", function (event, num) {
        //show / hide content or pull via ajax etc
        $("#content").html("Page " + num);
        LoadCentralStockAll("", num, $('#myInputTextField').val());
    });

    $("#myInputTextField").keypress(function (e) {
        if (e.keyCode == 13) {
            if ($('#myInputTextField').val().length == 0) {
                GetTotalNumberOfStyleSize($('#myInputTextField').val());
                LoadCentralStockAll("", 1, "");
            } else {
                debugger;
                GetTotalNumberOfStyleSize($('#myInputTextField').val());
                LoadCentralStockAll("", 1, $('#myInputTextField').val());
            }
        }
    });

});


function LoadCentralStockAll(parameter, pageNumber, searchText) {
    if ($.fn.dataTable.isDataTable('#dlWarehouseStock')) {
        var tables = $('#dlWarehouseStock').DataTable();
        tables.destroy();
    }
    $('#dlWarehouseStock').dataTable({
        "processing": true,
        'paging': false,
        "bLengthChange": false,
        "info": false,
        //"ajax": url + "Process/GetCentralStockByType?Type=" + parameter,
        "ajax": url + "Setup/GetAllstyleSizeBySupIDWithPagination?pageNumber=" + pageNumber + "&searchText=" + searchText + "&stockType=NonZero",
        "columns": [
            { "data": "Barcode" },
            { "data": "PrdName" },
            { "data": "BTName" },
            { "data": "SSName" },
            { "data": "SupName" },
            { "data": "CPU" },
            { "data": "BalQty" },
           {
               "mData": null,
               "bSortable": false,
               "mRender": function (data, type, full) {
                   return '';
               }
           }
        ]
    });
}


function GetTotalNumberOfStyleSize(searchText) {
    $.ajax({
        url: url + 'Setup/GetTotalNumberOfStyleSize',
        data: { 'stockType': 'All', 'searchText': searchText },
        success: function (data) {
            console.log("Total no.");
            console.log(data.data[0].TotalNoOfBarcode);
            var paginationSize = parseInt(data.data[0].TotalNoOfBarcode) / 10;
            if (paginationSize < 1) {
                paginationSize = 1;
            }
            if (data.data.length) {
                $('#pagination-here').bootpag({
                    total: Math.round(paginationSize),
                    page: 1,
                    maxVisible: 5,
                    leaps: true,
                    firstLastUse: true,
                    first: '←',
                    last: '→',
                    wrapClass: 'pagination',
                    activeClass: 'active',
                    disabledClass: 'disabled',
                    nextClass: 'next',
                    prevClass: 'prev',
                    lastClass: 'last',
                    firstClass: 'first'
                });
            } else {
                alert("Invalid !");
            }
        },
        error: function () {
            alert('An error occured try again later');
        }
    });
} 
 

C# Winform DataGridView on Cell Edit Move to Right Cell

Thursday, July 27, 2017 Category : 0

By Default If you press enter on any cell it will move to Down row cell. so i made some tweak, which will move it right side cell.



       private bool trigger = false;
        private void dgForecast_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 2 && e.ColumnIndex < 33)
            {
                ProcessColumnIndex(true);

            }
        }

        private void dgForecast_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                ProcessColumnIndex(false);
                e.Handled = true;
            }
        }

        private void ProcessColumnIndex(bool flag)
        {
            int row = dgForecast.CurrentCell.RowIndex;

            int col = dgForecast.CurrentCell.ColumnIndex;

            if (col == 32)
            {
                col = 2;
                row++;
            }
            else
            {
                if (flag)
                    trigger = true;
                col++;
            }
            dgForecast.CurrentCell = dgForecast.Rows[row].Cells[col];
        }

        private void dgForecast_SelectionChanged(object sender, EventArgs e)
        {
            if (trigger)
            {
                trigger = false;
                SendKeys.Send("{up}");
            }
        }

Javascript Get ASP.NET Application hosting main path

Tuesday, February 21, 2017 Category : 0

Problem Arise when use to set image source using javascript , then after publish in IIS sub directory image is not loaded, for hosting directory miss match. then we can catch the hosting directory , and append to image source.




var dd = '<% =Request.ApplicationPath %>';
                console.log(dd);



        var _baseURL = '<%=Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath.TrimEnd('/') + "/" %>';

C# winform read write any file to Database

Monday, December 26, 2016 0




Browse File for Save to DB

string fileName="";
 object file;
 string ext="";
 private void LoadFile()
        {
            OpenFileDialog OpenFileDialog = new OpenFileDialog();
            OpenFileDialog.Title = "Open File...";
            //OpenFileDialog.Filter = "Binary File (*.bin)|*.bin";
            OpenFileDialog.InitialDirectory = @"C:\";
            if (OpenFileDialog.ShowDialog() == DialogResult.OK)
            {
                byte[] file;
                using (var stream = new FileStream(OpenFileDialog.FileName, FileMode.Open, FileAccess.Read))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        file = reader.ReadBytes((int)stream.Length);
                    }
                }
                fileName = OpenFileDialog.FileName;
                file = file;
                ext = Path.GetExtension(OpenFileDialog.FileName);
            }
        } 
 
During Save operation use file object as byte array and save to database.
for easy save use entity framework .
where i have select datatype for sql server is varbinary(MAX).
 
 View File to user
 
private void ViewDocument(Label lblloc, string fileName)
        {
            try
            {
                if (file == null)
                {
                    MessageBox.Show("No file for view");
                    return;
                }

                SaveFileDialog savefile = new SaveFileDialog();
                // set a default file name
                savefile.FileName = fileName + ext;
                // set filters - this can be done in properties as well
                savefile.Filter = "All files (*.*)|*.*";

                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    // using (StreamWriter sw = new StreamWriter(savefile.FileName))
                    //      sw.WriteLine("Hello World!");

                    ByteArrayToFile(savefile.FileName, file as byte[]);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


  public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream =
                   new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                            System.IO.FileAccess.Write);
                // Writes a block of bytes to this stream using data from
                // a byte array.
                _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

                // close file stream
                _FileStream.Close();

                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}",
                                  _Exception.ToString());
            }

            // error occured, return false
            return false;
        }


C# Open XML SDK ,Excel Read,Write

Category : 0

Installation :
1.https://www.microsoft.com/en-us/download/details.aspx?id=30425
or
2. https://www.nuget.org/packages/DocumentFormat.OpenXml/

Adding Reference :

  • DocumentFormat.OpenXml
  • WindowsBase
 Ref : https://msdn.microsoft.com/en-us/library/office/bb456488.aspx


Write Excel

public void ExportDataTable(DataTable table, string destination)
        {
            using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = workbook.AddWorkbookPart();

                workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();

                workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

                //foreach (System.Data.DataTable table in ds.Tables)
               // {

                    var sheetPart = workbook.WorkbookPart.AddNewPart();
                    var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                    sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                    DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild();
                    string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                    uint sheetId = 1;
                    if (sheets.Elements().Count() > 0)
                    {
                        sheetId =
                            sheets.Elements().Select(s => s.SheetId.Value).Max() + 1;
                    }

                    DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = table.TableName };
                    sheets.Append(sheet);

                    DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                    List columns = new List();
                    foreach (System.Data.DataColumn column in table.Columns)
                    {
                        columns.Add(column.ColumnName);

                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }


                    sheetData.AppendChild(headerRow);

                    foreach (System.Data.DataRow dsrow in table.Rows)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                        foreach (String col in columns)
                        {
                            DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                            cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                            cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                            newRow.AppendChild(cell);
                        }

                        sheetData.AppendChild(newRow);
                    }

                //}
            }
        }
   





Read Excel File

     public static DataSet ExtractExcelSheetValuesToDataTable(string xlsxFilePath, string sheetName)
        {
            DataTable dt = new DataTable();
            DataSet ds = new DataSet();
            using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(xlsxFilePath, true))
            {
                //Access the main Workbook part, which contains data
                WorkbookPart workbookPart = myWorkbook.WorkbookPart;
                WorksheetPart worksheetPart = null;
                if (!string.IsNullOrEmpty(sheetName))
                {
                    Sheet ss = workbookPart.Workbook.Descendants().Where(s => s.Name == sheetName).FirstOrDefault();
                    if(ss == null)
                    {
                        throw new Exception("Sheet name not mathced");
                    }
                    worksheetPart = (WorksheetPart)workbookPart.GetPartById(ss.Id);
                }
                else
                {
                    worksheetPart = workbookPart.WorksheetParts.FirstOrDefault();
                }
                SharedStringTablePart stringTablePart = workbookPart.SharedStringTablePart;
                if (worksheetPart != null)
                {
                    Row lastRow = worksheetPart.Worksheet.Descendants().LastOrDefault();
                    Row firstRow = worksheetPart.Worksheet.Descendants().FirstOrDefault();
                    if (firstRow != null)
                    {
                        foreach (Cell c in firstRow.ChildElements)
                        {
                            string value = GetValue(c, stringTablePart);
                            dt.Columns.Add(value);
                        }
                    }
                    if (lastRow != null)
                    {
                        for (int i = 2; i <= lastRow.RowIndex; i++)
                        {
                            DataRow dr = dt.NewRow();
                            bool empty = true;
                            Row row = worksheetPart.Worksheet.Descendants().Where(r => i == r.RowIndex).FirstOrDefault();
                            int j = 0;
                            if (row != null)
                            {
                                foreach (Cell c in row.Descendants())
                                {
                                    int? colIndex = GetColumnIndex(((DocumentFormat.OpenXml.Spreadsheet.CellType)(c)).CellReference);
                                    if (colIndex > j)
                                    {
                                        dr[j] = "";
                                        j++;
                                    }

                                    if(j == 21)
                                    {
                                        // only for checking
                                    }
                                    //Get cell value
                                    string value = "";
                                   // if (c.ElementAt(0).Count() >0)
                                      //  value=  c.CellValue.Text;
                                     value = GetValue(c, stringTablePart);
                                    //if (!string.IsNullOrEmpty(value))
                                    //    empty = false;
                                    dr[j] = value;
                                    j++;
                                    if (j == dt.Columns.Count)
                                        break;
                                }

                                //foreach (Cell c in row.ChildElements)
                                //{
                                //    //Get cell value
                                //    string value = GetValue(c, stringTablePart);
                                //    //if (!string.IsNullOrEmpty(value))
                                //    //    empty = false;
                                //    dr[j] = value;
                                //    j++;
                                //    if (j == dt.Columns.Count)
                                //        break;
                                //}
                                //if (empty)
                                //    break;
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                }
            }
            ds.Tables.Add(dt);
            return ds;
        }
     
        public static string GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {
            if (cell.ChildElements.Count == 0) return null;
            //get cell value
            string value = cell.ElementAt(0).InnerText;//CellValue.InnerText;
            //Look up real value from shared string table
            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
                value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            return value;
            
        }

        private static int? GetColumnIndex(string cellReference)
        {
            if (string.IsNullOrEmpty(cellReference))
            {
                return null;
            }

            //remove digits
            string columnReference = Regex.Replace(cellReference.ToUpper(), @"[\d]", string.Empty);

            int columnNumber = -1;
            int mulitplier = 1;

            //working from the end of the letters take the ASCII code less 64 (so A = 1, B =2...etc)
            //then multiply that number by our multiplier (which starts at 1)
            //multiply our multiplier by 26 as there are 26 letters
            foreach (char c in columnReference.ToCharArray().Reverse())
            {
                columnNumber += mulitplier * ((int)c - 64);

                mulitplier = mulitplier * 26;
            }

            //the result is zero based so return columnnumber + 1 for a 1 based answer
            //this will match Excel's COLUMN function
            return columnNumber;
        }







Powered by Blogger.