.NET and Coldfusion and IIS7 and Charting and AJAX and…

ARRGH!

ARRGH!

     I am in the process of creating an application that uses the MS Charting controls along with some AJAX.  I was working on my machine of XP with VS 2008.  I didn’t have IIS installed so I was using built in browser functionality from VS to view site. Everything was going great. Was being the key word.  I had to finally move it over to a real development environment for more reasons than one.  When I finally moved the application it broke. It just wouldn’t work.  I got a 500 error.  Then after a few refreshes I found that I had this error: The WebResource.axd handler must be registered in the configurtion to process this request.  What!? What does that mean?  I searched for a few days to find a solution. I came up with a few from restarting the web service to reinstalling the .NET framework (none of which worked by the way).  After 4 days I finally came across the solution, Coldfusion does not play well with AJAX and .NET. For some reason, after looking at the compiled error logs, I saw that my appication was calling a .DLL in the Coldfusion directory.  Why on earth would my Microsoft .NET 3.5 SP1 application even be concerned with anything Coldfusion?  It seems that it is a mapping issue within IIS 7.  Yup, IIS 7. I had to remove (not sure if it was the right thing to do) but I removed all mappings to anything Coldfusion (.cfm, cfml, jsp, etc.).  It it was mapped to anything in the Coldfusion directory, I got rid of it.  Guess what?  It worked.  Application works like a champ now!  I am putting this up here so to be another resource to call upon.  There wasn’t anything I found that said to do what I did.  The closest I came was to have .NET and Coldfusion install on different servers.  Likely scenerio.  Yea right… Hope this helped someone.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

Creating a Pop-Up Using ASP.NET VB

I have searched for a way to create a simple popup on my project. Something that is scalable and reusable. I found the answer and I do not know why I never thought of this. It consists of a little five line function. It can probably be done in C# as well.  I just haven’t taken the time to convert it over.  Well here it is.  All you have to do is pass in the page, the message, and a key.

 

CreateMessageAlert(page, message, “keyname”)

 

Message has to be type of string:

Dim message As String

 

Below is the code to implement the above call:

 

Public Shared Sub CreateMessageAlert(ByRef aspxPage As System.Web.UI.Page, _

                           ByVal strMessage As String, ByVal strKey As String)

        Dim strScript As String = “<script language=JavaScript>alert(‘” _

                                            & strMessage & “‘)</script>

        If (Not aspxPage.IsStartupScriptRegistered(strKey)) Then

            aspxPage.RegisterStartupScript(strKey, strScript)

        End If

    End Sub

 

That is it. Not too bad. Pretty easy stuff. Hope this helped.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

  

Using Classes in ASP.NET VB

I have created a web application that introduced me to something I haven’t really used before, classes.  They are a great thing.  This may be a 101 style post but I find it very interesting.  What I have done is create a class of user. Inside the user.vb class I have all the methods/functions that has to do with the user.  I have things like a function to find the user name, another to find user ID, and yet another to find the user roles. To use it all you have to do is create an instance of that class and you can call the methods directly on the caller page. For instance my class is named user.vb. To use it you have to reference it. This is how I reference it:

 

Dim iUser As New User

 

That’s it! Then to use the methods:

 

iUser.methodname()

 

How easy is that?  I also have a sqlMethod.vb which houses all my sql methods used throughout my web application.  I even use it in the User class. Again, the same way whether its in a class or another page is to use the:

 

Dim iSQL As New sqlMethods

 

And then you guessed it, to use any method just reference it like:

 

iSQL.methodname()

 

You can also pass in variables if you need to:

 

iSQL.Methodname(var1, var2)

 

One thing to remember is that the call has to be set to a variable. You have to have:

 

Dim roles As String

Roles = iSQL.roles(userID)

 

To create the class, if your using Visual Studio, you just have to right click on the project name and choose add new item and choose class, name it, and your good to go to use one. Make sure you Import anything that is needed at the top of the class. Below is a real world example of how I use it.

 

Here is my User.vb code:

 

Dim iSQL As New sqlMethods

Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String

        Dim userID As String

        userID = iSQL.GetUserID(userlogin, userpassword).ToString

        Return userID

    End Function

 

Here is my sqlMethods.vb Code:

 

