Saturday, December 15, 2018

Angular reusable Grid with Web api


Hi guys,
Today I’m going to show custom angular grid with asp.net web api. This grid implementation is very easy and also can reuse it.
Features :can change the data orientation (eg. div based , table or any custom)  pagination , searching





Appreciate any comment on this.


Wednesday, December 12, 2018

Create String more and less text component in Angualr 2+


When we’re working with long strings in application user interfaces it distracts the user interfaces. Here is the example





                                                                                         

In the above example there is paging grid with 10 rows per page. The better way to represent the data, we can show first 250 characters for much better user experience.
Solution for overcome of this sort of problems is provided some of the data to get the idea.(or else without showing it J) , we can provide a link with having two options. Showing more or less link with the paragraph (default less) and user can toggle it.



Ok , now let come to development in angular. In angular we can use pipes for that but their some limitation to do that. In this example I’m going to component for that and reuse it.  We can use Parent and Child component with @Input  for this.


ParentComponent.html



ChildComponent.html



ChildComponent.ts ("app-show-more" selector)



How to use it using npm package 

Step 1 :Install npm package
npm install show-less-more-string

Step 2import module 
import { ShowLessMoreStringModule} from 'show-less-more-string';

imports: [
    BrowserModule,
    AppRoutingModule,
    ShowLessMoreStringModule
  ]

Step 3 :How to use 
<app-show-more [_longString]='YourString' [_length]=25> </app-show-more>

That's all.Happy Coding


Monday, January 15, 2018

Asp.net mvc with jquery reuserble model dialog for adding reference data (e.g. Employee type, Termination Type)




In production normally used lot of master data with separate user interface for adding them. As an example if user goes to edit the employee with remarks which is a dropdown to select the particular remark of the control. What if the suggested remarks isn’t in the controller then user has to go the particular screen to add the remark and then has to refresh the current page for getting updated remarks.
In the above case what if it’s there any option for adding remark to the control itself without refreshing the page. As a common solution we can give common reusable interface for adding remark or whatever in to the control with adding few properties.
What we have to it just double click the dropdown and add items and it will updated the database and control itself with new data.

<select id="cmbResignReasonCategory"
class=" addDropDown"
data-NatTableName="hrm.ResignReasonCategory"
data-NatColName="ResignReasonCategoryName">
</select>

 Explanation
·         class=" addDropDown"
                This is the key class for fire the double click event in the control
·         data-NatTableName="hrm.ResignReasonCategory"
this is html5 data attribute for getting table name which is used to populate the dropdown

·         data-NatColName="ResignReasonCategoryName
o   This the table column name which is related to the table.

This is the only configuration is needed for getting this feature.

Technical Explanation:
The entire idea is very simple, when double click the control it is triggered the event which is used the following java script.

    <script>
    var NatDropDownAdd = function () {
        this.NatTableName = '';
        this.NatColName = '';
        this.NatValue = '';
        this.NatSavedID = 0;

    }

    var optionModl = function () {
        this.text = '';
    }
 
    $(document).ready(function (e) {
        $(document).on("dblclick", ".addDropDown", function (ee) {

            debugger;

            $("#CustomAddItem").modal();
            $("#NatSave").removeAttr("data-NatControlID");
            $("#NatSave").attr("data-NatControlID", $(this).attr('id'));
            var name = [];
            var input = $("#" + $(this).attr('id')).find("option").each(function (i) {
                debugger;
                if ($(this).val() != '0') {
                    var obj = new optionModl();
                    obj.text = $(this).text();
                    name.push(obj);
                }
            });
            $("#NatGet").html('');
            $("#NatGet").append(BindTable(name));

        });

        $(document).on("click", ".NatSave", function (ee) {
            debugger;
            var obj = new NatDropDownAdd();

            var natID = $(this).attr('data-NatControlID');

            obj.NatTableName = $('#' + natID).attr('data-NatTableName');
            obj.NatColName = $('#' + natID).attr('data-NatColName');
            obj.NatValue = $('#txtAddDropDownItem').val();

            if (obj.NatValue.length > 0) {
                ajaxCall('Testing/SavedDropDownItemAdd', { obj: obj }, function (obj) {
                    debugger;
                    $('#' + natID).append("<option value=" + obj.NatSavedID + " selected='selected'>" + obj.NatValue + "</option>");
                    $('#txtAddDropDownItem').val('');
                    $("#CustomAddItem .close").click()
                });
            }
            else {
                showMessage("Invalid value", "W");
            }
        });


function ajaxCall(url, parameters, successCallback) {
    //show loading... image
    //
 
    $.ajax({
        type: 'POST',
        url: rootUrl + url,
        timeout: 0,
        data: JSON.stringify(parameters),
        contentType: 'application/json;',
        dataType: 'json',
        success: successCallback,
        error: function (request, status, error) {
           
            console.log(request.responseText);
         
        } });
}

function BindTable(lst){

    var tbl = "<table id='x' class='table   table-striped table-bordered table-condensed bindTableSort tablesorters' >";
 
    //table header
    if (lst.length > 0) {
        tbl += "<thead> <tr style='font-weight:bold'>"
        tbl += "<th style='font-size: 12px !important;font-weight: bold !important;background-color: #f1f1f1;padding: 5px !important '>" + "#"+ "</th>";
            for (var i = 0; i < Object.keys(lst[0]).length; i++) {
                tbl += "<th class='" + Object.keys(lst[0])[i] + "' style='font-size: 12px !important;font-weight: bold !important;background-color: #f1f1f1;padding: 5px !important '>" + Object.keys(lst[0])[i] + "</th>";
            }
            tbl += "</tr></thead>";


            tbl += "<body>  "
           
            for (var i = 0; i < lst.length; i++) {
                tbl += "<tr>";
                tbl += "<td> " + (i + 1) + "</td>";
                for (var j = 0; j < Object.keys(lst[i]).length; j++) {
                    tbl += "<td class='" + Object.keys(lst[i])[j] + "'>" + lst[i][Object.keys(lst[i])[j]] + "</td>";
                }
                tbl += "</tr>";
            }
            tbl += " </body>";
    }
    tbl += "</table>"
    $('.bindTableSort').trigger('update');
    return tbl;
}

    });

    </script>
