tag:blogger.com,1999:blog-70795097610883255052024-03-18T22:04:23.047-07:00AspDiaryUnknownnoreply@blogger.comBlogger10125tag:blogger.com,1999:blog-7079509761088325505.post-27842574596819413272012-05-01T15:55:00.000-07:002012-05-01T20:56:21.003-07:00SQL: Select rows from Comma Separated IDs<div dir="ltr" style="text-align: left;" trbidi="on">
It's not a very common scenario when IDs are present as Comma Separated data and you have to select all rows against those IDs.<br/><br/>
For example, if <b>Addresses</b> is a table and its primary key is <b>u_address_id</b><br/>
There is another table <b>OrganizationObject</b>, which would store details of Organizations. The organizations' addresses are stored in Addresses table. <br/><br/>
Ideally the Addresses table should contain a column to store primary key of OrganizationObject. Unfortunately, if you don't have that column, the data is stored in reverse order, where all the addresses's IDs for a particular organization are stored in CSV format in OrganizationObject row itself and you don't even have the privilege of changing the structure, here's a solution.<br/>
<br />
<pre class="brush: sql">
select ad.u_country_name as Country, aid.u_Name as ProviderName, aid.u_organization_type as ProviderType from (
SELECT
F1.u_Name,
F1.u_organization_type,
O.u_address_id
FROM
(
SELECT *,
cast('<X>'+replace(F.u_addresses,';','</X><X>')+'</X>' as XML) as xmlfilter from OrganizationObject F
where F.u_organization_type in ('2', '3')
)F1
CROSS APPLY
(
SELECT AData.A.value('.','varchar(50)') as u_address_id
FROM f1.xmlfilter.nodes('X') as AData(A)) O) aid --Address IDs
join
Addresses ad
on
aid.u_address_id = ad.u_address_id
where
ISNULL(NULLIF(u_country_name, ''), NULL) is not null
and ad.u_st_address_type = 2
order by u_country_name
</pre>
<br /></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-35360207482058559082011-07-12T19:10:00.000-07:002011-07-12T19:10:21.115-07:00Sql CE & LINQ with SQL MetalTo 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.<br/><br />
<a href="http://skainsez.blogspot.com/2008/06/getting-started-with-linq-to-sql-and.html">This post</a> is a good guide to start off with. <br/><br />
<br />
Use the below command to generate the cs and dbml file.<br />
<br />
<b> Generate DBML file</b><br />
<br />
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<br />
Microsoft (R) Database Mapping Generator 2008 version 1.00.30729<br />
for Microsoft (R) .NET Framework version 3.5<br />
Copyright (C) Microsoft Corporation. All rights reserved.<br />
<br />
<b> Generate CS file</b><br />
<br />
C:\Program Files\Microsoft Visual Studio 9.0\VC>sqlmetal /Code:J:\Sid\WinApp<br />
s\Auto-motive\Auto-motive\AutoDB.cs J:\Sid\WinApps\Auto-motive\Auto-motive\AutoDB.sdf<br />
Microsoft (R) Database Mapping Generator 2008 version 1.00.30729<br />
for Microsoft (R) .NET Framework version 3.5<br />
Copyright (C) Microsoft Corporation. All rights reserved.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-69572817613500035692011-05-27T19:59:00.000-07:002011-05-27T19:59:40.324-07:00Getting QueryString parameters from ReWritten URL in ASP.NetAfter a URL is rewritten to merge querystring into the actual URL, to get the querystring params, you should look towards Request's RawUrl property. <br />
<br />
Use this code to extract QueryString params from the raw url: <br />
<pre class="brush: csharp">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");
</pre>Actual code from <a href="http://dot-net-web-developer-bristol.blogspot.com/2010/08/getting-parameters-from-rawurl.html">this blog</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-32395735403256383402011-05-15T22:43:00.000-07:002011-05-16T21:52:08.793-07:00ASP.Net - Redirecting with URL RewriterTo redirect one URL to another, use this rule inside "rewriter" section:<br />
<pre class="brush: html"><redirect url="index.aspx" to="~/Pages/1/home.aspx"></redirect>
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-40716022630599142392011-04-18T22:47:00.000-07:002011-04-19T17:20:58.746-07:00Adding 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.<br />
<br />
Heres a simple relation between ASP.Net & WinForms.<br />
<br />
ASP.Net <--> WinForms<br />
GridView <--> DataGridView<br />
DataKeyNames(Considering 1 column is stored) <---> DataGridViewRow.Tag(Tag can store literally any value, but here it can solve our problem)<br />
<br />
With the below code you have control on what you display to users while you still keep (one)important detail invisible. <br />
Only one solution, to lengths of my knowledge, will help in this situation. Using DataGridViewRow. <br />
<br />
<pre class="brush: csharp">List<customer> 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;
}
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-70447461053412421692011-04-08T18:18:00.000-07:002011-04-08T18:38:27.850-07:00Add Site-Search functionality with JRank & RESTful web service - ASP.NetIf you are looking to add Site-Search functionality to your web site, and if you dont want Google ads in your search results page, <a href = "http://jrank.org">JRank</a> comes to rescue. <br />
Starting off with JRank is quite an easy task. Just 3 easy steps to complete.<br />
<ul><li><b>Join JRank</b></li>
<li><b>Create a context.</b> 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.</li>
<li><b>Integrate search into your site.</b> Explained below</li>
</ul>Complete 1st and 2nd steps. The 3rd step has 3 tasks in it again.<br />
<ul><li>Add a search box</li>
<li>Post Search Query & Get results from JRank</li>
<li>Parse & Display</li>
</ul><u><b>Adding a search box</b></u><br />
<br />
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.<br />
<br />
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.<br />
Use plain old way of passing data from one page to other.<br />
<pre class="brush: html"><div id="box"><asp:TextBox ID="sb1" runat="server" Width="115px" BorderStyle="None" BorderWidth="0px"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl="Images/search_button.jpg" BorderWidth="0" style="padding-left: 10px; padding-top: 6px;
border: 0px;" onclick="ImageButton1_Click" />
</div></pre>You can also use GET or POST methods but to keep it simple, I've used post back.<br />
In the code behind, add this code.<br />
<pre class="brush: csharp">protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
if (string.IsNullOrEmpty(sb1.Text.Trim()))
{
return;
}
Response.Redirect("searchresults.aspx?q=" + sb1.Text);
}
</pre><u><b>Post Search Query & Get results from JRank</b></u><br />
<br />
In SiteSearch.aspx page, get the search key words from Query string and pass it to JRank to do the search.<br />
<pre class="brush: csharp">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());
}
}
}
</pre><u><b>Parse & Display</b></u><br />
Once JRank is called to search, it will return an XML of result that contains page details, content preview and other stuff. <br />
I have used RESTful API as I will have more control over end result than the HTML response of JRank.<br />
Parse it and display what you want.<br />
<pre class="brush: csharp">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 <b>").Append(q).Append("</b> has ").Append(nodes.Count.ToString()).Append(" results.
");
sb.Append("<ul style=\"list-style-type:none;margin-left:0px;padding-left:0px\">"); foreach (XmlNode node in nodes) { sb.Append("
<li>");<br />
string url = node["url"].InnerText;<br />
string title = node["title"].InnerText; <br />
string content = node["content"].InnerText;<br />
sb.Append("<a href="").Append(url).Append("">").Append(title).Append("</a>").Append(content).Append("");<br />
sb.Append("</li>
"); } sb.Append("</ul>");
ltSearchResults.Text = sb.ToString();
}
</pre>Try understanding the code and tweak some to get the results you need. <br />
Happy coding!Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-14895076287538669122011-03-27T20:22:00.000-07:002011-03-27T21:32:50.140-07:00Problem 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. <br /><br />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.<br /><br />Theoretically what you are going to do is, <br />1.Assign the div, whose height you are looking to change dynamically, an ID. <br />2.When the document is loaded, get the height occupied by that div<br />3.Assign that height to the CSS rule where background repeat is mentioned.<br />As simple as that! Heres the working code.<br /><pre class="brush: html"><br /><br /><head><br /> <style type="text/css"><br /> #content<br /> {<br /> width: 450px;<br /> background-image: url(images/line_v.gif);<br /> background-repeat: repeat-y;<br /> background-position: right center;<br /> min-height: 10px;<br /> float: left;<br /> }<br /> </style><br /></head><br /><body><br /> <div id="content><br /> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam semper turpis in<br /> tortor interdum sed mattis lectus mollis. Pellentesque laoreet quam et mauris feugiat<br /> sit amet eleifend turpis imperdiet. Praesent condimentum libero vitae massa imperdiet<br /> pellentesque. Vestibulum et risus dolor, ac tincidunt velit. Maecenas lobortis diam<br /> tellus. Suspendisse auctor, velit ut imperdiet semper, erat orci pharetra tortor,<br /> venenatis vulputate metus eros ut felis. Cras ullamcorper odio sed felis ornare<br /> ultricies. Phasellus porta adipiscing aliquet. Aenean ligula tellus, blandit a pulvinar<br /> in, fermentum a erat. Sed arcu nisl, porta eu vestibulum at, luctus sed tellus.<br /> Aenean eget quam justo, quis ultricies ante. Vivamus tempor sollicitudin augue ut<br /> rhoncus. Sed odio mauris, imperdiet ut elementum vitae, dapibus at quam. Nullam<br /> in aliquam sem. Fusce consectetur laoreet elit, non consequat nunc tempus nec. Cras<br /> at enim ipsum. Praesent ipsum purus, tempus non sagittis volutpat, fringilla eget<br /> mi. Maecenas sed elit est. Morbi facilisis purus eget nunc tincidunt iaculis mattis<br /> quam pellentesque. Sed tortor leo, laoreet sit amet mattis a, fermentum in ligula.<br /> Sed tempor lacus a lorem fermentum fermentum semper nunc sagittis. Vivamus et est<br /> porta purus mollis cursus eget in ante. Sed lacinia, diam in tempor suscipit, turpis<br /> enim posuere turpis, sit amet vestibulum quam nulla id elit. Vivamus ultricies tempus<br /> mi, non consequat velit mollis id. Curabitur vehicula, turpis id tempor condimentum,<br /> sem nulla molestie enim, vel commodo metus ipsum non nisi. Aliquam erat volutpat.<br /><br /> </div><br /><br /> <script type="text/javascript"><br /><br /> var divHeight;<br /> var textobj = document.getElementById("content");<br /><br /> if (textobj.offsetHeight) { divHeight = textobj.offsetHeight;}<br /> else if (textobj.style.pixelHeight) { divHeight = textobj.offsetHeight; }<br /><br /> changecss('#content', 'min-height', divHeight + "px");<br /><br /> function changecss(theClass, element, value) {<br /> var cssRules;<br /><br /> var added = false;<br /> for (var S = 0; S < document.styleSheets.length; S++) {<br /><br /> if (document.styleSheets[S]['rules']) {<br /> cssRules = 'rules';<br /> } else if (document.styleSheets[S]['cssRules']) {<br /> cssRules = 'cssRules';<br /> } else {<br /> //no rules found... browser unknown<br /> }<br /><br /> for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {<br /> if (document.styleSheets[S][cssRules][R].selectorText == theClass) {<br /> if (document.styleSheets[S][cssRules][R].style[element]) {<br /> document.styleSheets[S][cssRules][R].style[element] = value;<br /> added = true;<br /> break;<br /> }<br /> }<br /> }<br /> if (!added) {<br /> try {<br /> document.styleSheets[S].insertRule(theClass + ' { ' + element + ': ' + value + '; }', document.styleSheets[S][cssRules].length);<br /><br /> } catch (err) {<br /> try { document.styleSheets[S].addRule(theClass, element + ': ' + value + ';'); } catch (err) { }<br /><br /> }<br /> }<br /> }<br /> }<br /> </script><br /><br /></body><br /></html><br /></pre><br />Here's the line_v.gif, <a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9OkTtYVrczL4auSyWm4e3P3GWcmvw5RD5BZ3cIY2R9JoaBwpDUy94f6jNc4IZ77PQhQ_MEobMDhVcoruXL1oeisrMu9R9jXI1QXLa-oMfU8BUTfFpBg0kqkBcGNKC85f7xKbeS3ubnvcX/s1600/line_v.gif"><img style="cursor:pointer; cursor:hand;width: 3px; height: 5px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9OkTtYVrczL4auSyWm4e3P3GWcmvw5RD5BZ3cIY2R9JoaBwpDUy94f6jNc4IZ77PQhQ_MEobMDhVcoruXL1oeisrMu9R9jXI1QXLa-oMfU8BUTfFpBg0kqkBcGNKC85f7xKbeS3ubnvcX/s320/line_v.gif" border="0" alt=""id="BLOGGER_PHOTO_ID_5588971596198166354" /></a>. Place it in images folder and give it a go to see how it works.<br /><br />Make sure the javascript is at the end of document. Else it would would throw "object required" error.<br /><br />Happy coding!Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-52904972658631102762011-03-24T19:09:00.000-07:002011-03-25T16:53:57.076-07:00Using JQuery Datepicker in Master PagesI will cover 2 points here.
<br />1. Using JQuery's DatePicker
<br />2. Using it in Master Page, Content Page situations
<br />
<br />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.
<br />The libraries have both JavaScripts and CSS files.
<br />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!
<br />
<br />Time to get dirty.
<br />In the master page's head section, add the links to the libraries
<br /><pre class="brush: csharp">
<br /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<br /> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<br /> <link href="../assets/jquery-ui-1.8.11.custom.css" rel="stylesheet" type="text/css" />
<br /> <link href="../assets/datepickersize.css" rel="stylesheet" type="text/css" />
<br /></pre>
<br />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.
<br />It should look like below.
<br /><pre class="brush: csharp">
<br /> <script type="text/javascript">
<br /> $(document).ready(function() {
<br /> $('[id$=TextBox1]').datepicker({ showAnim: 'slideDown' });
<br /> });
<br /> </script>
<br />
<br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br /></pre>
<br />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.
<br />Happy coding!Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7079509761088325505.post-63482805509019064662011-03-23T19:22:00.000-07:002011-03-23T19:50:05.440-07:00Binding a List or string array to ListView and operating on itSuppose 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.
<br /><span style="font-weight:bold;">Displaying</span>
<br />The problem with showing a plain string array to ListView is, that array is nameless.
<br />To overcome this, all you have to do is use Container.DataItem where it usually was Bind("Name")
<br /><pre class="brush: csharp">
<br /><asp:Label ID="NameLabel" runat="server" Text='<%# Container.DataItem %>'> </asp>
<br /></pre>
<br /><span style="font-weight:bold;">Operating on the data</span>
<br />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.
<br /><pre class="brush: csharp">
<br />protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
<br /> {
<br /> string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
<br /> (e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
<br /> }
<br /></pre>
<br />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.
<br /><pre class="brush: csharp">
<br />protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
<br /> {
<br /> string venueName = (e.Item as ListViewDataItem).DataItem.ToString();
<br /> (e.Item.FindControl("DeleteButton") as Button).CommandArgument = venueName;
<br /> }
<br /> protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
<br /> {
<br /> if (e.CommandName == "Delete")
<br /> {
<br /> string venue = e.CommandArgument.ToString();
<br /> Venue.DeleteVenue(venue);
<br /> Response.Redirect(Request.Url.AbsolutePath, true);
<br /> }
<br /> else if (e.CommandName == "Insert")
<br /> {
<br /> VenueEntity venueEntity = new VenueEntity();
<br /> venueEntity.Name = (ListView1.InsertItem.FindControl("VenueTextBox") as TextBox).Text;
<br /> venueEntity.AddedBy = User.Identity.Name;
<br /> venueEntity.DateAdded = DateTime.Now;
<br />
<br /> Venue.InsertVenue(venueEntity);
<br /> Response.Redirect(Request.Url.AbsolutePath, true);
<br /> }
<br /> }
<br /></pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7079509761088325505.post-49733608989491915532011-03-23T18:32:00.000-07:002011-03-23T20:09:05.276-07:00Adding Attributes to ListView item in Asp.NetOne problem when switching from GridView to ListView would be to understand that ListView doesn't have rows as GridView. To add attributes to ListView <i>item</i>, it should be done in ItemDataBound event as below.<br /><br/><br /><pre class="brush: csharp"><br />protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)<br /> {<br /> if (e.Item.ItemType == ListViewItemType.DataItem)<br /> {<br /> object objTemp = ListView1.DataKeys[((ListViewDataItem)e.Item).DisplayIndex].Value as object;<br /> if (objTemp != null)<br /> {<br /> string id = objTemp.ToString();<br /> ((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onmouseover"] = "this.style.color='DodgerBlue';this.style.cursor='hand';";<br /> ((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onmouseout"] = "this.style.color='Black';";<br /> ((HtmlTableRow)e.Item.FindControl("courserow")).Attributes["onclick"] = "window.location.href = 'ManageCourse.aspx?CourseId=" + id + "'";<br /> }<br /> }<br /> }<br /></pre><br />You need the runtat attribute set to server for "courserow" row.Unknownnoreply@blogger.com0