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()

Here I’m providing short examples with ui rules only. I’ll assume you have some knowledge in URL Rewrite otherwise I’ll suggest you to read official documentation at http://www.iis.net/learn/extensions/url-rewrite-module/using-the-url-rewrite-module

I’m listing below some examples in the form of questions and how to solve them

Outbound rules

Note: in some of the outbound rules precondition responseHtml1 configured as below

1) Add custom script at the end of the response html

2) Add custom script at the beginning of response html

3) Rewrite subdomain with different domain with same URL path and query

Example:  I want to rewrite

https://domain1.rajbandi.dev/examples/urlrewrite/domain1.aspx

as

https://domain2.rajbandi.dev/examples/urlrewrite/domain1.aspx

Only domain part is changing, path and query is same.

4) Modify redirect location domain to a different domain with same path and query only when particular words exists.

For example:

Modify response header location if path starting with accounts or customer to different domain

http://www.rajbandi.dev/account/login.aspx  or http://www.rajbandi.dev/customer/login.aspx

to

http://www.rajbandi.com/account/login.aspx or http://www.rajbandi.com/customer/login.aspx

5) Remove body onload function in response html

Actual

;

Expected

;

6) Find all the links with some text and prevent click on them

Actual

Click here to visit rajbandi.dev;

Expected

Click here to visit rajbandi.dev

Alternatively, you can attach some javascript(preventDefault or something) to href

I’ll update more examples asap.

Recently I was working on a portable class library(PCL) example in VS2012 to create a proxy class for an external asmx soap service with return types DataTable and DataSet. The easiest way to create a proxy class to add a service reference. In my case, it failed. The add service reference generated code  contains XmlElement and failed to generate response messages with DataTable and DataSet. VS2012 gives a warning for Xml Element.

The alternative way to add service reference is to create a HttpWebRequest to asmx service wsdl and use System.ServiceModel.Description.ServiceDescription to load response xml and parse WSDL. This is one too not supported in PCL.

Because of these limitations, What I think a work around for this is to create a custom wsdl parser or manually construct soap envelopes and parse responses but its not an easiest way to do it and a time consuming.

Some of the limitations of PCL are

1) PCL doesn’t support System.Xml.XmlElement, instead use System.Xml.Linq.XElement

2) PCL doesn’t support System.Data.

3) PCL doesn’t support some of the member classes of System.ServiceModel.Description for example ServiceDescription, WSDLImporter etc.

My project target settings as below

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.

Sharepoint 2010 provides a custom tag ScriptLink to register script files in a webpart. This can also be done using simple html script tag but using ScriptLink ensures all the sharepoint script namespaces are available for your custom script.

All the scripts that are to be registered should be placed in Layouts/ProjectName folder of your project. By default, when you create a project Layouts folder will not be added.

To add it, right click on your project –> add –> SharePoint “Layouts” Mapped Folder

A default folder with project name will be automatically created under Layouts folder.

Add your custom script files in Layouts/ProjectName/Scripts folder (create Scripts folder if not exist, it can be any name like JS etc.).

Add your code in the script file, here in this example I have added some alert code which is opened by clicking on web part button ‘click here’

Now add ScriptLink tag in your visual web part (i,e. .ascx control)
If you want to do the same in a standard web part, add the below code in OnPreRender method

ScriptLink.register(page,”RajWebPartsDemo/Scripts/RajDemoScript.js”, false);

Deploy your solution and add a your webpart in a page (say home page).

On clicking button ‘Click Here’ an alert is displayed.