Sunday, 16 July 2017

.net framework

1. How will you count the odd numbers from the array shown below using LINQ in .Net framework 4.0?
int[]numbers={5,4,1,3,9,8,6,7,2,0};
Answers:
  1. int findoddNumbers = numbers.Count(n => n % 2 == 1);
  2. int findoddNumbers = numbers.Count( n % 2 == 1);
  3. int findoddNumbers = (from number in numbers where numbers%2==1 select Count());
  4. int findoddNumbers = (from number in numbers where number%2==1 select numbers).Count();
2. How do you add MetaDescription to your web page in .Net framework 4.0?
Answers:
  1. HtmlMeta meta2 = new HtmlMeta(); meta2.Name = “description”; meta2.Content = “add meta description”; Page.Header.Controls.Add(HtmlMeta );
  2. Page.MetaDescription
  3. Both a and b are correct.
  4. None of the above.
3. Consider the following code snippet:
namespace ExtensionMethods
{
public static class NumericExtensionMethods
{
public static bool IsNumeric(this string s)
{
float output;
return float.TryParse(s, out output);
}
}
}
After adding the namespace, how will you call the ExtensionMethod on the string if your string variable is defined as:
string test=”4″;
Answers:
  1. test.IsNumeric();
  2. ExtensionMethods.NumericExtensionMethods.IsNumeric();
  3. NumericExtensionMethods m = new NumericExtensionMethods(); m.IsNumeric(test);
  4. None of the above
4. What is the purpose of the System.Windows.Data namespace in .Net framework 4.0?
Answers:
  1. Using System.Windows.Data namespace, you can integrate rich media, including drawings, text, and audio/video content in Windows Presentation Foundation applications.
  2. It contains classes used for binding properties to data sources, data source provider classes, and data-specific implementations of collections and views.
  3. It provides the types that support navigation, including navigating between windows and navigation journaling.
  4. It contains classes for creating windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system.
5. Suppose you want to eliminate duplicate elements from the array
int[] source = { 7, 4, 1, 3, 9, 8, 6, 7, 2, 1, 8, 15, 8, 23}
and sort the elements in descending order using LINQ in .Net framework 4.0. Which of the following statements can you use?
Answers:
  1. var result = (from s in source orderby s select distinct s).Descending();
  2. var result = (from s in source orderby s descending select s).Distinct();
  3. var result = select distinct s from s in source sortby s descending;
  4. var result = from s in source orderby s descending group p by s select s;
6. Which of the following classes of System.Windows.Media namespace provides rendering support in WPF which includes hit testing, coordinate transformation, and bounding box calculations in .Net framework 4.0?
Answers:
  1. HitTestResult
  2. Visual
  3. Colors
  4. Brush
7. Which of the following statements is correct for ASP.NET MVC Routing in .Net Framework 4.0?
Answers:
  1. It is used to match the incoming requests and to map them to a controller action.
  2. It is used to construct the outgoing URLs which correspond to controller actions.
  3. Both a and b are correct.
8. Which of the following is NOT a valid data source control in .Net framework 4.0?
Answers:
  1. LinqDataSource
  2. XmlDataSource
  3. AccessDataSource
  4. EntityDataSource
  5. All of the above are valid data sources
9. Which of the following statements is correct for WSHttpBinding of WCF in .Net framework 4.0?
Answers:
  1. It is a secure and interoperable binding that is suitable for non-duplex service contracts.
  2. It is a secure and interoperable binding that is suitable for duplex service contracts or communication through SOAP intermediaries.
  3. It is a secure and optimized binding suitable for cross-machine communication between WCF applications.
  4. It is a queued binding that is suitable for cross-machine communication between WCF applications.
10. What result will you get when you run the following LINQ query in .Net framework 4.0?
var scoreRecords = new[] { new {Name = “Alice”, Score = 50},
new {Name = “Bob” , Score = 40},
new {Name = “Cathy”, Score = 45}
};
var scoreRecordsDict = scoreRecords.ToDictionary(sr =>sr.Name);
Response.Write(scoreRecordsDict[“Bob”]);
Answers:
  1. { Name = Bob}
  2. { Name = Bob, Score = 40 }<
  3. Name = Bob
  4. None of the above
