Thursday, September 13, 2012

Add Numbers in MVC



@{
    Layout = null;
}

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>My Title</title>
 <meta charset="utf-8" />
 <style type="text/css">
     body
     {
         background-color: beige; font-family: Verdana, Arial;margin: 50px;
          }
          form
          {padding: 10px; border-style: solid; width: 250px;}
          </style>
          </head>
          <body>
          <p>
          Enter two whole numbers and then click
          <strong>Add</strong>.</p>
          <form action="" method="post">
          @{
            var total = 0;
            var totalMessage = "";
            if(IsPost)
             {
             @*Retrieve the numbers that the user entered.*@
             var num1 = Request["text1"];
             var num2 = Request["text2"];
             @*Convert the entered strings into integers numbers and add.*@
             total = num1.AsInt() + num2.AsInt();
             totalMessage = "Total = " + total;
             }
             }
          <p>
          <label for="text1">First Number:</label>
          <input type="text" name="text1" />
          </p><p>
          <label for="text2">Second Number:</label>
          <input type="text" name="text2" />
          </p><p>
          <input type="submit" value="Add" />
          </p>
          </form>
          <p>@totalMessage</p>
          </body>
          </html>



The Top 8 Programming Tips in MVC

1.You add code to a page using @ Character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks:


<!-- Single statement blocks -->
       @{ var total = 7; }
       @{ var myMessage = "Hello World"; }
       <!-- Inline expressions --><p>
       The value of your account is: @total </p>
       <p>The value of myMessage is: @myMessage</p>
       <!-- Multi-statement block -->
       @{
         var greeting = "Welcome to our site!";
         var weekDay = DateTime.Now.DayOfWeek;
         var greetingMessage = greeting + " Today is: " + weekDay;

        }
        <p>The greeting is: @greetingMessage</p>


The value of your account is: 7
The value of myMessage is: Hello World
The greeting is: Welcome to our site! Today is: Thursday

2. You enclose code blocks in braces

A code block includes one or more code statements and is enclosed in braces.:


<!-- Single statement block. -->
        @{ var theMonth = DateTime.Now.Month; }
        <p>The numeric value of the current month: @theMonth</p>
        <!-- Multi-statement block. -->
        @{
            var outsideTemp = 79;
             var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
          }
                                                                                                                                                                       
        <p>Today's weather: @weatherMessage</p>

The numeric value of the current month: 9
Today's weather: Hello, it is 79 degrees.

3. Inside a block, you end each code statement with a semicolon

Inside a code block, each complete code statement must end with a semicolon. Inline expressions donot end with a semicolon.:

4. You use variables to store values

You can store values in a variable , including strings, numbers, and dates, etc. You create a new variableusing the var keyword. You can insert variable values directly in a page using @ :


<!-- Storing a string -->
         @{ var welcomeMessage = "Welcome, new members!"; }
         <p>@welcomeMessage</p>
         <!-- Storing a date -->
         @{ var year = DateTime.Now.Year; }
         <!-- Displaying a variable -->
         <p>Welcome to our new members who joined in @year!</p>


Welcome, new members!
Welcome to our new members who joined in 2012!

5. You enclose literal string values in double quotation marks

A string is a sequence of characters that are treated as text. To specify a string, you enclose it in doublequotation marks:


@{ var myString = "This is a string literal"; }
          <p>Literal : @myString</p>
          <!-- Embedding a backslash in a string -->
          @{ var myFilePath = @"C:\MyFolder\"; }
          <p>The path is: @myFilePath</p>


          <!-- Embedding double quotation marks in a string -->
          @{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
          <p>@myQuote</p>


Literal : This is a string literal
The path is: C:\MyFolder\
The person said: "Hello, today is Monday."

6. Code is case sensitive

In C#, keywords ( var, true, if ) and variable names are case sensitive.
The following lines of codecreate two different variables, lastName and LastName.
@{var lastName = 'Smith';var LastName = 'Jones';}
If you declare a variable as var lastName = "Smith"; and if you try to reference that variable in yourpage as @LastName , an error results because LastName won't be recognized.

7. Much of your coding involves objects

An object represents a thing that you can program with — a page, a text box, a file, an image, a webrequest, an email message, a customer record (database row), etc.


<table border="1" style="width:400px">
            <tr>
            <td>Requested URL</td>
            <td>Relative Path</td>
            <td>Full Path</td>
            <td>HTTP Request Type</td>
            </tr>
            <tr>
            <td>@Request.Url</td>
            <td>@Request.FilePath</td>
            <td>@Request.MapPath(Request.FilePath)</td>
            <td>@Request.RequestType</td>
            </tr>
            </table>



8. You can write code that makes decisions

A key feature of dynamic web pages is that you can determine what to do based on conditions. Themost common way to do this is with the if statement (and optional else statement).


@{var result = "";
              if(IsPost)
              {
                  result = "This page was posted using the Submit button.";
              }
              else
              {
                  result = "This was the first request for this page.";
              }
              }
              <input type="submit" name="Submit" value="Submit"/>
              <p>@result</p>


This was the first request for this page.

Current System Time Display in MVC


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Time</title>
</head>
<body>
    <div>
        <h1>Hello World Page</h1>
        <p>Hello World !</p>
        <p>The Time is @DateTime.Now</p>
    </div>
</body>
</html>



Operators inMVC


Operator

Description

Example

.

Dot. Used to distinguish objects and theirproperties and methods.

var myUrl = Request.Url;var count =Request["Count"].AsInt();

()

Parentheses. Used to group expressions and topass parameters to methods.

@(3 + 7)@Request.MapPath(Request.FilePath);

[]

Brackets. Used for accessing values in arrays orcollections.

var income =Request["AnnualIncome"];

=

Assignment. Assigns the value on the right side of a statement to the object on the left side. (Noticethe distinction between the = operator and the == operator.)

var age = 17;

!

Not. Reverses a true value to false and viceversa. Typically used as a shorthand way to testfor false (that is, for not true ).

bool taskCompleted = false;// Processing.if(!taskCompleted) {// Continue processing}

==

Equality. Returns true if the values are equal.

var myNum = 15;if (myNum == 15) {// Do something.}

!=

Inequality. Returns true if the values are notequal.

var theNum = 13;if (theNum != 15) {// Do something.}

<

>


<=

>=

Less-than,greater-than,less-than-or-equal, andgreater-than-or-equal.

if (2 < 3) {// Do something.} var currentCount = 12; if(currentCount >= 12) {// Do something.}

+

Math operators used in numerical expressions.

@(5 + 13)@{ var netWorth = 150000; }@{ var newTotal = netWorth * 2; }

Classes in MVC


Method

Description

Example

AsInt(),IsInt()

Converts a string that representsa whole number (like "93") to aninteger.

var myIntNumber = 0;var myStringNum = "539";if(myStringNum.IsInt()==true){myIntNumber = myStringNum.AsInt();}

AsBool(),IsBool()

Converts a string like "true" or"false" to a Boolean type.

var myStringBool = "True";var myVar = myStringBool.AsBool();

AsFloat(),IsFloat()

Converts a string that has adecimal value like "1.3" or "7.439"to a floating-point number.

var myStringFloat = "41.432895";var myFloatNum = myStringFloat.AsFloat();

AsDecimal(),IsDecimal()

Converts a string that has adecimal value like "1.3" or "7.439"to a decimal number.

(A decimalnumber is more precise than afloating-point number.)
var myStringDec = "10317.425";var myDecNum = myStringDec.AsDecimal();

AsDateTime(),IsDateTime()

Converts a string that representsa date and time value to theASP.NET DateTime type.

var myDateString = "12/27/2010";var newDate = myDateString.AsDateTime();

ToString()

Converts any other data type to astring.

int num1 = 17;int num2 = 76;// myString is set to 1776string myString = num1.ToString() +num2.ToString();

Wednesday, September 5, 2012

DatePicker in MVC

View


@model DatePickerTemp.Models.FooEditModel
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Edit</h2>
@Model.Message
@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.Foo)
    <input id="submit" name="submit" type="submit" value="Save" />
}

Models


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using DatePickerTemp.Infrastructure;

namespace DatePickerTemp.Models
{
    public class Foo
    {
        public string Name { get; set; }

        [DataType(DataType.Date)]
        public DateTime Date1 { get; set; }

        [DateRange(Min = "2010/12/02")]
        public DateTime Date2 { get; set; }

        [DateRange(Max = "2010/12/20")]
        public DateTime Date3 { get; set; }

        [DateRange(Min = "2010/12/02", Max = "2010/12/20")]
        public DateTime Date4 { get; set; }
    }
}



namespace DatePickerTemp.Models
{
    public class FooEditModel
    {
        public string Message { get; set; }
        public Foo Foo { get; set; }
    }
}


DatePicker.zip


Tuesday, September 4, 2012

Gridview in MVC

Model 


  public DataSet displayPageLoad(Int64 opt6)
        {
            if (cn.State == ConnectionState.Open)
                cn.Close();
            cn.Open();
            ds = new DataSet();
            ds.Clear();
            SqlDataAdapter ad;
            sqlcmd = new SqlCommand();
            sqlcmd.Parameters.Clear();
            sqlcmd.Connection = cn;
            sqlcmd.CommandType = CommandType.StoredProcedure;
            sqlcmd.CommandText = "Outgoing_Calls_SP";
            sqlcmd.Parameters.AddWithValue("@opt", opt6);
            sqlcmd.Parameters.AddWithValue("@telecom_id", "");
            sqlcmd.Parameters.AddWithValue("@datee", "");
            sqlcmd.Parameters.AddWithValue("@timee_from", "");
            sqlcmd.Parameters.AddWithValue("@timee_to", "");
            sqlcmd.Parameters.AddWithValue("@contact_number", "");
            sqlcmd.Parameters.AddWithValue("@contact_person", "");
            sqlcmd.Parameters.AddWithValue("@communication_msg", "");
            sqlcmd.Parameters.AddWithValue("@response_msg", "");
            sqlcmd.Parameters.AddWithValue("@dept", "");
            sqlcmd.Parameters.AddWithValue("@callername", "");
            sqlcmd.Parameters.AddWithValue("@branch", "");
            sqlcmd.Parameters.AddWithValue("@status", "");
            sqlcmd.Parameters.AddWithValue("@alerttime", "");
            sqlcmd.Parameters.AddWithValue("@alert", "");
            sqlcmd.Parameters.AddWithValue("@cid", "");
            sqlcmd.Parameters.AddWithValue("@deptmanager", "");
            ad = new SqlDataAdapter(sqlcmd);
            ad.Fill(ds);
            return ds;
        }
        public List<IDictionary> FetchOutgoingDetails()
        {
            DataSet dsEmployee = new DataSet();
            Int64 opt6 = 6;
            dsEmployee = displayPageLoad(opt6);

            return ConvertToDictionary(dsEmployee.Tables[0]);
        }
        private List<IDictionary> ConvertToDictionary(DataTable dtObject)
        {
            var columns = dtObject.Columns.Cast<DataColumn>();

            var dictionaryList = dtObject.AsEnumerable()
                .Select(dataRow => columns
                    .Select(column =>
                        new { Column = column.ColumnName, Value = dataRow[column] })
                             .ToDictionary(data => data.Column, data => data.Value)).ToList().ToArray();

            return dictionaryList.ToList<IDictionary>();
        }

Controller


 public ActionResult OutgoingList(CabAutomationSystem.Models.Outgoing outgoinglist)
        {
            var resultSet = outgoinglist.FetchOutgoingDetails();
            return View(resultSet);
        }

View


@{
    ViewBag.Title = "OutgoingList";
    Layout = "~/Views/Admin/Master.cshtml";
}

<h2>OutgoingList</h2>

@section Styles
{
<link href="@Url.Content("~/Content/grid.css")" rel="stylesheet" type="text/css" />
}

@{
          ViewBag.Title = "List";
    }

    @using System.Dynamic
@model List<System.Collections.IDictionary>
@{
    var result = new List<dynamic>();

    foreach (var emprow in Model)
    {
        var row = (IDictionary<string, object>)new ExpandoObject();
        Dictionary<string, object> eachEmpRow = (Dictionary<string, object>)emprow;

        foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
        {
            row.Add(keyValuePair);
        }
        result.Add(row);
    }
 
}

@{
 
    var grid = new WebGrid(source: result,
                                           defaultSort: "telecom_id",
                                           rowsPerPage:5, fieldNamePrefix:"wg_",
                                           canPage:true,canSort:true,
                                           pageFieldName:"pg",sortFieldName:"srt"
                                           );
 }

 <table cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td>
            @grid.GetHtml(tableStyle:"listing-border",headerStyle:"gridhead",footerStyle:"paging",rowStyle:"td-dark",alternatingRowStyle:"td-light",
                            columns:
                                grid.Columns(
                                grid.Column(header:"", format: @<text><input id="chk" type="checkbox" value="@item.telecom_id" /></text>),
                                    grid.Column("datee", "Date", style: "colFirstName"),
                                    grid.Column("timee_from", "Time from", style: "colLastName"),
                                    grid.Column("timee_to", "Time to", style: "colPhone"),
                                    grid.Column("contact_number", "Contact Number", style: "colEmail"),
                                    grid.Column("contact_person", "Contact Person", style: "colContactType"),
                                    grid.Column(header: "Edit", format: @<text><a href="@Url.Action("Edit", "Contact", new { id = item.telecom_id })" ><img src="../../Content/images/Edit.jpg" alt="" style="border:none;" /></a></text>, style: "colOperation"),
                                    grid.Column(header: "Delete", format: @<text><a href="@Url.Action("Delete", "Contact", new { id = item.telecom_id })" onclick="javascript:return ConfirmDelete();"><img src="../../Content/images/delete.jpg" alt="" style="border:none;" /></a></text>, style: "colOperation")
                                ),mode:WebGridPagerModes.Numeric)
        </td>
    </tr>
 </table>
<script type="text/javascript">
    function ConfirmDelete() {
        return confirm("Are you sure you want to delete contacts?");
    }
</script>



CSS


.listing-border { background: #fd7d0f;}
.gridhead { background:#FFAA5F;  font: bold 13px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; height: 27px; text-align: left;}
.gridhead th a {text-decoration:none;color:#000000;}
.gridhead th a:hover {text-decoration:underline;color:#FF0000;}
.td-dark { background: #ffffff; height: 20px; }
.td-light { background: #FFE2BF; height: 20px; }
.paging { background: #fd7d0f;text-align: right;color:#000000;}
.paging span { font: bold 12px Arial, Helvetica, sans-serif; color:#FFFFFF; margin-right: 3px; padding: 1px 3px 1px 3px }
.paging a { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; margin-right: 3px; border: 1px solid #ffffff; background: #fd7d0f; padding: 1px 3px 1px 3px }
.paging a:hover { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; border: 1px solid #ffffff; background: #ffffff; }
.colFirstName{width:18%;text-align:left;}
.colLastName{width:18%;text-align:left;}
.colPhone{width:14%;text-align:left;}
.colEmail{width:19%;text-align:left;}
.colContactType{width:18%;text-align:left;}
.colOperation{width:50px;text-align:center;}








Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...