Monday, 28 November 2016

Setting PayPal in ionic project

No comments
Install PayPal cordova plugin from

https://github.com/paypal/PayPal-Cordova-Plugin

create service



app.factory('PaypalService', ['$q', '$ionicPlatform', 'shopSettings', '$filter', '$timeout','RequestData', function ($q, $ionicPlatform, shopSettings, $filter, $timeout,RequestData) {
    debugger
    var init_defer;
    /**
     * Service object
     * @type object
     */
    var service = {
        initPaymentUI: initPaymentUI,
        createPayment: createPayment,
        configuration: configuration,
        onPayPalMobileInit: onPayPalMobileInit,
        makePayment: makePayment
    };
    /**
     * @ngdoc method
     * @name initPaymentUI
     * @methodOf app.PaypalService
     * @description
     * Inits the payapl ui with certain envs.
     *
     *
     * @returns {object} Promise paypal ui init done
     */
    function initPaymentUI() {
        init_defer = $q.defer();
        $ionicPlatform.ready().then(function () {
            debugger
                var promisePost = RequestData.GetPaypalCredential();
                promisePost.then(function (data) {
                debugger
                    var clientIDs = {
                        "PayPalEnvironmentSandbox": data.data.PayPalEnvironmentSandbox,
                        "PayPalEnvironmentProduction": data.data.PayPalEnvironmentProduction
                    };
                    PayPalMobile.init(clientIDs, indexApp.onPayPalMobileInit());
                });        
        });
        return init_defer.promise;
    }
    /**
     * @ngdoc method
     * @name createPayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Creates a paypal payment object
     *
     *
     * @returns {object} PayPalPaymentObject
     */
    function createPayment(total, name) {              
        // "Sale  == >  immediate payment
        // "Auth" for payment authorization only, to be captured separately at a later time.
        // "Order" for taking an order, with authorization and capture to be done separately at a later time.
        var payment = new PayPalPayment("" + total, "EUR", "" + name, "Sale");
        return payment;
    }
    /**
     * @ngdoc method
     * @name configuration
     * @methodOf app.PaypalService
     * @description
     * Helper to create a paypal configuration object
     *
     *
     * @returns {object} PayPal configuration
     */
    function configuration() {
        // for more options see `paypal-mobile-js-helper.js`
        var config = new PayPalConfiguration({merchantName: shopSettings.payPalShopName, merchantPrivacyPolicyURL: shopSettings.payPalMerchantPrivacyPolicyURL, merchantUserAgreementURL: shopSettings.payPalMerchantUserAgreementURL});
        return config;
    }
    function onPayPalMobileInit() {
        $ionicPlatform.ready().then(function () {
            // must be called
            // use PayPalEnvironmentNoNetwork mode to get look and feel of the flow
            PayPalMobile.prepareToRender(shopSettings.payPalEnv, configuration(), function () {
                $timeout(function () {
                    init_defer.resolve();
                });

            });
        });
    }
    /**
     * @ngdoc method
     * @name makePayment
     * @methodOf app.PaypalService
     * @param {string|number} total total sum. Pattern 12.23
     * @param {string} name name of the item in paypal
     * @description
     * Performs a paypal single payment
     *
     *
     * @returns {object} Promise gets resolved on successful payment, rejected on error
     */
    function makePayment(total, name) {
        var defer = $q.defer();
        total = $filter('number')(total, 2);
        $ionicPlatform.ready().then(function () {
            PayPalMobile.renderSinglePaymentUI(createPayment(total, name), function (result) {
                $timeout(function () {
                    defer.resolve(result);
                });
            }, function (error) {
                $timeout(function () {
                    defer.reject(error);
                });
            });
        });
        return defer.promise;
    }
    return service;
}]);  
//To use this service
//PaypalService.initPaymentUI().then(function () {
//    PaypalService.makePayment($scope.total(), "Total").then(...)
//});
   
