How to format GridView or DataGrid Using JQuery

by Viper 14. July 2009 14:12
datagrid using jquery

Download Sample Project

This is based on a question asked by one of my blog readers.

I have 2 datagrids. Each Grid has the same amount of columns and each grid has a select column as the last column on the right added from the "gridview/ edit Columns/ CommandField/ Add" sequence. The first GridView has the Select column as a Link The second GridView has the select Column as a button I want to be able to change the text for both the Link and button in cell(4), setting them to the value in cell(1) from the same row using the GridView_RowDataBound event. However, using "cell(4).text = cell(1).text" just overwrites the text value removing the hyperlink and button.

The behavior described in this question is as expected. When you set text of a cell in grid, it directly affects HTML that is going to be rendered. When you set text value of a cell, it means that you are setting innerText of the cell. The column that GridView creates for command fields (Edit, Delete and Select) are a (anchor) or button elements. So you can see what will happen if you set text value in that cell. It will wipe out those link or button controls and replace them with simple text string.

There are properties like EditText, DeleteText and SelectText for CommandField column in grid view. If you try to set these values using a server side method by passing it DataContainer object, you will get following exception thrown.


Databinding expressions are only supported on objects that have a DataBinding event. 
System.Web.UI.WebControls.CommandField does not have a DataBinding event.

After looking at the requirements, i realized that requirements are as simple as replacing text with value from another cell in the same row. There is no need for doing any server side tricks or things like that. I can simple put together a simple client side java script that will take values from cell 1 and put them in whatever cell I want. Abd I came up with this small javascript solution using jQuery. This small code snippet shows how you can manipulate GridView or DataGrid on client side using jQuery. Let me show you the client side javascript that I added on the page. Then I will explain what this code is doing.


<script type="text/javascript">
function updateCommandLinks() {
 var $gridTable = $('#productsGrid');
 var rows = $gridTable.find('tbody > tr');
 var slicedRows = rows.slice(1, rows.length - 2);
 slicedRows.each(function() {
  var cells = $(this).find('td');
  var cellElem1 = cells.get(1);
  var cellElem5 = cells.get(5);
  $(cellElem5).find('a').each(function() {
   $(this).addClass('commandlink').append(" " + cellElem1.innerText);
  });
 });
}

$(document).ready(function() {
  updateCommandLinks();
});
</script>

The above code may look little verbose considering you can write very concise code using jQuery. But for sale of explaining and debugging, I decided to make it little bit verbose. I am sure you can reduce it to half the lines of code that I have written.

The implementation adds a handler for document load event. In that event handler here are the steps it follows:

  1. Finds the element that has id of productsGrid. In our case, that is HTML element ID of our grid view.
  2. In the table, it gets collection of all the rows, identified by tr tag.
  3. Since in my implementation I have header and pager, that adds three rows into the collection. One top row for the header and then the last row itself will contain another table that contains a row for paging elements. To keep it simple, I decided to use slice function to remove first and last 2 rows from collection. You will need to modify this implementation depending on your grid rendering.
  4. It iterates over each row in the collection.
  5. For each row it then finds all cells, identified by td tag.
  6. In my case, I want to replace text in command links with text from second column. So I saved reference to cell at index 1 by using get function.
  7. Then I extracted all elements with tag a from sixth column.
  8. Then it iterates over collection of anchor a tags and appends text from second cell to text in each of the links.

I think that is a simple implementation that serves the purpose without making any changes on the server side. The attached project has the complete implementation for this grid. This is a Visual Studio 2010 project. But you should be able to copy the script from the page to your implementation.

Give your advice to big bosses and make money

Views: 2022

Tags: , , ,

ASP.Net | DataGrid | GridView | JQuery

How to format and modify value in data grid row at run time based on previous row values

by Viper 7. July 2009 14:35
grid view row formatting

Download Sample Project

This was a question was asked by one of my site visitors, Mike. Following is the text of the question:

