.Net "Specified method is not supported." Error

by nolovelust 20. April 2011 16:13

I started to get this "Specified method is not supported." error quite a lot since I moved one of the sites to Windows 2008 R2 64bit.

Exact error something like below

 

 

Server Error in '/' Application.
Specified method is not supported. 
 Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.NotSupportedException: Specified method is not supported.

Source Error: 
 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 


Stack Trace: 

[NotSupportedException: Specified method is not supported.]
   System.Web.HttpResponseStream.get_Position() +29
   System.Drawing.ComStreamFromDataStream.Seek(Int64 offset, Int32 origin) +44

[HttpException (0x80004005): An error occurred while communicating with the remote host. The error code is 0x800703E3.]
   System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect) +3049599
   System.Web.Hosting.IIS7WorkerRequest.ReadEntityCoreSync(Byte[] buffer, Int32 offset, Int32 size) +49
   System.Web.Hosting.IIS7WorkerRequest.ReadEntityBody(Byte[] buffer, Int32 size) +23
   System.Web.HttpRequest.GetEntireRawContent() +8920994
   System.Web.HttpRequest.GetMultipartContent() +68
   System.Web.HttpRequest.FillInFormCollection() +172
   System.Web.HttpRequest.get_Form() +68
   System.Web.HttpRequest.get_HasForm() +8921807
   System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull) +97
   System.Web.UI.Page.DeterminePostBackMode() +69
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +135



Above sample from a page where user submits multipart form data.

Same eror happens when user downlods file from a HttpHandler.

Actual error is quite confusing and as far as i understand it has nothing to do with System.Drawing but client disconnect during to upload proccess.

There is a bug report about I couldn't get any more info.

I have seen no side effects of this error and can say simply igonoring it is the current solution :)

Tags: , ,

ASP.NET | Useful

mobile geolocation with jquery and google maps api and asp.net c#

by nolovelust 13. December 2010 09:38

Below code uses google maps api with local proxy code to get country,city and local area of user. Fully functuional apart from multiple entries not being filtered in the result. I'll hopefully fix it too.

It only workd phones that support navigator.geolocation such as iPhone, webOs, Android, Nokia N900

Due to same origin policy I've had to use local proxy code to download location data from google (see below)

 

To run the code create an html file and paste below code on to it 

<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
         function find() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(success, error);
            } 
            else if ( window.google && google.gears ) {
            var geo = google.gears.factory.create( 'beta.geolocation' );
            geo.getCurrentPosition(success, error);
          }
          else {
                $('#output').html('Not supported');
            }
        }
        function success(position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
            var pullurl = 'getLocationResponse.ashx?latlng=' + lat + ',' + long;
            get(pullurl);
            //$('#output').html(pullurl);
        }
        function error(msg) {
            $('#output').html('failed to get coordinates');
        }
        function get(url) {
            $.ajax({
                type: "GET",
                url: url,
                dataType: "xml",
                success: parseXml,
                error: function (xhr, status, error) {
                     $('#output').html("An AJAX error occured: " + status + "\nError: " + error);
                }
            });
        }
        function parseXml(xml) {
            $(xml).find("GeocodeResponse").each(function () {
                if ($(this).find("status").text() == "OK") {
                    parseOkXml(xml)
                }
                else {
                    $('#output').html('response code was not OK');
                }
            });
        }
        function parseOkXml(xml) {
            $(xml).find('type').each(function () { // find all "type" tag in XML
                if ($(this).text() == 'administrative_area_level_1') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
				 if ($(this).text() == 'administrative_area_level_2') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
				 if ($(this).text() == 'administrative_area_level_3') { // in here $(this) is our "type" tag
                    add($(this).parent().find('long_name').text());
                    //return false;
                }
            });
        }
		function add(data)
		{
                $('#location').append('');
		}
    </script>

Proxy code to load maps data from google getLocationResponse.ashx

 

<%@ WebHandler Language="C#" Class="getLocationResponse" %>
using System;
using System.Web;
using System.Net;
using System.IO;

