コード例 #1
0
    private void Awake()
    {
        Instance = this;
#if UNITY_EDITOR
        AdjustConfig adjustConfig = new AdjustConfig(APP_TOKEN, AdjustEnvironment.Sandbox);
#else
        AdjustConfig adjustConfig = new AdjustConfig(APP_TOKEN, AdjustEnvironment.Production);
#endif
        adjustConfig.sendInBackground       = true;
        adjustConfig.launchDeferredDeeplink = true;
        adjustConfig.eventBufferingEnabled  = true;
        adjustConfig.logLevel = AdjustLogLevel.Info;
        adjustConfig.setAttributionChangedDelegate(OnAttributionChangedCallback);
        Adjust.start(adjustConfig);
    }
コード例 #2
0
ファイル: CommandExecutor.cs プロジェクト: eliatlas/unity_sdk
        private void RemoveSessionPartnerParameter()
        {
            if (!_command.ContainsParameter("key"))
            {
                return;
            }

            var keys = _command.Parameters["key"];

            for (var i = 0; i < keys.Count; i = i + 1)
            {
                var key = keys[i];
                Adjust.removeSessionPartnerParameter(key);
            }
        }
コード例 #3
0
        private void RemoveSessionCallbackParameter()
        {
            if (!Command.ContainsParameter("key"))
            {
                return;
            }

            var keys = Command.Parameters["key"];

            for (var i = 0; i < keys.Count; i = i + 1)
            {
                var key = keys[i];
                Adjust.RemoveSessionCallbackParameter(key);
            }
        }
コード例 #4
0
        public string GetAttribution(string request)
        {
            Debug.Log($"Adjust GetAttribution {request}");
            var attribution = Adjust.getAttribution();

            return(request switch
            {
                "adid" => attribution.adid,
                "campaign" => attribution.campaign,
                "network" => attribution.network,
                "adgroup" => attribution.adgroup,
                "clickLabel" => attribution.clickLabel,
                "trackerName" => attribution.trackerName,
                "trackerToken" => attribution.trackerToken,
                _ => string.Empty
            });
コード例 #5
0
ファイル: CommandExecutor.cs プロジェクト: Monakajn/unity_sdk
        private void SetPushToken()
        {
            var pushToken = _command.GetFirstParameterValue("pushToken");

            if (!string.IsNullOrEmpty(pushToken))
            {
                if (pushToken.Equals("null"))
                {
                    Adjust.setDeviceToken(null);
                }
                else
                {
                    Adjust.setDeviceToken(pushToken);
                }
            }
        }
コード例 #6
0
        private void AddSessionPartnerParameter()
        {
            if (!Command.ContainsParameter("KeyValue"))
            {
                return;
            }

            var keyValuePairs = Command.Parameters["KeyValue"];

            for (var i = 0; i < keyValuePairs.Count; i = i + 2)
            {
                var key   = keyValuePairs[i];
                var value = keyValuePairs[i + 1];
                Adjust.AddSessionPartnerParameter(key, value);
            }
        }
コード例 #7
0
    public static void runResponseDelegate(string sResponseData)
    {
        if (Adjust.instance == null)
        {
            Debug.Log(Adjust.errorMessage);
            return;
        }
        if (Adjust.responseDelegate == null)
        {
            Debug.Log("adjust: response delegate not set to receive callbacks");
            return;
        }
        ResponseData obj = new ResponseData(sResponseData);

        Adjust.responseDelegate(obj);
    }
コード例 #8
0
        public static void Render()
        {
            if (App.Setting.PinchPunchRadius < 0)
            {
                App.Setting.PinchPunchRadius = 1;
            }
            else if (App.Setting.PinchPunchRadius > 1000)
            {
                App.Setting.PinchPunchRadius = 1000;
            }

            //偏移
            float     W = (float)App.Model.PunchDisplacement.Size.Width;
            float     H = (float)App.Model.PunchDisplacement.Size.Height;
            Matrix3x2 m = Matrix3x2.CreateTranslation(-W / 2, -H / 2)
                          * Matrix3x2.CreateScale(App.Setting.PinchPunchRadius / W * 2, App.Setting.PinchPunchRadius / H * 2)
                          * Matrix3x2.CreateTranslation(App.Model.Width / 2, App.Model.Height / 2);

            //判断
            if (App.Setting.PinchPunchAmount > 0)
            {
                DisScale = new Transform2DEffect {
                    Source = App.Model.PunchDisplacement, TransformMatrix = m,
                }
            }
            ;
            else
            {
                DisScale = new Transform2DEffect {
                    Source = App.Model.PinchDisplacement, TransformMatrix = m,
                }
            };

            //绘画
            using (var ds = DisTarget.CreateDrawingSession())
            {
                ds.Clear(App.Setting.LiquifyColor);
                ds.DrawImage(DisScale);
            }

            //置换贴图
            App.Model.SecondCanvasImage = Adjust.GetDisplacementMap(App.Model.SecondSourceRenderTarget, DisTarget, Math.Abs(App.Setting.PinchPunchAmount));

            App.Model.isReRender = true; //重新渲染
            App.Model.Refresh++;         //画布刷新
        }
    }
コード例 #9
0
        public virtual List <StoreLocatorItemAdjustment> CheckSufficientQuantity(Adjust adjust)
        {
            var adjustments = new List <StoreLocatorItemAdjustment>();

            foreach (var item in adjust.AdjustItems)
            {
                adjustments.Add(new StoreLocatorItemAdjustment
                {
                    StoreLocatorId   = item.StoreLocatorId,
                    StoreLocatorName = item.StoreLocator.Name,
                    ItemId           = item.ItemId,
                    ItemName         = item.Name,
                    Quantity         = item.AdjustQuantity
                });
            }
            return(_storeService.CheckSufficientQuantity(adjustments));
        }
コード例 #10
0
ファイル: CommandExecutor.cs プロジェクト: Monakajn/unity_sdk
        private void Start()
        {
            Config();

            var configNumber = 0;

            if (_command.ContainsParameter("configName"))
            {
                var configName = _command.GetFirstParameterValue("configName");
                configNumber = int.Parse(configName.Substring(configName.Length - 1));
            }

            var adjustConfig = _savedConfigs[configNumber];

            Adjust.start(adjustConfig);
            _savedConfigs.Remove(0);
        }
コード例 #11
0
ファイル: CommandExecutor.cs プロジェクト: Monakajn/unity_sdk
        private void TrackEvent()
        {
            Event();

            var eventNumber = 0;

            if (_command.ContainsParameter("eventName"))
            {
                var eventName = _command.GetFirstParameterValue("eventName");
                eventNumber = int.Parse(eventName.Substring(eventName.Length - 1));
            }

            var adjustEvent = _savedEvents[eventNumber];

            Adjust.trackEvent(adjustEvent);
            _savedEvents.Remove(0);
        }
コード例 #12
0
ファイル: Modder.cs プロジェクト: sericaer/Tais_TXT_MOD
        public Mod(string name, string path)
        {
            this.name = name;
            this.path = path;

            languages   = Language.Load(path + "/language");
            initSelects = InitSelect.Load(name, path + "/init_select");
            personName  = PersonName.Load(path + "/person_name");
            parties     = Party.Load(name, path + "/party");
            departs     = Depart.Load(name, path + "/depart");
            pops        = Pop.Load(name, path + "/pop");
            common      = Common.Load(name, path + "/common");
            events      = GEvent.Load(name, path + "/event");
            warns       = Warn.Load(name, path + "/warn");
            risks       = Risk.Load(name, path + "/risk");
            adjusts     = Adjust.Load(name, path + "/adjust");
        }
