Tuesday, December 4, 2012

RadGrid inside Radgrid hierarchy using Template Column

Problem:

I want to make RadGrid hierarchy using ItemTemplate.and I want commandItem display at top in Detail Grid just like Master Grid.

Solution:

Its technique is very simple,you have to put a <DetailTables> tag just after <MasterTableView> and make the relation of  Master and Detail, see the following example and watch for Bold text.But here I like to mention one thing that insert/update/delete events of Master and Detail grids are same and you have to differentiate that either insert/update/delete is called from Master or Detail. However NeedDataSource event is called when Master Grid is binned and DetailTableDataBind event is called when Detail table is binned.

<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" PageSize="20"
        AllowSorting="True" AllowPaging="True" ShowStatusBar="True" GridLines="None"
        Skin="WebBlue" CellSpacing="0">
        <MasterTableView DataKeyNames="ParentID_PK" ClientDataKeyNames="ParentID_PK" CommandItemDisplay="Top">
        <DetailTables>
            <telerik:GridTableView DataKeyNames="DetailID_PK" ClientDataKeyNames="DetailID_PK"
                    Width="100%" runat="server" CommandItemDisplay="Top">
                <ParentTableRelation>
                    <telerik:GridRelationFields DetailKeyField="ParentID_FK" MasterKeyField="ParentID_PK">
                    </telerik:GridRelationFields>
                </ParentTableRelation>

                <Columns>

<%--here will be the columns of Detail table--%>

                </Columns>
            </telerik:GridTableView>
        </DetailTables>
        <Columns>



<%--here will be the columns of Master table--%>

        </Columns>
    </MasterTableView>
</telerik:RadGrid>

Friday, November 16, 2012

RadGrid Multirow Selection form Client Side

Problem:

How to select a multiple rows in RadGrid from client side?

Solution:

Make AllowMultiRowSelection  property to True for multi row selection and in client settings make AllowRowSelect to True. and include a GridClientSelectColumn in Columns Tag.

For Example:

<telerik:radgrid id="RadGrid1" runat="server" autogeneratecolumns="False" pagesize="20"
        allowsorting="True" allowpaging="True" showstatusbar="True" gridlines="None"
        skin="WebBlue" cellspacing="0" allowmultirowselection="true">
<ClientSettings>
           <Selecting AllowRowSelect="True"/>
</ClientSettings>

<MasterTableView>
<Columns>
<telerik:GridClientSelectColumn UniqueName="MyClientSelectColumn" HeaderText="asd">
</telerik:GridClientSelectColumn>

<telerik:GridTemplateColumn UniqueName="TemplateColumn">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text="It is hidden ID or primary key of the row" Visible="false"></asp:Label>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:radgrid>

To get the selected rows you should use a for each loop on selected Items of RadGrid like this one :

For Each item As GridDataItem In RadGrid1.SelectedItems
          Dim lblID As Integer = CType(CType(item.FindControl("lblID"), Label).Text, Integer)
Next

Friday, June 15, 2012

Give an option of "All" in RadGrid PageSize Combo


To show all rows in RadGrid. I want to give an option of "All" in RadGrid
PageSize Combo. Like this:


Solution:
VB Code
Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated
        If TypeOf e.Item Is GridPagerItem Then
            Dim combo As RadComboBox = TryCast(TryCast(e.Item, GridPagerItem).FindControl("PageSizeComboBox"), RadComboBox)

            ' The number of items shown when all is selected
            Dim allRowsCount As Integer = Integer.MaxValue

            ' Remove duplicates
            Dim duplicate As RadComboBoxItem = combo.Items.FindItemByValue(allRowsCount.ToString())
            If duplicate IsNot Nothing Then
                duplicate.Remove()
            End If

            ' Create a new item for showing all
            Dim item As New RadComboBoxItem("All", allRowsCount.ToString())
            item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID)
           
combo.Items.Add(item)

            ' Set the current pagesize as the selected value
            combo.Items.FindItemByValue(RadGrid1.PageSize.ToString()).Selected = True
        End If
    End Sub

Thursday, June 14, 2012

Hashtable Vs Dictionary(of T,T)

I will prefer yo use Dictonary(of T,T)  instead of hastbale because it is type safe and second it will not cast object type  in to appropriate type so performance is better .

Hashtable:

Hashtable is non generic type collection from name space(system.collection)
by default it can contain  any type  means it accept system.object(every type reference or value type derived from system.object class).Hashtable store item in key /value pair. means value are stored in hashcode of key
"key Can't duplicate".