Public Function GetUserID(ByVal userlogin As String, ByVal userpassword As String) As String

        Dim mySQLString As String = “SELECT tblUser.userID FROM tblUser WHERE tblUser.userLogin = ‘” & userlogin & “‘ AND tblUser.userPassword = ‘” & userpassword & “‘”

        Dim myCommand As New SqlCommand(mySQLString, dsn)

        Dim userID As String

        Try

            dsn.Open()

            userID = Convert.ToString(myCommand.ExecuteScalar())

            If userID = “” Then

                Return 0

            Else

               Return userID

            End If

        Catch ex As Exception

            ‘Something went wrong

            dsn.Close()

            Throw ex

        Finally

            ‘Cleanup

            dsn.Close()

        End Try

    End Function

 

Hope this helped.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

Connection Strings for Desktop Search in Application

Okay, I have been fighting with this for about two days now.  I believe I mentioned previously that there isn’t much docuemntation on the new desktop seach for Windows Server 2008.  it turns out that what I thought to be true was in fact wrong.  I thought, and please correct me if I am wrong, that the windows search feature in Windows Server 2008 is the same as the windows search feature in Vista.  Boy I was wrong on that one.  I was trying to search for something that wasn’t there.  I just needed a different connection string is all. Here is what I used for Vista:

 

Dim connString As String = “Provider=MSIDXS.1;Integrated Security .=””

 

It works fine.  I thought it worked fine in server 2008 also.  I was trying to find a whole plethora of solutions that could fix my problem.  What I needed to change was that line of code above to:

 

Dim connString As String = “Provider=Search.CollatorDSO;Extended Properties=’Application=Windows’”

 

Go figure! The error I was getting was System.Data.OleDb.OleDbException: Service is not running.

 

That told me that the windows indexing or windows search was not running. I didn’t figure that the connection string would be wrong.  Oh and there is no catalog created when you index files on server 2008.  You have to reference them this way:

 

SELECT filename blah blah FROM systemindex..scope() WHERE SCOPE=‘file:C:\inetpub\cgweb\appname\repository’

 

You also have to not include the directory folders like this:

 

AND system.itemtype NOT LIKE ‘%Directory%’

 

I guess that can be chalked up as lessons learned.  Don’t look for the obvious, look of the unobvious. Hope this helps you.  Have fun coding and as always, if there are any questions or suggestions, they are welcome.  Thank you.

Page.IsPostback is Sneaky

   I had an issue yesterday with a dropdown on a form. I was trying to post the values to a new form.  All the values would post fine except this one dropdown.  I was racking my brain.  What was happening is everytime I submitted the form, the value of the dropdown (varname.SelectedItem.Value) would be item[0] no matter what I choose!?  This was driving me crazy because all the other form variables were passing just fine. I even had another dropdown that was posting fine.  This one was giving me a problem.  What was the difference you may ask?  The only difference was that the dropdown that was not passing correctly was dynamically populated by a databind.  Well, it turns out, which now makes sense, is that when the page posts back, the original value is sent. This happens because the page load function runs first on post back. Hence the default value being posted. What you have to do is this;

 

If Not Page.IsPostBack Then

   varname.DataSource = DataTable

   varname.DataTextField = “value

   varname.DataValueField = “value

   varname.DataBind()

End If

 

Adding these two lines of code around my databind worked wonders. It’s the small things that count. Keep your eyes open and as always, if there are any questions or suggestions, they are welcome. Thank you.

Working With Dates and Times Using ASP.NET VB

I know we have all have to use dates at some time or another.  I came across this posting and thought I would list it here for you.  Hope it helps.

Dim now As Date = Date.Now ‘ date and time

Dim today As Date = Date.Today ‘ just the date

Dim tomorrow As Date = today.AddDays(1)

Dim yesterday As Date = today.AddDays(-1)

‘ use parse functions to convert from strings

Dim vb1 As Date = Date.Parse(“1991-05-01″)

‘ use culture info to parse dates in regional formats

Dim gb As New CultureInfo(“en-GB”)

vb1 = Date.Parse(“01-05-1991″, gb.DateTimeFormat)

‘ format dates as strings

vb1.ToLongDateString() ‘ Wednesday, May 01, 1991

vb1.ToShortDateString() ‘ 5/1/1991

