Discussion Locked

Aloks Blog

0 helpful
8 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
blog root

8 replies

by alok

I am working on a C# webservice project where you have to transfer a lot of image files. I was not quite satisfied that the binary data I sent was converted to a 64 bit string and then converted back to binary. Finally I found that using DIME in WSE you can actually send the binary data without converting them, they just add them as attachments. Also, one another major problem was that the desktop capture didn't show the cursor, I also found the solution for that. Here is the revised version of the code.....

On the server........

byte [] img = null;
lock(_robj){
img = _robj.GetDesktopBitmapBytes(); //this is just a method for capturing the screen and returning it as it binary value
}
System.IO.MemoryStream ms = compress.CompressBitmap(img);//this method is used to compress the image
Bitmap bmp = (Bitmap) Image.FromStream(ms);
Graphics g = Graphics.FromImage(bmp);
Point cursor = System.Windows.Forms.Control.MousePosition;
cursorimage.Draw(g, new Rectangle(cursor.X,cursor.Y,cursor.X+50,cursor.Y+50));

g.Save();
System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
bmp.Save (ms2,System.Drawing.Imaging.ImageFormat.Jpeg);
Display.AppendText("-------------------------------\n");
Display.AppendText("Saving Image\n");
DimeAttachment dattach = new DimeAttachment("imagefile","image/jpeg",TypeFormat.MediaType,ms2);
proxy.RequestSoapContext.Attachments.Clear();//clear previous attachment...
proxy.RequestSoapContext.Attachments.Add(dattach);
try{
proxy.SaveImage();
}
catch(Exception exp){
Display.AppendText(exp.ToString());
}
Display.AppendText("Image Saved at " + DateTime.Now.ToString()+"\n");
Display.AppendText("--------------------------------\n");

On the client.......(which is actually the webservice on this case)

[SoapDocumentMethod(OneWay=true)]
[WebMethod]
public void SaveImage()
{
UsernameToken user = GetUsernameToken((RequestSoapContext.Current));
string sessionvalue = user.Principal.Identity.Name+"_save";
Object _countobj = Application[sessionvalue];
int count;
if (_countobj == null) count = 0;
else{count = (Int32) _countobj;
count = (count+1)%Globals.imageperuser;
}
Image bmp =null;
bmp = new Bitmap(RequestSoapContext.Current.Attachments["imagefile"].Stream);
string username = user.Principal.Identity.Name;
string userimagepath = imagepath+"\\"+username+"image_"+count.ToString()+".jpg";
bmp.Save(userimagepath, System.Drawing.Imaging.ImageFormat.Jpeg );
SessionManager smanager = (SessionManager) Application["_smanager"];
smanager.SetExpirationTime(username);
Application[sessionvalue] = count;
}

This post originally appeared on an external website

by alok

So the project I am working on also involves a web client, the client part which shows the images from another computers screen. Now there were several problems that we faced, we had to do it without using any ActiveX components or the custom active controls build using .NET. So we had to use javascript to develop this. Now, it is pretty easy to load a new image with javascript, but as the pictures in our system are constantly changed, first we run into the problem of browser caching. Wen browser caching is enabled, once the picture is loaded, loading the picture a second time shows the same image (of course it loads faster) but does not show the new version of the picture. But thankfully there is a quick fix for that. For example if the image is http://www.whatever.com/test.jpg and you want to load a new version of the picture you can do this using http://www.whatever.com/test.jpg?t=0009. Now the postfix doesn't actually do anything, but the browser doesn't know that, so it loads the image as if it were loading it for the first time, without browser catching. The scope of this technique doesn't just apply to images, it can be very useful wih html or other server-side pages. I personally use it constantly to see the new changes I have made to my blog. Of course, if the prefix DOES actually exist, then you may run into some problems. So that was the solution to the first problem. Another, a more critical one was that the use could actually see the pictures being loaded, which was quite not acceptable. What we wanted was for the pictures to load at once, without the user noticing that a new image was loaded(obviously, he can see the new version of the image). Now we all know that one sure method of achieving that is using preloading. When you use a script in javascript like

image = new Image();
image.src = "c:\welcome.jpg";

the browser loads the image and saves it in is cache, and when the image is actually displayed on the browser, it is displayed very quickly. Now this works well in other cases, since once the images are preloaded, newer version of the same images are not required. As we later found out, just preloading the images didn't work. One of the problems was that the preload method is called asyncronously, so if you display the image immediately after preloading, it fails. Of course, it preloads the image, but when you display it before it is completely loaded in the cache, you will see the image being loaded. So one way to fix this would be using a setTimeout() immediately after calling the preload method. But this method has its catch too. Because of the varying bandwidth, how do you know how much time should you allocate. If you set the method for 10 seconds, then it would be too slow for those with higher bandwidth and not enough for those using dial-up. One other point, the setTimeout() method is also called asyncronously, and the code below it is executed immediately, So some code like:

//do something
setTimeout('dostuff()', 10000) //time in
milliseconds
//stuff to do after
10000 seconds

