A WinRT component can used to include some common code along with embedded resources that can be reused in store app irrespective of language in which it is developed like C#, JavaScript etc.
In this article, I’ll explain how to read a WinRT component embedded resource file from JavaScript app. App reads content from embedded resource and replace your page content with new content.

1. Create a WinRT component

1. Create a new windows store apps class library or WinRT component say with name ‘ExampleLib’.
WinRT component

2. If it is a class library, open its properties and change output to WinRT component.

Class library settings

3. Add a text file say ‘Data.txt’ in the project root folder with some text and change to embedded resource from its properties.

Embedded resource

4. Add a new C# code file ResHelper.cs in the project root folder and add the following code in that

using System;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Windows.Foundation;

namespace ExampleLib
{
    public  sealed class ResHelper
    {
       static async Task<string> ReadResourceAsync(Assembly assembly, string resource)
        {
            string xml;
            using (var stream = assembly.GetManifestResourceStream(resource))
            {
                    using (var reader = new StreamReader(stream))
                    {
                        xml = await reader.ReadToEndAsync();
                    }
            }
            return xml;
        }
        public static IAsyncOperation GetConfiguration(string fileName)
        {
            return (ReadResourceAsync(typeof(ResHelper).GetTypeInfo().Assembly, fileName)).AsAsyncOperation();
        }

    }
}

}

2. Create a windows store app in javascript

1. Create a new windows store app under language javascript (blank app is fine)
2. Add reference to ExampleLib
3. Open default.js and add the following code in activated.

args.setPromise(WinJS.UI.processAll().then(function () {

//call getConfiguration method with fully qualified
//file name (including dll name, folder path if any and file name)
ExampleLib.ResHelper.getConfiguration("ExampleLib.Data.txt")
.done(function (result) {
document.body.innerText = result;
}, function (err) {
document.body.innerText = err;
});

}));

Complete solution looks like as below

Projects

All done, deploy and run the app, now you’ll see embedded resource content as your main page content. Try with invalid file name; you’ll see an error message

you can download solution from here ExampleApp

Aspose words for .Net doesn’t support word field skipif to skip some merge fields between tablestart and tableend i,e skipping rows based on some condition.

Here, I’ll explain how to include skipif common functionality  with custom merge field in the word document.
The custom skipif merge field syntax should be as below

skipif:tablename:condition  

where condition must be a valid t-sql where clause and use ~ for spaces if any. Skipif can be used at any position and for any table. If you use multiple skipif’s for the same table, the last skipif will be considered ignoring all the previous skipif’s.

Ex:

if the table name is productstable (provided with tablestart: and tableend:)

skipif:productstable:price>0   (or in alt f9 view, { MERGEFIELD skipif:productstable:price>0 } )

skipif:productstable:price~in~(100,200,300,400)

1) Define a method ApplyFilters that takes two parameters, data set and aspose document.


DataSet ApplyFilters(DataSet ds, Document doc)
        {
            var fieldNames = doc.MailMerge.GetFieldNames().ToList();
            var newDs = ds.Clone();
            var skipIfs = fieldNames.Where(x => x.ToLower().StartsWith("skipif"));
            if (skipIfs.Any())
            {
                foreach (DataTable table in ds.Tables)
                {
                    foreach (var s in skipIfs)
                    {
                        var sp = s.Split(":".ToCharArray());
                        if (sp.Length > 2)
                        {
                            var where = sp[2];
                            if (!String.IsNullOrWhiteSpace(where))
                            {
                                DataTable newTable;
                                where = where.Replace("~", " ");
                                var skipRows = table.Select(where);
                                var rows = table.AsEnumerable().Except(skipRows);
                                var dataRows = rows as List ?? rows.ToList();
                                if (dataRows.Any())
                                {
                                    newTable = dataRows.CopyToDataTable();
                                }
                                else
                                {
                                    table.Clear();
                                    newTable = table;
                                }
                                newTable.TableName = table.TableName;
                                newDs.Tables.Remove(newTable.TableName);
                                newDs.Tables.Add(newTable);
                            }
                        }
                    }
                }
            }
            return newDs;
        }

