|
|
by Naveen
2. September 2010 05:34
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 when page load
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. Start
typing some search term and see how autocomplete start providing hints and then when you hit
ENTER key, page posts back and returns with search results and then text box focus is
set at the end of text in text box.
Live Demo Of Text Box Features
|
|
|
by Naveen
31. August 2010 03:01
Recently I decided to join band wagon of Android and go with latest and greatest DroidX. No, I am not a big fan of iPhone. Being a developer myself I do not like a platform that is too restrictive and hinders innovation just because some nut named Jobs does not want you to. Any how, I have been tracking DroidX reviews etc. for some time. And most importantly its demand and supply. It seems that Motorola may be having some issues in keeping up with supply. Few days ago tentative ship date for more units was set to September 6th. Then it moved to September 10th and today I noticed that it has been pushed further down to September 14th. The thing that amuses me the most is that graphic artists of Verizon are having hard time keeping up with this delay when creating delay images for their web site. The list page on the site says Will be shipped by 9/13 and when you go to details page of DroidX you will find the following line.
|
Due to high demand, this device will ship by 9/14
|

|
|
|
|
65c25866-c24f-4602-a031-f13e5fb1b252|0|.0
Views: 176
Tags: DroidX
Android
by Naveen
25. August 2010 17:19
While implementing integrating ASP.Net Ajax AutoComplete control on a site's search text box, I ran into an issue. While I was typing inside the text box, no request was getting sent to my web service to get the list of previously used search terms with a given prefix that user was typing. I checked the mark up for
AutoCompleteExtender on the page and all the required properties etc. There was nothing out of place. Obviously request was not making it to my web service method. That's when I called on handy dandy Fiddler. And there it was the following response from the web service request with Http Status code of 500.
Only Web services with a [ScriptService] attribute on the class definition can be called from script
Thats when I realized that I forgot to enable this attribute on my ASP.Net web service. So remember that if you are using an ASP.Net web service with Ajax toolkit controls, you have to enable ScriptService on
your service.
by Naveen
23. August 2010 13:40
Its been a while since I did some custom work on controls like GridView, DataGrid etc. Last
week I was working on a prototype of some application that required me to add some records into the
database. So I decided to give GridView control in ASP.Net a try. I needed a very simple
UI so I decided to use as much built in functionality of this control. Since I needed to add a new
record, so I needed a way to be able to add a new row into GridView. So I looked at the
CommandField column. One of the properties it has is ShowInsertButton . So
I added this property and set it to true. So now my mark up on ASP.Net on the page looked as shown
below.
<Columns>
<asp:CommandField ShowEditButton="True"
ShowDeleteButton="true"
ShowInsertButton="true"></asp:CommandField>
.... othe bound columns.
</Columns>
I ran the application and my grid shows up and has all three data manipulation links visible. So I clicked on
New link button. Well, I did not see an empty row appear where I was going to add new data for
new row in database. I checked, everything looked in order. I have event handler correctly mapped and
code looked fine. After trying few things around, I searched on internet. I could not find any
useful information on why my event is not firing or why new row is not getting added. All the posts and articles
that I ran into talked about adding a new button in the grid to accomplish taks of added new records. Well
that sounded a little odd that why would I need to add my own button when there is already a command
link buttoon available. Thats when I decided to read the documentation on this property ShowInsertButton.
Here is something in documentation that stood out.
This property applies only to data-bound controls that support insert operations, such as the DetailsView control.
When you look at various events in GridView control, you will not find any related to
Insert. Now that explained why I am not getting new row added to my grid.
Adding new row to GridView
So here is quick solution that I came up with for my prototype. When you click on New
link button in GridView, it does fire RowCommand event. Here you can check for
CommandName value of New. In this event handler, I added a new empty
record into the data source to which my GridView was bound, set the EditIndex of the
grid to first record and bind the grid again. Now I have an empty row in Edit mode open for me to
add some data.
if (e.CommandName == "New")
{
ViewState["_inserting_"] = 1;
var glossaryTerm = new Services.GlossaryTerm();
_terms.Insert(0, glossaryTerm);
GlossaryGrid.EditIndex = 0;
BindGrid();
}
You can see that I added a flag in ViewState that grid is in Insert mode. The reason
for this is that since GridView does not support Insert directly, when you
will click on Update link button, you are going to get RowUpdated event
handed to you. So you will need some way of knowing that this record is actually to be added and not edit
some existing one. The way I did is not one of the best and elegant way. But you get the idea. One nice
of doing is to have an hidden field where some unique ID of each record is stored. And you can keep
this field hidden. Since I did not have any unique ID in my data source, I had to do it
differently. But most grids are bound to some data source with some unique ID. So when you add a new
empty record for adding, you can set its Unique ID value to some token valur like -1. When you
handle RowUpdated event, then you can look for this unique ID value and perform
the database accordingly.
This trick should allow you to use built in command buttons to add new row in GridView.
|
|
|
by Naveen
19. August 2010 11:21
As part of using Membership controls in ASP.Net, one thing lot of people do
as part of user creation is send some sort of email to the new user when they register. This email
could be some welcome email or email that send the user their password etc. Good news is that
CreateUserWizard control takes care of most of the email functionality for you. Here
is what you need to make it all work.
How does it work?
CreateUserWizard control sends an email to the newly registered when the new user
has been created. SendEmail event is fired after CreatedUser event has been
successfully fired and handled. Interestingly, CreateUserWizard sends this email using
method SendPasswordMail. It seems this email feature was designed for sending
passwords to user when password is automatically generated. But this does not mean that it is
only going to be called when certain password option is chosen.
MailDefinition is the key
CreateUserWizard control does not try to send email all the time. It looks for
MainDefinition template to be set in the control. If you do not definie
MailDefinition template, control will not send the email. So what you need to do is
fill this template inside your control container. Here is sample implementation from my sample
code.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:CreateUserWizard ID="RegisterUser"
runat="server" EnableViewState="false"
OnCreatedUser="RegisterUser_CreatedUser"
OnCreatingUser="RegisterUser_CreatingUser"
BorderStyle="Dotted"
OnSendingMail="RegisterUser_SendingEmail"
OnSendMailError="RegisterUser_SendingEmailError">
<LayoutTemplate>
<asp:PlaceHolder ID="wizardStepPlaceholder" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="navigationPlaceholder" runat="server"></asp:PlaceHolder>
</LayoutTemplate>
<MailDefinition
From="xyz@mymail.com"
IsBodyHtml="true"
Priority="Low"
BodyFileName="~/WelcomeEmail.htm"
Subject="Welcome to Project Helpers from ByteBlocks.com">
<EmbeddedObjects>
<asp:EmbeddedMailObject Name="LogoImage" Path="~/Images/ByteBlocksLogo.png" />
</EmbeddedObjects>
</MailDefinition>
</asp:CreateUserWizard>
As you can see, MailDefinition template allows you to configure email parameters. You
do not have to hard code some string as body of your email. It will actually become problem when
you have long HTML content to be sent in email body. You can put content of your email in external file
and then set the path to that file in BodyFileName attribute of MainDefinition.
You can put some token or markers inside that body to replace them with appropriate values at run time. More about it
little later. So remember that MailDefinition is key to sending email as part of
CreateUserWizard control.
Customize email content and attachment
Some time you want to send welcome email to new users with some documents and also want to
have some logo image inside the email body. Well, this all can be handled by using a standard format
that the control provided. You will make use of EmbeddedObjects section of
MailDefinition template. This is where you can include all the external objects or file
paths. Make sure that you have unique names for these objects.
-
To include images inside email body, use the following syntax in HTML email body content.
<img src="cid:LogoImage" alt="ByteBlocks Project Helpers" />
<h2>Welcome To ByteBlocks Project Helper</h2>
This is part of HTML file that I use for email body. The key to this is src=cid:uniqueid part.
This uniqueid is the name of the object that you added in EmbeddedObjects section. You
can see from the markup that I showed earlier that I have included my logo image inside
EmbeddedObjects section.
-
If you need to attach some documents, then include them in EmbeddedObjects section.
Following screenshot shows sample of email that get sent from my application. You can see that at the top of
the email is sample logo image as well.
Configure SMTP Server for CreateUserWizard Email
This is one of the most asked question to me. Where do I set SMTP server settings for emails from
CreateUserWizard?. When SendEmail event is fired, you get
MailMessageEventArgs object as parameter of event handler. This object only provides
you access to email message only. It does not provide a way to configure SMTP settings for outgoing
email. Then how do you set it?
See the following call stack when CreateUserWizard control is trying to send the email
out.
System.Net.Mail.SmtpClient.Send(MailMessage message)
System.Web.UI.WebControls.LoginUtil.SendPasswordMail(String email, String userName,
String password, MailDefinition
Now if you look at constructor of SmtpClient, it initializes the settings of email
transport from mailSettings section of web.config. That means the place
to configure your SMTP server is in web.config file. Add mailSettings section in
system.net section of web.config value. Following snippet shows
you an example from my site.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="xyz@myisp.com">
<network host="localhost" />
</smtp>
</mailSettings>
</system.net>
You can provide the values as per your server settings. If you are just testing using your local machine
as email relay then you do not have to specify these settings. SmtpClient by default will
use local machine.
Important things
There are few things that you will need to pay attention to when setting up this MailDefinition
template and changing settings for MailMessage.
-
Make sure that you have specified an email address in From section. This does not have
to be a valid emails address. You can simply put something like noreply@mydomain.com. But do not leave
it empty.
-
If your process does not require the users to provide their email address but you still want to send some
email for record keeping then you can add a placeholder email to To collection. You
can not leave To collection empty. Otherwise SmtpClient object will throw exception at you.
protected void RegisterUser_SendingEmail(object sender, MailMessageEventArgs e)
{
var sendTo = RegisterUser.Email;
if (string.IsNullOrEmpty(sendTo))
{
sendTo = "foo@bar.com";
e.Message.To.Add(sendTo);
}
}
Do provide an event handler for SendEmailError. If there is some error or
exception thrown during outoging email process, you can look at the error message. Handle this error gracefully and
then set Handled properly.
protected void RegisterUser_SendingEmailError(object sender, SendMailErrorEventArgs e)
{
System.Diagnostics.Trace.WriteLine(e.Exception.Message);
e.Handled = true;
}
If you do not handle this error, then it will get propagated to the top as unhandled exception and depending
on your CustomError settings, users may see ugly yellow screen with full stack trace and all.
|
|
|
1f16a4fa-9ec8-4790-837b-8d2af0788e1b|0|.0
Views: 405
Tags: ASP.Net
ASP.Net
by Naveen
18. August 2010 10:50
I was working on using CreateUserWizard ASP.Net control on my web site to allow
users to create their account for authorized and authenticated access to certain access of sites. One
of the problems you face on the web sites is that spammers tend to run bots to create accounts
on sites using direct HTTP requests and things like that. One of the ways to fight this is the use of some
CAPTCHA control on the pages. Yes, there are some hackers who claim to bypass some of these
counter measures. But still it protects you from about 80% or so of these spam bots.
So one of things you can do is to add ASP.Net plugin for reCaptcha control in template
for CreateUserWizard control. There are few issues that I ran into when I tried to integrate
into my page. So here are some of the things you can learn from my experience to integrate reCaptch
in ASP.Net.
-
There seems to be a validation bug in older version of reCaptcha control plugin. So I had
to download the latest source code from google SVN and recompile it to use in my ASP.Net web site. The problem
I was running into with bugged plugin was that Postback was not getting fired. After I
will click on Create button, the page will just not fire event handler to postback the page. Once
I replaced it with recompiled version of reCaptch control, the page worked fine.
-
In the post back event handler, add the following code to validate reCaptcha challenge. This
will provide you server side validation of the control. I added following code to my event handler.
protected void RegisterUser_CreatingUser(object sender, LoginCancelEventArgs e)
{
var captcha =
(Recaptcha.RecaptchaControl)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("recaptchaCtl");
if (null == captcha)
{
e.Cancel = true;
return;
}
captcha.Validate();
if (!captcha.IsValid)
{
//TODO: Display validation message.
e.Cancel = true;
return;
}
e.Cancel = false;
}
|
|
|
1b3d7020-c71a-4804-b85d-5c1fc53ea44e|0|.0
Views: 390
Tags: ASP.Net
ASP.Net
by Naveen
17. August 2010 04:30
After installing Windows 2008 Server or for that matter any flavor of Windows server, you will
quickly realize that using Internet Explorer on that machine can be a real pain. Well Microsoft has every good intention about keeping the security very tight on the server and the default options set for
Internet Explorer on Windows 2008 Server are too tight. I am not going to debate about security
issues related to Internet Explorer.
I wanted to install Google Chrome browser just to avoid dealing with tight settings for IE. Well to start with I had to use IE anyways so I could access Google site to get installer. So I did and added Google.com to trusted sites list. So I started install of Google Chrome. After 3-4 seconds, installer threw an error that application is not properly formatted. I was like what application is not
formatted. I seriously doubt that it had anything to do with Chrome installer being corrupt. From the dialog box I clicked on the button to see the details of the error and found the following message.
PLATFORM VERSION INFO
Windows : 6.0.6001.65536 (Win32NT)
Common Language Runtime : 4.0.30319.1
System.Deployment.dll : 4.0.30319.1 (RTMRel.030319-0100)
clr.dll : 4.0.30319.1 (RTMRel.030319-0100)
dfdll.dll : 4.0.30319.1 (RTMRel.030319-0100)
dfshim.dll : 4.0.31106.0 (Main.031106-0000)
SOURCES
Deployment url : http://dl.google.com/update2/1.2.183.29/GoogleInstaller_en.application?
Server : downloads
ERROR SUMMARY
Below is a summary of the errors, details of these errors are listed later in the log.
* Activation of http://dl.google.com/update2/1.2.183.29/GoogleInstaller_en.application resulted
in exception. Following failure messages were detected:
+ Your Web browser settings do not allow you to run signed applications.
ERROR DETAILS
Following errors were detected during this operation.
* [8/16/2010 7:17:04 PM] System.Deployment.Application.InvalidDeploymentException (Manifest)
- Your Web browser settings do not allow you to run signed applications.
- Source: System.Deployment
- Stack trace:
at System.Deployment.Application.ApplicationActivator.BrowserSettings.Validate(String manifestPath)
at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri,
Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension,
BrowserSettings browserSettings, String& errorPageUrl)
at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state)
The key to this error message was Your Web browser settings do not allow you to run signed applications.. Well security settings on IE was preventing the installer to complete the installation. So here is what you can do if you run into issue with installation of any applications on Windows 2008 Server that you download from internet.
- Goto the application web site.
- Click in Download button or link or what ever way the site provides to install the application. When you get the dialog box with options to Run or Save, Choose to Save it on your disk.
- Now goto folder where you saved the installer and launch it from there. This should now run without being
under the context of IE security.
As usual, you just have to be careful with what you download and install on your server.
|
|
|
by Naveen
16. August 2010 17:01
After I installed Windows 7 x64 device driver on my Windows 2008 Server x64 laptop, I looked my wireless network connection utility and noticed that my wireless connection was not working. I looked in device manager and saw that there was no problem with driver installation. There was no yellow mark against the wireless card device. Then I went into Manage Network Connections windows. The icon was there for wireless connection but it was in Disabled. I tried to enable it and it won't enable. It kept getting back into Disabled and every time I tried to enabled a windows error message will pop up asking to check for solution online. I decided to look in the event log and found there were plenty of errors with following message.
Faulting application bcmwltry.exe, version 5.60.48.35, time stamp 0x4b591cc1, faulting module Wlanapi.dll, version 6.0.6001.18000, time stamp 0x4791adec, exception code 0xc0000135, fault offset 0x00000000000b1188, process id 0xbd8, application start time 0x01cb3d94e925870e.
One thing was clear that network utility was trying to do some action and it was failing in WLanApi.dll. This dll has implementation of Wireless Network APIs. Then it clicked that on
Windows 2008 Server, Wireless LAN Service feature is not installed by default. So simple solution is to goto Server Configuration wizard to launch features window and add Wireless LAN Service feature and finish the installation and wireless card will work fine.
|
|
|
by Naveen
16. August 2010 16:24
This morning I installed Windows 2008 Server on my laptop. Well, I wanted to try SharePoint Server 2010 and it only supports Windows Server OS and that too on 64 bit. There is no 32 bit version of MOSS 2010. The installation of Windows 2008 Server went fine and I wad able to get it up and running. Now I needed to install device drivers for most of the devices on the laptop. Windows 2008 installation does manage to install drivers for most of the things. But when it comes to drivers for Video, Audio, Network and other important things, then you are left with getting appropriate drivers from vendor or if you have media for your machine. Problem is that most vendors do not have drivers downloads for Windows 2008 Server. Well you do not buy laptops for running servers.
There is easy solution to this problem. Download the drivers for Windows 7 x64 and you are golden. Most of these drivers will install and work fine on Windows Server 2008.
by Naveen
13. August 2010 13:35
Adding a panel on a web page with rounded corners is something very common that we all do at some point in
web application development. We all have been thought standard solution of using a collection of images to
arrange them in a manner that they form a rectangle with rounded corners.
If you are developing ASP.Net web site then, Ajax Toolkit makes this task every easy for you. By
adding one additional control tag you end up adding a rounded corner panel around an existing panel. Let's
see how this done.
-
I am going to skip the discussion on download of Ajax toolkip, installation and all that good stuff. I am going
to assume that you have already done it.
-
Add reference to AjaxControlToolkit.dll assembly to your ASP.Net project if you do not
already have it added.
-
At the top of the page add tag for registering TagPrefix for the controls in this Ajax assembly.
<%@ Register Assembly="AjaxControlToolkit"
Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
-
Make sure that you add ScriptManager server control tag on the page as well. Otherwise
you will end up with the following run time error.
The control with ID 'intoPanelRoundedCornersExtender' requires a ScriptManager on the page.
The ScriptManager must appear before any controls that need it.
In my case I just added in the master page of the site.
<asp:ScriptManager ID="masterScriptManager" runat="server" />
-
Now add RoundedCornersExtender control on the page. The most important property to
set is TargetControlID. This ID of the control around which rounded corner panel is
going to be added. Without it, the control will not work.
<ajaxToolkit:RoundedCornersExtender ID="intoPanelRoundedCornersExtender" runat="server"
BehaviorID="RoundedCornersBehavior1"
TargetControlID="siteIntroPanel"
Radius="6"
BorderColor="#111"
Color="#696969"
Corners="All" />
Other property that can be set to control behavior of rounded corner panel are Color,BorderColor,
Radious and Corners. The names of these properties pretty much tell what these are supposed
to control.
See how easy it is to add these rounded corners. You can see the demo on this
live site. The top two panel are created using
this RoundedCornerExtender control from Ajax toolkit.
|
|
|
by Naveen
13. August 2010 09:12
Last week I was updating the site to include some new features. I realized that I was missing a very
important component on the blog and that was google search box. I had this search on my other sites
for quite some time. I remember that I had to deal with the fact that Google Custom Search script
is implemented as a POST FORM with the action set to a URL that will be used
to display results.
First you have to deal with the fact that ASP.Net framework does not allow you to have multiple
FORM tags on the page. But if you want have more than one then only one can have
runat='server' attribute on it. And then you have to make sure that your FORM
tags are not nested. Well, depending on your layout of the site and implementation, you may or may not
be able to control location of this google search form. Here is the solution that I implemented few years
ago and deployed on this site as well.
Use of iform
Yes, took the Google Custom Search script and put it in a static HTML page. And then put an
IFRAME on the page where I wanted to display the search box. This is where you will
have to be little careful. You will have to make sure that style of the HTML page matches your main site.
Next make sure that height and width of iframe is big enough to accomodate the search box otherwise
you will end up with horizontal and vertical scroll bars around the frame and that will not be a pretty sign
for site users. You want to give the illusion to users that this search box is sitting on the page itself. Now
perform search and it works. But there is a problem. Search result target URL is being opened in the frame where
search box is. Well that is a little problem.
Fix target of FORM
This is where you will have to make a change in the script that Google Custom Search generated for you. In
FORM tag, set target to _top. Now when this form is
submitted, the action is sent to page contained this iframe. The following snippet
is what I have in my HTML page.
<div class="cse-branding-bottom" style="background-color:#FFFFFF;color:#000000">
<div class="cse-branding-form">
<form action="http://localhost/ByteBlocksWeb/SearchResults.aspx"
id="cse-search-box"
target="_top">
<div>
<input type="hidden" name="cx" value="partner-pub-xxxxxxxxxxxxx:wcbg5i-ahdn" />
<input type="hidden" name="cof" value="FORID:11" />
<input type="hidden" name="ie" value="ISO-8859-1" />
<input type="text" name="q" size="60" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
</div>
<div class="cse-branding-logo">
<img src="http://www.google.com/images/poweredby_transparent/poweredby_FFFFFF.gif" alt="Google" />
</div>
<div class="cse-branding-text">
Custom Search
</div>
</div>
Now perform a search and you will notice that your results show up in main page and not in iframe
anymore. Give it a try right here in this site by using search at top of the page and see how it works.
|
|
|
by Naveen
12. August 2010 10:08
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.
|
|
|
by Naveen
11. August 2010 20:46
Yesterday I had to deal with one of the worst email spam issue on the mail server. One of the person who had email
account on the server, got his desktop or account hacked. And that desktop was sending email through
the server like crazy. The way I came to know about the problem was that one of the site administrators
told me that all email deliveries were stopped few hours ago. And after that I got the information, an
email came from our email server hosting provider that the server has reached daily limit of email relay.
This was the first time ever I got this notification.
I have SmarterMail mail server application installed. So far I never had any issue with it
and has worked great. I quickly logged onto the server and brought up management console for email server. I
looked at the email spool. Wow! There were more than 100K email waiting to be delivered in the spool. Well,
that explained that why none of the valid emails were not getting emails because there were so many spam emails
stuck in the que waiting to clear.
Steps Followed To Resolve The Issue
- First, I stopped mail service on the server from Service Control Manager.
- Next i looked at emails that were stuck in the spooler. There were whole bunch of emails that did not
have any sender email associated with it in the report. I opened about dozen of them and found that
all of them were associated with one user account through which those were being delivered.
- Since I could not keep the email server down forever while I was working resolving the problem, I had to
start the mail server. But before starting the service, I had to take come precaution so that no more
spam emails are getting put on the spool. So here are steps taken to avoid further clogging of spool.
- Added the offending email address into the Blocked list of people for outgoing emails.
- Deleted the offending email address from the server. I tried disabling that account but that
did not work very well. Only thing I can say is that Relay settings were not honoring the disabled account.
- Now was the time to clean up spool. Well, I was not going to wait till I clean up 100K messages
from the spool though the user interface. So simple procedure is to rename Spool folder
on your server to something like Spool_Spam. Then create a new folder with name
Spool on the server.
- Now I started the mail service again. Watchd it for few minutes to make sure that spam emails were not
appearing on the spool. Well, that went great. No more outgoing spam emails.
Restoring Old Spool
Now that problem with spam emails were taken care of, now I had to restore valid emails from old spool so that
we do not loose any emails. Here are the steps that I followed.
-
Since I figured out that there was only one sender account that was causing the problem all outgoing
spam emails, I just need to make sure that all entried from old spool related to that account
are removed. All emails are stored as individual files with extension .eml in
Subspool folders under Spool folder. I searched for that sender
email address in all folders and deleted all .eml files for that. Now you will be left
with .hdr files related to those deleted .eml files. Clean those files
up.
- Copy the remaining .eml and .hdr files from this old spool folder into the new working Spool
folder.
This should put everything back to normal.
|
|
|
by Naveen
9. August 2010 10:57
Some times when you execute a SQL query to insert or update data into a table, you may see the following error.
String or binary data would be truncated.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it
originated in the code.
Exception Details: System.Data.SqlClient.SqlException: String or binary data would be truncated.
The statement has been terminated.
What this error means is that you are trying to insert more data into a field than the schema specified for. For example if you have a varchar field and limited its size to 100, if you try to insert a string with length more than 100, then you will end up with this exception. In older version of SQL, the server used to silently let this case go through and truncate the data and you would not know it. And then you will notice it when trying to display these fields in some form.
by Naveen
9. August 2010 06:12
If you are trying a new toon in Age Of Conan as a Khitan then you are going to run into few of these quests that make you go through some burial grounds right next to your Gateway To Khitai starting area. There is a guy starting on top of a small plateau that hand you the quest to dig excavation sites for artifacts. Here are few tips that you will help you a lot in that area.
- Do not start on the quest right away. There is another quest that asks you to talk a Yue. Go through
that area to get to that woman. She and a guy standing next to her has quests as well that will require you to
go through the excavation sites. So if you get all three quests, then you can finish all of them together.
- While going through the area you will run into stallions. Very quickly you will realize that those are elite
mobs. You will not be able to take them down unless you have help from friends. The quest log clearly says
that you will have to try to avoid them. So do exactly as quest says, avoid them. The easier way is to stay on the small hills in that area and try to stay away from valley like areas where these stallions roam. On top of these small hills you will find your other quests mobs like painstalkers and hyenas. So you will avoid stallions as well as finish the quest of killing these mobs.
-
Before you dig any of the excavation sites, make sure that you use /kneel command to finish the task that asks you to kneel at the excavation sites. And around these excavation sites you will run into mini bosses that you need to finish another quest.
-
Yue gives you quest that requires you to burn a body. The body is at the base of the hill where she is standing, just go behind her down the hill. There is a mini-boss around that body. So you can kill that mob as part of the quest or avoid that boss and wait for it go away and then burn the body.
|
|
|
6bf2233a-50c4-4385-9802-693c67d9824e|0|.0
Views: 438
Tags: Games
Games
by Naveen
8. August 2010 16:48
Other day I was doing quests in Gateway Of Khitai area. I was handed quest Listen in on Wu-ji's Meeting. The quest is very simple and it says that you need to eves drop on meeting between Wu-ji and another person. I tried it 3-4 times and it kept failing although I was doing everything right. Finally I got it right. The key to the quest completion is:
- Stay hidden till Wu-ji comes and talk to the guy in hut.
- This is most important part. You have to stay very close to them. If you can see the bubbles of conversation on them, you are in good shape. Otherwise even if they don't spot you and you can see the conversation text in chat window, the quest will not complete.
3be79dc1-c664-4d90-acf2-0c54c4c989aa|0|.0
Views: 427
Tags: Games
Games
by Naveen
7. August 2010 05:41
I have been out of MMORPG world for quite some time now. It was two years ago when I last played Age Of Conan. It was frustrating to play that game at the time because of bugs, issues with lag, lack of content and constant crashes. Although game had good graphics some quest lines but it was just frustrating.
Last week I renewed subscription to Age Of Conan and also got Rise Of God Slayer expansion as well. I heard that Funcom did good job in making some major improvements to the game. My first impression was not bad at all. So I created a new Khitan ranger. I had to try new race to see new area. I had to say that so far I only had 2 crashes. The lag is not bad and performance is much better.
Khitai area is fun to play as well. Unlike World Of Warcarft where you are always over powered and can take down 5 mobs that are 2-3 levels aboves you, Khitai area can give you run for the money. If you are not paying attention to what you are doing, you will be overrun by mob that may be at same level as you are.
The expansion is definitely worth trying.
|
|
|
9ebe9a74-3f0c-4ff9-a89d-959e72001438|0|.0
Views: 851
Tags: Games
Games
by Naveen
5. August 2010 06:47
Recently one of my clients asked me question about affiliate web stores and how they work.
I have been involved in creating affiliate mashup webstore creation for quite some time
now. I have created mashup web stores based on Amazon, Ebay, Google etc. affiliate programs.
And lot of these stores have been very successful in generating decent revenue for clients. Lately
I got introduced to Commission Junction affiliate program by a new client. This client
was looking into creating a web store based on Commission Junction web services. In this
post I will provide some information on how to use Commission Junction web services to create
a targetted web store.
Get Started
-
As with every affiliate program, first you need to sign up with Commission Junction
affiliate program. Click here
to get started with sign up.
-
Now you need a develop key from Commission Junction to access their API. It is a simple process.
Go to CJ Webservices
page and register for a developer key. After completing this step, the key will be sent to your mail box as well
as displayed on the page. Save it and keep it safe.
Build The Site
Now that you have completed the registration process and everything, you are all set to build the site.
As with any application or web site, you will need data to show some content and products on the
site. The data is going to come from Commission Junction web services. Commission Junction
provides REST services to access following kind of data.
- Products
- Links
- Advertisers
- Categories
These are bread and butter of making the site. There are some other services available as well. But
for now you can focus on these only. You will need to build an API or some sort of agent
that can consume REST services to access the data from Commission Junction web service. Since I am mostly
doing .Net development these days, so I have a built a nice handy library that hides all the
implementation details and downloads the data from web service and makes it available to the web site. You
can Contact Me if you are looking into
using .Net API.
Now that you have the data, you will need to think about what type of products or category you want to
target to build your store. You have all the data for all the categories from advertisers that you
signed up for. But that does not mean that you want to create some store that is going to
market all type of products. Well, I am not saying that you can not do that. But it is always
better to concentrate on one or two categories. That makes it easier for you to create some
focused marketing and promotion plan for your web site.
I created a mash up store where I am marketting all products from all advertisers. You can see how the
landing page shows all the coupons and deals of the day from all the vendors and then you
can navigate to each page to see how the product page combines links, coupons and product list data
to display information to user. Click below to see the store in action.
Affiliate Webstore Demo
|
|
|
by Naveen
30. July 2010 05:00
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??
}
}
}
If you are looking for any help building any tools based on Commission Junction API, contact me. I can guide you through the development using .Net.
|
|
|
by Naveen
27. July 2010 05:12
Download Sample Project (41.34 kb)
Some of the cool applications on smart phones are developed to help present information to the user
based on their geo locations. And lot of time it involves using maps. Since Windows 7 Phone
development platform is based on Silverlight, use of Bing Maps Silverlight Control comes
as a natural choice. But so far there is not a official release of the control specific to
Windows 7 Phone. Good news is that since Windows 7 Phone SDK is built on top of
Silverlight 3 platform, you can use current release of Bing Maps Control for Silverlight with
a small caveat. In this post I will discuss how to use Bing Maps in Windows 7 Phone.
First thing first. You will need to make sure that you all the tools needed for Bing Maps development. I have
explained this in my earlier post
Using Bing Maps In Silverlight 4. The steps to use Bing Maps Silverlight Control are exactly the
same as in your conventional Silverlight application development.
How to use Bing Maps in Windows 7 Phone
- Create Windows 7 Phone project in Visual Studio 2010
-
Add reference to following assemblies in your project from location where you installed Bing Maps SDK.
- Microsoft.Maps.MapControl
- Microsoft.Maps.MapControl.Common
Now compile the project to make sure that the reference to Bing Maps are correctly included. This is where
you will hit the first road block. You will get a compile time error.
error CS0234: The type or namespace name 'Maps' does not exist in the namespace
'Microsoft' (are you missing an assembly reference?)
The primary reference "Microsoft.Maps.MapControl" could not be resolved because it has
an indirect dependency on the framework assembly
"System.Windows.Browser, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"
which could not be resolved in the currently targeted framework.
"Silverlight,Version=v4.0,Profile=WindowsPhone". To resolve this problem, either remove the
reference "Microsoft.Maps.MapControl" or retarget your application to a framework version which
contains "System.Windows.Browser, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e".
Here is little piece of information you will need to know and is very important. As per Silverlight
documentation for Windows 7 Phone namespace System.Windows.Browser is not supported
on the device. Good news is that you can add reference to this assembly from the folder where your
Silverlight assemblies are installed by Visual Studio. For example in my case the location is
C:\Program Files\Microsoft Silverlight\4.0.50524.0\System.Windows.Browser.dll. Adding
reference to this assembly does not mean that you can actually use all the APIs from this namespace. If
you will try, you will get run time errors. Remember that this namespace is not supported in
Windows 7 Phone platform. Now compile the project again and you should be good to go.
- Now implement the code that will fetch data that needs to be used to render locations on
Bing Maps. In previous post
How to use WCF in Windows 7 Phone, I
described use of WCF. In the sample project attached with the post, I am using WCF service to
get geo locations that I want to plot on Bing Maps on Windows 7 Phone.
As I mentioned in previous posts about Windows 7 Phone development, you can cut and paste code from
your regular Silverlight application in Windows 7 Phone application and it will work as long as
you are not using any APIs that is not supported on Windows 7 Phone.
|
|
|
Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli
|
|