Showing posts with label web. Show all posts
Showing posts with label web. Show all posts

May 17, 2023

How to stream image from generic handler

This article provides an example of streaming images from a generic handler in .NET.

If you store your images in a database table as byte[] then you can utilize a handler to display them in a data grid.

The process involves sending a request to the handler (.ashx) page, retrieving the image, and then displaying it.

In the given example, we have a grid that stores IDs in one column and displays the corresponding images in another column using an asp:ImageField.

Create a generic handler that streams image. In this example ImageField requests image from getFaceImage.ashx by DataImageUrlField parameter in DataImageUrlFormatString format

public void ProcessRequest(HttpContext context)
{
    int id;

    if (context.Request.QueryString["id"] != null)
    {
        id = Convert.ToInt32(context.Request.QueryString["id"]);

        if (id > 0)
        {
            context.Response.ContentType = "image/jpeg";

            Stream strm = new MemoryStream();
            GetImage(id).Save(strm, ImageFormat.Jpeg);
            strm.Position = 0;

            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
        }
    }
    else
        return;
}

public Image GetImage(int id)
{
    //Make appropriate calls for image according to id
    //...

    //return the image
    return new Bitmap("");
}

Sep 10, 2018

PWA to App Shortcut in Chrome

If you are interested to open a web application like a desktop application in Chrome follow this.

Prerequisites
  • A web application
  • Web server
  • HTTPS support
  • Service Worker on web app
  • Google Chrome (My version: Version 69.0.3497.81)

Web App

If you don't have a web app you can download a sample html application here

Web Server

You can use IIS, Apache or any kind of webserver.
Or just for local testing use python package SimpleHTTPServer.
python -m SimpleHTTPServer 5000

HTTPS

For IIS it is easy to add https in Bindings link. You will need an SSL certificate. Creating a local certificate not included in here.
SSL development certificate is available for local webserver via IIS Express.

Service Worker

To complete our aim we need to add service worker to your web app.

If you downloaded my sample you can look at following files.
  • manifest.json: Contains definition for our web application.
  • sw.js: Contains service worker functions
  • default.html: Contains user interface elements, interactive functions and service worker register functions.
Or you can follow sample in Google Developer blog to add service workers to your web app.

Google Chrome

You will need to enable PWA.

Go to chrome://flags/ url in Chrome.
Enable Desktop PWAs
Experimental windowing and install banner treatment for Progressive Web Apps on desktop platforms. Implies #enable-experimental-app-banners. – Mac, Windows, Linux, Chrome OS #enable-desktop-pwas

Check service workers

You will need Chrome developer tools.

In the sample application log lines added to show status in console.



Go to Application tab > Manifest to check manifest settings.



Go to Application tab > Service Workers to check service worker.



If you followed our sample app press "Add to Home" button to see a prompt.


After that you will see a new window appears with our web application.


Shortcut appears in Chrome Apps.


Now your application looks like desktop app with it is own window. It is useful for kiosk-like apps.

Appendix: Errors

If you see an error check your manifest and worker functions.

Some error samples:
default.html:39 Uncaught TypeError: Cannot read property 'prompt' of undefined at HTMLButtonElement.btnAdd.addEventListener 

Site cannot be installed: no matching service worker detected. You may need to reload the page, or check that the service worker for the current page also controls the start URL from the manifest
Check start_url in manifest.
If start url starts with "/" it may help to remove "/".
Change 
"start_url": "/default.html?source=pwa" 
to 
""start_url": "default.html?source=pwa","

If you want to try with other browsers remember that:
beforeinstallprompt Is Not a Web Standard

Jan 14, 2016

How to send an object and a parameter to an asp.net web api

In this sample we will post an object and a string parameter with ajax from client. Asp.net side will recognize data as form data. We will convert (deserialize) coming object data into corresponding class.

  • Server side: Webapi function


[HttpPost]
public string WebapiPost()
{
    var httpRequest = HttpContext.Current.Request;

    string name = httpRequest.Form["name"];
    string jsonObj = httpRequest.Form["obj"];

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    MyObject obj = jsonSerializer.Deserialize<MyObject>(jsonObj);

    return obj.Key;

}

public class MyObject
{
    public int ID { get; set; }
    public string Key { get; set; }

}

  • Client side: Post function 

function PostDataSample(url, data) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'html',
        success: function (response) {
            console.log("PostData::success");
            callback(response);
        },
        failure: function (response) {
            console.log("PostData::failure");
            callback(response);
        }
    });

}
Note that "dataType" is "html"

  • Client side: Call post function


var name = "Oktay";
var myObject = {};
myObject.ID = 1;
myObject.Key = "key1";

