-->

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

How to Create Partition Function for Particular Column: SQL

A partition function specifies how a table should be partitioned. It specifies the range of values on a particular column. Based on which the table is partitioned. For example, in the scenario of Adventure Works, you can partition the data based on years. The following statement creates a partition function for the same:

CREATE PARTITION FUNCTION RateChangDate, (datetime)
AS RANGE RIGHT FOR VALUES (‘1996-01-01’, ‘2000-01-01’, ‘2004-01-01’, ‘2008-01-01’)

The preceding query creates a partition function named RateChangDate. It specifies that the data pertaining to the change in the payment rate will be partitioned based on the year.

Creating a Partition Scheme

After setting the partition function, you need to create the partition scheme. A partition scheme associates a partition function with various filegroups resulting in the physical layout of the data. Therefore, before creating a partition scheme, you need to create filegroups.

To create partition filegroups, you need to perform the following steps:

  • Expand the Database folder in the Object Explorer windows and right-click the AdventureWorks database.
  • Select the Properties option from the short-cut menu to display the Database Properties – AdventureWorks window.
  • Select the Filegroups folder from Select a page pane to display the list of all the filegroups in AdventureWorks.
  • Click the Add button to add a filegroup. Specify the name of the filegroup in the Name text box as Old.
  • Report Step 4 to add four more filegroups named First, Second, Third, and Fourth, as shown in the following figure.

    How to Create Partition Function for Particular Column: SQL
  • Select the Files folder from Select a page pane to display the list of all the files.
  • Click the Add button and type the name of the file as OldFile in the Logical Name text box, and select Old from the Filegroup drop-down list.
  • Report Step 7 to create four files names File1, File2, File3, File4, select filegroup as First, Second, Third, Fourth for the files.
  • Click OK button to close the Database Properties – AdventoreWorks window.

Execute the following statements in the Microsoft SQL Server Management
CREATE PARTITION SCHEME RateChangDate
AS PARTITION RateChangDate
TO (Old, First, Second, Third, Fourth)


Create partitioned table in sql

How to Create Partitioned Table in SQL Server

When the volume of data in a table increases and it takes time to query the data, you can partition the tables and store different parts of the tables in multiple physical locations based on a range of values for a specific column. This helps in managing the data and improving the query performance.

Consider the example of a manufacturing organization. The details of inventory movements are stored in the InventoryIssue table. The table contains a large volume of data and the queries take a lot of time to execute thereby slowing the report generation process.

To improve the query performance, you can partition the table to divide the data based on a condition and store different parts of the data in different locations. The condition can be based on the date of transaction and you can save the data pertaining to five years at a location. After partitioning the table, data can be retrieved directly from a particular partition by mentioning the partition number in the query.

In the preceding example, the partitioned table were created after the database had already been designed. You can also create partitioned tables while designing the database and creating tables. You can plan to create a partitioned table when you know that the data to be stored in the table will be large. For example, if you are creating a database for a banking application and you know that the transaction details will be voluminous, you can create the transaction table s with partitions.

Partitioning a table is only allowed in Enterprise Edition of SQL Server. To create a partitioned table, perform the following tasks:

  • Create a partition function.
  • Create a partition scheme.
  • Create a table by using the partition scheme.

For example, the AdventureWorks database stores the data of all the employees for the last 11 years. This data includes the personal details of the employees and their payment rates. Whenever there is a change in the payment rate of an employee, it is recorded in a separate record. However, this result in generation of large volume of data. This adversely affects the query performance.

To improve the query performance, the database developer needs to partition the table storing the changes in wage rate.

Create Rule and User-defined DataType

How to use LINQ Generation operators in ASP.NET

Introduction

