Announcement

Thursday, 4 December 2014

Json Size Limit

json size limit techiners
This post will highlight a very common error that comes often when we visit a webpage/website that uses AJAX. We know that in AJAX we have anonymous functions like: success, error etc. success gets called when our ajax request gets successfully completed and it returns a response whereas error gets called when ajax encounters a problem in processing a request.

Thursday, 6 November 2014

How to create a pop up window

Create a pop up window

create a pop up window using jquery in mvc4 techiners.in
Sometimes in our application we need to take input dynamically from the user such as when a user tries to submit a form which contains a drop down for selecting a Country that is mandatory, but the Country is not present in the drop down list which the user wants to select. If this is the case, than probably user will select any country in order to get rid of the error message of selecting mandatory country. There must be a way to dynamically add new country. So, In this post we will learn how to create a pop up window using jquery that will allow the user to add new country simultaneously loading it into drop down and make available for selection.

So, let us begin our step-by-step procedure to add a pop-up so that the user need

Friday, 17 October 2014

Create xml file using XmlSerializer

System.Xml.Serialization_techiners
In my previous post Create xml file in C# .net we have seen the method of creating xml file using C# with XDocument class which is in System.Xml.Linq namespace. There are many ways of creating XML file in C#. One of the method is using XmlSerializer which is in System.Xml.Serialization namespace. Serialization is the process of converting object types to basic types and Deserialization is vice-versa. XmlSerialization allows us to create xml file from

Monday, 29 September 2014

How to find nth highest salary

nth highest salary
How to find nth highest salary?


At the time of interview a very common question that is asked to almost all the candidates is to find the 2nd highest salary. And very often too candidates are unable to answer it. To find highest salary is not a big deal. But to find second highest salary... need to think a bit. But again, not a difficult task.

Wednesday, 24 September 2014

Create pdf file with logo along with table formatting

Pdf with Logo techiners
In the previous post Create Pdf file using C#, we have seen how to create a pdf file using C# and to display the data in the table format. This is like exporting HTML table to pdf format. Creating report in pdf format is not the motto but what if the report comes along with the company logo and the data is properly formatted. YES! That will look like a perfect report and official too. So, here is how we export company logo along with the properly formatted data in pdf format.

Steps For inserting the logo:

Wednesday, 17 September 2014

Create Pdf File using C#

Create Pdf File using C#

C# to Pdf

As mentioned in the post Create XML file in C# .net that often we require to create text file, csv file or excel file for reporting purpose, an important format over internet can't be omitted i.e., pdf format.

pdf is Portable Document Format, a file format to present document independent of application software, hardware and operating system. It is widely used format because of it security and flexibility. Hence, we need to know how to create pdf file in C#? Or how to export HTML table to pdf format? So first we need a dll file

Tuesday, 2 September 2014

Transforming XML to HTML using LINQ to XML


Converting XML to HTML using C#
XML to HTML
In the post Create xml file in C# .net, we got to know about how to create XML file in C#. As mentioned in the previous post, XML helps creating our own tags and it focuses on what data is rather than how data looks. But... many a times it is important how data looks, to get the better look and feel. Thus need arises to convert the XML data into HTML format.

In this post we will convert XML file that we created previously into HTML format.

Thursday, 21 August 2014

Create xml file in C# .net

Creating XML file in C# .net

xml file
Students.xml


Often we require to create text file or csv file, excel file, some other kind of file for reporting purpose. As a Developer, we often require to create an xml file for easily manipulating or rendering the data on the view. XML stands for EXtensible Markup Language.

It allows us to create our own tags. Unlike HTML, it focuses on what data is rather than how data looks. XML simplifies data transportation and data sharing since data is stored in plain text format and thus provides a hardware and software independent way of storing data.

It uses System.Xml.Linq; namespace.

The XML file that we create will have the following structure:

Wednesday, 20 August 2014

SQL Query Performance Issue

SQL Query Performance Issue
SQL Query Performance
SQL Query Performance

As a developer we need to take care a lot of performance of the system that we develop. Recently in one of my project I got a task to check the performance of the query. I tried with three different ways using joins each returning the same result. BUT...

Thursday, 14 August 2014

Create a method that execute a SP irrespective of number of parameters.

Execute Stored Procedure
We as a developer always use Stored Procedure for retrieving results from database. We write code to execute stored procedure and pass all the required parameters using Command Object. But writing all code including connection string, command object, AddWithValue() parameters and executing it every time when you have to execute a stored procedure with different parameters is a tedious task. As a developer, we must be lazy while writing our code which give rise to re-usability. This post will explain how to execute Stored Procedure irrespective of the number parameters where in we just have to pass command object and an empty DataSet object to retrieve the result.

Wednesday, 13 August 2014

How to change the name of project in visual studio?

