Tuesday, July 12, 2011

Sql CE & LINQ with SQL Metal

To start programming with LINQ against SQL CE 3.5, as if a table in Sql CE is a class, you can make use of SQL Metal.

This post is a good guide to start off with.


Use the below command to generate the cs and dbml file.

Generate DBML file

C:\Program Files\Microsoft Visual Studio 9.0\VC>sqlmetal /dbml:J:\Sid\WinApps\Auto-motive\Auto-motive\AutoDB.dbml J:\Sid\WinApps\Auto-motive\Auto-motive\AutoDB.sdf
Microsoft (R) Database Mapping Generator 2008 version 1.00.30729
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

Generate CS file

C:\Program Files\Microsoft Visual Studio 9.0\VC>sqlmetal /Code:J:\Sid\WinApp
s\Auto-motive\Auto-motive\AutoDB.cs J:\Sid\WinApps\Auto-motive\Auto-motive\AutoDB.sdf
Microsoft (R) Database Mapping Generator 2008 version 1.00.30729
for Microsoft (R) .NET Framework version 3.5
Copyright (C) Microsoft Corporation. All rights reserved.

Friday, May 27, 2011

Getting QueryString parameters from ReWritten URL in ASP.Net

After a URL is rewritten to merge querystring into the actual URL, to get the querystring params, you should look towards Request's RawUrl property.

Use this code to extract QueryString params from the raw url:
Uri theRealURL = new Uri(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl);  
string utm_source = HttpUtility.ParseQueryString(theRealURL.Query).Get("utm_source");  
Actual code from this blog

Sunday, May 15, 2011

ASP.Net - Redirecting with URL Rewriter

To redirect one URL to another, use this rule inside "rewriter" section:

Monday, April 18, 2011

Adding new row to DataGridView programatically in C#

This article would be helpful if you are looking to add rows programatically to DataGridView and keeping key values invisible to user.

Heres a simple relation between ASP.Net & WinForms.

ASP.Net <--> WinForms
GridView <--> DataGridView
DataKeyNames(Considering 1 column is stored) <---> DataGridViewRow.Tag(Tag can store literally any value, but here it can solve our problem)

With the below code you have control on what you display to users while you still keep (one)important detail invisible.
Only one solution, to lengths of my knowledge, will help in this situation. Using DataGridViewRow.

List custList = GetAllCustomers();
            dataGridView1.Rows.Clear();

            foreach (Customer cust in custList)
            {
                //First add the row, cos this is how it works! Dont know why!
                DataGridViewRow R = dataGridView1.Rows[dataGridView1.Rows.Add()];
                //Then edit it
                R.Cells["Name"].Value = cust.Name;
                R.Cells["Address"].Value = cust.Address;
                R.Cells["Phone"].Value = cust.PhoneNo;
                //Customer Id is invisible but still usable, like, 
                //when double clicked to show full details
                R.Tag = cust.IntCustomerId;
            }

Friday, April 8, 2011

Add Site-Search functionality with JRank & RESTful web service - ASP.Net

If you are looking to add Site-Search functionality to your web site, and if you dont want Google ads in your search results page, JRank comes to rescue.
Starting off with JRank is quite an easy task. Just 3 easy steps to complete.
  • Join JRank
  • Create a context. Contexts are a way to tell JRank where to search in our site, the crawl frequency and for us to know how many pages are crawled/indexed, last crawled date and other stuff.
  • Integrate search into your site. Explained below
Complete 1st and 2nd steps. The 3rd step has 3 tasks in it again.
  • Add a search box
  • Post Search Query & Get results from JRank
  • Parse & Display
Adding a search box

I suppose, search button should exist on each page that a user can access. For that purpose, I have put search box on master page. So when user searches, search data will be passed to SiteSearch.aspx.

Add SiteSearch.aspx page to your web site. This page will receive search strings from other pages in your site. Also add a Literal control to this page to display the results.
Use plain old way of passing data from one page to other.
You can also use GET or POST methods but to keep it simple, I've used post back.
In the code behind, add this code.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        if (string.IsNullOrEmpty(sb1.Text.Trim()))
        {
            return;
        }
        Response.Redirect("searchresults.aspx?q=" + sb1.Text);
    }
Post Search Query & Get results from JRank