This is a similar question to one you have already answered in formatting Grid Views. However there are 2 main differences. First: I want to change the value of a column (not the format) in any row if the row preceding it has a certain value in the same column.

This question translates to How do you change value of a data grid column based on values of previous row(s). I generalized this question to cover all previous rows and not just the preceding row. Answer to all such questions relies on handling events like RowDataBound or RowCreated events. When a data grid or grid view renders, RowDataBound fires when row is being data bound and then RowCreated is fired after it has been data bound and row has been created. So depending on at what stage of rendering you want to change behavior of a row, you will subscribe either of these events. In the sample project, I am subscribing to RowDataBound event.

Next step is to access values from previous rows. Here you have choice. One, you can keep some local vaiable that stores values from previous row(s) and then use them in current row event handling. Two, you can access the previous GridRow based on index. In this sample i will discuss the approach of accessing previous row based on index and then extracting values from certain cells.

In RowDataBound event handler, GridViewRowEventArgs provides you access to DataItem associated with current row only. You do not have access to DataItem associated with previous rows. But at this point, previous rows have been prepared for rendering. You have access to all the cell values associated with previous row. You can access GridRow object of previous rows and extract text from cells that you are interested in. In the sample project, I am accessing ListPrice from fourth column and then displaying it in current row along with price associated with current row. Well, this does not sound like something that is very interesting or useful. But it serves the purpose of demonstrating you will accomplish the task.

Here is the code snippet from sample project.


protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  double price = -1.0;
  double prevPrice = -1.0 ;
  // Access the previous row.
  if (e.Row.RowIndex != 0)
  {
   GridViewRow prevRow = this.productsGrid.Rows[e.Row.RowIndex - 1];
   if (null != prevRow && 
    prevRow.RowType == DataControlRowType.DataRow)
   {
    double.TryParse(prevRow.Cells[3].Text, out prevPrice);
   }
  }
  var thisRowData = e.Row.DataItem as DataRowView;
  if (!Convert.IsDBNull(thisRowData["ListPrice"]))
  {
   double.TryParse(thisRowData["ListPrice"].ToString(), out price);
  }
  var ctrl = e.Row.FindControl("prevPriceLabel") as Label;
  if (null != ctrl)
  {
   ctrl.Text = string.Format("{0} - {1}", prevPrice, price);
  }
 }
}

The attached sample project is a VS2010 project. There is no VS2010 or .Net4.0 implementation in the project. So if you are using VS2008 or prior, you should be able to copy the implementation files into your own project.

Feel free to send me any request for any other grid view implementation you would like to be answered or implemented.

Give your advice to big bosses and make money

Views: 2193

Tags: , ,

.Net | ASP.Net | C# | DataGrid

How to insert google map in DataGrid or GridView

by Viper 2. July 2009 05:08

Download Sample Project

While working on a car dealership listings web site, I was experimenting with inserting google maps into the data grid. The grid will show name and address of top rated car dealers in certain categories. And along side their information, it will show their location on google map. To accomplish this task, I needed the longitude and latitude of car dealership's address or location. Some time back in my earlier post Convert Address and/or IP address to Geo Location I described how you can utilize google map's api to convert a physical address to geo location coordinates. This is the same technique that I used in Backyardtweets to show tweets in a specified location. So use the google map api to get these coordinates and insert these coordinates in the java script.

Now that you have geo location corresponding to an address, your task is to insert that little piece of java script in each row of the data grid. The way google map java script works is that it requires a HTML element where it can insert the map image. So I inserted a div with unique id in a cell in each row and then passed that unique id to java script that is used to render the map. Add an event handler for RowDataBound event and there you can add the element and register a client script for map as well. Here is some code snippet that shows how this all is accomplished.


