Google
Web Netomatix

How to set cursor position in text box and handle enter key to submit page

by Admin 2. September 2010 05:44

While implementing a high performance search functionality for a site, I ran into some interesting issues with some UI aspects. So I thought I would share it with everybody so you have answers to some of the following questions when you run into similar issues.

  • How to set focus in text box at page load time

    This is a very common requirement that when you are implementing a search box for your site, you want the users to be able to start typing in search keywords when the page load. Well it is pretty simple by using a small javascript on the page. Since Microsoft shipd jQuery with Visual Studio now and jQuery provides very concise implementation of some very common tasks, so I used jQuery to accomplish the task. Following snippet shows how to use jQuery to set focus on text box.

     $(document).ready(function () {
     	var keywordTextBox = $get("<%=keywordTextBox.ClientID%>");
     	keywordTextBox.focus();
     }
    

    Yes, I could have done whole thing in one line instead of storing the element in local variable first. But I needed this element for some other user as well. Soon you will see why. The code simple translates to when document has been loaded and DOM is ready get text box html element and call focus method to set focus on it.

  • How to set cursor position at end of text in text box

    Now that you have seen how to set focus on text box, next thing you will run into is that when page post backs when you have text in search text box, the focus is set on the text box but it is set at the start of the text. What you are really looking for is that when you have some text in text box, the focus should be set at the end of the text so user can either continue with what is already there or start deleting for a new search term. The following snippet shows how you can use setSelectionRange or createTextRange depending on browser, javascript method on text box to set the cursor at the end of the text in text box. Or for that matter you can use this technique to set cursor in text box at any position.

    $(document).ready(function () {
    try {
      var keywordTextBox = $get("<%=keywordTextBox.ClientID%>");
      if (null != keywordTextBox) {
          var pos = keywordTextBox.value.length;
          if (keywordTextBox.setSelectionRange) {
             keywordTextBox.setSelectionRange(pos, pos);
          }
          else if (keywordTextBox.createTextRange) {
            var textRange = keywordTextBox.createTextRange();
            textRange.collapse(true);
            textRange.moveEnd("character", pos);
            textRange.moveStart("character", pos);
            textRange.select();
          }
          keywordTextBox.focus();
       }
    });
    
  • How to handle enter key click in text box to submit page

    Now that we have set focus in text box. Now your user should be able to enter some text in the text box and hit ENTER key to perform search. Following code snippet shows how you can hook key events of your text box to look for ENTER key press and then submit the page.

    $(document).ready(function () {
    try {
      var keywordTextBox = $get("<%=keywordTextBox.ClientID%>");
      if (null != keywordTextBox) {
          var pos = keywordTextBox.value.length;
          if (keywordTextBox.setSelectionRange) {
             keywordTextBox.setSelectionRange(pos, pos);
          }
          else if (keywordTextBox.createTextRange) {
            var textRange = keywordTextBox.createTextRange();
            textRange.collapse(true);
            textRange.moveEnd("character", pos);
            textRange.moveStart("character", pos);
            textRange.select();
          }
          keywordTextBox.focus();
           $("input").keydown(function (e) {
           if (e.keyCode == 13) {
             __doPostBack("<%=searchButton.UniqueID%>", "");
            return false;
           }
          });
       }
    });
    

    The above code javascript snippet demonstrates all three features of handling various text box features together. You can see all this in real action at the following page.

Live Demo Of Text Box Features

 

Views: 24

Tags: ,

ASP.Net | JavaScript | JQuery

How to use Linq To Bind GridView in ASP.Net

by Admin 12. August 2010 10:05

Linq is one of the best things that has happened in recent past in .Net framework world. It has made data manipulation so much easy. Yes, Linq has its own set of limitations but for most part it does the job. For those special cases you can always go back to classic ways. In this post, I will describe use of Linq for Sql and provide some simple answers to questions like:

  • How to connect to database using Linq?
  • How to query data from a table using Linq?
  • How to use Linq with GridView, DataGrid etc.?

Namespace and reference to use Linq with Sql

The classes that you need to use Linq with Sql live in System.Data.Linq namespace. So in your project you will have to add the following line at top of your source code file.

using System.Data.Linq;

This namespace lives in System.Data.Linq assembly. That means that you will have to add reference to this assembly in your project. Now you are all set to us Linq.

How to connect to the databae?

You have been using ADO.Net for a while now and first thing we all do is have a connection object that will be used to connect to database, open it and later on close it. Well when you are using, all that plumbing is taken care of for you by Linq frameework. The entry point to all actions in Linq for Sql is DataContext object. This object takes care of establishing connection with the database. You can provider either a connection string or connection object to create instance of DataConext object. Rest will get taken care of for you.

var dataContext = 
new DataContext(ConfigurationManager.ConnectionStrings["blogengine"].ConnectionString);

Query data using Linq

Now you have set up DataContext object, it is time to get some data from the database. You will notice that DataContext object provides methods like GetTable, ExecuteQuery, ExecuteCommand etc. All the methods that return collection of data, expect another parameter which is Type of an object that represent the data returned from query or command. In otherwords, the method is looking for a mapping between table in the database to an object. Here is an object definition that I used in my code to map to fields from a datatable that I wanted to fetch.

[Table(Name="be_Posts")]
public class BlogPost
{
  [Column(IsPrimaryKey=true)]
  public Guid PostID
  {get;set;}

  [Column]
  public string Title
  {get;set;}

  [Column]
  public string MiniUrl
  {get;set;}
}

There are few attributes on this class that are to be notices. First, there is TableAttribute on the class itself. By default Linq assumes that name of the class or object is same as table in the database. But if your table name does not match with the class name, then you can use this attribute to provide the name of the table that maps witht this obejct. For example in my case table name be_Posts is to be mapped to BlogPosts object which is my ViewModel. Next attribute is ColumnAttribute. You will assign this attribute to properties or fields that needs to be queried. If your column name does match with name of the property or field, you can provide that mapping as well. There are more values you can set in the column attribute. I will discuss those in subsequent posts. For now this simple definition of .Net object will work for our simple query purposes.

Bind Linq To GridView

Now we have our Linq query set to go, rest is just setting this collection to our GridView object on ASP.Net page and rest is all taken care of for us. Following code snippet shows how in few lines we are able to connect to database, query the data and bind it to a GridView.

void BindGrid()
{
 var dataContext = 
  new DataContext(ConfigurationManager.ConnectionStrings["blogengine"].ConnectionString);
 var posts = dataContext.GetTable<BlogPost>();
 postsGridView.DataSource = posts;
 postsGridView.DataBind();
}

It is as simple as these 4 lines of code to connect to database, query the table and bind to a gridview using Linq to Sql.

Views: 416

Tags: , ,

.Net | ASP.Net | DataGrid | GridView | Linq

How to use Commission Junction REST API with .Net

by Admin 30. July 2010 05:10

This code sample shows how to use Commission Junction REST API using .Net. The code is very straight forward. Only thing that you need to pay attention to is that you will be passing your user credentials through request header named Authorization. The value for this header is the Developer Key that was assigned to you when you signed up for Commission Junction web services account. This is a mile long string that was sent to you in your mail box as well when you signed up for CJ Web Service access.


class Program
{
 const string ADVERTISERS_LOOKUP_JOINED = 
 "https://advertiser-lookup.api.cj.com/v3/advertiser-lookup?advertiser-ids=joined";
 static void Main(string[] args)
 {
  var reqUrl = string.Format("{0}", ADVERTISERS_LOOKUP_JOINED);
  var webReq = WebRequest.Create(reqUrl) as HttpWebRequest;
  webReq.Headers.Add("Authorization", App.Default.DEVKEY);
  var resp = webReq.GetResponse() as HttpWebResponse;
  // Get the stream associated with the response.
  var receiveStream = resp.GetResponseStream();
  var readStream = new StreamReader(receiveStream, Encoding.UTF8);
  var respText = readStream.ReadToEnd();
  resp.Close();
  readStream.Close();
  if (resp.StatusCode == HttpStatusCode.OK)
  {
   // Parse response.
   Console.WriteLine(respText);
  }
  else
  {
   // what is the error??
  }
  }
}

Views: 342

Tags: ,

Advertising

How to apply Silverlight Toolkit Themes

by Admin 14. July 2010 14:12

When you are working on a rich user interface application, the most important thing that you need to figure out is how you can make your user interface appealing and intutive. As developer you can put together the back end plumbing to fetch the data and wire it to the user interface. But its the design part that can be tricky at times. You try to figure out color schemes and layout details of your pages and controls to make it appealing to your users.

Silverlight Toolkit provides more than a dozen themes that you can choose to implment your user interface look and feel. Some time you find that one theme may not fit all the needs. Well, tool kit does not stop you from mixing the themes as well. In this post I will show simple steps on how to use Themes from Silverlight Toolkit.

Install Silverlight Toolkit

If you are reading this post then there is good chance that you already know what silverlight toolkit is and you have already installed it. But for sake of completion, I will provide the link from where you can download latest toolkit.

Download Silverlight Toolkit From CodePlex

Add Assembly Reference

Add reference to theme assemblies as per your need. Each theme is contained in with in its own assembly. You can add reference to all or what you need. For example I wanted to add Shiny Red and Rain Purple themes to my project. So I have added reference to those assemblies only. Following screen shot how the references look like in my project.

Add Theme From Toolbox

Adding a theme to your page is as simple as dropping a control from the toolbox. If you look under Silverlight Controls node in Toolbox, you will find the controls as shown in the snapshot below. Pick the one that you want to use and drop in on your Silverlight page surface. You will see a code snippet as shown below appear on your page's XAML.


<shinyRedTheme:ShinyRedTheme>
 <Grid x:Name="LayoutRoot">
  <ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">
   <StackPanel x:Name="ContentStackPanel">
    <toolkit:RainierPurpleTheme Height="50" Name="rainierPurpleTheme1" Width="100">
     <Button x:Name="ClickItButton" Content="Click Me!" Width="Auto"></Button>
    </toolkit:RainierPurpleTheme>
   </StackPanel>
  </ScrollViewer>
 </Grid>
</shinyRedTheme:ShinyRedTheme>

The tag prefix toolkit and shinyRedTheme are ones that need to be defined at top of your page with other namespace declaration. When you drop a theme from toolbox on the page, the declaration gets added at top of the page automatically. Here is what it looks like in my project.


xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"

shinyRedTheme is namespace declaration that I added manually.

Add Controls

One you have dropped a theme on the page, you can add your UI controls inside that theme's container and all the controls with in that block will have that theme applied to it.

Mix Themes On Silverlight Page

If your UI needs to more than one themes and needs to be nested, there is nothing special you will need to do. Simple drag and drop another theme inside one theme and you are good to go. Following image shows rainier purple theme nested inside shiny red theme. And the XAML code snippet above reflects it as well.

I hope this gives you a good starting point on how to use themes from silverlight toolkit.

Views: 517

Tags:

Silverlight

Enable step into properties in Visual Studio Debugger

by Admin 25. June 2010 05:52

Recently I installed VS2010 on my new shiny Windows 7 64bit machine. I started to debug my blog application and moment I tried to stepped into a property of my class, I got the following message displayed to me. I knew what this was about because I resolved it last time I ran into this.

Your step-into request resulted in an automatic step-over of a property or operator.

This behavior can be overridden in the context menu for the line being executed by choosing 'Step Into Specific' or by unchecking the option 'Step over properties and operators'.

Do you want to continue being notified when an automatic step-over happens?

Microsoft probably has a reason to not allow to step into a property by default. Properties are supposed to be mostly get and set and not contain a whole lot of implementation in it. But that may not be the case all the time. If somebody is trying to step into a property that means this developer is suspecting something in that property that may be causing problems. So by default this behavior needs to be reversed and allow stepping into properties. For now this is how you can enable stepping into properties.

  • Go to Tools > Options menu in Visual Studio.
  • Goto Debugging > General menu item in left pane.
  • In right view you will see and option Step over properties and operators (Managed only). Uncheck this option and then you are all set.

Views: 652

Tags: ,

Visual Studio

Develop index.dat file viewer using .Net

by Admin 11. June 2010 12:20

I have been looking around to build an open source Index.dat file viewer using .Net. It's not that there are no viewers available but I could not find any that were built using C# or .Net framework. So finally I ran into some old C code developed by FoundStone.com to develop a command line took named PASCO. So I took that code built a viewer of my own.

You can go to the following link to download source code for Index.dat viewer developed using C#.

Index.dat File Reader Using .Net

Views: 680

Tags: ,

.Net | Windows 7

How to embed YouTube video in ASP.Net web page?

by Admin 3. June 2010 04:52

Download Source Code (9.09 kb)

Download Binaries (6.28 kb)

Recently I started created some YouTube videos and wanted to embed them in my ASP.Net web site. YouTube provides Embed button next to each video and that helps you create HTML code that you can put on your page. But that would mean that you will have to hard code this HTML on all pages where you want to embed videos. Also if you want to show some random videos on the pages, then this approach is not flexible.

I created this ASP.Net server control that allows to embed YouTube videos on any page. The control allows you to embed videos for which you already have URL or you can configure it to fetch any of the standard YouTube feeds and then display random video from that feed.

How to use it?

  • Download source code of the control and compile it or download pre-compiled binaries of the control.
  • Add reference to ByteBlocks.YouTubeWeb assembly in your project.
  • On the page where you want to embed YouTube video, add the following directive at the top of the page.

    <%@ Register TagPrefix="ByteBlocks" Assembly="ByteBlocks.YouTubeWeb" Namespace="ByteBlocks.Web.Control" %>

  • Now add the control on the page.

    <ByteBlocks:YouTube id="youTubeVideo" runat="server" Width="480" Height="385" VideoUrl="" FeedType="MostRecent" RandomResults="true" />

  • And you are all set to show random video from Most Recent video feed from YouTube.

Configurable Properties

  • VideoUrl: This property allows you to set URL of the video that needs to be embeded.
  • Width: Sets the width of the video player
  • Height: Set the height of the videeo player
  • FeedType: If you do not want to use a pre-defined video URL, you can pick a standard feed type. The control will fetch that feed from YouTube and display it based on value set for RandomResults and IndexToShow. This property is mututally exlcusive with VideoUrl. If you want the control to fetch standard feed, then do not set any URL in VideoUrl.
  • RandomResults: This property indicates to control to pick a random Video Url from the list of videos from standard feed type.
  • IndexToShow: If you set RandomResults to false, then the control will fetch the video at this index value. If this index is out of range, then the control picks the last entry in the feed list.

Under the covers

When you generate HTML code for a video from YouTube, it looks something like as shown below.


<object width="480" height="385">
<param name="movie" value="http://www.youtube.com/v/XcugLsKDmRs&hl=en_US&fs=1&rel=0"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/XcugLsKDmRs&hl=en_US&fs=1&rel=0" 
  type="application/x-shockwave-flash" allowscriptaccess="always" 
  allowfullscreen="true" width="480" height="385"></embed>
</object>

So the control simply renders this HTML on ASP.Net page and uses the control properties to configure the display accordingly. The important components of this HTML is video ID used with the video player. I have shown that in bold in snipper above. A video URL looks like as shown below.

http://www.youtube.com/watch?v=Qp9_6ACSWug

Video ID is provided in v query string parameter. The control parses this ID and replaces it in the URL that is required for URL for video player.

Source Code and Binaries

Attached code is compiled using Visual Studio 2010 and .Net 4.0 framework. If you need code for earlier versions of Visual Studio, feel free to conttact me.

Views: 825

Tags: ,

.Net | ASP.Net

MethodAccessException - Upgrading Assemblies to .Net4.0

by Admin 25. May 2010 05:19

This morning I was upgrading my HtmlParser and YahooFinanceParser libraries to use .Net 4.0 frameowrk. isual Studio 2010 conversion wizard did all the job of conversion. When I launched my test application to make sure everything was working, I was hit by a surprise. No code was changed other than compilation target was changed to .Net 4.0 and I got the following exception.

MethodAccessException

Attempt by method 'Winista.YahooFinanceParser.StockQuoteFetcher.GetStockQuote(System.String
to access method 'Winista.YahooFinanceParser.StockQuoteFetcher.CreateRequestAttributes(System.String)'
failed.

Since all assemblies were recompiled so the error details were not of much help asking to recompile with new referenced assmblies. I started with my usual ways of isolating the problem. Here was the call flow.

Console Application -->Library1 -->Library2

Exception was being thrown from a method in Library1. The exception message was not much of a help because it is complaining that class is having problem calling into its own private method. So I started my usual way of isolating the problem. The problem definitely seems to be code that was in CreateRequestAttributes. So I took the code out of there and directly put in the method GetStockQuote that was calling into CreateRequestAttributes. Now when i ran the test, i got the following exception.

MethodAccessException

Attempt by security transparent method 'Winista.YahooFinanceParser.StockQuoteFetcher.TestIt(System.String)' 
to access security critical method 'Winista.Text.HtmlParser.Http.RequestAttributes..ctor()' failed.

Assembly 'Winista.YahooFinanceParser, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null' 
is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security 
transparency model.  Level 2 transparency causes all methods in AllowPartiallyTrustedCallers 
assemblies to become security transparent by default, which may be the cause of this exception.

Now this exception detail made more sense. So let me explain what this issue is. In .Net4.0 framework, security tranparency rules prevent any security transparent code to call into security critical code. In .Net4.0 default security transpareny of library assemblies is security critical. My assembly Winista.YahooFinanceParser is marked with AllowPartiallyTrustedCallers attributes. This explicitly tells the security framework that this library will accept calls from security transparent callers. But the assembly Winista.HtmlParserPro do not have AllowPartiallyTrustedCallers attribute on it. This means it will not allow partial trusted or untrusted code to call into it. Therefore when method from Winista.YahooFinanceParser tried to create an object from Winista.HtmlParser, it threw MethodAccessException.

My original intention was to allow partially trusted to call into all these assemblies. But somehow AllowPartiallyTrustedCallers attribute slipped through the cracks for one assembly. After I applied AllowPartiallyTrustedCallers on Winista.HtmlParserPro assemnly, everything worked fine.

So if you are upgrading your libraries to .Net4.0 and you are not restricting any partially trusted or security transparent code to call into it, then put AllowPartiallyTrustedCallers attribute on your assemblies.

Views: 568

Tags:

.Net

Free Software Tool For Creating Instruction Videos

by Admin 26. April 2010 05:45

For a long time I have been thinking of creating some instruction videos on some software development exercises. And also when I received bug reports from my users and clients, I used to ask them to send screen captures and things like that to show the behavior of the bug. And lot of time I wished if they could send me some video clip to demonstrate the bug. Few days ago I reported a bug to Microsoft about some refresh issues in Visual Studio 2010. It was very hard to explain what I was seeing. Microsoft responded to my bug report and one items in the email caught my attention.

2.A video file about the issue ((Community clips is an easy way to record and share: http://www.officelabs.com/projects/communityclips/Pages/Default.aspx )

Yes, this is a tool that Microsoft created to record video clips, Community Clips. And this is absolutely free and is still available at their site. I installed it and it worked like a charm. There is no need to pay $300 to some commercial software when the only thing you are looking to do is create some simple video. You can always use other video editing tools to edit the video clips.

Click here Download Microsoft Community Clips

If for some reason the link is down or tool has been removed from Microsoft site, let me know. I will try to make it available to you.

Views: 977

Tags:

General

How to determine row and cell Index of mouse click inside Silverlight DataGrid?

by Admin 16. March 2010 06:31

Download Sample Projects (116.00 kb)

Some back I wrote about How to customize display of columns in DataGrid in silverlight application. But this customization was limited to accessing DataGridRow and changing of style as a whole. Recently I have come across lot of questions about knowing what row and what cell was accessed by user and other related questions. So this post is about addressing some of the following questions.

  • How to find row and cell index of user selection in DataGrid?
  • How to find row and column index of mouse click in Silverlight datagrid?
  • How to find row and column index of datagrid depending on mouse click?

I thought this was going to be a stright forward excercise. I was expecting some kind of direct method or property on some event that I could access to answer the question. It turned out that half of this question could be answered directly by using GetIndex method on DataGridRow object. But I could not get direct answer to index of cell that a user selected in datagrid. A lot of answers that I found revolved around adding a event handler for mouse events in the template for a given DataGridColumn. That meant that I will have to attach these event handlers to all the columns. Then the question was what if I added the columns dynamically or some other custom implementation.

Coming from classic Win32 and MFC background, I thought there has to be some kind of API that I could use where I could capture moust position and do some kind of hit test to find out location of mouse click or mouse move position. After digging around the APIs, I found VisualTreeHelper class that gave me what I was looking for. Following code snippet shows how I was able to get the column and row index inside DataGrid where moust position was.


private void GetGridRowColumnIndex(Point pt, DataGrid grid, out int rowIndex, out int colIndex, out object dataContext)
{
 rowIndex = -1;
 colIndex = -1;
 dataContext = null;
 var elements = VisualTreeHelper.FindElementsInHostCoordinates(pt, grid);
 if (null == elements ||
	elements.Count() == 0)
 { 
  return;
 }

 // Get the rows and columns.
 var rowQuery = from gridRow in elements where gridRow is DataGridRow select gridRow as DataGridRow;
 var cellQuery = from gridCell in elements where gridCell is DataGridCell select gridCell as DataGridCell;
 var cells = cellQuery.ToList<DataGridCell>();
 if (cells.Count == 0)
 {
  return;
 }
			
 foreach (var row in rowQuery)
 {
  dataContext = row.DataContext;
  rowIndex = row.GetIndex();
  foreach (DataGridColumn col in grid.Columns)
  {
   var colContent = col.GetCellContent(row);
   var parent = GetParent(colContent, typeof(DataGridCell));
   if (parent != null)
   {
    var thisCell = (DataGridCell)parent;
    if (object.ReferenceEquals(thisCell, cells[0]))
    {
     colIndex = col.DisplayIndex;
    }
   }
  }
 }
}

private void ProductsGrid_MouseMove(object sender, MouseEventArgs e)
{
 int rowIndex, colIndex;
 object dataContext;
 GetGridRowColumnIndex(e.GetPosition(null), ProductsGrid, out rowIndex, 
   out colIndex, out dataContext);
 SelectedRow.Text = string.Format("[Page={0}], [Row={1}] ", ProductsPager.PageIndex, rowIndex);
 SelectedColumn.Text = string.Format(" [Cell={0}] ", colIndex);
 if (null != dataContext)
 {
  var prod = dataContext as Product;
  ProductInfo.Text = string.Format("[{0}, {1}] ", prod.Name, prod.Color);
 }
}

You can download the attached project to see the whole code in action. The implementation is in Home.xaml/cs

Views: 2497

Tags: ,

DataGrid | Silverlight