This post will explain simple steps for changing the name of Project in Visual Studio including all the directories of layered architecture.

Step 1: Right click on the solution file->Open With Notepad.

Step 2: CTRL+H and type ExistingProjectName in Find What and NewProjectName in Replace With textboxes.

Step 3: Click on Replace All

Step 4: CTRL+S to save and close it.

Step 5: Now open the project as usual with Visual Studio.

NOTE : You don't need to edit or change the references. Just run the project.

Monday, 30 June 2014

Encrypting and Decrypting connection string in .NET 4.0

Sometimes we need to store a lot of confidential data in web.config in our production environment (for examples: username/password for impersonation or for connect to database, some appSettings, etc.). And in fact there is a very important information in web.config file and it is our connection string that contains our server name, database name, user id and password. And it is not secure to store that as clear text, obviously some people on your server may have access to this file and steal your data. So we must store them in encrypted form. So how to encrypt the data in web.config file? And how to decrypt the same?

Monday, 9 June 2014

Check all check box on the click of a single check box.

Following is the code to select all the check boxes on the click of a single check box.


$("input[name='checkboxes']").click(function () {
if ($("input[name='checkboxes']").length == $("input[name='checkboxes']:checked").length) {
$("#checkAll").attr("checked", "checked");
}
else {
$("#checkAll").removeAttr("checked");
}
});

$("#checkAll").click(function () {
$("input[name='checkboxes']").attr("checked", this.checked);
});


checkboxes is the name given to all the check boxes that need to be checked on the click of a single check box.

checkAll is the ID of the single check box on the click of which all check boxes will get checked/unchecked.

Friday, 23 May 2014

Server side ajax paging using jquery MVC4

Server Side AJAX paging using jquery in MVC4


Every developer has to code for a view that displays all the records. But what if the database consists of thousands of records? In that case displaying all the records on the view is not good. Rather some sort of paging must be provided that will give the user the ability to navigate among the records and even provide the developer to have fast web page. So, we need to fetch the records on demand and display them on the view. This will be much fast if records are fetched using AJAX. Pagenation can be done in different ways. One way is to use Html Helpers. i.e., @Html.PagedList. The other way is using AJAX. So, how AJAX is used for fast paging?

Thursday, 15 May 2014

Store Password in Encrypted form

Store Password in Encrypted Form

Now a days security is a big issue for any organisation or an individual. Whether you do surfing on internet or use your ATM. Everywhere we can find in some or the other way to secure our data or transaction or just to be on the safe side.

Software Engineers or Developers try hard to provide security for the applications they built. One common way to provide security is to provide Login credentials for their applications. To improve it further, 3-attempts login feature is provided. After 3 unsuccessful attempt, the applications gets blocked.

There are lot of other ways to provide security.

Now, what is more important is to secure your data. i.e., What if somebody peeps into your database? The person will get to know users credentials of your system or application.

One way to prevent this is to store password in encrypted form.

So let us learn how to store password in encrypted form using a reliable MD5 algorithm.

Wednesday, 30 April 2014

How to trigger button click in MVC4?

How to trigger button click in MVC4?

This post will let you know to handle the click event of button when Enter Key is hit by the user.

A function keypressHandler() is created in which we need to check whether the key hit by the user is Enter Key or not. If it is, then get the focus on the login button and trigger the click event.

This keypressHandler() function should be called from the form whenever any key is pressed.

In the example code below, we have assumed the id of the form as 'loginForm'. You can replace it with your own form Id.


function keypressHandler(e){
if (e.which == 13) {
$(this).blur();
$('#Loginbutton').focus().click(); //give your submit button an ID
}
}

$('#loginForm').keypress(keypressHandler); //give your form an ID

How to prevent the functionality of browser back button?

Prevent the functionality of browser back button

In this post I will teach you how to prevent the functionality of browser back button.

Since, we have to prevent the back functionality of the browser, this can't be handled from the code-behind. This is the client functionality. So we need to so something at the client side.

So, we simply have to use javascript history object which is a part of the window object.

history object has 3 methods and 1 property.

history object methods:
  • forward()- loads the next URL in the history list. It won't work if the next page does not exist in the history list.
  • back()- loads the previous URL in the history list. It won't work if the previous page does not exist in the history list.
  • go()- loads the specific URL from the history list. It accepts either int parameter or string parameter.
history object property:
  • length- returns the number of URL in the history list.
I have created a javascript function where I have redirected the user to the current page using window.history.forward() method.


/*This is the function*/
function disableBackButton() {
window.history.forward()
}
/* call the function */
disableBackButton();

/* when the page loads again call the function */
window.onload=disableBackButton();

/* if the page is persisted than disable the back functionality */
window.onpageshow = function (evt) {
if (evt.persisted) disableBackButton()
}