vb1.ToLongTimeString() ‘ 12:00:00 AM

vb1.ToShortTimeString() ‘ 12:00 AM

vb1.ToString(“u”) ‘ 1991-05-01 00:00:00Z

vb1.ToString(“yyyy-MM-dd”) ‘ 1991-05-01

‘ TimeSpan represents differnce between two dates

Dim time As TimeSpan = tomorrow – today

Dim days As Integer = time.Days

Dim hours As Integer = time.Hours

Dim minutes As Integer = time.Minutes

Dim seconds As Integer = time.Seconds

Dim milliseconds As Integer = time.Milliseconds

‘ Add time using other timespan instances

time.Add(New TimeSpan(days, hours, minutes, seconds,

milliseconds))

‘ or

time += New TimeSpan(days, hours, minutes, seconds,

milliseconds)

‘ use a timespan to add time to a date

today.Add(time)

‘ or

today += time

‘ timespan represented as Days.Hours:Minutes:Seconds:

‘ Subseconds

time = TimeSpan.Parse(“1.2:3:4:5″)

‘ or

If TimeSpan.TryParse(Console.ReadLine(), time) Then

Console.WriteLine(time)

End If

 

As always, if there are any questions or suggestions, they are welcome. Thank you.

Using Windows Desktop Search in ASP.NET VB Application

I was searching around the Internet for something or someone to help me with seaching files in a given directory.  No, not that easy, it had to be recursive.  That is where I ran into problems.  As I was looking, I came across something that I wouldn’t even have thought of, why not use windows desktop search?! I was like what?  There is no way.  Then I got to thinking, it’s Microsoft.  Why not. So I dove right in. I am all up for learning something new.  Even if it is something I was not even looking for to begin with, sort of.  Well, I got it working and I thought I would share with you what I did and post some code for you to look at.  I can even use multiple keywords to search on. I do use drop downs vice free for text field though.  I already know what the files are named if you have been following the blog, you know what I am refering to.  With that said, lets get into some code.

 

First here is the code for the datagrid.  I chose to use a datagrid because of the ease of creating the columns.  It was simple to create a hyperlink field. See below.

 

<asp:DataGrid runat=”server” ID=”datagrid1″ Font-Name=”Verdana”

AutoGenerateColumns=”False”

AlternatingItemStyle-BackColor=”#eeeeee”

HeaderStyle BackColor=”Navy”

HeaderStyle-ForeColor=”White”

HeaderStyle-Font-Size=”15pt”

HeaderStyle-Font-Bold=”True”>

<AlternatingItemStyle BackColor=”#EEEEEE”>

</AlternatingItemStyle>

<Columns>

<asp:HyperLinkColumn

DataNavigateUrlField=”Path”

DataTextField=”Filename”

HeaderText=”File Name” />

</Columns>

<HeaderStyle BackColor=”Navy”

Font-Bold=”True”

Font-Size=”15pt”

ForeColor=”White”>

</HeaderStyle>

</asp:DataGrid>

 

On this page I also have drop downs and a search button.  That is what is used to perform the search. 

 

In the code behind in the Page_Load function(I really wish MVC would be finished so I could start using that, but that’s another story) I added the following:

 

If Page.IsPostBack Then

      Dim keyword1 As String = dropdown1.Text

      Dim keyword2 As String = dropdown2.Text

      Dim keyword3 As String = dropdown3.Text

      Dim keyword4 As String = dropdown4.Text

      Dim strCatalog As String

      ‘ Catalog Name

      strCatalog = “catalogNameHere”

      Dim strQuery As String

      strQuery = “select create, filename, path from scope() “

      strQuery = strQuery & ” WHERE FILENAME LIKE ‘%” & keyword1 & “%’”

      strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword2 & “%’”

      strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword3 & “%’”

      strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword4 & “%’”

      strQuery = strQuery & ” AND Path NOT LIKE ‘%vti%’ ORDER BY create DESC”

      Dim connString As String = “Provider=MSIDXS.1;Integrated Security .=”;Data Source=’”

      & strCatalog & “‘”

      Dim cn As New

      System.Data.OleDb.OleDbConnection(connString)

        Dim cmd As New

      System.Data.OleDb.OleDbDataAdapter(strQuery, cn)

            Dim testDataSet As New Data.DataSet()

            cmd.Fill(testDataSet)

            Dim srvrnm As String = Server.MachineName

            Dim dt As DataTable = testDataSet.Tables(0)

            Dim rownum As Integer = 0

            For Each row As DataRow In dt.Rows

            dt.Rows(rownum)(“path”) = dt.Rows(rownum)(“path”). _

      ToString.Replace(“c:\inetpub\dirname\”, “\\” & srvrnm & “\cgweb\”)

                rownum = rownum + 1

            Next

            Dim source As Data.DataView = testDataSet.Tables(0).DefaultView

            datagrid1.DataSource = dt

            datagrid1.DataBind()

      End If