11. Which of the following is the correct way to expand the size of application URLs in .Net framework 4.0?
Answers:
  1. <httpModules maxRequestPathLength=”260″ maxQueryStringLength=”2048″ />
  2. <httpRuntime maxRequestPathLength=”260″ maxQueryStringLength=”2048″ />
  3. <httpHandlers maxRequestPathLength=”260″ maxQueryStringLength=”2048″ />
  4. None of the above
12. How will you implement the logic for the following scenario in .Net framework 4.0?
Suppose you have a GridView with paging enabled. You select the third row on page 1 and then move to page 2. Nothing is selected on page 2. When you move back to page 1, the third row should still be selected.
Answers:
  1. Set the GridView DataKeyNames property.
  2. Set the GridView EnablePersistedSelection property to true.
  3. Set the Gridview PagerSettings-Mode property.
  4. It is not possible to implement the given logic for the scenario described above.
13. Which of the following statements is correct for the bubbling routing strategies used by the routing events in WPF in .Net framework 4.0?
Answers:
  1. This event is first raised on the root, then on each element down the tree until the source element is reached.
  2. This event is only raised on the source element. It will have the same behavior as a plain .NET event, except that such events can still participate in mechanisms specific to routed events such as event triggers.
  3. This event is first raised on the source element, then on each element up the tree until the root is reached.
  4. None of the above.
14. How many columns can you select by $orderby OData system query option in .Net Framework 4.0?
Answers:
  1. 5
  2. 12
  3. 20
  4. infinite
15. Which of the following OData system query options is used to determine the maximum number of records to be returned in .Net framework 4.0?
Answers:
  1. $top
  2. $filter
  3. $select
  4. $expand
16. How can you determine, at runtime, if your application is running in the 64-bit version of .Net framework 4.0?
Answers:
  1. Check IntPtr.Size property for a value of 8.
  2. Call the Environment.GetEnvironmentVariable method and pass in the string “Platform” as an argument. Check for a return value of “x64”.
  3. Call the WOW64 emulator method Isx64() and check the boolean return value.
17. Suppose your WCF service root URL is “http://examples.svc”. What will be the response when you request a WCF data service URL with a $skip system query option, as shown below, in .Net framework 4.0?
http://examples.svc/Products?$skip=2&$top=2&$orderby=Rating
Answers:
  1. The response will be the first two product entries from the collection of all products after sorting the collection in descending order of Rating.
  2. The response will be the third and fourth product entries from the collection of all products after sorting the collection in ascending order of Rating.
  3. The response will be the second and third product entries from the collection of all products after sorting the collection in descending order of Rating.
18. Which of the following arrays will be returned as result when you run the following LINQ query in .Net framework 4.0?
object[] varnumbers = { null, 1.0, “two”, 3, “four”, 5, “six”, 7.0 };
var doubles = varnumbers.OfType<double>();
foreach (var d in doubles)
{
Response.Write(d);
}
Answers:
  1. 1, 7
  2. null
  3. two, four, six
  4. null, 1.0, “two”, 3, “four”, 5, “six”, 7.0
19. Which of the following ASP.NET MVC namespaces includes the classes that support forms, input controls, links, partial views, and validation in .Net Framework 4.0?
Answers:
  1. System.Web.Mvc
  2. System.Web.Mvc.Async
  3. System.Web.Mvc.Html
  4. System.Web.Mvc.Sync
20. What is DLR in .Net framework 4.0?
Answers:
  1. It defines the common types that are supported by the languages which are compatible with the .Net framework.
  2. It represents the data types of different languages in a specific format specification.
  3. It is a programming language that manages the execution of programs written in any of several supported languages, allowing them to share common object-oriented classes written in any of the languages.
  4. It is a runtime environment that adds a set of services for dynamic languages to the common language runtime.
