Adsense

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, June 25, 2007

Installing Infragistics on Vista Ultimate with IIS 7.0

I just upgraded to Windows Vista this weekend and am trying to get my development box up and running. We us Infragistics in a couple of our ASP.Net projects and I'm finding that it's not quite as straight forward to install it on Vista.

I found a great site with a walk-through of how to setup your Vista and IIS to allows Infragistics to install correctly.

Basically you need to do the following...

  • Disable User Account Control (UAC)
  • Restart your machine
  • Edit the path of your IIS WWWRoot folder in the registry
    • Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InetStp\PathWWWRoot
    • Change "%SystemDrive%\inetpub\wwwroot" to "C:\inetpub\wwwroot"
  • Enable IIS 6.0 Compatibility in the "Turn Windows features on or off" section of the Programs menu (make sure to check all the child boxes)

That should allow you to get your infragistics installed on Windows Vista Ultimate and IIS 7.0.

Developing on Windows Vista

I recently took the plunge and installed Vista Ultimate on my Dev box. I'm sure this will have it's ups and downs, but on the bright side... It will most definitely spawn lots of blog posts.

I will be installing Orcas soon and playing around too. I will also be focusing as much as I can on WPF, WCF, and WWF, so I'm sure I will have a lot of fun stuff to blog about for the next few months (after I get back from my Honeymoon that is. Yay for Hawaii...!)

Thursday, June 14, 2007

Web Services, IDictionaries and Serialization... Oh My!

I have been building some .Net web services lately and created one that was trying to return a generic IDictionary. (IDictionary<int, int>) To my surprise and ultimate disappointment, I was presented with the following Server Error when trying to access my webservice...

"The type System.Collections.Generic.Dictionary ..<removed babble>.. is not supported because it implements IDictionary."

It looks like the XmlSerializer is unable to serialize objects that implement IDictionary. How annoying! I use a lot of generic dictionaries and it's a bit of a pain work around this XmlSerializer limitation. I was able to find a solution from this Aaron Skonnard post on the msdn site.

The solution shows you how to write a class that actually wraps your dictionary object. The values of your dictionary are copied to an array of serializable objects which are allowed to be passed through your web service and then deserialized on the other end. Pretty handy and worked really well in our solution.

Aaron warns that the IXmlSerializable interface is undocumented/unsupported feature of the .Net Framework and is subject to change at any time.

Friday, June 01, 2007

How to sort a generic IList<T>

Sorting a generic IList
I was trying to sort a generic IList<> and found a fairly simple way of doing it.
Step 1
You need to implement IComparable for the type contained in your IList. For this example I am going to use a simple Language Dto class.
public class LanguageDto : IComparable {
private String name;
public string Name { get { return name; } set { name = value; } }

public LanguageDto(string name) {
this.name = name;
}

#region IComparable Members
public int CompareTo(object obj) {
if (obj is LanguageDto) {
LanguageDto language = (LanguageDto)obj;
return this.name.CompareTo(language.name);
}
throw new ArgumentException(string.Format("Cannot compare a LanguageDto to an {0}", obj.GetType().ToString()));
}
#endregion
}

STEP 2

Sort your IList. To do this you will use the ArrayList.Adapter() method passing in your IList, and then calling the Sort method. Like so...

ArrayList.Adapter((IList)languages).Sort();
Note: languages is of type "IList<LanguageDto>"
Languages should then be a sorted list of your type!

Tuesday, May 29, 2007

Web Service Security (Invalid URI: The format of the URI could not be determined)

Ran into an issue today while trying to connect to a Java Web Service from a .Net environment. It looks like this happens when Web Service Security is enabled in the application server of the web service and uses the ActorURI attribute. .Net's Web Services Enhancements feature does not support relative URI's for this attribute and basically FUBAR's on you. Therefore, you must us an absolute URI.

An example of an absolute URI is "http://LoginWebService" while an example of a relative URI would be "LoginWebService"... You must configure your Application Server to using either the Rational Application Developer or the Application Server Toolkit.

  1. Open the Web Service Editor, click the Extensions tab and expand Server Service Configuration.
  2. Enter the full absolute URI in the Actor field.
  3. Expand Response Generator Service Configuration Details > Details.
  4. Enter the full absolute URI in the Actor field.

Source

Sunday, March 04, 2007

Sending mail through Gmail Programatically - C# .Net VS2005 Gmail

