Try MySite.GetContent() Catch(Useless Info) Finally Site.Close() End Try

The guide to programming and analyzing SQL, .NET, and SAP
posts - 18, comments - 280, trackbacks - 0

My Links

News

Hello World. I'm Jon Hermiz and am a software engineer here in Michigan. Feel free to look around and leave feedback!

Archives

Post Categories

Tuesday, November 17, 2009

How to add TinyMCE into ASP.net web form.

Recently I needed a WYSIWYG editor in my asp.net web form.  I looked at various ones including WMD Editor (which I
know is not exactly a WYSIWYG editor, there site states 'It just wasn't built for WYSIWYG. So WMD is something new:
a Wysiwym Markdown editor').  The support is lacking and from the looks of it the API is too.  Lastly, I've seen a lot of sites
using WMD Editor but the visitors on that site certainly don't care about a 'Markdown editor'.  End users try to manipulate
the formatting down to WYSIWYG so why bother?  Look at the comments in this post from stackoverflow if you don't believe me.
  As much as the creators of the site want users to read and listen a user's intuition and what they want to accomplish is more important.
  So why bother?  You code applications for people who plan to use it.  You just don't code it simply because you think it's right.

Usability is a topic on its own, lets focus on getting TinyMCE working inside of an ASP.net web project. 

Getting TinyMCE

1. Download the development package of TinyMCE here

2. You'll get a folder structure starting at "tinymce" for now leave that in some temporary place (your desktop or c:\temp)

Copying TinyMCE Into Visual Studio

1. Fire up visual studio (this has been tested on 2005, 2008)

2. File->New->Web Site

3. Select ASP.NET Web Site for the language select C# (if you are more comfortable with VB then select Visual Basic)

4. Remember that tinymce folder you had saved temporarily, well it's time to drag and drop that folder into this project.

The result of that looks like this:

tinyMCE has an init() function which initalizes the mode, the theme, the various

buttons within the toolbars and so on.  So inside of your default.aspx go to the

source code and add the following javascript:

<script type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>

<script type="text/javascript">tinyMCE.init({"textareas","advanced","safari,pagebreak,style,layer,table,save,advhr,

advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,

contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,

template","save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright

,justifyfull,styleselect,formatselect,fontselect,fontsizeselect","cut,copy,paste,pastetext,

pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,

unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",

"tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,

|,print,|,ltr,rtl,|,fullscreen","insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,

abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak","top","left","bottom",

true,"css/content.css","lists/template_list.js","lists/link_list.js","lists/image_list.js",

"lists/media_list.js","Some User","991234"script>

 

// General options

mode :

theme :

plugins :

// Theme options

theme_advanced_buttons1 :

theme_advanced_buttons2 :

theme_advanced_buttons3 :

theme_advanced_buttons4 :

theme_advanced_toolbar_location :

theme_advanced_toolbar_align :

theme_advanced_statusbar_location :

theme_advanced_resizing :

// Example content CSS (should be your site CSS)

content_css :

// Drop lists for link/image/media/template dialogs

template_external_list_url :

external_link_list_url :

external_image_list_url :

media_external_list_url :

// Replace values for the template plugin

template_replace_values : {

username :

staffid :

}

});

</

You'll want to make sure you insert this inside of your <head> </head> section.

Inserting the TinyMCE textarea field

You're almost done all that is left is too add a textarea inside of your default.aspx page.  Something to this effect:

<

form id="form1" runat="server">

 

<div>

 

<

<textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%" runat="server"></textarea>br />

 

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

 

</div>

 

</form>

When I try to preview or get the data ASP.net complains

A potentially dangerous Request.Form value was detected from the client (elm1="<p>fdsfsdfdsad</p>").

To fix this go back to the source (html) code of your default.aspx page.  You will see a page directive like so:

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

Change it to this:

<%

We've simply added ValidateRequest="false" in the page directive.

@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false"%>

How it ends up looking

If you've done everything correctly you should end up seeing a form like so:

But WMD Editor I can get a quick preview with one line of code

No problem you can do that with TinyMCE as well.  Remember the init() function we talked

about in the head section of your html.  Those control themes, buttons on the toolbars etc.

etc.  Well simply add the Preview button to one of the toolbars.

For instance, we had the following:

theme_advanced_buttons1 :

theme_advanced_buttons1 :

 

justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",

for one of the Theme options..simply add preview before say save so that the above becomes:

theme_advanced_buttons1 :

Now this will create a preview button in the toolbar right next to the save button.

 

justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",

So how do I get data or the text / formatting from the textarea box

Simple, it is runat=server so we have access to it via server side code.

Something like this behind the click event of a button

Response.Write(this.elm1.Value); 

 

"preview,save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,
"save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,

posted @ Tuesday, November 17, 2009 1:01 PM | Feedback (7) | Filed Under [ .NET TinyMCE ]

Wednesday, March 26, 2008

How To Set Default Dates In Reporting Services

I posted this in the SQL Team forum: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=99696

It shows you a good way of creating a bunch of date functions so that you can use them in reporting services as date default values for any date parameter.

 

posted @ Wednesday, March 26, 2008 11:53 AM | Feedback (4) | Filed Under [ SQL Server Reporting Services ]

Thursday, December 20, 2007

Just Hillarious!

I cant stop laughing, and neither will you!  Play the video below, this reminds me of the 80s!

posted @ Thursday, December 20, 2007 1:54 PM | Feedback (4) | Filed Under [ Other ]

Wednesday, December 19, 2007

Asking For A Raise

Its that time of year when many people have a big decision to make:

  • Go with the flow and take whatever your corporation gives you.
  • Ask for a raise
  • Forget about it..change careers cause you just aren't going anywhere or getting anything

It really is a tough decision to make when it involves more money.  We started a post over at sqlteam about this over here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=94258.  Some very interesting comments so first check those out before you read on.

Dont Blow It

One thing you need to remember is this is probably your one and only chance for the year to get a raise so dont blow it.  Here are some do nots to follow:

  • Do not ask for a raise without being prepared.  So many people just want more money but have no documentation or support as to why they deserve the pay raise.
  • Do not mention that you've purchased a new vehicle and your bills have increased, your car has nothing to do with the company.
  • Do not tell them you have a new baby on the way / have existing kids at home and that you need the pay to help with costs around the house.
  • Don't even bother telling them about any bills including mortgage bills that you need to pay off...again no one in the company cares about your problems
  • Do not argue, if they make you mad be professional and ask questions.  Find out why they cant, find how how to improve your current skill set to be reconsidered...always ASK ASK ASK.
  • Do not force them or tell them that you will look else where.  Even if you do look else where keep it to yourself.  Dont bother threatning them or it could back fire.
  • Don't cry and definately do not YELL.  Yelling is verbal abuse and you will be repremanded for this.  Be careful...

Do Your Homework

This is your chance to finally get a raise, so what's the best way to do it?  Well first of all just like anything you have to be well prepared, organized, and review the work you've done in the past, present, and the future.  Do not walk into this meeting (when you have your review) with no paper and no pen.  Print out emails, bring your portfolio of work you've done or supported.  No one that I know is just going to hand you over some extra money just for being you.

Here are some Do's in getting a raise:

  • Prepare yourself by printing e-mails from end users, or customers who enjoy your work or your personality (business only nothing outside of work).
  • Have a list of questions ready in case they close the meeting with "Do you have any questions".
  • Don't just take No for a final answer.  Ask questions why, or what you could do better next time.
  • Be professional, use eye contact, sit up straight.  I know review time can get a little boring but its worth the sacrifice if it means an extra 5-10 thousand (not a bad raise).
  • Listen to your manager's opinions and understand where he / she is coming from.
  • If you don't agree on something, do NOT get mad simply ask questions and understand that this should be something that you care about.
  • Be on time (I know people who have not even shown up on their review day).
  • Show off but DO NOT BE COCKY.  Don't try to be arrogant in your approach but definately show them the great things you've done for the company.
  • Get advice from people who have been in the industry longer than you.
  • Check out the job market, find out what people are paying for skills which you have.
  • List out your accomplishments and talk about your future with the company.
  • Be positive, and sincere, show them that you truly care
  • Always always ask for a time frame or a date when you think your manager can get back to you if he / she does contemplate a raise.  If you don't get a date it probably means you won't get a raise or at least you won't get one any time soon.
  • Leave your managers office with a good impression.  You want your manager to think "Wow...I really need this guy / gal in our functional group"

One thing I got from my previous boss that I'll share with you is something to think about:

"Basically there are 3 roles, support, part of the product, and the product.  In the support role your work is not very scaleable, whereas if your work was the product it would be very scaleable.  The salary you can command is always going to be proportional to the scaleability of your work.  You need to take this into consideration when you compare salaries.So doing the same work is worth more as it becomes more scaleable. You have to decide the role you want your work to  be in."

If you have additional tips or pointers definately share them.

posted @ Wednesday, December 19, 2007 2:16 PM | Feedback (0) | Filed Under [ Other ]

Monday, December 17, 2007

What If: The Dream Company

What If : The Dream Company
 
Ever wonder what if when it comes to your imaginary corporation where you have an unlimited amount of money to spend on talent?
 
What if...
 
 
 
 
 
 
  • MVJ (Michal Valentine Jones…not sure if that is really his name) he’d be in charge of the final base code. Would be willing to give him a duplicate gate keeper key much like that of Peso’s. He’s the go to guy, the man with an answer to much anything when it comes to SQL. He’d come up with weird functions that handle dates…reusable code…ya the weird stuff that just seems to work!
 
  • Kristen (http://www.sqlteam.com/forums/pop_profile.asp?mode=display&id=10539) the Director of the company.  Ahh he makes the big bucks..but he’s well worth it.  He steers the company in the direction of success…well most of the time.  He’s been known for making programmers happy (which just doesn’t sound right).  He actually made a couple of Mladen’s group laugh!  He writes clean code…but he’s too good for that now.  Sometimes MVJ gets frustrated with code he’s inventing, but putting him in the same office with Kristen and Peso he always comes out with a monster that works. But don’t piss Kristen off or you might become a twit: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=69568
 
  • Jezemine (http://www.sqlteam.com/forums/pop_profile.asp?mode=display&id=24731) he would be the central brain of the entire company. The guy is brilliant IMHO. He’s like the Einstein of today (ok not that much but still he knows his stuff). He’s written some nice database documentation tool called SQLSpec http://www.elsasoft.org/. Of course the company would take ownership of it ;) (just kidding). Along with his brain he’d be in charge of the documentation support of the company. His role is essential to our customer base. Without him our customers are lost and frustrated. Him and Peso seem to find speed as a good topic to discuss when it comes to SQL: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=93911
 
  • Graz…good ol graz…the one that put everyone together in one room. He insisted that it would work out…success comes with patience and hard work he would always say. He’s the heart of the corporation and when the heart stops we’re in for some trouble. Graz also runs many of the presentations and brings in special guests to help our developers and our customers as well!
 
We’d hire some major players as well guys / gals like:
 
 
 
 
 
 
 
We’d be a lot like google minus those colors and the lava lamps. Work environment would include jeans, tshirts, pajamas, and even shorts. Roller blading / biking to work would be an option. We’d all have lunch together … maybe Emerald would cook! We’d all become rich too…our stock options would supersede our pay rates just some day.
 
Maybe just maybe…Of course affording all of you would probably be impossible…but then again it’s just a dream.

posted @ Monday, December 17, 2007 11:07 AM | Feedback (9) | Filed Under [ Other ]

How To Create A Sharepoint Like Calendar In ASP.net

This article relates to a couple of articles that are on the site.  The original article was "Cool Tricks With The ASP.net Calendar".  You can find this here: http://weblogs.sqlteam.com/jhermiz/archive/2007/12/10/Cool-Tricks-With-The-ASP.net-Calendar.aspx.  The other article you might find useful is the "Additional Tip For that Calendar Control In ASP.net" this article can be found here: http://weblogs.sqlteam.com/jhermiz/archive/2007/12/11/Additional-Tip-For-That-Calendar-Control-In-ASP.net.aspx.

Have you ever wanted to create a nice calendar control much like the sharepoint calendar control?  You know the calendar control with hyperlink data directly on each calendar day.  The previous articles shows you how to use the DayRender Calendar control event to add image controls.  But what about adding hyperlink controls as well as setting the NavigateURL property for each hyperlink to take you to another web page.

This process is very similiar to the second article where we added image controls to a calendar control.  Now we want to simply add hyperlink controls.

To do this drag and drop a calendar control on your web page.  Use your SQL knowledge to pull some data (with the date for each row of data) from your database table.  Store this data in a datatable or a dataset.  Then loop through your data and compare the date in your dataset / datatable with the day in the Calendar_DayRender event.  If they are equal instantiate a Hyperlink object.  Set its text property, its navigateurl property and whether or not you want a border.

From our previous examples here's some code to help you out:

 

Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
        Dim nextDate As DateTime
        Dim hl As HyperLink
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean

        notTouched = True
        Try
            If Not CType(Session("dsHolidays"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsHolidays"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("HolidayDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.Color.Pink
                        e.Cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#24618E")
                        notTouched = False
                    End If
                Next
            End If

            If Not CType(Session("dsRequests2"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests2"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        hl = New HyperLink
                        hl.Text = CType(dr("ToolTip"), String)
                        hl.NavigateUrl = "Entry.aspx?ID=" & CType(dr("VacationID"), String)
                        hl.BorderColor = Color.Gray
                        hl.BorderWidth = 1
                        hl.ToolTip = "Click this item to get more detailed information."
                        hl.Font.Name = "Arial Narrow"
                        hl.Font.Bold = False
                        hl.ForeColor = System.Drawing.ColorTranslator.FromHtml("#24618E")
                        e.Cell.BackColor = Color.Azure
                        e.Cell.Controls.Add(hl) 
                        notTouched = False
                    End If
                Next
            End If

            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If
        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user!  " & "Additional errors include: " & ex.ToString())
        End Try
        
    End Sub

The result:

posted @ Monday, December 17, 2007 9:01 AM | Feedback (16) | Filed Under [ .NET SQL Server ]

Tuesday, December 11, 2007

Additional Tip For That Calendar Control In ASP.net

Regarding my post about the tips and tricks with the ASP.net calendar control someone emailed me asking how to add additional text / images to the calendar control to give the calendar day a more appealing visual representation.

Something to this effect:

You handle images like so in the same event as we discussed before.  The event you want to use for this is the DayRender event since you want to control each day.  Anytime you need to handle something that is associated with a single day cell you have to take care of it in the day render event. 

How To Do This

I assume the reader has a good understanding of ASP.net, the web, and SQL.  In my case I had some fields to store a request status.  A request can be in three states:

  1. Pending (yellow question mark)
  2. Approved (green check mark)
  3. Declined (a red x)

So in my previous post I showed you how to pull the requests from the SQL database.  Remember you do not have to do it this way, I am just showing you an example.  So in the DayRender event declare an Image web control:

Dim s as System.Web.UI.WebControls.Image

Then perform the following:

  • Instantiate the object
  • Set its image url property
  • Set a tooltip (optional)
  • Add the image object to the Controls collection of e ( e.Cell.Controls.Add)

So here we go:

s = New System.Web.UI.WebControls.Image()

With s

  .ImageUrl = "~/images/yourimage.gif"

  .ToolTip = "Some tool tip"

End With

e.Cell.Controls.Add(s)

In my case I store some tool tip information inside of the actual database by concatenating some fields together and bringing them back in a stored procedure.  That way I can set the tool tip with some text that may be valuable to the end user.

From Our Previous Example

Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
        Dim nextDate As DateTime
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean
        Dim s As System.Web.UI.WebControls.Image

        notTouched = True

        Try
            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))

                        Select Case (CType(dr("VacationStatusID"), String))
                            Case "Pending"
                                s = New System.Web.UI.WebControls.Image()
                                s.ImageUrl = "~/images/p.gif"
                                s.ToolTip = CType(dr("ToolTip"), String)
                                e.Cell.Controls.Add(s)

                            Case "Approved"
                                s = New System.Web.UI.WebControls.Image()
                                s.ImageUrl = "~/images/a.gif"
                                s.ToolTip = CType(dr("ToolTip"), String)
                                e.Cell.Controls.Add(s)

                            Case "Declined"
                                s = New System.Web.UI.WebControls.Image()
                                s.ImageUrl = "~/images/d.gif"
                                s.ToolTip = CType(dr("ToolTip"), String)
                                e.Cell.Controls.Add(s)
                            Case Else
                        End Select

                        notTouched = False
                    End If
                Next
            End If

            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If

        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user!  " & "Additional errors include: " & ex.ToString())
        End Try
    End Sub

 

posted @ Tuesday, December 11, 2007 3:25 PM | Feedback (13) | Filed Under [ .NET SQL Server ]

Monday, December 10, 2007

Cool Tricks With The ASP.net Calendar

UPDATE: Additional tips: More Tips

Been A Long Time

Hello world...sorry I haven't posted in quite some time, we've been real busy at home this Christmas season.  Anyhow I thought I would share some tricks and tips with using the calendar control before you or your company spends some change to buy a control on the internet.

What Is The ASP.NET Calendar Control

The ASP.net calendar control is simply the calendar that comes prepackaged with visual studio and is available as a standard control.  Here she is on the standard control:

And here is what the calendar control may look like:

The Problem

You have been tasked to create a time off tool request involving some pretty complicated things.  Your boss has asked for numerous features in this tool which you hoped he had never asked. 

Da Boss

 

  • I want it to highlight specific days signaling holidays or time off requests. This helps me visualize what type of day the request is.   Color coding is a plus :-).
  • I'd like some nice mouse over effect on days that are not requested.  This helps the user notice a clickable type of cell.
  • O I dunno...I'd like to not only see a monthly view, but a yearly view so that I can quickly glance over an entire year for an employee.
  • O well...I dunno...Impress me...maybe allow a user to click a day on the calendar and have it go to a page with that calendar day being selected.

Umm you know the simple things..besides you have all the tools that the company has purchased for you.

You

Thoughts to self: ***O NO NOT THE CALENDAR CONTROL...BUT CANT WE JUST BUY SOMETHING PRE MADE***

Boss

O by the way...we don't have any money to buy any third party tools...have a great day.  Don't forget to e-mail when its all done.

You

O certainly boss...*cringe*...this should be no sweat *thank God I wore deodorant*.  Quickly images begin flashing in your head about what your boss said:

"I want it to highlight specific days signaling holidays or time off requests. This helps me visualize what type of day the request is.   Color coding is a plus :-)."

"I'd like some nice mouse over effect on days that are not requested.  This helps the user notice a clickable type of cell."

"O I dunno...I'd like to not only see a monthly view, but a yearly view so that I can quickly glance over an entire year for an employee."

"O well...I dunno...Impress me...maybe allow a user to click a day on the calendar and have it go to a page with that calendar day being selected."

**Ok that one is simple response.redirect and send a query string**

How in the world am I going to do all of these with the ASP.net calendar control?  That control is just so dull, so plain, difficult to use. 

Got To Get To Work

Well the ASP.net calendar control is pretty limited, its got a few events you can hook onto.  In fact when I started writing code using this control I was pretty upset because the control just seemed plain, really stale, didn't live up to my expectations.  But I was forced to use it.  Sure you can probably spend 100-200 bucks on a RAD Control...but do you really need to.  Most everything the Boss wants is right there in the calendar control.  So lets tackle it one step at a time.

Lets do the simple one first.  Before we begin, I am putting a caution that this code may need to be cleaned, this could o r could not be production code, it is merely a sample.  Samples help beginners and even advanced programmers learn how they can accomplish a specific task.  So take what you need and modify to fit your needs.  DO NOT EMAIL ME SAYING HOW BAD / GOOD IT IS TO DO A SPECIFIC THING.  TAKE WHAT YOU NEED AND RUN!!!  Ok done with the rant.  Now lets take the simple example of how to create the rollover effect of the calendar.

Rollover Effect

At first you might think to use the PreRender event to handle this.  The problem with the PreRender event in this case will cause your entire calendar to highlight a specific color when you roll over it.  To avoid this let's use the DayRender event this will ensure that the rollover effect is per day and not per calendar.  To do this first decide what color you want to use to highlight the calendar when you rollover it (onMouseOver).  Then decide what color you want to highlight when you are off of the calendar day (onMouseOut).

In this case I will use a light shade of blue (almost a baby blue) as the onMouseOver color and I'll use white for the onMouseOut color.  You can use hex codes or named colors, both work using this code.  You can also obtain the default backcolor property using @BackColor.

Heres some vb.net to help you:


 

 Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
 	 Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
	 Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
	 Dim rowBackColor As String = String.Empty
            
	 e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
	 e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
    
     If Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
     End If
 End Sub

 So here all you're doing is setting a mouseOver for days that are not weekends.  The result:

Ok so now that we are done with the highlight effect lets look at the example of color coding specific days. 

Color Coding Specific Days In The ASP.net Calendar Control

In this case I assume the reader knows how to use datatables, datasets, and common sql statements such as SELECT, INSERT, UPDATE, etc.  So assume you have a table that has time off requests.  In this table you have a field where you store the time off request date.  You want the days requested off visually displayed on the calendar control in a different color.  To do this you simply write a stored procedure to pull your data.  You then store this data inside of a datatable or a dataset.  Once you have done this you check the e.Day.Date property with the value stored in your data row value.  If the values match you handle this event and you change the e.Cell.BackColor.

In my case I will use a dataset that is stored in a session variable.  You do not need to do it like this, this is just an example.  For instance, you may want to use a data table, or maybe you just want a dataset but you do not want to store it in a session variable.  In any event you preform this code yet again in the DayRender event of the calendar control.

Here is some code that will help make more sense:

 


Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender 

        Dim nextDate As DateTime
 
        Try
               'this part is the actual time off requests
            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                  End If
                Next
            End If
 
        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user! " & "Additional errors include: " & ex.ToString())
        End Try
    End Sub

What's going on in this code.  Well first and foremost get rid of what you don't need and change field names, code based on your needs.  In my table I store a field called VacationDate this field has the date value of the time off request.  I assign this value to nextDate and compare nextDate with e.Day.Date.  If these values are the same then I set the e.Cell.BackColor to a color based on another field in my database HTMLColor.  You do not have to have this field, this field is used because in my circumstances we have many time off request types and I want to associate a hex color with each time off type.  You may want to only use a specific color like, System.Drawing.Color.Red.  In this case you would do:

e.Cell.BackColor =  System.Drawing.Color.Red

So the steps are:

  1. Pull the data using a stored procedure, order it by date asc
  2. Take this data and store it in a dataset or a datatable
  3. Use the DayRender event to handle the event each day
  4. Check if e.Day.Date is equal to your date that was returned from the database (dr("HolidayDate") from above)
  5. If the values match up set the e.Cell.BackColor property to the color you want.  Better yet store a color hex value in your database for each type of time off request.

But I Used The DayRender Event For That OnMouseOver Effect Now What?

Simple, combine both together like so:

    Protected Sub Calendar13_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar13.DayRender
        Dim nextDate As DateTime
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean

        notTouched = True

        Try
            If Not CType(Session("dsHolidays"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsHolidays"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("HolidayDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.Color.Pink
                        notTouched = False
                    End If
                Next
            End If

            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                        notTouched = False
                  End If
                Next
            End If

            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If

        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user!  " & "Additional errors include: " & ex.ToString())
        End Try

    End Sub

 
The OnMouseOver effect as well as the colored background cells on the 7th and the 25th of December 07.
 
But What If I Am Using More Then One Calendar Control
 
There is always those what if's.  You may be using more then one calendar control in your application, if you are no problem.  In this case create a sub routine to HANDLES all the calendar objects in your application.  For instance, assume you have 12 calendar controls then your subroutine signature should look like this:
 

Private Sub DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender, Calendar2.DayRender, _ 
                          Calendar3.DayRender, Calendar4.DayRender, Calendar5.DayRender, Calendar6.DayRender, Calendar7.DayRender, Calendar8.DayRender, Calendar9.DayRender, _
                          Calendar10.DayRender, Calendar11.DayRender, Calendar12.DayRender

This shows one sub routine called DayRender which can handle the DayRender event of any of the 12 calendars.
The rest of the code is very similiar to what we posted previously:

Private Sub DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender, Calendar2.DayRender, _ 
                          Calendar3.DayRender, Calendar4.DayRender, Calendar5.DayRender, Calendar6.DayRender, Calendar7.DayRender, Calendar8.DayRender, Calendar9.DayRender, _
                          Calendar10.DayRender, Calendar11.DayRender, Calendar12.DayRender
 
        Dim nextDate As DateTime
        Dim cal As Calendar = CType(sender, Calendar)
        Dim onmouseoverStyle As String = "this.style.backgroundColor='#D4EDFF'"
        Dim onmouseoutStyle As String = "this.style.backgroundColor='@BackColor'"
        Dim rowBackColor As String = String.Empty
        Dim notTouched As Boolean
 
        notTouched = True
 
        If e.Day.Date.Month <> cal.TodaysDate.Month Then Exit Sub
 
        Try
            If Not CType(Session("dsRequests"), DataSet) Is Nothing Then
                For Each dr As DataRow In CType(Session("dsRequests"), DataSet).Tables(0).Rows
                    nextDate = CType(dr("VacationDate"), DateTime)
                    If nextDate = e.Day.Date Then
                        e.Cell.BackColor = System.Drawing.ColorTranslator.FromHtml(CType(dr("HTMLColor"), String))
                        notTouched = False
                    End If
                Next
            End If
 
            If notTouched And Not e.Day.IsWeekend Then
                e.Cell.Attributes.Add("onmouseover", onmouseoverStyle)
                e.Cell.Attributes.Add("onmouseout", onmouseoutStyle.Replace("@BackColor", rowBackColor))
            End If
 
        Catch ex As Exception
            Response.Write("Errors occurred: No RuleID / Hire Date specified for user! " & "Additional errors include: " & ex.ToString())
        End Try
    End Sub

In this case we handle all 12 calendar controls.  The result is as follows:

Passing The Date To Another Page

Suppose you want to pass a calendar day to a Response.Redirect to another page when you click on a calendar day.  Here you can simply pass a parameter to a page like so:

Response.Redirect("entry.aspx?VacationDate=" & CType(Calendar13.SelectedDate, Date))

And to pull that date in the entry.aspx page simply use the following:


Dim d as Date

d = CType(Request("VacationDate"), Date) 'grab date


Hope this helps someone out there who needs to do something similiar.  

posted @ Monday, December 10, 2007 12:16 PM | Feedback (62) | Filed Under [ .NET SQL Server ]

Wednesday, August 22, 2007

Forgetting the little things in life...

Remember the good old hello world program?  Ahh the first program any teacher in any type of programming course would assign was good old Hello World.  But as students / new developers we were excited!  Wow my first program and I got it to say Hello World and it displayed it right on my screen.  "Just take a look" you'd say to the student next to you, I even included the header iostream.h. 

How did our young minds go from writing programs like Hello World to robust database applications in the .net framework?  Do you ever wonder how your mind has actually created the beasts that people are using today?  Admit it, you are smart, better yet we are smart.  Computer Science guys are engineers, we're doctors, we are artists, and we're even lawyer's.  We have to take large business processes and convert it into a useable tool (engineers).  We have to debug, optimize, and fix bugs (doctors).  We have to design nice interfaces, whether web based or win form, and make them useable to end users (artists).  We have to fight for what we believe, pointing blame on our clueless end users (lawyers).

How did we ever go from writing hello world, and a mini calculator to these fairly large applications?  We've worked hard...that's how.  So programmers / dba's / and even you system admins take a moment smile and pat yourself on the back because you've busted your butt doing this stuff and you're damn good at it.

Since we've gone to writing complex applications I sometimes look back at some basic programs and say wow this is so simple that its difficult.  I've forgotten how to think in a simple manner.  We sit day to day writing use cases, designing forms, and working on large databases that we forget how to do the simple things in life.

So its time for some old school CS 101 programming assignments.  Here's 4 homework assignments you can do in any language:

1) In a pretty slick way output the maximum value of a unsigned integer.  Try to not use a library which allows you to display the maximum of this value (in addition such as max.h in C++).

2) Write a cash register program which displays the amount of change given back to the customer in dollars, quarters, dimes, nickels and pennies.  For instance:

Your total is 18.20

You give: 20 dollars

Output should be:

1 dollar

3 quarters

1 nickel

The program should try to use exact change using 1 nickel instead of 5 pennies for instance.

3) Write a program finding the first 500 prime numbers.  You should try to use the least amount of code and remember the limits of how to check for prime numbers..hint square roots.

4) Write an assignment to the next person who responds to this blog.  Please be nice and make it simple on the next guy or we wont get the next response!

Skip the ones you cant do, but #4 is a must!

Have fun

posted @ Wednesday, August 22, 2007 11:37 PM | Feedback (5) | Filed Under [ .NET Other ]

Monday, August 20, 2007

DevConnections 2007

Count me in this year again!

I had an excellent time last year and met some real cool folks.

I'll be in the visual studio asp.net conference along with the reporting services seminars.  Bring your RS questions if you have any.

Here's some pics from last years: http://jhermiz.googlepages.com/devconnections2006

I wonder if Isaac Stubbs is still cruising in that motorcycle he won??  If you've never been to devconnections before then now is the time to go.  Tell your boss you need to attend www.devconnections.com.  You get a free copy of MS Visual Studio 2k8...you can easily make a case to your boss about going.  Most of you can write it off on your taxes as well; since this helps you do your daily job.

See you there!

 

posted @ Monday, August 20, 2007 11:57 AM | Feedback (0) | Filed Under [ .NET SQL Server Reporting Services ]

Powered by:
Powered By Subtext Powered By ASP.NET