21. What is default format used to represent data returned in an ADO.NET Data Services response in .Net framework 4.0?
Answers:
  1. XAML
  2. SOAP
  3. Atom
  4. WSDL
22. Considering the image, which of the following is the correct syntax for encoding a particular string in .Net framework 4.0?
Answers:
  1. Only a
  2. Only b
  3. Both a and b
23. In WCF, what is the significance of the ReceiveRetryCount property of a Poison message in .Net framework 4.0?
Answers:
  1. It is an integer value that indicates the maximum number of times to retry delivery of a message from the application queue to the application.
  2. It is an integer value that indicates the maximum number of retry cycles.
  3. It is the time delay between retry cycles.
24. Which of the following is NOT a valid WPF Localizability attribute in .Net framework 4.0?
Answers:
  1. Readability
  2. Modifiability
  3. Category
  4. Both a and b
  5. All of the above are Localizability attributes
25. Which of the following is NOT a valid QueryExtender filter option in .Net framework 4.0?
Answers:
  1. SearchExpression
  2. RangeExpression
  3. OrderByExpression
  4. All of the above are valid QueryExtender filter options
26. What is the function of WCF Data contracts in .Net framework 4.0?
Answers:
  1. They define, for each parameter or return type, what data is serialized to be exchanged..
  2. They define which operations the client can perform on the service.
  3. They define which errors are raised by the service, and how the service handles and propagates errors to its clients.
27. Which of the following pieces of information is provided by the WCF service contract in .Net framework 4.0?
Answers:
  1. The grouping of operations in a service.
  2. The location of the operations.
  3. The specific protocols and serialization formats that are used to support successful communication with the service.
  4. All of the above.
28. Suppose your site has a page called Index.aspx that you no longer use. Search engines may keep requesting this page.
Which of the following method will you add to the CodeBehind file of Index.aspx that will send requests (including search engine requests) to Default.aspx in .Net framework 4.0?
Answers:
  1. Server.Transfer
  2. Response.Redirect
  3. Response.RedirectPermanent
  4. Server.Execute
29. How will you display the view data in the view of an ASP.NET MVC Application?
Answers:
  1. <%: ViewData[“CurrentTime”] %>
  2. <%=ViewData[“CurrentTime”] %>
  3. %ViewData[“CurrentTime”] %
  4. <ViewData[“CurrentTime”] >
30. How is data passed from controllers to views in an ASP.NET MVC Application?
Answers:
  1. Using ViewData
  2. Using ViewState
  3. Using Sessions
  4. Using Cookies
31. What result will you get when you run the following LINQ query in .Net framework 4.0?
List<string> alphabets = new List<string>() { “whats”, “new”, “in”, “aspnet” };
var alphabetsquery = from alphabet in alphabets select alphabet.Substring(0, 1);
foreach (var alpha in alphabetsquery)
{
Response.Write(alpha);
}
Answers:
  1. wnia
  2. whats
  3. whatsnewinaspnet
  4. aspnetinnewwhats
32. What is a Decorator in WPF of .Net framework 4.0?
Answers:
  1. It is used to add functional handles to elements or provide state information about a control.
  2. It is the base class for elements that apply effects onto or around a single child element, such as Border or Viewbox.
  3. It provides a set of services that can be used to extend the functionality of a common language runtime property.
  4. It is a property with the exception that its value cannot be set outside the class that declared the read-only property.

Thursday, 13 July 2017

How to use stored procedure using linq query

 var result = (from p in objectDBML.SSP_ACGetAllUser()
                                              where p.UserName.Trim().ToLower().StartsWith(SearchCode.ToLower())
                                              && p.IsApproved == true
                                              select new { p.UserName }).Take(15).ToList();