コード例 #13
0
        public virtual void Approve(PhysicalCount physicalCount)
        {
            if (physicalCount.IsApproved == false)
            {
                bool needAdjust = false;
                var  adjust     = new Adjust();

                //add adjust from physical count
                foreach (var item in physicalCount.PhysicalCountItems)
                {
                    var currentQuantity = _storeService.GetTotalQuantity(item.StoreLocator.StoreId, item.StoreLocatorId, item.ItemId);
                    if (item.Count.HasValue && item.Count != currentQuantity)
                    {
                        needAdjust = true;
                        var adjustItem = new AdjustItem
                        {
                            StoreLocatorId = item.StoreLocatorId,
                            ItemId         = item.ItemId,
                            AdjustQuantity = item.Count - currentQuantity
                        };
                        adjust.AdjustItems.Add(adjustItem);
                    }
                }

                if (needAdjust == true)
                {
                    adjust.Name       = adjust.Description = string.Format("Auto Generated adjust for PhysicalCount {0}", physicalCount.Number);
                    adjust.AdjustDate = DateTime.UtcNow;
                    adjust.SiteId     = physicalCount.SiteId;
                    adjust.StoreId    = physicalCount.StoreId;
                    string number = _autoNumberService.GenerateNextAutoNumber(_dateTimeHelper.ConvertToUserTime(DateTime.UtcNow, DateTimeKind.Utc), adjust);
                    adjust.Number          = number;
                    adjust.PhysicalCountId = physicalCount.Id;
                    _adjustRepository.InsertAndCommit(adjust);
                }

                physicalCount.IsApproved = true;
                if (needAdjust == true)
                {
                    physicalCount.AdjustId = adjust.Id;
                }

                _physicalCountRepository.UpdateAndCommit(physicalCount);
            }
        }
コード例 #14
0
ファイル: ExportTests.cs プロジェクト: swharden/SciTIF
        public void Test_Export_AllTestImages()
        {
            string outputFolder = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "output"));

            if (!Directory.Exists(outputFolder))
            {
                Directory.CreateDirectory(outputFolder);
            }

            foreach (string tifPath in SampleData.TifFiles)
            {
                TifFile tif = new(tifPath);
                Console.WriteLine(tif);
                string outputPath = Path.Combine(outputFolder, Path.GetFileName(tifPath) + ".png");
                Console.WriteLine(outputPath);
                Export.PNG(outputPath, Adjust.AutoScale(tif.Channels[0].Values));
            }
        }
コード例 #15
0
 private void CmdConf_OnClick(object sender, RoutedEventArgs e)
 {
     try
     {
         var conf = new Adjust()
         {
             ShowTitleBar      = false,
             IsWindowDraggable = false,
             TitleCaps         = false,
             GlowBrush         = new SolidColorBrush(Colors.White)
         };
         conf.ShowDialog();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.StackTrace);
     }
 }
コード例 #16
0
        private void TrackSubscription()
        {
            var price         = Command.GetFirstParameterValue("revenue");
            var currency      = Command.GetFirstParameterValue("currency");
            var sku           = Command.GetFirstParameterValue("productId");
            var signature     = Command.GetFirstParameterValue("receipt");
            var purchaseToken = Command.GetFirstParameterValue("purchaseToken");
            var orderId       = Command.GetFirstParameterValue("transactionId");
            var purchaseTime  = Command.GetFirstParameterValue("transactionDate");

            AdjustPlayStoreSubscription subscription = new AdjustPlayStoreSubscription(
                long.Parse(price),
                currency,
                sku,
                orderId,
                signature,
                purchaseToken);

            subscription.SetPurchaseTime(long.Parse(purchaseTime));

            if (Command.ContainsParameter("callbackParams"))
            {
                var callbackParams = Command.Parameters["callbackParams"];
                for (var i = 0; i < callbackParams.Count; i = i + 2)
                {
                    var key   = callbackParams[i];
                    var value = callbackParams[i + 1];
                    subscription.AddCallbackParameter(key, value);
                }
            }

            if (Command.ContainsParameter("partnerParams"))
            {
                var partnerParams = Command.Parameters["partnerParams"];
                for (var i = 0; i < partnerParams.Count; i = i + 2)
                {
                    var key   = partnerParams[i];
                    var value = partnerParams[i + 1];
                    subscription.AddPartnerParameter(key, value);
                }
            }

            Adjust.TrackPlayStoreSubscription(subscription);
        }
コード例 #17
0
        public static void TrackEvent(string eventToken, double?revenue, string currency,
                                      string purchaseId, string callbackId, List <string> callbackList, List <string> partnerList)
        {
#if NETFX_CORE
            var adjustEvent = new AdjustEvent(eventToken)
            {
                PurchaseId = purchaseId
            };

            if (revenue.HasValue)
            {
                adjustEvent.SetRevenue(revenue.Value, currency);
            }

            if (!string.IsNullOrEmpty(callbackId))
            {
                adjustEvent.CallbackId = callbackId;
            }

            if (callbackList != null)
            {
                for (int i = 0; i < callbackList.Count; i += 2)
                {
                    var key   = callbackList[i];
                    var value = callbackList[i + 1];

                    adjustEvent.AddCallbackParameter(key, value);
                }
            }

            if (partnerList != null)
            {
                for (int i = 0; i < partnerList.Count; i += 2)
                {
                    var key   = partnerList[i];
                    var value = partnerList[i + 1];

                    adjustEvent.AddPartnerParameter(key, value);
                }
            }

            Adjust.TrackEvent(adjustEvent);
#endif
        }
コード例 #18
0
    void Start()
    {
        sessionNumber = PlayerPrefs.GetInt("session", 0);
        sessionNumber++;
        PlayerPrefs.SetInt("session", sessionNumber);

        playerLevel   = PlayerPrefs.GetInt("playerLevel", 0);
        gemInventory  = PlayerPrefs.GetInt("gemInventory", 0);
        coinInventory = PlayerPrefs.GetInt("coinInventory", 0);
        maxStage      = PlayerPrefs.GetInt("maxStage", 0);
        maxStar       = PlayerPrefs.GetInt("maxStar", 0);



        // adjust event
        AdjustEvent app_start = new AdjustEvent("ksgr8s");

        app_start.addPartnerParameter("session", sessionNumber.ToString());
        app_start.addPartnerParameter("page_type", "surface");
        app_start.addPartnerParameter("page_name", "main_menu");
        app_start.addPartnerParameter("activity_type", "surface");
        app_start.addPartnerParameter("activity_name", "app_start");
        app_start.addPartnerParameter("player_level", playerLevel.ToString());
        app_start.addPartnerParameter("currency1_inv", gemInventory.ToString());
        app_start.addPartnerParameter("currency2_inv", coinInventory.ToString());
        app_start.addPartnerParameter("max_stage", maxStage.ToString());
        app_start.addPartnerParameter("max_star", maxStar.ToString());

        Adjust.trackEvent(app_start);
        // adjust event

        tutorialStep = PlayerPrefs.GetInt("tutorialStep", 0);
        tutorialStepText.GetComponent <Text>().text    = tutorialStep.ToString();
        gemText.gameObject.GetComponent <Text>().text  = gemInventory.ToString();
        coinText.gameObject.GetComponent <Text>().text = coinInventory.ToString();


        if (PlayerPrefs.GetInt("tutorialPassed", 0) == 1)
        {
            tutorialPassedText.gameObject.SetActive(true);
        }

        CameraObject = transform.GetComponent <Animator>();
    }
コード例 #19
0
        private void Start()
        {
            string adjustAppToken = Constants.ADJUST_TOKEN_IOS;

            if (Application.platform == RuntimePlatform.Android)
            {
                adjustAppToken = Constants.ADJUST_TOKEN_ANDROID;
            }
            else if (Application.platform == RuntimePlatform.IPhonePlayer)
            {
                adjustAppToken = Constants.ADJUST_TOKEN_IOS;
            }

            AdjustEnvironment environment = AdjustEnvironment.Production;

            if (Debug.isDebugBuild)
            {
                environment = AdjustEnvironment.Sandbox;
            }
            else
            {
                environment = AdjustEnvironment.Production;
            }


            AdjustConfig config = new AdjustConfig(adjustAppToken, environment, true);

            config.setDeferredDeeplinkDelegate(DeferredDeeplinkCallback);

            if (Debug.isDebugBuild)
            {
                config.setLogLevel(AdjustLogLevel.Verbose);
            }
            else
            {
                config.setLogLevel(AdjustLogLevel.Info);
            }
            config.setSendInBackground(true);
            new GameObject("Adjust").AddComponent <Adjust>();
            config.setAttributionChangedDelegate(this.attributionChangedDelegate);
            Adjust.start(config);
        }