doesn't work. You can include the latter part in the method dostuff() instead.
Of course, the only logical thing to do here is to show the image only after completely loading the image. Surprisingly, even this causes some flickers. So just to make sure, I set a timeout of 200 milliseconds so that we can be perfectly sure. Heres the code....

language='JavaScript' type='text/javascript'>

image =
'c:\\images\\kimage_0.jpg' //name of the image

image1 = new
Image();

function showimage(){

if (!image1.complete)
{
setTimeout('showimage()',200);
return;
}
else{
document.images['off'].src
= document.images['on'].src;
document.images['on'].src =
image1.src;
Start_on();
document.images['off'].src
= document.images['on'].src;
}
}
function Start_on() {
tmp = new Date()
tmp = '?'+tmp.getTime()
image1.src =
image+tmp
image1.onload =
function(){setTimeout('showimage()',200);}
image1.onerror =
function(){setTimeout('Start_on()',200);}
}

name='off' src = 'c:\images\kimage_0.jpg'>

name='on' src = 'c:\images\kimage_0.jpg' onload
='javascript:Start_on()'>

And also just to be really sure, I used two div tags, one that displays the latest image and the other that shows the previous one, so that and even if something goes wrong, I have one that works.
Its just something that works perfectly for a webcam or something like that.

This post originally appeared on an external website

by alok

Now that refreshing the image has been solved, we move on to another minor update. Instead of refreshing only one image, we save the incoming image streams into multiple files and then rotate through the image files. Now, since the files are saved asynchronously, one file may be updated later than others and as we rotate throught the pictures, we will come across an 'old' image in midst of 'new' ones. To solve this problem, we have to check the write timestamp on the images. Then we can save the latest timestamp from among the images and discard images whose timestamp is older than this timestamp.

private string GetNewImage(string me, string host)
{
string sessionvalue = me+"_retrieve_"+host;
Object _countobj = Context.Cache[sessionvalue];

int count;
if (_countobj == null) count = 0;
else
{
count = (Int32) _countobj;
count = (count+1)%Globals.imageperuser;
}
Context.Cache[sessionvalue] = count;
string userimagepath = Globals.imagepath+"\\"+host+"image_"+count.ToString()+".jpg";
long image_timestamp = System.IO.File.GetLastWriteTime(userimagepath).ToFileTime();
string str_timestamp = me+"_timestamp_"+host;
object prevtimestamp = Context.Cache[str_timestamp];
if(prevtimestamp !=null && (long) prevtimestamp>image_timestamp) return this.GetNewImage(me,host);
Context.Cache[str_timestamp] = image_timestamp;
return userimagepath;
}

[WebMethod]
public void RetriveImage(string host, int sessionid)
{
UsernameToken user = GetUsernameToken((RequestSoapContext.Current));
if (ValidUserSession(host,sessionid) && IsUsernameToken((RequestSoapContext.Current)))
{
string userimagepath = GetNewImage(user.Principal.Identity.Name,host);
SoapContext respContext = ResponseSoapContext.Current;
DimeAttachment dimeAttach = new DimeAttachment("image/jpeg",TypeFormat.MediaType,userimagepath);
respContext.Attachments.Add(dimeAttach);
}
}

