Thursday, October 15, 2015

Data Access Class for .net Apps


A generic data access class for .net apps.



    public class DataAccessClient
    {      
        public DataSet ExecuteStoredProc(string StoredPorc,string ConString,SqlParameter[] Parameters)
        {                     
            DataSet dsResult = new DataSet();
            using (SqlConnection sqlCon = new SqlConnection(ConString))
            {                             
                try
                {                  
                    sqlCon.Open();
                    SqlCommand sqlCmd = sqlCon.CreateCommand();
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.CommandText = StoredPorc;
                    sqlCmd.CommandTimeout = 1200;
                    foreach (SqlParameter Param in Parameters)
                    {
                        sqlCmd.Parameters.Add(Param);
                    }                  
                    SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
                    sqlDa.Fill(dsResult);
                    return dsResult;
                }
                catch (Exception ex)
                {
                    Logger.TextLogger log = new Logger.TextLogger();
                    log.WriteLog(ex.ToString());
                    //return null;
                    throw;
                }
                finally
                {
                    dsResult.Dispose();
                    sqlCon.Close();
                    sqlCon.Dispose();
                }
            }
        }             
        public DataSet ExecuteQuery(string ConString, string Query)
        {
            DataSet dsResult = new DataSet();
            using (SqlConnection sqlCon = new SqlConnection(ConString))
            {
                try
                {
                    sqlCon.Open();
                    using (SqlCommand sqlCmd = sqlCon.CreateCommand())
                    {
                        sqlCmd.CommandType = CommandType.Text;
                        sqlCmd.CommandText = Query;
                        SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
                        sqlDa.Fill(dsResult);
                    }
                    return dsResult;
                }
                catch (Exception ex)
                {
                    Logger.TextLogger log = new Logger.TextLogger();
                    log.WriteLog(ex.ToString());
                   // return null;
                    throw;
                }
                finally
                {
                    dsResult.Dispose();
                    sqlCon.Close();
                    sqlCon.Dispose();
                }
            }
        }
        public bool ExecuteInsertQuery(string Query,string ConnectionString)
        {
            bool isDataInserted = false;
            int insertedRows = 0;
            using (SqlConnection sqlCon = new SqlConnection(ConnectionString))
            {
                try
                {
                    sqlCon.Open();
                    using (SqlCommand sqlCmd = sqlCon.CreateCommand())
                    {
                        sqlCmd.CommandType = CommandType.Text;
                        sqlCmd.CommandText = Query;
                        sqlCmd.CommandTimeout = 1200;
                        insertedRows = sqlCmd.ExecuteNonQuery();
                    }
                    if (insertedRows > 0)
                    {
                        isDataInserted = true;
                    }
                    return isDataInserted;
                }
                catch (Exception ex)
                {
                    Logger.TextLogger log = new Logger.TextLogger();
                    log.WriteLog(ex.ToString());
                   // return false;
                    throw;
                }
                finally
                {
                    sqlCon.Close();
                    sqlCon.Dispose();
                }
            }          
        }
      
        public List<T> ConvertDtToList<T>(DataSet ds)
        {
            DataTable dt = ds.Tables[0];
            List<T> CustomerListData = new List<T>();
            foreach (DataRow row in dt.Rows)
            {
                T item = GetItem<T>(row);
                CustomerListData.Add(item);
            }
            return CustomerListData;
        }
        public T GetItem<T>(DataRow dr)
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();
            foreach (DataColumn column in dr.Table.Columns)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name == column.ColumnName)
                        pro.SetValue(obj, dr[column.ColumnName], null);
                    else
                        continue;
                }
            }
            return obj;
        }      
    }

To call any method


                DataAccessClient client = new DataAccessClient();
                SqlParameter[] Parameters = new SqlParameter[2];
                SqlParameter param1 = new SqlParameter("@Param1", SqlDbType.VarChar, 50);
                param1.Value = value1;
                SqlParameter param2 = new SqlParameter("@Param2", SqlDbType.VarChar, 50);
                ParentHierUniqueCode.Value = value2;
                Parameters[0] = hierType;
                Parameters[1] = ParentHierUniqueCode;
   
                string spname = "Stored Proc Name";
                ds = client.ExecuteStoredProc(spname, connectionstring, Parameters);
 

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>