2) Define a class that inherits IFieldMergingCallback and implement FieldMerging method


public class HandleSkipIfField : IFieldMergingCallback
    {
        void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
        {
            if (!String.IsNullOrWhiteSpace(args.TableName))
            {
                var fieldName = args.FieldName;
                if(fieldName.ToLower().StartsWith("skipif"))
                {
                    args.Text = "";
                }
            }
        }

        void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
        {
            // Do Nothing
        }
    }

3) Add below code before firing executewithregions


//Add below 2 lines before executewithregions
doc.MailMerge.FieldMergingCallback = new HandleSkipIfField();
var dataSource = ApplyFilters(ds, doc);


doc.MailMerge.ExecuteWithRegions(dataSource);

Using async and await in windows 8 store apps bit tricky sometimes. Here I’m listing below some of the do’s and don’ts when working with async and await.

1) Always use void type for  top level async method. Don’t use return type Task for top level async method i,e. the method called by some app handler  for example click, onnavigatedfrom, onloaded etc.  This may not be same for console apps, where the top level method should always return Task in order to put wait instruction from Main method. Using same Task.Wait() in store apps blocks the UI thread and enters into deadlock.

   void Page_Loaded(object sender, RoutedEventArgs e)
        {
              TopLevelMethod();
	}
  
public static async void TopLevelMethod()
{
     var response = await PostAsync(url, content);
}

Without any top level async method

 async void Button1_Click( object sender, RoutedEventArgs e)
{
 var response = await PostAsync(url, content);
}

2) To update UI before and/or after async operation, include update code in the async method but not in its caller for example showing/hiding progress ring or some alert after receiving response etc.

3) If your top level async method is called by timer event or some other scheduler  event and it is accessing any UI related stuff, then use Dispatcher.RunAsync to run that method uses same thread context.

Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, TopLevelMethod);

4)  Utilize features of newly introduced simplified HttpClient class for all asynchronous get and post methods. You can use httpwebrequest async methods but same can be achieved with lesser code using HttpClient.

HttpClient

Example using httpclient post async (fewer lines )

    
public static async Task PostAsync(string url, string postContent)
        {
            using (var httpClient = new HttpClient())
            {
                var httpContent = new StringContent(postContent, Encoding.UTF8, "text/xml");

                using (var response = await httpClient.PostAsync(url, httpContent))
                {
                    response.EnsureSuccessStatusCode();

                    string content = await response.Content.ReadAsStringAsync();

                    return content;
                }
            }
        }

5)  Use always async and await for all anything that reads/writes from/to media(disk i/o etc.).

Example:

 
var file = await Package.Current.InstalledLocation.GetFileAsync("Data\\Groups.txt");
var result = await  FileIO.ReadTextAsync(file);
var xml = await reader.ReadToEndAsync()

I love these store apps. The most interesting and promising feature is integration of html, css technologies as well as support for .Net languages like C# etc.

Windows 8 store apps are nothing but those acquired from Windows store and are different from desktop applications. All the store apps runs in a restricted app container.

Html/Jscript based apps mainly aimed at jscript/html developers. These apps uses WinJS toolkit and WinRT(windows run time). WinJS toolkit provides JS classes, helpers, patterns, html implementation of controls etc where as WinRT javascript api provides api to access platform features.

Windows 8 provides WinRT api to access platform core features like networking, storage, media, graphics etc. This api can be accessed from Javascript, C#, C++ and VB.

Example

Windows.ApplicationModel

Windows.UI

I’m a web developer and is flexible with html/jscript, xaml/c# apps. I choose xaml/c# if advanced functionality and behaviour are required in my app. Html/jscript apps are simple and quick to develop(you just need a html and jscript files).

 

In this post, I’ll explain how to pass a model with dynamic objects to a view.

If you are new to C# 4 features like dynamic objects, ExpandoObject etc I suggest to visit below links to get familliar with the concepts.

