Thats Why No-One Will Remember Your Name

Share a Session Across ASP Classic and ASP.NET Webforms

24. November 2016 04:56 by Scott in C#, ASP Classic, Webforms  //  Tags:   //   Comments (0)

This is a brief code piece how to share sessions across ASP Classic and ASP.NET.  Having to make some changes on a classic site and I would rather not keep writing classic.  So after I migrated the site to ASP.NET using DLRSOFT.ASP, I needed to make sure that I can access the ASP Classic Session without replacing destroying the ASP Classic code base.  So I got this gem from Jonavis but I have made a few updates to it to make it work better.

This is a page called aspsession.asp.  This page allows me to send and receive ASP Classic session variables.

<%@ Language=VBScript %>
<%Option Explicit%>
<%Response.Expires=-1%>

<%
Dim strMode, strName, strValue

If Request.ServerVariables("REMOTE_ADDR") = Request.ServerVariables("LOCAL_ADDR") Then
    strMode = Request.QueryString("mode")
    strName = Request.QueryString("name")
    If strMode = "get" Then
        Response.Write(Session(strName))
    ElseIf strMode = "set" Then
        strValue = Request.QueryString("value")
        Session(strName) = strValue
    End If
End If
%>
 
 
 
Then this is the C# logic I plugged in so that I can send and receive the session from ASP Classic.
 
 public static object Get(string name)
        {
            HttpContext context = HttpContext.Current;
            object value = null;
            String[] cookies = context.Request.Cookies.AllKeys;
            System.Uri uri = context.Request.Url;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString() + "/Services/AspSession.asp?mode=get&name=" + name);

            for (int i = 0; i < cookies.Length; i++)
            {
                HttpCookie cookie = context.Request.Cookies[cookies[i]];
                if (cookie.Name.StartsWith("ASPSESSION"))
                {
                    request.Headers.Add("Cookie: " + cookie.Name + "=" + cookie.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader readStream = new StreamReader(responseStream, encode);
            value = readStream.ReadToEnd();
            response.Close();
            readStream.Close();

            return value;
        }

        public static void Set(string name, object value)
        {
            HttpContext context = HttpContext.Current;

            String[] cookies = context.Request.Cookies.AllKeys;

            System.Uri uri = context.Request.Url;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri.Scheme + "://" + uri.Host + ":" + uri.Port.ToString() + "/Services/aspsession.asp?mode=set&name=" + context.Server.UrlEncode(name) + "&value=" + context.Server.UrlEncode(value.ToString()));

            for (int i = 0; i < cookies.Length; i++)
            {
                HttpCookie cookie = context.Request.Cookies[cookies[i]];

                if (cookie.Name.StartsWith("ASPSESSION"))
                {
                    request.Headers.Add("Cookie: " + cookie.Name + "=" + cookie.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();

        }
 
After that, this method simply works.
 

Insert HTML at Cursor/Caret within a Content Editable Div

27. July 2014 03:29 by Scott in javascript, jquery, C#, Development  //  Tags:   //   Comments (0)

First we need to capture the cursor position within the Div it self.

$scope.editorSelection;

    $scope.SetupEditor = function () {
        var editable = document.getElementById('editor'),
selection, range;
        var captureSelection = function (e) {
            // Don't capture selection outside editable region
            var isOrContainsAnchor = false,
                isOrContainsFocus = false,
                sel = window.getSelection(),
                parentAnchor = sel.anchorNode,
                parentFocus = sel.focusNode;

            while (parentAnchor && parentAnchor != document.documentElement) {
                if (parentAnchor == editable) {
                    isOrContainsAnchor = true;
                }
                parentAnchor = parentAnchor.parentNode;
            }

            while (parentFocus && parentFocus != document.documentElement) {
                if (parentFocus == editable) {
                    isOrContainsFocus = true;
                }
                parentFocus = parentFocus.parentNode;
            }

            if (!isOrContainsAnchor || !isOrContainsFocus) {
                return;
            }
            selection = window.getSelection();

            // Get range (standards)
            if (selection.getRangeAt !== undefined) {
                range = selection.getRangeAt(0);

                // Get range (Safari 2)
            } else if (
                document.createRange &&
                selection.anchorNode &&
                selection.anchorOffset &&
                selection.focusNode &&
                selection.focusOffset
            ) {
                range = document.createRange();
                range.setStart(selection.anchorNode, selection.anchorOffset);
                range.setEnd(selection.focusNode, selection.focusOffset);
            } else {
                // Failure here, not handled by the rest of the script.
                // Probably IE or some older browser
            }
            $scope.editorSelection = range;
        };
        editable.onkeyup = captureSelection;
    }

 

From here, we need to be able to insert HTML at the selection when we choose to.

    function insertHtmlAfterSelection(html) {
        var range, expandedSelRange, node;
        if ($scope.editorSelection) {
            range = $scope.editorSelection;
            expandedSelRange = range.cloneRange();
            range.collapse(false);
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
        }
    }

 

That will be it.

High Precision Stop Watch Class For C#

9. March 2014 14:27 by Scott in C#, Stopwatch  //  Tags:   //   Comments (0)

Requirements were to make a very high precision stop watch class for one of our projects.  This is what we came up with.  This class is used in one application by many sports teams around the world.

public class StopwatchWrapper : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        Timer timer;

        private bool _isPaused;
        /// <summary>
        /// is the clock currently counting down.
        /// </summary>
        public bool IsPaused
        {
            get { return _isPaused; }
            set
            {
                _isPaused = value;
                OnPropertyChanged("IsPaused");
            }
        }
        /// <summary>
        /// we need to track how many milliseconds occured since the last elapsed timer interval.
        /// </summary>
        private long _millisecondsSinceLastInterval = 0;

        private bool _isRunning;
        /// <summary>
        /// is the clock currently counting down.
        /// </summary>
        public bool IsRunning
        {
            get { return _isRunning; }
            set
            {
                _isRunning = value;
                OnPropertyChanged("IsRunning");
            }
        }
        private long _timerLength;
        public long TimerLength
        {
            get { return _timerLength; }
            set
            {
                _timerLength = value;
                OnPropertyChanged("TimerLength");
            }
        }
        private DateTime _startTime;
        public DateTime StartTime
        {
            get { return _startTime; }
            set
            {
                _startTime = value;
                OnPropertyChanged("StartTime");
            }
        }

        private long _timeElapsed;
        public long TimeElapsed
        {
            get { return _timeElapsed; }
            set
            {
                _timeElapsed = value;
                OnPropertyChanged("TimeElapsed");
            }
        }

        private bool _isClockAtZero;
        public bool IsClockAtZero
        {
            get { return _isClockAtZero; }
            set
            {
                _isClockAtZero = value;
                OnPropertyChanged("IsClockAtZero");
            }
        }

        private long _timeRemaining;
        /// <summary>
        /// time remaing in milliseconds from the timer Length
        /// </summary>
        public long TimeRemaining
        {
            get { return _timeRemaining; }
            set
            {
                _timeRemaining = value;
                OnPropertyChanged("TimeRemaining");
            }
        }

        public StopwatchWrapper(long timeForClockInMilliseconds)
        {
            timer = new Timer(500);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            TimerLength = timeForClockInMilliseconds;
            TimeRemaining = timeForClockInMilliseconds;
            TimeElapsed = 0;
        }
        /// <summary>
        /// dummy constructor for the xport of xml games
        /// </summary>
        public StopwatchWrapper()
        {
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            TimeSpan ts = DateTime.UtcNow - StartTime;
            _millisecondsSinceLastInterval = (long)ts.TotalMilliseconds - _millisecondsSinceLastInterval;

            TimeElapsed += _millisecondsSinceLastInterval;
            TimeRemaining = _timerLength - TimeElapsed;

            _millisecondsSinceLastInterval = (long)ts.TotalMilliseconds;



            Console.WriteLine(TimeElapsed);
            Console.WriteLine(_timerLength);
            Console.WriteLine(TimeRemaining);
            Console.WriteLine(StartTime);
            IsRunning = true;
            if (TimeRemaining <= 0)
                IsClockAtZero = true;
        }

        public void Stop()
        {
            if (timer != null)
                timer.Stop();
            IsRunning = false;
        }
        public void Pause()
        {
            if (timer != null && IsRunning)
            {
                timer.Stop();
                IsPaused = true;
            }
        }
        public void Start()
        {
            StartTime = DateTime.UtcNow;
            timer.Start();
            IsRunning = true;
            IsClockAtZero = false;
            _millisecondsSinceLastInterval = 0;
        }
        /// <summary>
        /// resumes the clock.
        /// </summary>
        public void Resume()
        {
            if (IsPaused)
            {
                StartTime = DateTime.UtcNow;
                timer.Start();
                IsRunning = true;
                IsPaused = false;
                _millisecondsSinceLastInterval = 0;
                Console.WriteLine(TimeElapsed);
                Console.WriteLine(_timerLength);
                Console.WriteLine(TimeRemaining);
                Console.WriteLine(StartTime);
            }
        }
        /// <summary>
        /// adds seconds to the clock.
        /// </summary>
        /// <param name="seconds">seconds to be added.  Can be negative or positive.</param>
        public void AddSecondsToClock(int seconds)
        {
            if (StartTime == new DateTime())
            {
                StartTime = DateTime.UtcNow;
                TimeRemaining = _timerLength;
            }
            StartTime = StartTime.AddSeconds(seconds);
            TimeRemaining += seconds * 1000;
            TimerLength += seconds * 1000;
            //Console.WriteLine("change");
            //Console.WriteLine("change"+TimeRemaining);
            //Console.WriteLine("change"+TimerLength);
        }
        /// <summary>
        /// changes the amount of seconds of a clock
        /// </summary>
        /// <param name="seconds"></param>
        public void changeSecondsOfClock(int seconds)
        {
            TimeElapsed = 0;
            TimeRemaining = seconds * 1000;
            TimerLength = seconds * 1000;
            //Console.WriteLine("change");
            //Console.WriteLine("change" + seconds);
            //Console.WriteLine("change" + TimeRemaining);
            //Console.WriteLine("change" + TimerLength);
        }

        public void Reset()
        {
            IsRunning = false;
            StartTime = DateTime.UtcNow;
        }


        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

    }

TinyMCE writer Image Upload for C# MVC

23. November 2013 21:12 by Scott in C#, javascript, tinymce, jquery  //  Tags:   //   Comments (0)

Just a quick code sample on how to plug an Image Upload into C# and MVC.  Since I searched all around the internet with no real easy example.

Put this somewhere on the page. This will be where the person adds the image.  As you can see, we will be posting the image to the “data-action” attribute.

  @Html.TextArea("Message", string.Empty, new
                           {
                               id = "wmd-input"
                           })
                            <div id="insertImageDialog" title="Insert Image">
                                <input type="file" name="file" id="file" data-action="/forum/postimageupload" />
                            </div>

Here is the Javascript. 

  1. Below, you can see in the first block, I create another button for TinyMCE panel.  I call it the imageUpload.
  2. I then add it to the Plugin Manager.
  3. I then enable it in the plugins: options called imageUpload.
  4. I create a Modal Dialog as I am using Jquery and the Jquery.UI library within my project.
  5. Below that is the hook up for the Image Upload Modal.  As you can see I use the AjaxFileUpload by jquery.
$(function () {
        tinymce.create('tinymce.plugins.imageUpload', {
            createControl: function (n, cm) {
                switch (n) {
                    case 'imageupload':
                        var c = cm.createButton('mysplitbutton', {
                            title: 'Upload Image',
                            image: '@Url.Content("~/content/images/icons/imageUpload.png")',
                            onclick: function () {
                                $dialog.dialog('open');
                            }
                        });
                        return c;
                }
                return null;
            }
        });
        tinymce.PluginManager.add('imageIupload', tinymce.plugins.imageUpload);
        tinymce.init({
            mode: "textareas",
            elements: "elm2",
            theme: "advanced",
            skin: "o2k7",
            skin_variant: "silver",
            plugins: "imageIupload,safari,style,layer,table,advhr,advimage,advlink,inlinepopups,preview,media,contextmenu,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

            theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,blockquote,|,formatselect,fontsizeselect",
            theme_advanced_buttons2: "link,unlink,anchor,image,imageupload,cleanup,code,|,preview,|,forecolor,backcolor,|tablecontrols,|,hr,removeformat,visualaid,|,iespell,media,|,ltr,rtl",
            theme_advanced_buttons3: "",
            theme_advanced_buttons4: "",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,
            language: "en",
            relative_urls: false
        });
        var $dialog = $('#insertImageDialog').dialog({
            autoOpen: true,
            closeOnEscape: false,
            modal: false,
            open: function (event, ui) {
                $(this).parent().css('position', 'fixed');
                $(".ui-dialog-titlebar-close").hide();
            }
        });
        var $loader = $('span.loading-small', $dialog);
        var $url = $('input[type=text]', $dialog);
        var $file = $('input[type=file]', $dialog);
        var dialogInsertClick = function () {
            dialogClose();
        };
        var dialogCancelClick = function () {
            dialogClose();
        };
        var dialogClose = function () {
            $url.val('');
            $file.val('');
            $dialog.dialog('close');
        };
        $dialog.dialog('option', 'buttons', {
            'Insert': dialogInsertClick,
            'Cancel': dialogCancelClick
        });
        var uploadStart = function () {
            $loader.show();
        };
        var uploadComplete = function (response) {
            $loader.hide();
            if (response.success) {
                tinyMCE.execCommand("mceInsertContent", false, "<img src='" + response.imagePath + "'/>");
                dialogClose();
            } else {
                alert(response.message);
                $file.val('');
            }
        };
        $file.unbind('change').ajaxfileupload({
            action: $file.attr('data-action'),
            onStart: uploadStart,
            onComplete: uploadComplete,
            'params': {
                'Id': '@Model.Id',
                'TopicId': '@Model.Id'
            },
        });
        $dialog.dialog('close');
    });
 


Here is the MVC Model Method.

As you can see from above, within the AjaxFileUpload, I am posting a C# Model.  Its called NewPost.  Below is the Model I am passing in.

    [HttpPost]
        public ActionResult PostImageUpload(NewPost model)
        {
            string result;
            var serializer = new JavaScriptSerializer();
            try
            {
                // upload the file
                if (model.File != null && model.File.ContentLength > 0)
                {
                   
                }
            }
            catch (Exception exception)
            {
                ErrorDatabaseManager.AddException(exception, exception.GetType());
            }
            result = serializer.Serialize(
                        new { success = false, message = "Invalid image file" });
            return Content(result);
        }

Last but not least, I am posting a file within the Model.  Rather than it be apart of the request object, its within the model.

public HttpPostedFileBase File { get; set; }

 

Hope this little write up helps someone.

Small Google Calendar Class To Add Events

17. September 2013 18:22 by Scott in C#  //  Tags:   //   Comments (0)

I created a small C# class to add Google calendar events to a calendar in C#.  It is quite simple, but I didn’t find it searching the internet, so here it is.  Its dead simple.

 public class GoogleCalendar
    {

        private static string GoogleUrl = "http://www.google.com/calendar/event?action=TEMPLATE";
        public string What { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public string Description { get; set; }
        public string Location { get; set; }
        public string WebsiteName { get; set; }
        public string Website { get; set; }

        public string GetGoogleUrl()
        {
            //20130918T103000Z
            return GoogleUrl + "&text=" + What + "&dates=" + StartDate.ToString("yyyyMMddTHHmmssZ") + "/" + EndDate.ToString("yyyyMMddTHHmmssZ") + "&details=" + Description + "&location=" + Location + "&trp=false" + "&sprop=" + WebsiteName + "&sprop=name:" + Website;
        }
    }

Multi-Threading with C# and a Website

23. November 2011 00:40 by Scott in Development, C#  //  Tags: , , ,   //   Comments (6)

Let me tell you my experience.

I have a website at http://www.utopiapimp.com that gets hit well over 1 Million times a day.  Thats 11 hits every Second.  Utopiapimp works on being a Live Stock Ticker for a online game called Utopia.  My users need live feeds 24/7 of whats happening in the game and thats what my application does for it.  Live feeds 24/7 for all users.  Its extremely dynamic as well.  Always changing, always updating.

My server that hosts my website is a VPS located with the company Ultima Hosts.  I have a middle tiered plan that costs a bit to host.  The advertising on Pimp pays for the hosting fees, but it doesn’t cover any more than that.  I have 4 GBs of Ram and 1 CPU.  I store so much in the caching system, that I take and use up at times almost all 4 GBs of Ram.  The problem mainly is the CPU.  At times the CPU hits 80% used and other times it coasts around 15% used.  So I was hoping to bring in some multi threading into Pimp to make the inserts into the DB much faster and a much faster response time for the users.

I started with just one thread, the new type of tasking in C# introduced in .Net 4.0.

Task.Factory.StartNew(() => DoSomeWork());

The Problem with this I think, is I only have one CPU.  When I implemented this method, I sadly and immediately saw a block.  The application started to hang.  I spent the next few weeks to try and stop the hang.  Yes, sadly, I introduced a bug so bad, I immediately started getting user connections loss.  I introduced a ton of code when I introduced this bug, so I was completely lost on the topic.  I thought well, it had to be something else.  Not until I wrapped the task around my error handling code to insert errors into the DB, did I realize what was going on. So I tried threading instead.

System.Threading.Thread newThread = new System.Threading.Thread(anObject.AMethod);
newThread.Start();

This didn’t work either.  I then realized, well maybe threads just don’t work on .Net Web apps.  I then thought, well maybe its just my 1 CPU.  Well, I haven’t yet upgraded to the second CPU, to test this out.

But believe me, when I get the chance, I will.

Scott