How to Read Binary Documents (in base64 binary format) by ASP.NET Web Service

Add new web service in your ASP.NET web application.

Adding a web service will create two file in your web application:

1)      ASMX FILE(For example WebService.asmx)

2)      CS FILE(in App_Code folder, like WebService.cs)

Create web method inside it as follow.  It takes document name as parameter and returns array of byte (binary data).

 

[WebMethod]

public Byte[] ReadDocument(string strDocumentName)

{

string strdocPath;

strdocPath = “D:\\TESTDIR1\\TESTDIR2″ + strDocumentName;

FileStream objfilestream = new FileStream(strdocPath,FileMode.Open,FileAccess.Read);

int docLen = (int)objfilestream.Length;

Byte[] arrDocumentContents  = new Byte[docLen];

objfilestream.Read(arrDocumentContents,0,len);

objfilestream.Close();

return arrDocumentContents;

}

 

Above example reads file from a physical path on a system. You can also use Server.MapPath() for specifying virtual directory.

You can call webservice by using following like URL

http://yourdomain / WebService.asmx/ ReadDocument? strDocumentName=test.gif

 

Web service will return base64 binary data as follow:

<?xml version=”1.0″ encoding=”utf-8″?>

<base64Binary xmlns=”http://tempuri.org/”>R0lGODlhCAAFAIABAMaAgP///yH5BAEAAAEALAAAAAAIAAUAAAIKBBKGebzqoJKtAAA7</base64Binary&gt;


Advertisements

DATA CACHING in asp.net with cache class

ASP.Net caching feature stores objects in memory.

By using instance of ‘Cache’ class, we can use this feature. Internally key/value pairs

Unlike sessions, application cache is global (application wide) and every user who accesses that application can access the value in the cache.

Syntax:

Store data in cache

HttpContext.Current.Cache.Insert(key, data)

Retrieve data from cache

HttpContext.Current.Cache(“keyname”)

Clear all cached items

ClearCache(“”)

See one example:

If you set following page load function, then each time you refresh page, you will see same time value each time.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If IsNothing(HttpContext.Current.Cache(“mykey”)) Then

HttpContext.Current.Cache.Insert(“mykey”, “This message was stored in cache at : ” & Date.Now)

End If

Response.Write(HttpContext.Current.Cache(“mykey”))

End Sub

Advantages to your web application by using ASP.NET Data Caching :

With ASP.Net Caching, you have to add just few line of code will reduce database access from your application.

As web server will send fewer requests to database Performance of web application will be improved. (As in many cases redundant data will be retrieved from ASP.NET Cache)

Quick responding web application, gives more satisfaction to end user, while spending time on your site.

multiple jquery.ajax request on same page and server variable for tracking status of long running process

Once i was stuck with a process(long running for loop) at server side in asp.net, hence i thought to change code in such a way that some how i got intimation about how much work that process has done.

I have decided to make two pages,
one page when called starts a long running process,
And, Second page i call frequently from java script(with jQuery.ajax()), and that page gives me status (% of work done) of process start by first page.

Following is two JavaScript functions,

That uses JQuery’s Ajax request,

First function is intended to update page with some kind of intimation to user (like 30% work has been done).