The Generation operators help in creating a new sequence of values. The Generation operators are DefaultlfEmpty, Empty, Range, and Repeat. The DefaultlfEmpty clause replaces an empty collection with a default single collection. The Empty clause refers to an empty collection. The Range clause generates a collection that contains a sequence of numbers. The Repeat clause generates a collection that contains at least one repeated value.
The syntax of Range clause is:
For C#
public static IEnumerable<int> Range( int start, int count);
The Range clause throws an ArgumentOutOfRangeException exception if the count is less than 0, or if the start + or count -1 parameters are larger than the maximum value.
The syntax of the Empty clause is:
For C#
public static IEnumerable<T> Empty<T>();
The Empty clause caches a single empty sequence of the given type.

Lets take an simple example

<form id="form1" runat="server">
    <div>
    
        <asp:ListBox ID="ListBox1" runat="server" Height="254px" Width="153px">
        </asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="odd and even " />
    
    </div>
    </form>
Code Behind 
protected void Button1_Click(object sender, EventArgs e)
    {
        var num = from n in Enumerable.Range(1, 20)
                  select new { Number = n, oddevennumber = n % 2 == 1 ? "odd" : "even" };
        foreach (var item in num)
        {
            ListBox1.Items.Add("The number is " + item.Number + item.oddevennumber);
            
        }
    }
Code Generate the following output
How to use LINQ Generation operators in ASP.NET

How to Create Rule and User Defined Data Type in SQL

A rule enforces domain integrity for columns or user-defined data types. The rules is applied to the column of the user-defined data type before an INSERT or UPDATE statement is issued. In other words, a rule specifies a restriction on the values of a column or a user-defined data type. Rules are used to implement business-related restrictions or limitations. A rule can be created by using the CREATE RULE statement.

The syntax of the CREATE RULE statement is:
CREATE RULE rule_name AS conditional_expression
Where,

  • Rule_name specifies the name of the new rule that must conform to rules for identifiers.
  • Conditional_expression specifies the condition(s) that defines the rule. It can be any expression that is valid in a WHERE clause and can include elements, such as arithmetic operators, relational operators, IN, LIKE, and BETWEEN.

The variable specified in the conditional expression must be prefixed with the @ symbol. The expression refers to the value that is being specified with the INSERT or UPDATE statement.

In the preceding example of the EmployeeLeave table, you applied a rule to accept only three values: ‘CL’, ‘SL’, and ‘PL’. You can perform the same task by creating a rule. You can use the following statement to create the rule:
CREATE RULE rulType
AS @LeaveType IN (‘CL’, ‘SL’, ‘PL’)

After you create the rule, you need to activate the rule by using a stored procedure, sp_bindrule.

The syntax of sp_bindrule is:
Sp_bindrule <’rule’>, <’object_name’>, [<’futureonly_flag’>]
Where,

  • Rule specifies the name of the rule that you want to bind.
  • Object_name specifies the object on which you want to bind the rule.
  • Futureonly_flag applies only when you want to bind the rule to a user-defined data type.

Using a user defined data type

User-defined data types are custom data types defined by the users with a custom name. User-defined data types allow modifying the composite data type used in the database. The user-defined data types are based on the system data types and can be used to predefine several attributes of a column, such as its data type, length, and whether it supports NULL values.

You can create user-defined data types by using the CREATE TYPE statement. The syntax of the CREATE TYPE statement is:
CREATE TYPE [schema_name. ] type_name {FROM base_type [ ( precision [, scale ] ) ] [ NULL | NOT NULL ] } [;]
Where,

  • Schema_name specifies the name of the schema to which the alias data type or the user-defined data type belongs.
  • Type_name specifies the name of the alias data type or the user-defined data type.
  • Base_type specifies the SQL Server supplied data type on which the alias data type is based.
  • Precision specifies the decimal or numeric point. Decimal and numeric are non-negative integers that indicate the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point.
  • Scale specifies the decimal or numeric scale.
  • NULL | NOT NULL specifies whether the data type can hold a null value. If not specified, NULL is the default value.

The following SQL query creates a user-defined data type for descriptive columns:
CREATE TYPE DSCRP
FROM varchar (100) NOT NULL;

In the preceding example, a user-defined data type DSCRP is created to store the varchar data type and the size limit is specified as 100. Further, it also specifies NOT NULL. Therefore, you can use this data for the columns that hold description, address, and reason.