PostDataSample("/api/postMyobject/WebapiPost", "obj=" + JSON.stringify(myObject) + "&name=" + name, "html");
Note that we used object as JSON.stringify. You can add more parameters.

Nov 27, 2015

Performance Counters on ASP.NET

If you want to use performance counters on your ASP.NET page you can use  System.Diagnostics.PerformanceCounter class. Example below shows running inside a generic handler.


static System.Diagnostics.PerformanceCounter cpuUsage;

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    if (cpuUsage == null)
    {
        cpuUsage = new System.Diagnostics.PerformanceCounter();
        cpuUsage.CategoryName = "Processor";
        cpuUsage.CounterName = "% Processor Time";
        cpuUsage.InstanceName = "_Total";
    }

    context.Response.Write(cpuUsage.NextValue());
}


When you test in Visual Studio you will see you can get CPU usage for every call (except first call, it is 0 for the first time). But when you deploy your code to the server probably you will see the error below.
Access to the registry key 'Global' is denied. 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.UnauthorizedAccessException: Access to the registry key 'Global' is denied.
To solve this problem;

1. Check your application pool from the IIS website settings (basic or advance).


2. Go to "Application Pools" section. Right click and select "Advanced Settings".


3. Find "Identity".


4. Go to "Server Manager" > "Local Users and Groups" > "Groups". On the right pane right click to "Performance Monitor Users" > Properties.



5. Add user you saw in the 3rd step (Identity). If you saw "ApplicationPoolIdentity" in the "Identity" then type "IIS APPPool\[Pool name]". In our example pool name is "ASP.NET v4.0".



6. Restart IIS. Now you should see the performance counter page without error.

Nov 21, 2014

Feb 11, 2010

Web Farm (Load Balancing)

Web farm term is used for load balancing. It means running a web application (or a website) on multiple servers to distribute workload. If there are too much traffic on a server then distributing load among servers is a good way. It is scalable. Once you created an environment you can add more servers easily. But there are some criteria that must be taken into consideration:
First make it clear whether there is high traffic load on your server or not. Using cache or any other technologies may solve problem. Don't jump into load balancing solution until defining real problem. Problems may come from database. The database server may have wrong configuration or insufficient hardware. Network configuration also have a place in problem space.
If you decide to make web farm then you should use a load balancer. There are very smart balancers that have features like firewall, cache, filtering, client authentication, tcp buffering, http compression, DDoS protection and so on. 
Be careful when you update your website. To keep all servers synchronized all of them must be updated. Deploying new versions must be tracked.
As you see there are too much servers. We had one before load balance. After that we have at least 3- load balancer, 2 web servers.

I want to mention an important point about web farm in terms of Asp.net. A couple of years ago a company that have a load balancing solution came to us. We decided to try it. I don't know what they did on our servers. But i know they weren't successful. Because they didn't know how to manage ASP.NET sessions. This is another task that we need to complete. 

A state server must be created to keep sessions. I won't write detailed steps. You should know about tags that is used to set some parameters in web.config file. You may want to keep sessions on Sql Server than you must set sessionstate mode to SQLServer. You can read ASP.NET State Management Overview article.

<sessionstate cookieless="false" mode="SQLServer" sqlconnectionstring="data source=SERVERNAME; user id=sa; password=sa" stateconnectionstring="tcpip=127.0.0.1:42424" timeout="20">

Feb 4, 2010

Cloud Computing

There are many discussions on the internet about cloud computing. Cloud is internet. But computing is a fuzzy word with cloud.
The best definition that i've seen is on wiki page. Please read it to get detailed explanation.
What i understand from Cloud Computing is "software as a service" concept.

The problems with software set up are:
  • installing an application,
  • downloading updates,
  • buying server to host application,
  • providing office spaces for server,
  • paying to set up server (physical set up-hardware, network-, software set up)
  • worrying about security,
  • buying expensive licences,
  • hiring experts with high costs.
These problems are general. But the question is which applications should we use as a service. Many applications need to be installed on the local of the corporation becasue they worry about their security especially about data security. What cloud computing offer is an alternative solution to use technology. It is a model and growing concept. We must take it into consideration.

If corporations use this model wisely then they will reduce costs. All of the problems that i mentioned above consume resources. Why do we buy Microsoft Office? Do we use all features? In the future we will use office as a service. Google started a big challenge with many services. Google Docs is a very sophisticated service. I use especially "service" keyword. Because we don't install anything. We don't keep any application files. We only use it.

I hope we will see many alternative services soon. Mail applications and office packages are only examples. We can connect those services together and reach them from everywhere.