コード例 #20
0
        public void SetConfig(string json)
        {
            Debug.Log($"---- AdjustHelper SetConfig // Json {json}");

            if (!string.IsNullOrEmpty(json) && !json.Equals("{}"))
            {
                _adjustData = JsonUtility.FromJson <AdjustData>(json);

                if (string.IsNullOrEmpty(_adjustData.token))
                {
                    Debug.Log("!!!!!!!!!!!!!!!! Error: Adjust Token is Empty ");
                    return;
                }
                else
                {
                    Debug.Log($"AdjustHelper Init // Token {_adjustData.token}");
                }

                var config = new AdjustConfig(_adjustData.token, AdjustEnvironment.Production, false);
                config.setLogLevel(AdjustLogLevel.Verbose);
                config.setSendInBackground(true);
                config.setAttributionChangedDelegate(AttributionChangedCallback);

                config.setDefaultTracker(_adjustData.token);
                config.setAllowIdfaReading(true);
                config.setPreinstallTrackingEnabled(true);
                config.setAllowiAdInfoReading(true);
                config.setAllowAdServicesInfoReading(true);

                config.setEventBufferingEnabled(true);
                //config.setProcessName();

                Adjust.setEnabled(true);
                Adjust.start(config);

                Debug.Log($"Adjust started");
            }
            else
            {
                Debug.Log($"!!!!!!!!!!!!!!!! AdjustHelper isn`t inited");
            }
        }
コード例 #21
0
        public void Init(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                AdId = "organic";
                return;
            }
#if UNITY_ANDROID && !UNITY_EDITOR
            AdjustConfig config = new AdjustConfig(token, AdjustEnvironment.Production, false);
            config.setLogLevel(AdjustLogLevel.Verbose);
            config.setLogDelegate(msg => Debug.Log(msg));

            //config.setAttributionChangedDelegate(AttributionChangedCallback);

            Adjust.start(config);
#else
            Debug.Log("ADID IS ORGANIC");
            AdId = "organic";
#endif
        }
コード例 #22
0
    private void InitAdjust(string adjustAppToken)
    {
        var adjustConfig = new AdjustConfig(
            adjustAppToken,
            AdjustEnvironment.Production, // AdjustEnvironment.Sandbox to test in dashboard
            true
            );

        adjustConfig.setLogLevel(AdjustLogLevel.Info);    // AdjustLogLevel.Suppress to disable logs
        adjustConfig.setSendInBackground(true);
        new GameObject("Adjust").AddComponent <Adjust>(); // do not remove or rename

// Adjust.addSessionCallbackParameter("foo", "bar"); // if requested to set session-level parameters

//adjustConfig.setAttributionChangedDelegate((adjustAttribution) => {
// Debug.LogFormat("Adjust Attribution Callback: ", adjustAttribution.trackerName);
//});

        Adjust.start(adjustConfig);
    }
コード例 #23
0
        private void TrackThirdPartySharing()
        {
            var isEnabledS = Command.GetFirstParameterValue("isEnabled");
            AdjustThirdPartySharing thirdPartySharing = new AdjustThirdPartySharing(
                isEnabledS == null ? null : Java.Lang.Boolean.ValueOf(isEnabledS));

            if (Command.ContainsParameter("granularOptions"))
            {
                var granularOptions = Command.Parameters["granularOptions"];
                for (var i = 0; i < granularOptions.Count; i = i + 3)
                {
                    var partnerName = granularOptions[i];
                    var key         = granularOptions[i + 1];
                    var value       = granularOptions[i + 2];
                    thirdPartySharing.AddGranularOption(partnerName, key, value);
                }
            }

            Adjust.TrackThirdPartySharing(thirdPartySharing);
        }
コード例 #24
0
    private void InitAdjust(string token)
    {
        if (UnityEngine.Object.FindObjectOfType(typeof(Adjust)) == null)
        {
            GameObject ga = new GameObject();
            ga.name = "Adjust";
            //ga.transform.parent = transform;
            ga.AddComponent <Adjust>();
        }
        else
        {
            Debug.LogWarning("A GameAnalytics object already exists in this scene - you should never have more than one per scene!");
        }

        AdjustConfig config = new AdjustConfig(token, AdjustEnvironment.Production, true);

        config.setLogLevel(AdjustLogLevel.Suppress);
        config.setLogDelegate(msg => Debug.Log(msg));
        Adjust.start(config);
    }
コード例 #25
0
        private void TryToGetDataFromAdjust()
        {
            if (GlobalFacade.AdjustHelper.IsReady)
            {
                Debug.Log($"Adjust TryToGetDataFromAdjust: Adjust is Ready");
                OnAdjustReady();
            }
            else if (!string.IsNullOrEmpty(Adjust.getAdid()))
            {
                string adId = Adjust.getAdid();

                Debug.Log($"-------------- Adjust TryToGetDataFromAdjust: GetAdid alone // Adjust.adid = {adId} // Adjust.idfa = {Adjust.getIdfa()}");
                SaveAdid(adId);
                SetAdjustValue(adId);
            }
            else if (Time.time - TimeFromInit > _waitTime)
            {
                Debug.Log($"!!!!!!!!!!!!!! Adjust TryToGetDataFromAdjust: Waiting is over // add organic // Adjust.idfa = {Adjust.getIdfa()}");
                SetAdjustValue(Organic);
            }
        }
コード例 #26
0
        public void SendAdResult(AdResultType result, AdType type, AdSourceType adSource)
        {
            if (ShouldSkipSendEvent)
            {
                DebugLog($"[ANALYTICS] [Skip] AD EVENT: {MapAdResult(result).ToString()} {MapAdSource(adSource).ToString()}, {MapAdType(type).ToString()}");
                return;
            }

            QLAdEvent adEvent = new QLAdEvent(MapAdResult(result), MapAdType(type), MapAdSource(adSource));

            TrackEvent(adEvent);

            if (result == AdResultType.Watched)
            {
                AdjustEvent adjustEvent = new AdjustEvent(Constants.Analytics.AdjustEvents.AdImpression);
                adjustEvent.addPartnerParameter("type", $"{type.ToString()}");
                adjustEvent.addPartnerParameter("eCPM", "0.0");
                Adjust.trackEvent(adjustEvent);
                DebugLog($"[ADJUST] AD WATCHED - {adjustEvent.ToString()} - {type.ToString()}");
            }
        }
コード例 #27
0
    public void TutorialPassed()
    {
        if (PlayerPrefs.GetInt("tutorialPassed", 0) == 0)
        {
            PlayerPrefs.SetInt("tutorialPassed", 1);
            tutorialPassedText.gameObject.SetActive(true);
            // adjust event
            AdjustEvent tutorial_passed = new AdjustEvent("37znbm");
            tutorial_passed.addPartnerParameter("session", sessionNumber.ToString());
            tutorial_passed.addPartnerParameter("flag_type", "progress");
            tutorial_passed.addPartnerParameter("flag_name", "tutorial_passed");
            tutorial_passed.addPartnerParameter("player_level", playerLevel.ToString());
            tutorial_passed.addPartnerParameter("currency1_inv", gemInventory.ToString());
            tutorial_passed.addPartnerParameter("currency2_inv", coinInventory.ToString());
            tutorial_passed.addPartnerParameter("max_stage", maxStage.ToString());
            tutorial_passed.addPartnerParameter("max_star", maxStar.ToString());

            Adjust.trackEvent(tutorial_passed);
            // adjust event
        }
    }
コード例 #28
0
    public static void LogEvent(string eventName, Dictionary <string, string> dict)
    {
        if (!AdjustHelper.inited)
        {
            return;
        }
        string text = AdjustHelper.EventNameToToken(eventName);

        if (!string.IsNullOrEmpty(text))
        {
            AdjustEvent adjustEvent = new AdjustEvent(text);
            if (dict != null)
            {
                foreach (KeyValuePair <string, string> keyValuePair in dict)
                {
                    adjustEvent.addPartnerParameter(keyValuePair.Key, keyValuePair.Value);
                    adjustEvent.addCallbackParameter(keyValuePair.Key, keyValuePair.Value);
                }
            }
            Adjust.trackEvent(adjustEvent);
        }
    }
コード例 #29
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            //define instances
            SingleFamily house = new SingleFamily();
            Vector3d     vec   = new Vector3d();

            //Get data
            if (!DA.GetData(0, ref house))
            {
                return;
            }
            if (!DA.GetData(1, ref vec))
            {
                return;
            }

            //Calculate
            SingleFamily movedHouse = Adjust.Move(house, vec);

            //Set data
            DA.SetData(0, movedHouse);
        }
