Saturday, April 20, 2013

Running .net application as an Administrator using UAC

You probably are already familiar with the whole new concept of UAC(User Access Control) security model that Microsoft introduced since windows Vista. This security model restricts the application from making system level changes in your application and requires any application that need such kind of access control to go through UAC dialog for user's consent. User can then authorize or simply cancel the application execution.


My purpose here is not to go in-depth regarding UAC, however as an application developer building a desktop app that requires administrative privilage to make system changes, you and I both are interested in popping up this UAC dialog to run the application with Administrator privilege so that your application do not fail with security reason. Please remember that if your application do not perform any Administrative task then do not show this dialog for fun as It might irritate your user and this is something you always need to be careful about as a developer.

The solution is rather simple and shorter than all the bullshits that I bothered you with, above.

  1. Add "Application Manifest File" in your application using Add New Item Dialog.
  2. Find <requestedExecutionLevel /> element inside the manifest file. This is the only element in the whole manifest file we are interested in right now.
  3. If you have gotten this far and have properly read the comment inside the manifest file then you already know what to do next.
  4. If not change/add level attribute in this element to "requireAdministrator". By default it is "asInvoker".
  5. Now compile your application and run the exe inside "bin" folder. 
  6. After the changes your <requestedExecutionLevel /> element should look something like this <requestedExecutionLevel level="asInvoker" uiAccess="false" />
If you are looking for a demo then you can download the sample code from here.



Saturday, April 6, 2013

Sending office document content from Office App to server side

So here goes another post for App for Office Api. This post will focus on providing you with some basic knowledge on sending the whole document from your app to your server side code.
The sample I tried on is built on Asp.net MVC4, but it necessarily doesn't mean that this thing is possible on Asp.net or Asp.net MVC only. Any server side language that can handle ajax calls and can convert base 64 string to byte array can do :)

Another thing to note down here is that this sample will use one of my javascript library that I named it "OffQuery". This library is just a wrapper on top of Office.js javascript api aiming at hiding most of the complexities for simple functionalities. It also supports jquery's promise giving you a more flexible and jquery way to handle Office.js asynchronous calls. For more on it I'd suggest visiting jquery site and get your hands dirty with couple of samples yourself.  "OffQuery" is still in it's infancy and hope to post some more examples , if I'm able to continue on it. But today let's focus on learning how can we send the whole office document from your app to server side and write on your disk.

I won't be going in detail on setting up your project for this tutorial, which obviously varies depending on the server side language you are familiar with. However in this sample I'll show you a way to get your document content using OffQuery and then a simple Mvc controller action that handles the ajax calls and write the content to disk. If you are an Asp.net MVC developer and want to convert your Asp.net MVC project to App for office project then you can visit my previous posts "Convert existing web project to office app using Visual Studio 2012" and "Convert App For Office Project to Asp.net MVC Project Type"

For this tutorial make sure you include MicrosoftAjax.js, Office.js, Jquery OffQuery.js. For jquery you can download the latest file from jquery site and for OffQuery you can visit https://github.com/ishwormali/OffQuery.
After that write javascript to handle Office.initialize function. Please make sure you do this before calling any of the Office or OffQuery api's







Next write your javascript to get the document content in byte array.

function saveContent() {

    $.when(OffQuery.getContent({ sliceSize: 50000 }, function (j, data, result, file, opt) {
        var temp = data;

    })).then(function (finalByteArray, file, opt) {
        //this function is called at the end.
        //FullData contains byte array.
        //file is the file object of Office.js
        //opt is the option supplied at the very beginning when calling OffQuery.getContent() function.
        var fileContent = OSF.OUtil.encodeBase64(finalByteArray); //encode the byte array into base64 string.
        sendFileMethod(fileContent)
     

    }).progress(function(j, chunkOfData, result, file, opt){
        //handle the progress here.
    });
}



This function basically leverages the jquery's new inbuilt asynchronous api $.when. The anonymous function provided in then function will be called after the asynchronous call to getContent function is complete. If you have been using office.js then you probably have noted that it's very simple to get the whole content at once using OffQuery rather than using the Office.context.document.getFileAsync() function, providing your own implementation to handle the recursive calls and all. The OSF.OUtil.encodeBase64() function converts your byte array to Base64 string ready for sending it to your server.

function sendFileMethod(fileContent) {

    $.ajax({
        url: saveContentUrl,
        data: { contentByte: fileContent },
        type: 'POST'


    }).then(function (a, b, c) {
        var tempa = a;
        var tempb = b;

    });
}


sendFileMethod doesn't do much than sending the content to server using jquery's ajax call.

public JsonResult SaveContent(string contentByte)
        {
         
            var byteArr2 =Convert.FromBase64String(contentByte);//convert the base64 string to byte array
            using (var fileStream = System.IO.File.OpenWrite(@"c:\tempfolder\tempfile.docx")) //open a file
            {
                fileStream.Write(byteArr2, 0, byteArr2.Length); //write the byte array as content in the file
            }

            return Json(new { success=true});
         
        }




The server side code is self explanatory. It simply converts the base64 string to byte array, opens a .docx file on disk and then writes the byte array. The code provided is in Asp.net MVC.

Download the sample code from here.