// shop settings
// include appConstant into your app.js
app.constant('shopSettings',{        
    payPalEnv: 'PayPalEnvironmentSandbox',   // for testing  production for production
    payPalShopName : 'GoHealthNow',
    payPalMerchantPrivacyPolicyURL : 'https://mytestshop.com/policy',
    payPalMerchantUserAgreementURL : 'https://mytestshop.com/agreement'  

});

Pay Button CLick

app.controller('PaymentCtrl', ['PaypalService',

    function (PaypalService) {
 $scope.PayPaymnt = function () {        
                PaypalService.initPaymentUI().then(function () {
                    PaypalService.makePayment(100, "Total").then(function () {                  
                        $state.go('app.orderComplete', { completeId: 1 });
                    });
                });
            }      

        }
});
read more

Sunday, 20 November 2016

Environment setting for cordova

No comments
USER VARIABLE
--------------------------------------------------------------------------------------------------------------


ANDROID

VariableName - ANDROID_HOME
VariableValue - C:\Program Files (x86)\Android\android-sdk


NPM/CORDOVA

C:\Users\me\AppData\Roaming\npm\node_modules\cordova\bin

C:\Users\vikas\AppData\Roaming\npm


SYSTEM VARIABLE
-----------------------------------------------------------------------------------------------------------------
VN - ADT_HOME
VV - C:\Program Files (x86)\Android\android-sdk


VN - ANDROID_NDK_PATH
VV - C:\Program Files\Android\ndk\android-ndk-r11c

VN - ANT_HOME
VV - C:\apache-ant-1.9.3

VN - GIT_HOME
VV - C:\Program Files (x86)\Git

VN - JAVA_HOME
VV - C:\Program Files (x86)\Java\jdk1.7.0_55
read more

Friday, 18 November 2016

Payment with Sudopay for Authorize.net

No comments
 public class SudopayResponse
    {
        public int id { get; set; }
        public DateTime created { get; set; }
        public DateTime modified { get; set; }
        public string status { get; set; }
        public string paykey { get; set; }        
        public SudopayResponseError error { get; set; }
    }


    public class SudopayResponseErrorArray
    {
        public SudopayResponseError[] SudopayResponseError { get; set; }
    }
    public class SudopayResponseError
    {
        public string code { get; set; }
        public string message { get; set; }
    }