public class getLocationResponse : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";
        string latlng = context.Request.QueryString["latlng"];
        string url = "http://maps.google.com/maps/api/geocode/xml?latlng=" + latlng + "&sensor=true";
        WebRequest request = WebRequest.Create(url);
        request.Timeout = 1000;
        ;


        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    context.Response.Write(reader.ReadToEnd());
                }
            }
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

 you now can request location info by calling find() JavaScript function from html

Tags: , , , , ,

ASP.NET | Mobile web | Useful

Generate website screenshot/thumbnail with .net webbrowser control on c# asp.net website

by nolovelust 4. December 2010 11:29

Attached code uses altered version of WebPreview from http://smallsharptools.com/Projects/WebPreview/. WebPreview works just fine with most of the sites but, if site you are trying to get screenshot/thumbnail has a JavaScript prompt, by default webbrowser control shows it to user. Its ok if you are using it on an asp.net application, user can click to prompt. Things change if you try to use it on an asp.net website. As there will be no one to click to prompt or even no way to display the prompt code hangs. I have derived from webbrowser control and overwrite OnNavigated event and injected some java script code to disable prompts. Download SmallSharpTools.WebPreview-1.0.0-src.rar (84.13 kb). Keep in mind that webbrowser control uses internet explorer installed on the system and trying to get screenshots/thumbnails of malicious sites may create trouble for your server.
You may also be interested with http://nolovelust.com/post/C-Website-Screenshot-Generator-AKA-Get-Screenshot-of-Webpage-With-Aspnet-C.aspx

 

WebBrowserEx.cs 

 

using System.Windows.Forms;
using mshtml;

namespace SmallSharpTools.WebPreview
{
    class WebBrowserEx : WebBrowser
    {
        public WebBrowserEx() { }

        protected override void OnNavigated(WebBrowserNavigatedEventArgs e)
        {

            HtmlElement he = this.Document.GetElementsByTagName("head")[0];
            HtmlElement se = this.Document.CreateElement("script");
            mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;
            string alertBlocker = "window.alert = function () { }";
            element.text = alertBlocker;
            he.AppendChild(se);
            string alertBlockerB = "window.confirm = function () { }";
            element.text = alertBlockerB;
            he.AppendChild(se);
            string alertBlockerC = "window.prompt = function () { }";
            element.text = alertBlockerC;
            he.AppendChild(se);
            string alertBlockerD = "window.open = function () { }";
            element.text = alertBlockerD;
            he.AppendChild(se);
            
            base.OnNavigated(e);
        }
 
    }
}

 

 

 ThumbnailBuilder.cs

 

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace SmallSharpTools.WebPreview
{
    public class ThumbnailBuilder
    {

        #region "  Events  "

        public event EventHandler ExceptionCatching;

        /// 
        /// Raise the ExceptionCatching event
        /// 
        /// 
        protected virtual void OnExceptionCatching(EventArgs e)
        {
            if (ExceptionCatching != null)
            {
                ExceptionCatching(this, e);
            }
        }

        #endregion

        #region "  Methods  "

        public void CreateThumbnail(string sourceFilename, string cachedFilename, int width, int height)
        {
            if (File.Exists(sourceFilename))
            {
                FileInfo inputFile = new FileInfo(sourceFilename);
                FileInfo outputFile = new FileInfo(cachedFilename);

                if (!outputFile.Directory.Exists)
                {
                    outputFile.Directory.Create();
                }

                if (outputFile.Exists && inputFile.CreationTime < outputFile.CreationTime)
                {
                    return;
                }

                try
                {
                    using (Bitmap inBmp = new Bitmap(sourceFilename))
                    {
                        using (Bitmap outBmp = new Bitmap(width, height))
                        {
                            using (Graphics g = Graphics.FromImage(outBmp))
                            {
                                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                g.DrawImage(inBmp, 0, 0, width, height);
                            }
                            outBmp.Save(cachedFilename);
                        }
                        
                    }
                }
                catch (Exception ex)
                {
                    CurrentError = ex;
                    OnExceptionCatching(EventArgs.Empty);
                }
            }
        }

        #endregion

        #region "  Properties  "

        private Exception _currentException = null;

        public Exception CurrentError
        {
            get { return _currentException; }
            set { _currentException = value; }
        }

        #endregion

    }
}

 