http://msdn.microsoft.com/en-us/library/dd264741.aspx

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

By using dynamic and ExpandoObject, you can pass a runtime object with some dynamic properties to a view and use them efficiently.

Controller Action
——————
——————

 public ActionResult DisplayDynamic()
{
      dynamic obj = new ExpandoObject();
      obj.FirstName = "Raj";
      obj.LastName = "Bandi";
      obj.Country = "Australia";

      return View("DynamicView", obj);
}

DynamicView.cshtml
————————
————————
//here I’m creating a simple view without any layout just to explain how to use the object

@model dynamic

  1. First Name: @Model.FirstName
  2. Last Name: @Model.LastName
  3. Country: @Model.Country

Demo
————–
—————
http://demos.rajbandi.dev/mvc3/home/dynamic

Source Code
————-
————–

http://code.rajbandi.dev/examples/mvc3/mvc3source.zip

In this post, I’ll explain how to post form data without refreshing a page using JQuery ajax and JSON.

Here, I assume a model is used to render form(form elements names same as model properties).

**Step 1:**

Define an action that takes Model as parameter and returns a json object along with attribute HttpPost(simple way)

[HttpPost]
public JsonResult PostMethod(YourModelType m)
{
   // Do something with the model, all the form elements posted are available in the model

   //return json string. Json method that serializes any C# object to json format.
   return Json(your object, JsonRequestBehavior.AllowGet);
}

**Step 2:**

Add javascript function to post data

function PostData(form)
{
  //use only if you wish to validate the form before posting, requires JQuery.validate plugin
 if (!$(form).valid()) {

        return;
    }

    // use $.post, $.ajax can also be used but with some additional parameters
    // 1st parameter is form action to submit, 2nd parameter serialized form data
    // 3rd parameter is the function to be called after successful post and return value
    $.post($(form).attr('action'), $(form).serialize(), function (data) {

           alert('Posted successfully and received data...'+data);


    });
}

Call PostData function to post data on any element action i,e. click etc.

In Sharepoint, SP.UI script namespace provides required methods and classes for showing different types of dialogs.

The following are the list of various dialog methods available under class ModalDialog

1) showModalDialog: To show a modal dialog with some options.

SP.UI.ModalDialog.showModalDialog(options);

2) ShowPopupDialog :

To show a modal dialog with an url and without any options.

3) showWaitScreenSize : this one is used to show a wait screen dialog with a close button

SP.UI.ModalDialog.showWaitScreenSize(title,message,callback,height,width);

for more information on options visit http://msdn.microsoft.com/en-us/library/ff411803.aspx

4) showWaitScreenWithNoClose:

To show a wait screen without any cancel button.

SP.UI.ModalDialog.showWaitScreenWithNoClose(title,message,height,width);

5) commonModalDialogOpen(url,options,callback,args)

To show a modal dialog with url, options, callback, parameters.

SP.UI.ModalDialog.commonModalDialogOpen(url, options, callback, parameters);

ModalDialog class provides other non dialog methods

1) RefreshPage:

SP.UI.ModalDialog.RefreshPage(dialogResult);

2) close:
To close a dialog.
SP.UI.ModalDialog.close(dialogResult);

for showModalDialog and commonModalDialog, there are two ways to pass the options

//generic way

var options = { title: ‘Dialog1’ .height: 300 ,width:300
,url : ‘http://www.rajbandi.dev’
}

//with DialogOptions class

var options = SP.UI.$create_DialogOptions();
options.title = ‘Dialog1’;
options.height = 300;
options.width=300;
options.url = ‘http://www.rajbandi.dev’;

You can also display html string instead of url but have to do in indirect way. Options html property takes a DOM element as an input. When html and url properties are provided, url takes precedence.

var div = document.createElement('div');
div.innerHTML = 'Dialog html demo Dialog html takes an DOM object but not an html string';
var options = {    title: 'Dialog1',
width : 300
,height:300
,html = div
}

To refresh a page after dialog ok clicked.