How to use transactions in EF


   using(Context ctx= new Context())
   {
 Country country= new Country();
 country.Name="India";
 ctx.Countries.Add(country);
 ctx.submitChanges();

 State state= new State();
 state.Name="UP";
 state.countryId=country.countryId;
 ctx.States.Add(state);
 ctx.submitChanges();


   }

 Note : Succesfully added Country and states values in database.



 using(Context ctx= new Context())
   {
 Country country= new Country();
 country.Name="India";
 ctx.Countries.Add(country);
 ctx.submitChanges();

 State state= new State();
 int a=0;
 int total = 10/a;
 state.Name="UP";
 state.countryId=country.countryId;
 ctx.States.Add(state);
 ctx.submitChanges();


   }

 Note : Country added sucessfully but state are not added corresponding to country.
 So use transactions.



try
{
  using(TransactionScope ts= new TransactionScope())
  {
  using(Context ctx= new Context())
  {
 Country country= new Country();
 country.Name="India";
 ctx.Countries.Add(country);
 ctx.submitChanges();

 State state= new State();
 state.Name="UP";
 state.countryId=country.countryId;
 ctx.States.Add(state);
 ctx.submitChanges();

 ts.Commit();
  }
   }
}
catch(Exception ex)
{
 ts.RollBack();
}

Saturday, 8 July 2017

What is IRouteConstraint ? why we use it

In this tip, I show how you can create custom route constraints that prevent you from accessing a URL unless you are local and authenticated. I show you how you can create a LocalConstraint and an AuthenticatedConstraint. I also demonstrate how you can test your custom constraints.
When you create an MVC route, you can add constraints to a route. For example, the following route maps browser requests to a controller named Blog and an action named Archive:
routes.MapRoute(
  "BlogArchive",
  "Archive/{entryDate}",
  new { controller = "Blog", action = "Archive" }
);
This route, named BlogArchive, maps three parameters. The controller parameter is assigned the value Blog and the action parameter is assigned the value Archive. Finally, the entryDate parameter gets its value from the entryDate parameter in the URL.
Unfortunately, this route matches too many requests. It matches:
· /Archive/12-25-1966
· /Archive/12
· /Archive/apple
You don’t want entryDate to get values like 12 or apple. These values cannot be converted into a date.
You can fix this problem with the BlogArchive route by adding a constraint to the entryDate parameter like this:
routes.MapRoute(
  "BlogArchive",
  "Archive/{entryDate}",
  new { controller = "Blog", action = "Archive" },
  new { entryDate = @"d{2}-d{2}-d{4}" }
);
This new version of the BlogArchive route includes a constraint on the entryDate parameter. The constraint requires that the entryDate parameter matches a date pattern that looks like 12-25-1966. A URL like /Archive/apple won’t satisfy this constraint and the route won’t be matched.

Two Types of Route Constraints

The URL Routing framework recognizes two different types of constraints. When you supply a constraint, you can either supply a string or you can supply a class that implements the IRouteConstraint interface.
If you supply a string for a constraint then the string is interpreted as a regular expression. For example, the entryDate constraint that we discussed in the previous section is an example of a regular expression constraint.
The other option is to create a custom constraint by creating an instance of a class that implements the IRouteConstraint interface. The URL Routing framework includes one custom constraint: the HttpMethod constraint.

Using the HttpMethod Constraint

You can take advantage of the HttpMethod constraint to prevent a controller action from being invoked unless the action is invoked with a particular HTTP method. For example, you might want a controller action named Insert() to be invoked only when performing an HTTP POST operation and not when performing an HTTP GET operation.
Here’s how you can use the HttpMethod constraint:
routes.MapRoute(
  "Product",
  "Product/Insert",
  new { controller = "Product", action = "Insert"},
  new { httpMethod = new HttpMethodConstraint("POST") }
);
The last argument passed to the MapRoute() method represents a new HttpMethod constraint named httpMethod. If you post an HTML form to the /Product/Insert URL, then the Product.Insert() controller action will be invoked. However, if you simply request /Product/Insert with an HTTP GET, then this route won’t be matched.
By the way, the name of the constraint is not important. Only the value is important. For example, the following code works just as well as the previous code:
routes.MapRoute(
  "Product",
  "Product/Insert",
  new { controller = "Product", action = "Insert"},
  new { Grendal = new HttpMethodConstraint("POST") }
);
In this code, the HttpMethodConstraint is named Grendal. You can name the constraint anything you want and the constraint will still work.

