Search This Blog

Tuesday 28 August 2012

How to implement Collapsible panel inside listview control for MENU in asp.net/C#


Collapsible menus using listview control in ASP.Net/C#
We have already posted a blog regarding how to create Menu control in ASP.Net/C# using List view control inside a Listview control. Here we are going to demonstrate how to implement collapsible panel extender for each categories in the menu control. Most of the websites showing menu with category and subcategory list. We can create this menu as dynamic data with ASP.Net/C#. 
Dynamic menu using ListView inside another ListView Control in ASP with collapsible panel. 
For eg : If we need to implement dynamic menu control by fetching category and subcategory from the database. In this case there is n number of category so we need to use a listview for this, but each category there is also n number of subacategories so we have to implement a another ListView for this subcategory list.
Steps to use a listview inside another listview
In our scenario, there will be a category list and under the each categories, there is n number of subcategories should be display. First of all we cretaed a ListView control which is used to hold category name and list of subcategories coming under this category. For display category name, we just included a div and bounded a ‘Name’ value to this. For listing subcategories, we created another listview control inside the itemtemplate of the first listview and included the linkbutton for display subcategory name.
And also here we are giving a facility to user to expand and collapse each subgaries list by clicking category header. So if we having largest number of categories and subcategories in the menu, user can collapse unwanted categories and hence length of the menu control will be decreased. Here are the aspx  code for the implementing menu control with categories and subcategories which including collapsible panel for each subcategory section.
<div id="boxbg">
<asp:ListView runat="server" ID="RightMenuItems" ItemPlaceholderID="PlaceHolder2">
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="PlaceHolder2" />
</LayoutTemplate>
<ItemTemplate>
<asp:Panel runat="server" ID="panelCategory" CssClass="h1header" >
<div style="float: left;">
<%# Eval("Name") %></div>
<div style="float: right; margin-top: 5px; margin-right: 5px;">
<%--<asp:Image runat="server" ID="imgCollapse" />--%></div>
</asp:Panel>
<asp:ListView runat="server" ID="subMenu" ItemPlaceholderID="PlaceHolder3"
DataSource='<%# Eval("subCategories") %>'
OnItemCommand="listViewTest_ItemCommand">
<LayoutTemplate>
<asp:Panel runat="server" ID="panelSubCategory" HorizontalAlign="center" Width="100%">
<table width="100%" cellspacing="0" border="0" cellpadding="0">
<asp:PlaceHolder runat="server" ID="PlaceHolder3" />
</table>
</asp:Panel>
<ajaxToolkit:CollapsiblePanelExtender ID="ajxColapase1" runat="server" TargetControlID="panelSubCategory"
CollapseControlID="panelCategory" ExpandControlID="panelCategory" CollapsedSize="1"
Collapsed="false" ImageControlID="imgCollapse" CollapsedImage="~/images/arrow01.gif"
ExpandedImage="~/images/arrow02.gif" />
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID="lnkBtnSubMenu" runat="server" Text='<%# Eval("Name") %>' CommandName="clickSubMenu"
CommandArgument='<%# Eval("ID") %>' />
<asp:Label runat="server" ID="lblID" Visible="false" Text='<%# Eval("ID") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:ListView>
</div>
Create a structured data to binding Menu Control (Listview inside another List view Control)
In order to bind the data source to the above ListView controls, the data should be having same structure (Category List having each category child subcategory List). For achieving this we fetch the category and subcategory from the database and created a list having required structure as follows.
DataTable dtTblCategory = new DataTable();
dtTblCategory = (new eMallBL()).getCategories(0);
DataTable dtTblSubCategory = new DataTable();
dtTblSubCategory = (new eMallBL()).getSubCategories(0, 0);
IList<eMallEntity.ItemCatagory> categories =
    new List<eMallEntity.ItemCatagory>();
for (int i = 0; i < dtTblCategory.Rows.Count; i++)
{
eMallEntity.ItemCatagory category = new eMallEntity.ItemCatagory();
category.Name = dtTblCategory.Rows[i]["Name"].ToString();
category.ID = Convert.ToInt32(dtTblCategory.Rows[i]["ID"].ToString());
IList<eMallEntity.ItemSubCatagory> subCategories =
    new List<eMallEntity.ItemSubCatagory>();
for (int j = 0; j < dtTblSubCategory.Rows.Count; j++)
{
if (dtTblSubCategory.Rows[j]["CategoryID"].ToString()
    == dtTblCategory.Rows[i]["ID"].ToString())
{
    eMallEntity.ItemSubCatagory subCategory = new eMallEntity.ItemSubCatagory();
    subCategory.Name = dtTblSubCategory.Rows[j]["Name"].ToString();
    subCategory.ID = Convert.ToInt32(dtTblSubCategory.Rows[j]["ID"].ToString());
    subCategories.Add(subCategory);
}
}
category.subCategories = subCategories;
categories.Add(category);
}
RightMenuItems.DataSource = categories;
RightMenuItems.DataBind();