SiteConfiguration.cs 

 

using System.Configuration;
using System.Web;

/// 
/// Summary description for SiteConfiguration
/// 
public class SiteConfiguration
{
    
    public static string SourceImageDirectory
    {
        get
        {
            return HttpContext.Current.Server.MapPath(
                ConfigurationManager.AppSettings["SourceImageDirectory"]);
        }
    }

    public static string CachingImageDirectory
    {
        get
        {
            return HttpContext.Current.Server.MapPath(
                ConfigurationManager.AppSettings["CachingImageDirectory"]);
        }
    }

}

 

 

PreviewBuilder.cs 

using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace SmallSharpTools.WebPreview
{
    public class PreviewBuilder
    {

        #region "  Variables  "

        private string _url = String.Empty;
        private string _filename = String.Empty;

        #endregion
        
        #region "  Constructor  "

        public PreviewBuilder(string url, string filename)
        {
            this._url = url;
            this._filename = filename;
            // Path.Combine(Environment.CurrentDirectory, "output.bmp");
        }

        #endregion

        #region "  Methods  "

        public void CreatePreview()
        {
            ThreadStart ts = new ThreadStart(this.DoWork);
            Thread t = new Thread(ts);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();

            // TODO find the proper way to wait for a thread
            // wait for the thread
            while (t.IsAlive)
            {
                Thread.Sleep(25);
            }
        }

        private void DoWork()
        {
            Bitmap bitmap = GetPreviewImage();

            bitmap.Save(_filename);
            bitmap.Dispose();
        }

        private Bitmap GetPreviewImage()
        {
            WebBrowser wb = new WebBrowserEx();
            wb.ScrollBarsEnabled = false;
            wb.Size = new Size(Width, Height);
            wb.ScriptErrorsSuppressed = true;
            wb.NewWindow += new System.ComponentModel.CancelEventHandler(wb_NewWindow);
            wb.Navigate(_url);

           
            // wait for it to load
            while (wb.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
            }
            Bitmap bitmap = new Bitmap(Width, Height);
            Rectangle rect = new Rectangle(0, 0, Width, Height);
            wb.DrawToBitmap(bitmap, rect);
            return bitmap;
        }

        void wb_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        #endregion

        #region "  Properties  "

        private int _width = 1024;

        public int Width
        {
            get { return _width; }
            set { _width = value; }
        }

        private int _height = 768;

        public int Height
        {
            get { return _height; }
            set { _height = value; }
        }

        #endregion

    }
}

 

WebPreviewHandler.ashx 

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Caching;
using SmallSharpTools.WebPreview;

public class WebPreviewHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string url = context.Request.QueryString["url"];
        
        int width;
        if (!int.TryParse(context.Request.QueryString["width"], out width))
        {
            width = 150;
        }
        int height;
        if (!int.TryParse(context.Request.QueryString["height"], out height))
        {
            height = 100;
        }
        
        string sourceFilename = GetSourceFilename(url);
        FileInfo file = new FileInfo(sourceFilename);
        
        if (!file.Exists || file.CreationTime < DateTime.Now.AddHours(-4))
        {
            PreviewBuilder pb = new PreviewBuilder(url, sourceFilename);
            pb.CreatePreview();
        }

        string cachedFilename = GetCachedFilename(sourceFilename, width, height);
        
        if (!File.Exists(cachedFilename))
        {
            ThumbnailBuilder tb = new ThumbnailBuilder();
            // handle the error by throwing it
            tb.ExceptionCatching += delegate { throw tb.CurrentError; };
            tb.CreateThumbnail(sourceFilename, cachedFilename, width, height);
        }  
        
        context.Response.ContentType = GetContentType(cachedFilename);
        context.Response.WriteFile(cachedFilename);
    }
    
    public string GetContentType(string filename)
    {       
        string contentType = "image/x-unknown";
        string ext = Path.GetExtension(filename);
        switch (ext)
        {
            case ".jpg":
                contentType = "image/jpeg";
                break;
            case ".gif":
                contentType = "image/gif";
                break;
            case ".png":
                contentType = "image/png";
                break;
            default:
                contentType = "image/jpeg";
                break;
        }
        return contentType;
    }
    
    public string GetSourceFilename(string url)
    {
        Uri uri = new Uri(url);
        string shortFilename = uri.Host.Replace(".", "_") + 
            uri.LocalPath.Replace("/", "_") + ".png";
        return Path.Combine(SiteConfiguration.SourceImageDirectory, shortFilename);
    }
    
    public string GetCachedFilename(string sourceFilename, int width, int height)
    {
        FileInfo sourceFile = new FileInfo(sourceFilename);
        string shortFilename = sourceFile.Name;
        string ext = Path.GetExtension(shortFilename);
        string replacementEnding = String.Format("-{0}x{1}", width, height) + ext;
        string cachedFilename = shortFilename.Replace(ext, replacementEnding);
        return Path.Combine(SiteConfiguration.CachingImageDirectory, cachedFilename);
    }
    
    public bool IsReusable 
    {
        get {
            return false;
        }
    }

}