Creating an Authenticated Constraint

You create custom constraints by implementing the IRouteConstraint interface. This interface has one method that you must implement: the Match() method.
For example, the code in Listing 1 represents a custom constraint that prevents unauthenticated access to a URL:
Listing 1 – AuthenticatedConstraint.cs
using System.Web;
using System.Web.Routing;
public class AuthenticatedConstraint : IRouteConstraint
{
  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    return httpContext.Request.IsAuthenticated;
  }
}
Notice that Listing 1 contains a class that implements the IRouteConstraint interface. The Match() method checks whether the current user is authenticated and returns either True or False.
Here’s how you can use the AuthenticatedConstraint when creating a route:
routes.MapRoute(
  "Admin",
  "Admin/{action}",
  new { controller = "Admin", action = "Index" },
  new { authenticated= new AuthenticatedConstraint()}
);
This constraint prevents requests from anonymous users from being mapped to the Admin route.
It is important to understand that even though this particular route cannot be accessed by an anonymous user, a later route might map an anonymous user to the same controller and controller action. For example, if the Admin route is followed by the following Default route, then a user can access the Admin pages:
routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", id = "" }
);
For this reason, you should explicitly exclude the Admin pages from the Default route with an explicit constraint.

Creating a NotEqual Constraint

The easiest way to exclude one set of pages from matching a particular route is to take advantage of the custom route constraint in Listing 2.
Listing 2 – NotEqualConstraint.cs
using System;
using System.Web;
using System.Web.Routing;

public class NotEqual : IRouteConstraint
{
  private string _match = String.Empty;

  public NotEqual(string match)
  {
    _match = match;
  }

  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    return String.Compare(values[parameterName].ToString(), _match, true) != 0;
  }
}
Here’s how you can use the NotEqual constraint to exclude the /Admin pages from the Default route:
routes.MapRoute(
  "Default",
  "{controller}/{action}/{id}",
  new { controller = "Home", action = "Index", id = "" },
  new { controller = new NotEqual("Admin") }
);
This route won’t match any request when the controller parameter gets the value Admin. For example, this route won’t match the URLs /Admin/DeleteAll or /Admin/Index.

Creating a Local Constraint

You also can create a custom constraint that prevents a request from matching a URL unless the request is made from the local machine. This type of constraint can be useful for restricting access to website administrative pages.
Listing 3 contains the code for the LocalConstraint class.
Listing 3 – LocalConstaint.cs
using System.Web;
using System.Web.Routing;

public class LocalConstraint : IRouteConstraint
{

  public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
  {
    return httpContext.Request.IsLocal;
  }
}
The LocalConstraint simply checks whether the current request is a local request by taking advantage of the Request.IsLocal property. This property returns the value True when the host is either equal to localhost or 127.0.0.1.

Testing Route Constraints

So how do you test route constraints? Easy, fake the HttpContext. The test in Listing 4 can be used to verify that the Product route includes an HttpMethod constraint.
Listing 4 – A Unit Test for the HttpMethod Constraint
[TestMethod]
public void TestInsertIsPost()

