Create Linked List

#include <stdio.h>
#include <stdlib.h>

struct node {
 int data;
 struct node* next;
};

void addNode(struct node** head_ref, int input)
{
 //1 create temp node
 struct node* temp = (struct node*)malloc(sizeof(struct node));
 
 //2 assign data to temp node
 temp->data = input;
 
 //3 temp node address should point to head_ref
 temp->next = (*head_ref);
 
 //4 move the head_ref to temp node
 (*head_ref) = temp;
 
}

void printNode(struct node* head)
{
 if(head == NULL) 
 {
 return;
 }
 
 printf("Data: %d , Next: %p \n", head->data, head->next);
 printNode(head->next);
};

int main()
{
 struct node* head = NULL;
 for(int i = 0; i < 5; i++)
 {
 addNode(&head, i);
 }
 
 printNode(head);
 
 return 0;
};

Create and Read LINKED LIST

#include <stdio.h>
#include <stdlib.h>

struct node
 {
 int data;
 struct node *addr;
 };

void generateData(struct node *head)
 {
 struct node *current = NULL;
 for(int i=0; i<5; i++)
 {
 current = (struct node *)malloc(sizeof(struct node));
 current->data=i;
 current->addr=head;
 head=current;
 }

while(head)
 {
 printf("%d \n", head->data);
 head=head->addr;
 }

}
 int main()
 {
 struct node *head = NULL;
 generateData(head);
 return 0;
 }

 

Image in Kendo Grid Dropdown List

In this article, I would demonstrate how to insert a image in dropdown list (inside kendo grid) based on Type (CrewId) also this will help us to how to define the foreign key column in kendo grid

In this example, the grid will contain 3 columns a) Id b) CrewId [Man/Machine which is foreign key column] 3) Comments

Let’s define below Kendo Grid in Index.cshtml of HomeController. This is a basic kendo grid configuration with 2 columns as Bound columns

and another column as ForeignKey Column which contains CrewID and we have list of CreworEquipment data which is stored in ViewState.


@(Html.Kendo().Grid<UserMachine>()
.Name("MyGrid")
.HtmlAttributes(new { style = "height:100%; width:100%; " })
.Columns(columns =>
{
columns.Bound(m => m.Id).Hidden(true);
columns.ForeignKey(m => m.CrewId, (System.Collections.IEnumerable)ViewData["CrewOrEquipment"], "Id", "Name").Title("User/Equipment").Width(100);
columns.Bound(m => m.Comments).Width(175).Title("Comments");
}
)
.ToolBar(toolbar => toolbar.Template(
<text>
<a class="k-button k-button-icontext k-grid-add anch-show-hide"><span class="k-icon k-add"></span></a>
<a class="k-button k-button-icontext anch-show-hide" id="cancelAct1" href="javascript:void(0)"><span class="k-icon k-cancel"></span></a>
</text>))
.Scrollable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Sortable()
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(row => row.Id);
}
)
.ServerOperation(false)
.PageSize(25)
)
.Resizable(resize => resize.Columns(true))
.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))

The major part of the code is the Grid Foreign Key template which would be defined in Shared folder. Lets add file GridForeignKey.cshtml inside folder View ==> Shared ==> EditorTemplate and add the below code to the file.


@(Html.Kendo().DropDownListFor(m => m).DataValueField("Id").DataTextField("Name")
.BindTo((System.Collections.IEnumerable)ViewData["CrewOrEquipment"])
.TemplateId("contact-template"))

Now lets define below template, and this is pretty straightforward based on Id, we are setting the respective Image along with data to it.

 
<script id="contact-template" type="text/x-kendo-template"> 
# if(data.CrewType == 1) { # 
 <img alt="icon" class="k-image" src="http://icons.iconarchive.com/icons/icons-land/vista-people/16/Office-Customer-Male-Light-icon.png"> #: data.Name # 
# } # 

# if(data.CrewType == 2) { # 
 <img alt="icon" class="k-image" src="http://icons.iconarchive.com/icons/iconshock/real-vista-construction/16/hand-driller-icon.png"> #: data.Name # 
# } # 

</script> 

Finally lets define the Controller action Index with following code. As you can see we are using the ViewData in our ForeignKey column

public ActionResult Index()
{
    ViewData["CrewOrEquipment"] = GetCrewOrEquipment();
    return View();
}

Let’s run the application and once page loads, click the Plus button and now you select Crew Columns and you should be seeing the Images (crew/equipment images) based on type.

Hope this was helpful…

Building MVC 4 App with Bootstrap layout

Prerequisites: VS2013, MVC 4

First let’s create a default MVC4 application using VS.

Go to menu File –> New Project –> Installed –> Templates –> Visual C# –> Web –> Select “ASP.NET MVC 4 Web Application” –> name application as “MVC_Bootstrap”

Now just run the application and see if everything is working. Sounds good….

Now right click the MVC_Bootstrap web project –> Manage Nuget Package –> Online –> in top right search text area enter “bootstrap” and click search. (look for package created by: Twitter, Inc)

