Wednesday, September 30, 2015

Intel XDK - Device load function

While working on apps, many a times we need to take certain decisions when app is ready during app initialization. this can be done in init-aap.js file.

below sample code is written to add Device.Ready function to do something when app is executed.


document.addEventListener("app.Ready", app.initEvents, false) ;
document.addEventListener("intel.xdk.device.ready",function(){
    var value = intel.xdk.cache.getCookie("mobilenum");
    if(!value)
    {
        alert("no");
    }
    else
    {
        alert("yes");
        $(":mobile-pagecontainer").pagecontainer("change", "#aasReg", { reverse: false});
    }

},false);

 

Upload file on sharepoint 2013 using SharePoint REST API

Code to upload file on SharePoint using SharePoint REST API

        public int FileUploadToSharePointREST(string filePath, string libraryName, string SharepointUrl)
        {
            int posted = -1;
            string errorMessage = string.Format("Sharepoint upload failed.. for File {0} on {1}", filePath, SharepointUrl);
            try
            {
               // string libraryName = "Launch Pad Files UAT";
                byte[] binary = System.IO.File.ReadAllBytes(filePath); ;
                string fname = System.IO.Path.GetFileName(filePath);
                string result = string.Empty;
                string resourceUrl = SharepointUrl + "/_api/web/lists/getbytitle('" + libraryName + "')/RootFolder/files/add(url='" + fname + "',overwrite=true)";
                HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
                wreq.UseDefaultCredentials = true;
                string formDigest = GetFormDigest(SharepointUrl);
                wreq.Headers.Add("X-RequestDigest", formDigest);
                wreq.Method = "POST";
                wreq.Timeout = 1000000;
                wreq.Accept = "application/json; odata=verbose";
                wreq.ContentLength = binary.Length;
                using (System.IO.Stream requestStream = wreq.GetRequestStream())
                {
                    requestStream.Write(binary, 0, binary.Length);
                }
                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                if (wresp.StatusDescription == "OK")
                {
                    posted = 0;
                }
                else
                {
                    Console.Write(errorMessage);
                    Console.Write("Upload operation failed for " + filePath + ".\r\n" + "Error : " + wresp.StatusDescription);
                }              
                return posted;
            }
            catch (Exception ex)
            {
                log.WriteLog(ex.ToString()+":"+ex.StackTrace);
                log.WriteLog(errorMessage);
                return posted;
            }
        }
        public string GetFormDigest(string SharepointUrl)
        {
            string formDigest = null;
            string resourceUrl = SharepointUrl + "/_api/contextinfo";
            HttpWebRequest wreq = HttpWebRequest.Create(resourceUrl) as HttpWebRequest;
            wreq.UseDefaultCredentials = true;
            wreq.Method = "POST";
            wreq.Accept = "application/json;odata=verbose";
            wreq.ContentLength = 0;
            wreq.ContentType = "application/json";
            string result;
            WebResponse wresp = wreq.GetResponse();
            using (System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()))
            {
                result = sr.ReadToEnd();
            }
            var jss = new JavaScriptSerializer();
            var d = jss.Deserialize<dynamic>(result);
            formDigest = d["d"]["GetContextWebInformation"]["FormDigestValue"];
            return formDigest;
        }

Intel XDK - useful tips

If the screen is a full independent page, you can write the below script to load this screen from other page button click event.

af.ui.loadContent("#uib_Validate_User",false,false,"fade");
      
If the screen is a sub page, you can write the below script to load this screen from other page button click event.

$(":mobile-pagecontainer").pagecontainer("change", "#uib_Validate_User", { reverse: false});

Reading value of the Radio Button group on a button click.

var adVal = $("input:radio[id='af-radio-ad']:checked").val();
        var acVal = $("input:radio[id='af-radio-ac']:checked").val();
        if (adVal=="on")
            alert("Auto driver");
        else if(acVal=="on")
            alert("Auto customer");
        else   
        {
            $("label[id='lblNewUserMobile']").html("Please select");
           
        }

Creating a cookie in intel XDK
        var mobilenum= $("#txtMobile").val();
       
         // 1 is to expire in1 day. put -1 if you don't want cookie to expire
        intel.xdk.cache.setCookie("mobilenum",mobilenum,1);

Remove the cookie

intel.xdk.cache.removeCookie("mobilenum");

Read the Cookie

 var value = intel.xdk.cache.getCookie("mobilenum");


Getting a geocode and passing to web service on click of button

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    }
    function showPosition(position) {
        var lat =   position.coords.latitude ;
        var lang =  position.coords.longitude;
        var url = "http://localhost:62905/MarketFeed.svc/DoWork/" + lat + "/" + lang;
       
        $.ajax ({
         url: url,
         type: "GET",
         dataType: "json",
         success: function(data){ alert("Request succeeded. Data: " ); },
         error: function(xhr) { alert("Request error"); }
        });

 

WCF rest based API Web.Config

Here are the required web.config for rest based API

<system.serviceModel>

<services>

<service name="WcfService1.MarketFeed" behaviorConfiguration="serviceBehavior">

<endpoint address="" binding="webHttpBinding" contract="WcfService1.IMarketFeed" behaviorConfiguration="web"></endpoint>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="serviceBehavior">

<serviceMetadata httpGetEnabled="false"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

</behavior>

</serviceBehaviors>

<endpointBehaviors>

<behavior name="web">

<webHttp/>

</behavior>

</endpointBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

</system.serviceModel>