For example, you can use the DSCRP data type to store the data of the LeaveReason column of the EmployeeLeave table, as shown in the following statement:

CREATE TABLE HumanResources.EmployeeLeave
(
EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES
HumanResources.Employee (EmployeeID),
LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY (EmployeeID, LeaveStartDate),
LeaveEndDate datetime NOT NULL,
LeaveReason DSCRP,
LeaveType char(2) CONSTRAINT chkLeave CHECK (LeaveType IN (‘CL’, ‘SL’, ‘PL’)) CONSTRAINT chkDefLeave DEFAULT ‘PL’)

Solve Decision-Making Expression using Logical Operators in JAVA

Relational operators often are used with logical operators (also known as conditional operators sometimes) to construct more complex decision-making expression. The Java programming language supports six conditional operators-five binary and one unary-as shown in the following image.


The logical OR operator (||)

The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to Boolean true if either of its operands evaluate to true.

This principle is used while testing evaluating expressions. Following are some examples of logical OR operation:

  • (4= =4) || (5 = =8)    results into true because first expression is true.
  • 1 = = 0 || 0 > 1         results into false because neither expression is true (both are false).
  • 5 > 8 || 5 < 2            results into false because both expression are false.
  • 1 < 0 || 8 > 0            results into true because second expression is true.

The operator || (logical OR) has lower precedence than the relational operators, thus, we don’t need to use parenthesis in these expressions.

The logical AND operator (&&)

The logical AND operator, written as &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expression (its operands) are true. Following are some examples of AND operator (&&).

  • (6 == 3) && (4 == 4)           results into false because first expression is false.
  • (4 == 4) && (8 == 8)           results into true because both expressions are true.
  • 6 < 9 && 4 > 2                     results into true because both expressions are true.
  • 6 > 9 && 5 < 2                     results into true because both expressions are false.

Because logical AND operator (&&) has lower precedence than the relational operators, we don’t need to use parentheses in these expressions.

The logical NOT operator (!)

The logical NOT operator, written as "!", works on single expression or operand i.e. it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e. if the expression is true, then expression is false, and vice versa.

Following are some examples of logical NOT operation:

  • ! (5 ! = 0) results into false because 5 is non zero (i.e., true)
  • ! (5 >2) results into false because the expression 5>2 is true.
  • !(5>9)  results into true because the expression 5>9 is false.

The logical negation operator "!" has a higher precedence then any of the relational or arithmetic operators. Therefore, to negate an expression, you should enclose the expression in parentheses:

!( x > 5 ) will reverse the result of the expression x > 5
    Whereas! x > 5 is equivalent to ( ! x ) > 5

i.e., it will first reverse the truth value of x and then test whether the reverse of x’s truth value is greater than 5 or not.

Relational Operators in JAVA

Compare Values using Relational Operators in JAVA

In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands.

Java provides six relational operator for comparing numbers and characters. But they don’t work with strings. If the comparison is true, the relational expression results into the Boolean value true and to Boolean value false, if the comparison is false. The six relational operators are:

  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to) and
  • != (not equal to)

Summarizes the action of these relational operators.

Compare Values using Relational Operators in JAVA

t represents true and f represents false.
The relational operators have a lower precedence than the arithmetic operators. That means the expression
a + 5 > c – 2  ...expression 1
Corresponds to
( a + 5 ) > ( c – 2 ) ...expression 2
And not the following
a + ( 5 > c ) -2  …expression 3

Though relational operators are easy to work with, yet while working with them, sometimes you get unexpected results and behavior from your program. To avoid so, we would like you to know certain tips regarding relational operators.
Do not confuse the = and the = = operators.
A very common mistake is to use the assignment operators (=) in place of the relational operator (==). Do not confuse the testing the operator (==) with the assignment operator (=). For instance, the expression
Value = 3
Tests whether value is equal to 3? The expression has the Boolean value true if the comparison is true and Boolean false if it is false.

