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.
Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Create xml file using XmlSerializer
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 fromTransforming XML to HTML using LINQ to XML
![]() |
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.
Create xml file in C# .net
Creating XML file in C# .net
![]() |
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:
Create a method that execute a SP irrespective of number of parameters.
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.
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?
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?
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.
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>");
Pagination in MVC4
Pagination in MVC4
This post will explain pagination 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:
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 pagination.
The view will look like this:
The various display options for the PagedList can be found in PagedList.Mvc namespace
This post will explain pagination 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 pagination.
The view will look like this:
@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>
@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.
The Complete View is as:
View
Now that your view is ready, you will have to write code for your controller for the pagination. This is as under:
Controller
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 pagination. This is as under:
Controller
public ActionResult Index(int? page)
{
return View(db.Districts.ToList()
.ToPagedList(page ?? 1,4));
}
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.
If you do not have a favorite icon than you can create your own favorite icon by importing the image. Just visit favicon generator.
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.
How to create a connection string from Web.config file using stored procedure?
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.
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);
}
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);
}
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);
}
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();
}
Subscribe to:
Posts (Atom)