MVC: Set Master Page File based on day and Night time

  
Here you need to follow just simple four steps to get this activity done.

Step1:

On your Controller set a “TempData” [a variable which is shared among controller and view internally using session] variable like below to identify current time is Day or Night.

     
   public ActionResult Index()
   {

      TimeSpan time = DateTime.Now.TimeOfDay;
      if ((time > new TimeSpan(05, 59, 00)) && (time < new TimeSpan(17, 59, 00)))
            {
                TempData["DayNight"] = true; //True is Day

            }
            else
            {
                TempData["DayNight"] = false; //False in Night
           
            }
     return View();
    }



I have added it on “Index” Action method on some controller. It is not mandatory to set it on only index, you can use any other action method but need to make sure that you once after executing action method you should return any view basically where[returning View] we will do our stuff for Master page file selection.

Step2:

Create your view by right clicking on Action method à Add View. Default name is Index. Press okay. So a new View called “Index” gets created on the view folder.

[This is step is pretty much common in MVC. We create controller named as Employee, on the Employee controller we have an action method named as Index, then we right click and add a view. On the View folder you have a subfolder Employee and within that one page “Index.aspx” (aspx engine) or “Index.cshtml”(for razor engine)]


Step3:

Now  add two views in your shared folder like below. They are named as “_DayLayout” and “_NightLayout”. Simple and straight forward.



Step4:

Now top of your main view [The View which you have created in Step2] include the below. I am using MVC3 with Razor view.


@{ 
    if (Convert.ToBoolean(@TempData["DayNight"]) == true)
    {
        Layout = "~/Views/Shared/_DayLayout.cshtml";
    }
    else
    {
        Layout = "~/Views/Shared/_NightLayout.cshtml";
    }   
}



You are done. Execute and Check it where as in ASP.Net we use to set up master page file in “Page_PreInit()  method . Feel free to post your query @nit.pradip@gmail.com


MVC: Multiple Models in One Single View

Here the question is say you have two model M1 and M2. M1 model consistd properties like a,b. M2 Consists properties like c,d. All a,b,c, d are required(Tagged as [Required]). Now you have a single View V. You have to display all a,b,c,d four properties into V view.

The simplest solution is first create M1 and M2 model class with a,b[in M1] and c,d[in M2] property . Now in M1 Model have a list property of M2 class

public List<M2> M2Prop { get; set; }

Access M1 Class in V view. You are done. Have a look on the below sample code.