I was implementing a simple Contact Us form for a friend's website that would allow users to shoot him an E-mail message from the site. You can send E-mail directly from a .Net application using an SMTP server, but most free web-based E-mail companies wont allow you to use their SMTP servers for stuff like this. I was delighted to find that you could get this working with Gmail. I'll show you a quick sample method that will allow you to do this.
Information You'll Need...
  1. Your Gmail information (Username, Password)
  2. The Gmail SMTP server address (smtp.gmail.com)
  3. The port Gmail uses (465 or 587)
Namespaces used...
  1. System.Net;
  2. System.Net.Mail;
  3. System.ComponentModel;
Key Objects...
  1. MailMessage
  2. SmtpClient
Your Configuration File
<appSettings> <add key="pswd" value="YourGmailPassword"/> <add key="account" value="yourUserName@gmail.com"/> <add key="host" value="smtp.gmail.com" /> </appSettings>
Implementing a simple SendMail method
public void SendMail(string host, int port, string userName, string pswd, string fromAddress, string toAddress, string body, string subject, bool sslEnabled) { MailMessage msg = new MailMessage(new MailAddress(fromAddress), new MailAddress(toAddress)); // Create a MailMessage object with a from and to address msg.Subject = subject; // Add your subject msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.Body = body; // Add the body of your message msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = false; // Does the body contain html SmtpClient client = new SmtpClient(host, port); // Create an instance of SmtpClient with your smtp host and port client.Credentials = new NetworkCredential(userName, pswd); // Assign your username and password to connect to gmail client.EnableSsl = sslEnabled; // Enable SSL try { client.Send(msg); // Try to send your message ShowMailMessage("Your message was sent successfully.", false); // A method to update a ui element with a message Clear(); } catch (SmtpException ex) { ShowMailMessage(string.Format("There was an error sending you message. {0}", ex.Message), true); } }


Calling your SendMail method

public void imgSubmit_Click(object sender, EventArgs e) { string pswd = ConfigurationManager.AppSettings["pswd"]; // Your Password string account = ConfigurationManager.AppSettings["account"]; // Your account name (username@gmail.com) string host = ConfigurationManager.AppSettings["host"]; // Your smtp server name (smtp.gmail.com) int port = 587; // The port used to connect to your host if (string.IsNullOrEmpty(pswd) || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(host)) // Validate App Settings ShowMailMessage("Unable to send your message. Configuration Error.", true); else { SendMail(host, port, account, pswd, txtFrom.Text, account, txtBody.Text, txtSubject.Text, true); } }
That's pretty much all there is to it. Your user fills out the form and clicks submit, and you get an E-mail in your Gmail box, send through your Gmail Account

Creating ActiveX Controls using C# in VS2005 (Intro)

We recently had a need to handle communication between an existing windows service (Running on client machines) and the current ASP.Net web application that we are working on. We chose to implement this feature using .Net Remoting and an ActiveX Control that would live on one of our aspx pages.

Implementing an ActiveX control in VS2005 using C# isn't difficult, but there are a lot of little issues that a co-worker and I encountered along the way.

I'll try and list the results of my research and a walk-through of creating a sample project. This will probably span several posts.

The steps that I will cover... Check it out HERE!

1. Create a C# Web Application project

2. Create a Windows Control Library project

a. Note: The Windows Control Library DLL file must be located in the same directory as the aspx page and NOT in the bin folder.

3. Add a user control item to the class library project

a. Creating the user control

b. Implement an Interface on your user control that will exposes members, methods, and events of your user control to COM

4. Create an object in your aspx page that embeds your user control

5. Handle communication between your web application and your ActiveX control using JavaScript

6. Expose and raise/handle user control events using javascript

7. A brief overview of configuring the .Net Framework and zone permissions to allow your web application and ActiveX control to communicate

8. Configuration issues with IIS (set to allow scripts only, not scripts and exes)

9. How to view IE7 error messages to get the exact exception that might be causing you problems.

Check it out HERE!

"Unrecognized configuration section 'connectionStrings'" .Net 2.0

If you get the following error when trying to bring up your IIS hosted web page, you might need to configure IIS to use .Net 2.0 instead of 1.1.

""Unrecognized configuration section 'connectionStrings'" .Net 2.0"

You can do this through the Internet Information Services configuration. (click on RUN from the start menu, type in 'inetmgr' and hit enter.)

Bring up the properties for your web page or virtual directory and click on the ASP.NET tab. Change your ASP.NET version to the appropriate value and try again.

Monday, January 29, 2007

Centering an Element via CSS vs JavaScript...

We recently ran into a situation where we were dynamically showing and centering model popup windows in an ajaxified environment. Our initial implementation had one down side.

We were showing and dynamically centering our div/panels via JavaScript. The windows would very briefly show up in its default location before jumping to center. Not a huge problem, but very annoying.

Our initial approach looked something like this. Statically build a hidden div/panel and when the user triggers a pop up dialog, call the CenterPanel method from JavaScript and show the panel. We were calculating the screen height and width and making it available globally.

The JavaScript process looked something like this...


CenterPanel("<%= SendToGeneralQueuePopupPanel.ClientID %>");


function CenterPanel(panelId){
var panel
= document.getElementById(panelId);
if (panel) {
panel.style.top
= ((screenHeight / 2) - (GetSize(panel.style.height) / 2)) + 'px';
panel.style.left
= ((screenWidth /2) - (GetSize(panel.style.width) / 2)) + 'px';
}
}

The result was a panel that would show up, then jump to the center of the screen. (Annoying)

After getting a bit of time to think about the issue, I remembered a much simpler way to center a control with pure CSS rather than dealing with problematic JavaScript at all. I'd used this technique in other projects and it makes things quite a bit more simple and stops the panel from jumping around the screen.

The CSS method...

We define a Panel to use as the pop that applies our modalPopup CssClass. Notice that the panel's Width is 200 and it's Height is 60.

<asp:Panel ID="PanelPopup" runat="server" CssClass="modalPopup" Width="200" Height="60">
<div style="text-align:center;">
Are you sure you wish to continue?

</div>
<div style="text-align:center;">
<asp:Button ID="ButtonYes" runat="server" Text="Yes" OnClick="ButtonYes_Click" />

<input id="ButtonNo"
type="button" value="No"
onclick="return HidePopupPanel('PanelPopup', '<%= PanelPopup.ClientID %>');" />
</div>
</asp:Panel>

The modalPopup CSS...

.modalPopup{
//Other CSS
left:50%;
margin-left:-100px;
top:50%;
margin-top:-30px;
}

The CSS above sets the left edge of the panel to be aligned with the center of the browser and then adjusts the left margin of the panel by subtracting 100 pixels (which happens to be half of the panel's width.) This centers the panel horizontally. In the same way, the panel is centered vertically by setting the top of the panel to the middle of the screen and then adjusting the top margin by subtracting 30 pixels which is half of the panel's height.

You can do a lot of fun stuff by using this technique. Setting the left, top, right or bottom of a control and then modifying the margins. Play around with it...

Friday, January 26, 2007

Session Management - Facade Pattern - C# .Net VS2005

State Management is a big part of any web application and using the session variable in ASP.NET is one way to persist data throughout a user’s session. Interacting with the session variable is fairly straight-forward…
Session["UserId"] = user.Id;
int id = (int)Session["UserId"];
Session[
"FirstName"] = user.FirstName;
string fName = (string)Session["FirstName"];
You can store any object or primitive into the session variable and retrieve the value at any time throughout the user’s session.

As you might imagine, your project could get fairly convoluted if you are accessing the same (or many different) session variable across many different pages throughout your application. Using explicit string values as your keys can also cause problems if you accidentally typo when entering them or decide to change one later. Throw several developers into the mix and this can turn into a nightmare.

You can alleviate some of this frustration by using an enum that contains all of your session key values. This allows you to make changes much easier, provides a quick reference to what objects you have in the session, and makes calls to the session variable consistent. The new session calls (with the help of an enum) would look like this.
enum SessionKeys {
UserId
= 1,
FirstName
= 2
}
Session[SessionKeys.UserId .ToString()]
= user.Id;
int id = (int)Session[SessionKeys.UserId .ToString()];
Session[SessionKeys.FirstName .ToString()]
= user.FirstName;
string fName = (string)Session[SessionKeys.FirstName .ToString()];
Taking this a step further, you could wrap this functionality into a static class in your project and route all session traffic through this class. By wrapping session calls in properties within this class, you can ensure type safety and make it much more easy to work with the session object.
public static class SessionFacade {
public static int UserId {
get {
return (int)Session[SessionKeys.UserId.ToString()];
}
set {
Session[SessionKeys.UserId.ToString()]
= value;
}
}
public static string FirstName {
get {
return (string)Session[SessionKeys.FirstName.ToString()];
}
set {
Session[SessionKeys.FirstName.ToString()]
= value;
}
}
}
Sessions calls would then look like this.
int id = SessionFacade.UserId;
SessionFacade.UserId
= user.Id;
string fName = SessionFacade.FirstName;
SessionFacade.FirstName
= user.FirstName;
The SessionFacade class acts as a Facade between you and the session object and alleviates much of the frustrations mentioned above. No more misspelled keys, no more huge updates if you want to change a key. Type safety... Who could ask for more?