[HttpPost]
        public HttpResponseMessage PayForRideWithSudopay()
        {
            string requestBody = string.Empty;
            requestBody = HttpMessage(requestBody);
            var callForRideRequest = JsonConvert.DeserializeObject<CallForRideRel>(requestBody);
            if (callForRideRequest.CallForRideId == null)
            {
                return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "There was problem in processing your payment");
            }

            try
            {
                var callForRideRepository = uow.Repository<CallForRideRepository>();
                var callForRideData = callForRideRepository.GetRideById((int)callForRideRequest.CallForRideId);

                var userRideRepository = uow.Repository<UserRideRepository>();
                var userRideData = userRideRepository.GetRideByCallForRide((int)callForRideRequest.CallForRideId);

                var userRepository = uow.Repository<UserRepository>();
                var userData = userRepository.GetUsersById((int)userRideData.UserId);

                var userCreditCardRepository = uow.Repository<UserCreditCardRepository>();
                var creditCardData = userCreditCardRepository.GetUserCreditCard(((int)userRideData.UserId)).Where(x => x.IsDefault == true).FirstOrDefault();

                var countryRepository = uow.Repository<CountryRepository>();
                var countryData = countryRepository.GetContryById((int)userData.CountryId);

                if (userRideData != null && countryData != null)
                {
                    userRideData.IsAmountPaid = true;

                    UnitOfWork uow = new UnitOfWork();
                    var appConfigCodeRepository = uow.Repository<AppConfigRepository>();
                    var appConfigCode = appConfigCodeRepository.GetByGroupName("payment");

                    System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();
                    string websiteId = appConfigCode.FirstOrDefault(x => x.Name == "Website").Value;

                    #region Sudopay Capture
                    Inputs = new System.Collections.Specialized.NameValueCollection();
                    Inputs.Add("website_id", websiteId);
                    Inputs.Add("currency_code", appConfigCode.FirstOrDefault(x => x.Name == "CurrencyCode").Value);
                    Inputs.Add("amount", callForRideRequest.RideAmount.ToString());
                    Inputs.Add("item_name", "Pay For Ride");
                    Inputs.Add("item_description", "Ride From '" + callForRideData.Source + "' to '" + callForRideData.ActualDestination + "'");
                    Inputs.Add("buyer_ip", Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString());
                    Inputs.Add("buyer_address", userData.Address);
                    Inputs.Add("buyer_city", userData.City);
                    Inputs.Add("buyer_country", countryData.CountryCode.ToString());
                    Inputs.Add("buyer_email", userData.Email);
                    Inputs.Add("buyer_phone", userData.Mobile);
                    Inputs.Add("buyer_state", userData.State);
                    Inputs.Add("buyer_zip_code", userData.ZipCode);

                    Inputs.Add("credit_card_number", creditCardData.LastFourDigit);
                    Inputs.Add("credit_card_expire", creditCardData.ExpMonth + "/" + creditCardData.ExpYear);
                    Inputs.Add("credit_card_name_on_card", creditCardData.NameOnCard);
                    Inputs.Add("credit_card_code", creditCardData.CVV);
               
                    Inputs.Add("success_url", appConfigCode.FirstOrDefault(x => x.Name == "success_url").Value);
                    Inputs.Add("cancel_url", appConfigCode.FirstOrDefault(x => x.Name == "success_url").Value);

                    WebClient client = new WebClient();
                    client.Headers.Add("Authorization", string.Concat("Basic ", appConfigCode.FirstOrDefault(x => x.Name == "SudopayAuth").Value));
                    byte[] response = client.UploadValues("http://sandbox.sudopay.com/api/v1/merchants/11337/gateways/2/payments/capture.json", Inputs);
                    string result = System.Text.Encoding.UTF8.GetString(response);
                    result = result.Replace("[", "'");
                    result = result.Replace("]", "'");
                    var sudopayResponseData = JsonConvert.DeserializeObject<SudopayResponse>(result);

                    #endregion
                    if (sudopayResponseData.status == "Error")
                    {
                        return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, sudopayResponseData.error.message);
                    }
                    userRideData.TransactionId = sudopayResponseData.paykey;
                    userRideRepository.UpdateUserRide();
                    return this.Request.CreateResponse(HttpStatusCode.OK, "Success");
                }
                else
                {
                    return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "Please check if you have valid information i.e country,state,zipcode");
                }
            }
            catch (Exception ex)
            {

                logger.Error(ex.Message, ex.Message);
                return this.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, "Something went wrong");
            }
        }
read more

Send message with CallFire

No comments
public static string SendText(string number, string message)
        {
            UnitOfWork uow = new UnitOfWork();
            var appConfigCodeRepository = uow.Repository<AppConfigRepository>();
            var appConfigCode = "CallFireAuth";

            var webAddr = "https://api.callfire.com/v2/texts";
            var webrequest = (HttpWebRequest)WebRequest.Create(webAddr);
            webrequest.Method = "POST";
            webrequest.ContentType = "application/json";
            webrequest.Headers.Add("Authorization", String.Concat("Basic ", appConfigCode.Value));

            using (var streamWriter = new StreamWriter(webrequest.GetRequestStream()))
            {                              
                string json = "[{\"message\":\"" + message + "\",\"phoneNumber\":\"" + number + "\"}]";
                streamWriter.Write(json);
            }
            StreamReader reader = null;
            string stripeResponse;
            try
            {
                HttpWebResponse webresponse = (HttpWebResponse)webrequest.GetResponse();
                Stream responseStream = webresponse.GetResponseStream();
                reader = new StreamReader(responseStream);
                return stripeResponse = reader.ReadToEnd();
            }
            catch (WebException exception)
            {
                using (WebResponse response = exception.Response)
                {
                    using (Stream data = response.GetResponseStream())
                    using (reader = new StreamReader(data))
                    {
                        return stripeResponse = reader.ReadToEnd();
                    }
                }
            }
        }

 public class CallFireResponse
    {

        public int httpStatusCode { get; set; }
        public string internalCode { get; set; }
        public string message { get; set; }

    }