public class Student
    {
        [Required]
        public int RollNo { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Class { get; set; }

        public string Address { get; set; }

        public List<StudentScore> StudentScore { get; set; }

   }

And the ‘StudentScore’ class is as follows.

public class StudentScore
    {
        [Required]
        public int StudentRollNo { get; set; }

        [Required]
        public string StudentName { get; set; }

        [Required]
        public string Subject { get; set; }

        [Required]
        public int Marks { get; set; }

        [Required]
        public string Grade { get; set; }

    }

Create View with strongly typed of Student Class.
And on the view it is like below.

@model IEnumerable<MultipleModelInOneView.Models.Student>


@foreach (var item in Model)
    {

<td>
                @item.RollNo
            </td>
            <td>
                @item.Name
            </td>

       @foreach (var score in item.StudentScore)
            {
                 <td>
                    @score.Grade
                  
                </td>
                <td>
                    @score.Marks
                </td>
           
            }

}



You are done. Feel free to post any query.

MVC: Hide a model property to display in view


Below is the model class for Employee. Pretty Simple!

public class Employee
    {
        [Required]
        public int EmpID { get; set; }

        [DisplayName("Name")]
        [Required]
        public string EmpName { get; set; }

        [DisplayName("Bussiness Segment")]
        [Required]
        public string EmpDept { get; set; }
       
        [Required]
        public string Salary { get; set; }

        [DisplayName("Designation")]
        [Required]
        public string EmpLevel { get; set; }
    }


And below is the view I have to display list of employees which I have created like in Index action method of Employee Controller – right click and add View and then select strongly type view and then select Employee model class.

@model   IEnumerable<MvcAppModelBinding.Models.Employee>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <fieldset>
        <legend>Employee</legend>
   
        @foreach (var item in Model)
        {
        <div class="display-label">EmpID</div>
        <div class="display-field">@item.EmpID</div>
   
        <div class="display-label">EmpName</div>
        <div class="display-field">@item.EmpName</div>
   
        <div class="display-label">EmpDept</div>
        <div class="display-field">@item.EmpDept</div>
   
        <div class="display-label">Salary</div>
        <div class="display-field">@item.Salary</div>
   
        <div class="display-label">EmpLevel</div>
        <div class="display-field">@item.EmpLevel</div>

       
        }

    </fieldset>
    <p>
        @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
        @Html.ActionLink("Back to List", "Index")
    </p>
</body>
</html>

Now in the Employee Controller Index is the action method where I am display the above view.
The below code is in Employee Controller class.

// GET: /Employee/


// Static list to display multiple Employee records

 public static List<Employee> lstEmp = new List<Employee>();

        public ActionResult Index([Bind(Exclude = "EmpLevel")]Employee emp)
        {
            lstEmp.Add(emp);
            return View(lstEmp);
        }

The only new thing is Bind which applied on the class level. Like Exclude you also have include and prefix tag here. Here all the properties except designation/EmpLevel will be displayed. So I am hiding ‘EmpLevel’ property of Employee class model from controller.

Sort based on given order with no repeating code

static void Main(string[] args)
        {
           
            Console.WriteLine("Enter How many numbers you want for Sort:-");
            int arrLength = Convert.ToInt32(Console.ReadLine());

            int[] userInputs = new int[arrLength];
           

            Console.WriteLine("Enter List of  {0} Integer items to sort:" ,arrLength);
            for(int i=0;i<arrLength ; i ++)
            {
                userInputs[i] =Convert.ToInt32(Console.ReadLine());
            }
            Console.WriteLine("Enter whcih order you want to sort:");
            Console.WriteLine("\t Press '0' for Descending | \t '1' for Ascending:");
            int order = Convert.ToInt32(Console.ReadLine());
           
            userInputs = GetSortedData(userInputs, order);

            Console.WriteLine("The Sorted result is as below:");
            for (int num = 0; num < arrLength; num++)
            {
              Console.Write(" "+ userInputs[num]+" ");
            }
            Console.ReadLine();

        }



        /// <summary>
        /// This method sorts your input array on your specified order.
        /// </summary>
        /// <param name="inputArray"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public static int[] GetSortedData(int[] inputArray, int order)
        {
            for (int i = 0; i < inputArray.Length - 1; i++)
            {
                for (int j = 0; j < inputArray.Length - 1; j++)
                {
                    if (order == 0? inputArray[j] < inputArray[j + 1] : inputArray[j] > inputArray[j + 1])
                    {
                        int temp = inputArray[j];
                        inputArray[j] = inputArray[j + 1];
                        inputArray[j + 1] = temp;
                    }               
                }           
            }
            return inputArray;
        }

How to change Master page file dynamically

Use Page_PreInit method and use the default property MasterPageFile and set to the specific file like below.

protected void Page_PreInit(object sender, EventArgs e)
{
       MasterPageFile =
"simple2.master";
}

Encrypt and Decrypt any section of config file


On the below code I am encryting and decrypting the ConnectionString section of Web.Config
Here "DataProtectionConfigurationProvider" is just a type of protection level.

Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");


ConfigurationSection section = objConfig.GetSection("connectionStrings");
            if (!section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                objConfig.Save();

            }

            if (section.SectionInformation.IsProtected)
            {

                section.SectionInformation.UnprotectSection();
                objConfig.Save();

           
            }

How to change any property of Config File in Code



Here I have kept a connection string in web.config file and the below code will help you out to modify the connection string property. Like this you can modify other section in your Web.config file.Paste the below code on the required method.


string constr = ConfigurationManager.ConnectionStrings[0].ConnectionString;

            Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
            ConnectionStringsSection conSetSection = (ConnectionStringsSection)objConfig.GetSection("connectionStrings");
            if (conSetSection != null)
            {
                conSetSection.ConnectionStrings[0].ConnectionString = "Not found";
                objConfig.Save();
           
            }


So Finally connection string property will change as "Not Found" where as it was earlier "Data Source=(Local);Initial Catalog=xyz; integrated security=true;"