protected void OnDealerRowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
	var carDealer = e.Row.DataItem as CarDealer;
	var divId = string.Format("dealloc_{0}", carDealer.Id);
	var mapPanel = e.Row.Cells[2].FindControl("mapPanel") as Panel;
	var div = new HtmlGenericControl("div");
	div.Attributes.Add("id", divId);
	div.Attributes.Add("class", "mapdiv");
	mapPanel.Controls.Add(div);
	string js = GetGoogleMapScript(carDealer, divId);
	ScriptManager.RegisterStartupScript
	  (this.Page, this.GetType(), "_map_" + carDealer.Id, js, true);
 }
}

private string GetGoogleMapScript(CarDealer dealer, string ctlId)
{
 string loc = string.Empty;
 if (!string.IsNullOrEmpty(dealer.State))
 {
	loc = string.Format("{0},", dealer.State);
 }
 loc += dealer.Country;
 decimal longitude, latitude;
 GoogleMapUtility.GetGeoLocationFromGoogle(loc, out longitude, out latitude);
 dealer.Location.Latitude = latitude;
 dealer.Location.Longitude = longitude;
 return GetJScriptForGeoLocations(longitude, latitude, ctlId);
}

public static string GetJScriptForGeoLocations(decimal longitude, decimal latitude, string elemId)
{
 StringBuilder sb = new StringBuilder();
 sb.Append("function initialize_" + elemId + "() {{");
 sb.Append(" if (GBrowserIsCompatible()) {{ ");
 sb.Append(" var map = new GMap2(document.getElementById(\"{0}\"));");
 sb.Append(" map.setCenter(new GLatLng({1}, {2}), 13);");
 sb.Append(" map.setUIToDefault();}}}} initialize_" + elemId + "();");
 return string.Format(sb.ToString(), elemId, latitude, longitude);
}

The attached project with this post has all the implementation for this sample implementation. And this is a Visual Studio 2010 project. I have not used any 2010 specific namespaces or code in this implementation so you should be able to take all the code and move it into a VS2008 or VS2005 project. And you will need to get key for google map api use from google as well.

Give your advice to big bosses and make money

Views: 6374

Tags:

ASP.Net | DataGrid | GridView

Health Monitoring, Diagnostics, Logging and Instrumentation in ASP.Net

by Viper 18. May 2009 09:20

Troubleshooting, diagnostics and instrumentation is as big a part of the project is as the development of the application itself. Lot of time I have seen projects that do not account for these integral parts of the application development cycle. And when applications run into issue during production, then they do not any means to diagnose the problems quickly and come up with a solution with minimal downtime. In all the projects that I have lead, I put considerable effort in putting lot of diagnostics and health monitoring in place so that when ever there is error in the application we can identify the issue just by looking at log files.

In the past I have used frameworks like log4net and MS Instrumentation ans Logging Blocks to add logging and instrumentation capabilities to ASP.Net applications. Last week while I was researching on a new framework to add logging into an existing application I came across a less known healthMonitoring entry in web.config file of ASP.Net application. When I start digging deep into this I realized that ASP.Net framework already has a very flexible and robust mechanism built into it for logging and instrumentation. I realized that just by adding few entries in web.config file I can get the application to report all unhandled exceptions into a SQL server, Event log or WMI provider. And by writing a custom plugin I can get these to report to my custom repository. Long story short, you really don't need to use any third party plug ins or libraries to add logging capabilities to your ASP.Net applications. Just look at classes offered under System.Web.Management and healthMonitoring entry in web.config file of your ASP.Net applications and you will be able to find lot of information on how to add health monitoring capabilities like logging and instrumentation into your ASP.Net applications.

In next posts and articles I will describe how to use this ASP.Net feature to enable logging and instrumentation for your application and use different providers with it.

Give your advice to big bosses and make money

Views: 772

Tags: , ,

ASP.Net | Diagnostics

How to enable SQL server based session state for ASP.Net

by Viper 13. May 2009 08:03