In SiteSearch.aspx page, get the search key words from Query string and pass it to JRank to do the search.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (string.IsNullOrEmpty(Request.QueryString["q"].ToString().Trim()))
            {
                Response.Redirect("index.aspx");
            }
            else
            {
                search(Request.QueryString["q"].ToString().Trim());
            }
        }
    }
Parse & Display
Once JRank is called to search, it will return an XML of result that contains page details, content preview and other stuff.
I have used RESTful API as I will have more control over end result than the HTML response of JRank.
Parse it and display what you want.
private void search(string q)
    {
        string jrankURL = string.Format("http://www.jrank.org/api/search/v2.xml?key={0}&q={1}", "your-jrank-api-key", q);
        System.Net.WebClient serviceRequest = new System.Net.WebClient();
        string response = serviceRequest.DownloadString(new Uri(jrankURL));
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml(response);
        XmlNode root = doc.DocumentElement;
        XmlNodeList nodes = root.SelectNodes("/serp/entries/entry");

        StringBuilder sb = new StringBuilder();
        sb.Append("Your search for ").Append(q).Append(" has ").Append(nodes.Count.ToString()).Append(" results.

");
        sb.Append("
    "); foreach (XmlNode node in nodes) { sb.Append("
  • ");
    string url = node["url"].InnerText;
    string title = node["title"].InnerText;
    string content = node["content"].InnerText;
    sb.Append("").Append(title).Append("").Append(content).Append("");
    sb.Append("
  • "); } sb.Append("
"); ltSearchResults.Text = sb.ToString(); }
Try understanding the code and tweak some to get the results you need.
Happy coding!

Sunday, March 27, 2011

Problem repeating a background image on y axis in HTML?

Often we come across a situation where a div height will change across pages and a lot divs in those pages use the same CSS rule.

If you want to repeat the background image on y-axis and you want to change the height of the div dynamically where the background image has to repeat itself, you can do it using JavaScript. And now that you came here, it is a real simple job.

Theoretically what you are going to do is,
1.Assign the div, whose height you are looking to change dynamically, an ID.
2.When the document is loaded, get the height occupied by that div
3.Assign that height to the CSS rule where background repeat is mentioned.
As simple as that! Heres the working code.


<head>
<style type="text/css">
#content
{
width: 450px;
background-image: url(images/line_v.gif);
background-repeat: repeat-y;
background-position: right center;
min-height: 10px;
float: left;
}
</style>
</head>
<body>
<div id="content>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam semper turpis in
tortor interdum sed mattis lectus mollis. Pellentesque laoreet quam et mauris feugiat
sit amet eleifend turpis imperdiet. Praesent condimentum libero vitae massa imperdiet
pellentesque. Vestibulum et risus dolor, ac tincidunt velit. Maecenas lobortis diam
tellus. Suspendisse auctor, velit ut imperdiet semper, erat orci pharetra tortor,
venenatis vulputate metus eros ut felis. Cras ullamcorper odio sed felis ornare
ultricies. Phasellus porta adipiscing aliquet. Aenean ligula tellus, blandit a pulvinar
in, fermentum a erat. Sed arcu nisl, porta eu vestibulum at, luctus sed tellus.
Aenean eget quam justo, quis ultricies ante. Vivamus tempor sollicitudin augue ut
rhoncus. Sed odio mauris, imperdiet ut elementum vitae, dapibus at quam. Nullam
in aliquam sem. Fusce consectetur laoreet elit, non consequat nunc tempus nec. Cras
at enim ipsum. Praesent ipsum purus, tempus non sagittis volutpat, fringilla eget
mi. Maecenas sed elit est. Morbi facilisis purus eget nunc tincidunt iaculis mattis
quam pellentesque. Sed tortor leo, laoreet sit amet mattis a, fermentum in ligula.
Sed tempor lacus a lorem fermentum fermentum semper nunc sagittis. Vivamus et est
porta purus mollis cursus eget in ante. Sed lacinia, diam in tempor suscipit, turpis
enim posuere turpis, sit amet vestibulum quam nulla id elit. Vivamus ultricies tempus
mi, non consequat velit mollis id. Curabitur vehicula, turpis id tempor condimentum,
sem nulla molestie enim, vel commodo metus ipsum non nisi. Aliquam erat volutpat.

</div>

<script type="text/javascript">

var divHeight;
var textobj = document.getElementById("content");

if (textobj.offsetHeight) { divHeight = textobj.offsetHeight;}
else if (textobj.style.pixelHeight) { divHeight = textobj.offsetHeight; }

changecss('#content', 'min-height', divHeight + "px");

function changecss(theClass, element, value) {
var cssRules;

var added = false;
for (var S = 0; S < document.styleSheets.length; S++) {

if (document.styleSheets[S]['rules']) {
cssRules = 'rules';
} else if (document.styleSheets[S]['cssRules']) {
cssRules = 'cssRules';
} else {
//no rules found... browser unknown
}

for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
if (document.styleSheets[S][cssRules][R].style[element]) {
document.styleSheets[S][cssRules][R].style[element] = value;
added = true;
break;
}
}
}
if (!added) {
try {
document.styleSheets[S].insertRule(theClass + ' { ' + element + ': ' + value + '; }', document.styleSheets[S][cssRules].length);

} catch (err) {
try { document.styleSheets[S].addRule(theClass, element + ': ' + value + ';'); } catch (err) { }

}
}
}
}
</script>

</body>
</html>

Here's the line_v.gif, . Place it in images folder and give it a go to see how it works.

Make sure the javascript is at the end of document. Else it would would throw "object required" error.

Happy coding!

Thursday, March 24, 2011

Using JQuery Datepicker in Master Pages

I will cover 2 points here.
1. Using JQuery's DatePicker
2. Using it in Master Page, Content Page situations

To use JQuery's DatePicker, you should have access to JQuery and JQuery UI libraries. You can either use CDNs(Content Distribution Networks) or have JQuery libraries in your site.
The libraries have both JavaScripts and CSS files.
I have used Google CDN for JQuery & JQuery UI javascripts. And for the CSS part, I have downloaded them to my site. And the reason is, I could not get CSS running if used CDN for it!

Time to get dirty.
In the master page's head section, add the links to the libraries






Once you get the libraries, in the content page, drag & drop a asp:TextBox and add the jquery code to attach the datepicker to the textbox.
It should look like below.





If you are not using master page, you can replace $('[id$=TextBox1]') with $("#TextBox1"). Thats it! Just 4 files to link and 2 lines of code will get you a beautiful Datepicker on your page.
Happy coding!

Wednesday, March 23, 2011

Binding a List or string array to ListView and operating on it

Suppose you have a Object Datasource attached to ListView and you have GetList, Delete and Insert operations set on it that would operate on a db. If that ODS primarily deals with string array, then you are about to face some challenges.
Displaying
The problem with showing a plain string array to ListView is, that array is nameless.
To overcome this, all you have to do is use Container.DataItem where it usually was Bind("Name")



Operating on the data
To delete a row from db, the only information you have in the ListView is string data. So, we have to make use of it and tie that info to every delete button (you get this when you select delete operation on the ODS) for every row. You do that in ItemDataBound event.

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
(e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
}

To make insertion into db, find the input text control inside InsertItem template of ListView as shown below and in ItemCommand event, use the command name property to distinguish between operations.

protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
(e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
}
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string venue = e.CommandArgument.ToString();
Venue.DeleteVenue(venue);
Response.Redirect(Request.Url.AbsolutePath, true);
}
else if (e.CommandName == "Insert")
{
VenueEntity venueEntity = new VenueEntity();
venueEntity.Name = (ListView1.InsertItem.FindControl("VenueTextBox") as TextBox).Text;
venueEntity.AddedBy = User.Identity.Name;
venueEntity.DateAdded = DateTime.Now;

Venue.InsertVenue(venueEntity);
Response.Redirect(Request.Url.AbsolutePath, true);
}
}

Adding Attributes to ListView item in Asp.Net

One problem when switching from GridView to ListView would be to understand that ListView doesn't have rows as GridView. To add attributes to ListView item, it should be done in ItemDataBound event as below.



protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
object objTemp = ListView1.DataKeys[((ListViewDataItem)e.Item).DisplayIndex].Value as object;
if (objTemp != null)
{
string id = objTemp.ToString();
((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onmouseover"] = "this.style.color='DodgerBlue';this.style.cursor='hand';";
((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onmouseout"] = "this.style.color='Black';";
((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onclick"] = "window.location.href = 'ManageCourse.aspx?CourseId=" + id + "'";
}
}
}

You need the runtat attribute set to server for "courserow" row.