/* do nothing on unload */
window.onunload = function () { void (0) }


NOTE: Place this code in the <script type=text/javascript></script> tag. The code should be placed on the page where the user see Log Out button.

Monday, 21 April 2014

Writing an Image in Excel File


Writing an Image in Excel File

This post will explain you how to write an image in excel file. You first need to define the path of the image in web.config file. Just write the code in web.config file as
<add key="LogoPath" value="E:\\MyProject.Web\\Content\\Images\\ProjectLogo.jpg"/>

Now draw this logo into your excel file using System.Drawing.Image class. An abstract base class that provides functionality for the Bitmap and Metafile descended classes. We will use FromFile() method that is used to create image from the specified file. The file path is passed as an argument to FromFile() method. We can use its overloaded form where we need to specify another argument as boolean i.e., true or false. This specifies whether to use embedded color management information in that file.

Once this Image is created, now create final imagepath that will be rendered in the excel. Here we need to create an image tag(<IMG="" SRC="" WIDTH="" HEIGHT="" />). In this we need to specify the image's width and height by using the above created Image.

Now our iamgepath is ready for finally rendering it into excel file. The code is as follows:

NOTE: This code has a limitation. You need to specify the path every time whenever the image location is changed. The better solution is to use a mapping between ServerPath and LocalPhysicalPath.

HttpContext.Response.Write("<TR style='font-size:12.0pt; text-align:center; font-style:italic; text-decoration:underline; font-weight:bold; font-family:Book Antiqua;'>");
string filePath = System.Configuration.ConfigurationManager.AppSettings["LogoPath"];
System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(filePath);
string imagepath = string.Format("<img src='{0}' width='{1}' height='{2}'/>", filePath, imgPhoto.Width, imgPhoto.Height);
imgPhoto.Dispose();
HttpContext.Response.Write("<Td>");
HttpContext.Response.Write(imagepath);
HttpContext.Response.Write("</Td>");
HttpContext.Response.Write("</TR>");

Tuesday, 8 April 2014

Pagenation in MVC4

Pagenation in MVC4
This post will explain pagenation in MVC4.
You need to install NuGet Package manager named PagedList. You can get the same by clicking NuGet PagedList.
Once this is installed in your project, add a reference to PagedList and PagedList.Mvc dlls. In your view, include the following code at the top as:
@using PagedList;
@using PagedList.Mvc;

The model which your view will be returning should be IPagedList<> rather than IEnumerable<>. Now you are ready to use the Html Helper for the PagedList. i.e., @Html.PagedListPager() where you can also specify various display options for the pagenation.
The view will look like this:

@using PagedList;
@using PagedList.Mvc;
@model IPagedList&ltDistribution.Entities.District&gt
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<h2>Display</h2>
@Html.ActionLink("Create New", "Create")

The various display options for the PagedList can be found in PagedList.Mvc namespace inside the class PagedListRenderOptions.
You can make any changes as per the requirement.


public PagedListRenderOptions()
{
 DisplayLinkToFirstPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToLastPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToPreviousPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToNextPage = PagedListDisplayMode.IfNeeded;
 DisplayLinkToIndividualPages = true;
 DisplayPageCountAndCurrentLocation = false;
 MaximumPageNumbersToDisplay = 10;
 DisplayEllipsesWhenNotShowingAllPageNumbers = true;
 EllipsesFormat = "…";
 LinkToFirstPageFormat = "««";
 LinkToPreviousPageFormat = "«";
 LinkToIndividualPageFormat = "{0}";
 LinkToNextPageFormat = "»";
 LinkToLastPageFormat = "»»";
 PageCountAndCurrentLocationFormat = "Page {0} of {1}.";
 ItemSliceAndTotalFormat = "Showing items {0} through {1} of {2}.";
 FunctionToDisplayEachPageNumber = null;
 ClassToApplyToFirstListItemInPager = null;
 ClassToApplyToLastListItemInPager = null;
 ContainerDivClasses = new [] { "pagination-container" };
 UlElementClasses = new[] { "pagination" };
 LiElementClasses = Enumerable.Empty();
}

The Complete View is as:
View


@using PagedList;
@using PagedList.Mvc;
@model IPagedList<distribution .entities.district="">
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="../../Content/PagedList.css" rel="stylesheet" type="text/css" />
<h2>Display</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.First().State.StateName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().DistrictName)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.State.StateName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DistrictName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.DistrictId }) |
            @Html.ActionLink("Details", "Details", new { id=item.DistrictId }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.DistrictId })
        </td>
    </tr>
}
</table>
@Html.PagedListPager(Model,page=>Url.Action("Index",new {page}), new PagedListRenderOptions {Display=PagedListDisplayMode.IfNeeded, DisplayPageCountAndCurrentLocation=true})