Now step by step through the code.

First we create variables to hold the values of the dropdowns to use later in the query.

Dim keyword1 As String = dropdown1.Text

Dim keyword2 As String = dropdown2.Text

Dim keyword3 As String = dropdown3.Text

Dim keyword4 As String = dropdown4.Text

 

We then create a string variable to hold the catalog name (which will be covered later).

‘ Catalog Name

strCatalog = “catalogNameHere”

 

Now we build our query using dynamic data. Like I said previosly, I used drop down because the file names are known. Here is the query string being built:

Dim strQuery As String

strQuery = “select create, filename, path from scope() “

strQuery = strQuery & ” WHERE FILENAME LIKE ‘%” & keyword1 & “%’”

strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword2 & “%’”

strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword3 & “%’”

strQuery = strQuery & “AND FILENAME LIKE ‘%” & keyword4 & “%’”

strQuery = strQuery & ” AND Path NOT LIKE ‘%vti%’ ORDER BY create DESC”      

 

We then have to create our connection string to use the catalog and then fill a dataset with the data returned:

Dim connString As String = “Provider=MSIDXS.1;Integrated Security .=”;Data Source=’” & strCatalog & “‘”\

Dim cn As New

System.Data.OleDb.OleDbConnection(connString)

Dim cmd As New

System.Data.OleDb.OleDbDataAdapter(strQuery, cn)

Dim testDataSet As New Data.DataSet()

cmd.Fill(testDataSet)

 

I needed to replace some of the text before it was displayed so I set the dataset to a datatable and looped through the rows and changed what I needed. I use the varibale rownum so I can look at each row in the loop.  See below:

Dim srvrnm As String = Server.MachineName

Dim dt As DataTable = testDataSet.Tables(0)

Dim rownum As Integer = 0                

For Each row As DataRow In dt.Rows

dt.Rows(rownum)(“path”) = dt.Rows(rownum)(“path”).ToString.Replace _

(“c:\inetpub\dirname\”, “\\” & srvrnm & “\newdirname\”)

rownum = rownum + 1

Next

 

Last but not least I databind the datatable to the datagrid on the display page.

datagrid1.DataSource = dt

datagrid1.DataBind()

 

That’s it. Not too bad. I was happy with myself. I do have to add in the handling of the ‘no records found’ still.

 

As always, if there are any questions or suggestions, they are welcome. Thank you.

P.S. I will work on my coloring scheme. Having issues at the moment.

File Upload Using ASP.NET VB

I noticed or I should say it was brought to my attention that although I show how to work with files, I never discussed uploading files.  Well here it is.

 

In its simplest form, uploading a file using asp.net VB is quite simple. The following 2 links show how it is done:

 

http://msdn.microsoft.com/en-us/library/aa478971.aspx

http://support.microsoft.com/kb/323245

 

This link covers size limitations and how to circumvent it and also other things like multiple file uploads, controlling file types, and other issues.

 

On another note, if you want to see the code right here and now, just see below (this is how I do it):

 

In the display page we have the following:

 

<font face=”verdana”>Select File to Upload:</font>

<input id=”uploadedFile” type=”file” accept=”" runat=”server” />

<input type=”button” id=”upload” value=”Upload” onserverclick=”Page_Load” runat=”server” />

 

In the code behind we do this:

Make sure you import:

Imports System.IO 

Then button_click() you have:

If Not (uploadedFile.PostedFile Is Nothing) Then

Try

Dim postedFile As HttpPostedFile = uploadedFile.PostedFile

Dim filename As String = Path.GetFileName(postedFile.FileName)

