Email using C#

I had a co-worker recently ask me what I did to send email from a C# web application. I gave him what worked for me. He made a few adjustments and sent it back to me.  I did request that he send me what he came up with that finally worked for him. I think he did a better job than I so I am going to post it for you to see. Have a look and see how it may fit into your application or project. Improvements are welcome. He ended up writing a class to call from anywhere in the project. It takes the following arguments; from, to, subject, body, attachments, and isBodyHTML boolean.

using System.Net;
using System.Net.Mail;

public class mailer
{
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody+disclaimer;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto@xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = "mail.domain.com";
smtp.Port = 25; //Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
}

Thanks Shane!

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

AJAX Toolkit Mysterious Behavior

     I have been working with AJAX extensions for some time now.  I recently moved jobs and started working on a different project.  I remember that in my previous position I had a problem with Visual Studio 2008 working with AJAX and .NET Framework 3.5 SP1. I do not remember the problem or the fix but I resolved the issue originally. Now, here at me new job, I had the exact same problem.  What did I do this time you may ask?  I searched frantically around the web for a resolution because I didn’t remember what I did last time to fix the problem.  I found a lot of suggestions from removing wireless mouse (??) to reinstalling .NET 3.5 SP1 to restoring Visual Studio 2008 to initial install settings. None of which worked by the way.  I thought I would let you know this time what I did to remedy the problem.  First, the issue was I could not see the AJAX Toolkit in the VS toolbox.  I saw the AJAX Extensions tab and it was populated but no luck with the toolkit.  I had downloaded the AJAX binaries and extracted on my shared drive.  I included the toolkit on my web project and it did not work.  I tried several other things and to my disappointment didn’t work. 

The solution you ask: 

  • Copy the ajaxcontroltoolkit.dll to a local folder on your c: drive.
  • Then create a new tab and name it whatever you like (I named mine AJAX Toolkit).
  • Then right click inside toolbox in VS and then choose items. 
  • After the popup shows itself choose browse button and browse to newly placed .dll file. 
  • The toolkit will start populating from there. 

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

.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.

Standards of Coding

I just gave a presentation to a team of developers about coding standards for .NET.  I was a bit nervous as most of them were/are smarter than I.  I think it went off really well.  Better than I thought it would.  At least that is the feedback I got.  What I covered was that using .NET, there really are not ’standards’ to follow that are better than another.  What needs to be considered is that a set of standards are made and then followed by the development team.  These standards can be something created by a team member or something pre-built by a third party (MVC, nTier, etc.). What I am saying is that standards can be anything the team comes up with.  They only become standards if they are used as such.  If I came and implemented standards for the team for .NET and nobody used them, then what you have in essence is a different way of coding than that of anybody else.  If everyone used the methodology put forth, that’s when standards start to take shape.  I know there are many different methodologies but you only need one to get a team on the same page.  I am interested on any other thoughts on this subject. 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.

Working with a Database in ASP.NET VB

I just realized I added code on the blog for working with databases in C# but not for VB.  This will be the missing post of one way in which you can use Visual Basic. Enjoy!

Imports System.Data

Imports System.Data.SqlClient

Dim cs As String = “Data Source=.\SQLEXPRESS;” + _

Dim cs As String = “Initial Catalog=NamesDB;” + _

Dim cs As String = “Integrated Security=True;”

Using con As New SqlConnection(cs)

con.Open()

‘ insert a record

sql = “INSERT INTO Names(Name) VALUES(@Name)”

Dim cmd1 As New SqlCommand(sql, con)

cmd1.Parameters.Add(“@Name”, SqlDbType.NVarChar, 100)

cmd1.Parameters(“@Name”).Value = “Bob”

cmd1.ExecuteNonQuery()

‘ insert a second record

cmd1.Parameters(“@Name”).Value = “David”

cmd1.ExecuteNonQuery()

‘ read records

sql = “SELECT * FROM Names”

Dim cmd2 As New SqlCommand(sql, con)

Using r As SqlDataReader = cmd2.ExecuteReader()

Dim iName As Integer = r.GetOrdinal(“Name”)

Do While r.Read()

If r.IsDbNull(iName) Then

Console.WriteLine(“Null”)

Else

Console.WriteLine(r.GetString(iName))

End If

Loop

End Using

‘ read a single value

sql = “SELECT TOP 1 Name FROM Names”

Dim cmd3 As New SqlCommand(sql, con)

Console.WriteLine(cmd3.ExecuteScalar())

End Using

 

(This post was done with the help of LearnVisualStudio.net. Thanks!)

In a future post I will be sure to add a post about how to use stored procedures! Hope this helps you.  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.

Learning MVC: LINQ to SQL

I am in the process of watching a video about pulling back records form a database using LINQ to SQL.  This is new functionality that comes in .NET 3.0 or 3.5 (not exactly sure which one). I do know MVC is not available to use unless you have Framework 3.5 installed so we will go with that anyway. I was just looking at a video that indicate there are two ways to run a ‘query’ using LINQ to SQL.  Below are the two ways. We were working with movies so the queries are for movies. Here they are:

 

Query Syntax:

Dim movies = From m In dataContext.Movies Select m

 

Method Syntax:

Dim movies = dataContext.Movies.Select(Function(m) m)

 

Both of the statements pull back all rows from the movies table. Pretty crazy if you ask me.  I personally like the first statement.  It is easier to read in my opinion.  I will be venturing into learning MVC with the help of several people (Scott Guthrie, Stephan Walther, and Scott Hanselman amoung others [Google]). I don’t think there are many books out on it yet.  I am usign MVC release candidate currently. As I go through the steps of learning I will post what I learn. I will also post the steps to getting to this point at a later date. Have fun coding and as always, if there are any questions or suggestions, they are welcome. Thank you.

Posted in MVC. Tags: , , . 2 Comments »

Having Issues w/ Local Development and MS Server 2008

Our organization recently (within the last week) switched from server 2003 to server 2008.  When we were on server 2003 I developed my .net applications locally on my workstation, tested them and then uploaded to the development server for testing by the customer. That worked out well because both instances were running the same environments.  Now that we have gone to windows 2008, I can no longer develop on my workstation and upload to the development server. For one the environments are different. I use IIS 6 and server 2008 uses IIS 7. Another change is the development structure. I used the same directory structure as development and now it has changed because of incorporating CMS into our coding. It has been a long time coming. I am glad it is finally being implemented. Also there are differences in the OS’s so when I develop on my workstation I have to change code to work on the new development environment. It wouldn’t be so bad except that when there is an error, how does one troubleshoot if the environments are different?  Hence the steps of setting up remote debugging.

Well, that is another story. I have tried, I have connected, I have not successfully hit a break point yet.  I hope to have that fixed very soon. Once I can debug remotely, it should make it a bit easier, in theory anyway. The reason I brought this up in the first place is that I had an application almost completed and one of the last things I worked on was the addition of using the windows desktop search within the application which I have wrote about in the past. I’ll tell you what, in the 2008 environment, it has changed. What worked previously does not work currently. The syntax is different.  Triflin’! Anyway, I just wanted to put that out there. When I find the difference (which there is not much documentation on it at all) I will post it and name it the same but for server 2008 or something like that. Until then, have fun coding and as always, if there are any questions or suggestions, they are welcome. Thank you.

 

Oh, and Happy Birthday Elvis!