コード例 #30
0
        public void SetAudioEnabled(bool flag)
        {
            AudioManager amanager = (AudioManager)Application.Context.GetSystemService(Context.AudioService);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
            {
                Adjust value = (flag) ? Adjust.Unmute : Adjust.Mute;
                amanager.AdjustStreamVolume(Stream.Notification, value, 0);
                amanager.AdjustStreamVolume(Stream.Alarm, value, 0);
                amanager.AdjustStreamVolume(Stream.Music, value, 0);
                amanager.AdjustStreamVolume(Stream.Ring, value, 0);
                amanager.AdjustStreamVolume(Stream.System, value, 0);
            }
            else
            {
                amanager.SetStreamMute(Stream.Notification, !flag);
                amanager.SetStreamMute(Stream.Alarm, !flag);
                amanager.SetStreamMute(Stream.Music, !flag);
                amanager.SetStreamMute(Stream.Ring, !flag);
                amanager.SetStreamMute(Stream.System, !flag);
            }
        }
コード例 #31
0
ファイル: TextTool.cs プロジェクト: BackupTheBerlios/zimap
        public static void PrintAdjust(uint indent, uint maxcol, Adjust adjust, Decoration deco, string text)
        {
            if(Formatter == null) GetDefaultFormatter();
            if(maxcol == 0) maxcol = TextWidth;
            string sepc = null;
            uint   sepl = 0;
            if(indent > 0 && (deco & Decoration.Column) != 0)
            {   sepc = Formatter.GetIndexSeparator();
                sepl = (uint)sepc.Length;
            }
            if(indent+sepl >= maxcol) indent = 0;

            string left = null;
            if(indent > 0)
            {   if(string.IsNullOrEmpty(text))
                {   left = "".PadRight((int)indent);  text = "";
                }
                else if(text.Length == indent)
                {   left = text;
                    text = "";
                }
                else if(text.Length <= indent)
                {   left = text.PadRight((int)indent);
                    text = "";
                }
                else
                {   left = text.Substring(0, (int)indent);
                    text = text.Substring((int)indent);
                }
                left += sepc;
            }

            uint maxc = maxcol - (indent+sepl);
            string line;
            if(adjust != Adjust.None || text.Length > maxc)
                line = TextAdjust(text, maxcol-(indent+sepl), adjust, Formatter.GetEllipses());
            else
                line = text;
            if(indent > 0) line = left + line;

            Formatter.WriteLine(line);
            if(deco != Decoration.None && deco != Decoration.Column)
                Formatter.WriteLine(DecoLine(deco, indent, maxcol));
        }