Dim fileExt As String = Path.GetExtension(postedFile.FileName)

Dim contentType As String = postedFile.ContentType

Dim contentLength As Integer = postedFile.ContentLength

Dim qryString As String = Request.QueryString(“dir”)

If fileuploaded = True Then

message.Text = “The file was renamed and uploaded successfully.”

postedFile.SaveAs(currentDir & directorySeparatorChar.ToString() & filename)

End If

Catch ex As Exception

message.Text = “Failed uploading file. Please use feedback form.”

End Try

End If

 

The qryString variable would be the directory you are saving the files to.

This is how I did my qryString;

‘Find out the server name

 Dim srvrnm As String = Server.MachineName

‘Set up root directory. Doesn’t matter if live of dev, will know by above statement

Dim currentDir As String = “\\” & srvrnm & “\folder\folder”

 

To rename the files you would add the following code after the postedFile.saveAs above:

File.Move(currentDir & directorySeparatorChar.ToString() & filename, currentDir & directorySeparatorChar.ToString() & FilereName & fileExt)

 

A couple of last things, the ASPNET user needs to have permissions to write to the folder you are uploading to. Also, if you upload a file that is already there, it will not overwrite, it will throw an error. You have to try catch that error. You also have to add enctype=”multipart/form-data” to the form tag to allow file to be uploaded.

 

To allow for larger files than 4Mg you need to add the following code to the web.config file located in the application you are working on (add it inside the <system.web> node):

<httpRuntime

executionTimeout=”90″

maxRequestLength=”4096″ ß This would be changed to indicate size of file in Kb

useFullyQualifiedRedirectUrl=”false”

minFreeThreads=”8″

minLocalRequestFreeThreads=”4″

appRequestQueueLimit=”100″ />

 

That should work for you. If there are any issues or questions, post them and I will do my best to get back to you with an answer or a solution. Thank you.

Performing Loops – VB and C#

This will be a short post. I just wanted to display the differences between C# and VB when performing loops.  See below:

VB:

For i As Integer = 10 To 1 Step -1

Console.WriteLine(i)

If i < 5 Then

Exit For

End If

Next

 

Dim start As Integer = 5

For i As Integer = start To start + 10

Console.WriteLine(i)

Next

 

Dim str As String

Do

str = Console.ReadLine()

Console.WriteLine(str)

Loop Until str = “”

 

Do

str = Console.ReadLine().Trim()

If String.IsNullOrEmpty(str) Then

Exit Do

End If

Console.WriteLine(“You typed:{0}”, str)

Loop

Dim names As String() = New String() {“Bob”, “David”}

For Each name As String In names

Console.WriteLine(name)

Next

 

C#: 

for (int i=0; i<10; i++) {}

 

while (i<10) { i++; }

 

do { i++; } while (i<10);

 

foreach (ListItem item in list.Items) {}

 

Searching for Files Using ASP.NET VB

      One of the problems I had finding is searching directories for files via user input. Right now I am using a text field to allow users to enter search criteria. I may go to drop downs. The reason I may do this is because the files I am uploading are all being renamed as per the directory structure. (i.e. test.txt would be renamed to asp_ dept_station_1 with the directory structure being c:/asp/dept/station/). Then I just tack on a consecutive number at the end. But I digress. What I have found to be a good way of searching all files in the folders is to loop though all directories and add the files to an array() of type fileinfo. After that, I then loop the array and add the found files to a datalist. I have found this to work pretty well. I am now working on getting the search to allow for more than one word. That is why I may just go to dropdowns. Make sense? Anyway, the code is below for what I am doing currently. I will re-post if I decide to change it. If there are any improvements that can be made, please let me know. Thank you. Now that I think about it, I am using the same code as the post: Recursively Browse Directories Using ASP.NET VB I only added an ‘if’ loop to check for search criteria in filename:

If fi.Name.Contains(searchCriteria.ToUpper) Then
filelink = " Server.UrlEncode(dirname) + directorySeparatorChar + Server.UrlEncode(fi.Name) + "&action=download>" + fi.Name + "
"
row = myfiledt.NewRow()
row("filename") = filelink
row("creationtime") = fi.CreationTime
myfiledt.Rows.Add(row)
End If
position += 1 …