The above step, would add bunch of bootstrap css files in Content folder and  bunch of JS files in Scripts folder. Plz verify… Sounds good.

Open the _layout.cshtml file and below tags in HEAD section or you can add proper bundle configuration in App_Start/BundleConfig.cs file


<link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap-theme.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/bootstrap.min.js")"></script>

Things to know about Bootstrap :

css class “container-fluid”:  This is usually applied to main DIV of the body. This div should hold entire HTML for proper layout.

css class “row”: All rows should be applied with this class, this applies width in percentage. If you want to go with PX go with row-fluid.

Entire screen width is divided into 12 equal columns ( 1 to 12)

For our application we will have header and the followed by content

1) First let’s fix _Layout.cshtml page, so open this page and remove all html (HEADER, BODY & FOOTER) content inside the body tag

2) Let’s add 3 div’s as shown below. So here what we are doing is we are creating a container div and adding 3 div’s

a) header,

b) body and

c) footer

3) Each row is embedded with a column of width


<body>
 <div class="container-fluid">
<div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <h6> HEADER </h6>
 </div>

</div>
 <div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 @RenderBody()
 </div>
 </div>
 <div class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <h6> FOOTER </h6>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</div>
 </div>
 @Scripts.Render("~/bundles/jquery")
 @RenderSection("scripts", required: false)
</body>

Now lets add below action in HOME controller

public ActionResult MyForm()
{
            return View();
}

Add MyForm.cshtml in folder Views ==> Home

add below content to MyForm CSHTML. In this we have divided column into sum of 12 .

<div class="container-fluid">
 <div id="MyForm" class="row">
 <div class="col-sm-12 col-md-12 col-lg-12">
 <div class="row">
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Name:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <select id="User" name="User" style="width: 100%">
 <option>Select</option>
 <option>User1</option>
 </select>
 </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Lead Name:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <input id="LeadName" name="LeadName" type="text" value="" style="width: 100%">
 </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Date:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2"><input type="date" style="width: 100%" /> </div>
 <div class="col-sm-1 col-md-1 col-lg-1">
 <div class="labelClass">Country:</div>
 </div>
 <div class="col-sm-2 col-md-2 col-lg-2">
 <select id="Country" name="Country" style="width: 100%">
 <option>Select</option>
 <option>Select 1</option>
 </select>
 </div>
 </div>
 </div>
 </div>
</div>
 

Now when you run this application this all controls would be aligned properly.

Now try to resize the window to as small as you can and you would notice that the controls would auto align themselves one below another. You can also change your screen resolution and verify the same.

Happy Kooding… Hope this was helpful…..!

How to avoid special characters on key press – javascript

Avoid keying of special characters.. hope this doesn’t need any explanation…


&lt;input type="text" onkeypress="avoidSplChars(event)" /&gt;


 
function avoidSplChars(e) {
 e = e || window.event;
 var bad = /[^\sa-z\d]/i,
 key = String.fromCharCode( e.keyCode || e.which );

    if ( e.which !== 0 && e.charCode !== 0 && bad.test(key) ) {
          e.returnValue = false;
          if ( e.preventDefault ) {
              e.preventDefault(); 
          }
    } 
}
 

Happy Kooding… hope this helps!!


			

Oracle: Create a Job Script

Hi,

Below is the syntax for creating a JOB in Oracle


CREATE OR REPLACE PROCEDURE MySchema.Create_A_JOB

AS

BEGIN

DECLARE

X NUMBER;

BEGIN

SYS.<strong><em>DBMS_JOB.SUBMIT</em></strong>

( job       => X

,what      => 'MySchema.Call_The_Procedure(''10'');'

,next_date => to_date('15/04/2015 13:35:00','dd/mm/yyyy hh24:mi:ss')

,interval  => 'SYSDATE + 1'

,no_parse  => FALSE

);

SYS.<strong><em>DBMS_OUTPUT.PUT_LINE</em></strong>('Job Number is: ' || to_char(x));

SYS.<strong><em>DBMS_JOB.BROKEN</em></strong>

(job    => X,

broken => TRUE);

COMMIT;

END;

END;

/

Removing a Row from KENDO GRID

In this article, will demonstrate how to remove multiple grid items when a button is clicked.

Below is basic grid configuration.