コード例 #32
0
ファイル: TextTool.cs プロジェクト: BackupTheBerlios/zimap
        // =====================================================================
        // static methods
        // =====================================================================
        /// <summary>
        /// Create a left or right aligned, space padded string of fixed width.
        /// </summary>
        /// <param name="text">
        /// The text to be formatted (<c>null</c> is ok).
        /// </param>
        /// <param name="width">
        /// Size of the returned string.
        /// </param>
        /// <param name="adjust">
        /// Controls what happens to the string. All values except <c>Adjust.None</c>
        /// will expand the string to the size given by <c>width</c>.
        /// </param>
        /// <param name="ellipses">
        /// If <c>null</c> nothing happens if <c>text</c> is longer than <c>width</c>.
        /// An empty value will clip <c>text</c> and any other value will be appended to
        /// a clipped <c>text</c>.
        /// </param>
        /// <returns>
        /// The formatted string.
        /// </returns>
        public static string TextAdjust(string text, uint width, Adjust adjust, string ellipses)
        {
            int ipad = 0;
            int icnt = (text == null) ? 0 : text.Length;
            int itxt = icnt;
            if(width == 0) width = TextWidth;
            if(icnt >= (int)width) icnt = (int)width;
            else                   ipad = (int)width - icnt;
            StringBuilder sb = new StringBuilder((int)width);

            if(ipad > 0)                        // padding for Right and Center
            {   if(adjust == Adjust.Center)
                {   int ilef = ipad / 2; ipad -= ilef;
                    if(ilef > 0) sb.Append(' ', ilef);
                }
                else if(adjust == Adjust.Right)
                    sb.Append(' ', ipad);
            }

            if(itxt > 0)                        // has text output ...
            {   int irun = sb.Length;
                if(itxt <= (int)width || ellipses == null)
                    sb.Append(text, 0, itxt);   // no truncation
                else if(ellipses.Length >= (int)width)
                    sb.Append(ellipses, 0, (int)width);
                else
                {   sb.Append(text, 0, icnt-ellipses.Length);
                    sb.Append(ellipses);
                }

                int iend = sb.Length;
                while(irun < iend)              // remove control chars
                {   if(sb[irun] < ' ') sb[irun] = GetDefaultFormatter().GetBadChar();
                    irun++;
                }
            }

            if((adjust == Adjust.Left || adjust == Adjust.Center) && ipad > 0)
                sb.Append(' ', ipad);
            return sb.ToString();
        }
        static void Main(string[] args)
        {
            Console.BufferWidth = 150;
            //Console.BufferHeight = Console.LargestWindowHeight;
            Console.BufferHeight = 60;
            Console.SetWindowSize(Console.BufferWidth, Console.BufferHeight);

            #region Step 1: SignOn Authentication
            Console.WriteLine("Attempting to sign in...");
            _sessionToken = _svcClient.SignOn(_identityToken);
            Console.WriteLine(!string.IsNullOrEmpty(_sessionToken) ? "Successfully signed in!\n" : "ERROR Signing in!\n");
            #endregion

            #region Step 2: Managing Application Configuration Data
            Console.WriteLine("Attempting to save application data...");
            var applicationData = DataGenerator.CreateApplicationData();
            _applicationProfileId = _svcClient.SaveApplicationData(_sessionToken, applicationData);
            if(!string.IsNullOrEmpty(_applicationProfileId))
                Console.WriteLine("Application saved successfully! Application Profile ID: " + _applicationProfileId + "\n");
            else Console.WriteLine("ERROR Saving Application!\n");
            #endregion

            #region Step 3: Retrieving Service Information
            Console.WriteLine("Getting service information...");
            var serviceInfo = _svcClient.GetServiceInformation(_sessionToken);
            #endregion

            #region Step 4: Managing Merchant Profiles
            if (serviceInfo.BankcardServices.Any())
            {
                // If there are multiple services you'll want to use them as desired. The sample will only focus on the first one.
                var bankcardService = serviceInfo.BankcardServices.First();
                _bcpServiceId = bankcardService.ServiceId;
                Console.WriteLine("There are " + serviceInfo.BankcardServices.Count() + " bankcard services available. Using serviceId " + _bcpServiceId + "\n");

                if (!_svcClient.IsMerchantProfileInitialized(_sessionToken, _bcpServiceId, _merchantProfileId, TenderType.Credit))
                {
                    Console.WriteLine("Merchant Profile " + _merchantProfileId + " does not exist. Attempting to save...");
                    _svcClient.SaveMerchantProfiles(_sessionToken, _bcpServiceId, TenderType.Credit, DataGenerator.CreateMerchantProfiles());
                    if (_svcClient.IsMerchantProfileInitialized(_sessionToken, _bcpServiceId, _merchantProfileId, TenderType.Credit))
                        Console.WriteLine("Merchant Profile " + _merchantProfileId + " saved successfully!\n");

                } else Console.WriteLine("Merchant Profile " + _merchantProfileId + " exists. Skipping SaveMerchantProfiles.");
            }
            if(serviceInfo.ElectronicCheckingServices.Any())
            {
                // If there are multiple services you'll want to use them as desired. The sample will only focus on the first one.
                var eckServce = serviceInfo.ElectronicCheckingServices.First();
                _eckServiceId = eckServce.ServiceId;
                Console.WriteLine("There are " + serviceInfo.BankcardServices.Count() + " electronic checking services available. Using serviceId " + _eckServiceId + "\n");

                if (!_svcClient.IsMerchantProfileInitialized(_sessionToken, _eckServiceId, _merchantProfileId, TenderType.PINDebit))
                {
                    Console.WriteLine("Merchant Profile " + _merchantProfileId + " does not exist. Attempting to save...");
                    _svcClient.SaveMerchantProfiles(_sessionToken, _eckServiceId, TenderType.PINDebit, DataGenerator.CreateMerchantProfiles());
                    if (_svcClient.IsMerchantProfileInitialized(_sessionToken, _eckServiceId, _merchantProfileId, TenderType.PINDebit))
                        Console.WriteLine("Merchant Profile " + _merchantProfileId + " saved successfully!\n");

                }
                else Console.WriteLine("Merchant Profile " + _merchantProfileId + " exists. Skipping SaveMerchantProfiles.");
            }
            if(serviceInfo.StoredValueServices.Any())
            {
                // If there are multiple services you'll want to use them as desired. The sample will only focus on the first one.
                var svaService = serviceInfo.ElectronicCheckingServices.First();
                _svaServiceId = svaService.ServiceId;
                Console.WriteLine("There are " + serviceInfo.BankcardServices.Count() + " stroed value services available. Using serviceId " + _svaServiceId + "\n");

                if (!_svcClient.IsMerchantProfileInitialized(_sessionToken, _svaServiceId, _merchantProfileId, TenderType.NotSet))
                {
                    Console.WriteLine("Merchant Profile " + _merchantProfileId + " does not exist. Attempting to save...");
                    _svcClient.SaveMerchantProfiles(_sessionToken, _svaServiceId, TenderType.NotSet, DataGenerator.CreateMerchantProfiles());
                    if (_svcClient.IsMerchantProfileInitialized(_sessionToken, _svaServiceId, _merchantProfileId, TenderType.NotSet))
                        Console.WriteLine("Merchant Profile " + _merchantProfileId + " saved successfully!\n");

                }
                else Console.WriteLine("Merchant Profile " + _merchantProfileId + " exists. Skipping SaveMerchantProfiles.");
            }

            // GetMerchantProfiles
            var merchantProfiles = new List<MerchantProfile>();
            if(!string.IsNullOrEmpty(_bcpServiceId))
            {
                Console.WriteLine("Getting Merchant Profiles with service ID: " + _bcpServiceId);
                merchantProfiles = _svcClient.GetMerchantProfiles(_sessionToken, _bcpServiceId, TenderType.Credit);
            }
            else if (!string.IsNullOrEmpty(_eckServiceId))
            {
                Console.WriteLine("Getting Merchant Profiles with service ID: " + _eckServiceId);
                merchantProfiles = _svcClient.GetMerchantProfiles(_sessionToken, _eckServiceId, TenderType.PINDebit);
            }
            else if (!string.IsNullOrEmpty(_svaServiceId))
            {
                Console.WriteLine("Getting Merchant Profiles with service ID: " + _svaServiceId);
                merchantProfiles = _svcClient.GetMerchantProfiles(_sessionToken, _svaServiceId, TenderType.NotSet);
            }
            Console.WriteLine("There are " + merchantProfiles.Count + " merchant profiles related to this serviceId.");
            foreach (var merchantProfile in merchantProfiles)
            {
                Console.WriteLine("    Merchant Profile Id: " + merchantProfile.ProfileId);
                Console.WriteLine("        Service Name: " + merchantProfile.ServiceName);
            }
            #endregion

            #region Step 5: Authorizing Transactions
            var bankcardTransaction = DataGenerator.CreateBankcardTransaction();
            var eckTransaction = new ElectronicCheckingTransaction(); // TODO create ECK Transaction
            var svaTransaction = new StoredValueTransaction(); // TODO Create SVA Transaction

            var txnIdForAdjustAndCapture = "";
            var txnIdForUndo = "";
            var txnIdsForCaptureAll = new List<string>();
            var txnIdsForCaptureSelective = new List<string>();
            var txnIdForReturnById = "";
            // Bankcard Services - Authorize
            if(!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.Authorize)
            {
                Console.WriteLine("\nBankcard Processing: Creating transaction to adjust and then capture...");
                var response = _txnClient.Authorize(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId,_bcpServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "AUTHORIZE");
                if(response != null)
                    txnIdForAdjustAndCapture = !string.IsNullOrEmpty(response.TransactionId) ? response.TransactionId : null;

                Console.WriteLine("\nBankcard Processing: Creating transaction to undo...");
                var response2 = _txnClient.Authorize(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                ScreenPrinter.PrintTransactionResponse(response2, "AUTHORIZE");
                if (response2 != null)
                    txnIdForUndo = !string.IsNullOrEmpty(response2.TransactionId) ? response2.TransactionId : null;

                Console.WriteLine("\nBankcard Processing: Creating 3 transactions to be used to Capture All...");
                for (int i = 0; i < 3; i++)
                {
                    var response3 = _txnClient.Authorize(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                    ScreenPrinter.PrintTransactionResponse(response3, "AUTHORIZE");
                    if (response3 != null && !string.IsNullOrEmpty(response3.TransactionId))
                        txnIdsForCaptureAll.Add(response3.TransactionId);
                }

                Console.WriteLine("\nBankcard Processing: Creating 3 transactions to be used to Capture Selective...");
                for (int i = 0; i < 3; i++)
                {
                    var response4 = _txnClient.Authorize(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                    ScreenPrinter.PrintTransactionResponse(response4, "AUTHORIZE");
                    if (response4 != null && !string.IsNullOrEmpty(response4.TransactionId))
                        txnIdsForCaptureSelective.Add(response4.TransactionId);
                }
            }
            // Bankcard Services - Authorize and Capture
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.AuthAndCapture)
            {
                Console.WriteLine("\nBankcard Processing: Creating authorize and capture transaction to return by id...");
                var response = _txnClient.AuthorizeAndCapture(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "AUTHORIZE AND CAPTURE");
                if (response != null)
                    txnIdForReturnById = !string.IsNullOrEmpty(response.TransactionId) ? response.TransactionId : null;
            }
            // Electronic Checking Services - Authorize
            if (!string.IsNullOrEmpty(_eckServiceId) && serviceInfo.ElectronicCheckingServices.First().Operations.Authorize)
            {
                Console.WriteLine("\nElectronic Checking Service: Creating 3 transactions to be used to Capture All...");
                for (int i = 0; i < 3; i++)
                {
                    var response = _txnClient.Authorize(_sessionToken, eckTransaction, _applicationProfileId, _merchantProfileId, _eckServiceId);
                    ScreenPrinter.PrintTransactionResponse(response, "AUTHORIZE");
                    if (response != null && !string.IsNullOrEmpty(response.TransactionId))
                        txnIdsForCaptureAll.Add(response.TransactionId);
                }
            }
            // Stored Value Services - Authorize
            if (!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.Authorize)
            {
                Console.WriteLine("\nStored Value Service: Creating transaction to adjust and then capture...");
                var response = _txnClient.Authorize(_sessionToken, svaTransaction, _applicationProfileId, _merchantProfileId, _svaServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "AUTHORIZE");
                if (response != null)
                    txnIdForAdjustAndCapture = !string.IsNullOrEmpty(response.TransactionId) ? response.TransactionId : null;

                Console.WriteLine("\nStored Value Service: Creating transaction to undo...");
                var response2 = _txnClient.Authorize(_sessionToken, svaTransaction, _applicationProfileId, _merchantProfileId, _svaServiceId);
                ScreenPrinter.PrintTransactionResponse(response2, "AUTHORIZE");
                if (response2 != null)
                    txnIdForUndo = !string.IsNullOrEmpty(response2.TransactionId) ? response2.TransactionId : null;
            }
            // Stored Value Services - Authorize and Capture
            if(!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.AuthAndCapture)
            {
                Console.WriteLine("\nStored Value Service: Creating authorize and capture transaction to return by id...");
                var response = _txnClient.AuthorizeAndCapture(_sessionToken, svaTransaction, _applicationProfileId, _merchantProfileId, _svaServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "AUTHORIZE AND CAPTURE");
                if (response != null)
                    txnIdForReturnById = !string.IsNullOrEmpty(response.TransactionId) ? response.TransactionId : null;
            }
            #endregion

            //_txnClient.Capture(_sessionToken, )

            #region Step 6: Adjusting and Voiding Transactions

            // Bankcard Services - Adjust
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.Adjust)
            {
                Console.WriteLine("\nBankcard Services: Adjust on transaction " + txnIdForAdjustAndCapture + "...");
                var adjust = new Adjust { Amount = 5.00m, TransactionId = txnIdForAdjustAndCapture };
                var response = _txnClient.Adjust(_sessionToken, adjust, _applicationProfileId, _bcpServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "ADJUST AUTH(" + txnIdForAdjustAndCapture + ")");
                if(response != null) // Save the new txn guid, you'll use the most recent txn guid associated with the transaction for capture later.
                    txnIdForAdjustAndCapture = !string.IsNullOrEmpty(response.TransactionId) ? response.TransactionId : null;
            }
            // Bankcard Services - Undo
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.Undo && !string.IsNullOrEmpty(txnIdForUndo))
            {
                Console.WriteLine("\nBankcard Services: Undo on transaction " + txnIdForUndo + "...");
                var bankcardUndo = new BankcardUndo(){TransactionId = txnIdForUndo, PINDebitReason = PINDebitUndoReason.NotSet, ForceVoid = false};
                var response = _txnClient.Undo(_sessionToken, bankcardUndo, _applicationProfileId, _bcpServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "UNDO (" + txnIdForUndo + ")");
            }
            // Electronic Checking Services - Undo
            if (!string.IsNullOrEmpty(_eckServiceId) && serviceInfo.ElectronicCheckingServices.First().Operations.Undo && !string.IsNullOrEmpty(txnIdForUndo))
            {
                Console.WriteLine("\nElectronic Checking Services: Undo on transaction " + txnIdForUndo + "...");
                var response = _txnClient.Undo(_sessionToken, new Undo() { TransactionId = txnIdForUndo }, _applicationProfileId, _eckServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "UNDO AUTH(" + txnIdForUndo + ")");
            }
            // Stored Value Services - Undo
            if (!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.Undo && !string.IsNullOrEmpty(txnIdForUndo))
            {
                Console.WriteLine("Stored Value Services: Undo on transaction " + txnIdForUndo + "...");
                var response = _txnClient.Undo(_sessionToken, new Undo() { TransactionId = txnIdForUndo }, _applicationProfileId, _svaServiceId);
                ScreenPrinter.PrintTransactionResponse(response, "UNDO AUTH(" + txnIdForUndo + ")");
            }
            #endregion

            #region Step 7: Capturing Transaction for Settlement

            // Bankcard Services - Capture
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.Capture && !string.IsNullOrEmpty(txnIdForAdjustAndCapture))
            {
                Console.WriteLine("\nBankcard Services: Capture on transaction " + txnIdForAdjustAndCapture + "...");
                var chargeType = ConfigurationManager.AppSettings["IndustryType"] == "Retail" ? ChargeType.RetailOther : ChargeType.NotSet;
                var capture = new BankcardCapture() { TransactionId = txnIdForAdjustAndCapture, ChargeType = chargeType};
                if (ConfigurationManager.AppSettings["IndustryType"] == "MOTO")
                    capture.ShipDate = DateTime.Now;
                var response = _txnClient.Capture(_sessionToken, capture, _applicationProfileId, _bcpServiceId);
                if(response != null)
                    ScreenPrinter.PrintCaptureResponse(response, "CAPTURE (" + txnIdForAdjustAndCapture + ")");
                // Incase the returnById txnId was not set earlier, we will use this Id to return later.
                if (string.IsNullOrEmpty(txnIdForReturnById))
                    txnIdForReturnById = txnIdForAdjustAndCapture;
            }
            // Bankcard Services - CaptureSelective
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.CaptureSelective && txnIdsForCaptureSelective.Count > 0)
            {
                Console.WriteLine("\nBankcard Services: CaptureSelective on transactions" + "...");
                var chargeType = ConfigurationManager.AppSettings["IndustryType"] == "Retail" ? ChargeType.RetailOther : ChargeType.NotSet;
                var captures = new List<BankcardCapture>();
                foreach (var txnId in txnIdsForCaptureSelective)
                {
                    var capture = new BankcardCapture() { TransactionId = txnId, ChargeType = chargeType };
                    if (ConfigurationManager.AppSettings["IndustryType"] == "MOTO")
                        capture.ShipDate = DateTime.Now;
                    captures.Add(capture);
                }
                var response = _txnClient.CaptureSelective<BankcardCapture>(_sessionToken, txnIdsForCaptureSelective, captures, _applicationProfileId, _bcpServiceId);
                if (response != null)
                    foreach (var r in response)
                        ScreenPrinter.PrintCaptureResponse(r, "CAPTURE (" + r.TransactionId + ")");
            }
            // Bankcard Services - CaptureAll
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.CaptureAll && txnIdsForCaptureAll.Count > 0)
            {
                Console.WriteLine("\nBankcard Services: CaptureAll on transactions" + "...");
                var chargeType = ConfigurationManager.AppSettings["IndustryType"] == "Retail" ? ChargeType.RetailOther : ChargeType.NotSet;
                var captures = new List<BankcardCapture>();
                foreach (var txnId in txnIdsForCaptureAll)
                {
                    var capture = new BankcardCapture() { TransactionId = txnId, ChargeType = chargeType };
                    if (ConfigurationManager.AppSettings["IndustryType"] == "MOTO")
                        capture.ShipDate = DateTime.Now;
                    captures.Add(capture);
                }
                var response = _txnClient.CaptureAll<BankcardCapture>(_sessionToken, captures, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                if (response != null)
                    foreach (var r in response)
                        ScreenPrinter.PrintCaptureResponse(r, "CAPTURE (" + r.TransactionId + ")");
            }
            // Electronic Checking Services - Capture All
            if (!string.IsNullOrEmpty(_eckServiceId) && serviceInfo.ElectronicCheckingServices.First().Operations.CaptureAll && txnIdsForCaptureAll.Count > 0)
            {
                Console.WriteLine("\nElectronic Checking Services: CaptureAll on transactions" + "...");
                var captures = txnIdsForCaptureAll.Select(txnId => new Capture() {TransactionId = txnId}).ToList();
                var response = _txnClient.CaptureAll<Capture>(_sessionToken, captures, _applicationProfileId, _merchantProfileId, _eckServiceId);
                if (response != null)
                    foreach (var r in response)
                        ScreenPrinter.PrintCaptureResponse(r, "CAPTURE (" + r.TransactionId + ")");
            }
            // Stored Value Services - Capture
            if (!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.Capture && !string.IsNullOrEmpty(txnIdForAdjustAndCapture))
            {
                Console.WriteLine("\nStored Value Services: Capture on transaction " + txnIdForAdjustAndCapture + "...");
                var capture = new Capture() { TransactionId = txnIdForAdjustAndCapture};
                var response = _txnClient.Capture(_sessionToken, capture, _applicationProfileId, _svaServiceId);
                if (response != null)
                    ScreenPrinter.PrintCaptureResponse(response, "CAPTURE (" + txnIdForAdjustAndCapture + ")");
            }

            #endregion

            #region Step 8: Refunding Transactions
            // If the txnIdForReturnById was not set by this point, attempt to authorize and capture a new transaction.
            if(!string.IsNullOrEmpty(_bcpServiceId) && string.IsNullOrEmpty(txnIdForReturnById))
            {
                var authResponse = _txnClient.Authorize(_sessionToken, bankcardTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                if (authResponse != null)
                {
                    var chargeType = ConfigurationManager.AppSettings["IndustryType"] == "Retail"? ChargeType.RetailOther : ChargeType.NotSet;
                    var capture = new BankcardCapture() {TransactionId = authResponse.TransactionId, ChargeType = chargeType};
                    if (ConfigurationManager.AppSettings["IndustryType"] == "MOTO")
                        capture.ShipDate = DateTime.Now;
                    var cList = new List<BankcardCapture>();
                    cList.Add(capture);
                    var capResponse = _txnClient.CaptureAll<BankcardCapture>(_sessionToken, cList, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                    if (capResponse != null)
                        txnIdForReturnById = authResponse.TransactionId;
                }
            }

            if(!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.ReturnById && !string.IsNullOrEmpty(txnIdForReturnById))
            {
                Console.WriteLine("\nBankcard Services: Return by id on " + txnIdForReturnById+ "...");
                // Specify an amount in the BankcardReturn if performing a partial return.
                // BankcardTenderData is required for PIN Debit transactions.
                var returnById = new BankcardReturn() {TransactionId = txnIdForReturnById};
                var response = _txnClient.ReturnById(_sessionToken, returnById, _applicationProfileId, _bcpServiceId);
                if (response != null)
                    ScreenPrinter.PrintTransactionResponse(response, "RETURN BY ID (" + txnIdForReturnById+ ")");
            }
            if (!string.IsNullOrEmpty(_bcpServiceId) && serviceInfo.BankcardServices.First().Operations.ReturnUnlinked)
            {
                Console.WriteLine("\nBankcard Services: Return Unlinked Transaction" + "...");
                var response = _txnClient.ReturnUnlinked(_sessionToken, bankcardTransaction, _applicationProfileId,_merchantProfileId, _bcpServiceId);
                if (response != null)
                    ScreenPrinter.PrintTransactionResponse(response, "RETURN UNLINKED");
            }
            if (!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.ReturnById && !string.IsNullOrEmpty(txnIdForReturnById))
            {
                Console.WriteLine("\nStored Value Services: Return by id on " + txnIdForReturnById + "...");
                var returnById = new Return() { TransactionId = txnIdForReturnById};
                var response = _txnClient.ReturnById(_sessionToken, returnById, _applicationProfileId, _svaServiceId);
                if (response != null)
                    ScreenPrinter.PrintTransactionResponse(response, "RETURN BY ID (" + txnIdForReturnById + ")");
            }
            if (!string.IsNullOrEmpty(_svaServiceId) && serviceInfo.StoredValueServices.First().Operations.ReturnUnlinked)
            {
                Console.WriteLine("\nStored Value Services: Return Unlinked Transaction" + "...");
                var response = _txnClient.ReturnUnlinked(_sessionToken, svaTransaction, _applicationProfileId, _merchantProfileId, _bcpServiceId);
                if (response != null)
                    ScreenPrinter.PrintTransactionResponse(response, "RETURN UNLINKED");
            }
            #endregion

            #region Step 9: Optional Operations
            // TODO Add Content for optional operations. They can include:
            // Bankcard Processing (BCP): Acknowledge, Disburse, QueryAccount, Verify, RequestTransaction (Leave out Acknowledge and Dispurse in sample)
            // Electronic Checking (ECK): QueryAccount
            // Stored Value Account (SVA): QueryAccount, ManageAccount, ManageAccountById
            #endregion

            #region Transaction Management Services

            Console.WriteLine("\n***Begin Transaction Managment Services***\n");

            var queryTransactionParameters = DataGenerator.CreateQueryTransactionParameters(QueryType.AND);
            var pagingParameters = DataGenerator.CreatePagingParameters();

            // QueryTransactionFamilies
            Console.WriteLine("Querying transaction Families...");
            var queryTransactionFamilies = _mgmtClient.QueryTransactionFamilies(_sessionToken, queryTransactionParameters, pagingParameters);
            ScreenPrinter.PrintTransactionFamilies(queryTransactionFamilies);

            //QueryTransactionsDetails
            var txnIds = new List<string>();
            if (queryTransactionFamilies[0] != null)
                txnIds.Add(queryTransactionFamilies[0].TransactionIds.First());
            if (queryTransactionFamilies[1] != null)
                txnIds.Add(queryTransactionFamilies[1].TransactionIds.First());
            if (queryTransactionFamilies[2] != null)
                txnIds.Add(queryTransactionFamilies[2].TransactionIds.First());

            queryTransactionParameters = DataGenerator.CreateQueryTransactionParameters(QueryType.OR, txnIds);
            queryTransactionParameters.TransactionDateRange = null;
            Console.WriteLine("\nQuery Transaction Details on the first " + txnIds.Count + " transaction ids returned from Query Transaciton Families...");
            var queryTransactionsDetail = _mgmtClient.QueryTransactionsDetail(_sessionToken, queryTransactionParameters, TransactionDetailFormat.CWSTransaction, pagingParameters, includeRelated: false);
            ScreenPrinter.PrintTransactionDetail(queryTransactionsDetail);

            Console.WriteLine("\nQuery Transaction Summaries on the first " + txnIds.Count + " transaction ids returned from Query Transaction Families...");
            var queryTransactionsSummary = _mgmtClient.QueryTransactionsSummary(_sessionToken, queryTransactionParameters, pagingParameters, true);
            ScreenPrinter.PrintTransactionSummary(queryTransactionsSummary);

            Console.WriteLine("\n***End Transaction Managment Services***\n");

            #endregion

            // Cleaning up after the sample code by deleting the merchant profile and the application data.
            Console.WriteLine("\n****CLEAN UP****\n");
            Console.WriteLine("Deleting Merchant Profile " + _merchantProfileId + ".");
            _svcClient.DeleteMerchantProfile(_sessionToken, _bcpServiceId, _merchantProfileId, TenderType.Credit);
            if (!_svcClient.IsMerchantProfileInitialized(_sessionToken, _bcpServiceId, _merchantProfileId, TenderType.Credit))
                Console.WriteLine("Merchant Profile " + _merchantProfileId + " deleted successfully!");

            Console.WriteLine("\nDeleting Application Data for Application Profile Id " + _applicationProfileId + "...");
            _svcClient.DeleteApplicationData(_sessionToken, _applicationProfileId);
            if (_svcClient.GetApplicationData(_sessionToken, _applicationProfileId) == null)
                Console.WriteLine("Application Data deleted successfully!");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
        private void cmdAdjust_Click(object sender, EventArgs e)
        {
            if (ChkLstTransactionsProcessed.CheckedItems.Count == 0) { MessageBox.Show("Please Select (Check) Authorize transactions for Adjust"); return; }
            //Check to see if this transaction type is supported
            if (!SupportedTxnTypes.Adjust) { MessageBox.Show("Adjust Not Supported"); return; }

            Cursor = Cursors.WaitCursor;

            //First verify if all transactions selected are "Authorize" transactions
            List<ResponseDetails> txnsToProcess = new List<ResponseDetails>();
            foreach (object itemChecked in ChkLstTransactionsProcessed.CheckedItems)
            {
                if (((ResponseDetails)(itemChecked)).TransactionType != TransactionType.Authorize.ToString() & ((ResponseDetails)(itemChecked)).TransactionType != TransactionType.AuthorizeAndCapture.ToString())
                {
                    MessageBox.Show("All selected messages must be of type Authorize or AuthorizeAndCapture");
                    Cursor = Cursors.Default;
                    return;
                }
                txnsToProcess.Add(((ResponseDetails)(itemChecked)));
            }

            List<ResponseDetails> response = new List<ResponseDetails>();
            if (_bcs != null) //Process a BankCard Transaction
            {
                try
                {
                    //Now process each message selected
                    foreach (ResponseDetails _RD in txnsToProcess)
                    {
                        Adjust aTransaction = new Adjust();
                        //Let's Undo or Void the transaction
                        aTransaction.TransactionId = _RD.Response.TransactionId;
                        aTransaction.Amount = Convert.ToDecimal(TxtAmount.Text);
                        if (TxtTip.Text.Length > 0)
                            if (Convert.ToDecimal(TxtTip.Text) > 0)
                                aTransaction.TipAmount = Convert.ToDecimal(TxtTip.Text);

                        processResponse(Helper.ProcessBCPTransaction(TransactionType.Adjust, null, null, null, null, aTransaction, null, null, null, ChkAcknowledge.Checked, false));
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
            else if (_ecks != null) //Process as a Check transaction
            {
                try
                {
                    MessageBox.Show(@"Placeholder for ECK code. Please ask your solution consultant for an example");
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
        }
コード例 #35
0
        public List<ResponseDetails> ProcessBCPTransactionPro(
            TransactionType _TT //Required
            , BankcardTransactionPro _BCtransaction //Conditional : Only used for an AuthorizeAndCapture, Authorize and ReturnUnlinked. Otherwise null
            , BankcardCapturePro _BCDifferenceData //Conditional : Only used for a Capture. Otherwise null
            , List<String> _BatchIds //Conditional : A list of one or more batch Ids to capture.
            , BankcardReturn _RDifferenceData //Conditional : Only used for a ReturnById. Otherwise null
            , Adjust _ADifferenceData //Conditional : Only used for an Adjust. Otherwise null
            , BankcardUndo _UDifferenceData //Conditional : Only used for an Undo. Otherwise null
            , List<string> _TransactionIds //Conditional : Only used for a CaptureSelective. Otherwise null
            , List<Capture> _CaptureDifferenceData //Conditional : Only used for CaptureAll and CaptureSelective. Otherwise null
            , bool _SendAcknowledge
            , bool _UseWorkflowId)
        {
            List<Response> _Response = new List<Response>();
            try
            {
                CheckTokenExpire();//Make sure the current token is valid

                string _serviceIdOrWorkflowId = _serviceId;
                if (_UseWorkflowId)
                    _serviceIdOrWorkflowId = _workflowId;

                if (_TT == TransactionType.AuthorizeAndCapture)
                {
                    if (CredentialRequired())
                        _BCtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.AuthorizeAndCapture(_sessionToken, _BCtransaction, _applicationProfileId, _merchantProfileId, _serviceIdOrWorkflowId));
                    //Always Verify that the requested amount and approved amount are the same.
                    BankcardTransactionResponsePro BCR = new BankcardTransactionResponsePro();
                    BCR = (BankcardTransactionResponsePro)_Response[0];
                    if (_BCtransaction.TransactionData.Amount != BCR.Amount)
                        MessageBox.Show("The transaction was approved for " + BCR.Amount
                            + " which is an amount not equal to the requested amount of " + _BCtransaction.TransactionData.Amount
                            + ". Please provide alternate payment to complete transaction");
                }

                if (_TT == TransactionType.Authorize)
                {
                    if (CredentialRequired())
                        _BCtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Authorize(_sessionToken, _BCtransaction, _applicationProfileId, _merchantProfileId, _serviceIdOrWorkflowId));
                    //Always Verify that the requested amount and approved amount are the same.
                    BankcardTransactionResponsePro BCR = new BankcardTransactionResponsePro();
                    BCR = (BankcardTransactionResponsePro)_Response[0];
                    if (_BCtransaction.TransactionData.Amount != BCR.Amount)
                        MessageBox.Show("The transaction was approved for " + BCR.Amount
                            + " which is an amount not equal to than the requested amount of " + _BCtransaction.TransactionData.Amount
                            + ". Please provide alternate payment to complete transaction");
                }
                if (_TT == TransactionType.Capture)
                {
                    if (CredentialRequired())
                        _BCDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Capture(_sessionToken, _BCDifferenceData, _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.CaptureAll)
                {
                    if (CredentialRequired())
                        _BCDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response = Cwsbc.CaptureAll(_sessionToken, _CaptureDifferenceData, _BatchIds, _applicationProfileId,
                                                 _merchantProfileId, _serviceId);
                }
                if (_TT == TransactionType.CaptureAllAsync)
                {
                    if (CredentialRequired())
                        _BCDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.CaptureAllAsync(_sessionToken, _CaptureDifferenceData, _BatchIds,
                                                        _applicationProfileId, _merchantProfileId, _serviceId));
                }
                if (_TT == TransactionType.CaptureSelective)
                {
                    if (CredentialRequired())
                        _BCDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response = Cwsbc.CaptureSelective(_sessionToken, _TransactionIds, _CaptureDifferenceData,
                                                       _applicationProfileId, _serviceId);
                }
                if (_TT == TransactionType.CaptureSelectiveAsync)
                {
                    if (CredentialRequired())
                        _BCDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.CaptureSelectiveAsync(_sessionToken, _TransactionIds, _CaptureDifferenceData,
                                                              _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.ReturnById)
                {
                    if (CredentialRequired())
                        _RDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.ReturnById(_sessionToken, _RDifferenceData, _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.Return)
                {
                    if (CredentialRequired())
                        _BCtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.ReturnUnlinked(_sessionToken, _BCtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                }
                if (_TT == TransactionType.Adjust)
                {
                    if (CredentialRequired())
                        _ADifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Adjust(_sessionToken, _ADifferenceData, _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.Undo)
                {
                    if (CredentialRequired())
                        _UDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Undo(_sessionToken, _UDifferenceData, _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.QueryAccount)
                {
                    if (CredentialRequired())
                        _BCtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.QueryAccount(_sessionToken, _BCtransaction, _applicationProfileId,
                                                     _merchantProfileId, _serviceId));
                }
                if (_TT == TransactionType.Verify)
                    _Response.Add(Cwsbc.Verify(_sessionToken, _BCtransaction, _applicationProfileId, _merchantProfileId, _serviceId));

                List<ResponseDetails> RD = new List<ResponseDetails>();//Convert the response to response details so that we can report on the UI
                if (_Response != null)
                {
                    foreach (Response r in _Response)
                    {
                        if (_SendAcknowledge && r.TransactionId.Length > 0)
                            Cwsbc.Acknowledge(_sessionToken, r.TransactionId, _applicationProfileId, _serviceId);

                        ResponseDetails RDN = new ResponseDetails(0.00M, r, _TT.ToString(), _serviceIdOrWorkflowId, _merchantProfileId, true, TypeCardType.NotSet, "");
                        MessageBox.Show(ProcessResponse(ref RDN));//Pass as reference so we can extract more values from the response
                        RD.Add(RDN);
                    }
                }

                return RD;
            }
            catch (EndpointNotFoundException)
            {
                //In this case the SvcEndpoint was not available. Try the same logic again with the alternate Endpoint
                try
                {
                    SetTxnEndpoint();//Change the endpoint to use the backup.

                    //TODO : Add a copy of the code above once fully tested out.

                    return null;

                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show("Neither the primary or secondary endpoints are available. Unable to process.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to AuthorizeAndCapture\r\nError Message : " + ex.Message, "AuthorizeAndCapture Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (System.TimeoutException te)
            {
                //A timeout has occured. Prompt the user if they'd like to query for the last transaction submitted
                if(_BCtransaction != null)
                {
                    DialogResult Result;
                    Result = MessageBox.Show("A timeout has occured. Would you like to query 'RequestTransaction' to obtain transactions with the exact same TenderData? To avoid duplicate charges your code will need to reconcile transactions.",
                                "Request Transaction", MessageBoxButtons.YesNo);
                    if (Result == DialogResult.Yes)
                    {
                        RequestTransaction(_BCtransaction.TenderData);
                    }
                    else { throw te; }
                }
                else{throw te;}
            }
            catch (Exception ex)
            {
                string strErrorId;
                string strErrorMessage;
                if (_FaultHandler.handleTxnFault(ex, out strErrorId, out strErrorMessage))
                { MessageBox.Show(strErrorId + " : " + strErrorMessage); }
                else { MessageBox.Show(ex.Message); }
            }

            return null;
        }
コード例 #36
0
        private void cmdAdjust_Click(object sender, EventArgs e)
        {
            if (ChkLstTransactionsProcessed.CheckedItems.Count == 0) { MessageBox.Show("Please Select (Check) Authorize transactions for Adjust"); return; }
            //Check to see if this transaction type is supported
            if (!SupportedTxnTypes.Adjust) { MessageBox.Show("Adjust Not Supported"); return; }

            Cursor = Cursors.WaitCursor;

            List<ResponseDetails> response = new List<ResponseDetails>();
            if (_bcs != null) //Process a BankCard Transaction
            {
                try
                {
                    BankcardTransaction BCtransaction = SetBankCardTxnData();
                    Adjust aTransaction = new Adjust();

                    if (_bcs.Tenders.CreditAuthorizeSupport == CreditAuthorizeSupportType.AuthorizeOnly)
                    {//For Terminal Capture use Authorize
                        response = Helper.ProcessBCPTransaction(TransactionType.Authorize, BCtransaction, null, null, null, null, null, null, null, ChkAcknowledge.Checked, ChkUserWorkflowId.Checked);
                    }
                    else
                    {//For Host Capture use AuthorizeAndCapture
                        response = Helper.ProcessBCPTransaction(TransactionType.AuthorizeAndCapture, BCtransaction, null, null, null, null, null, null, null, ChkAcknowledge.Checked, ChkUserWorkflowId.Checked);
                    }
                    if (response.Count < 1) { return; }
                    ChkLstTransactionsProcessed.Items.Add(response[0]);
                    BankcardTransactionResponse BCR = (BankcardTransactionResponse)response[0].Response; 
                    string strTransactionId = BCR.TransactionId;

                    //Now Let's Adjust the transaction
                    aTransaction.TransactionId = strTransactionId;
                    aTransaction.Amount = 12.00M;
                    response = Helper.ProcessBCPTransaction(TransactionType.Adjust, null, null, null, null, aTransaction, null, null, null, ChkAcknowledge.Checked, false);
                    if (response.Count < 1) { return; }
                    ChkLstTransactionsProcessed.Items.Add(response[0]);
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
            else if (_ecks != null) //Process as a Check transaction
            {
                try
                {
                    MessageBox.Show(@"Placeholder for ECK code. Please ask your solution consultant for an example");
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
        }