Turning validators on from Javascript

Oh the adventures of JavaScript and ASP.NET. 

Can you turn on  validators [RequiredFieldValidators or otherwise] from JavaScript.  Yes, and actually it is easier than I thought.

ValidtorEnable(ControlId,True/False)

Ex:

//You could easily make this prettier by not hardcoding the ClientID here
ValidatorEnable(document.getElementById('ctl00_ContentPlaceHolder1_Login1_UserName'), true);

Keep in mind, you need to pass the object not the clientID of the object.

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

Convert C# to ActionScript

I'm really just getting started with flash and in the process of doing some research I came across what seems to be very interesting.  A free tool that allows a .NET developer to write code that will be translated into ActionScript on-the-fly. 

It also does C# to JavaScript, and C# to Java.  Interesting. 

The JsC homepage has a lot more information on this. kick it on DotNetKicks.com

VB.NET & C# Extension Methods

An easy way to HTMLEncode…

I recently had the need to do some HTMLEncoding on code that was already written.  That meant I had to go back into the code where appropriate and add a call to what would likely be a shared (VB.NET) or static (C#) function.  This really isn’t that big of a deal, but it would be a little annoying…I’d have to do something like this

    4     Public Class ApplicationUtils

    5         Public Function HTMLEncode(ByVal s As String) As String

    6             Return If(Not String.IsNullOrEmpty(s), System.Web.HttpUtility.HtmlEncode(s), s)

    7         End Function

8                    End Class

Alright, that’s not terrible – so I have to go into each web form and modify.  That means I will have web form code that looks like this (Below is within a repeater)

<%# ApplicationUtils.HTMLEncode(Eval("Association"))%>

I guess life could be worse.  That does the job, but it’s a lot to type, and it could be a bit more elegant.  An easier way to do this is is by leveraging a new .NET 3.0 (VB & C#) language feature (actually to be clear it’s really a smart compiler, but hey, whatever).  This feature is method extensions.  Basically, you can create a method to execute on your type just like .ToString().  In my case, I added the following code…

   11 <System.Runtime.CompilerServices.Extension()> _

   12 Public Module StringExtensions

   13 

   14     ''' <summary>

   15     ''' HTML encode a string if String.IsNullOrEmpty() = false

   16     ''' </summary>

   17     ''' <param name="s"></param>

   18     ''' <returns></returns>

   19     ''' <remarks></remarks>

   20     <System.Runtime.CompilerServices.Extension()> _

   21     Public Function HTMLEncode(ByVal s As String) As String

   22         Return If(Not String.IsNullOrEmpty(s), System.Web.HttpUtility.HtmlEncode(s), s)

   23     End Function

   24 End Module

That means instead of the code above, I can just do this…

<%# Eval("Association").ToString().HTMLEncode()%>

That’s it.  This is a pretty trivial example but there are probably tons of instances where this would be handy.  In my case, I liked it for the sheer lack of typing (Less typing less errors!) and the fact that I think it’s much more intuitive for someone to look at .ToString().HTMLEncode() rather than ApplicationUtils.HTMLEncode(whatever).  Of course, either way you’re going to want to wrap the HttpUtility.HTMLEncode() .NET provided logic in some function, so you have a single point of control for your code/logic.

Here is the MSDN link on extension methods in C#...the syntax is slightly different between VB.NET and C#


 

kick it on DotNetKicks.com

.NET C# Image / Photo Crop Logic

I just posted an article, tutorial, and code on how to crop an image using asp.net and a javascript library. 

You can check it out here!

Google Search Appliance API in VB.NET

A while back I ported the C# Google Search Appliance API to VB.NET.  You can find it here.

The original API was ported over from JAVA by MC+A.

Enjoy! kick it on DotNetKicks.com

CSS Tags Specific to Browser [IE6, IE7]

I came across this posting on Ed Eliot's blog and had NO idea this existed but it made my life a lot easier.  Full credit goes to him on this - the below is cut and pasted directly from his blog so I know where to find it in the future.  The URL for this post on his blog is:
http://www.ejeliot.com/blog/63

.box {
background: #00f; /* all browsers including Mac IE */
*background: #f00; /* IE 7 and below */
_background: #f60; /* IE 6 and below */
padding: 7px;
color: #fff;
}
I think it speaks for itself.  In my case, I easily fixed my annoying IE6 problem by applying a negative bottom margin that only applies to IE6.  Perfect.  I have used conditional statements to load CSS files based on your browser, but this is really helpful for those elements where you need to apply a tag to an element here or there - no point in creating an entirely different CSS file for things like this.

Login Control, ImageButton, Default Button...

I feel like I do a lot of bitching about the DefaultButton property.  But anyway...

What happens when you're using a Login control, and you decide to use an ImageButton for the Login button?  You guessed it, you break the DefaultButton property.

''Make the login button of the login control the default button. This is useful when your login control uses an image button.

''Doing so makes the DefaultButton property do nothing.

Dim loginControl As Control = Me.FindControl("Login1")

If Not loginControl Is Nothing Then

Dim loginButton As Control = loginControl.FindControl("LoginButton")

If Not loginButton Is Nothing Then

pnlLogin.DefaultButton = loginButton.UniqueID.Remove(0, pnlLogin.Parent.UniqueID.Length + 1)

End If

End If

Login Control, Default Button, ugh.

Yes, you can definitely find this information elsewhere but...what happens when you want to use a login control on a page and also use the default button property so when a user hits enter it submits the login control's button.  Nothing, because you have no idea what the hell the ID of the submit button is. 

Here is the workaround:

<asp:LinkButton ID="lnkbtn1" runat="server" />
<asp:Panel ID="pnlLogin" runat="server" style="display:none" CssClass="modalPopup"  DefaultButton="Login1$LoginButton"  >
     <div class="modaltext">
    <label id="modalTextMessage" ></label>
    <asp:Login ID="Login1" runat="server" Width="246px" >
    </asp:Login>
    <asp:button id="btnCancel" runat="server" text="Cancel" />
    </div>
</asp:Panel>

Default Button Workaround for imagebuttons & linkbuttons, Part II

Okay...so, the post yesterday was clearly not as researched as it should have been. 

It's true...the Click() event does NOT work in FF...so, the solution I had to utilize the click event had a rather short lifespan. 

I tried to dynamically add the __onPostBack javascript event onKeyPress as well as onkeydown - to no avail.  I'm not sure why it wouldn't work...but, it just wouldn't.  (I'm using an image button, .NET 3.5, a lot of JS & AJAX on the page - not sure what, if any of that muddies the waters)

So...I decided to stick with my core solution, and just find a workaround for the lack of a click() FF event. 

I added this to my page..

function FireClick(id){

if ($get(id).dispatchEvent){

var e = document.createEvent("MouseEvents");

e.initEvent("click", true, true);

$get(id).dispatchEvent(e);

}

else

{

$get(id).click();

}

}


Then, I used this...

tbSearchBox.Attributes.Add("onkeydown", "javascript:if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){FireClick('" _

& btnSearchButton.ClientID & "');return false;}else return true;")

Nothing too special - Basically I'm firing my FireClick() JS event to handle the click() - but seems to work on IE6/7 and FF....

Default Button Workaround for imagebuttons & linkbuttons

UPDATE: If you're looking for the solution that will work in FireFox & IE...Go here

Okay, I admit, this is yet another post so I know where to go in 3 months when I totally forget this day. 

Long story short: I was trying to use the DefaultButton property on a panel in order to get a button clicked by default when a user hits enter on my search form.  I was using an ImageButton, and surprise! That won't freakin' work!  Seriously...try it. 

I came across a post on here ( http://bytes.com/forum/thread288545.html ) from S. Justin Gengo. With a link to his site.... http://www.aboutfortunate.com/Code-Repository.aspx?entryid=14

And booya, his simple JS code works perfectly in IE6/7 & FF. 

Good day, sir.

ps - Thank you Justin

___
 tbSearchBox.Attributes.Add("onkeydown", _
    "javascript:if((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){document.getElementById('" _
    & btnSearchButton.ClientID & "').click();return false;}else return true;")

Get BehaviorID from Master Page

You can definitely find this information elsewhere

But...I'm going to put it here right so I know where to go next time :)

I have/had a situation where I had a modal control on my master page - it's what I'm using for a user to log into my application.  I have many pages that need to call this - but I needed a way to call the show() method on my modal pop-up, from javascript.  Here is the solution...

  var modalOnmaster = $find("ctlModalPopupBehavior");
  modalOnmaster.show();

Thank you Brett.

Send e-mail with attachment from database image column (sql server 2k5)

Soooo...I needed to get files out of my SQL Server table (which has the files in an image column) and attach them to an email to send out.  I honestly thought this would be a no-brainer but turned out it was pretty finicky.  Anyway...the code to so is below just in case anyone is wondering.

 

    2 Partial Class _Default

    3     Inherits System.Web.UI.Page

    4 

    5     Function SendEmail()

    6 

    7         'Get your data (filename, content type, image column) from the db

    8 

    9         Dim dt As DataTable = GetYourStuff()

   10         If dt.Rows.Count <= 0 Then Return Nothing

   11 

   12         Dim msg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

   13         msg.Subject = "Sample Message"

   14         msg.To.Add(New System.Net.Mail.MailAddress("Receiver@yourDomain.com"))

   15 

   16         Dim fromadx As New System.Net.Mail.MailAddress("Sender@yourDomain.com", "Sender Name")

   17         msg.From = fromadx

   18         msg.IsBodyHtml = False

   19         msg.Body = "Sample body..."

   20 

   21         Dim strMem As System.IO.MemoryStream = New System.IO.MemoryStream(CType(dt.Rows(0)("ImageColumn"), Byte()))

   22         Dim strWriter As System.IO.StreamWriter = New System.IO.StreamWriter(strMem)

   23 

   24         strWriter.Flush()

   25         'this is very important..wont work without it

   26         strMem.Position = 0

   27         'Filename and content type are hardcoded here, but I assume you get them from GetYourStuff() above

   28 

   29         Dim attachment As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(strMem, "myFile.txt", "text/plain")

   30         msg.Attachments.Add(attachment)

   31 

   32         Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings.Item("smtpserver"), 25)

   33         smtpClient.Send(msg)

   34 

   35     End Function

   36 End Class

kick it on DotNetKicks.com

Alternatives to FindControl()?

Alright, as much as I try to avoid using FindControl() sometimes I need to get a control by its ID.  I came across what seems like a good idea here : http://www.thescripts.com/forum/thread269592.html

It's in C#, but here is the VB.NET adaptation...

  549     Private Sub BuildControlHashTable()

  550         Dim cName As String = String.Empty

  551         For i As Int16 = 0 To Me.Controls.Count - 1

  552             cName = Me.Controls(i).ID

  553             If Not (cName Is Nothing) Then

  554                 cntrlHashTbl.Add(cName, Me.Controls(i))

  555             End If

  556         Next

  557     End Sub

  558     Private Function GetControlByName(ByVal cntrlName As String) As Control

  559         Return CType(Me.cntrlHashTbl(cntrlName), Control)

  560     End Function


Good idea? Bad idea? Thoughts?


Export to vCard from .NET (VB.NET)

Hi all -
So was poking around a few weeks ago and couldn't find any code that'll allow me to export data to vcard...The class would require a little modification to utilize, but should get you 90% of the way there

Partial Class vCardExport

Inherits System.Web.UI.Page

Private Const nameFirst As String = "FirstName"

Private Const nameLast As String = "LastName"

Private Const nameMiddle As String = "MiddleName"

Private Const nameTitle As String = "Mr"

Private Const email As String = "firstname.lastname@domain.com"

Private Const uRL As String = "www.geekswithblogs.net/sanjayu"

Private Const telephone As String = "555 555 5555"

Private Const fax As String = "555 555 5555"

Private Const mobile As String = "555 555 5555"

Private Const company As String = "My Company"

Private Const department As String = "My Department"

Private Const mtitle As String = "My Title"

Private Const profession As String = "My Profession"

Private Const office As String = "227"

Private Const addressTitle As String = "New York"

Private Const streetName As String = "42nd Street"

Private Const city As String = "New York"

Private Const region As String = "Northeast"

Private Const postCode As String = "00000"

Private Const counTry As String = "USA"

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

eVCard.VCard(Response, nameFirst, nameLast, nameMiddle, nameTitle, email, uRL, telephone, fax, mobile, company, department, mtitle, profession, office, addressTitle, streetName, city, region, postCode, counTry)

End Sub

End Class

Public Class eVCard

Inherits System.ComponentModel.Component

 

 

Public Shared Sub VCard(ByVal response As HttpResponse _

, ByVal nameFirst As String _

, ByVal nameLast As String _

, ByVal nameMiddle As String _

, ByVal nameTitle As String _

, ByVal email As String _

, ByVal uRL As String _

, ByVal telephone As String _

, ByVal fax As String _

, ByVal mobile As String _

, ByVal company As String _

, ByVal department As String _

, ByVal title As String _

, ByVal profession As String _

, ByVal office As String _

, ByVal addressTitle As String _

, ByVal streetName As String _

, ByVal city As String _

, ByVal region As String _

, ByVal postCode As String _

, ByVal counTry As String)

response.Clear()

response.Charset = ""

response.ContentType = "text/x-vCard"

Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()

Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)