Now that your view is ready, you will have to write code for your controller for the pagenation. This is as under:

Controller

public ActionResult Index(int? page)
{
return View(db.Districts.ToList().ToPagedList(page ?? 1,4));
}

Monday, 7 April 2014

Validations in MVC 4


There are two ways to add custom validations in MVC 4:
  1. Using Data Annotations with Model Binder.
  2. Using Data Annotations in Entity Framework.
Let us see:
  1. Using Data Annotations with Model Binder
Inorder to use DataAnnotation with Model Binder, you need to add references to the following dlls:


Thursday, 3 April 2014

How to find if radio button is checked or not?

This post will explain how to get the checked item from radio button. It will determine if radio button is checked or not.

This is done using jquery as follows:

$('#RadioButtonId').is(':checked')

Wednesday, 2 April 2014

How to include favicon in your website in MVC?

Inorder to include favorite icon in your website you just have to provide a reference in the link tag to the favorite icon (provided you have a favorite icon).

It is also known as Shortcut icon, Tab icon, Website icon or Bookmark icon.

<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />

If you do not have a favorite icon than you can create your own favorite icon by importing the image. Just visit favicon generator.

Tuesday, 1 April 2014

Deleting records using ajax and updating the content after deletion

This post will explain how to delete records from table and updating the content after deletion using ajax.

We will delete records based on the user's choice i.e., user will be given the option to select or deselect the record or records using check boxes.

We will take an example of deleting graphics from the clips that are already allocated to the clips in GraphicsClipsMap table.

For each graphics, check box will be displayed adjacent to it. One delete button is provided for deleting those selected graphics.

1. Write a function that will be called when the delete button is clicked.

2. Within this function write the code to check whether the checkbox is checked or not when the delete button is clicked. If there is no single check box checked and the user clicked the delete button, then display an error in alert to select atleast one checkbox for deletion.

  function DeleteGraphicsFromClip(playoutcode) {
            var checkedIds = [];
            var flag = 1;
            $('input[class=' + playoutcode + ']:checked').each(function () {
                if ($('input[class=' + playoutcode + ']:checked').length <= 0) {
                    alert($(this).attr("id"));
                    flag = 1;
                }
                else {
                    checkedIds.push($(this).attr("id"));
                    alert($(this).attr("id"));
                    flag = 0;
                }
            });

3. Now, pass the selected checkbox ids- the ids are the primary key associated with the graphics to be deleted, to the controller using ajax. These ids are stored in the array using javascript.

4. Flag is set to zero. Now we will pass the checked ids to the controller.

 if (flag == 0) {
                if (confirm('Do you really want to delete the checked graphics?')) {
                    alert('checked: ' + checkedIds);
                    /* pass this array of GraphicClipMap ids to controller's Delete Action Method
                    for deleting the mapped graphics from the clip */
                    $.ajax({
                        url: '@Url.Action("DeleteGraphicsFromClips", "GraphicsClipMap")',
                        data: JSON.stringify({ graphicsClipMapIds: checkedIds }),
                        dataType: 'json',
                        type: 'POST',
                        contentType: "application/json",
                        async: true,
                        success: function (result) {
                            if (result == "3") {
                                alert('You are not allowed to delete graphics form this clip. It is about to scheduled within 2 weeks time.');
                                return false;
                            }
                            if (result == "2") {
                                alert("Graphics already deleted.");
                                return false;
                            }
                            else if (result == "1") {
                                alert('Problem deleting graphics from clip.');
                                return false;
                            }
                            else {
                                /* successfully deleted: now get all graphics after deletion from the clips */
                                $.ajax({
                                    url: '@Url.Action("GetAllClips", "GraphicsClipMap")',
                                    data: JSON.stringify({ ScheduledProgrammeCode: $('#ddlProgramme :selected').val() }),
                                    dataType: 'json',
                                    type: 'POST',
                                    contentType: "application/json",
                                    async: true,
                                    success: function (clips) {
                                        showClipGraphics(clips);
                                        $('.label').show();
                                        $('#clipGrid').show();
                                    },
                                    Error: function () {
                                        alert("Unable to retrive clips due to unsuccessful ajax call.");
                                    }
                                })
                                alert('Graphics successfully deleted from this clip.');
                            }
                        },
                        Error: function () {
                            alert("Unable to delete graphics from clips due ajax call unsuccessfull.");
                        }
                    });
                }
                flag = 1;
            }
            else {
                alert('Please select graphics to delete from this clip.');
                flag = 1;
            }
    }     //finally delete function is closed here.