========================================================================


Model popup
    <div class="modal fade" id="CustomAddItem" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Dropdown Item</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group row">
                        <label class="control-label col-lg-2 col-md-2 col-sm-2" for="email">Value:</label>
                        <div class="col-lg-10  col-md-10 col-sm-10">
                            <div class="input-group">
                                <input type="text" class="form-control tab1 input-sm" id="txtAddDropDownItem" />
                                <span class="input-group-btn">
                                    <button type="button" id="NatSave" class="btn btn-primary input-sm NatSave">
                                        Save
                                    </button>
                                </span>
                            </div>

                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-lg-12 col-md-12 col-sm-12">
                            <div id="NatGet"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

========================================================================
Serverside

  [HttpPost]
        public JsonResult SavedDropDownItemAdd(NatDropDownModel obj)
        {

            string s=" Insert into " + obj.NatTableName + "  (" + obj.NatColName + ",EnteredBy,EnteredOn) values('" + obj.NatValue.ToUpper() + "'"    ); SELECT CAST(scope_identity() AS int)";
            int newID;
            using (SqlConnection con = new SqlConnection("YOURCONNECTIONSTRING"))
            {
                 using (SqlCommand insertCommand = new SqlCommand(s, con))
                {
                    con.Open();
                    newID = (int)insertCommand.ExecuteScalar();

                    if (con.State == System.Data.ConnectionState.Open) con.Close();
                 
                }
            }
            obj.NatSavedID = newID;
            return Json(obj, JsonRequestBehavior.AllowGet);



        }
========================================================================
Database Table

CREATE TABLE [HRM].[ResignReasonCategory](
[ResignReasonCategoryID] [smallint] IDENTITY(1,1) NOT NULL,
[ResignReasonCategoryName] [varchar](100) NULL

 CONSTRAINT [PK_ResignReasonCategory] PRIMARY KEY CLUSTERED
(
[ResignReasonCategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]


 ========================================================================

Add these file into the _Layout page.
That’s all


Thursday, February 19, 2015

Common method for INSERT,UPDATE ,DELETE (part 01)



Hi guys
Last few months I couldn’t blog any post; here is the first one in 2015
When we are developing database driven application, INSERT,UPDATE and DELETE operations are frequently used.in early we develop (write) entire code to against the database eg. (create sqlconnection,command,Tansaction object etc.).
Then ORM introduced by Microsoft which is Entity Framework (other ORM tool also available Subsonic,nhibernate etc), It provides more flexibility way to accessing data base. It also has some drawbacks (multiple database, memory consumption etc).

This post is about the INSERT,UPDATE and DELETE with SqlTransaction using common method to reduce code duplication and coding less method to saving data in database.

Common Class:
    public class Tra : IDisposable
    {
        SqlTransaction tra;
        SqlConnection connection = null;
        public Tra()
        {
            if (connection == null)
            {
                connection = new SqlConnection(sqlConnection);
            }
        }
        
        public   long Save(string query,bool isIdentity,CommandType cmdType, params SqlParameter[] paras)
        {          
            try
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }

                SqlCommand command = new SqlCommand();
                if (tra == null)
                {
                    tra = connection.BeginTransaction();
                }
                command.Transaction = tra;
                command.Connection = connection;
                if (cmdType == CommandType.StoredProcedure)
                {
                    command.CommandType = CommandType.StoredProcedure;
                }
                else
                {
                    command.CommandType = CommandType.Text;
                }
                    
                command.CommandText = query;
                command.Parameters.AddRange(paras);
                long x;
                if (isIdentity)
                {
                    x = long.Parse(command.ExecuteScalar().ToString());
                }
                else
                {
                    x = long.Parse(command.ExecuteNonQuery().ToString());
                }
                return x;
            }
            catch (Exception ex)
            {

                tra.Rollback();
                throw ex;
            }
        }

        public SqlTransaction sqlTransaction { get { SqlTransaction tra=null; return tra; } }
       
        public string sqlConnection { get { return @" PUT CONNECTION STRING"; } }

        public void Commit()
        {
            tra.Commit();
        }

        public void Dispose()
        {
            tra.Dispose();
        }
    }


