Translate

Home > 2017

2017

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('/') + "/" %>';

Powered by Blogger.