function getFrequentUpdate() {

jQuery.ajax({
url: “getFrequentUpdate.aspx?” + “tmp=” + Math.random() * 1000,
async: true,
type: ‘GET’,
cache: false,
success: function(msg) {
jQuery(“#divMsg”).html(” Current Progress is: ” + msg);

var runtimeProgress = (parseInt(msg) * 100) / parseInt(jQuery(“#hdTotalObject”).val());
runtimeProgress = Math.ceil(parseFloat(runtimeProgress));
runtimeProgress = parseFloat(runtimeProgress) * 10;

jQuery(“#divProgress”).css(‘width’, runtimeProgress + ‘px’);
}
});

}

Second function calls a page that starts a long running process.


function startLongRunningProcess() {
getFrequentUpdate();
myintval = setInterval('getFrequentUpdate()', myDelay);

jQuery.ajax({
url: “someProcess.aspx?” + “tmp=” + Math.random() * 1000,
async: true,
type: ‘GET’,
cache: false,
success: function(msg) {

window.clearInterval(myintval);
jQuery(“#lblStartBackup”).html(“Process has been completed successfully.“);

}
});

}

Main challenging task is to update page with % of work long running process has done.

Here, I have first tried with using session variable, but later I came to know that somehow, when, I tried to run multiple pages together, and if they access SESSION variable, one of process was stopped, until second one has finished.

To overcome that issue, I have used a class in “App_Code” folder with STATIC VARIABLE that can be used application wide:

static public int MyStatusVariable = 0;

In my case, my long running process was updating above server variable and first Ajax function was fetching it frequently, with interval specified with in

myintval = setInterval(' getFrequentUpdate ()', 2000);

With above logic i achieved a interface as follow.

 

Other Popular posts:

Display Image in html as Binary Data with Base64 encoding

https://siddharthboraniait.wordpress.com/2011/08/16/display-imagein-html-as-binary-data-with-base64-encoding

Introduction to android,first step towards

https://siddharthboraniait.wordpress.com/2011/07/18/know-andriod-introduction-to-andriod

 

 

Web development small tips

Single quote in java script, may result in error

In Javascript,when using or concatenating string, use it with double quotes.
Or it may generate error.

Recommanded:
var str="Some String" + document.getElementById("txtName").value;

Should be avoid:
var str='Some String' + document.getElementById("txtName").value;


To overcome Date format related error, in .Net, with CompareValidator validation control
You can, specify culture in web config file.


Put Share Button on your website with ADD THIS

Go to http://www.addthis.com site, and it will ask you button layout you want to Choose.
And that site will display code snippet, which will contain one SCRIPT tag and HTML lines.

So you have to add script line in your page and put ‘html’ tags at place where you want to display share icons.


To set content in tinyMCE editor box by using javascript
var editorInstance = tinyMCE.getInstanceById("ctl00_cpMain_txtCampaignDesc"); //specify clientid of textarea field
editorInstance.getBody().innerHTML = "This is dynamic text set by javascript.";

ASP.NET error BC30456: ‘CreateResourceBasedLiteralControl’ is not a member of [any file]

Recently i came across an error in asp.net web application, on a web server.

error BC30456: ‘CreateResourceBasedLiteralControl’ is not a member of [file name of master page/ control file].

I have tried to find error in many blogs and reputed site, but it did not helped.

Finally, it is solved by just Deleting the directory in which error was throwing. and again same directory uploaded to server and error gone immediately.

I think it was just error due to temporary files, or reference not updated to recent compiled version.

Hope, this helps some one facing same error.

Siddharth borania’s profile on Google

jQuery plugin for showing charecter counter – by borania siddharth

May times we have faced requirement to display character counter near text areas. We can do it by using java script also.But, using jquery it gives easy re usability of logic.

here is one small jquery plugin to display character counter.

First you need to include java script file references.
and Write HTML as:


key thing is jquery code snippet after textarea you want to use, as shown below:


var jq=jQuery.noConflict();
jq("#txtAddress").dicCharCount(50,"spanAddress");

and,Plug in handling will be done by following jquery code (which you can write in separate .js file):

var jq=jQuery.noConflict();
(
function(jq)
{
jq.fn.dicCharCount=function(charLimit,lbl)
{
jq("#" + lbl).html("Charecters left : " + charLimit);

jq(this).keyup(function()
{
var tmplen=jq(this).val();
var diff=parseInt(charLimit)-parseInt(tmplen.length);
if(diff>=0)
{
jq("#" + lbl).html("Charecters left : " + diff);
}
else
{
var d=jq(this).val().substring(0,charLimit);
jq(this).val(d);
}

});

//extra
jq(this).click(boxClick);

};

boxClick= function(parent,obj,callBack)
{
alert('text box clicked!');
}
}
)(jQuery);

It will look like as follow:

online video conversion(flv conversion) using asp.net(web development) – borania siddharth

Audio and Video files are becoming important part of web sites, now a days.

Many social networking and job portal sites are built to offer audio/video upload and play functionality.

These videos are then played in client’s browsers.

Playing video in client’s machine is preferred with FLV format rather than any other(like .wmv).

And same technology is applied for audio playing.

and as there is different format files may be uploaded by user, always there is question to weather restricting users for ONLY uploading FLV files or giving them FLEXIBILITY to upload file in their desired(available) format, and online convert it into FLV.

So, here i have present small code snippet, to outline how FLEXIBILITY may be given to user for uploading any audio/video format, and same time its playable by website.

string strinp;
strinp = Server.MapPath(“~/test1.wmv”).ToString();

string strop;
strop = Server.MapPath(“~/test2.flv”);

Process p;
try
{
ProcessStartInfo info = new ProcessStartInfo(Server.MapPath(“~/ffmpeg.exe”));

info.Arguments = “-i \”” + strinp + “\” \”” + strop + “\””;

p = Process.Start(info);
p.Start();
p.Kill();
}
catch (Exception ex)
{
//catch error here
p.Kill();
}

Any Suggestions are welcome.

-By Siddharth Borania from Dhanashree Incorporation