Calling:
            try
            {
                using (var tra = new Tra())//required
                {// required

                 var a = tra.Save(@"insert into dbo.Table_1 (name) values (@name) SELECT SCOPE_IDENTITY()",true,CommandType.Text,
                                    new SqlParameter("@name", "test1"));

                    var b = tra.Save(@"insert into dbo.Table_2 (name) values (@name)", false,CommandType.Text,
                                     new SqlParameter("@name", "test1"));


                    tra.Commit();//required
                }//
                
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

        }

HAPPY CODING :)

Tuesday, November 18, 2014

Asp.net Binding


Asp.net Data binding that provides much easy way to manipulate data to the control eg.gridview,dropdownlist etc
I’ve notice when we are binding there are some unnecessary codes
 Dropdownlist1.DataTextField = "JObName";
 Dropdownlist1.DataValueField = "JobID"
 Dropdownlist1.DataSource = lstJobs;
 Dropdownlist1.DataBind();
We’re calling DataBind() method to asking to binding.totaly 4 lines of codes is required to bind dropdownlist.what is if we have common method to call to binding.
to find a way to overcome this issue in mind, I thought to create common method to bind it .oh no situation getting will be worsen , have to be specified to each of the  control to bind. Generic is there to solve my issue.
I wrote generic extension method to bind all controls…..
Here is the code…
    public static class EasyBinds
    {
        public static void EasyBind<T>(this Control ct, T t,   string ValueMember = "", string DisplayMember = "")
        {
            Utility<T>.CustomBind(ct, t,  ValueMember, DisplayMember);
        }
    }

    public static class Utility <T2>
    {
        public static void CustomBind(Control gv, T2 lst, string display = null, string value = null)
        {
            if (gv is GridView)
            {
                ((GridView)gv).DataSource = lst;
                ((GridView)gv).DataBind();
            }
            else if (gv is DropDownList)
            {
                ((DropDownList)gv).DataTextField = display;
                ((DropDownList)gv).DataValueField = value;
                ((DropDownList)gv).DataSource = lst;
                ((DropDownList)gv).DataBind();
            }
            else if(gv is ListBox)
            {
                ((ListBox)gv).DataTextField = display;
                ((ListBox)gv).DataValueField = value;
                ((ListBox)gv).DataSource = lst;
                ((ListBox)gv).DataBind();
            }
            else
            {
                throw new Exception("Invalid control to bind");
            }
        }
    }

Calling to method
GridView1.EasyBind<List<Employee>>(lst);
DropDownList2.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");
ListBox1.EasyBind<List<Job>>(lstJobs, "JObName", "JobID");

Happy coding...

Monday, November 17, 2014

Working With Asp.net GRIDVIEW

Lets play with asp.net GRIDVIEW
hi guys, today I’m going to demonstrate working with grid view with different situations.asp.net provides much more flexible way to (tabular) to represent data  .keep it mind what every server tags finally converted to the classical html code (GRIDview to html table).
What is the easiest way to bind grid view?
1)Using Automaically Genarated columns
This method directly bind all the data source columns into grid.(good for only display data)
2)BoundField
If you’re not working data key fields in bound filed then you can’t able to get the selected cell value using column name , have to work with index?
Working with index like calling to trouble????????????????????
So what is the better way?
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"  DataKeyNames="EmpNo,EmpName"
        ShowHeaderWhenEmpty="True">
        <Columns>
            <asp:BoundField HeaderText="EmpNO" DataField="EmpNO" />
            <asp:BoundField HeaderText="EmpName" DataField="EmpName" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:DropDownList ID="DropDownList1" runat="server"        >
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            [Data not found]
        </EmptyDataTemplate>
    </asp:GridView>