{
  // Arrange
  var routes = new RouteCollection();
  GlobalApplication.RegisterRoutes(routes);

  // Act with POST request
  var fakeContext1 = new FakeHttpContext("~/Product/Insert", "POST");
  var routeData1 = routes.GetRouteData(fakeContext1);

  // Assert
  NamedRoute matchedRoute1 = (NamedRoute)routeData1.Route;
  Assert.AreEqual("Product", matchedRoute1.Name);

  // Act with GET request
  var fakeContext2 = new FakeHttpContext("~/Product/Insert");
  var routeData2 = routes.GetRouteData(fakeContext2);

  // Assert
  NamedRoute matchedRoute2 = (NamedRoute)routeData2.Route;
  Assert.AreNotEqual("Product", matchedRoute2.Name);

}
The unit test in Listing 4 consists of two tests. First, the URL /Product/Insert is requested by performing a POST operation. The Product route should be matched in the route table. Next, the same URL is requested while performing a GET operation. The Product route should not be matched when performing a GET.
The unit test in Listing 5 demonstrates how you can test the AuthenticatedConstraint.
Listing 5 – Unit Test for AuthenticatedConstraint
[TestMethod]
public void TestAdminRouteIsAuthenticated()
{
  // Arrange
  var routes = new RouteCollection();
  GlobalApplication.RegisterRoutes(routes);

  // Act with authenticated request
  var fakeUser = new FakePrincipal(new FakeIdentity("Bob"), null);
  var fakeContext1 = new FakeHttpContext(new Uri("http:/Index"), "~/Admin/Index", fakeUser);
  var routeData1 = routes.GetRouteData(fakeContext1);

  // Assert
  NamedRoute matchedRoute1 = (NamedRoute)routeData1.Route;
  Assert.AreEqual("Admin", matchedRoute1.Name);

  // Act with anonymous request
  var fakeContext2 = new FakeHttpContext(new Uri("http:/Index"), "~/Admin/Index");
  var routeData2 = routes.GetRouteData(fakeContext2);

  // Assert
  Assert.IsNull(routeData2);
}
This unit test also consists of two tests. First, a fake user is created with the help of the FakeIdentity class. When the /Admin/Index URL is requested with the fake identity in context, the Admin route should be matched. When the same URL is requested anonymously, on the other hand, no route should be matched.

OR,

//GuidConstraint  - class to implement IRouteConstraint


using System;
using System.Web;
using System.Web.Routing;

namespace Nop.Web.Framework.Mvc.Routes
{
    public class GuidConstraint : IRouteConstraint
    {
        private readonly bool _allowEmpty;

        public GuidConstraint(bool allowEmpty)
        {
            this._allowEmpty = allowEmpty;
        }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (values.ContainsKey(parameterName))
            {
                string stringValue = values[parameterName] != null ? values[parameterName].ToString() : null;

                if (!string.IsNullOrEmpty(stringValue))
                {
                    Guid guidValue;

                    return Guid.TryParse(stringValue, out guidValue) && 
                        (_allowEmpty || guidValue != Guid.Empty);
                }
            }

            return false;
        }
    }
}

//RouteProvider.cs


 
  routes.MapRoute("GetDownload",
                            "download/getdownload/{orderItemId}/{agree}",
                            new { controller = "Download", action = "GetDownload", agree = UrlParameter.Optional },
                            new { orderItemId = new GuidConstraint(false) },
                            new[] { "Nop.Web.Controllers" });


            routes.MapRoute("GetLicense",
                            "download/getlicense/{orderItemId}/",
                            new { controller = "Download", action = "GetLicense" },
                            new { orderItemId = new GuidConstraint(false) },
                            new[] { "Nop.Web.Controllers" });

//Action

public virtual ActionResult GetLicense(Guid orderItemId)
        {
            var orderItem = _orderService.GetOrderItemByGuid(orderItemId);
            if (orderItem == null)
                return InvokeHttp404();

            var order = orderItem.Order;
            var product = orderItem.Product;
            if (!_downloadService.IsLicenseDownloadAllowed(orderItem))
                return Content("Downloads are not allowed");

            if (_customerSettings.DownloadableProductsValidateUser)
            {
                if (_workContext.CurrentCustomer == null || order.CustomerId != _workContext.CurrentCustomer.Id)
                    return new HttpUnauthorizedResult();
            }

            var download = _downloadService.GetDownloadById(orderItem.LicenseDownloadId.HasValue ? orderItem.LicenseDownloadId.Value : 0);
            if (download == null)
                return Content("Download is not available any more.");
            
            if (download.UseDownloadUrl)
                return new RedirectResult(download.DownloadUrl);

            //binary download
            if (download.DownloadBinary == null)
                return Content("Download data is not available any more.");
                
            //return result
            string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : product.Id.ToString();
            string contentType = !String.IsNullOrWhiteSpace(download.ContentType) ? download.ContentType : MimeTypes.ApplicationOctetStream;
            return new FileContentResult(download.DownloadBinary, contentType) { FileDownloadName = fileName + download.Extension };
        }