read more

SignalR example - mvc

No comments
ContachHub.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Repository.Pattern;
using CarribeaneTaxi.Entity;
using System.IO;

namespace signalRTest.Hubs
{
    public class ContactHub : Hub
    {
        UnitOfWork uow = new UnitOfWork();  
        public void addRequest(Guid GUID, int Id)
        {
            var userRepository = uow.Repository<UserRepository>();
            var userData = userRepository.GetUsersByGUID(GUID);

            var repository = uow.Repository<Repository>();
            var data = repository .GetAll(Id);

            Clients.All.addRequest(userData.UserId, userData.Name, DateTime.Now, GUID);
        }

        public static void addRequest1(string name, string message)
        {
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ContactHub>();
            hubContext.Clients.All.broadcastMessage(name, message);
        }

    }

}


Startup.cs

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;
[assembly: OwinStartupAttribute(typeof(signalRTest.Startup))]
namespace signalRTest
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                map.RunSignalR();
            });      
        }
    }

}


JQUERY

<script src="Scripts/jquery.signalR-2.2.0.js"></script>
 <script src="http://localhost:4562/signalr/hubs"></script>

Common.SignalRURL: function () {
            return 'http://localhost/signalr';
        },

<script type="text/javascript">
        var contactNotifyUsers = undefined;
        $.connection.hub.url = CarribeanCommon.SignalRURL();
        contactNotifyUsers = $.connection.contactHub;
    </script>


Client where you get response 


   //set signalr real time data fetch        
        $.connection.hub.url =Common.SignalRURL();
        contactNotifyUsers = $.connection.contactHub;
        contactNotifyUsers.client.addRequest = function (userId, name, date, GUID) {
            setTimeout(function () {
                if (localStorage.getItem('GUID').toUpperCase() == GUID.toUpperCase()) {
                 
                }
            }, 1000);
        }
        $.connection.hub.start();

//Or

       $.connection.hub.url = Common.SignalRURL();
        $.connection.contactHub.client.broadcastMessage = function (id, name) {
            if (id == userId) {
                $scope.callerName = name;
                $scope.ShoWpop();
                $scope.$apply();
            }
        };
        $.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(function () {
            setTimeout(function () {
                contactNotifyUsers.server.addRequest1('displayname', 'message');
            }, 2000)
        });




Request to server 


$.connection.hub.url = CarribeanCommon.SignalRURL();
                    contactNotifyUsers = $.connection.contactHub;
                    $.connection.hub.start({ transport: ['webSockets', 'longPolling'] }).done(function () {
                        contactNotifyUsers.server.addRequest(localStorage.getItem('GUID'), Id);
                        if (window.location.hash == '#/userCurrentRide') {
                            $route.reload();
                        }
                    });
read more

Friday, 4 November 2016

T-SQL Query Example

No comments
declare @drugname int =null
declare @clientid  int=null
declare @mfgid int=NULL

DECLARE @Skip INT
DECLARE @Take INT    
DECLARE @SQL VARCHAR(MAX)


declare @q varchar(max)='SELECT * FROM (SELECT ROW_NUMBER() OVER
(ORDER BY drugid asc) rownumber,*,(select unitname from UnitDetails where UnitDetails.unitid= Drug.unitid) as unitname,
(select mfgname from Manufacture where Manufacture.mfgid= Drug.mfgid) as mfgname
from Drug
where drugid = coalesce('+case when @drugname is not null then cast(@drugname as varchar) else 'NULL'end+',drugid,'''')
AND
mfgid '+case when @mfgid > 0 then '=('+cast(@mfgid as varchar)+')' else ' is null or mfgid = mfgid' end+'
) A '

execute(@q)
select @q
read more