But the expression
Value = 3
Assigns 3 to value. The whole expression, in the case, has the value 3 because that’s the value of the left-hand side.
Avoid equality comparisons on floating-point numbers.
Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 X 5 is exactly 15, but 3.25 X 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 X 5.25 is 17.0625.

Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.
The relational operators group Left-to-right i. e., a <b<c means (a <b) < c and not a < ( b < c ).

Postfix version of operators 

How to use LINQ Conversion operators in ASP.NET

Introduction

Conversion operators convert a collection to an array. A Conversion operator changes the type of input objects. The different Conversion operators are ToSequence, ToArray, ToList, ToDictionary, ToLookup, OfType, and Cast.
The ToSequence clause simply returns the source argument by changing it to IEnumerable<T>. The ToArray clause enumerates the source sequence and returns an array containing the elements of the sequence. The ToList clause enumerates the source sequence and returns a List<T> containing the elements of the sequence. The ToDictionary clause lists the source sequence and evaluates the keySelector and elementSelector functions for each element to produce the element key and value of the source sequence. The ToLookup clause implements one-to-many dictionary that maps the key to the sequence of values. The OfType clause allocates and returns an enumerable object that captures the source argument. The Cast clause also allocates and returns an enumerable object that captures the source argument.
The syntax of the ToList clause is:


For C#
public static List<T> ToList<T>( this IEnumerable<T> source);

Lets take an simple example

<form id="form1" runat="server">
    <div>
 
        <asp:ListBox ID="ListBox1" runat="server" Height="143px" Width="143px">
        </asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="String type" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="Integer Type" />
 
    </div>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        var strtype = list.OfType<string>();
        ListBox1.Items.Add("String type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item);
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        ListBox1.Items.Clear();
        var strtype = list.OfType<int>();
        ListBox1.Items.Add("integer type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item.ToString ());
        }

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

How to use LINQ Conversion operators in ASP.NET

Saturday, April 26, 2014

How to use LINQ Set Operators in ASP.NET

Introduction

The Set operators in LINQ refer to the query operations that produce a result set. The result is based on the presence or absence of the equivalent elements that are present within the same or separate collection. The Distinct, Union, Intersect, and Except clauses are classified as the Set operators. The Distinct clause removes duplicate values from a collection.
The syntax of the Distinct clause is:
For C#
public static IEnumerable<T> Distinct<T>( this IEnumerabIe<T> source);

The Union clause returns the union of two sets. The result elements are the unique elements that are common in the two sets.
The syntax of the Union clause is:
For C#
public static IEnumerabIe<T> Union<T>( this IEnumerabIe<T> source1, IEnumerabIe<T> source2);

The Intersect clause returns the set intersection. The elements appear in each of the two collections.
The syntax of the Intersect clause is:
For C#
public static IEnumerabIe<T> Intersect<T>( this IEnumerabIe<T> source1, IEnumerabIe<T> source2);
The Except clause returns the set difference. The result of the Except clause returns the elements of one collection that do not appear in the second collection.
The syntax of the Except clause is:
For C#
public static 1Enumerable<T> Except<T>( this 1Enumerable<T> sourcel, IEnumerab1e<T> source2);

lets take an simple example

Source Code
<form id="form1" runat="server">
    <div>
    
    </div>
    <asp:ListBox ID="ListBox1" runat="server" Height="137px" Width="221px">
    </asp:ListBox>
    <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="common word" />
    </form>
Code behind
protected void Button1_Click(object sender, EventArgs e)
    {
        string[] fruits = { "apple", "mango", "banana" };
        string[] wds = { "my world", "mango", "operation" };
        var common = fruits.Intersect(wds);
        ListBox1.Items.Add("common in both array");
        foreach (var item in common)
        {
            ListBox1.Items.Add(item);
        }
    }
Code Generate the following output
How to use LINQ Set Operators in ASP.NET

How to add hour, minute and seconds in existing time ASP.NET Example

Introduction

If you want to add hour, minute and seconds in existing time then you should take TimeSpan structure with overload function. Now, you can easily add TimeSpan structure with existing date time object using Add method. Lets take an simple example for demonstration.
Step-1 : Add new web form into the project
Step-2 : Add one button and label control on it.
Step-3 : Handle Button click event.

<form id="form1"
    runat="server">
    <asp:Button ID="Button1"
    runat="server"
    BackColor="#33CCFF"
    onclick="Button1_Click"
    Text="Click" />
    <div>  
    <asp:Label ID="Label1"
    runat="server"
    BackColor="Yellow"></asp:Label>  
    </div>
    </form>
Code Behind
 protected void Button1_Click(object sender, EventArgs e)
        {          
            DateTime now = DateTime.Now;    
            TimeSpan TR = new TimeSpan(3, 41, 11);
            DateTime afterAddedSpanTime = now.Add(TR);
            Label1.Text = "current time : " + now.ToLongTimeString();
            Label1.Text += "<br /><br />";
            Label1.Text += "after added a spantime with current time <br />";
            Label1.Text += "time span: 3 hours|41 minutes|11 seconds <br />";
            Label1.Text += afterAddedSpanTime.ToLongTimeString();

        }
Code Generate the following output
How to add hour, minute and seconds in existing time ASP.NET Example

How to show AM and PM with time in ASP.NET

Introduction

You can show System time as well as universal time through DateTime class. Now, this time you want to show only am and pm text after the current time. You can use "tt" in the ToString ( ) method. Lets create an simple algorithm.
Step-1 : Take a web form into the project
Step-2 : Add two control (button and label control) onto the form window.
Step-3 : Raise button click event
Step-4 : Take single instance of DateTime class also pass "tt" parameter in ToString ( ) method.
Step-5 : Now Run your application from green triangle button or Ctrl+f5

Complete Source Code

<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 now = DateTime.Now;          
            Label1.Text = "current time PM AM: " + now.ToLongTimeString();
            Label1.Text += "<br /><br />";          
            Label1.Text += "current time [PM AM]: " + now.ToString("tt");

        }
