Change RadWindow’s Title from Javascript or from Client-side


As per my scenario, I have RadGrid which contains Add and Edit button for Adding new record and Updated existing record respectively. On click of any of these button it will open a RadWindow which contains all my page controls. And I have a requirement to set the Title of RadWindow accordinly. I mean when user click Add button at that time RadWindow’s Title should be Add Mode and for Edit button click it should be Edit Mode.

And I found an easy way to set the Title of RadWindow from client-side, which I am going to share with you.

On Button, I have a ClientClick() event from where I am opening RadWindow, so now I am going to pass the Mode of the RadWindow in which it is going to be opened. Say for example,

OnClientClick=”openFileBuilderDialog(‘Add’);”

Here, openFileBuilderDialog is my Javascript Function, which is shown as below.

function openFileBuilderDialog(Mode) {

var wnd = $find(‘<%=RadWindow1.ClientID %>’);

if (Mode == “View”) {

wnd.set_title(“View File Information”);

}

elseif (Mode == “Edit”) {

wnd.set_title(“Edit File Information”);

}

elseif (Mode == “Add”) {

wnd.set_title(“Add File Information”);

}

wnd.show();

}

 In this function,

  1. Get the RadWindow using its ClientID.
  2. Find the current mode of the RadWindow, which I have supply on appropriate button’s onClientClick event.
  3. Then use the “set_title” method to set the Title that we want.
  4. And finally called, “show” method to open the RadWindow.

That’s it.

If the content page has its own title set in the @Page directive or in the <head> section, this title will override the RadWindow’s one.

To find more methods of RadWindow and examples please follow the below link,

http://www.telerik.com/help/aspnet-ajax/window-programming-radwindow-methods.html

Advertisements

Export to Excel or PDF in RadGrid


Introduction:

RadGrid has a built-in facility to export the grid’s data into different formats like Excel, CSV, Word or PDF and we can export the same as per the system requierement. Here I will show you how to export grid’s data in PDF or Excel format.

Code:

First of all in RadGrid, place the ExportSettings tag as below in the code. Here I have set properties like IgnorePaging equal to True to export all grids data and OpenInNewWindow equal to true to open the export data in a seperate window. Also in ExportSettings section I have defined the width of the PDF page.

<ExportSettingsIgnorePaging=”true”OpenInNewWindow=”true”>

<PdfPageWidth=”1500px”/>

</ExportSettings>

Now in RadAjaxManager of your page add the following event:

ClientEvents-OnRequestStart=”requestStart”

Then, add the following javascript function in your aspx page:

function requestStart(sender, args) {

if (args.get_eventTarget().indexOf(“btnExportToPDF”) > 0 ||

args.get_eventTarget().indexOf(“btnExportToExcel”) > 0)

args.set_enableAjax(false);

}

And then add the command name for the button as like following for PDF or Excel.

CommandName=”ExportToPdf”

and it’s done.

GROUPING in RadGrid


Introduction:

RadGrid supports grouping of items based on the value of a particular column. You can even have multilevel grouping based on different criteria.

To group the data in a grid, specify grouping criteria by setting the GroupByExpressions property of a table view in the grid

Code:

<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server” ShowGroupFooter=”true”>

<GroupByExpressions>

<telerik:GridGroupByExpression>

<SelectFields>

<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />

</SelectFields>

<GroupByFields>

<telerik:GridGroupByField FieldAlias=”Security” FieldName=”SEC_CODE” SortOrder=”Ascending” />

</GroupByFields>

</telerik:GridGroupByExpression>

</GroupByExpressions>

</MasterTableView>

Change RadGrid PageSize Dropdown


Introduction:

Telerik’s RadGrid provides in-built functionality for paging. User have to select the number of records from the Page Size combo box (default is 10, 20 and 50) and selected number of records is going to display in RadGrid. But we can also change the Page Size in combo box as per our requirement. Following is the code to do the same:

Code:

protectedvoid grdViewReport_ItemDataBound(object sender, GridItemEventArgs e)

{

if (e.Item isGridPagerItem)

{

RadComboBox PageSizeCombo = (RadComboBox)e.Item.FindControl(“PageSizeComboBox”);

PageSizeCombo.Items.Clear();

PageSizeCombo.Items.Add(newRadComboBoxItem(“100”));

PageSizeCombo.FindItemByText(“100”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.Items.Add(newRadComboBoxItem(“200”));

PageSizeCombo.FindItemByText(“200”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.Items.Add(newRadComboBoxItem(“500”));

PageSizeCombo.FindItemByText(“500”).Attributes.Add(“ownerTableViewId”, grdViewReport.MasterTableView.ClientID);

PageSizeCombo.FindItemByText(e.Item.OwnerTableView.PageSize.ToString()).Selected = true;

}

}

Extension methods in c#


Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T> types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable<T> appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type “dot” after an instance of an IEnumerable<T> type such as List<T> or Array.

The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this is not a requirement for extension methods. For more information, see Lambda Expressions (C# Programming Guide).

class ExtensionMethods2    
{
    static void Main()
    {            
        int[] ints = { 10, 45, 15, 39, 21, 26 };
        var result = ints.OrderBy(g => g);
        foreach (var i in result)
        {
            System.Console.Write(i + " ");
        }           
    }        
}
//Output: 10 15 21 26 39 45

Extension methods are defined as static methods but are called by  using instance method syntax. Their first parameter specifies which type  the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}
The WordCount extension method can be brought into scope with this using directive:
using ExtensionMethods;
And it can be called from an application by using this syntax:
string s = "Hello Extension Methods";
int i = s.WordCount();
In your code you invoke the extension method with instance method syntax. However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method. Therefore, the principle of encapsulation is not really being violated. In fact, extension methods cannot access private variables in the type they are extending.
For more information, see How to: Implement and Call a Custom Extension Method (C# Programming Guide).
In general, you will probably be calling extension methods far more often than implementing your own. Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code. To enable extension methods for a particular type, just add a using directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this using directive to your code:
using System.Linq;
(You may also have to add a reference to System.Core.dll.) You will  notice that the standard query operators now appear in IntelliSense as  additional methods available for most IEnumerable<T> types.

Binding Extension Methods at Compile Time  

You can use extension methods to  extend a class or interface, but not to override them. An extension  method with the same name and signature as an interface or class method  will never be called. At compile time, extension methods always have  lower priority than instance methods defined in the type itself. In  other words, if a type has a method named Process(int i),  and you have an extension method with the same signature, the compiler  will always bind to the instance method. When the compiler encounters a  method invocation, it first looks for a match in the type's instance  methods. If no match is found, it will search for any extension methods  that are defined for the type, and bind to the first extension method  that it finds. The following example demonstrates how the compiler  determines which extension method or instance method to bind to.

Example: 

The following example  demonstrates the rules that the C# compiler follows in determining  whether to bind a method call to an instance method on the type, or to  an extension method. The static class Extensions contains extension methods defined for any type that implements IMyInterface. Classes A, B, and C all implement the interface.
 
The MethodB extension method is never called because its name and signature exactly match methods already implemented by the classes. 
When the compiler cannot find an  instance method with a matching signature, it will bind to a matching  extension method if one exists.
// Define an interface named IMyInterface.
namespace DefineIMyInterface
{
    using System;
    public interface IMyInterface
    {
        // Any class that implements IMyInterface must define a method
        // that matches the following signature.
        void MethodB();
    }
}
// Define extension methods for IMyInterface.
namespace Extensions
{
    using System;
    using DefineIMyInterface;
    // The following extension methods can be accessed by instances of any 
    // class that implements IMyInterface.
    public static class Extension
    {
        public static void MethodA(this IMyInterface myInterface, int i)
        {
            Console.WriteLine
                ("Extension.MethodA(this IMyInterface myInterface, int i)");
        }
        public static void MethodA(this IMyInterface myInterface, string s)
        {
            Console.WriteLine
                ("Extension.MethodA(this IMyInterface myInterface, string s)");
        }
        // This method is never called in ExtensionMethodsDemo1, because each 
        // of the three classes A, B, and C implements a method named MethodB
        // that has a matching signature.
        public static void MethodB(this IMyInterface myInterface)
        {
            Console.WriteLine
                ("Extension.MethodB(this IMyInterface myInterface)");
        }
    }
}
// Define three classes that implement IMyInterface, and then use them to test
// the extension methods.
namespace ExtensionMethodsDemo1
{
    using System;
    using Extensions;
    using DefineIMyInterface;
    class A : IMyInterface
    {
        public void MethodB() { Console.WriteLine("A.MethodB()"); }
    }
    class B : IMyInterface
    {
        public void MethodB() { Console.WriteLine("B.MethodB()"); }
        public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
    }
    class C : IMyInterface
    {
        public void MethodB() { Console.WriteLine("C.MethodB()"); }
        public void MethodA(object obj)
        {
            Console.WriteLine("C.MethodA(object obj)");
        }
    }
    class ExtMethodDemo
    {
        static void Main(string[] args)
        {
            // Declare an instance of class A, class B, and class C.
            A a = new A();
            B b = new B();
            C c = new C();
            // For a, b, and c, call the following methods:
            //      -- MethodA with an int argument
            //      -- MethodA with a string argument
            //      -- MethodB with no argument.
            // A contains no MethodA, so each call to MethodA resolves to 
            // the extension method that has a matching signature.
            a.MethodA(1);           // Extension.MethodA(object, int)
            a.MethodA("hello");     // Extension.MethodA(object, string)
            // A has a method that matches the signature of the following call
            // to MethodB.
            a.MethodB();            // A.MethodB()
            // B has methods that match the signatures of the following
            // nethod calls.
            b.MethodA(1);           // B.MethodA(int)
            b.MethodB();            // B.MethodB()
            // B has no matching method for the following call, but 
            // class Extension does.
            b.MethodA("hello");     // Extension.MethodA(object, string)
            // C contains an instance method that matches each of the following
            // method calls.
            c.MethodA(1);           // C.MethodA(object)
            c.MethodA("hello");     // C.MethodA(object)
            c.MethodB();            // C.MethodB()
        }
    }
}
/* Output:
    Extension.MethodA(this IMyInterface myInterface, int i)
    Extension.MethodA(this IMyInterface myInterface, string s)
    A.MethodB()
    B.MethodA(int i)
    B.MethodB()
    Extension.MethodA(this IMyInterface myInterface, string s)
    C.MethodA(object obj)
    C.MethodA(object obj)
    C.MethodB()
 */

General Guidelines

In general, we recommend that  you implement extension methods sparingly and only when you have to.  Whenever possible, client code that must extend an existing type should  do so by creating a new type derived from the existing type. For more  information, see Inheritance (C# Programming Guide). 

When using an extension method  to extend a type whose source code you cannot change, you run the risk  that a change in the implementation of the type will cause your  extension method to break. 
If you do implement extension methods for a given type, remember the following two points:  

1) An extension method will never be called if it has the same signature as a method defined in the type.  

2)Extension methods are brought into scope at the namespace level.  For example, if you have multiple static classes that contain extension  methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive.

GROUP BY Query in LINQ TO ENTITY


Introduction:

When we create our application using LINQ, in that case we have to write all SQL queries using LINQ query operators. And it is a general requirement to write GROUP BY query when we try to build reports in our application in most cases.

CODE:

Following is the code or Query example to write GROUP BY Query in LINQ to Entities or Entity Framework:

var objData = from f in DASEntity.FILES
from fr in DASEntity.FILE_REQUEST_DETAILS
from s in DASEntity.STATUS
where f.ID == fr.FILE_ID
&& fr.STATUS_ID == s.ID
&& f.CLIENT_TOKEN == ClientToken
&& fr.CLIENT_TOKEN == ClientToken
group s by new { s.ID, s.NAME } into t
select new
{
StatusID = t.Key.ID,
Name = t.Key.NAME,
FileCount = t.Count()
};

Firefox and the FileUpload control in ASP.NET


I’ve been pretty annoyed about the fact that FireFox ignores the width property of the ASP.NET FileUpload control. It doesn’t matter if you set it by CSS or even in JavaScript, Firefox always ignores it and that results in a crippled layout since you have no control over the width of the upload input field. This actually has nothing to do with the FileUpload control, but with the rendered output of that control, which is just a standard field.

Here the width is set to 400px. The FileUpload control renders the Width attribute to the correct CSS style value of 400px at runtime.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ />

But as mentioned, Firefox totally ignores that. Then I remembered a forum thread I read some years ago about a size attribute. The only thing I could find was this list of available HTML attributes, but I gave it a try.

This is what I ended up with. The size attribute actually works in Firefox and IE ignores it, but adheres to the Width attribute instead.

FileUpload runat=”server” ID=”txtUpload” Width=”400″ size=”50″ />

The size attribute determines the number of characters should be visible and then adjusts the width accordingly. It is not the same as setting a maximum length of the file name, so it doesn’t break anything.

You should think that since a size of 50 generates the same width as 400px that you could always just divide the width in pixels with 8 to find the equivalent size. That is not the case. You have to manually adjust every time until you find the right size value that matches the pixel width

Tricks to increase SQL Server query performance


Thanks to the natural language roots of the SQL language, writing queries has become extremely easy for just about anyone to pick up. But its simplicity also makes it easy to write poorly performing queries. Here are some simple changes you can make to improve not only query performance, but, in some cases, overall SQL Server system performance as well.

CREATE TABLE vs. SELECT INTO

Oftentimes, within stored procedures or other SQL scripts, temp tables must be created and loaded with data. When writing these queries, many SQL Server DBAs and developers like to use the SELECT INTO method, like this:

SELECT *
INTO #TempTable
FROM sysobjects

While this technique works fine for small tables, when dealing with large record sets or long-running queries, it creates locks on the system objects within the tempdb database. As a result, other queries and procedures that need to create objects within the tempdb database will have to wait for the long-running query to complete. This is because when an object is created, an exclusive lock is taken against the sysobjects, syscolumns, sysindexes, etc system tables (SQL Server 2000) or the sysallocunits, syscolpars, syshobtcolumns, sysschobjs, sysserefs, etc system tables (SQL Server 2005). You can see this easily by opening two query windows and running the following:

(First window)
begin tran
create table #test1 (c1 int)
(Second window SQL 2005)
select object_name(rsc_objid), *
from sys.syslockinfo
where req_spid = 52 /*Where 52 = the SPID of the first window*/
order by 1

(Second window SQL Server 2000)
sp_lock 52 /*Where 52 = the SPID of the first window*/

When you have a very long-running query in a temporary table using the SELECT INTO format, those same system table locks are held until the query completes and data loads into the temp table. You can avoid system table locking by manually creating the table with the CREATE TABLE command—before loading the data into the table.
For example, this code…

CREATE TABLE #TempTable
(spid int)
INSERT INTO #TempTable
SELECT spid
FROM sys.objects

…will require much less locking than this code:

SELECT spid
INTO #TempTable
FROM sys.objects

While the total number of locks taken is the same, the length of time the locks are held for the first query will be much shorter. This allows other processes to create temp tables.
Typically, when developing SQL code the development server has only a single user or few users. When working on SQL code, it’s important to know when the code will impact sessions other than the current session. And unexpected interaction can cause major performance issues.

Accessing data across linked servers

Linked servers are an excellent way to get data in real-time from one server to another. However, incorrectly written linked server queries can quickly decrease system performance on one or both servers. While it’s easy to write these queries across linked servers, the query optimizer doesn’t always work as you would expect. I often see queries that join a local table to two remote tables and the queries take hours to run. That’s because the local optimizer doesn’t know which records to request from the remote table.
It therefore requests that the remote server transmit the entire table, and all that data is then loaded into a temporary table and the join is done locally. Unfortunately, because the local table is a temporary table—and not a physical table on the source system—the indexes on the remote table do not get created on the temporary table. Because of the lack of indexes, expected query execution time skyrockets.

There are a couple of techniques you can use to improve query response time. The first is to create a stored procedure on the remote database and have it return a record set, being a subset of the remote tables, which is then loaded into a local temporary table. It can then be indexed as needed. The trick with this method is to provide an input variable to the remote procedure where input values can be passed to. Thus, you will reduce the number of returned records by as much as possible. Fewer records will reduce the run time of that stored procedure as well as
the network latency on transferring those records from the remote system to the local system.
The second technique you can use is a variation of the first method. You create local temporary tables for each of the remote tables and transfer over the columns and records needed from each of the remote tables. Next, index the tables as needed and join the temp tables locally.
While the second technique is easier and faster to set up and implement, the first method gives you a greater performance savings, as typically less data needs to be transferred between servers.

Subqueries as join partners

When working with joins, you may want to manually control the order that data is selected. An easy (and usually safe) way to do this is to use subqueries as the join object instead of joining directly to a table. In some instances, you can decrease your query execution time by forcing the SQL Server to prefilter data in the table. This method is not foolproof and if used incorrectly it can increase the execution time of your query. The method should be fully tested before moving it to your production environment.

As we have seen, there are some quick and easy methods for improving query performance for some long-running processes. While these techniques will not apply to every issue you run across, they will help in some instances.

Simple way to Show/Hide Filter in RadGrid


Description:

Telerik’s RadGrid provides in-built search functionality. You can find the search functionality at top of the grid just below the header columns. But user should be able to hide the same to save unnecessary space all the time from the grid.

RadGrid Example when Filter is not visible to the user:

Radgrid without Filter

Radgrid without Filter

RadGrid Example when Filter is visible to the user:

RadGrid With Filter

RadGrid With Filter


Code:

First of all in RadGrid’s MasterTableView tag, add following checkbox:

<MasterTableView Width=”100%” CommandItemDisplay=”Top” GroupLoadMode=”Server”>

<CommandItemTemplate>

<asp:CheckBox ID=”CheckBox2″ AutoPostBack=”true” CssClass=”CheckBox” runat=”server”

ForeColor=”White” Text=”Show Filter” />

</CommandItemTemplate>

After that add the ItemCreated event in the RadGrid as following code does:

protected void grdManageTransType_ItemCreated(object sender, GridItemEventArgs e)

{

if (e.Item.ItemType == GridItemType.CommandItem)

{

GridCommandItem commandItem = e.Item as GridCommandItem;

CheckBox chkFilter2 = (CheckBox)commandItem.FindControl(“CheckBox2”);

chkFilter2.AutoPostBack = true;

chkFilter2.ForeColor = System.Drawing.Color.White;

chkFilter2.Checked = grdManageTransType.AllowFilteringByColumn;

//Adding the event handler

chkFilter2.CheckedChanged += new EventHandler(chkFilter2_CheckedChanged);

}

if (e.Item.ItemType == GridItemType.SelectedItem)

e.Item.BackColor = Color.FromName(“#FFEDC1”);

}

In above portion of code we are creating CheckedChanged event of the checkbox. So now create the CheckedChanged event of the checkbox as per following code:

protected void chkFilter2_CheckedChanged(object sender, EventArgs e)

{

grdManageTransType.AllowFilteringByColumn = !grdManageTransType.AllowFilteringByColumn;

grdManageTransType.Rebind();

}

As per the above code portions, we can the checkbox at the top of the RadGrid. On click of that checkbox RadGrid’s filter should be visible on or off.

Count items in Telerik’s RadComboBox


Description:

It is general requirement to show and count number of items in Telerik’s RadComboBox. And we can do that by using a simple javascript function.

Code:

In javasript:

function UpdateItemCountField(sender, args) {

//set the footer text

sender.get_dropDownElement().lastChild.innerHTML = “A total of “ + sender.get_items().get_count() + ” items”;

}

In aspx page:

add footer template as shown below code.

<FooterTemplate>

A total of

<asp:Literal runat=”server” ID=”RadComboItemsCount” />

items

</FooterTemplate>