Above code snippet shows in yellow color, to mark the column name as data key names. Then we can access the columns using data key names.
Eg. Int empID=(int)GridView1.DataKeys[0]["EmpNo"];

3)Template Filed
If we are using totally template fieds like lable,textbox it also very secure (can access data via its id) way to working with data, but it take times to develop. In exceptional scenario like add dropdown list then you’ll have to use it.

Here with I’ve attached code which contained working with selected dropdown item in grid view and events.

Happy coding.
(thre're more alternative way can find on internet)

Sunday, September 28, 2014

Jquery Number to Word alert

Hi guys, today I’m going to demonstrate jquery alert box. Recently I was received a project by manager and that is invoicing and payment system and i pointed out sometimes I also bit difficultly to entering the prices. , Because sometime I enter values incoreclty.to avoid the same issue to users, I decided to build the alert box to display the value in the text box.
 easy configuration , just need to add the  class="WordToNum" to textbox

Entire code snippt:
<style type="text/css">
        #xx a IMG
        {
            display: none;
        }
     
        #PageDiv
        {
        }
        .bubble
        {
            background-color: #F2F2F2;
            border-radius: 5px;
            box-shadow: 0 0 6px #B2B2B2;
            display: inline-block;
            padding: 10px;
            position: relative;
            vertical-align: top;
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
        }
     
        .bubble::before
        {
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
            content: "\00a0";
            display: block;
            position: absolute;
            transform: rotate( 29deg ) skew( -35deg );
            -moz-transform: rotate( 29deg ) skew( -35deg );
            -ms-transform: rotate( 29deg ) skew( -35deg );
            -o-transform: rotate( 29deg ) skew( -35deg );
            -webkit-transform: rotate( 29deg ) skew( -35deg );
            width: 20px;
        }
     
        .me
        {
            float: left;
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
        }
     
        .me::before
        {
            background: #e14f1c url(images/ui-bg_gloss-wave_45_e14f1c_500x100.png) 50% top repeat-x;
            left: -10px;
            top: 2px;
        }
    </style>

 <script src="https://code.jquery.com/jquery-git1.min.js"></script>
<script type="text/javascript">
var th = ['', 'thousand', 'million', 'billion', 'trillion'];
// uncomment this line for English Number System
// var th = ['','thousand','million', 'milliard','billion'];

var dg = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; var tn = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']; var tw = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; function toWords(s) { s = s.toString(); s = s.replace(/[\, ]/g, ''); if (s != parseFloat(s)) return 'not a number'; var x = s.indexOf('.'); if (x == -1) x = s.length; if (x > 15) return 'too big'; var n = s.split(''); var str = ''; var sk = 0; for (var i = 0; i < x; i++) { if ((x - i) % 3 == 2) { if (n[i] == '1') { str += tn[Number(n[i + 1])] + ' '; i++; sk = 1; } else if (n[i] != 0) { str += tw[n[i] - 2] + ' '; sk = 1; } } else if (n[i] != 0) { str += dg[n[i]] + ' '; if ((x - i) % 3 == 0) str += 'hundred '; sk = 1; } if ((x - i) % 3 == 1) { if (sk) str += th[(x - i - 1) / 3] + ' '; sk = 0; } } if (x != s.length) { var y = s.length; str += 'point '; for (var i = x + 1; i < y; i++) str += dg[n[i]] + ' '; } return str.replace(/\s+/g, ' '); }

</script>

<script type="text/javascript">
$(document).ready(function(evt) {




                $('.WordToNum').on('keyup', function (evst) {
                 
                 //if ($(this).val().length == 0) return;
 var words = toWords($(this).val());
                    //if (words.length == 0) return;
                    //alert($(this).attr("id"));
                    JqueryAlertJS(words, $(this).attr("id"));
                 
                });


                 $('#ff').click(function(eeee) {
alert('xx');
                   // $('#ff').remove();
                });

         
$( ".WordToNum" )
  .focusout(function() {
      $('#ff').remove();
  })
   .focus(function() {

var words = toWords($(this).val());

     JqueryAlertJS(words , $(this).attr("id"));
  })

});

        function JqueryAlertJS(message, id) {
            $('#ff').remove();

            var position = $('#' + id).position();
            var top = position.top;
            var l = position.left + $('#' + id).width() + 20;
            // alert(l);
div = $("<div id='ff' class='ui-corner-all bubble me towords'   style='color:white;z-index:500500;                                    background-color:#e14f1c;position:absolute;top:" + position.top + "px;left:" + l + "px;'>").html(message);
            //$("#numm").prepend(div);
 $( "#numm" ).append(div );

            return false;

        }

</script>

<br />
<div id="numm"></div>
<input class="WordToNum" id="MainContent_TextBox1" name="ctl00MainContentTextBox1" type="text" />