5. Now its time to delete Graphics from the Clips that are selected in the view using checkboxes.

   public JsonResult DeleteGraphicsFromClips(string[] graphicsClipMapIds)
        {
            string query = string.Empty;
            foreach (var graphicsClipMapId in graphicsClipMapIds)
            {
                int gmId = Convert.ToInt32(graphicsClipMapId);
                /* check if graphics Id exists or not in the graphics clip map, if
                 *  not then it is already deleted. If present, enter its history in 
                 *  the history table then delete it. */
                int deletegmIdexists = Convert.ToInt32(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == gmId).Select(b => b.GraphicsId).SingleOrDefault());
                if (deletegmIdexists > 0)
                {
                    //string playoutCode = context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == gmId).Select(b => b.playoutcode).FirstOrDefault();
                    query = bizGraphicsClipMap.DeleteGraphicsFromClips(gmId);
                    //query = query.Replace("0",playoutCode);
                    //GetScheduledGraphics(playoutCode);
                }
                else
                {
                    //Already deleted.
                    query = "2";
                }
            }
            return Json(query, JsonRequestBehavior.AllowGet);
        }

6.  Now, get all the scheduled graphics for the selected clip i.e., playout.

  public JsonResult GetScheduledGraphics(string pc)
        {
            dynamic graphics;
            /* check for graphics whether it exists for any of the playout, if 
             * it exists, then display all graphics for that clip.*/
            List<GraphicsMaster> scheduledGraphics = new List<GraphicsMaster>();
            List<int> graphicClipMapId = new List<int>();
            List<int> graphicsCode = new List<int>();
            List<GraphicsClipMap> graphicsId = new List<GraphicsClipMap>();
            List<string> graphicsOffset = new List<string>();
            List<string> graphicsDuration = new List<string>();

            List<int> clipMapId = new List<int>();
            graphicsId = context.GraphicsClipMaps.Where(y => y.playoutcode.Equals(pc)).ToList();
            if (graphicsId.Count > 0)
            {
                foreach (var gId in graphicsId)
                {
                    int id = Convert.ToInt32(gId.GraphicsId);
                    graphicsCode.Add(id);
                    clipMapId.Add(gId.GraphicsClipMapId);
                }
                for (int i = 0; i < clipMapId.Count; i++)
                {
                    int id = Convert.ToInt32(clipMapId[i]);
                    int gcode = Convert.ToInt32(graphicsCode[i]);
                    graphicClipMapId.Add(Convert.ToInt32(context.GraphicsClipMaps.Where(p => p.GraphicsId == id).Select(b => b.GraphicsClipMapId).FirstOrDefault()));
                    scheduledGraphics.Add(context.GraphicsMasters.Where(c => c.GraphicsId == gcode).FirstOrDefault());
                    graphicsOffset.Add(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == id).Select(b => b.GraphicsOffset).FirstOrDefault().ToString());
                    graphicsDuration.Add(context.GraphicsClipMaps.Where(a => a.GraphicsClipMapId == id).Select(b => b.GraphicsDuration).FirstOrDefault().ToString());
                }
            }
            graphics = (new { PlayoutId = pc, GraphicsName = scheduledGraphics.Select(a => a.GraphicsName), GraphicStartTime = graphicsOffset, GraphicEndTime = graphicsDuration, GraphicsMapId = clipMapId });
            return Json(graphics, JsonRequestBehavior.AllowGet);
        }

7. Now, Update the Clip Details in the div to show graphics after deleting selected graphics. This is achieved using another ajax call within the delete ajax call i.e., showClipGraphics(clips);. Where in we pass the updated clips object after deleting the graphics from the clip.