Tuesday 21 August 2012

How to create thumbnail image in ASP.Net/C# OR resize the image before upload in ASP.Net/C#

How to reduce the size of image before uploaded to the server in ASP.Net/C#

In most of the ASP.Net application with uploaded image facility will face the performance issue while loading uploaded images to display for the user. We can limited the maximum size of the image that a user can upload but it may not be a good solution because a user has to facing very difficult situation for uploading a large image. He has to reduce the image from other tools and upload again.
The better approach to solve this issue, we are not going to giving any maximum size limit for uploading image. Instead we are internally reducing the size of the image that a user going to upload by checking whether it is exceeds affordable size.  Then there is no constraints are given to user so that he doesn’t care about the size and quality of the image.
Image Size 764 KB
Simple steps to reduce the size of image before upload in ASP.Net/C#
 Here we are going to demonstrate a very simple and best approach to reduce the size of the image before uploaded to the server. In some application we need to show thumbnail image with uploaded images. In that case there is no need to store very large image in the server. So before going to uploading to the server, we are going to create thumbnail image or reduce the size of image as we wish using C#/ASP.net. This is very simple sample of reducing image and can be easily understand by beginners also.
Step by Step process to create an application for reducing size of image before uploaded to the server in ASP.Net/C#
 Step 1 . Create a ASP.Net project and create a web page.
Step 2.  Drag a file uploader, button and Datalist(for display uploaded images)
ASPX Page
 <asp:Panel runat="server">
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btnsave" runat="server" Text="Upload" OnClick="btnsave_Click" />
</div>
<div>
<asp:DataList ID="dtlist" runat="server" RepeatColumns="3" CellPadding="5">
<ItemTemplate>
<asp:Image ID="Image1" ImageUrl='<%# Bind("Name", "~/Images1/{0}") %>' runat="server" />
<br />
<asp:HyperLink ID="HyperLink1" Text='<%# Bind("Name") %>'
NavigateUrl='<%# Bind("Name", "~/Images1/{0}") %>'
runat="server" />
</ItemTemplate>
<ItemStyle BorderColor="Brown" BorderStyle="dotted" BorderWidth="3px"
HorizontalAlign="Center"
VerticalAlign="Bottom" />
</asp:DataList>
</asp:Panel>

Step 3 .  In page load call function ‘BindDataList’ to display uploaded images
Step 4.   On Save button click event, call function ‘GenerateThumbnails’ for reduce of image.
Code Behind Page 
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
protected void BindDataList()
{
DirectoryInfo dir = new DirectoryInfo(MapPath("Images1"));
FileInfo[] files = dir.GetFiles();
ArrayList listItems = new ArrayList();
foreach (FileInfo info in files)
{
listItems.Add(info);
}
dtlist.DataSource = listItems;
dtlist.DataBind();
}
protected void btnsave_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
string targetPath = Server.MapPath("Images1/" + filename);
Stream strm = fileupload1.PostedFile.InputStream;
var targetFile = targetPath;
//Based on scalefactor image size will vary
GenerateThumbnails(0.5, strm, targetFile);
BindDataList();
}
private void GenerateThumbnails(double scaleFactor, Stream sourcePath,
string targetPath)
{
using (var image = Image.FromStream(sourcePath))
{
// can given width of image as we want
var newWidth = (int)(image.Width * scaleFactor); 
// can given height of image as we want
var newHeight = (int)(image.Height * scaleFactor);
var thumbnailImg = new Bitmap(newWidth, newHeight);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);
thumbGraph.DrawImage(image, imageRectangle);
thumbnailImg.Save(targetPath, image.RawFormat);
}           
}
 
Image Size 36 KB
By using above application, we can reduce the size of images before uploaded to the server. If we check the size of the image that we uploaded, that will be less than the size of image that having in the local folder. We can implement this mechanism in most of the shopping site and photo gallery sites so that we can store large amount of images with small size and it will help the performance of the application. We can identify that even reducing the size of image there is no variation in quality or clarity of the image.  So we can easily reduce the resolution of the image using above code in ASP.Net/C# application.