@(Html.Kendo().Grid<User>()
           .Name("UserGrid")
            .HtmlAttributes(new { style = "height:100%; width:100%; " })
            .Columns(columns =>
            {
                       columns.Bound(m => m.Id).Hidden(true);
                       columns.Bound(m => m.Name).Width(175).Title("Name");
                       columns.Bound(m => m.Hours).Width(175).Title("Hrs");
                       columns.Bound(m => m.Comments).Width(175).Title("Comments");
            }
            )
            .Scrollable()
            .ToolBar(toolbar => toolbar.Template(@<text>
                       <a class="k-button k-button-icontext k-grid-add" href="#"><span class="k-icon k-add"></span>New</a>
                       <a class="k-button k-button-icontext" id="cancelItem" 
href="javascript:void(0)"><span class="k-icon k-cancel"> </span>Cancel</a>

           </text>))
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Filterable()
            .Sortable()
            .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Model(model =>
                       {
                       model.Id(row => row.Id);
                       }
                       )
            .ServerOperation(false)
            .PageSize(25)
            )
            .Resizable(resize => resize.Columns(true))
            .Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))
            .Reorderable(reorder => reorder.Columns(true))
            .Pageable(p => p.PageSizes(new[] { 25, 50, 100 }))
 )



Below are the key configurations. We defining that our grid is multi selectable. Also we defined Cancel button in Grid toolbar


.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))

<a class="k-button k-button-icontext" id="cancelItem" href="javascript:void(0)"><span class="k-icon k-cancel"></span>Cancel</a>

Now its time to define the Javascript, which will remove the grid item. Find the INLINE comments for the below code.


// adding click event for cancel button

$("#cancelItem").on("click", function (e) { 
           clearSelectedRows("UserGrid"); 
 });

clearSelectedRows = function (gridName) {

           // identifying grid

            var entityGrid = $("#" + gridName + "").data("kendoGrid");

            // finding all the selected rows
            var rows = entityGrid.select();
            rows.each(function (index, row) {

                        // reading each selected item
                         var selectedItem = entityGrid.dataItem(row);

                       // finally removing selected item from grid data source
                         entityGrid.dataSource.remove(selectedItem); 
              });
 }

Happy Kooding… Hope this helps….!

Upload & Read Excel File

This article demonstrate

1) How to upload the file in MVC

2) Read excel file content

How to upload the file in MVC

In your MVC razor view add the below html content

@using(Html.BeginForm("Upload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <table>
        <tr>
            <td>File:</td>
            <td>
                <input type="file" name="UploadedFile" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" name="Submit" value="Submit" />
            </td>
        </tr>
    </table>
}

Notice, the action name : Upload, Controller Name: Home

Now come to home controller and add action called Upload

 public ActionResult Upload(FormCollection formCollection)
        {
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength &gt; 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

		}
	    }
	}

Now try to run the app by putting a breakpoint and see if all is working until now

Now add dll called EPPLUS from NUGET which is used for reading and writing files.

Lets say I have file with FirstName & LastName

Now add a class called users

public class Users
{
      public string FirstName { get; set; }

       public string LastName { get; set; }
}

Now lets modify our action method to read the file stream object which we uploaded. Add using OfficeOpenXml; statement


 public ActionResult Upload(FormCollection formCollection)
        {
            if (Request != null)
            {
                HttpPostedFileBase file = Request.Files["UploadedFile"];

                if ((file != null) && (file.ContentLength &gt; 0) && !string.IsNullOrEmpty(file.FileName))
                {
                    string fileName = file.FileName;
                    string fileContentType = file.ContentType;
                    byte[] fileBytes = new byte[file.ContentLength];
                    var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));

                    var usersList = new List&lt;Users&gt;();

                    using (var package = new ExcelPackage(file.InputStream))
                    {
                        var currentSheet = package.Workbook.Worksheets;
                        var workSheet = currentSheet.First();
                        var noOfCol = workSheet.Dimension.End.Column;
                        var noOfRow = workSheet.Dimension.End.Row;

                        for (int rowIterator = 2; rowIterator &lt;= noOfRow; rowIterator++)
                        {
                            var user = new Users();
                            user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
                            user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
                            usersList.Add(user);
                        }


                    }
                }
            }

            return View("Index");
        }

Finally all the users will be available in usersList object.

Happy Kooding…. Hope this helps!!

Example on Read & Write to Dictionary in JAVASCRIPT

Below sample code demonstrate on how to read/write dictionary in JS world.

Creating & Adding data to Dictionary

var workOrderDictionary = []; // declare dictionary

var companyId1 = 1;
var orders1 = [{ ProductId: 10, ProductName: Pen } , {ProductId: 20, ProductName: Eraser} ]
workOrderDictionary.push({ key: companyId1, value: orders1 });

var companyId2 = 2;
var orders2 = [{ ProductId: 101, ProductName: Lunch-Box } , {ProductId: 20, ProductName: Bottle } ]
workOrderDictionary.push({ key: companyId2, value: orders2 });

Reading the data from Dictionary

for (var key in workOrderDictionary) {
	if (workOrderDictionary.hasOwnProperty(key)) {
	    var orders =	workOrderDictionary[key];
	}
}

Happy Kooding… Hope this helps…!

Tips/Tricks: Javascript or JQuery

1) How to get difference between 2 days in days using Javascript


var noOfDays = (finishDate - startDate) / (1000 * 60 * 60 * 24);

2) Remove Last Comma from a string

var str = commaInLastStr.replace(/,\s*$/, "")

Happy Kooding… Hope this helps!