For high performance web applications caching of data plays a significant part in improving performance. We all use session or application cache to store data in one form or the other. By default ASP.Net is configured to use InProc session storage mechanism. What this means is that all session data is stored in-memory on web server that is serving ASP.Net application. But when you are developing high availability web applications, you will find your self hosting your web application across web farms or web gardens in network load balanced systems. What this means is that user requests are served from multiple web servers. And load-balancer will pick the web server based on some internal load balancing algorithm. Unless you use stick IPs, you don't have control on what web server will be picked for next request. So if you are using InProc mechanism for session state management, you have a problem. Your session state is saved on one web server where as next request may be served from different server. So you end up loosing session state for that request. This is where you will need to use an external storage for storing session state that can be accessed across multiple servers.

ASP.Net framework provides mechanism to use SQLServer as an option that you can set in sessionState settings in your web application's configuration. Before you can start using sql server to store and server session state, you will need to set up some tables and means to store this data in SQL server. When you install ASP.Net framework on your server, Microsoft provides some SQL scripts along with an installer application that helps you in preparing your SQL Server for session state management.

If you look in WINDOWS\Microsoft.NET\Framework\{Version}, you will find an executable with name aspnet_regsql.exe. This is the same executable that you may have used to install membership and personalization database. If you supply specific command line parameters to this executable it will install required tables and database to manage session state. A very simple command to install session related database and tables can look like as below

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regsql.exe -ssadd -sstype p -E
Start adding session state.
....
Finished.
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>

You will find a new database named ASPState in your SQL server now. You can have more control on creation of this database by using appropriate command line options. Following is list of options that you can use.

-- SESSION STATE OPTIONS --

-ssadd                  Add support for SQLServer mode session state.

-ssremove               Remove support for SQLServer mode session state.

-sstype t|p|c           Type of session state support:

                        t: temporary. Session state data is stored in the "tempdb"
                        database. Stored procedures for managing session are installed in
                        the "ASPState" database. Data is not persisted if you restart
                        SQL. (Default)

                        p: persisted. Both session state data and the stored procedures
                        are stored in the "ASPState" database.

                        c: custom. Both session state data and the stored procedures are
                        stored in a custom database. The database name must be specified.

-d <database>     The name of the custom database to use if -sstype is "c".

Once you have created the database for session state management, modify web.config file of your application to start using SQLServer mode for session state management.

<sessionState 
    mode="SQLServer"
    sqlConnectionString="data source=127.0.0.1;
        user id=<username>;password=<strongpassword>"
    cookieless="false" 
    timeout="20" 
    />

Important step

After you uninstall SQL Server mode session state management configuration, you must restart the w3svc service. To restart the w3svc process, type net start w3svc at a command prompt.

Give your advice to big bosses and make money

Views: 820

Tags:

ASP.Net

How to add meta tags for a web page dynamically

by Viper 27. February 2009 20:51

If you are using some Content Management System (CMS) for your web site, then there is good chance that all your content along with meta tag content like Title, Description, Keywords etc. is stored in some data source and need to be added to the page dynamically. This all is doable from server side using HtmlMeta html server side control to Controls collection of Header of your page. You just need to add head element to your page and make sure that you have set runat=server for it and you are good to go. See the following snippet how it is done.


protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {
  this.Header.Title = "My Page Title";
  HtmlMeta meta = new HtmlMeta();
  meta.Content = "my description for this page";
  meta.Name = "description";
  this.Header.Controls.Add(meta);
 }
}

And on the page I have defined the mark up like this.


<head runat="server">
    <title></title>
</head>

Give your advice to big bosses and make money

Views: 1652

Tags:

.Net | ASP.Net | SEO

How to bind a control on page to DataSource directly

by Viper 27. February 2009 19:50

A lot of time we have lot of controls on our ASP.Net page that are directly bound to data object for which page is being rendered. For example you may be implementing a page to display some details of a product. All the data that you want to display comes from a database record. You can directly bind all the information on the page directly with the data source using FormView on the page. If you don't intend to edit and update the data, you don't have to specify EditTemplate etc. You can simply have ItemTemplate for FormView and display data in read only format. Following snippet shows how this can be done.