Tags: , , , ,

Important Update to Another Simple C# Wrapper For FFmpeg

by nolovelust 7. October 2010 11:00

If you haven't, read Another Simple C# Wrapper For FFmpeg before this post.

After long hours of suffering I found a solution to large video encoding on asp.net with ffmpeg! If you ever tried you already know that encoding videos larger than 5-6 MB with asp.net and FFmpeg couses Application pool to hang and start eating froms erver's ram. I finally found out that you  .NET does not provide more memory to FFMpeg. When converting large files, FFMpeg's out put stream gets filled and waits for .NET to allocate memory resources but is never done. In order to utilize less memory, you need to the buffer periodically.

To do that, just add below method to Encoder.cs and use it in EncodeVideo method instead of using RunProccess method. Or, you could replace actual RunProccess method with this one.

private string RunProcessLargeFile(string Parameters)
        {
            /* The below will be the right solution ....
             * The while loop which reads the stream is very improtant 
             * for FFMPEG as .NET does not provide more memory to FFMPEG. 
             * When converting large files, FFMPEG's out put stream gets filled...
             * And waits for .NET to allocate memory resources but is never done. 
             * In order to utilize less memory, we are clearing the buffer periodically.
             **/

            ProcessStartInfo oInfo = new ProcessStartInfo(this.FFmpegPath, Parameters);
            oInfo.WorkingDirectory = Path.GetDirectoryName(this.FFmpegPath);
            oInfo.UseShellExecute = false;
            oInfo.CreateNoWindow = true;
            oInfo.RedirectStandardOutput = true;
            oInfo.RedirectStandardError = true; 
            using (Process proc = System.Diagnostics.Process.Start(oInfo))
            {
                using (StreamReader srOutput = proc.StandardError)
                {
                    System.Text.StringBuilder output = new System.Text.StringBuilder();

                    using (StreamReader objStreamReader = proc.StandardError)
                    {
                        System.Text.StringBuilder sbOutPut = new StringBuilder();

                        while (!proc.WaitForExit(1000))
                        {
                            sbOutPut.Append(objStreamReader.ReadToEnd().ToString());
                        }

                        if (proc.ExitCode == 0)
                        {
                            proc.Close();
                            if (objStreamReader != null)
                            {
                                objStreamReader.Close();
                            }
                        }
                        else
                        {
                            proc.Close();
                            if (objStreamReader != null)
                            {
                                objStreamReader.Close();
                            }
                        }
                        return sbOutPut.ToString();
                    }
                }
            }

        }

Tags: , , , ,

Contribution to C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C#

by nolovelust 20. May 2010 18:06

Thanks to Colarado State University Web team for their improvments on my C# Website Screenshot Generator AKA Get Screenshot of Webpage With Asp.net C# (see original post first)

With their contribution it now

  • Allowing individuals to pass parameters via querystring.
  • Instead of generic thumbnail sizes of 1, 2, 3 for small, medium, and large, changed to allow individuals to specify the exact thumb size in querystring
  • Ability to now see/download the resulting image in the browser.

 

