Follow by Email

Tuesday, December 23, 2014

[Resolved] The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files'

hi i was accessing a SharePoint portal when i got this below error

The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files'



lets see how to resolve this :

now run cmd as admin and go to this below path and type aspnet_regiis -i

path : C:\Windows\Microsoft.NET\Framework64\v2.0.50727



Next type aspnet_regiis -ga "NT AUTHORITY\NETWORK SERVICE"









Now you should be able to browse your websites.
Thanks.

Calling a json rest api from angularJS || using AngularJS XMLHttpRequest to call service

hi lets see how to call a http rest api from angularjs

1. create the rest api which returns JSON data

2. Host the Http rest api ( in my case im hosting it on localhost )

3. Now we will see how to call this http api from angularjs

Code:

<!DOCTYPE html>

<html>
<head>

    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

</head>

<body>
    <div ng-app="" ng-controller="EmpData">

        <div ng-repeat="x in Emp">
            <h1> {{ 'Employee ID:' + x.EID  }} </h1>
            <p>{{ 'Name: ' + x.EName}}</p>
            <p>{{ 'Salary: ' + x.ESalary}}</p>
        </div>

    </div>

    <script>

        function EmpData($scope, $http) {
            $http.get("http://localhost/api/Home").
                success(function (data) {
                    $scope.Emp = data;

                });
        }
    </script>

</body>
</html>

4. Output





[Resolved] WEBAPI ERROR using Json: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

hi lets see  how to resolve below error occurred while accessing web api for Json datatype :


 The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.



Solution:

go to global.asax file and in Application_Start() event add this below line.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter); 


After this u shud b able to run the webapi

Output:




Friday, December 5, 2014

Tutorial for Selecting nth last element using jquery || using nth-last-child in jquery

hi let see how to select a nth last element like the <div>, <p>, <h1> etc. using jquery.
Now in below example just to check if we have selected the correct element we will change its color
example for selecting a 2nd last <h1> element which is inside a <div>
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title></title>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
$(“button”).click(function () {
$(“h1:nth-last-child(2)”).css(“background-color”, “yellow”);
});
});
</script>
</head>
<body>
<div>
<h1>im 1st h1</h1>
<h1>im 2nd h1</h1>
<h1>im 3rd h1</h1>
<h1>im 4th h1</h1>
<h1>im 5th h1</h1>
</div>
<button>Change color of 4th element ( as it is 2nd last )</button>
</body>
</html>

output:
1

AngularJS alert message box using $window

hi in this post i will show how to show an alert box in angularJS using $window element

Code :
<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title></title>
<script src=”//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js”></script>
<script type=”text/javascript”>
function homeController($scope, $window)
{
$scope.showalert = function ()
{
$window.alert($scope.name);
}
}
</script>
</head>
<body>
<div ng-app=”” ng-controller=”homeController”>
<input type=”text” ng-model=”name” />
<button type=”submit” ng-click=”showalert()”>Submit</button>
</div>
</body>
</html>
output:
1

Exception Handling in asp.net mvc using global.asax application_error() Method

hi now lets see how to catch exception in asp.net mvc using global.asax application_error() Method.

1. set Custom Error to Off in the web.config file
2. go to global.asax file and add this below code.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null)
{
string action;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = “HttpError404″; // create action method named HttpError404  in controller and also add the appropriate view
break;
case 500:
// server error
action = “HttpError500″; // create action method named HttpError500 in controller and also add the appropriate view
break;
default:
action = “HttpOtherErrors”; // create action method named HttpOtherErrors in controller and also add the appropriate view
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, action, exception.Message)); // ErrorHandle is the controller Name 
}
else
{
Response.Redirect(String.Format(“~/ErrorHandle/{0}/?message={1}”, “HttpOtherErrors”, exception.Message));
}
}
3. in controller catch the exception message and show it in the view
public ActionResult HttpOtherErrors(string message)
{
ViewBag.ExceptionMessg = message;
return View();
}

[Resolved] Asp.net MVC Error : The controller for path ‘/favicon.ico’ was not found or does not implement IController

hi just came across this below error while debugging a asp.net mvc application.
 The controller for path ‘/favicon.ico’ was not found or does not implement IController
1
. 1. To resolve this go to RouteConfig.cs and write
 routes.IgnoreRoute(“{*favicon}”, new { favicon = @”(.*/)?favicon.ico(/.*)?” });
2
2. Now run the application and check.

Angularjs : HTML form validation example

hi let see how to do validate a html form using angularjs
example :
<!DOCTYPE html>
<html>
<head>
<script src=”https://code.angularjs.org/1.2.9/angular.js”></script&gt;
<script>
function EmpForm($scope) {
$scope.empname = ‘Chandan Singh';
$scope.empemail = ‘chandan.may2@gmail.com';
}
</script>
</head>
<body>
<form ng-app=”” ng-controller=”EmpForm” name=”EmpFormPage” novalidate>
Emp name:
<input type=”text” name=”empname” ng-model=”empname” required>
<span ng-show=”EmpFormPage.empname.$error.required”>Please Enter Emp Name</span>
<br>
<br>
Email:
<input type=”email” name=”empemail” ng-model=”empemail” required>
<span ng-show=”EmpFormPage.empemail.$error.required”>Please Enter Email Address</span>
<span ng-show=”EmpFormPage.empemail.$error.email”>Invalid Email Address</span>
<p>
<input type=”submit” ng-disabled=”EmpFormPage.empname.$invalid || EmpFormPage.empemail.$invalid”>
</p>
</form>
</body>
</html>
  • ng-show directive show and hides the error messages as per the expression provided into it.
  • ng-disabled directive will disable the submit button till all the fields are validated properly