<asp:FormView ID="FormView1" runat="server" CellPadding="4" 
	DataKeyNames="CategoryID" DataSourceID="SqlDataSource3" ForeColor="#333333">
	<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
	<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
	<ItemTemplate>
		CategoryID:
		<asp:Label ID="CategoryIDLabel" runat="server" 
			Text='<%# Eval("CategoryID") %>' />
		<br />
		CategoryName:
		<asp:Label ID="CategoryNameLabel" runat="server" 
			Text='<%# Bind("CategoryName") %>' />
		<br />
		Description:
		<asp:Label ID="DescriptionLabel" runat="server" 
			Text='<%# Bind("Description") %>' />
		<br />
 </ItemTemplate>
</asp:FormVi

If you have an image to display, you can add Image control inside template and bind ImageUrl property to one of the columns of the data source that contains url for your image.

Give your advice to big bosses and make money

Views: 1058

Tags: ,

ASP.Net | FormView

Blogengine updated to use post and page titles different from Url to make it SEO friendly

by Viper 18. February 2009 05:54

Last week I added a new page to my blog site. The article was very popular and lot of people bookmarked it as well. After 3 days I realized that there is typo in the title that I need to fix. So I made the change. After few minutes of making the change I started getting flood of emails about broken link from the people who bookmarked that article. Then I realized that BlogEngine.net generated URLs for posts and pages based on Title field. So if you change the title of the item, your URL changes as well. Well there are following problems I see with this approach.

  • Biggest problem is that URL changes if title changes. That would mean that you will have keep track of where you have used this URL internally and externally and update them.
  • If i specify a very long title for my post or page, I will have a gigantic URL. This is not something that is recommended in best practices of URL creation.
  • Now to keep the URL to manageable length, I will have to come up with short titles that explain what the page or post is all about. Well, in some cases you want to have a title that is little bit more descriptive for SEO purposes

After thinking through this, I decided to make change in BlogEngine.net to include a new field named MetaTitle for pages and posts.

This new field allows you to enter a title that is different from what is used to create URL of that post or page. And when you want to update title of the item, you just need to update MetaTitle and never have to worry about URL change because you changed title. You can still change Title field, but it will result in a new URL for your page or post.

You can download the updated code from BlogEngine.Net Update 1.5.3. This update requires change in SQL Server tables. The updated script has been appended at the bottom of the page. I will post that update here as well. This update requires addition of new field MetaTitle in be_Pages and be_Posts tables.


/* Script for MetaTitle features */
ALTER TABLE [dbo].[be_Pages]
 ADD
 [MetaTitle] [nvarchar](255) NOT NULL DEFAULT (N'')
GO
 UPDATE [be_Pages]	SET [MetaTitle] = [Title]
GO
ALTER TABLE [dbo].[be_Posts]
 ADD
 [MetaTitle] [nvarchar](255) NOT NULL DEFAULT (N'')
GO
 UPDATE [be_Posts]	SET [MetaTitle] = [Title]
GO

Admin pages Add_Entry and Pages have also been updated to include new text box for MetaTitle field. And all the core code has been updated to account for new database field as well. If you have any feature that you would like implemented or modified, please feel free to contact me. I will be glad to work with you on the changes.


BlogEngine.Net Custom Updates
Give your advice to big bosses and make money

Views: 2225

Tags: ,

ASP.Net | Blog Engine | SEO

New Widgets Added To BlogEngine

by Viper 8. February 2009 11:09

Based on the last update where I added ability to make pages in blogengine first class citizens, it became too much to list most viewed posts/pages, categories of posts and pages separately. They were taking too much vertical space in widget zone. So I decided to create new widgets that use tabbed views. See the following snapshots of most categories and recent items widgets.

These widgets are implemented using Yahoo User Interface (YUI) library. You don't have to worry about carrying these java script files on your server. You can just reference them directly from YUI site. You can add these references in master file of your theme. See site.master file in Blues theme to see how these references were added.

Following code package contains all the updates that were done to BlogEngine since last official code release from original site.

Download Latest BlogEngine (modified) Code (~2MB))