Well this works nicely for a webservice, and with a few modifications, it is also possible to use this method with web applications.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication2
{

///

/// Summary description for imagehandler.
///

public class imagehandler : System.Web.UI.Page
{

private void Page_Load(object sender, System.EventArgs e)
{

// Put user code to initialize the page here
//string src = Request.QueryString["src"];
if (Session["clienthandle"]==null)
{
Response.Write("You are not authorized to view this page.");
return;
}

string imagesrc = GetNewImage(User.Identity.Name.ToString(),(string)Session["clienthandle"]);
System.Drawing.Image bmp = System.Drawing.Image.FromFile(imagesrc);
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}

private string GetNewImage(string me, string host)
{
string imagefolder = System.Configuration.ConfigurationSettings.AppSettings["imagefolder"];
string sessionvalue = me+"_retrieve_"+host;
Object _countobj = Application[sessionvalue];
int count;
if (_countobj == null)
{
count = 0;
Application[sessionvalue] = count;
return imagefolder+"wait.jpg";
}
else
{
count = (Int32) _countobj;
count = (count+1)%Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["imageperusers"]);
}

Application[sessionvalue] = count;
string userimagepath = imagefolder+host+"image_"+count.ToString()+".jpg";
long image_timestamp = System.IO.File.GetLastWriteTime(userimagepath).ToFileTime();
string str_timestamp = me+"_timestamp_"+host;
object prevtimestamp = Application[str_timestamp];
if(prevtimestamp !=null && (long) prevtimestamp>image_timestamp) return this.GetNewImage(me,host);
Application[str_timestamp] = image_timestamp;
return userimagepath;
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
///

/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
}

This post originally appeared on an external website

by alok

Well lately I haven't been working on my main project, I'm just finishing up on some other stuff....
Anyways, I totally canned the previous model because it was pretty slow, when you had to check the timestamp on the images and the overhead in saving and opening files from a hard drive. So now the code is completely revamped using Caching. So now I just cache the images and retrieve them from the cache itself, without saving it on the hard drive. This has so many advantages above the other. For one, I had developed this session manager class which would check for valid sessions running, now I have no need for that altogether, all user session which are not used within a given timeframe are disposed of.
Here is the code although I still need to make some minor changes.....

using System;
using System.Web;
using System.Web.Caching;
using
System.IO;

namespace DesktopCaptureService
{
///

/// Specification for entering data into the cache...
/// for
users: "user."+username
/// for the queue: "updater."+username
///
///

public class CacheHelper:System.Web.HttpApplication
{

static CacheHelper()
{
//
// TODO: Add constructor logic
here
//
}
///

///
///

/// public static int UserSessionStart(string username,
int sessionid)
{
int session =
DatabaseHelper.StartSession(username,sessionid);
if (session !=
DatabaseHelper.INVALIDSESSION)
HttpContext.Current.Cache.Insert("user."+username, session, null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(Globals.sessionexpirationtime),CacheItemPriority.High,new
CacheItemRemovedCallback(RemovedCallback));
return session;
}
///

///
///

/// public static void UserSessionStop(string username)
{
HttpContext.Current.Cache.Remove("user."+username);
DatabaseHelper.StopSession(username);
}
///

///
///

/// /// public static void InsertImage(string username,
MemoryStream ms)
{
if (HttpContext.Current.Cache["user."+username] !=
null)
{
System.Collections.Queue updater=
(System.Collections.Queue)HttpContext.Current.Cache["updater."+username];
if
( updater == null )
{
updater= new System.Collections.Queue();
HttpContext.Current.Cache.Insert("updater."+username, updater, new
CacheDependency(null,new string[]{"user."+username}));
updater=
(System.Collections.Queue)HttpContext.Current.Cache["updater."+username];
}

if (updater.Count <>
///
///

/// ///
public static
MemoryStream NextImage(string username)
{
if
(HttpContext.Current.Cache["user."+username] != null)
{
System.Collections.Queue updater=
(System.Collections.Queue)HttpContext.Current.Cache["updater."+username];
if
( updater == null ) return null;
if (updater.Count ==1) return
(MemoryStream)updater.Peek();

return (MemoryStream) updater.Dequeue();
}
return null;

}

private static void
RemovedCallback(string k, object v,CacheItemRemovedReason r)
{
if
(r==CacheItemRemovedReason.Expired r==CacheItemRemovedReason.Removed )
{
string username = k.Substring(k.IndexOf('.')+1);
HttpContext.Current.Cache.Remove("updater."+username);
}

}
}
}

[SoapDocumentMethod(OneWay=true)]
[WebMethod]
public
void SaveImage()
{
// UsernameToken user =
GetUsernameToken((RequestSoapContext.Current));
// string sessionvalue =
user.Principal.Identity.Name+"_save";
//
// Object _countobj =
Context.Cache[sessionvalue];
// int count;
// if (_countobj == null)
count = 0;
// else
// {
// count = (Int32) _countobj;
// count =
(count+1)%Globals.imageperuser;
// }
// Image bmp =null;
//
//
bmp = new Bitmap(RequestSoapContext.Current.Attachments["imagefile"].Stream);
// string username = user.Principal.Identity.Name;
// string
userimagepath = imagepath+"\\"+username+"image_"+count.ToString()+".png";
//
bmp.Save(userimagepath, System.Drawing.Imaging.ImageFormat.Png);
//
SessionManager smanager = (SessionManager) Context.Cache["_smanager"];
//
smanager.SetExpirationTime(username);
// Context.Cache[sessionvalue] =
count;

UsernameToken user =
GetUsernameToken((RequestSoapContext.Current));
string username =
user.Principal.Identity.Name;
CacheHelper.InsertImage(username,(System.IO.MemoryStream)RequestSoapContext.Current.Attachments["imagefile"].Stream);

}

[WebMethod]
public void RetriveImageCached(string
host, int sessionid)
{
UsernameToken user =
GetUsernameToken((RequestSoapContext.Current));

if
(ValidUserSession(host,sessionid) &&
IsUsernameToken((RequestSoapContext.Current)))
{
// string userimagepath
= GetNewImage(user.Principal.Identity.Name,host);
//
// SoapContext
respContext = ResponseSoapContext.Current;
// DimeAttachment dimeAttach =
new DimeAttachment("image/jpeg",TypeFormat.MediaType,userimagepath);
//
// respContext.Attachments.Add(dimeAttach);

string username =
user.Principal.Identity.Name ;
SoapContext respContext =
ResponseSoapContext.Current;
DimeAttachment dimeAttach = new
DimeAttachment("image/gif",TypeFormat.MediaType,CacheHelper.NextImage(host));
respContext.Attachments.Add(dimeAttach);
}

}
}

This post originally appeared on an external website

This discussion is closed to new replies.