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>


 
 
 

Wednesday, December 31, 2014

Easy Way to upload a PDF file to SharePoint Document Library

A proven solution to copy a PDF document to SharePoint document library is to use the CopyIntoItems web service. You will never regret your approach if you follow this path.
 
Here are the summary of steps for your coding..
 
1. convert the document into byte for easy transmission
 
                    FileStream fStream = File.OpenRead(fileName);
                    byte[] contents = new byte[fStream.Length];
                    fStream.Read(contents, 0, (int)fStream.Length);
                    fStream.Close();
 
2. Add the web service reference of your SharePoint Server.
 
3. Create a Proxy of your SharePoint service
 
SharePointServerReference.CopySoapClient copy = new SharePointServerReference.CopySoapClient();
 
4. Call the final CopyIntoItems () service
 
uint result = copy.CopyIntoItems(fileName,
                                new string[] { strDestinationUrl },
                                myFieldInfoArray,
                                contents,
                                out myCopyResultArray);
 
where
filename is the name of actual pdf file.
strDestinationUrl  is the location of the document library where file will be uploaded.
myFieldInfoArray can be defined as follows:

                copy.FieldInformation fields = new copy.FieldInformation();
                copy.FieldInformation[] myFieldInfoArray = { fields };

 
 myCopyResultArray can be defined as follows:

copy.CopyResult myCopyResult1 = new copy.CopyResult();
                copy.CopyResult[] myCopyResultArray = { myCopyResult1 };


Please find below url from MSDN for this entire activity for reference :
http://msdn.microsoft.com/en-us/library/copy.copy.copyintoitems(v=office.12).aspx
 

Tuesday, December 30, 2014

Creating GUID from CommandLine

We know that we can create a GUID easily from C# code by just executing Guid.NewGuid() code. This is one of the easiest way. But quite a few times we want GUID for some data manipulation in excel sheet or in Access database. Also many a times we want GUID to be generated in batch programs in that case uuidgen.exe can be a great help.

You can find the uuidgen.exe in the below folder.

C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\uuidgen.exe


 

Monday, December 29, 2014

Encrypt Web.Config specific section


A very cool feature of ASPNET_REGIIS tool is to encrypt and decrypt config sections of Web.Config file.

Here is one example for your reference.

encrypt:
aspnet_regiis -pef [sectionName] "D:\inetpub\wwwroot\" -prov DataProtectionConfigurationProvider

decrypt:
aspnet_regiis -pdf [sectionName] "D:\inetpub\wwwroot\" -prov DataProtectionConfigurationProvider

Example :

aspnet_regiis -pef "system.web/identity" D:\inetpub\wwwroot\thresholdui -prov DataProtectionConfigurationProvider