<link rel="me" href="https://www.blogger.com/profile/16032550589156935534" /> <meta name='google-adsense-platform-account' content='ca-host-pub-1556223355139109'/> <meta name='google-adsense-platform-domain' content='blogspot.com'/> <!-- data-ad-client=ca-pub-6672515474304268 --> <!-- --><style type="text/css">@import url(//www.blogger.com/static/v1/v-css/navbar/3334278262-classic.css); div.b-mobile {display:none;} </style> </head><body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar/4865038256408662682?origin\x3dhttps://imacomputernerd.blogspot.com', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe" }); } }); </script>
0 comments | Thursday, November 1, 2007

How to easily remove multiple list items with ASP.NET C#

I searched everywhere for code to do this and found about 10-12 posts of example that includes dozens of lines of code and still didn’t even work correctly, then I found this one and thought I would share, it is an easy small piece of code that removes multiple selected items from a listbox in C#.


int i = ListBox1.Items.Count;
for(int j = 0; j < i; j++)
{
ListBox1.Items.Remove(ListBox1.SelectedItem);
}


This would be called on button click (as an example). Works great for me. Hope it helps.

Labels: , ,

0 comments | Monday, April 23, 2007

I'll be the first to admit that in the beginning I cut a few corners. Putting more focus into making it work quickly than correctly. I think all programmers have done it from time to time, especially on tight time schedules. One mistake that I and MANY others have made in the past is for validation. Checking to see if data even exsists is not enough anymore especially when your dealing with formatted information like email addresses and phone numbers. There are several different ways to validate an email address. From checking to make sure it "@" in it, all the way to querying the web server to verify the actual address entered. In my experience I've found that no matter what you are going to get a few bogus emails, but finding the fine line between application speed and getting the most valid data possible is up to you.



Checking to see if an address includes a "@" and has a extension following a "." can be done very quickly. I generally tend to simply check syntax because I figure if the user doesn't want to give you his/her address than he/she is not really going to want to read your newsletter either. For more complex applications where a actual address is mandatory, I would recommend using a email verify system where you send an email to the applicant with a link to verify his/her email address. That way your gauranteed that he/she entered an actual valid address that he/she has access to. But for simple mailing list or newletter signups I stick with a pain free fast and easy verification to check for a few things.



1. Make sure it has only 1 "@"
2. Make sure it has at least 1 "."
3. Make sure there are no more than 3 charactors after the last "."
4. Make sure it has no "_" after the "@"
5. A brief check to make sure invalid charactors were not used in the address.



Here is what the function to check an address would look like;





Public function chkEmail(theAddress as String)
' returns 1 for invalid addresses
dim atCnt
chkEmail = 0

' chk length
if len(cstr(theAddress)) < 5 then
' a@b.c should be the shortest an
' address could be
chkEmail = 1

' chk format
' has at least one "@"
elseif instr(theAddress,"@") = 0 then
chkEmail = 1

' has at least one "."
elseif instr(theAddress,".") = 0 then
chkEmail = 1

' has no more than 3 chars after last "."
elseif len(theAddress) - instrrev(theAddress,".") > 3 then
chkEmail = 1

' has no "_" after the "@"
elseif instr(theAddress,"_") <> 0 and _
instrrev(theAddress,"_") > instrrev(theAddress,"@") then
chkEmail = 1

else
' has only one "@"
Dim i as integer
atCnt = 0
for i = 1 to len(theAddress)
if mid(theAddress,i,1) = "@" then
atCnt = atCnt + 1
end if
next

if atCnt > 1 then
chkEmail = 1
end if

' chk each char for validity

for i = 1 to len(theAddress)
if not isnumeric(mid(theAddress,i,1)) and _
(lcase(mid(theAddress,i,1)) < "a" or _
lcase(mid(theAddress,i,1)) > "z") and _
mid(theAddress,i,1) <> "_" and _
mid(theAddress,i,1) <> "." and _
mid(theAddress,i,1) <> "@" and _
mid(theAddress,i,1) <> "-" then
chkEmail = 1
end if
next
end if
end function





In this we are passing the email address to the function. Then its checking the address for the above listed items and returning a value. The value states wether or not the email was valid. In this case "1" being invalid, and "0" being valid. With this in mind a simple 'If' statment can control what we do in this scenario. Check it out.




Dim strEmail as string = Request.Form("txtEmail")

If chkEmail(strEmail) = 1 Then
'The address was NOT vaild. Do not proceed, return error message

Else
'The address was valid. Proceed with writing the address
'into the database or whatever action you want to do.

End If





Thats pretty wasy, we said 'If' the result of the Function chkEmail = 1 then we know its bad. Else would mean it passed and we can proceed to capture the good email address.



Again, there are a TON of different ways to verify email addresses. I have found for light use this code to work very well.

Labels: , , , ,

0 comments

XML has been around for a while but is starting to really pick up with the use of RSS feeds growing. Many companies have news, blogs, and much more available through custom RSS feeds hosted on their site. The great part about them is that they are responsible for updating them. What this does is allow a "smaller" website to have late breaking news articles on his/her site without lifting a finger. It provides a way for webmasters to have ever changing dynamic content on his/her site without the hastle of spending hours a day writing. Today we are going to build a .NET script that pulls the XML RSS feed from the source, reads it and displays its content on your page. Once that's done I'll show you a couple tricks to improve performance and appearance.



First let me show you what the bulk of the script will look like. Then I'll go through piece by piece and explain what its doing. For this example I am going to use the Yahoo World News RSS Feed. Now keep in mind, you will need to read up on each RSS feed you are pulling to ensure you are complying with their terms of use. You are dealing with content that belongs to someone else so be sure you know all laws and their rules when it comes to the content you are pulling. Generally speaking if you are not directly making money using their feeds then you’re OK. But its your responsibility to know what you can and can't do with a 3rd party RSS Feed.



Here we go.




<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<script language="VB" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
dlRSSData.DataSource = ReadRSS("http://rss.news
.yahoo.com/rss/world")

dlRSSData.DataBind()
End Sub


Function ReadRSS(strRSSURL as String) as DataTable
Dim XMLreader as XmlTextReader = New
XmlTextReader(strRSSURL)

Dim objds as DataSet = New DataSet()
objds.ReadXml(XMLreader)
Return ds.Tables(3)
End Function
</script>
<html>
<body>
<form runat="server">

<asp:DataList runat="server" id="dlRSSData">
<itemtemplate>

<a href="<%# DataBinder.Eval(Container.DataItem, "Link")
%> " target="_blank">
<%# DataBinder.Eval(Container.DataItem, "title") %> </a> <br />
<%# DataBinder.Eval(Container.DataItem, "description") %>
<br /> <br />

</itemtemplate>
</asp:DataList>

</form>
</body>
</html>





Alright, that believe it or not is ALL the code for the page. Its starts off by importing the system.data and system.XML namespaces. This lets the .NET server know that you plan on using both a form of data and XML (in this case its the same document) in your code. It tells the .NET server all it needs to know regarding the commands you'll pass to it like 'Dim XMLreader as XmlTextReader'.



In the first line of our Page_Load script we set the datasource of our datalist. If you look in the HTML section of the code we have a datalist on the page. I'll explain more about that in a little bit. Anyway, in the first line we set the datasource equal to the results of a function. Pretty cool programming going on here. We are calling a function and passing it the location of the RSS feed. When the function gets done running it will return some data and that data will then be the datasource to our DataList. Make sense? Let’s look further. If we follow the code down to the function that was called we see are creating a new XMLTextReader. We do this so that when we pass it the RSS XML doc it will know how to understand it. We then create a dataset off that XML data and we tell it to return the data to the Sub that called the function. In this case its the datasource code for our datalist. We then immedietly bind the data to the datalist and were done. The page will load.



So the series of events that happen are;
1. Page is requested on the .NET server
2. .Net creates the datasource for the datalist by running a function called 'ReadRSS' passing it the actual location of the RSS feed.
3. The function creates a XML reader and returns it to the datalist
4. The datalist is bound to the XML data
5. The page displays the formatted XML data on the page.


Pretty simple and easy with BIG results.



Now before we began I promised you that I'd show you how to also improve performance and appearance. So here we go. If you look at the code it’s having to go to yahoo's site and pull the XML data every time the page is requested. This can cause your site to slow significantly not only for 1 hit but especially if your dealing with thousands of hits. One method to resolve this is to "cache" the XML data on your site and pull from that cache. You can set a time limit on the cache so that you get the latest data release every X number of minutes. That way you are still pulling dynamic up to date content but with a significantly less amount of overhead in bandwidth and time.



If you reference the above code our first line in the <script> tag is setting the data source to the datalist. We are going to add some cache code before it to see if we have a valid cache of the feed, if we do then we use the cached data if we don't then it will go to yahoo's site and get the latest RSS feed. Then we pick up where we started above but instead of setting the datasource from the live data we set it from the cache data. This will speed up your performance drastically. As a test try writing your code the non-cached way. Test it out and get a feel for how long it takes to pull and display the data. Then immediately change the code to the cached version and see the difference.



The cached way of doing it looks like this.



 
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<script language="VB" runat="server">
Sub Page_Load(sender as Object, e as EventArgs)
If Cache("RSSfeed") Is Nothing then
'Item not in cache, go and get it
Dim dt as DataTable = GetRSSFeed("http://rss.news
.yahoo.com/rss/world")
Cache.Insert("RSSfeed", dt, Nothing, DateTime.
Now.AddMinutes(60), TimeSpan.Zero)
End If

dlRSSData.DataSource = Cache("RSSfeed")
dlRSSData.DataBind()

End Sub


Function ReadRSS(strRSSURL as String) as DataTable
Dim XMLreader as XmlTextReader = New
XmlTextReader(strRSSURL)

Dim objds as DataSet = New DataSet()
objds.ReadXml(XMLreader)
Return ds.Tables(3)
End Function
</Script>
<html>
<body>
<form runat="server">

<asp:DataList runat="server" id="dlRSSData">
<itemtemplate>

<a href="<%# DataBinder.Eval(Container.DataItem, "Link")
%> " target="_blank">

<%# DataBinder.Eval(Container.DataItem, "title") %> </a> <br />

<%# DataBinder.Eval(Container.DataItem, "description")
%> <br /> <br />

</itemtemplate>
</asp:DataList>

</form>
</body>
</html>


Now its almost doing the same thing as above except it is checking for a cached version of the feed. It there is one then it uses that, if not then it creates a cached version by going and getting it and running the function to read it. Then we set our datasource for our datalist from the cache. Its simple and quick.



Now we can easily change the appearance of our data by adding appearance code to our datalist object in the HTML part of the page. Here is an example on how to change the font and color of the text to the feed.




<asp:DataList runat="server" id="dlRSSData">
<itemtemplate>
<font size="2" face="Arial" color="#ff000">
<a href="<%# DataBinder.Eval(Container.DataItem, "Link")
%> " target="_blank">

<%# DataBinder.Eval(Container.DataItem, "title") %> </a> <br />

<%# DataBinder.Eval(Container.DataItem, "description")
%> </font> <br /> <br />

</itemtemplate>
</asp:DataList>




Now with 2 little snippets of code we changed the font size, face, and color. Its easy and makes the XML feed look great.

Labels: , , , , , , ,

0 comments | Saturday, April 21, 2007

If your like me, you were probably pretty pumped when you heard that the official release of AJAX 1.0 for Visual Studio was available. I had messed around with "Atlas" when it was out and I see the similarities, but it wasn't until fairly recently that I really got my hands dirty in the new AJAX toolkit for VS 2005.

In this example we are going to be working with the new 'Calender Extender'. This cool new feature adds so much to your .NET web application but are so SIMPLE to use, you will be blown away at how easy it is. First lets create a new ASP.NET AJAX 1.0 enabled web site. We can do this by opening up Visual Studio 2005 and selecting new, then select AJAX enabled web site.


Lets take a look at our .NET page before adding any controls. If you are used to using Visual Studio to build web based applications then you should be pretty familiar with the standard layout and items that are involved with a web application. But with the new AJAX toolkit you will notice a new control on your page on default. Its called the 'AJAX Script Manager' (see screen shots below) I'm not going to go into the script manager in this example but it is used by the AJAX toolkit and is necessary to have on your page above any code on the page that will use it. Its best to keep it at the top of the page so that anything you have under it can use it. You only need 1 Script Manager per page and it will NOT effect the over-all appearance of your .NET page.


Now lets add a 'AJAX Update Panel' to our form. You will find it under the AJAX Extensions section of your Toolbox. The update panel assists in the AJAX functions, in most cases anything you want to update on the form without the whole page posting back you will want to place inside an update panel. Now that we have our update panel on the page we are going to drag and drop a .NET text box and a .NET Image into the Update Panel. This can be done very easily, just simply drag and drop like you normally would except place it inside the Update Panel.

Lets name the text box "txtSelectedDate", and the image "imgCalender". Now lets drag the AJAX CalenderExtender into the Update Panel as well. So now we should have a text box, an Image and a Calender Extender inside the update panel. Now lets assign some properties to our new form controls. For the ASP:Image lets set the ImageURL to point to a picture of a calender Icon like this one;

Your form should now look similar to this;


We'll finish up by setting the necessary properties of the calender Extender. We're going to set the PopupButttonID property to 'imgCalender' which is image we put in the update panel on our form. Then we'll set the TargetControlID to 'txtSelectedDate' which is the text box we added. Now make sure that the CalenderExtender , EnabledOnClient, and EnableViewState
properties are all set to 'True'.



Now run your form and click the calender image we put on the page. You should get a cool pop up calender control. Simply select a date and the calender will disappear and the date you selected will be placed in the text box on the form.


Pretty easy huh! This is just one of the features of the AJAX toolkit for Visual Studio. You can download the sample Visual Studio 2005 project by CLICKING HERE

Labels: , , , , , ,