-->

Thursday, May 1, 2014

How to find last day of month in ASP.NET C#

Introduction

If you want to get last day of this month , use DateTime structure with AddMonths( ) method. using this method you can get first day of next month. Now, create a new instance of DateTime structure with some parameter like DateTime(Int32, Int32, Int32). This parameterized method Initializes a new instance of the DateTime structure to the specified year, month, and day. Here you can pass integer 1 in day field. Now, you can delete 1 day from current DateTime object using AddDays (-1) method. Now, your object will return last day of current month.

<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
         runat="server"
         onclick="Button1_Click"
         Text="Click"
         BackColor="#99CCFF" />  
    </div>
        <asp:Label ID="Label1"
         runat="server"
         Text="Label"
         BackColor="Yellow"></asp:Label>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
        {        
            DateTime today = DateTime.Today;          
            DateTime tempDate = today.AddMonths(1);
            DateTime tempDate3 = new DateTime(tempDate.Year, tempDate.Month, 1);
            DateTime Monthlastday = tempDate3.AddDays(-1);
            Label1.Text = "Today : " + today.ToLongDateString();
            Label1.Text += "<br /><br />month last day= ";
            Label1.Text += Monthlastday.ToLongDateString();

        }

Code generate the following output


How to put an image into a Button in WPF

Introduction

Window Presentation Foundation support Rich Composition, in which you can use a control as a container. In this example i will show, how to put an image into a Button control. If you want to make highly visualize application, must use WPF, because of the strict separation of appearance and behavior you can easily change the look of a control. Now, lets take an simple example

Source Code (xaml file)


<Grid>
    <Button>
        <StackPanel Orientation="Horizontal" Width="155">
                <Image Source="home.jpg " Height="33" Width="66" Stretch="Uniform"/>
            <TextBlock Text=" Home" FontSize="20"/> 
            
 </StackPanel>
    </Button>
    </Grid>

Code Generate the following output

According to above mentioned source code, A Button control contains a stack panel so its work as a container. We already learn about stack panel in previous article. In client based application you can design more powerful application using WPF.

Sunday, April 27, 2014

How to use LINQ Aggregate operators in ASP.NET

Introduction

The Aggregate operators compute a single value from a collection. The different Aggregate operators are: Aggregate, Average, Count, LongCount, Max, Min, and Sum. The Aggregate clause calculates a sum value of the values in the collection. The Average clause calculates the average value of the collection of the values. The Count clause counts the elements in the collection. The LongCount clause counts the elements in a large collection. The Max clause determines the maximum value in a collection. The Min clause determines the minimum value of the collection. The Sum clause calculates the sum of values in the collection.
The syntax of the Count clause is:
For C#
public static int Count<T>( this IEnumerable<T> source, Function<T, bool> predicate);
The Count clause throws an ArgumentNullException exception, if any argument is null and an OverflowException exception is thrown if the count exceeds the maximum value.
The syntax of the Sum clause is:
For C#
public static Numeric Sum<T>( this IEnumerable<T> source, Function<T, Numeric> selector);

The Sum clause returns 0 for an empty sequence. The clause does not include null values in its result.
The Aggregate clause applies a function over a sequence.
The syntax of the Aggregate clause is:
For C#
public static T Aggregate<T>( this IEnumerable<T> source, Function<T, T, T> func);
The LongCount clause counts the number of elements in the given sequence.
The syntax of the LongCount clause is:
For C#
public static lonq LonqCount<T>( this IEnumerable<T> source);
The Min clause finds the minimum value of the given sequence.
The syntax of the Min clause is:
For C#
public static T Min<T>(this IEnumerable<T> source);
The Max clause returns the maximum value of the given sequence.
The syntax of the Max clause is:
For C#
public static T Max<T>(this IEnumerable<T> source);

The Average clause computes the average of the given sequence.
The syntax of the Average clause is:
For C#
public static Result Average(this IEnumerable<Numeric> source);

Lets take an simple example

<form id="form1" runat="server">
    <div>
    
        <asp:ListBox ID="ListBox1" runat="server" Height="176px" Width="267px">
        </asp:ListBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Agg. Operator Ex" Width="107px" />
    
    </div>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        int[] num = { 5, 4, 3, 2, 1, 7, 8, 9, 10, 34, 67 };
        double sum = num.Sum();
        ListBox1.Items.Add("The Sum of the Number is= " + sum);
        int minimum = num.Min();
        ListBox1.Items.Add("Minimum Number is= " + minimum);
        int oddnum = num.Count(n => n % 2 == 1);
        ListBox1.Items.Add("Count of the odd Number is= " + oddnum);

    }
Code Generate the following output
How to use LINQ Aggregate operators in ASP.NET

How to Create CheckboxList in Asp.Net MVC

CheckboxList is used to provide some options to be select by the user. In this article we will create a list of items and then pass it to view to create a checkbox list.

Create two classes with the following format