stringWrite.WriteLine("BEGIN:VCARD")

stringWrite.WriteLine("VERSION:2.1")

stringWrite.WriteLine("N:" + nameLast + ";" + nameFirst _

+ ";" + nameMiddle + ";" + nameTitle)

stringWrite.WriteLine("FN:" + nameFirst + " " + nameMiddle _

+ " " + nameLast)

stringWrite.WriteLine("ORG:" + company + ";" + department)

stringWrite.WriteLine("URL;WORK:" + uRL)

stringWrite.WriteLine("TITLE:" + title)

stringWrite.WriteLine("ROLE:" + profession)

stringWrite.WriteLine("TEL;WORK;VOICE:" + telephone)

stringWrite.WriteLine("TEL;WORK;FAX:" + fax)

stringWrite.WriteLine("TEL;CELL;VOICE:" + mobile)

stringWrite.WriteLine("EMAIL;PREF;INTERNET:" + email)

stringWrite.WriteLine("ADR;WORK;ENCODING=QUOTED-PRINTABLE:" + ";" + _

office + ";" + addressTitle + "=0D" + streetName + ";" + _

city + ";" + region + ";" + postCode + ";" + _

counTry)

stringWrite.WriteLine("END:VCARD")

response.Write(stringWrite.ToString())

response.End()

End Sub

End Class

"Cannot drop the queue 'SqlQueryNotificationService-{GUID}', because it does not exist or you do not have permission."

Working on my first SQL 2K5 application here...and came across this error trying to implement the SqlNotificationService.  I read a lot on this error...However, I was able to avoid this error by simply making the current user of own the DB. 

1. Security > Users > [select the user your application is accessing the DB as]
2. Select properties (right click)
3. Find and check your DB schema in the list of "Owned Schemas"
4. Ensure "DB Owner" is checked off in the "Role Members" list

That's it...