in

Stuart Manning

Belfast Web Development | C# | ASP.NET | Ajax | LINQ | JQuery | CSS | Flex

ASP.NET

  • Uploading Large Files - IIS 7

    Haveing a problem with large file uploads on IIS7. Are you finding that regardless of what you do the  <httpRuntime> setting are being ignored? Well I did and here's the anser - thanks to a Telerik article.

    Note that this does not require the "RadUpload" component to work - as featured in the  original article.
    http://www.telerik.com/help/aspnet-ajax/upload_uploadinglargefiles.html

    [Web.config] Web.config settings for 100MB and 1 hour
    <configuration>
    ...
    <system. web>
      <httpRuntime maxRequestLength="102400" executionTimeout= "3600" />
      ...
    </system .web>
    </configuration>  

    Settings for IIS7

    Add these lines in the web.config file:

    [Web.config] maxAllowedContentLength attribute for IIS7 
    <system.webServer>
    ...
       <security >
         <requestFiltering>
           <requestLimits maxAllowedContentLength="1024000000" />
         </requestFiltering>
       </security>
    </system.webServer>

    Open the file C:\Windows\System32\inetsrv\config\applicationHost.config and find the line:   

    Set the overrideModeDefault property to Allow.
    <section name="requestFiltering" overrideModeDefault="Allow" />

     

     

  • Google GeoCoder for ASP.NET C# - Latitude, Longitude, Address & Reverse GeoCode

    Google GeoCoder for ASP.NET C# is a sample code example for look up an address and return the latitude and longitude.

    Reverse look-up can be achieved by clicking on the map.

    Demo [using MicrosoftAjax.js]

    Demo [using JQuery]

    Download Source @ CodePlex http://www.codeplex.com/GoogleGeoCoder

     

     

     

     

  • Convert html image to cid - Embedding email images on the fly.

    Ever needed to convert html image link on your site to cid to embed on email

    public ArrayList arr_image_path = new ArrayList();//image array (for embedding images)
    public string _html, _plain;
    public string RootDirectory = HttpRuntime.AppDomainAppPath.ToString();
    
    
    
    public void covert_image_to_embedded_cid()
        {
            int cid = 0;
    
    
            string Pattern = @"url\(['|\""]+.*['|\""]\)|src=[""|'][^""']+[""|']";
    
    
            MatchCollection match_vars = Regex.Matches(_html, Pattern,
                                            RegexOptions.IgnoreCase);
    
    
            string img_path;
    
    
            foreach (Match match in match_vars)
            {
    
    
                _html = _html.Replace(match.Value, "src=\"cid:EmbedRes_" + cid + "\"");
    
    
                //get path;
                img_path = Regex.Replace(match.Value, @"url\(['|\""]", "");
                img_path = Regex.Replace(img_path, @"src=['|\""]", "");
                img_path = Regex.Replace(img_path, @"['|\""]\)", "").Replace("\"", "");
    
    
    
                arr_image_path.Add(img_path);
                cid++;
            }
    
    
        }
    
    
    public bool sendmail(string strTo, string strSubject)
        {
    
    
            bool success = false;
    
    
            StringBuilder sb_plain = new StringBuilder();
            StringBuilder sb_html = new StringBuilder();
    
    
            //create the mail message
            MailMessage mail = new MailMessage();
    
    
            //set the addresses
            mail.From = new MailAddress(Mail_From);
    
    
            mail.To.Add(strTo);
    
    
            //set the content
            mail.Subject = strSubject;
    
    
            //Plain Text
            AlternateView plainView = AlternateView.CreateAlternateViewFromString(_plain, null, "text/plain");
    
    
            //Html part
            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(_html, null, "text/html");
            mail.AlternateViews.Add(plainView);
            mail.AlternateViews.Add(htmlView);
    
    
            //add images
            if (arr_image_path.Count > 0)
            {
                for(int i=0; i<arr_image_path.Count; i++)
                {
                    string img = arr_image_path[i].ToString();
    
    
                    if (!img.ToLower().StartsWith("http"))
                    {
                        img = RootDirectory + img;
                    }
                    LinkedResource logo = new LinkedResource(img);
                    logo.ContentId = "EmbedRes_"+i;
                    htmlView.LinkedResources.Add(logo);
                }
            }
    
    
     
    
    
    
            //send the message
            SmtpClient smtp = new SmtpClient(MailServer); //specify the mail server address
    
    
            //check if server creditial required
    
    
            if (credentialsRequired)
            {
                smtp.Credentials = new NetworkCredential(Mail_Username, Mail_Password);
    
    
            }
    
    
            //try
            {
    
    
                smtp.Send(mail);
            }
            //catch
            {
    
    
            }
    
    
     
    
    
            return success;
        }
     

  • Call asp:updatepanel from Javascript

    Javascript

    __doPostBack ('UpdatePanel1', '');

    If your using UserControls the ClientId can be harder to find.

    Inline .aspx Javascript

    __doPostBack('<%= UpdatePanel1.ClientID =%>', '');

    or

    var panel = '<%= UpdatePanel1.ClientID =%>'

    __doPostBack(panel, '');

    A super article can be found at

    http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript

     

  • Large File upload. SwfUpload & C#

    Follow up to SwfUpload - ASP.NET Flash uploader

    SwfUpload works by placing a simple 1x1px flash application onto the page, which is highly degradable. The C# example on the main site only works with single uploads at the time of writing. So below is a quick adaption of to get the multiple large file uploader working.

    www.swfupload.com

    http://swfupload.org/project/asp_net

    Because we use a JavaScript detection routine to select

    Default.aspx - JavaScript

    <script src="jquery-1.2.3.pack.js" type="text/javascript"></script>
    
    
    <link href="/swfupload/css/custom.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="/swfupload/swfupload.js"></script>
    <script type="text/javascript" src="/swfupload/js/swfupload.graceful_degradation.js"></script>
    <script type="text/javascript" src="/swfupload/js/swfupload.queue.js"></script>
    <script type="text/javascript" src="/swfupload/js/fileprogress.js"></script>
    <script type="text/javascript" src="/swfupload/js/handlers.js"></script>
    <script type="text/javascript">
    var upload1
    
    
    window.onload = function() {
    upload1 = new SWFUpload({
    // Backend Settings
    upload_url: "../../upload.aspx",// Relative to the SWF file
                    post_params : {
                        "ASPSESSID" : "<%=Session.SessionID %>"
                    },
    
    
    // File Upload Settings
    file_size_limit : "102400",// 100MB
    file_types : "*.*",
    file_types_description : "All Files",
    file_upload_limit : "0",
    file_queue_limit : "0",
    
    
    // Event Handler Settings (all my handlers are in the Handler.js file)
    file_dialog_start_handler : fileDialogStart,
    file_queued_handler : fileQueued,
    file_queue_error_handler : fileQueueError,
    file_dialog_complete_handler : fileDialogComplete,
    upload_start_handler : uploadStart,
    upload_progress_handler : uploadProgress,
    upload_error_handler : uploadError,
    upload_success_handler : uploadSuccess,
    upload_complete_handler : uploadComplete,
    
    
    // Flash Settings
    flash_url : "/assets/swfupload/swfupload_f8.swf",// Relative to this file (or you can use absolute paths)
    
    
    swfupload_element_id : "flashUI1",// Setting from graceful degradation plugin
    degraded_element_id : "degradedUI1",// Setting from graceful degradation plugin
    
    
    custom_settings : {
    progressTarget : "fsUploadProgress1",
    cancelButtonId : "btnCancel1"
    },
    
    
    // Debug Settings
    debug: false
    });
    
    
    
         }
    </script>


    Default.aspx - body

    <div id="uploader" style="display:none">
        <div id="flashUI1" style="display: none;">
         <fieldset class="flash" id="fsUploadProgress1">
         <legend>File Upload</legend>
         </fieldset>
         <div>
          <input type="button" value="Upload file (Max 100 MB)" onclick="upload1.selectFiles()" style="font-size: 8pt;" />
          <input id="btnCancel1" type="button" value="Cancel Uploads" onclick="cancelQueue(upload1);" disabled="disabled" style="font-size: 8pt;" />
          <br />
         </div>
        </div>
        <div id="degradedUI1">
         Flash 8 or greater is required.
    Note: can place standard asp:FileUploader here.
        </div>
    </div> 

    Uploader.aspx

                             
    public HttpPostedFile posted_file;
    
    
        private static string RootDirectory = HttpRuntime.AppDomainAppPath.ToString();
    
    
        public string folder = "/images/";
    
    
        public string filename;
    
    
        protected void Page_Load(object sender, EventArgs e)
        {
    
    
            try
            {
                posted_file = Request.Files["Filedata"];
                string destination_folder = RootDirectory + folder;
    
    
                posted_file.SaveAs(destination_folder + unique_filename(posted_file.FileName, destination_folder));
    
    
                Response.StatusCode = 200;
    
    
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                // Clean up
    
    
            }
        }
    
    
    //Unique filename GetRandomFileName function
    
    
        public string unique_filename(string filename, string folder)
        {
    
    
            filename = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) +
            Path.GetExtension(orginal_file_name).ToLower();
    
    
            Boolean exists = true;
    
    
            //check if exists
            if (File.Exists(folder + filename))
            {
                while (exists)
                {
                    if (File.Exists(folder + filename))
                    {
                        exists = false;
                    }
                    else
                    {
                        filename = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) +
                        Path.GetExtension(orginal_file_name).ToLower();
                    }
                }
            }
    
    
            return filename;
    
    
        }


    Uploader will return custom 500 message if required straight back to the main page.

  • ASP.NET: Restrict Dimensions While Uploading Images With The FileUpload Control

  • Linq to XML

  • Accessing a Hyperlink (or other server control) inside a usercontrol - Custom Server Control Example for JavaScript reference

    Need to shorten a server control ClientId to be accessible from JavaScript. This example creates a custom hyperlink control with shorted ClientID sans control id.

    using System;
    using System.ComponentModel;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    
    /// <summary>
    /// Summary description for hyperlink
    /// </summary>
    /// 
    namespace Gasta.CustomControl
    {
    
    
        public class href : HyperLink
        {
    
    
            public override string ClientID
            {
                get
                {
                    return this.ID;
                }
            }
        }
    }
    
    
    
     

    Web.config <- add

    <pages>
    <add tagPrefix="custom" namespace="My.CustomControl"></add>
    </pages>


    ASPX
    <custom:href runat="server" id="li_nav_web" href="/Default.aspx" mce_href="/Default.aspx">Web</custom:href></h1>

    Reference

    http://msdn.microsoft.com/en-us/library/yhzc935f.aspx
    http://blog.danbartels.com/archive/2005/11/11/1110.aspx

  • Programmatically creating an IIS7 site

     using Microsoft.Web.Administration;
    
    
    string url = "mysite.com";
    string sitename = "mysite";
    string ip_address = "128.0.1.100";
    string folder = "c";
    
    
    protected void create_iis_instance()
        {
            
                string app_site = sitename.Replace("\\","_");
                app_site = sitename.Replace("/", "_");
                ServerManager serverMgr = new ServerManager();
                Site mySite = serverMgr.Sites.Add(sitename, folder, 80);
                mySite.Bindings.Clear();
    
    
                string bind = ip_address + ":" + 80 + ":" + url
    
    
                Binding binding = mySite.Bindings.CreateElement();
    
    
                binding.Protocol = "http";
    
    
                binding.BindingInformation = bind;
    
    
                mySite.Bindings.Add(binding);           
    
    
                serverMgr.ApplicationPools.Add(app_site);
                mySite.ApplicationDefaults.ApplicationPoolName = app_site;
                /*mySite.TraceFailedRequestsLogging.Enabled = true;
                mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";*/
                serverMgr.CommitChanges();
        }

  • Loading UserControl Dynamically in UpdatePanel

  • Regular Expression Generator

    Life just got easier. Try http://www.txt2re.com a superb regular expression generator. Generates code in C#, as well as VB, C++, ruby and more.

    Quick Example.

  • Client Side problem with maximum characters for multiline asp:textbox

    I was asked recently as to how best handle client side cut & pastes using asp:textbox. The main problem was when the TextMode is set to multiline the MaxLenght parameter is ignored.

    Client side: JavaScript solution

    function textCounter(field, countfield, maxlimit) 
    {
      var thisfield = $get(field);
      var counter = $get(countfield);
      
       if (thisfield.value.length > maxlimit)
            thisfield.value = thisfield.value.substring(0, maxlimit);
        else
            counter.innerHTML = maxlimit - thisfield.value.length;
    }

    Notice $get. This is the dom equivelent to document.getElementById courtsey of the asp.net ajax javascript client library. http://asp.net/AJAX/Documentation/Live/ClientReference/Global/GetShortCutMethod.aspx

    $get is interchangable with document.getElementById.

    Client  side: ASP.NET

    </asp:TextBox ID="txt_headline" runat="server" MaxLength="50" TextMode="MultiLine" ToolTip="Please enter only 50 chars" Width="300px">
    
    
    <span id="count_headline" style="font-weight: bold">50</span> characters

     

    To get this code working we need to bind the form attributes onKeyDown, onKeyUp, onChange

    Importantly, we use onChange to catch our paste function

    Server Side C#

    protected void Page_Load(object sender, EventArgs e) 
    
    
    {
    
    
          textcounter(); //call to bind attributes
    
    
    }
    
    
    private void textcounter()
    
    
        {
    
    
            //validation
    
    
            txt_headline.Attributes.Add("onKeyDown", "j a v a s c r i p t:textCounter('" + txt_headline.ClientID + "', 'count_headline', 50);");
    
    
            txt_headline.Attributes.Add("onKeyUp", "j a v a s c r i p t:textCounter('" + txt_headline.ClientID + "', 'count_headline', 50);");
    
    
            txt_headline.Attributes.Add("onChange", "j a v a s c r i p t:textCounter('" + txt_headline.ClientID + "', 'count_headline', 50);");      
    
    
        }

    Please replace j a v a s c r i p t with javascript in above example 

    Now, when we run our colution we will have a text counter & we will also capture paste events to lock out string longer than we require. We are capturing the changes after KeyDown, KeyUp and importantly OnChange (cut & paste)

    Futher enchancements

    By default, when I create a simple form I would expressively as validation

    </b>
    
    
    </asp:TextBox ID="txt_headline" runat="server" MaxLength="50" TextMode="MultiLine" ToolTip="Please enter only 50 chars"
    
    
                                Width="300px">
    
    
                            <span id="count_headline" style="font-weight: bold">50</span> characters</asp:RequiredFieldValidator
    
    
                                ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_headline"
    
    
                                Display="Dynamic" ErrorMessage="<br />Headline Required!">
    
    
                            </asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="txt_headline"
    
    
                                Display="Dynamic" ErrorMessage="<br />Headline cannot contain < or >" ValidationExpression="[^<>]*">

    To enrich this solution for simple form why not use ValidatorCallOutExtender as documented

    http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx

     

    </asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txt_headline"  Display="Dynamic" ErrorMessage="<br />Headline cannot contain < or >" ValidationExpression="[^<>]*">
    
    
    </cc1:ValidatorCalloutExtender ID="txt_headline " runat="server" TargetControlID="RequiredFieldValidator1">

    This requires the use of the AjaxControlKit to be added to you project, and brings much of the rich form interaction we have come to expect.

    This article, however does not exclude the idea of good server side validation. Never expect that your user relies on JavaScript to validate. Personally I add universal validation to my entity class saving the labourous task of repeatitly importing/writing validation routines. But that is for another blog.

     

     

     

     

     

     

  • Windows Server 2008 & IIS7 - Live Project

    Just a quick note that I have started on pilot of Windows Server 2008 & IIS. Installation in test server was extremely easy and by default old IIS projects where migrated on launch. Installation was < 30 mins.

    Addition of .NET 3.0 and IIS from user environment was a breeze, and IIS immediately imported my test site from previous test server with no questions asked.

    IIS7

  • AjaxToolkit - problems rendering in VS2008 - eg. TabContainer

    Never fear, if you like me are having a few problems with the AjaxControl toolkit after installing the VS2008 hotfix, then you can still get VS2005 express editions @

    http://msdn2.microsoft.com/en-us/express/aa975050.aspx

    Link provides downloads for complete express range and required SP1 where required

  • LINQ RSS Writer

    LINQ makes everyday tasks a joy and not a chore. This simple code example was implemented and deployed on http://www.causewaydesign.co.uk/ in 15 mins.

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.ServiceModel.Syndication;
    using System.Xml;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    
    
    public partial class rss : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
            DataClassesDataContext dataContext = new DataClassesDataContext();
    
    
    
            // Select data
    
            var itemsQuery = from post in dataContext.tbl_causeway_news
                             orderby post.news_date descending
    
                             select new
    
                             {
    
                                 post.news_id,
    
                                 post.news_title,
    
                                 post.news_text,
    
                                 post.news_date,
    
                             };
    
    
    
            // Prepare response
    
            Response.Buffer = false;
    
            Response.Clear();
    
            Response.ContentType = "application/xml";
    
    
    
            // Create an XmlWriter to write the feed into it
    
            using (XmlWriter writer = XmlWriter.Create(Response.OutputStream))
            {
    
                // Set the feed properties
    
                SyndicationFeed feed = new SyndicationFeed
    
                    ("Stuart Manning",
    
                    "Causeway Design - Web Development, Belfast, Northern Ireland",
    
                    new Uri("http://www.causewaydesign.co.uk"));
    
    
    
                // Add authors
    
                feed.Authors.Add(new SyndicationPerson
    
                    ("info@causewaydesign.co.uk",
    
                    "Stuart Manning",
    
                    "http://www.causewaydesign.co.uk"));
    
    
    
    
    
    
    
                // Set copyright
    
                feed.Copyright = new TextSyndicationContent
    
                    ("© Copyright 2005-"+DateTime.Now.Year.ToString()+" Causeway Design");
    
    
    
                // Set generator
    
                feed.Generator = "Causeway Design RSS Generator";
    
    
    
                // Set language
    
                feed.Language = "en-GB";
    
    
    
                // Add post items
    
                List items = new List();
    
                foreach (var Post in itemsQuery)
                {
    
                    SyndicationItem item = new Syndi