This is achieved as under...

 function showClipGraphics(clips) {
        $('#clipDetails').empty();
        $('#clipDetails').append('<tr style="background-color:#20ff00"><th>Select</th><th>'
                    + 'Start Time</th><th>End Time</th><th>Duration</th><th>Title</th><th>File Server '
                    + 'Programme Id</th></tr>');
        for (var i = 0; i < clips.PlayoutId.length; i++) {
            if (clips.Prefix[i] == "FF" || clips.Prefix[i] == "MB" || clips.Prefix[i] == "SO") {
                $('#clipDetails').append('<tr style="background-color:#01ACFE"><td><input type="radio" class="rdoClip" name="rdoClipDetail" id="'
                 + clips.PlayoutId[i] + '" value="' + clips.PlayoutId[i] + '" onclick="selectedClip(this)" /></td><td>'
                 + clips.ClipStartTime[i].toString() + '</td><td>' + clips.ClipEndTime[i].toString() + '</td><td>'
                 + clips.ClipDuration[i].toString() + '</td><td>' + clips.ClipName[i].toString()
                 + '</td><td>' + clips.FileServerProgrammeId[i].toString() + '</td><td>'
                 + clips.Prefix[i].toString() + '</td></tr>');
                /* ajax call for getting all scheduled graphics within a clip */
                var playoutcode = clips.PlayoutId[i];
                if (playoutcode != null) {
                    var options = {};
                    options.url = '@Url.Action("GetScheduledGraphics", "GraphicsClipMap")';
                    options.data = JSON.stringify({ pc: playoutcode });
                    options.type = "POST";
                    options.dataType = "json";
                    options.contentType = "application/json";
                    options.async = false;
                    options.success = function (graphics) {
                        if (graphics.GraphicsName.length > 0) {
                            $('#clipDetails').append('<tr style="background-color:#F9FF00"><th colspan="3">Graphic for this clip</th><th>Graphics Name</th><th>Graphics Offset</th><th>Graphics Duration</th><th><input type="button" class="delButton" value="Delete" id="' + playoutcode + '" onclick=DeleteGraphicsFromClip('+playoutcode+')></th>');
                            for (var i = 0; i < graphics.GraphicsName.length; i++) {
                                $('#clipDetails').append('<tr style="background-color:#00FF9F"><td colspan="3">&nbsp</td><td>' + graphics.GraphicsName[i] + '</td><td>' + graphics.GraphicStartTime[i] + '</td><td>' + graphics.GraphicEndTime[i] + '</td><td><input type="checkbox" name="chkDelete" class="' + playoutcode + '" value="' + graphics.GraphicsMapId[i] + '" id=' + graphics.GraphicsMapId[i] + ' /></td></tr>');
                            }
                        }
                    };
                    options.error = function () { alert("Error retrieving scheduled graphics due to problem in ajax call!"); };
                    $.ajax(options);
                }
            }
            else {
                $('#clipDetails').append('<tr><td></td><td>' + clips.ClipStartTime[i].toString() + '</td><td>' + clips.ClipEndTime[i].toString() + '</td><td>' + clips.ClipDuration[i].toString() + '</td><td>' + clips.ClipName[i].toString() + '</td><td>' + clips.FileServerProgrammeId[i].toString() + '</td><td>' + clips.Prefix[i].toString() + '</td></tr>');
            }
        }
    }

In the above function, we retrieve all the clips and the graphics under that clip, if any, using ajax. Then we update the clipDetails div with the newly retrieved clip details.

Thursday, 27 March 2014

How to create a connection string from Web.config file using stored procedure?

ConnectionStringInWeb.ConfigFile techiners.in
This post will illustrate how to create a database connection in C# using web.config file in MVC along with the reusable function for executing the stored procedure.


1. Create a connection string in web.config file or copy the code given below. Put this code in your <configuration> </configuration> part.


Wednesday, 26 March 2014

How to get checked items using jquery?

This DeleteGraphicsFromClip() function is called on the click event of Delete button whose id is deleteGraphicsFromClip.

The function will iterate over all the check boxes present in the form or in table <td> tag using jquery as $('input[name=chkDelete]:checked').each(function (){...}.

If the check box is checked, then get the id of the checked checkbox and set the flag to 0.

If there are no checked checkboxes, then set the flag to 1 for displaying error.

ids is declared as an array, and hence we use push method to insert the id of the checked checkbox.

Finaly, if the flag is 0, then do the required operation as passing the all checked ids to the controller for deleting the records. If the flag is 1, then display alert to the user to select atleast one checkbox for deleting.

 function DeleteGraphicsFromClip() {
        var ids = [];
        var flag=1;
        $('input[name=chkDelete]:checked').each(function () {
            if ($('input[name=chkDelete]:checked').length <= 0) {
                flag = 1;
            }
            else {
                ids.push($(this).attr("id"));
                flag = 0;
            }
        });
        if (flag==0) {
            alert('checked: ' + ids);
            flag = 1;
        }
        else {
            alert('Please select graphics to delete');
            flag = 1;
        }
    }

Friday, 21 March 2014

How to prevent the default action of submit button?

This is my submit button with id as "btnSubmitModification" .

We need to prevent the default action of this submit button i.e., to prevent the
form from submission on click of this button.

<input type="submit" class="button" id="btnSubmitModification" value="Save"/>

Here is the code in script tag.
This is achieved using jquery.

We handle the click event of submit button and pass the parameter to the
event handler function as e.

This is parameter is than used to prevent the default action of submit button i.e., to
prevent the form from submission.

Just write e.preventDefault(); and you are done.

<script type="text/javascript">
    $('#btnSubmitModification').click(function (e) {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            e.preventDefault();
        }
    });
</script>

Alternative way to do the same thing is as: Just write return false and don't pass any
argument to the function.

<script type="text/javascript">
    $('#btnSubmitModification').click(function () {
        if ($("#txtName").val() != "" && $("#txtName").val() != null) {
            // write your further code here.
            return true;
        }
        else {
            alert('Please enter name.');
            return false;
        }
    });