Code generate the following output
How to show AM and PM with time in ASP.NET

How to find first day of next month in ASP.NET

If you want to get first day of next 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 2 in day field. Now, you can delete 1 day from current DateTime object using AddDays (-1) method.

Source Code 

 <form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        BackColor="#66CCFF"
        onclick="Button1_Click"
        Text="Click" />  
    </div>
       <asp:Label ID="Label1"
       runat="server"
       BackColor="Yellow"
       Text="Label"></asp:Label>
    </form>

Code Behind

 protected void Button1_Click(object sender, EventArgs e)
        {            
            DateTime today = DateTime.Today;            
            DateTime tempDate = today.AddMonths(1);
            DateTime tempDate2 = new DateTime(tempDate.Year, tempDate.Month, 2);
            DateTime nextmonthfirstday = tempDate2.AddDays(-1);
            Label1.Text = "Today : " + today.ToLongDateString();
            Label1.Text += "<br /><br />next month first day = ";
            Label1.Text += nextmonthfirstday.ToLongDateString();

        }

Code Generate the following output

How to find first day of next month in ASP.NET

Tuesday, April 22, 2014

How to Create DropDownList in Asp.Net MVC

Drop down list is a common and usable control in every programming area to let the user can select only one item from the list. In MVC we have to create a list in action method of controller and then pass it through any method like ViewBag and ViewModel etc.

Programmer can create required type of list as per the requirements, we will create a SelectListItem type of list because this list provides two property Text and Value by default. Create a simple list of type SelectListItem and add some items (we have added four item here) as added below:

List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Value 1", Value = "1" });
items.Add(new SelectListItem { Text = "Value 2", Value = "2" });
items.Add(new SelectListItem { Text = "Value 3", Value = "3" });
items.Add(new SelectListItem { Text = "Other", Value = "4" });

Now to pass this to View page write a single line as written below:

ViewBag.ddlItems = new SelectList(items, "Value", "Text");