What is model binder/ default model binder in mvc and when which senario create custom model binder and how?



Model Binder-

I have a customer model like -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ModelBinder.Models
{
    public class Customer
    {
        public string  CustomerName { get; set; }
        public string CustomerCode { get; set; }
    }
}


Now, i am creating view on based on Customer model,ie, also known as Strongly typed view.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ModelBinder.Models.Customer>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>CustomerDatsils</title>
</head>
<body>
    <div>
        <%= Html.LabelFor(model => model.CustomerCode)%> :
        <%= Html.TextBoxFor(model => model.CustomerCode) %> <br />
         <%= Html.LabelFor(model => model.CustomerName)%> :
        <%= Html.TextBoxFor(model => model.CustomerName) %>
    </div>
</body>
</html>

So, when we post the data on server side to manupulate operations lke

[HttpPost]
 public ActionResult CustomerDatsils(Customer customer)
 {
         return View("CustomerDatsils", customer);
  }

So, we get the all model properties values filled automatically known as Default model binder. Its values filled automatically due to model properties name same as the controls name.

Suppose, i have changed the controls names or can say not creating strongly typed view like as



<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>CustomerInfo</title>
</head>
<body>
    <div>
       <form action="Home/CustomerDatsils" method="post">
        Customer Code : <input id="txtCustomerCode" name="txtCustomerCode" type="text" /><br />
        Customer Name : <input id="txtCustomerName" name="txtCustomerName" type="text" /><br />
   
        <input id="Submit1" type="submit" value="submit" />
      </form>
    </div>
</body>
</html>

So, in this senario when i post the data on server side then gets model properties values null. because model properties names is not same as controls names in view. So, to bind model properties values with different controls names and get filled values of model when we post data on server, it can be possible by Custom model binder.


 public class CustomerBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpContextBase context = controllerContext.HttpContext;

            string custCode = context.Request.Form["txtCustomerCode"];
            string custName = context.Request.Form["txtCustomerName"];

            Customer cust = new Customer()
            {
                CustomerCode =custCode,
                CustomerName =custName
            };

            return cust;
        }
    }



        [HttpPost]
        public ActionResult CustomerDatsils(
            [ModelBinder(typeof(CustomerBinder))]
            Customer info)
        {
            return View("CustomerDatsils", info);
        }




Tuesday, 4 July 2017

Insert/update and delete query in linq?

Insert :- 

using (DataContext objDataContext = new DataContext())
            {
                Employee objEmp = new Employee();
                // fields to be insert
                objEmp.EmployeeName = "";
                objEmp.EmployeeAge = 25;
                objEmp.EmployeeDesc = "";
                objEmp.EmployeeAddress = "";
                objEmp.EmployeeExperience = 8;
                objDataContext.Employees.InsertOnSubmit(objEmp);
                // executes the commands to implement the changes to the database
                objDataContext.SubmitChanges();
            };

Update :- 

 using (DataContext objDataContext = new DataContext())
            {
                // Get single employee to update
                Employee objEmp = objDataContext.Employees.Single(emp => emp.EmployeeName == "john");
                //Field which will be update
                objEmp.EmployeeExperience = 10;
                // executes the commands to implement the changes to the database
                objDataContext.SubmitChanges();
            };

Deletete :- 

using (DataContext objDataContext = new DataContext())
            {
                // Get single employee to update
                Employee objEmp = objDataContext.Employees.Single(emp => emp.EmployeeName == "john");              
                objDataContext.Employees.DeleteOnSubmit(objEmp);
                // executes the commands to implement the changes to the database
                objDataContext.SubmitChanges();
            };