</script>



Tuesday, 18 March 2014

Add items from one drop down to another drop down using jquery

1. Define a function that will move items from one drop down to another drop down.

2. This function will be called on the click of buttons i.e., Button for removing item and Button for       adding item.

3. The function accepts two parameters i.e., fromDropdown and toDropdown. It will move items           from fromDropdown to toDropdown.

4. The .off() method removes event handlers that were attached with .on(). See the discussion of         delegated and directly bound events on that page for more information. Calling .off() with no           arguments removes all handlers attached to the elements. Specific event handlers can be                 removed on elements by providing combinations of event names, namespaces, selectors, or             handlers function names.
 
    It basically removes an event handlers. For more information Click here.

Function for adding and removing items from one drop down to another drop down.

   function cutAndPaste(from, to) {
        $(to).append(function () {
            return $(from + " option:selected").each(function () {
                this.outerHTML;
            }).remove();
        });
   }

On click of Add button.

    $("#btnAdd").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#fromDropDown").val();
        e.preventDefault();
        $("#toDropDown option").each(function () {
            if ($(this).val() == txt) {
                itemExists = true;
                alert('Items already exists.');
                return false;
            }
        });
        if ($('#fromDropDown').val() == null) {
            alert('Item list is empty.')
        }
        if (!itemExists) {
            cutAndPaste("#fromDropDown", "#toDropDown");
        }
    });

On click of Remove button.

    $("#btnRemove").off("click").on("click", function (e) {
        var itemExists = false;
        var txt = $("#toDropDown").val();
        e.preventDefault();
        if ($("#toDropDown :selected").val() > 0) {
            cutAndPaste("#toDropDown", "#fromDropDown");
        }
        else {
            alert('Item does not exists');
            return false;
        }
    });

Friday, 14 March 2014

Get the total number of items of drop down using jquery


DropDownId is the id of the DropDown whose items you would like to count.

var items = $('#DropDownId>option').length;

Monday, 10 March 2014

Shutdown PC with Timer

How to shutdown a PC with Timer?

Follow these simple steps:

In windows XP

1. Goto Run>Command Prompt
2. Type the following code: shutdown -s -t xxxx
3. Press Enter. Your PC is scheduled to shutdown after xxxx seconds.

In Windows 7

Click Windows icon, type shutdown -s -t xxxx in the search box at the bottom.

Please Note: xxxx is the time in seconds.

To abort the automatic shutdown use the following code:

shutdown -a

Thursday, 6 March 2014

Populate drop down via AJAX using MVC4 C# when page loads.

1. Create a view that contains one drop down list for displaying items into it.

2. In Controller write a method that return JsonResult. And don't forget to mention it as [HttpPost]     since we will be using AJAX POST method, Ajax data type as Json hence the return type of             method is JsonResult.

3. We will create a function loadChannels() that will be called when the document is ready. This is        achieved using Jquery as :- 
      $(document).ready(function(){
               //Function call goes here.
      });

4. The method that we have written in controller (NOTE STEP 2) which will return JsonResult will     get called via AJAX from the method loadChannels() (NOTE STEP 3).



View as FpcDetails.cshtml

@{
    ViewBag.Title = "FpcDetails";
    Layout = "~/Views/Shared/_LayoutPrivate.cshtml";
}
@using (Html.BeginForm("FpcDetails", "Fpc", FormMethod.Post, new { enctype = "multipart/form-data", id = "form" }))
{
        <table>
            <tr>
                <td>
                    Select Channel:
                </td>
                <td>
                    @Html.DropDownList("channelsList", new List<SelectListItem> { }, string.Empty, new {                                                                   @class = "DropDown", @id = "dropDownChannels" }
                                                        )
                </td>
            </tr>
        </table>

    <input type="hidden" id="hdnChannels" />
}

//Document.ready function calling loadChannels().

<script type="text/javascript">

    $(document).ready(function () {
        loadChannels();
    });

/* Defining loadChannels() function */

    /*Loading channels on page load*/
 
  function loadChannels() {
        var options = {};
/* url for ajax to call a method GetChannels in the controller Fpc that will return JsonResult */

        options.url = '@Url.Action("GetChannels", "Fpc")';

/* Method type of Ajax is POST. Same will be mentioned in controller GetChannels() method as [HttpPost] */
        options.type = "POST";

/* Type of Ajax is json. This will  be the return type of method defined in Controller.i.e., JsonResult. */

        options.dataType = "json";
        options.contentType = "application/json";

/* channels passed as argument in the function as used to get the returned values from the controller back to       the view. This will give us an List of Id and Name. Hence we need to iterate over it in order to display           them. */

        options.success = function (channels) {

/* Empty the drop down list before appending any new values. */

            $("#dropDownChannels").empty();
            $("#dropDownChannels").append("<option value=></option>");
            for (var i = 0; i < channels.length; i++) {
                $("#dropDownChannels").append("<option value=" + channels[i].Id + ">" + channels[i].Name +                                                                           "</option>");
            }
            $("#dropDownChannels").prop("disabled", false);
        };

/* If there is any problem in Ajax, error method will get invoked. */

        options.error = function () { alert("Error retrieving Channels!"); };
        $.ajax(options);
    }