Value will be the dataValue field and Text will be dataText field for this dropdownlist. In the view page create a form and of course a dropdownlist with a submit button:

@using (Html.BeginForm())
{
    <div>
        @Html.DropDownList("selectedItem", (IEnumerable<SelectListItem>)ViewBag.ddlItems)
        <input type="submit" value="Submit" id="submitBtn" />
    </div>
}

First parameters of this helper Html.DropDownList() specifies name of the HTML select element, and also the name of the view model property that is bound to the element. Second parameter shows the list of options of select list.

This will create a dropdownlist with a submit button. Run the application and open particular view in the browser. Select any value and then submit. Oops! i haven't write the code to access the selected value. So write HttpPost type of action:

public ActionResult Index(string selectedItem)
{
....
....

Here parameter selectedItem is the same name of dropdownlist we have assigned in the view page. Again run the application, select any value("Value 2") and then submit. This parameter will contain the selected value(2).

How to add Hours in existing time in ASP.NET

Introduction

Using AddHours method  you can add Hours in integer, Object will be updated with new date and time. This method is used where you want to calculate time after some time. Like Library management project. Lets take an simple example

<form id="form1" runat="server">
    <div>  
        <asp:Button ID="Button1"
        runat="server"
        BackColor="#66FFFF"
        onclick="Button1_Click"
        Text="Click" />  
    </div>
        <asp:Label ID="Label1"
        runat="server"
        BackColor="Yellow"></asp:Label>
    </form>
Code Behind
 protected void Button1_Click(object sender, EventArgs e)
        {
            DateTime now = DateTime.Now;          
            DateTime after3Hours = now.AddHours(3);            
            DateTime after4Hours = now.AddHours(4);
            Label1.Text = "present time = " + now.ToLongTimeString();
            Label1.Text += "<br /><br />";
            Label1.Text += "after added three hours with present time <br />";
            Label1.Text += after3Hours.ToLongTimeString();
            Label1.Text += "<br /><br />";
            Label1.Text += "after added four hours with present time <br />";
            Label1.Text += after4Hours.ToLongTimeString();

        }
 Code Generate the following Output
How to add Hours in existing time in ASP.NET

Monday, April 21, 2014

Add seconds in existing time ASP.NET example

Introduction

Using AddSeconds method  you can add seconds in integer, Object will be updated with new date and time. This method is used where you want to calculate time after some seconds. Like Library management project. Lets take an simple example

<form id="form1" runat="server">
    <asp:Button ID="Button1"
    runat="server"
    BackColor="#66CCFF"
    onclick="Button1_Click" Text="Click" />
    <div>  
    <asp:Label ID="Label1"
    runat="server"
    BackColor="Yellow"></asp:Label>  
    </div>
    </form>
Code Behind
 protected void Button1_Click(object sender, EventArgs e)
 
        {        
            DateTime now = DateTime.Now;          
            DateTime after56Seconds = now.AddSeconds(56);
            Label1.Text = "present time = " + now.ToLongTimeString();
            Label1.Text += "<br /><br />";
            Label1.Text += "after added 56 seconds with present time= ";
            Label1.Text += after56Seconds.ToLongTimeString();

        }
Code Generate the following output
Add seconds in existing time ASP.NET example

Sunday, April 20, 2014

Doctor Medicine Prescription Project in Windows Forms with C#

Download this project

Project cost : 300Rs or $10
Pay me at:
PayPal id : saini1987tarun@gmail.com

Via bank transfer

ICICI bank account number is :    153801503056
Account holder name is :                 Tarun kumar saini
IFSC code is :                                   ICIC0001538

SBBJ bank detail :                             61134658849
Account holder name:                        Tarun kumar saini
IFSC code :                                        SBBJ0010398

CONTACT ME

narenkumar851@gmail.com

Doctor Medicine Prescription system covers the functionality to store the symptoms of the patient’s disease date by date and also the medicines written by the doctor. It is windows form project which may be a setup file to be installed in client’s system.


Features of the project:


  • Only authorized person can login into the system and use the software.
  • User can add/modify patients, disease and medicines which will stored in the database.
  • Through this system, all the symptoms of particular disease and their medicines may be stored in the database according to date.
  • Small project to be installed in the windows platform.

System Requirements:


  • Visual studio 2010 or higher
  • SqlServer 2008 or higher
  • DotNet Framework 4.0 or higher(pre-loaded with visual studio)

Run the Project:

It is a windows form application, so either press F5 or click on Start button. It will load the login window, which requires username and password. Username is “admin” and password is “password”, click on login button and the manage options window will be shown to you.

Project’s Functions:

Manage List: here all the functions of project can be redirected through a single click.

1. Manage list doctor medicine project

Manage Patient: where user can add/modify all the details about a patient like name, father name, age, address, contact no and also registration date.

2. Manage patient in doctor medicine project

Manage Disease: user can add/modify details about diseases like their name and type.

Manage Symptoms: there are some symptoms of particular disease which should be first stored in the system. It also have related medicine details for each symptoms, which may be prescribed to the patient.

Manage Medicine: where user can add/modify all the details about medicines like their name, type, the salt contains and components including in the medicine.

Prescribe medicine: user can assign the medicines to particular patient according to their symptoms/disease. By a single click the system will store the medicines assigned to the patient.

3. prescribe form doctor medicine project

The coding part is so simple of this project so that other programmer can easily change the functionality as per the requirements.

How to Serve Files to User in Asp.Net MVC

Let the user download a file from server is not a typical task, programmer have to write some lines of code which will execute the task. Asp.Net MVC action with returning type FileResult will complete this task in few task listed in the article.

After uploading file/files on the server, how to deliver/serve a file for user to download and save on an individual system depends on the way of storing the file on the server by programmer. Programmer can provide a simple link to an action including some lines of code to perform the task.

In the controller write below line of c# code in the action named “DownloadFile” which will access the file saved on the root of this project and then prompt user to Open/Save that file.

public FileResult DownloadFile()
{
var file = Server.MapPath("~/download file.txt");
return File(file, "Text", "download file");
}

These two line of code will sufficient to prompt the user, now in view page create an actionline which will redirect the user to this action. The second line of code will creates a System.Web.Mvc.FilePathResult object by using the file name, the content type, and the file download name.

@Html.ActionLink("Download File", "DownloadFile");

Run the project and particular controller/action then click on the link created above. This will show an opening download file window having two option to open or save that file, as shown in the below image:

How to Serve Files to User in Asp.Net MVC

Saturday, April 19, 2014

How to Validate File or File type in Java Script MVC

Programmer need to check whether the file is selected by the user or not, when uploading a file. If user will not upload any file and submit the form, the code will throw an exception with description like "file must not be null".

To overcome this issue programmer have to check the uploaded file before the form submission, and this can be performed by using Java script. Write the following code in our view where the file upload control is placed:

function validateForm() {
if ($("#file").val() == "") {
alert("Please select a file");
return false;
}
}

Here “#file” is the id of file upload control and we are checking the value of this control. If the value is empty then it will alert with the message shown and return back to the form. If this control will have file then it will submit the form. On the submit button, just call this function to execute this code with Onclick=”validateForm();”.

Now to select only some file types write another function as below:

function checkfile(sender) {
        var validExts = new Array(".jpeg", ".jpg", ".png");
        var fileExt = sender.value;
        fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
        if (validExts.indexOf(fileExt) < 0) {
            alert("File must of types \".jpeg\", \".jpg\", \".png\");
            $("#file").val('');
            return false;
        }
        else return true;
    }

This function will be called on OnChange event of the file upload control. It will show an alert message written above if the type of selected file will not be in the list declared in the function. Write CheckFile(this) in onChange event of the file upload control.

In this function we are checking only the extension of the selected file, extension may be found by any individual logic. Earlier article was about to uploading file, this java script will not submit the form if user will not select any file through the file upload control.
© Copyright 2013 Computer Programming | All Right Reserved