Showing posts with label Eric Reid. Show all posts
Showing posts with label Eric Reid. Show all posts

Wednesday, July 9, 2014

FileZilla FTP - Phase II - Maintenance and Subsites

The previous post introduced the idea of publishing your website to a remote server using FileZilla and FTP. An additional video demonstrates updating the same site using a new local website version (PersonalV2) with ASP.NET and adding various "sub-websites" hosted off the same domain (such as one called WG).

The latter will also require adding an "Application Root Directory" (aka Virtual Directory) through your GoDaddy/CentriqHosting settings. This allows the "sub-website" to be treated as its own application, with its own root web.config and its own independent root relative referencing. At the time of this post, setting an application root folder requires you to:

  • Launch your Hosting control panel,
  • Go to the More navbar option, click the IIS Management option from the fly-out menu
  • Create a new directory and name it, then check the "Set application root" checkbox.


As a brief sidenote, if you are going to use MVC for your root website, it's a best practice to ensure that certain elements are not inherited by the "sub-websites" that would cause conflicts:

    <!--So parent MVC app doesn't conflict with sub-websites-->
    <location inheritInChildApplications="false">
    </location>


Typical tags that cause conflicts in sub-websites (and that you'll want to wrap with the location tag above) are <system.web> and <connectionStrings>. Note also with the code above, Visual Studio may not provide Intellisense for the inheritInChildApplications attribute, but it works.

Check out the FileZilla FTP Phase II video:

Thanks, and go forth and publish content! As always, best wishes on your continuing career development!

Friday, June 27, 2014

FileZilla and FTP - Setup - Phase I

When we first learn to create websites by hand, we normally use some software to develop the code on our computer. The software might be as simple as Notepad, or it might be a feature-rich IDE, like Visual Studio or Dreamweaver. We test those files we created on that local computer, running them in various browsers. No one can see the results of our work till it's ready, because it hasn't been published. It's just being run locally, on that one computer.

Once I'm ready to publish/deploy my website for the world to enjoy over the Web, I need a domain name and a server to host it. If I'm not hosting the domain on my company's computers, I've probably paid a hosting provider (such as CentriqHosting, Arvixe, 1&1, etc.) to handle that part for me. Even so, I still need one more thing. I need to get my content (those files I've been testing locally) onto that remote server. Regardless of the tool you use to accomplish this, the protocol you use is usually FTP (File Transfer Protocol).

FileZilla (Client) is free, open-source software that lets you handle FTP uploads/downloads between two computers.

Check out the "FileZilla and FTP – Setup – Phase I" video below for a tutorial on using Filezilla to publish a website you've been working on locally to your remote, live webserver.



In a nutshell, here are those steps.

Create a Site Definition

A site definition saves all the settings you'll need to continue publishing your local website files out to the remote live server.

  • Go to: File menu, Site Manager...
  • Click: New Site, then name your new site definition
  • Fill out the General tab settings (your hosted FTP upload location, your FTP username and password, etc.)
  • Fill out the Advanced tab. Identify the location of your local website files (Default Local Directory) and the file path on your remote server for this site definition (Default Remote Directory)
  • You can then connect. In the future, this site definition is saved as a quick load option off the dropdown arrow directly underneath the File menu.


Upload Updated Content

  • Once you are connected (showing files in the local directory pane on the bottom left and showing files in the correct remote directory pane in the bottom right), you can upload any files or subfolders of new or updated content.
  • Simply select the new/updated files or folders on the left, then right click them for the Upload option, or drag them into the correct spot on the right.


Common Errors to Avoid

  • Getting file locations out of sync. Be sure you are uploading local files to the correct remote directory. If you have moved into a subfolder of your root directory to upload a file, be sure to navigate to the matching subfolder on the remote server before you upload - or you may be putting the file into the wrong remote directory.
  • Failing to update the remote server for local website restructuring. If you rename a file or folder locally, or move files to different folders in the website structure, it's up to you to manually make changes on the remote server to reflect those local changes (deleting files and folders with former names, moving files to the correct new folders, etc.)

Thanks, and be sure to check out the following video for "FileZilla, Phase 2", which tackles maintaining content and updating/adding site definitions. As always, best wishes on your continuing career development!

jQuery Crash Course –Part III ofthe HCJ Series

Back in June, 2013 (yes, that was a year ago) we published the final installment of the HCJ series in the Centriq Alumni Network newsletter.

Installment 3 provided an introduction to jQuery, including what it is and isn't, what the syntax looks like, and a few examples of jQuery in use.

You can access the piece in its entirety, as well as code samples:


Thanks, and best wishes on your continuing career development!

Thursday, July 25, 2013

CSS3 Crash Course – Part II of HCJ Series

[This post is re-published from a piece I wrote for the January 2013 edition of the Centriq Alumni Network newsletter.] Continuing the HCJ series (HTML5/CSS3/jQuery) we started last month, let's push on with CSS3. As noted in the opening salvo for the series, this is intended to introduce you to these concepts and get you up and running with some new code and implementations that will work in many environments. It is by no means an exhaustive resource.

The next piece in the series will introduce incorporating some jQuery into your websites.

CSS3 Usage

Over the years, CSS3 has begun to be supported in parts by more and more browsers. And this is a good thing, because CSS3 promises not only more formatting options, but also finer control over selecting tags to format on the page. (This improved ability to target items in the DOM ties in well with JavaScript and jQuery, as we'll discuss more in the next installment of this series.)

Use Well-Supported Properties But Be Prepared For Non-Compliance

Although there's still lots of CSS3 that receives only partial support (or none) in various browsers, that doesn't mean we can't use some CSS3. There are various philosophies on this, but a common perspective is that if a CSS property we wish to use is fairly well supported, we use it – with the understanding that it may be ignored by some browsers. If you do this selectively, there shouldn't be too much "code bloat" where the users are wasting download time to get formatting that will be ignored by their browser anyway.

For example, you can use a CSS property for multiple text-columns (like those in a newspaper) on one of your div tags – but you will need to be prepared for the fact that no form of Internet Explorer except IE10 supports that CSS. (IE10, by the way, is only installed by default on Windows 8 machines; and is currently used by only 0.25% of users globally.) So that CSS will be ignored by most forms of IE, and your page will display that div's content in the standard 1-column layout.

Push Compliance with Modernizr and Polyfills

On the other hand, if a particular CSS property and its formatting is truly mission critical and we know some browsers do not inherently support it, we could try to force the browser to implement that formatting by using Modernizr and polyfills.

Modernizr is a free service that incorporates both the HTML shiv we discussed in the last installment, and JavaScript that performs feature detection. Then polyfills (more JavaScript) can be used to "help" the browser support the desired CSS3 or HTML5. This of course can still fall victim to the limitation that the browser in question must not be configured to block the JavaScript or your desired formatting can still fail. And this also adds more code to the download, and the potential for code bloat again – especially if you overuse the technique. Fortunately, to avoid this, the people at Modernizr do make it easy for you to generate custom JavaScript code to "force support" for only the desired CSS features you choose.

Using the Modernizr and polyfills approach may take more work, but if used with some care to only force support for truly important features, it can ensure a more consistent implementation of your CSS across browsers.

CSS3 Resources

Deciding which CSS to use can often come down to how well supported it is. For that, I have two quick recommendations:
  • CanIUse.com (solid stats and information)
  • CSS3Test.com (interesting at a glance for testing features of the browser you're currently using)
To start digging into using Modernizr with polyfills, I'd recommend the following sites:

CSS3 Formatting Highlights

The following is a quick sampling of some fairly well-supported CSS3 properties you may want to start using in your projects.

Text Shadows

Adding a drop shadow to your text uses the text-shadow property. Here's the template for using it:
text-shadow: right-offset | down-offset | blur-radius | color

And two examples:
h1
{
   color: green;
   text-shadow: 5px -3px 5px red;
}

h2 {text-shadow: 3px 3px;}


So the h1's would be green with a red drop shadow 5px to the right, 3px above (negative offsets reverse the direction), and a blur radius of 5px.

The h2's would have a text-shadow of the default color that's 3px to the right and down.

Rounded Corners and Box Shadows

For block-level elements, sometimes you want to shave off the hard edges from those corners and/or add drop shadows to them. This has been popular in web and UI design for awhile, but previous to proper CSS support, required cumbersome image manipulation and CSS hacks to make it work. Of course, for this to work, you need some borders to round, so that's your first pre-requisite. Also, this is another CSS feature that has mixed and sometimes proprietary support in different (older) browsers, so to be safe, you may want to use both proprietary and standard property variants.

The templates:
border-radius: radius-amount-for-all-corners //set equally
OR
border-radius: top-left | top-right | bottom-right | bottom-left //clockwise

box-shadow: right-offset | down-offset | blur-radius | spread | color


Examples:
aside.pullquote
{
   border: 3px solid blue;
   border-radius: 5px;
   -moz-border-radius: 5px; //for older Firefox versions
}

#wrapper
{
   border:3px solid blue;
   border-radius: 5px 3px 3px 5px;
   -moz-border-radius: 5px 3px 3px 5px; //for older Firefox versions

   box-shadow: -3px -3px 3px 3px green;
   -moz-box-shadow: -3px -3px 3px 3px green; //older Firefox versions
   -webkit-box-shadow: -3px -3px 3px 3px green; //older Safari/Chrome versions
}


So any aside with a class of pullquote will have 5px radius for its rounded corners on all sides.

The tag with an id of wrapper will have left corners with 5px rounding, right corners with 3px rounding. Also, it will have a green drop shadow outside the borders of 3px to the top and left, with 3px radius and spread.

Text Columns

As we've already mentioned, you can add CSS text columns for a block-level element, and style them with spacing and/or a line between the columns. (Also, as noted previously, this is not supported in most forms of IE as of the time of this writing).

Templates:
column-count: number-of-columns;
column-gap: width-between-columns;
column-rule: border-specs-between-columns; //defaults to none if unassigned

Example:
article.threecol
{
//3 variants for column count
-moz-column-count: 3;
-webkit-column-count: 3;
-moz-column-count: 3;

//3 variants for column gap
-moz-column-gap: 15px;
-webkit-column-gap: 15px;
-column-gap: 15px;

//3 variants for column rule
-moz-column-rule: 2px dashed black;
-webkit-column-rule: 2px dashed black;
-column-rule: 2px dashed black;
}


So, for browsers that support it, the article tag with a class of threecol will have 3 columns with a spread between them of 15px, as well as a 2px dashed black vertical line.

Background Gradients

You can set a background gradient (where solid colors "fade" into other solid colors) through a variant implementation of the background-image property. Again, this is currently a property supported mostly through the proprietary browser variants, so you'd typically use them all if you're going to use them.

Template:
background-image: linear-gradient(direction | color % | color %);
background-image: -moz-linear-gradient(direction | color % | color %);
background-image: -webkit-linear-gradient(direction | color % | color %);


Examples:
header
{
   background-image: linear-gradient(left, red 20%, olive 70%);
   background-image: -moz-linear-gradient(left, red 20%, olive 70%);
   background-image: -webkit-linear-gradient(left, red 20%, olive 70%);
}

aside
{
   background-image: linear-gradient(45deg, gray 20%, blue 30%, green 70%);
   background-image: -moz-linear-gradient(45deg, gray 20%, blue 30%, green 70%
   background-image: -webkit-linear-gradient(45deg, gray 20%, blue 30%, green 70%);
}


So the header will go from red to olive, fading in from the left, beginning the red-to-green transition 20% after the starting point and ending in solid green 70% from the starting point to the end.

The aside will fade in at a 45 degree angle, from gray to blue to green, starting the first transition at 20% of the distance, then the next at 30% and then finally at 70%.

This can all be a little tricky, so I highly recommend playing with it and/or downloading the free CSS Grady or ColorZilla app for the Chrome browser to interactively play with gradients and see CSS code generated that you can copy or tweak.

CSS3 Targeting Highlights

The following is a quick round-up of a couple of fairly well supported CSS3 selectors you may want to start using to target tags better, with less markup. Why add tons of classes to your HTML tags to get them systematically formatted a certain way if you can do it just as well with some slick pseudo class and contextual selectors?

Here are a few quick targeting selectors that you may want to consider using.

Some Pseudo Class Selectors

Sometimes you want set the formatting differently for the first or last item in a container tag – like the last bullet point in an unordered list, or the first row in a table. Example:

ul li:last-child
{
   margin-bottom: 30px;
}

tr:first-child
{
   text-align: center;
}


So the last list item in an unordered list would have 30px added beneath it. And the first table row would have its content centered.

On the other hand, sometimes you want to set repeating formatting for alternating items (like rows in a table) and so you might want to set every "even" or "odd" child to receive certain formatting. Examples:

tr:nth-child(even)
{
   color: yellow;
   background-color: green;
}

tr:nth-child(odd)
{
   color: white;
   background-color: black;
}


So the even rows in a table would be yellow on green, while the odd numbered rows would be white on black.

What about selecting the immediate child li's in an unordered list, but not the ones nested in that ul's child tags? Or selecting a certain tag when it immediately follows a particular other tag?

ul > li:last-child //only last child LI of UL, but only direct-child, not nested descendant LI tags
{
   margin-bottom: 30px;
}

h1+p // select P tags that immediately follow an H1
{
   margin-left: 2em;
}


There are many more CSS selectors you may not have worked with, but that's a few to give you a taste, and they are pretty well supported now.

Additional Development

As noted in the previous installment of this series, I recommend you pick up the books we're using in our HTML/CSS/jQuery class now for a fuller treatment of these topics:
  • Murach's HTML5 and CSS3 (including intro chapters for JavaScript, jQuery, and jQuery mobile) by Zak Ruvalcaba and Anne Boehm
  • SitePoint's jQuery: Novice to Ninja by Earle Castledine and Craig Sharkie
Remember to take advantage of being part of the Centriq alumni network, and best wishes on your continuing career development!

Friday, February 8, 2013

HTML5 Crash Course – Part I of HCJ Series

[This post is re-published from a piece I wrote for the December 2012 edition of the Centriq Alumni Network newsletter.] I thought I would start off a series that tackles a few concepts that we've begun incorporating into our web design class in the Application Developer track in the past 6 months – HTML5, CSS3 and the jQuery JavaScript libraries. This reflects the growing adoption and support of these languages and technologies, especially in the wake of the explosion of various mobile devices. Of course, HTML5, CSS3 and jQuery could each be a book-long discussion in and of themselves. This will only be an introduction to HTML5 – but one intended to get your feet wet quickly and without a lot of fuss. The next piece in this series will be for CSS3, and the final installation will introduce getting started with jQuery in your websites.

HTML5 Evolution and Philosophy

HTML5 is just the next evolution of the HTML language family, just like XHTML was an evolution of HTML 4.01. However, one of the first trends you'll notice in HTML5 is that they have tried to simplify things – such as the new DTD (Document Type Declaration). All this line of code was ever intended to do was to identify what language was going to be used in the document that followed, so we could validate the code against that version of the language's rules. Now the DTD has been radically simplified in HTML5:

XHTML 1.0 Transitional DTD code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

HTML 5 DTD code:
<!DOCTYPE html>

Part of simplifying HTML5 has included recognizing and supporting some of the common, real-world usage of HTML. So, for example, the target="_blank" attribute/value pair for the <a> tag (which can be used to cause a link to be opened in a separate browser window or tab) is so popular that HTML5 has rolled back its former deprecated (marked for deletion) status – it's now okay to use again. Similarly, all self-closing tags like <br /> and <img /> are no longer required to use the closing forward-slash explicitly stating that they are self-closing tags. Instead, in HTML5, you can write them simply as <br> and <img>. But in the spirit of being more loosely ruled, HTML5 doesn't disallow writing self-closing tags in the XHTML fashion with the closing slash – so adapting your XHTML documents to HTML5 is extremely easy, because you don't have to go back and change much. Just updating the DTD as noted above is your first step.

HTML5 Semantic Structural Tags

So what else is new and well-supported with HTML5? One of the strong trends with XHTML and CSS was to move away from using tables for page layout and to instead use a complex series of nested <div> tags combined with CSS to lay out any given page. However, since the <div> was such a generic structural container, we often coded them with a variety of classes and ID's describing their purpose. Through popular usage, some common container types became obvious: most pages would have a banner section, one or more navbars and a footer. Some pages would have sidebars for things like ads, highlighted side notes or pull quotes. Some pages might have tables or images that should be displayed with a consistently formatted caption.

HTML5 has new semantic tags for all these things, rather than just calling everything a <div> and manually assigning it some arbitrary ID or class to identify its purpose.
  • <header> – acts as a banner for the page, often containing the name of the site, logo or branding images and colors, and possibly navigation elements. Not to be confused with the <head> section of the document reserved for meta information and links to CSS, JavaScript, etc.
  • <nav> – for sections of the page with multiple links (especially for navbars used as the site's internal navigation system)
  • <footer> – a section, usually at the bottom of the page, with minor, closing details
  • <aside> – for sidebar/sidenote content of any kind
  • <figure> – to contain any illustrative information, especially that needs captioning (technically not a block-level element, but you'll often want to format it that way)
  • <figcaption> – a caption for the figure (also commonly formatted as block-level)
  • <article> – often used for blog posts, news items and periodically published content
  • <section> – another generic container, like the div. I'm not a fan of this one yet, but it's out there.
Transitioning to these new tags doesn't take that much work, especially if you are creating a webpage design from scratch. But you can also adapt an XHTML template by replacing things like <div id="banner"> with <header> and <div class="sidebar"> with <aside>. Just don't forget to make all the necessary changes in your CSS. Where #banner and .sidebar were included in your CSS (or div.#banner , or div.sidebar ), change them to header and aside instead.

Setting Basic HTML5 Compliance for Older Browsers (using Shiv and CSS)

Although many elements of HTML5 are well-supported in most modern browsers now (including most mobile devices), it's not universal. So to ensure that at least your basic HTML5 semantic tags (mentioned above) are handled properly by an older browser that is not familiar with these tags, it's an easy, two-step process.
  1. Add an HTML5 shiv/shim to the head of your HTML file.
  2. Add a style declaration to your CSS to ensure the newly introduced HTML5 tags that should be seen as block-level elements are formatted that way.
The HTML5 shiv is just JavaScript (or a link to JavaScript) that explains to an older browser that isn't familiar with HTML5 that these tags exist, and should not be ignored or rendered as plain text on the page. (The shiv is also sometimes called a shim.)
  1. 1.  Connecting to a shiv hosted by Google:
<head>
    <!--HTML5 Shiv-->
    <script
        src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
    </script>
</head>


This script we're linking to off googlecode.com essentially performs the following JavaScript function for all HTML5 elements:
<script>
    document.createElement('header');
    document.createElement('footer');
    document.createElement('aside');
    //…and so on, for each HTML5 element
</script>


You could even include the code above (with an additional line for every HTML5 tag that needed to be "created" for the older browsers) in the <head> instead of the link to the shiv from Google – but it would be more work and would only create the tags you manually listed.
  1. 2.  To further specify in CSS that some new tags should be formatted as block-level elements:
article,aside,figcaption,figure,footer,header,nav,section {display:block;}

The CSS addition above is quick, and should be placed near the top of your CSS to set the baseline formatting for these new HTML5 tags. It's just to tell the older browsers that these new tags should be displayed as block-level elements – for the most part, newer browsers will already know. Later in your CSS you could and will add additional style declarations to further format these tags – perhaps centering your header and footer or floating all sidebars to the left and giving them a tasteful background color.

Additional Development

For a fuller (but still not exhaustive!) treatment of the topics in this series, I recommend you pick up the books we're using in our HTML/CSS/jQuery class now:
  • Murach's HTML5 and CSS3 (including intro chapters for JavaScript, jQuery, and jQuery mobile) by Zak Ruvalcaba and Anne Boehm
  • SitePoint's jQuery: Novice to Ninja by Earle Castledine and Craig Sharkie
Best wishes on your continuing career development!

Tuesday, October 30, 2012

How do I use FindControl() in ASP.NET? When should I use FindControl()?

When coding ASP.NET pages, it often becomes necessary to call on a control from the code-behind page that is not directly available. Your first hint that you are in this situation is when you know the name of the control you are trying to access, but it does not show up in Visual Studio's Intellisense dropdown. Assuming you are actually calling the control by its correct ID (double-check!) then the reason it does not show up in Intellisense (and why you cannot call on it directly from the ASP.NET code-behind file) is usually because the control is housed inside some other structure.
There are several situations that can cause this, including but not limited to these three:
  1. Calling on a control, such as a textbox, that you defined on the page that used a CrossPage Postback to load this page.
  2. Calling on a control, such as a label, that you defined in the MasterPage associated with this content page.
  3. Calling on a control, such as a checkbox, that you defined in a templated control of a DetailsView on this page.
In all of these situations, the control you want to access is actually being built or housed by another control. To access it, you need to start by calling on the item you can access directly from the code-behind, then drill down into it using the FindControl() method.

The FindControl() method requires a string argument to be passed with the exact ID of the control being sought. A new Control object is returned in memory, with all the same properties and values of the one that was found. So you can use it to get the control's information or manipulate the control as needed.

Common Trip-ups

In case you don't call on the string ID properly (no Intellisense help for that!) or if under the current runtime circumstances, there is no value whatsoever for the Control you seek, you will run into a NullReferenceException. The Message property for this exception is "Object reference not set to an instance of an object". You can avoid this by first testing to make sure the control you are looking to call FindControl() from exists before trying to use it to call the method.

Keep in mind that because the FindControl() method returns a Control object, you will usually need to unbox that object to the more specific type of control you were actually looking for. So in case 1, cast it back to a TextBox. In case 2, cast it back to a DropDownList. In case 3, cast it to a CheckBox.

Also, realize that it is possible that the structure you need to dig through may be more complicated than it at first appears. Here is some sample code using FindControl() for cases 1-3, followed by a 4th example and the code it would require.

Case 1: TextBox1 available from PreviousPage property because it was passed using CrossPage Postback

protected void Page_Load(object sender, EventArgs e)
    {
        /*In a cross-page postback, be sure to test if
         * the page loaded with PreviousPage info before trying
         * to use it. If it's null, inform user of problem.
         * */
        if (PreviousPage != null)
        {
            TextBox tbName =
                (TextBox) PreviousPage.FindControl("TextBox1");
            lblName.Text = tbName.Text;
        }
        else
        {
            //Notify the user to start on the right page
            lblName.Text = "Please retry from the correct page.";
        }
    }


Case 2: DropDownList1 available from Master property because it was generated there for the Content Page

protected void Page_Load(object sender, EventArgs e)
    {
        /*Access the Label1 defined on master page from this
        * content page and assign its Text property. Each
        * content page will have unique content for this
        * label on the masterpage.
        * */
        Label lblPage = (Label)Master.FindControl("Label1");
        if (lblPage != null)
        {
            lblPage.Text = "Northwind Products Catalog";
        }
    }


Case 3: Checkbox1 available from DetailsView1 that generates it

protected void CheckBox1_PreRender(object sender, EventArgs e)
    {
        //waits until PreRender event to check the checkbox
        CheckBox cbIsActive =
            (CheckBox)DetailsView1.FindControl("CheckBox1");
        cbIsActive.Checked = true;
    }


Case 4: TextBox1 available from PreviousPage property due to CrossPagePostback. But because a MasterPage is also involved (the posted back page is a Content Page) the FindControl() path is more elaborate.

protected void Page_Load(object sender, EventArgs e)
    {
        /*Since we are involved with a masterpage, but we want
        * info on a control in PreviousPage (because of
        * crosspage postback or Server.Transfer), go through:
        * > PreviousPage> Form> ContentPlaceholder> desired control
        * */
       if(PreviousPage != null)
       {
            TextBox tbName = (TextBox)PreviousPage.Form.
            FindControl("ContentPlaceholder1").
            FindControl("TextBox1");
        }
        else
        {
            //Notify the user to start on the right page
            lblName.Text = "Please retry from the correct page.";
        }
    }   


The 4th example introduces a wrinkle because of the additional complexity of a crosspage postback combined with a masterpage. For an excellent write-up of how this actually gets built behind the scenes (and why you need to go through the PreviousPage's Form, then find its ContentPlaceHolder before you can find the TextBox inside it, see K. Scott Allen's OdeToCode.com Master Page article which includes the image below.)
Ode to Code Master Page hierarchy diagram

These types of wrinkles come up now and again when using FindControl() with more elaborate structures or controls housed inside of other controls, some of which may not be immediately apparent to you. Picking them apart is all part of furthering your capabilities with this method.

INamingContainer Sidebar

As a last technical sidenote, structures that wind up defining their own ID namespace on the page for controls housed inside them tend to implement the INamingContainer interface - meaning they must implement functionality to do just that. This is done to ensure that default ID's, like "Label1", aren't used repeatedly because some structure is automatically generating them. So just because a DetailsView builds label controls within its structure, we don't want it to generate an ID that might already being generated or used elsewhere on the page. So the DetailsView uses a naming convention for each label it generates to associate it with the control that created it – here, the DetailsView.

A standard ASP:Label control with a default ID of "Label1" would be adaptively rendered into HTML as:
<span id="Label1">Dynamically-Assigned Text Here</span>

Whereas a label control generated by a DetailsView with a default ID of "DetailsView1" would be adaptively rendered into HTML as:
<span id="DetailsView1_Label1">Dynamically-Assigned Text Here</span>

For more information, see also the MSDN information regarding the INamingContainerinterface.

At the end of the day, the FindControl() is a staple in your ASP.NET toolbox, and finding useful opportunities to employ it will improve your web development skillset.

Thursday, August 9, 2012

Visual Studio Tips and Tricks, Part III: Outlining with Collapsible Sections and #region

Eric Reid
This is part 3 of a 3-part series on Visual Studio Tips and Tricks. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.

Collapsible Sections

If you aren't taking advantage of various outlining features available in Visual Studio, you are missing out.  In C# and HTML/ASP code, some blocks of code are automatically marked as collapsible by a + symbol in the far left margin of the code block's opening line. (It's just to the right of the line number if you have those enabled).

The C# code block with a plus sign at line 66, indicating a collapsible region for the method block.

If you click on the + symbol, it will collapse the code block to display a much-abbreviated version of the block on one line. The abbreviated code block will be shown with ellipses (…) to denote the change in display. And if you're using line numbers, you'll see there is a jump from the starting line down to the next line number where the code block leaves off. Also, the + symbol changes to a - symbol. Clicking the - symbol will expand the code block back to its original size.

The C# code after collapsing the section. Note the line jump from 66 to 79, and the … abbreviation.

The benefit is being able to see the bigger picture with your code after that block is collapsed within the greater structure.


Note that collapsing code blocks in this way does absolutely nothing to affect the functionality of the code – it will still run as written. Instead, its job is to help you view the code you want at a glance. This can also help to see where a large code block ends or to help verify your opening and closing syntax.


#region Directive

In addition to the built-in collapsible sections you'll find in your code in Visual Studio, you can also manually add your own in C# (and even give them a "comment-style name") using the #region directive.


The C# code before adding a collapsible #region directive.

To add your own collapsible sections in C#:
  1. Place your cursor in the line above the section of code you want to make collapsible.
  2. Type #region
    • Optionally, type additional text to act as a comment-style name on the same line. (This additional text will not be compiled, but will be displayed when you collapse the region).
  3. Place your cursor at the end of the section you are making collapsible.
  4. Type #endregion

The C# code after adding a collapsible #region directive. This one also includes an optional comment-style name of "Variables Declaration" on the same line as the opening #region.

You can now collapse the #region directive area like any other collapsible section:
  • Click the + symbol in the left margin to collapse the region.
  • OR click the - symbol in the left margin to expand it again to its full size.

The C# code after collapsing the #region directive. (Note that because we added a comment-style name after the region, that is what is displayed after the collapse.)

Tuesday, August 7, 2012

Visual Studio Tips and Tricks, Part II: Format Spacing

Eric ReidThis is part 2 of a 3-part series on Visual Studio Tips and Tricks. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.

Visual Studio products will typically help with formatting the spacing of your code (including C#, HTML, CSS, etc.) by adding its form of standard spacing as you add line breaks or spaces within certain common structures – nesting indents for nested code blocks or tags, or adding spaces after some characters. However, it's easy (with copy-and-paste or tinkering) to get these out of whack.

To apply Visual Studio's standard spacing to your code you can use the Format Document or Format Selection features to update either the entire document or just your selected code.

The HTML code above is clearly using non-standard spacing.

Format Selection

To quickly format the spacing for the selected code:
  1. Select the code to format.
  2. Format the selection's spacing by either using the menus or shortcut keys:
    • Menu system Edit menu, Advanced submenu, Format Selection
    • OR Shortcut keys CTRL+K, then release and CTRL+F
Using Visual Studio's Format Selection feature.

The HTML code after the Format Selection feature has been applied. (Note that only the selected code, and those lines immediately before and after, have been updated.)

Format Document

To quickly format the spacing for the whole document, by using either the menus or shortcut keys:
  • Menu system Edit menu, Advanced submenu, Format Document
  • OR Shortcut keys CTRL+K, then release and CTRL+D

The HTML code after the Format Document feature has been applied. (Note all lines have been updated.)

Saturday, August 4, 2012

Visual Studio Tips and Tricks, Part I: Surround With

Visual Studio software products are a common and fundamental tool for most ASP.NET developers (and can also be used by developers and web designers for many environments). The following 3-part series illustrates a few quick tips and tricks that may help you with your work using these applications. These features are available in various versions of the Visual Studio family, including Visual Web Developer and Visual C# Express.




In this series, we'll look at the following quick-use features to speed up your code work:
  • Surround With
  • Format Document/Selection
  • Collapsible sections (and the #region)

Surround With

A common coding conundrum is the need to "wrap" some tag or code block around another section of code. The manual approach to this would be to type the opening tag or code block before the section to be surrounded; then scroll down to the end of that section and type the closing tag or code block afterwards.

A shortcut for these steps is to use the Surround With feature of Visual Studio:
  1. Select the code to surround with some other common tag or code block (such as an HTML div or a C# if block).
  2. Right-click on the selection and choose "Surround With…"
    • Alternative methods:
      • Menu system Edit menu, IntelliSense submenu, Surround With…
      • Shortcut keys CTRL+K, then release and CTRL+S
  3. Below the selected code, a pop-up menu will either display folders for different types of snippets (double-click the folder to enter), or it will display allowable snippets for that context.
  4. Double-click the desired tag or code block to surround the selected area.

Code before Surround With
In this example, the C# code should only be run if the number2 variable does not equal zero. It's a prime candidate to Surround With a C# if statement.


Applying Surround With to code, step 1
The C# code after it's been selected and right-clicked for the Surround With feature.


Applying Surround With to code, step 2
After selecting Surround With, the pop-up menu offers various snippets for surrounding the code.


Code after applying Surround With for an IF statement
The C# code after using Surround With to wrap the if statement around the code, and updating the statement's condition to only run when the number2 variable doesn't equal 0.

In the case of adding a standard if block for C#, be sure to choose the 2nd if listed (not the first one preceded by the # sign).

Tuesday, April 24, 2012

How Can I Print in Color in Visual Studio?


One issue that came up in class some time back was that a student was printing his code from Visual Studio when he noticed that all of his code was being printed in black and white. From a learning perspective, he sometimes likes to view his code on paper, mark it up by hand, draw arrows and in other ways interact with it and make it sense of it.

However, one of the helpful features of Visual Studio, of course, (and of most Integrated Development Environments) is the color coding. By default, comments are shown in green, strings of text in red, keywords in dark blue and so on. So the student wanted to see if there was any way to get Visual Studio to print the code using the color coding that shows up onscreen.

It turns out that in Visual Studio 2008 and 2010, the color coding isn't enabled for print-outs. However, there is an extension from Microsoft that can be loaded to enable it to print in color.

The upside is being able to print in color.

The downsides are:
1)      The extensions are not supported in the Express versions of the Visual Studio products, and so Microsoft's color printing extension cannot be loaded on those versions.
2)      Collapsible regions will be printed as expanded; they cannot be skipped from the printout.
3)      The new print dialog box doesn't enable printing line numbers, and so they can only be printed by enabling line number margins in Tools-->Options.
4)      Margins for the page itself cannot be altered in this version.

To review the documentation and/or install the Color Printing extension for Visual Studio, visit: http://visualstudiogallery.msdn.microsoft.com/00ec88c2-1553-47d2-8170-3c5baa0c6e44/?SRC=Home

Monday, July 25, 2011

Troubleshooting Ajax AsyncFileUpload Control

The ASP.Net Ajax Control Toolkit provides lots of interactive, feature-rich controls for the web developer. However, as my work transitioned from Visual Studio 2008 to Visual Studio 2010 products, I noticed a common problem with the Asynchronous File Upload control. The error message from trying to use the control was "The file attached is invalid".

 

If you're not familiar with this control, it behaves similarly to the normal File Upload control that's in the Standard section of the Tools panel in Visual Studio. Both versions of the control allow a user of the web application to browse for, select, and upload a file to the server. However, the Ajax toolkit's Asynchronous version allows the upload process to occur in real time (in the background) as the user continues to use the webpage, instead of forcing the user to wait for the page to be returned while the upload is being processed.

 

The issue appears to be with the control itself, but particularly when used in the .Net 4.0 framework, which is likely to be the default for Visual Studio 2010 products, unlike the 3.5 framework likely set as the default for Visual Studio 2008.

 

So, how do you fix the AsyncFileUpload that keeps telling you "The file attached is invalid"?

The Fix

Just add the ClientIDMode="AutoID" property to the control. This easy change allows the control to be properly identified. If you would like to control this at the web.config level, you could also consider using the following approach instead:



<pagecontrolRenderingCompatibilityVersion="4.0" clientIDMode="AutoID"/>


Of course, in that case you will want to be sure to test the rest of your controls to make sure this doesn't cause any problems elsewhere.

For additional reading on the topic, see:


- Eric Reid, Design Expert; CTT+, ACI (Adobe Certified Instructor), ACE (Adobe Certified Expert), i-Net+, IC3
LinkIn with Eric


Bookmark and Share

Thursday, January 6, 2011

Google Chrome and Auto Postbacks: What You WON'T See When Testing ASP.Net Apps

One common way developers transform a static web page into a dynamic web page (one that could contain different content based on varying circumstances) is by writing logic on the web server that essentially "generates" the HTML code that is needed.


Perhaps the ASP.Net code for my homepage is set to include a certain banner image if it's Friday, but a different banner for all other days of the week. When you visit my website, your browser is making a request to my web server. The web server checks the day, and only then sends the appropriate HTML code back to your browser. If today is Friday, you'll see my Friday banner at the top; otherwise you'll see another.


This is because the web server will send different HTML code based upon the circumstances. You can literally see the difference in this HTML code if you use the View Source feature in your browser on a Friday and then again on another day. It's different code being "translated" by your browser into content on the page.


Now, one of the most common ways in ASP.Net applications to dynamically update a page that’s already been requested (barring the use of AJAX) is to let the user make some choice that causes an auto postback. This means that you are already viewing a page in a browser, but something causes a new request to be made to the web server and it "re-generates" the HTML code for this same page, essentially updating it with new content.


For example, I might create a DropDownList that contains options for different headings to display on a page, then set the DropDownList's AutoPostBack property to true, and set its default event handler (SelectedIndexChanged) to display the heading chosen from the DropDownList. This configuration will cause an auto postback when you choose a different option from the drop down box on the page - meaning another request back to the web server to update this page. The web server will generate the appropriate new HTML code and send it back to your browser, where it will be reinterpreted and you'll see the new heading displayed.


Sample Code for an auto postback
Click on either image below for sample auto postback code. The first is the aspx page. The second is its aspx.cs C# code-behind file.

ASPX page code - auto postback example

ASPX.CS code-behind page - auto postback example



This is a very common technique. And for ASP.Net developers testing their application, it would be common not only to verify the browser screen has updated as expected after an auto postback, but also to use the View Source feature of the browser to see how the new code was generated.


Common Browser Handling of auto postback and ViewSource
Below is an example of the browser screen and View Source HTML code in Internet Explorer 8, before and after choosing an option from the dropdown list and causing an auto postback. Most browsers will display this behavior.

Common browser handling - Screen and ViewSource at initial page load
:



Common browser handling - Screen and ViewSource after auto postback:



Notice how in the second image, after the user chose "Wacky Heading" from the dropdown list, two things happened? The heading changed in the browser screen, and the View Source window reflected the updated code that had been sent back from the server.


Google Chrome Handling of auto postback and ViewSource
But if you're using Google Chrome, the View Source won't show the updated code. Unlike all the other major browsers out there, Google Chrome does not actually update the HTML code that its View Source displays when you "post back" to the same page with updated code. It will still show the code generated from the first request to the web server (as in the "is-it-Friday-or-not" example above), but if there is an auto postback that results in different HTML code for the page, Google Chrome's View Source will only show the original HTML code, which is very misleading. The page you see in Chrome will update (say with the new "Wacky Heading" chosen from the drop down list) but if you view the source, Chrome will still be showing the originally requested HTML code file.


Google Chrome handling - Screen and ViewSource at initial page load:



Google Chrome handling - Screen and ViewSource after auto postback:



I'm personally still a big fan of the Chrome browser for many types of browsing, but ASP.Net programmers should beware of this bug when testing.


***2011/09/30 Update:
Note, since this post was created, Chrome appears to have "gone legit" in regard to its implementation of the View Source feature, and handles the process in the traditional way now, updating the source after postbacks. (Thanks to the screenshots from the original post, though, you can still see the behavior for a browser that handles postbacks in this way. Incidentally, you'll still see this type of behavior in any browser where an asynchronous JavaScript postback manipulates the DOM behind the scenes, and the View Source fails to be updated.)

- Eric Reid, Design Expert; CTT+, ACI (Adobe Certified Instructor), ACE (Adobe Certified Expert), i-Net+, IC3
LinkIn with Eric


Bookmark and Share