</script>


Controller: 

/* Inside our controller we just add the following code. */

/*Get all Channels via AJAX */
        [HttpPost]
        public JsonResult GetChannels()
        {
            List<AMSChannel> channels;
            channels = context.AMSChannels.ToList();
            var result = (from x in channels select new { Id = x.ChannelId, Name = x.ChannelName });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

Friday, 21 February 2014

How to compare only month part of DateTime field using LINQ

Getting all values of a particular column by comparing Month part of DateTime field in SQL using Linq.

Fetch the month of date time field using the Value property in Linq. Then get the Month of it as: f.ForDate.Value.Month

e.g., the following query will get all start time as an array of String where the Month of ForDate field in Table FPCTimeMaster matches the Month of DateTime field timeMasterDate.

string[] startTimes = context.FPCTimeMasters.Where(f =>f.ForDate.Value.Month == timeMasterDate.Month && f.ChannelId == channelID ).Select(s => s.StartTime).ToArray();

Wednesday, 12 February 2014

Export DataTable to Excel without dll

You can simply export DataTable to Excel file without using dll provided that Microsoft Office is installed.

Here is the code:-

Function ExportToExcel() expects a parameter of type DataTable which contains required information
that is to be converted into excel.


private void ExportToExcel(DataTable table)
        {
            HttpContext.Response.Clear();
            HttpContext.Response.ClearContent();
            HttpContext.Response.ClearHeaders();
            HttpContext.Response.Buffer = true;
            HttpContext.Response.ContentType = "application/ms-excel";
            HttpContext.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            //Set the name of report as per query fired by the user.
            HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=Reports.xls");

            HttpContext.Response.Charset = "utf-8";
            HttpContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            //sets font
            HttpContext.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
            HttpContext.Response.Write("<BR><BR><BR>");
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            HttpContext.Response.Write("<Table border='1' bgColor='#ffffff' " +
              "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
              "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
            //am getting my grid's column headers
            //int columnscount = GridView_Result.Columns.Count;
            int columnscount = table.Columns.Count;
            for (int j = 0; j < columnscount; j++)
            {   //write in new column
                HttpContext.Response.Write("<Td>");
                //Get column headers  and make it as bold in excel columns
                HttpContext.Response.Write("<B>");
                //HttpContext.Response.Write(GridView_Result.Columns[j].HeaderText.ToString());
                HttpContext.Response.Write(table.Columns[j].ToString());
                HttpContext.Response.Write("</B>");
                HttpContext.Response.Write("</Td>");
            }
            HttpContext.Response.Write("</TR>");
            foreach (DataRow row in table.Rows)
            {   //write in new row
                HttpContext.Response.Write("<TR>");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    HttpContext.Response.Write("<Td>");
                    HttpContext.Response.Write(row[i].ToString());
                    HttpContext.Response.Write("</Td>");
                }
                HttpContext.Response.Write("</TR>");
            }
            HttpContext.Response.Write("</Table>");
            HttpContext.Response.Write("</font>");
            HttpContext.Response.Flush();
            HttpContext.Response.End();
        }

Sunday, 2 February 2014

Export table data to excel using jquery

Export table data to excel using jquery

Export DataTable to Excel ©techiners
Export DataTable to Excel


To export data table to excel using jquery just add following code:




$('#btnExcel').click(function (e) {

window.open('data:application/vnd.ms-excel,'+$('#dvData').html());
e.preventDefault();


Explanation: #btnExcel is the id of the button on the click of which you need to export the data to the excel file. #dvData is the id of the DIV element in which data is present or rendered on the view that needs to be exported to excel file.

Monday, 20 January 2014

How to display Search Box of jquery datatable at the bottom of the table?


To display the search box of jquery datatable at the bottom of the table use "sDom" parameter as follows:


"sDom": '<"top"i>rt<"bottom"flp><"clear">'

where "top", "bottom" and "clear" are the classes of the div where the text box will render in.


Friday, 17 January 2014

Adding country into the selected continent from drop down via ajax. ajax.success method was not being called.


While working on a project, we were given a task to show the countries of selected continent from drop down box and bind it to another drop down box as well as display it in a view. But, I got stuck at a point where my AJAX success method was not called. The code in the controller was perfect. The problem is because project is running on the IIS server.



So how to resolve it? Solution is right click