-->

Sunday, May 4, 2014

How to Implement Sorting and Searching Functionality in Asp.Net MVC

Asp.Net MVC offers a very simple way to implementing sorting and searching functionality of the listed data. This complete process will be discussed in this article.

Create a class Student having two columns i.e. Name and age (Here this Student class is from our Data Context), this class will be used to list the data on our View page. If programmer is collecting data from database as in this article then he/she only needs to write query to collect data, otherwise programmer have to create a list of students to be shown on view.
public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
    }

In our controller, create a new action that is passing a list of students to view as written below. This will get all the records of student saved in our database, convert them to list and then pass them to particular view.
public ActionResult SortSearch()
{
var students = dc.Student.ToList();
return View(students);
}

Replace this above code with the code written below, which will includes the sorting and searching functionality on the listed data.

public ActionResult SortSearch(string sortOrder, string searchText)
        {
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.AgeSortParm = sortOrder == "age" ? "age_desc" : "age";
            DataContext dc = new DataContext();

            var students = dc.Student.ToList();
            if (!String.IsNullOrEmpty(searchText))
                students = students.Where(a => a.Name.ToLower().Contains(searchText.ToLower())).ToList();
            switch (sortOrder)
            {
                case "name_desc": students = students.OrderByDescending(a => a.Name).ToList();
                    break;
                case "age": students = students.OrderBy(a => a.Age).ToList();
                    break;
                case "age_desc": students = students.OrderByDescending(a => a.Age).ToList();
                    break;
                default: students = students.OrderBy(a => a.Name).ToList();
                    break;
            }

            return View(students);
        }

In our view page start a loop that will show individual record as a row as shown. Include a textbox to input search text and replace the header code (<th></th>) with the code written here, means replace your view code with the code written here.

@using (Html.BeginForm())
{
    <div>
        Find by Name: @Html.TextBox("searchText")
        <input type="submit" value="Search" id="searchBtn"/>
    </div>
}
<table>
    <thead>
        <tr>
            <th>@Html.ActionLink("Name", "SortSearch", new { sortOrder = ViewBag.NameSortParm })</th>
            <th>@Html.ActionLink("Age", "SortSearch", new { sortOrder = ViewBag.AgeSortParm })</th>
        </tr>
    </thead>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Age</td>
        </tr>
    }
</table>

As you can see in the view code, the name of textbox and the parameter for search string in the action is same i.e. searchText, which will automatically get the value of text entered in the input textbox. The same may be noticed with table header’s viewbag parameter i.e. sortOrder.

Run this view and click on the Header’s, through which you want to sort this list. With a single click this list will sort (first ascending then descending order) as shown in the image.

How to Implement Sorting and Searching Functionality in Asp.Net MVC

Now write something in the search textbox (“h”) and click on Submit button, this will list only the data containing the entered text as shown:

How to Implement Sorting and Searching Functionality in Asp.Net MVC

Operator Precedence and Associativity to Evaluate Expression: JAVA

Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine the overall value of the expression. For example, take the following expression:
 Y  =  6  + 4/2

Depending on whether the 6+4 expression or the 4/2 expression is evaluated first, the value of y can end up being 5 or 8. Operator precedence determines the order in which expression are evaluated, so you can predict the outcome of an expression. In general, increment and decrement expression are evaluated before arithmetic expression; arithmetic expression are evaluated before comparisons, and comparisons are evaluated before logical expression. Assignment expression are evaluated are evaluated last.

Operator Precedence and Associativity to Evaluate Expression: JAVA


Above Table shows the specific precedence of the various operators in Java. Operators further up in the table are evaluated first; operator on the same line have the same precedence and are evaluated left to right based on how they appear in the expression itself. For example, given that same expression
Y = 6 + 4/2

You now known, according to this table, that division is evaluated before addition, so the value of y will be 8.

You always can change the order in which expressions are evaluated by using parentheses around the expressions you want to evaluate first. You can nest parentheses to make sure that expressions evaluate in the order you want them to (the innermost parenthetical expressions is evaluated first.

Consider the following expression:
y = (6 + 4)/2

This results in a value of5, because the 6+4 expression is evaluated first, and then the result of that expression (10) is divided by 2.

Parentheses also can be useful in cases where the precedence of an expressions isn’t immediately clear. In other words, they can make your code easier to read. Adding parentheses doesn’t hurt, so if they help you figure out how expressions are evaluated, go ahead and use them.

Operator Associativity

There is a linked term – Operator Associativity. Associativity rules determine the grouping of operands and operators in an expression with more than one operator of the same precedence. When the operations in an expression all have the same precedence rating, the associativity rules determine the order of the operators.

For most operators, the evaluation is done left to right, e.g.
X  = a + b – c

Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c is subtracted. Again, parentheses can be used to overrule the default associativity, e. g.
X = a + (b-c);

However, the assignment and unary operators, are associated right to left, e.g.,
X += y -= -4; equivalent to X  += (y  -= (-(4) ) );

Assignment and Remaining operators 

Other Remaining Operators used in JAVA Programming

All other remaining operators except assignment operators are listed in this article. Like instance of, shift operators, bitwise and many more described with example in the article.

The following table lists the other operators that the Java programming language supports.

Remaining operators used in java

In the following lines, we are discussing some of these operators. Discussion of all these operators may be large task here.

Conditional operator ?:

Java offers a shortcut conditional operator (?:) that store a value depending upon a condition. This operator is ternary operator i.e., it requires three operands. The general form of conditional operator ?: is as follows:
expressiona1 ? expression2 : expression3

If expression1 evaluates to true i.e., 1, then the value of the whole expression is the value of expression2, otherwise, the value of whole expression is the value of expression3. For instance
result = marks >= 50  ?  ‘P’ : ‘F’ ;

The identifier result will have value ‘P’ if the test expression marks >= 50 evaluates to true otherwise result eill have value ‘F’. Following are some more examples of conditional operator ? :

6 > 4 ? 9 : 7 evaluates to 9 because test expression 6 > 4 is true.
4 == 9 ? 10 : 25 evaluates to 25 because test expression 4 == 9 is false.

The conditional operator might be fascinating you but certainly one tip regarding ? :, we would like all of you to keep in mind and which is being told in form of following tip.
Beware that the conditional operator has a low precedence.The conditional operator has a lower precedence than most other operators that may produce unexpected results sometimes. Consider the following code:
n = 500;
bonus = n + sales > 15000 ? 250 : 50 ;

The above code is trying to add n and the value 250 or 50 depending upon whether sales > 15000 is true or false. But this code will not work in the desired manner. The above code will be interpreted as follows:
bonus = (n + sales) > 15000 ? 250 : 50;

Because operator ‘+’ has higher precedence over > and ?:
Therefore, for the desired behaviour the conditional expression should be enclosed in parentheses as shown below:
bonus = n + (sales > 15000 ? 250 : 50) ;

The [ ] Operator

The square brackets are used to declare arrays, to create arrays, and to access a particular element in an array. Similar data items, such as marks of 20 student or sales of 30 salesmen etc., are combined together in the form of arrays. Here’s an example of an array declaration
Float [ ] arrayofFloats = new float[10] ;

The previous code declares an array that can hold ten floating point numbers. Here’s how you would access the 7th item in that array :
arrayOfFlooats[6];

Please note that first element of array is referred to as array-named[0] i.e., to refer to first item of array namely arrayOfFloats, we shall write arrayOfFloats[0]. We are not going into further details of arrays right now.

The . Operator

The dot (.) operator accesses instance members of an object or class members of a class.

The ( ) Operator

When declaring or calling a method, the method’s arguments are listed between parenthesis ( and ). You can specify an empty argument list by using ( ) with nothing between them.

The ( type ) Operator

This operator casts ( or “ convent “ ) a value to the specified type. You’ll see the usage of this operator a title later in this chapter, under the topic Type Conversion.

The new Operator

You can use the new operator to create a new object or a new array. You’ll find examples highlighting the usage of new operator in a later section – Objects as instances of class – in this chapter.

The instance of Operator

The instanceof operator tests whether its first operand is an instance of second.
Op1  instanceof   op2

Op1 must be the name-of-an-object and op2 must be the name -of -a –class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.

Assignment and Shorthand Assignment Operators used in JAVA with Example

Java provides some assignment and shorthand operators listed in the article with example of each. The article also explains a table with all these assignment operators provided by JAVA Programming.

Like other programming languages, Java offers an assignment operator =, to assign one value to another e.g.
int x, y, z;
x = 9;
y = 7;
z = x + y;
z = z * 2;

Java shorthand Operators

Java offers special shorthand operators that simplify the coding of a certain type of assignment statement. For example,
a = a + 10; may be written as a += 10;

The operator pair += tells the compiler to assign to a value of a + 10. This shorthand works for all the binary operators in Java (those that require two operands). The general form of Java shorthand is
var = var operator expression same as var operator = expression

Following are some examples of Java shorthands:
X   -= 10; equivalent to x = x-10;
X*=3; equivalent to x=x*3;
X /=2; equivalent to x=x/2;
X%=z; equivalent to x=x%z;

Thus, we can say (=,*=, /=, %=, -=) are assignment operators in Java. The operators (*=, /=, %=, += and -=) are called arithmetic assignment operators. One important and useful thing about such arithmetic assignment operators of Java is that they combine an arithmetic operator and an assignment operator, and eliminate the repeated operand thereby facilitate a condensed approach.

The following table lists some shortcut assignment operators and their lengthy equivalents:

Shorthand assignment operators in java


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
© Copyright 2013 Computer Programming | All Right Reserved