Updated CutyCaptWrapper.cs:

 

using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;

public class CutyCaptWrapper
{
    /// 
    /// 1 - small
    /// 2 - medium
    /// 3 - large
    /// 
    private int ThumbNailSize { get; set; }
    public bool ThumbKeepAspectRatio { get; set; }
    public int ThumbExpiryTimeInHours { get; set; }
    public string ScreenShotPath { get; set; }
    public string CutyCaptPath { get; set; }
    //public string CutyCaptWorkingDirectory { get; set; }
    public string CutyCaptDefaultArguments { get; set; }
    public int ThumbWidth { get; set; }
    public int ThumbMaxHeight { get; set; }

    public CutyCaptWrapper()
    {
        //default values
        ThumbNailSize = 1;
        ThumbKeepAspectRatio = false;
        ThumbExpiryTimeInHours = 168; //1 week
        ScreenShotPath = HttpContext.Current.Server.MapPath("~/ThumbCache/"); // must be within the web root
        CutyCaptPath = HttpContext.Current.Server.MapPath("~/App_Data/CutyCapt.exe"); // must be within the web root
        //CutyCaptWorkingDirectory = HttpContext.Current.Server.MapPath("~/App_Data/");
        CutyCaptDefaultArguments = " --max-wait=10000 --out-format=jpg --javascript=off --java=off --plugins=off --js-can-open-windows=off --js-can-access-clipboard=off --private-browsing=on";

    }
    /// 
    /// Checks if there is a cached screenshot of the website and returns url path to thumbnail of the website in order to use ase html image element source
    /// Usage example: <img src="<%=CutyCaptWrapper().GetScreenShot("http://google.com")%>" alt="">
    /// 
    public string GetScreenShot(string url)
    {
        if (IsURLValid(url))
        {

            if (!Directory.Exists(ScreenShotPath))
            {
                Directory.CreateDirectory(ScreenShotPath);
            }
            //set thumbnail sizes
            //SetThumbnailSize();
            string ScreenShotFileName = ScreenShotPath + GetScreenShotFileName(url);
            string ScreenShotThumbnailFileName = ScreenShotPath + GetScreenShotThumbnailFileName(ScreenShotFileName, ThumbWidth, ThumbMaxHeight);
            string RunArguments = " --url=" + url + " --out=" + ScreenShotFileName + CutyCaptDefaultArguments;

            FileInfo ScreenShotThumbnailFileNameInfo = new FileInfo(ScreenShotThumbnailFileName);

            if (!ScreenShotThumbnailFileNameInfo.Exists || ScreenShotThumbnailFileNameInfo.CreationTime < DateTime.Now.AddHours(-ThumbExpiryTimeInHours))
            {
          
                    ProcessStartInfo info = new ProcessStartInfo(CutyCaptPath, RunArguments);
                    info.UseShellExecute = false;
                    info.RedirectStandardInput = true;
                    info.RedirectStandardError = true;
                    info.RedirectStandardOutput = true;
                    info.CreateNoWindow = true;
                    //info.WorkingDirectory = CutyCaptWorkingDirectory;
                    using (Process scr = Process.Start(info))
                    {
                        //string output = scr.StandardOutput.ReadToEnd();
                        scr.WaitForExit();
                        ThumbnailCreate(ScreenShotFileName, ScreenShotThumbnailFileName, ThumbWidth, ThumbMaxHeight, ThumbKeepAspectRatio);
                        //delete original file
                        File.Delete(ScreenShotFileName);
                        //return output;
                    }
            }
            return GetRelativeUri(ScreenShotThumbnailFileName);
        }
        else
        {
            return "Wrong URL";
        }
    }
    private void ThumbnailCreate(string sourceFilePath, string outFilePath, int NewWidth, int MaxHeight, bool keepAspectRatio)
    {
        using (Image FullsizeImage = Image.FromFile(sourceFilePath))
        {
            int NewHeight = MaxHeight;
            if (keepAspectRatio)
            {
                NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
                if (NewHeight > MaxHeight)
                {
                    NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
                    NewHeight = MaxHeight;
                }
            }
            using (Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero))
            {
                NewImage.Save(outFilePath, ImageFormat.Png);
            }
        }
    }
    private string GetScreenShotFileName(string url)
    {
        Uri uri = new Uri(url);
        return uri.Host.Replace(".", "_") + uri.LocalPath.Replace("/", "_") + ".png";
    }
    private string GetScreenShotThumbnailFileName(string sourceFilename, int width, int height)
    {
        FileInfo sourceFile = new FileInfo(sourceFilename);
        string shortFilename = sourceFile.Name;
        string ext = Path.GetExtension(shortFilename);
        string replacementEnding = String.Format("{0}x{1}", width, height) + ext;
        return shortFilename.Replace(ext, replacementEnding);
    }
    private string GetRelativeUri(string pathToFile)
    {
        string rootPath = HttpContext.Current.Server.MapPath("~");
        return pathToFile.Replace(rootPath, "").Replace(@"\", "/");
    }
    private bool IsURLValid(string url)
    {
       string strRegex = "^(https?://)"
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //user@ 
        + @"(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP- 199.194.52.184 
        + "|" // allows either IP or domain 
        + @"([0-9a-z_!~*'()-]+\.)*" // tertiary domain(s)- www. 
        + @"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // second level domain 
        + "[a-z]{2,6})" // first level domain- .com or .museum 
        + "(:[0-9]{1,4})?" // port number- :80 
        + "((/?)|" // a slash isn't required if there is no file name 
        + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        Regex re = new Regex(strRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        if (re.IsMatch(url))
            return (true);
        else
            return (false);
    }
    private void SmallThumbnail()
    {
        ThumbWidth = 200;
        ThumbMaxHeight = 150;
    }
    private void MediumThumbnail()
    {
        ThumbWidth = 240;
        ThumbMaxHeight = 190;
    }
    private void LargeThumbnail()
    {
        ThumbWidth = 320;
        ThumbMaxHeight = 270;
    }
    private void Res_1024x768()
    {
        ThumbWidth = 1024;
        ThumbMaxHeight = 5000;
    }
    private void Res_1280x1024()
    {
        ThumbWidth = 1280;
        ThumbMaxHeight = 5000;
    }
    private void Res_1920x1200()
    {
        ThumbWidth = 1920;
        ThumbMaxHeight = 5000;
        
    }
    private void SetThumbnailSize()
    {
        if (ThumbNailSize == 1)
        {
            SmallThumbnail();
        }
        if (ThumbNailSize == 2)
        {
            MediumThumbnail();
        }
        if (ThumbNailSize == 3)
        {
            LargeThumbnail();
        }
        if (ThumbNailSize == 1024)
        {
            Res_1024x768();
        }
        if (ThumbNailSize == 1280)
        {
            Res_1280x1024();
        }
        if (ThumbNailSize == 1920)
        {
            Res_1920x1200();
        }
        else
        {
            ThumbNailSize = 1;
        }
    }

}

 

 

Sample usage of updated wrapper 

 

protected void Page_Load(object sender, EventArgs e)
    {
        string url = HttpUtility.HtmlDecode(Request.QueryString["url"]);
        int width;
        int maxheight;
        string result;

        if (int.TryParse(Request.QueryString["width"], out width) == false)
        {
            width = 100;
        }
        if (int.TryParse(Request.QueryString["maxheight"], out maxheight) == false)
        {
            maxheight = 100;
        }

        CutyCaptWrapper ccw = new CutyCaptWrapper();
        ccw.ThumbWidth = width;
        ccw.ThumbMaxHeight = maxheight;
        ccw.ThumbKeepAspectRatio = true;

        if (!string.IsNullOrEmpty(url))
        {
            result = ccw.GetScreenShot(url);
            //System.Threading.Thread.Sleep(5000);
            //Response.Write(result);
            Image1.ImageUrl = Page.ResolveClientUrl("~" + result);
        }
        else
        {
            Response.Write("not a valid url");
        }
        
    }

 

 

 

Tags: , , , ,

Open Source

Tag cloud

Month List