public class CollectionVM
{
    public List<ChoiceViewModel> ChoicesVM { get; set; }
    public List<Int64> SelectedChoices { get; set; }
}

public class ChoiceViewModel
{
    public Int64 SNo { get; set; }
    public string Text { get; set; }
}

In controller’s action method write following code in which we will create a new list having some items created below. When we return this ViewModel in the view, we first set the SelectedChoices object to a new blank list of same type.

CollectionVM collectionVM = new CollectionVM();
List<ChoiceViewModel> choiceList = new List<ChoiceViewModel>();
choiceList.Add(new ChoiceViewModel() { SNo = 1, Text = "Objective Choice 1" });
choiceList.Add(new ChoiceViewModel() { SNo = 2, Text = "Objective Choice 2" });
choiceList.Add(new ChoiceViewModel() { SNo = 3, Text = "Objective Choice 3" });
choiceList.Add(new ChoiceViewModel() { SNo = 4, Text = "Objective Choice 4" });

collectionVM.ChoicesVM = choiceList;
collectionVM.SelectedChoices = new List<long>();
return View(collectionVM);

In View page start a loop to create individual checkbox and label for each item added above.

@using (Html.BeginForm())
{
    <div>
        <ul>
            @foreach (var choice in Model.ChoicesVM)
            {
                <li>
                    <input 
                                id="choice@(choice.SNo)"
                                type="checkbox" 
                                name="SelectedChoices"
                                value="@choice.SNo"
                                @(Model.SelectedChoices.Contains(choice.SNo) ? "checked" : "")/>
                    <label for="operator@(choice.SNo)">@choice.Text</label>
                </li>
            
            }
        </ul>
        <input type="submit" value="Submit" name="submitBtn" id="submitBtn" />
    </div>
}

Check out above very simple code through which we will set all the checked item's sNo in the object SelectedChoices we have sent by viewmodel. And in the second line, particular label have been designed for each checkbox.

How to Create CheckboxList in Asp.Net MVC

Now what happen when we submit this form. Write the HttpPost method of same action having this Viewmodel as parameter like:

[HttpPost]
        public ActionResult Index(CollectionVM collectionVM)
        {

This collectionVM object have all the SNo's of checked items by user. So we have created a checkbox list and then access all the checked items in our controller's action.

How to Use Multiple Models in View using ViewModel: Asp.Net MVC

Asp.Net MVC uses such type of classes in which each field may contains specific validation rules using data annotations, to let the user interact with those only. These fields may contains some extra fields to be used as a temporary purpose.

Create two classes in the Models folder named Student and Employee as written below:

public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
public class Employee
{
public int EmpId { get; set; }
public string EmpName { get; set; }
}

Create a folder in our solution named ViewModels and add a class named Student_EmployeeViewModel which will have the following code.

public class Student_EmployeeViewModel
{
public List<Student> Students { get; set; }
public List<Employee> Employees { get; set; }
}

Come to our Controller (Home controller) and add an Action (Student_Employee) which will be type of HttpGet. This action will have some lines of code as below which contains two list of student and employee and then assign them to the newly created object of Student_EmployeeViewModel.

public ActionResult Student_Employee()
{
List<Student> studentList = new List<Student>();
studentList.Add(new Student() { Name = "Student 1", Age = 24 });
studentList.Add(new Student() { Name = "Student 2", Age = 25 });
studentList.Add(new Student() { Name = "Student 3", Age = 23 });

List<Employee> empList = new List<Employee>();
empList.Add(new Employee() { EmpName = "Employee 1", EmpId = 101 });
empList.Add(new Employee() { EmpName = "Employee 2", EmpId = 102 });
empList.Add(new Employee() { EmpName = "Employee 3", EmpId = 103 });

Student_EmployeeViewModel vm = new Student_EmployeeViewModel();
vm.Students = studentList;
vm.Employees = empList;
return View(vm);
}

Create an empty view by right clicking on this action and then Add View dialog box as discussed earlier. Write the following code in this view which will have two list as defined in our ViewModel.

@model MvcApplication1.Models.Student_EmployeeViewModel

@{
    ViewBag.Title = "Student_Employee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Students List</h2>

@foreach (var item in Model.Students)
{
    <option>@item.Name &nbsp;&nbsp; @item.Age</option>
}

<h2>Employees List</h2>

@foreach (var item in Model.Employees)
{
    <option>@item.EmpName &nbsp;&nbsp; @item.EmpId</option>
}

In the above code, we run two loops for each list of student and employee and display their name and age/id on the page.

Run this project and write the address of this action in the address bar, this will shows all the data of student as well as employees we have added in the action.

How to Use Multiple Models in View using ViewModel: Asp.Net MVC

How to Rename and Dropping a Table in SQL

You can rename a table whenever required. The sp_rename stored procedure is used to remaname table. Sp_rename can be used to rename any database object, such as a table,view, stored procedure, or function. The syntax of the sp_rename stored procedure is:
Sp_rename old_name, new_name
Where,

  • Oldname is the current name of the object.
  • Newname is the new name of the object.

The following SQL query renames the EmployeeLeave table:
Sp_rename [HumanResources.EmployeeLeave] ,
[HumanResources.EmployeeVacation]

You can also rename a table by right-clicking the Table folder under the Database folder in the Object Employer window and selecting the rename option from the shortcut menu. After a table is created, you may need to see the details of the table. Details of the table include the column names and the constraints. For this purpose, you can use the sp_help command.

Dropping a Table

At times, when a table is not required, you need to delete a table. A table can be deleted along with all the associated database objects, such as its index, triggers, constraints, and permissions. You can delete a table by using the DROP TABLE statement. The syntax of
DROP TABLE [ database_name . [ schema_name ]. ] table_name
Where,

  • Database_name specifies the name of the database where th table is created.
  • Schema_name specifies the name of the schema to which the table belongs.
  • Table_name specifies the name of the table that needs to be dropped.

When a table is deleted, any other database object referenced by the table needs to be deleted explicitly. This should be done before deleting the table. This is because while deleting a table, if violations occur in the rule of referential integrity then an error occurs that restricts you from deleting the table. Therefore, if your table is referenced then you must delete the referenced table or the referenced constraint and then delete the table.

For example in the HumanResources schema, the Employee table contains EmployeeID as its primary key. The EmployeeLeave table under the same schema contains EmployeeID as its foreign key and is referenced with the EmployeeID column of the Employee table. Therefore, when you want to delete the Employee table, you first need to delete the EmployeeLeave table.

You can also delete a table by right-clicking the Tables folder under the Database folder in the Object Explorer window and selecting the Delete option from the shortcut menu.

Create table using partition scheme

Creating a Table by Using the Partition Scheme

After you create a partition function and a partition scheme, you need to create a table that will store the partition records. You can use the following statements for the same:
Create Table EmpPayHistPart
(
EmployeeID int,
RateChangeDate datetime,
Rate money,
PayFrequency tinyint,
ModifiedDate datetime
) ON RateChangDate (RateChangeDate)

In the preceding statement, the RateChangDate refers to the partition scheme that is applied to the RateChangeDate column. The records entered in the EmpPayHistPart table will be stored based on the condition specified in the partition function.

Modifying a Table

You need to modify tables when there is a requirement to add a new column, alter the data type of a column, or add or remove constraints on the existing columns. For example, Adventure Works stores the leave details of all the employees in the EmployeeLeave table. According to the requirements, you need to add another column named ApprovedBy in the table to store the name of the supervisor who approved the leave of the employee. To implement this change, you can use the ALTER TABLE statement.

The syntax of the ALTER TABLE statement is:
ALTER TABLE [database_name . [ schema_name ] .] table_name
(
ALTER COLUMN column_name
{
[NULL | NOT NULL ]
}
  |WITH {CHECK | NOCHECK }] ADD COLUMN <column_difinition>
{
ADD CONSTRAINT constraint_name constraint_type
Where,

  • Database_name specifies the name of the database in which the table is created. Schema_name specifies the name of the schema to which the table belongs.
  • Table_name is the name of the table that is to be altered. If the table is not in the current database, then the user needs to specify the database name and the schema name explicitly.
  • ALTER COLUMN specifies the name of the altered column.
  • ADD COLUMN spevifies the name of the column to be added,
  • Column_definition specifies the new column definition.
  • WITH CHECK|WITH NOCHECK specifies whether the existing data is to be checked for a newly added constraint or a re-enabled constraint.
  • Constraint_name specifies the name of the constraint to be created and must follow the rules for the identifier.
  • Constraint_type specifies the type of constraint.

The following SQL query adds a column called ApprovedBy to the EmployeeLeave table:
ALTER TABLE HumanResources.EmployeeLeave
ADD ApprovedBy VARCHAR(30) NOT NULL

In the preceding example, the ApprovedBy column is added that can store string values.
When modifying a table, you can drop a constraint when it is not required. You can perform the task by altering the table by using the ALTER TABLE statement. The syntax to drop a constraint is:
ALTER TABLE [database_name . [ schema_name ] . [ schema_name . ] table_name DROP CONSTRAINT constraint_name
Where,

  • Database_name specifies the name of the database in which the table is created.
  • Schema_name specifies the name of the schema to which the table belongs.
  • Table_name specifies the name of the table that contains the constraint to be dropped.
  • Constraint_name specifies the name of the constraint to be dropped.

The following statement drops the default constraint, chkDefLeave of the EmployeeLeave table:
ALTER TABLE HumanResources.EmployeeLeave DROP CONSTRAINT chkDefLeave
In the preceding statement, the chkDefLeave constraint is dropped from the EmployeeLeave table.

Partition function in sql
© Copyright 2013 Computer Programming | All Right Reserved