Tuesday 14 August 2012

How to access URL or URL parts using javascript / Get the Website URL using JavaScript


How To Get URL Parts in JavaScript :: A JavaScript Tutorial For Beginners
In some scenario we need to communicate with website url that seen in address bar of the browser using JavaScript. It’s very easy to access the url using javascript. But in order to get query string from URL, default functions or methods are not available. Using javscript we can access the URL using default method in javascript. We are not able to edit URL in javascript without postback. But we can reload the page from javascript and also we can redirect to other url from javascript. Let’s see all about jaavscript with website URL.
How to get website URL in JavaScript / how do I use javascript to get url of current page
Here we are going to explain how we can use javascript to get the website url of the current page. Lets imagine our current page is http://myexample.com/example/index.html and we need to get each part of the url separately in javascript. We can access the parts of URL using javascript as follows.
window.location.protocol = "http"
window.location.host = " myexample.com "
window.location.pathname = "example/index.html"
window.location.href = "http://myexample.com/example/index.html"
If we want to access the entire website URL of the current page we can use window.location.href as mentioned above. Also we can access part by part of current page URL in javascript using above mentioned options. But there is no default option to get/access the query string values in current page URL in javascript.
 Redirect to another page using JavScript/ JavaScript redirect to a new page
 By using window.location we can redirect to another website page from javascript. So it’s better to use javascript navigation to redirect to another page instead of asp.net response.redirect function. Because Response.Redirect function first send to Server then identifying the web page that we need to navigate and again resend to client. There is a extra round trips will be happen in the case of Response.Redirect method. To avoid this round trips we can use Javascript redirection method as follows.
           window.location = “http://www.supershope.com”;
 How to access/get query string values in website URL using JavaScript (from client side)
 In order to access the querystring  of the current web page there are no default functions or methods in JavaScript.  To get URL parameters using javascript we are demonstrating a function that is used to get all the URL parameters from website in JavaScript.
 Javascript function to get all URL parameters from Website URL
 function getUrlParams() {
    var params = {};
    window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function (str, key, value) {
    params[key] = value;
});
    return params;
}
 var params = getUrlParams();
alert(params.id);
alert(params.name);
 Whenever we want to get querystring values from website URL we can call above function and which returns a object that holds all website URL parameters of the current page as key value pairs.
 How to get a particular querystring value from the URL in JavaScript
 We have noted that we cannot able to get query string from website URL in default methods in JavaScript. So we written a function to get all parameter values in the current page. But if we want to get a particular querystring values from the URL it’s difficult to use above method. That means if I want to get ‘id’ query string from the URL we need to get all parameters from the URL and from that collection get id values. Instead of this we are going to write another function which access the URL parameter name as the function parameter and return value of the particular querystring. If there is no query string in the URL with specified name will return empty string.
 Javascript function to get particular querystring value from the website URL
 function getParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}
 
var id = getParam('id');
alert(id);
 
By using above function, we can easily get particular query string from client side script. If we send a value to above function and suppose there is no query string with that name, then it will return empty string. Hence we can easily accessing query string from client side using JavaScript.

Tuesday 7 August 2012

How to get all classes and methods from a dll in ASP.Net C# using Reflection


Use of reflection in ASP.Net/How to extract dll file in ASP.Net,C#
By using Reflection class we can access all types of objects in a dll file. Now we are going to demonstrate how we can access all list of classes and methods by browsing a dll file. We can also run a particular method from the dll by passing proper parameters. We are using Reflection class to accept all types from a dll file in ASP.Net, C#.  The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.
What is Reflection in ASP.Net/C#?
  • Reflection is a collection of classes which allow you to query assembly (classes/objects) metadata at runtime. Using reflection you can also create new types and their instances at runtime and invoke methods on these new type instances.
  • Reflection enables you to find out information about types in your assemblies during runtime. Using reflection, you can find out the details of an object’s methods in terms of its access modifier ( private, public etc.), you can discover the name and types of parameters in a methods signature.
  • Reflection is the ability to read metadata at runtime. Using reflection, it is possible to uncover the methods, properties, and events of a type, and to invoke them dynamically. Reflection also allows us to create new types at runtime.
  • Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them.