Output:
1

using renderSection() , renderBody() and renderpage() in asp.net mvc Layouts || Masterpages in asp.net mvc

hi in this post i will show how to use renderSection() , renderBody() and renderpage() in asp.net mvc

create a empty mvc application.
1. In view folder create a Shared folder and add a new view called _Layout.cshtml. this view will act as a master page for all the pages.
1


4
in the above code i have used renderbody() which will write the contents from the other view.
for rendersection() we need to define section named RSection in the other view

2. now lets use _Layout.cshtml into our actual view named homePage.cshtml
to achieve this we need to write this below code
@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}
2
in above code i have defined content for section RSection and also used renderPage() which will render view from other page named testPage.cshtml.
text hi im from homePage.cshtml will get called by renderBody() of the _Layout.cshtml.
Output:
3

Implementing bundling in asp.net mvc application || optimization of asp.net mvc application

hi here we will see how to implement bundling in asp.net mvc 4.
Bundling helps us to reduce the number of http requests made for calling .css and .js files. Bundling is a process where we bind multiple js or css files into one , so that we can reduce the number of http requests made for calling this files and thus improving the performance of a web application.

1. create a new mvc project, and go to manage nuget packages options and install asp.net web optimization framework.
11

2. now go to solution explorer app_start folder and create a new class called BundleConfig.cs
55

3. in bundleConfig.cs create seperate bundles for js and css files.
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new Bundle(“~/bundles/mycss”).Include(“~/css/StyleSheet1.css”,”~/css/StyleSheet2.css”));
bundles.Add(new ScriptBundle(“~/bundles/jsbundle”)
.Include(“~/js/jquery-2.1.1.js”).Include(“~/js/JavaScript1.js”));
//another way
//var bootstrapCss = new Bundle(“~/bootstrap/css”, new CssMinify());
//bootstrapCss.Include(“~/css/StyleSheet1.css”);
//bootstrapCss.Include(“~/css/StyleSheet2.css”);
//bundles.Add(bootstrapCss);
//var bootstrapJs = new Bundle(“~/bootstrap/js”, new JsMinify());
//bootstrapJs.Include(“~/js/jquery-2.1.1.js”);
//bootstrapJs.Include(“~/js/JavaScript1.js”);
//bundles.Add(bootstrapJs);
}
}
4. Now go to global.asax.cs file and add
BundleConfig.RegisterBundles(BundleTable.Bundles);
BundleTable.EnableOptimizations = true;
44

5. a) make sure debug is set to false in the web.config file of the application
b) and under <system.web> <pages><namespaces> tag add
  <add namespace=”System.Web.Optimization”/>
6. now we will go to view page(.cshtml) and add the js and css bundle references
66
@using System.Web.Optimization;
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
@Styles.Render(“~/bundles/mycss”)
@Scripts.Render(“~/bundles/jsbundle”)
<title>Samplepage</title>
</head>
<body>
<div>
<h1>Hi welcome to my site</h1>
<p>Enter your Name:</p>
<input id=”txtName” type=”text”/>
<button onclick=”message();”>Enter</button>
</div>
</body>
</html>

now lets run the application to check
output:
1. Before Bundling
22
2. After Bundling ( Check the time )
77

asp.net mvc validations using dataannotations

hi lets see how to do validation in asp.net mvc using dataannotations
so lets start implementing this.

1. first create a model :
public class DataForm
{
[Key]
public int EMPID { get; set; }
[StringLength(60, MinimumLength = 3,ErrorMessage=”Min String length is 3″)]
public string EMPNAME { get; set; }
[Required(ErrorMessage=”Field should not be empty”)]
public string EMPADD { get; set; }
[RegularExpression(@”^[0-9]{0,8}$”, ErrorMessage = “Salary should be Numeric”)]
public string EMPSAL { get; set; }
}
here in the above model we will define the form fields and the validation messages. we also need to add below namespace
using System.ComponentModel.DataAnnotations;
_1


2. after this go to controller and add two action methods.
httppost action method will only accept the postback requests like the submit, create.
public ActionResult data() // will be called intially
{
return View();
}
[HttpPost]
public ActionResult data(DataForm d1) // will handle postback requests
{
if (ModelState.IsValid)
{
return RedirectToAction(“saveData”);
}
return View(d1);
}

_2
3. now add a strongly typed view using model DataForm and using scaffold template as create.

1
@model mvcFilters.DataForm
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>data</title>
</head>
<body>
<script src=”~/Scripts/jquery-1.8.2.min.js”></script>
<script src=”~/Scripts/jquery.validate.min.js”></script>
<script src=”~/Scripts/jquery.validate.unobtrusive.min.js”></script>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>DataForm</legend>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPNAME)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPNAME)
@Html.ValidationMessageFor(model => model.EMPNAME)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPADD)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPADD)
@Html.ValidationMessageFor(model => model.EMPADD)
</div>
<div class=”editor-label”>
@Html.LabelFor(model => model.EMPSAL)
</div>
<div class=”editor-field”>
@Html.EditorFor(model => model.EMPSAL)
@Html.ValidationMessageFor(model => model.EMPSAL)
</div>
<p>
<input type=”submit” value=”Create” />
</p>
</fieldset>
}
<div>
@Html.ActionLink(“Back to List”, “Index”)
</div>
</body>
</html>
now run the project to check if the validations are working properly.
output:
2