Give your advice to big bosses and make money

Views: 2770

Tags:

ASP.Net | Blog Engine | Social Networking

Adding Custom Social Link Sharing ASP.Net Control To BlogEngine

by Viper 5. February 2009 12:04

I got little tired of adding these social networking site post sharing links to my themes. And I saw that there were few web sites offering these ShareIt or AddIt buttons. Well, I decided to create my own custom control for it. Please see the following link for more details about the control and how to use it instructions. There is little piece of code that you will need to add to PostView to get to use title of your posts as well as URL. Notice that in following code, I have added a server side script that overrides RenderControl method to set LinkTitle and LinkUrl properties of ShareLink control. If you don't add this piece of code, the control will still work but it will pick up URL and title of page from client side. More details as present in the article.

Custom Link Sharing ASP.Net Control

<script runat="server">
public override void RenderControl(HtmlTextWriter writer)
{
socialShareLink.LinkUrl = Post.AbsoluteLink.AbsoluteUri;
socialShareLink.LinkTitle = Post.Title;
base.RenderControl(writer);
}
</script>

You can download PostView.ascx from the site and see how it is used. All other steps are same as described in article for the control.

Download PostView.ascx (1.60 kb)

Give your advice to big bosses and make money

Views: 3084

Tags: ,

ASP.Net | Blog Engine | Custom Controls | Social Networking

Blogengine updated to include lot of new features

by Viper 2. February 2009 19:39

I have updated BlogEngine.Net to include following new features.

  • Added ability to assign categories to pages
  • Added new widget PostCategoryList that lists pages by category.
  • Added display of pages by category very much like the way currently posts are displayed by category. The difference is that the page only displays the link to the pages and does not display any details related to the pages. You can click on those links to get to the pages.

You can see all these changes in action on this site itself. Look at bottom right of the page where Articles by Category widget is displayed. This is the new widget that I added with this update.


There were too many changes in the core and web application implementation that I did not see it practical to create a svn patch. Just to keep the whole implementation separate from what is available on BlongEngine site, I have created a fresh package with all the latest code from BlogEngine.Net repository and my changes and named it BlogEngine 1.5.1

I have added changes to SQL script in MSSQLUpgradeTo1.5.0.0From1.4.5.0.sql that is present in "setup/SqlServer" folder.

I will be making more changes to this package to include some more new features and post them here.


Download BlogEngine_1_5_1(1.55 mb)

Give your advice to big bosses and make money

Views: 25188

Tags:

ASP.Net | Blog Engine

Added Most Viewed Posts Widget In BlogEngine

by Viper 1. February 2009 09:08

Finally i got around to adding new widget to BlogEngine.Net to display most viewed posts. I also added a new field in the database to track views of pages as well. And in a day or two I will add new widget to display most viewed pages as well. Here is list of changes to the code.

  • Updated be_Pages SQL table to include new column Views and two new entries be_Settings table for most viewed posts and page count.
  • Updated BlogSettings.cs to include new properties NumberOfMostViewedPosts and NumberOfMostViewedPages
  • Updated Page.cs file in Data provider project to include new property Views
  • Updated DbBlogProvider.cs to update CRUD metods for Page to manipulate page views count
  • Added new folder MostViewedPosts that contains implementation of new widget.

How to use new widget

Unzip MostViewedPosts.zip file into Widgets folder. Run sql update script to add new field and values in tables. And then apply the code patches.

Following is list of files that you will need to download to add new widget to your existing installation.

SVN Code Patch [BlogEngine_MostViews.patch]

Widget Files [MostViewedPosts.zip (2.44 kb)]

SQL UPdate Script [Sqlupdate.sql (297.00 bytes)]

Give your advice to big bosses and make money

Views: 4451

Tags:

ASP.Net | Blog Engine

Set name attribute for HtmlInputHidden or hidden input control

by Viper 28. January 2009 12:26