How to List all classes in a dll file using Asp.Net,C# using reflection?
The following function accept dll file and extracting dll file using reflection class and return all classes in the dll file. We can call this function by dll file path as parameter then it will return all classes in the dll. In our project we are using a openfiledialog control to browse dll file and once the user select the dll file from local folder it will call below mentioned function with parameter as dll path. Then  it will return all classes in the dll file and we are displaying this list of class names in a list so that user can clearly seen all classes in the dll.
Funtion for listing all classes/types in a dll file in ASP.Net,C#
/// <summary>
/// Return all types loaded from desired DLL
/// </summary>
/// <param name="dllName">The DLL in which to parse and get the types from</param>
/// <returns>A filled ArrayList object containing all types </returns>
public ArrayList GetAllTypesFromDLLstring(string dllName)
{
Assembly _Assemblies = null;
try
{
_Assemblies = Assembly.LoadFrom(dllName);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain assemblies from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
ArrayList _Quit = new ArrayList(1);
_Quit.Add("QUIT");
return _Quit;
}

Type[] _AllTypes = _Assemblies.GetTypes();

ArrayList _Temp = new ArrayList();

foreach (Type t in _AllTypes)
{
_Temp.Add(t.ToString());
}

return _Temp;
}
 
How to access all methods in a dll file in ASP.Net,C# using reflection library
Next we are going to access all methods in a class in the dll file. Here we have to pass dll file patha and class name to list all methods. The output will be the list of all methods in the particular class in the dll file.
Function for listin all methods in a class from dll file using reflection in ASP.Net,C#
/// <summary>
/// Returns all method names from desired DLL/Class
/// </summary>
/// <param name="dllName">The DLL in which to parse for desired class</param>
/// <param name="className">The class in which to parse for all methods</param>
/// <returns>An ArrayList of each method from desired class</returns>
public ArrayList GetAllTypesFromClass(string dllName, string className)
{
Assembly _Assemblies = Assembly.LoadFrom(dllName);

Type _Type = _Assemblies.GetType(className);

ArrayList _Temp = new ArrayList();

try
{
MethodInfo[] _Methods = _Type.GetMethods();

foreach (MethodInfo meth in _Methods)
{
_Temp.Add(meth.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain methods from " + dllName);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
_Temp.Clear();
_Temp.Capacity = 1;
_Temp.Add("QUIT");
}

return _Temp;
}

Is it possible to run a method in the dll file at run time in ASP.Net,C# using reflection ?
Yes, we can run a particular method in a dll file from our ASP.Net/C# application using reflection library at run time. Let’s see how we can run a method in the assembly file. The below mentioned function demonstrates how we can run a particular method from the asp.net,c# application at run time.
Function to call/run a method/function in a dll file from ASP.Net/C#  using reflection at runtime
/// <summary>
/// Runs target Method from target Class from target DLL.
/// </summary>
/// <param name="dllName">The DLL to load and use parse for methods</param>
/// <param name="className">The class to load from specific DLL</param>
/// <param name="methodName">The method to call from class</param>
public void RunClass(string dllName, string className, string methodName)
{
// Create the assemblies from our current DLL.
Assembly _Assemblies = Assembly.LoadFrom(dllName);

// Get the type that we want from the assemblies.
//  IE: This would be the fully qualified class name (including namespace)
//  Example: "Reflectionism.Examples.Example1" or "Reflectionism.Examples.Example2"
Type _Type = null;
try
{
_Type = _Assemblies.GetType(className);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain classrd from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}

// Get the desired method we want from the target type.
MethodInfo _MethodInfo = null;
try
{
_MethodInfo = _Type.GetMethod(methodName);
}
catch (Exception ex)
{
Console.WriteLine("\n\nError - couldn't obtain method " +
    methodName + " from " + className);
Console.WriteLine("EXCEPTION OUTPUT\n" + ex.Message + "\n" + ex.InnerException);
return;
}

// The first parameter to pass into the Invoke Method coming up.
Object _InvokeParam1 = Activator.CreateInstance(_Type);

// This calls the target method ("DisplayMyself").
//  NOTE: I'm not passing any arguments down to the method being invoked.
//  Therefore, I'm passing null as my argument, otherwise Invoke takes an
//  array of Objects.
_MethodInfo.Invoke(_InvokeParam1, null);
}
}
}
Hence we have discussed all possibilities regarding reflection in asp.net/c# such as how to access types/classes from dll file, how to get/access methods/functions from dll file/assembly using reflection in asp.net, possible way to call/run a method/function in the dll from asp.net/c# at run time. We hope you got a needful help from this post. Thanks..