Module Module1

    Sub Main()
        Dim list As New Hashtable
        list.Add(1, "yousuf")
        list.Add(2, "ashar")
        list.Add("third", "captain jack sparrow")
        list.Add(4, "babosa")
        Console.WriteLine("value of key :third")
        Console.WriteLine(list("third"))
        Console.WriteLine("Is Captain Jack Sparrow still in black perl")
        Console.WriteLine(list.ContainsValue("captain jack sparrow"))
        Console.WriteLine("Keys and values In list")
        For Each itm As DictionaryEntry In list
            Console.WriteLine("key : {0} and has value {1}", itm.Key, itm.Value)
        Next
        Console.WriteLine("Keys In list")
        For Each ky As Object In list.Keys
            Console.WriteLine("key : {0} ", ky)
        Next
        Console.WriteLine("values In list")
        For Each vl As Object In list.Values
            Console.WriteLine("value : {0} ", vl)
        Next
        Console.ReadLine()
    End Sub

End Module

Out Put:


Dictonary(of T,T):
Dictonary(of T,T)  is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New Dictonary(of T,T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.Dictonary(of T,T)  store item in key /value pair. means value are stored in hashcode of key"key Can't duplicate".

Module Module1
    Sub Main()
        Dim list As New Dictionary(Of Integer, String)
        list.Add(1, "yousuf")
        list.Add(2, "ashar")
        list.Add(3, "captain jack sparrow")
        list.Add(4, "babosa")
        Console.WriteLine("value of key :3")
        Console.WriteLine(list(3))
        Console.WriteLine("Is Captain Jack Sparrow still in black perl")
        Console.WriteLine(list.ContainsValue("captain jack sparrow"))
        Console.WriteLine("Keys and values In list")
        For Each itm As KeyValuePair(Of Integer, String) In list
            Console.WriteLine("key : {0} and has value {1}", itm.Key, itm.Value)
        Next
        Console.WriteLine("Keys In list")
        For Each ky As Object In list.Keys
            Console.WriteLine("key : {0} ", ky)
        Next
        Console.WriteLine("values In list")
        For Each vl As Object In list.Values
            Console.WriteLine("value : {0} ", vl)
        Next
        Console.ReadLine()
    End Sub
End Module

Out Put:

Tuesday, June 12, 2012

Stack VS Stack(of T)


I will prefer yo use Stack(of T)  instead of Stack because it is type safe and second it will not cast object type  in to appropriate type so performance is better .

Stack:

Stack is non generic type collection from name space(system.collection)
by default it can contain  any type  means it accept system.object(every type reference or value type derived from system.object class). stack work on the principle of  LIFO(Last  in First Out) .

Module Module1

    Sub Main()
        Dim stk As New Stack
        stk.Push(1)
        stk.Push("Second")
        stk.Push(3)
        stk.Push("4th")
        Console.WriteLine("first in List")
        Console.WriteLine(stk.Peek)
        stk.Pop()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(stk.Peek)
        Console.ReadLine()
    End Sub
End Module

Out Put:
first in List
4th
after deque first in List
3

Stack(of T):

Stack(of T)  is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New stack(of T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.Queue(of T)  work on the principle of  LIFO(Last  in First Out) .

Module Module1
    Sub Main()
        Dim stk As New Stack(Of Integer)
        stk.Push(1)
        stk.Push(2)
        stk.Push(3)
        stk.Push(4)
        Console.WriteLine("first in List")
        Console.WriteLine(stk.Peek)
        stk.Pop()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(stk.Peek)
        Console.ReadLine()
    End Sub
End Module

Out Put:
first in List
4
after deque first in List
3

Monday, June 11, 2012

Queue VS Queue(of T)


I will prefer yo use Queue(of T)  instead of Queue because it is type safe and second it will not cast object type  in to appropriate type so performance is better.

Queue:

Queue is non generic type collection from name space(system.collection)
by default it can contain  any type  means it accept system.object(every type reference or value type derived from system.object class). Queue work on the principle of  FIFO(first in First Out) .it insert items like in array (one after other in sequence)
Module Module1
 Sub Main()
        Dim que As New Queue()
        que.Enqueue(1)
        que.Enqueue("Second")
        que.Enqueue(3)
        que.Enqueue("4th")
        Console.WriteLine("first in List")
        Console.WriteLine(que.Peek)
        que.Dequeue()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(que.Peek)
        Console.ReadLine()
    End Sub
End Module


Out Put:

first in List
1
after deque first in List
Second

Queue(of T):

Queue(of T)  is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New Queue(of T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.Queue(of T) work on the principle of  FIFO(first in First Out) .it insert items like in array (one after other in sequence)

Module Module1

    Sub Main()
        Dim que As New Queue(Of Integer)
        que.Enqueue(1)
        que.Enqueue(2)
        que.Enqueue(3)
        que.Enqueue(4)
        Console.WriteLine("first in List")
        Console.WriteLine(que.Peek)
        que.Dequeue()
        Console.WriteLine("after deque first in List")
        Console.WriteLine(que.Peek)
        Console.ReadLine()
    End Sub
End Module

Out Put:

first in List
1
after deque first in List
2


I will prefer yo use Queue(of T)  instead of Queue because it is type safe and second it will not cast object type  in to appropriate type so performance is better .





Friday, June 8, 2012

Arraylist Vs List collection in VB.net

ArrayList:

arraylist is non generic type collection from name space (system.collection)
by default it can contain  any type  means it accept system.object (every type reference or value type derived from system.object class).
For Example:

Module Module1
    Sub Main()
        Dim lst As New ArrayList
        lst.Add("yousuf")
        lst.Add(2)
        Dim STR() As String = {"ashar", "kamran"}
        lst.AddRange(Str)
        For Each Obj As Object In lst
            Console.WriteLine(Obj)
        Next
        Console.ReadLine()
    End Sub

End Module

Out Put:
yousuf
2
ashar
kamran


LIST:

list is  generic type collection from name space(system.collection.generic)
 it can contain a specific type means that its type safe so that you can't insert an integer and string in same list.
Dim lst As New List(Of  T)
where "T" can be integer ,string or any type.  if you will assign T as "Object" then it will work same as non generic type.
For Example:

Module Module1
    Sub Main()
        Dim lst As New List(Of String)
        lst.Add("yousuf")
         Dim STR() As String = {"yasir", "kamran"}
        lst.AddRange(Str)
        For Each Obj As Object In lst
            Console.WriteLine(Obj)
        Next
        Console.ReadLine()
    End Sub

End Module

Out Put:
yousuf
ashar
kamran


I will prefer you to use List instead of arraylist because it is type safe and second it will not cast object type  in to appropriate type so performance is better .






 

Friday, June 1, 2012

How to apply css on RadDatePicker

Problem:

How to apply css on RadDatePicker? I am Applying css like that :

<telerik:RadDatePicker ID="RadDatePicker1" Runat="server" Culture="en-US"
CssClass="txt_box">
</telerik:RadDatePicker>

but is not working, it is giving me unwanted results.

Solution:

You should use "DateInput" tag in RadDatePicker. for example:

<telerik:RadDatePicker ID="RadDatePicker1" Runat="server" Culture="en-US">
       <DateInput CssClass="txt_box">
       </DateInput>

</telerik:RadDatePicker>

Wednesday, May 23, 2012

Find Label Control from Item Temple of RadGrid

Problem:

I am using GridTemplateColumn in RadGrid and I want find the label control which is in grid's ItemTemplate to update record.

I am using this code in grid's updatecommand,

VB CODE:
Dim Label1 As Label = CType(e.Item.FindControl("Label1"), Label)

but control is not found thus there is (nothing) in Label1.

Solution:

Try this,

VB CODE:
Dim Label1 As Label = DirectCast(CType(e.Item, GridEditFormItem).OwnerTableView.Items(e.Item.ItemIndex).FindControl("Label1"), Label)

Sunday, April 22, 2012

Code Snippets


Introduction:

Snippet is a programming term for a small region of re-usable source code, machine code or text. Code Snippets provide a way for you to insert ready-made snippets of code into your projects.

Advantages:

  • Write once use anywhere: Reduce the repeatable writing of code effort.
  • Define/Maintain a Coding Standard to be used for any Project/Organization.
  • Easy to use as well as create and also easily maintainable.
  • Share with other developers.
  • Increase productivity by making coding faster.

Creating a Snippet File:

To create a snippet file, you must create an XML file, and then write the XML code that makes up your code snippet.
Following are the steps to create a snippet file:

Step1



Step 2



Step 3



Step 4



Step 5



Step 6


Manage Code Snippets:

The Code Snippets Manager allows you to set the directories and individual snippets that you want available to insert into your code.

To access the Code Snippets Manager :

      On the Tools menu, click Code Snippets Manager.

To add a directory to the Code Snippet Manager :

In the Language: drop-down list, select the language that you want to add a directory to.
Click Add. This opens the Code Snippets Directory window.
Select the directory that you want to add to the Code Snippets Manager and click ‘OK’. The directory will now be used to search for available code snippets.

Monday, January 23, 2012

Update In LINQ not Working

Problem: I am working on a console application and I have a table in my .DBML File as FirstTable
I am using following code written below to update a field "Father Name" but it is still not updating it in Relational Database MS SQL.

VB Code:
Imports System.Data
Imports System.Collections.Generic
Module Module2
    Dim DB As New NorthWinddatacontext()

    Sub main()

        Dim UpdateName = (From p In DB.FirstTables Where p.Name = "Yousuf"
                       Select p).Single

        UpdateName.FatherName = "Hashmi1"
        DB.SubmitChanges()
    End Sub

My code is not working

Solution: You have not set any Primary Key on Your Table  in your Relational Database.Make a Primary Key and try the same code again by Droping the table again on Your DBML.

Friday, January 20, 2012

is neither a DataColumn nor a DataRelation for table DefaultView

Problem: I get this error when I try to filter any column in my RadGrid.I am using template columns.

"is neither a DataColumn nor a DataRelation for table DefaultView"

Here is my code of a Column
<telerik:GridTemplateColumn HeaderStyle-HorizontalAlign="Center" HeaderText="PO #" Visible="true">
 <ItemTemplate>
<asp:Label ID="lblPONumber" Text='<%# Eval("_PONumber") %>' runat="server">
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</telerik:GridTemplateColumn>


Solution: You have to check that DataField property is present or not.

Here is corrected Code
<telerik:GridTemplateColumn DataField="_PONumber" HeaderStyle-HorizontalAlign="Center" HeaderText="PO #" Visible="true">
 <ItemTemplate>
<asp:Label ID="lblPONumber" Text='<%# Eval("_PONumber") %>' runat="server">
</asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</telerik:GridTemplateColumn>

Wednesday, January 18, 2012

First Column of RadGrid to stay visible

Problem: I have many columns in my RadGrid ,I want first column to stay visible while scrolling.Only first column should appear all the time.
Solution: This can be done using FrozenColumnsCount in ClientSettings tag.

Example:
<telerik:RadGrid ID="radGridServices" runat="server">
    <MasterTableView CommandItemDisplay="Top" DataKeyNames="Services_ID_PK" ClientDataKeyNames="Services_ID_PK">
    </MasterTableView>
    <ClientSettings>
        <Scrolling AllowScroll="true" FrozenColumnsCount="1" SaveScrollPosition="true" UseStaticHeaders="true" />
        <ClientEvents />
    </ClientSettings>
</telerik:RadGrid>



Monday, January 16, 2012

Simple handling Of Events In Visual Basic .NET 4.0 Using Handler

Problem: How to handle events in Visual Basic .NET 4.0 using Handler ? 
Solution: Just Copy The Whole Code Below in Console Application

VB Code:
Module Module1
    Sub Main()
        Dim objWork As New Worker
        AddHandler objWork.WorkDone, AddressOf work_WorkDone
        objWork.DoWork()
    End Sub

    Private Sub work_WorkDone(ByVal completedWork As Integer)
        Console.WriteLine(completedWork)
    End Sub
End Module

Public Class Worker
    Public Event WorkDone(ByVal completedWork As Integer)
    Public Sub DoWork()
        For completedWork As Integer = 1 To 100
            System.Threading.Thread.Sleep(1000)
            RaiseEvent WorkDone(completedWork)
        Next
    End Sub
End Class

C# Code:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics; 
 
static class Module1
{
   public static void Main()
   {
     Worker objWork = new Worker();
     objWork.WorkDone += work_WorkDone;
     objWork.DoWork();
   }
}

private static void work_WorkDone(int completedWork)
{
   Console.WriteLine(completedWork);
}

public class Worker
{
   public event WorkDoneEventHandler WorkDone;
   public delegate void WorkDoneEventHandler(int completedWork);

   public void DoWork()
   {
     for (int completedWork = 1; completedWork <= 100; completedWork++)
     {
       System.Threading.Thread.Sleep(1000);

       if (WorkDone != null)
       {
         WorkDone(completedWork);
       }
     }
   }
}

Tuesday, December 20, 2011

Getting started with RadDesktopAlert

Problem: Is there any thing in which a pop-up or alert appears from the bottom of screen.
Solution: Telerik has a solution for this,use RadDesktopAlert.

To see video Click the following link.
http://tv.telerik.com/watch/winforms/getting-started-with-raddesktopalert

How to disable filter button in RadGridView in Winforms

Problem: I am setting the properties of RadGridView in Winforms like Header of column and filter to disable but they are not working.
Solution: This is a bug in current version of Telerik. and hope it iwll be resolved in next version but you can do this by coding.
for example:
VB Code:
RadGridView1.MasterTemplate.AllowDeleteRow = False
RadGridView1.MasterTemplate.AllowEditRow = False
RadGridView1.MasterTemplate.AllowAddNewRow = False
RadGridView1.MasterTemplate.EnableGrouping = False
RadGridView1.MasterTemplate.ShowRowHeaderColumn = False
C# Code:
RadGridView1.MasterTemplate.AllowDeleteRow = false;
RadGridView1.MasterTemplate.AllowEditRow = false;
RadGridView1.MasterTemplate.AllowAddNewRow = false;
RadGridView1.MasterTemplate.EnableGrouping = false;
RadGridView1.MasterTemplate.ShowRowHeaderColumn = false;

Thursday, December 15, 2011

How to show Desktop Alert (RadDesktopAlert)

Problem: How to show desktop alert or a pop-up in desktop which comes from the bottom of screen.
Solution: Drag and drop RadDesktopAlert control from toolbox.It will appear in bottom of form.

You can set its properties from the properties window and see its preview.
Now the code is really simple, I am using a simple button to demonstrate it.Desktop alert is shown at the OnClick event of this button.

VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        RadDesktopAlert1.ContentText = "Hello World"
        RadDesktopAlert1.Show()

End Sub

Wednesday, December 7, 2011

Calculate the GCD

Problem: Calculate the GCD of Three, Four, or Five Integers. (Vb.Net ,C #)

Solution:

GCD of Two Numbers:
GCD(a,b)
Algorithm
Step 1: a modulus b = r (remainder)  If r Not Equal To Zero i.e i < > 0
Then
Step 2: a: =b and b : = r
Repeat Step 1 Till R become Zero i.e i := 0
Step 3:
GCD is b
Stop


VB Code:
 Module Module1
      Sub Main()
   Dim FirstNumber As Integer
        Dim SecondNumber As Integer
        FirstNumber = Console.ReadLine()
        SecondNumber = Console.ReadLine()
        If FirstNumber < SecondNumber Then
            Dim Temp As Integer
            Temp = SecondNumber
            SecondNumber = FirstNumber
            FirstNumber = Temp
        End If
        Dim NewMod As Integer
        Dim GCD As Integer
        NewMod = FirstNumber Mod SecondNumber
        While (NewMod > 0)
            FirstNumber = SecondNumber
            SecondNumber = NewMod
            NewMod = FirstNumber Mod SecondNumber
  End While
        GCD = SecondNumber
 Console.WriteLine(GCD)
Console.ReadLine()
    End Sub
End Module


For C# Code Convert It From 
http://www.developerfusion.com/tools/convert/vb-to-csharp/

GCD Of Three Numbers:

GCD(a,b,c)=GCD(a,GCD(b,c))






VB Code:
Module Module1
    Sub Main()
        Dim FirstNumber As Integer
        Dim SecondNumber As Integer
        Dim ThirdNumber As Integer
        FirstNumber = Console.ReadLine()
        SecondNumber = Console.ReadLine()
        ThirdNumber = Console.ReadLine()
        ' For GCD(a,b)
        If FirstNumber < SecondNumber Then
            Dim Temp As Integer
            Temp = SecondNumber
            SecondNumber = FirstNumber
            FirstNumber = Temp
        End If
        Dim NewMod As Integer
        Dim GCD As Integer
        NewMod = FirstNumber Mod SecondNumber
        While (NewMod > 0)
            FirstNumber = SecondNumber
            SecondNumber = NewMod
            NewMod = FirstNumber Mod SecondNumber
 End While
        GCD = SecondNumber
        'Now For GCD(GCD(a,b),c)
        FirstNumber = GCD
        SecondNumber = ThirdNumber
        If FirstNumber < SecondNumber Then
            Dim Temp As Integer
            Temp = SecondNumber
            SecondNumber = FirstNumber
            FirstNumber = Temp
        End If
     
        NewMod = FirstNumber Mod SecondNumber
        While (NewMod > 0)
            FirstNumber = SecondNumber
            SecondNumber = NewMod
            NewMod = FirstNumber Mod SecondNumber 

         End While
        GCD = SecondNumber
        Console.WriteLine(GCD) ' GCD Of a,b,c
        Console.ReadLine()
    End Sub
End Module

 For C# Code Convert It From 
http://www.developerfusion.com/tools/convert/vb-to-csharp/
The Code Will Become Easy If Using Function And Can perform two three and four by a little modification.

VB Code:
Module Module1
    Public Freinds() As String
    Dim COUNT As Integer
    Sub Main()
    Dim FirstNumber As Integer
        Dim SecondNumber As Integer
        Dim ThirdNumber As Integer
        FirstNumber = Console.ReadLine()
        SecondNumber = Console.ReadLine()
        ThirdNumber = Console.ReadLine()
        Dim GCD As Integer
        GCD = GetGCD(FirstNumber, SecondNumber)
        Console.WriteLine(GCD)
        FirstNumber = GCD
        SecondNumber = ThirdNumber
        GCD = GetGCD(FirstNumber, SecondNumber)
     Console.ReadLine()
    End Sub
    Private Function GetGCD(ByVal Firstnumber As Integer, ByVal SecondNumber As Integer) As Integer
        If Firstnumber < SecondNumber Then
            Dim Temp As Integer
            Temp = SecondNumber
            SecondNumber = Firstnumber
            Firstnumber = Temp
        End If
        Dim NewMod As Integer
        Dim GCD As Integer
        NewMod = Firstnumber Mod SecondNumber
        While (NewMod > 0)
            Firstnumber = SecondNumber
            SecondNumber = NewMod
            NewMod = Firstnumber Mod SecondNumber 

        End While
        Return SecondNumber
    End Function
End Module 

Friday, November 25, 2011

RadImage in RadGrid

Problem: How to bind and insert a RadImage in RadGrid  From Server Side using RadAsyncUpload.

Solution:
Here Is The Sample Code.
ASPX

<%@ Page Title="Home Page" Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
    Inherits="_Default" %>

<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body class="BODY">
    <form id="form1" runat="server">
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server">
    </telerik:RadStyleSheetManager>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            var uploadedFilesCount = 0;
            var isEditMode;
            function validateRadUpload(source, e) {
                debugger;
                if (isEditMode == null || isEditMode == undefined) {
                    e.IsValid = false;

                    if (uploadedFilesCount > 0) {
                        e.IsValid = true;
                    }
                }
                isEditMode = null;
            }

            function OnClientFileUploaded(sender, eventArgs) {
                uploadedFilesCount++;
            }
            function conditionalPostback(sender, eventArgs) {
                var theRegexp = new RegExp("\.UpdateButton$|\.PerformInsertButton$", "ig");
                if (eventArgs.get_eventTarget().match(theRegexp)) {
                    var upload = $find(window['UploadId']);

                    //AJAX is disabled only if file is selected for upload
                    if (upload.getFileInputs()[0].value != "") {
                        eventArgs.set_enableAjax(false);
                    }
                }
            }
       
        </script>
    </telerik:RadCodeBlock>
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
        <Scripts>
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
            <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
        </Scripts>
    </telerik:RadScriptManager>
    <table width="100%">
        <tr>
            <td>
            </td>
        </tr>
        <tr>
            <td align="center" width="90%">
                <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
                    <AjaxSettings>
                        <telerik:AjaxSetting AjaxControlID="RadGrid1">
                            <UpdatedControls>
                                <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                            </UpdatedControls>
                        </telerik:AjaxSetting>
                    </AjaxSettings>
                </telerik:RadAjaxManager>
                <telerik:RadGrid ID="RadGrid1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
                    CellSpacing="0" GridLines="None" OnInsertCommand="RadGrid1_InsertCommand" OnItemCreated="RadGrid1_ItemCreated"
                    OnNeedDataSource="RadGrid1_NeedDataSource" PageSize="3" ShowStatusBar="True"
                    Skin="Web20" Width="900px">
                    <PagerStyle AlwaysVisible="true" Mode="NumericPages" />
                    <MasterTableView CommandItemDisplay="Top" Width="900px">
                        <Columns>
                            <telerik:GridTemplateColumn HeaderStyle-Width="190px" HeaderText="Image Name" SortExpression="Name"
                                UniqueName="ImageName">
                                <ItemTemplate>
                                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadTextBox ID="txbName" runat="server" Text='<%# Eval("Name") %>' Width="190px" />
                                    <asp:RequiredFieldValidator ID="Requiredfieldvalidator1" runat="server" ControlToValidate="txbName"
                                        Display="Dynamic" ErrorMessage="Please, enter a name!" SetFocusOnError="true" />
                                </EditItemTemplate>
                                <HeaderStyle Width="190px" />
                                <ItemStyle VerticalAlign="Top" Width="190px" />
                            </telerik:GridTemplateColumn>
                            <telerik:GridTemplateColumn DataField="Description" HeaderStyle-Width="200px" HeaderText="Description"
                                UniqueName="Description">
                                <ItemTemplate>
                                    <telerik:RadTextBox ID="lblDescription" runat="server" BorderColor="White" Height="60px"
                                        ReadOnly="true" Text='<%# TrimDescription(DirectCast(IIF(Eval("Description") IsNot DBNull.Value,Eval("Description"),string.Empty),String)) %>'
                                        TextMode="MultiLine" Width="200px" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadTextBox ID="txbDescription" runat="server" Height="60px" Text='<%# Eval("Description") %>'
                                        TextMode="MultiLine" Width="180px" />
                                </EditItemTemplate>
                                <HeaderStyle Width="200px" />
                                <ItemStyle VerticalAlign="Top" Width="180px" />
                            </telerik:GridTemplateColumn>
                            <telerik:GridTemplateColumn HeaderStyle-Width="220px" ItemStyle-Width="220px" HeaderText="Image"
                                UniqueName="Upload">
                                <ItemTemplate>
                                    <telerik:RadBinaryImage ID="RadBinaryImage1" runat="server" AlternateText='<%#Eval("Name", "Photo of {0}") %>'
                                        AutoAdjustImageControlSize="false" DataValue='<%#Eval("Image") %>' Height="140px"
                                        ToolTip='<%#Eval("Name", "Photo of {0}") %>' Width="220px" />
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <telerik:RadAsyncUpload ID="AsyncUpload1" runat="server" AllowedFileExtensions="jpg,jpeg,png,gif"
                                        MaxFileSize="5048576" OnClientFileUploaded="OnClientFileUploaded" OnValidatingFile="RadAsyncUpload1_ValidatingFile">
                                    </telerik:RadAsyncUpload>
                                </EditItemTemplate>
                            </telerik:GridTemplateColumn>
                        </Columns>
                        <EditFormSettings>
                            <EditColumn ButtonType="ImageButton" />
                        </EditFormSettings>
                        <PagerStyle AlwaysVisible="True" />
                    </MasterTableView>
                    <FilterMenu EnableImageSprites="False">
                    </FilterMenu>
                    <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Web20">
                    </HeaderContextMenu>
                </telerik:RadGrid>
            </td>
        </tr>
    </table>
</body>
</form>
</html>

VB Code.
Imports System.Data
Imports Telerik.Web.UI
Imports System.Data.SqlClient
Partial Class _Default
    Inherits System.Web.UI.Page 
Const MaxTotalBytes As Integer = 1024 ' 1 MB
    Dim totalBytes As Integer
    Dim ConnString As String = "data source=localDataSource;Initial Catalog=database;User Id=User;Password=*****;"

    Dim sqlconn As New SqlConnection(ConnString)


    Public Property IsRadAsyncValid() As System.Nullable(Of Boolean)
        Get
            If Session("IsRadAsyncValid") Is Nothing Then
                Session("IsRadAsyncValid") = True
            End If

            Return Convert.ToBoolean(Session("IsRadAsyncValid").ToString())
        End Get
        Set(ByVal value As System.Nullable(Of Boolean))
            Session("IsRadAsyncValid") = value
        End Set
    End Property
    Protected Function TrimDescription(ByVal description As String) As String
        If Not String.IsNullOrEmpty(description) AndAlso description.Length > 200 Then
            Return String.Concat(description.Substring(0, 200), "...")
        End If
        Return description
    End Function

 
    Protected Sub RadGrid1_InsertCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs)
        If Not IsRadAsyncValid.Value Then
            e.Canceled = True
            RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB")
            Return
        End If

        Dim insertItem As GridEditFormInsertItem = TryCast(e.Item, GridEditFormInsertItem)
        Dim imageName As String = TryCast(insertItem("ImageName").FindControl("txbName"), RadTextBox).Text
        Dim description As String = TryCast(insertItem("Description").FindControl("txbDescription"), RadTextBox).Text
        Dim radAsyncUpload As RadAsyncUpload = TryCast(insertItem("Upload").FindControl("AsyncUpload1"), RadAsyncUpload)

        Dim file As UploadedFile = radAsyncUpload.UploadedFiles(0)
        Dim fileData As Byte() = New Byte(file.InputStream.Length - 1) {}
        file.InputStream.Read(fileData, 0, CInt(file.InputStream.Length))
        sqlconn.Open()
        Dim Insert As New SqlCommand("Insert into [Test1].[dbo].[Test_Img] ([ImageID],[Name],[Description],[Image]) values ('3','" + imageName + "','" + description + "',  @image  )", sqlconn)
        Dim imageParam As SqlParameter = Insert.Parameters.Add("@image", SqlDbType.Image)
        imageParam.Value = fileData
        imageParam.Size = fileData.Length
        Insert.ExecuteNonQuery()
        sqlconn.Close()

      End Sub

    Protected Sub RadGrid1_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource

        Dim SqlCommand As New SqlCommand("Select [ImageID],[Image],[Name],[Description] from [Test1].[dbo].[Test_Img]", sqlconn)
        sqlconn.Open()
        Dim sqladap As New SqlDataAdapter
        sqladap.SelectCommand = SqlCommand
        Dim ds As New DataSet
        sqladap.Fill(ds, "ImageSet")

        RadGrid1.DataSource = ds.Tables(0)
        sqlconn.Close()

    End Sub

    Public Sub RadAsyncUpload1_ValidatingFile(ByVal sender As Object, ByVal e As Telerik.Web.UI.Upload.ValidateFileEventArgs)
        If (totalBytes < MaxTotalBytes) AndAlso (e.UploadedFile.ContentLength < MaxTotalBytes) Then
            e.IsValid = True
            totalBytes += e.UploadedFile.ContentLength
            IsRadAsyncValid = True
        Else
            e.IsValid = False
            IsRadAsyncValid = False
        End If
    End Sub
    Protected Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs)
        If TypeOf e.Item Is GridEditableItem AndAlso e.Item.IsInEditMode Then
            Dim upload As RadAsyncUpload = TryCast(DirectCast(e.Item, GridEditableItem)("Upload").FindControl("AsyncUpload1"), RadAsyncUpload)
            Dim cell As TableCell = DirectCast(upload.Parent, TableCell)

            Dim validator As New CustomValidator()
            validator.ErrorMessage = "Please select file to be uploaded"
            validator.ClientValidationFunction = "validateRadUpload"
            validator.Display = ValidatorDisplay.Dynamic
            cell.Controls.Add(validator)
        End If

    End Sub
End Class

C# Code.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Telerik.Web.UI;
using System.Data.SqlClient;
partial class _Default : System.Web.UI.Page
{

  // 1 MB
 const int MaxTotalBytes = 1024;
 int totalBytes;

 string ConnString = "data source=localDataSource;Initial Catalog=database;User Id=User;Password=*****;";

 SqlConnection sqlconn = new SqlConnection(ConnString);

 public System.Nullable<bool> IsRadAsyncValid {
  get {
   if (Session["IsRadAsyncValid"] == null) {
    Session["IsRadAsyncValid"] = true;
   }

   return Convert.ToBoolean(Session["IsRadAsyncValid"].ToString());
  }
  set { Session["IsRadAsyncValid"] = value; }
 }
 protected string TrimDescription(string description)
 {
  if (!string.IsNullOrEmpty(description) && description.Length > 200) {
   return string.Concat(description.Substring(0, 200), "...");
  }
  return description;
 }


 protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
 {
  if (!IsRadAsyncValid.Value) {
   e.Canceled = true;
   RadAjaxManager1.Alert("The length of the uploaded file must be less than 1 MB");
   return;
  }

  GridEditFormInsertItem insertItem = e.Item as GridEditFormInsertItem;
  string imageName = (insertItem("ImageName").FindControl("txbName") as RadTextBox).Text;
  string description = (insertItem("Description").FindControl("txbDescription") as RadTextBox).Text;
  RadAsyncUpload radAsyncUpload = insertItem("Upload").FindControl("AsyncUpload1") as RadAsyncUpload;

  UploadedFile file = radAsyncUpload.UploadedFiles(0);
  byte[] fileData = new byte[file.InputStream.Length];
  file.InputStream.Read(fileData, 0, Convert.ToInt32(file.InputStream.Length));
  sqlconn.Open();
  SqlCommand Insert = new SqlCommand("Insert into [Test1].[dbo].[Test_Img] ([ImageID],[Name],[Description],[Image]) values ('3','" + imageName + "','" + description + "',  @image  )", sqlconn);
  SqlParameter imageParam = Insert.Parameters.Add("@image", SqlDbType.Image);
  imageParam.Value = fileData;
  imageParam.Size = fileData.Length;
  Insert.ExecuteNonQuery();
  sqlconn.Close();

 }


 protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
 {
  SqlCommand SqlCommand = new SqlCommand("Select [ImageID],[Image],[Name],[Description] from [Test1].[dbo].[Test_Img]", sqlconn);
  sqlconn.Open();
  SqlDataAdapter sqladap = new SqlDataAdapter();
  sqladap.SelectCommand = SqlCommand;
  DataSet ds = new DataSet();
  sqladap.Fill(ds, "ImageSet");

  RadGrid1.DataSource = ds.Tables[0];
  sqlconn.Close();

 }

 public void RadAsyncUpload1_ValidatingFile(object sender, Telerik.Web.UI.Upload.ValidateFileEventArgs e)
 {
  if ((totalBytes < MaxTotalBytes) && (e.UploadedFile.ContentLength < MaxTotalBytes)) {
   e.IsValid = true;
   totalBytes += e.UploadedFile.ContentLength;
   IsRadAsyncValid = true;
  } else {
   e.IsValid = false;
   IsRadAsyncValid = false;
  }
 }
 protected void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
 {
  if (e.Item is GridEditableItem && e.Item.IsInEditMode) {
   RadAsyncUpload upload = (GridEditableItem)e.Item("Upload").FindControl("AsyncUpload1") as RadAsyncUpload;
   TableCell cell = (TableCell)upload.Parent;

   CustomValidator validator = new CustomValidator();
   validator.ErrorMessage = "Please select file to be uploaded";
   validator.ClientValidationFunction = "validateRadUpload";
   validator.Display = ValidatorDisplay.Dynamic;
   cell.Controls.Add(validator);
  }

 }
}


Thursday, November 24, 2011

Open RadWindow from server side programming


Problem: How to open RadWindow from server side programming
Solution: It is very simple and can be done in following steps,
Step1: Create a ASPX Page which will be open as RadWindow in project e.g "Windowsvb.aspx"
The Page Must Be On Same Directory Where Your Current Page(Calling Rad Window) e.g "Default.aspx" Exist . Not Neccessary But The Code Bellow Work On This Condition

Step2: In Your Current Page "Default.aspx.vb" Write The Function.Given bellow
Protected Sub CreateWindowScript() 
        Dim window1 As New RadWindow()
        window1.NavigateUrl = "Windowsvb.aspx" ' The Path  Be Same As Created In Project
        window1.VisibleOnPageLoad = True
        window1.Width = 950
        window1.Height = 700
        window1.Modal = True
        window1.Behaviors = WindowBehaviors.Close 
        window1.Visible = True
        window1.VisibleOnPageLoad = True
        window1.AutoSize = False
        window1.VisibleStatusbar = True 
        Me.form1.Controls.Add(window1)
End Sub

'You can call this function from any event e.g Click Button Event etc

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        CreateWindowScript()
End Sub


'The DOM Which IS calling This Function Must Not BE In RadAjaxManager OR RadAjaxPanel