While developing a custom control I discovered a very important thing related to how all key value pairs in FORM on a page get named and added. I had a hidden input field added to the page. I was only setting ID of the control but was not specifying the name attribute for it. On PostBack i was not getting my field back. May be I was but i did not see any key named as "name" that I specified for the control. Then I set "name" attribute for the control, and I was able to get the value set in that hidden input field back during post back.


HtmlGenericControl selectedObjField = new HtmlGenericControl("input");
selectedObjField .Attributes.Add("type", "hidden");
selectedObjField .Attributes.Add("id", "_selected_cms_list");
selectedObjField .Attributes.Add("name", "_selected_objs_list");
mainPanel.Controls.Add(selectedObjField );


if (this.Page.IsPostBack)
{
 string selectedCMs = this.Page.Request["_selected_objs_list"];
 if (!string.IsNullOrEmpty(selectedCMs))
 {}
}
Give your advice to big bosses and make money

Views: 1170

Tags:

.Net | ASP.Net

BlogEngine modified to include Post view count

by Viper 27. January 2009 06:16

I have modified latest version of BlogEngine.Net to record number of times a post has been viewed and then display it on the post itself. I did the following things to make this change:

  • Add a new field Views in be_Posts table to record view count. You can use following SQL query to update the existing table in SQL database.
    
    update table [dbo].[be_Posts]
      Add [Views] [int] DEFAULT(0)
    
    
  • Updated code in DbBlogProvider.cs to include column in all CRUD operations.
  • Updated Post.cs to include new property Views and a method to increment view count and then update that post in database.
  • Updated Post.aspx.cs in web application to call Viewed method on Post to increment view count.
  • Finally added a small piece of code in PostView.ascx to display view count.

I have attached SVN patch file that has the changes to latest code available from codeplex.

BlogEngine_View.patch (5.79 kb)

Give your advice to big bosses and make money

Views: 4551

Tags:

ASP.Net | Blog Engine

How to supply start parameters for Silverlight application in querystring

by Viper 18. January 2009 20:21

In my article Supply Parameters in InitParams I explained how you can make use of InitParams. But a lot of time, like traditional web applications, we want to specify start parameters or want to drive behavior of page based on some parameters specified in query string. Silverlight application does allow you to do so. Well it is not something specific to Silverlight application. You can access query string any time in your application using Document object of HtmlPage. Following code snippet shows how in my application I switch initial navigation of my application to specific page based on nav query string parameter.


private void Application_Startup(object sender, StartupEventArgs e)
{
if (HtmlPage.Document.QueryString.ContainsKey("nav"))
{
 string navAction = HtmlPage.Document.QueryString["nav"];
 switch(navAction)
 {
  case "Products":
  // Switch navigation to Products page
  break;
  case "Service":
  // SWitch navigation to Services page.
  break;
  default:
  // Switch navigation to default page
  break;
 }
}
this.RootVisual = new Page();
}

Unlike QueryString property in ASP.Net, you can not access querystring parameters by Item accessor. If you will try to access a querystring parameter using following code snippet, KeyNotFoundException exception will be thrown if that parameter is not present in query string.

Give your advice to big bosses and make money

Views: 1017

Tags:

ASP.Net | Silverlight

Manually resetting theme of BlogEngine.Net

by Viper 14. January 2009 06:25

I was experimenting with themes that are provided with BlogEngine.Net. I liked how Fresh looked. So i decided to use it. So I hit apply and all is well and good. Now I wanted to add a blog entry. I could not find Login link on the page anywhere. And now I had noway to reset the theme that has login button. So i looked around and found the table be_Settings. There is a column in there with name SettingName which has names of all the settings and their corresponding values. There is a row with Theme setting name. Here you can alter the value of this setting to whatever theme you want. Obviously you have to have that theme on your server :-)

Give your advice to big bosses and make money

Views: 965

Tags:

ASP.Net | Blog Engine

Setting ApplicationKey and SecretKey in Faceboot.Net library for FaceBook application

by Viper 12. January 2009 13:11

There are 2 unique pieces of information that are used in development of FaceBook application, Application Key and Secret key. When you are using Facebook.Net development kit for building FaceBook applications in ASP.Net, these 2 values are specified in configuration file under facebook section. If you do not specify these values in configuration file, your application will throw InvalidOperationException. Facebook.Net library tries to verify these 2 pieces of infomation very early in the stage during PagePreLoad event. If you don't feel comfortable leaving this information in configuration file and want to set it programatically, you can provide override method for OnInit in your page and set the values there.


protected override void OnInit(EventArgs e)
{
  base.OnInit(e);
  if (string.IsNullOrEmpty(MyFaceBookApp.Secret))
  {
     MyFaceBookApp.Secret = "xxxxxxxxxxxxxxxxxxxxxxx";
  }
  if (string.IsNullOrEmpty(MyFaceBookApp.ApplicationKey))
  {
     MyFaceBookApp.ApplicationKey = "xxxxxxxxxxxxxxxxxxxxxxxx";
  }
}

Give your advice to big bosses and make money

Views: 1598

Tags:

ASP.Net | FaceBook

How to display row number in Row header of DataGrid

by Viper 12. January 2009 08:17

Lot of time you want to display line number (row index) of rows in DataGrid in Row header of your grid very much like how each row in Microsoft Excel displays line number. One dirty solution is to add a new column in the grid at first position and then display its text as row number. There is more elegant solution available. You can actually set the Row.Header value to Row index in LoadingRow event of your grid.

protected GridRowLoading(object sender, DataGridRowEventArgs arg)
{
  arg.Row.Header = arg.Row.GetIndex();
}

Make sure that you set HeaderVisibility property of your grid to "Row" or "All". By default row header is not visible.

Give your advice to big bosses and make money

Views: 3189

Tags:

ASP.Net | Silverlight | DataGrid

ADO.Net Dataservice Error: Request Error Server Encountered an error processing request

by Viper 5. January 2009 09:03

I was working on a silverlight application that was connecting to an ADO.Net dataservice on my server. All of a sudden I started getting following error.

Request Error: The server encountered an error processing the request. See server logs for more details

I looked at event logs and sql server logs. I could not find anything wrong in the logs. Then I started thinking back to figure out what did I change in service that may have caused anything to break. Only thing I remember changing was that sql connection was changed from windows authentication to sql authentication. I looked at connection string and everything looked fine there as well. I tested the credentials and they were fine. After banging my head for few minutes I tried couple of URL in service and nothing worked. I fired up SQL profiler and started monitoring the requests. I did not see a single query making into it from ADO.Net data service. I looked at connection string again and there you go. There was typo. Instead of "User ID" I had typed "UserID" to provide login name. After I fixed that, everything worked like a charm.

You can see that error message from data service was not very helpful. So every time you run into this obscure error, make sure that you check names in query strings etc. to make sure there are no typos.

Give your advice to big bosses and make money

Views: 4052

Tags: ,

ASP.Net | Silverlight | ADO.Net | DataService

Silverlight support in FireFox is not very stable

by Viper 1. January 2009 10:34

This morning I was trying to set up a new web site to host some silverlight applications. I went through all the steps to set up the site and then fired up the demo page in FireFox 3.0.5. To my surprise page kept coming back empty all the time. When I looked at the source of the page, I could see all the markup and JavaScript that was required to run silverlight applications. I thought that I forgot something to do on web server to support silverlight applications. I went through my check list and saw i have done all the things. Then I fired up web site in Chrome. The application came up nicely and same thing in Internet Explorer. I looked at the plugin lists in FireFox and saw that Silverlight is installed. So much for cross-browser/cross-platform framework. From what I could see that behavior of silverlight applications is very flaky in Firefox. Oh well!

You can try the following demo application I created for another article on silverlight communication between plugins.

Silverlight Cross-plugin communication

Give your advice to big bosses and make money

Views: 1312

Tags:

ASP.Net | Silverlight | Visual Studio

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories