Example #1
0
        private static async Task Send(HttpContext httpContext)
        {
            Socket handler = httpContext.workSocket;

            Response response = new Response
            {
                Version = "HTTP/1.1",
                Code    = "200 OK"
            };

            response.Add("Server", "PoldoServer");
            response.Add("Connection", "close");
            httpContext.Response = response;


            await poldoMiddlewareManager.Invoke(httpContext);

            StringBuilder str = new StringBuilder();

            str.Append("<!DOCTYPE html>\r\n");
            str.Append("<html class=\"client -nojs\" lang=\"it\" dir=\"ltr\">\r\n");
            str.Append("<head>\r\n");
            str.Append("<meta charset=\"UTF -8\" />\r\n");
            str.Append("<title>POLDO</title>\r\n");
            str.Append("<body>\r\n");
            str.Append("<div style=\"width: 200px; height: 200px; background: red; \"></div>");
            str.Append("</body>\r\n");
            str.Append("</html>");
            StringBuilder strBuilder = response.ToStringBuilder(str.ToString());

            byte[] byteData = Encoding.ASCII.GetBytes(strBuilder.ToString());
            // Begin sending the data to the remote device.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                              new AsyncCallback(SendCallback), handler);
        }
Example #2
0
            public IActionResult GatherCallback([FromQuery] string digits, [FromQuery] string inboundCallId, [FromQuery] string conferenceNumber)
            {
                var bxmlResponse = new Response();

                switch (digits)
                {
                case "1":
                    // join to the conference
                    bxmlResponse.Add(new SpeakSentence {
                        Sentence = "Connecting to your call", Voice = "julie"
                    });
                    bxmlResponse.Add(new Conference {
                        From = conferenceNumber
                    });
                    break;

                case "2":
                    // redirect to voice mail
                    bxmlResponse.Add(new Redirect {
                        Context = inboundCallId, RequestUrl = "/demo/voicemailCallback"
                    });
                    break;

                default:
                    return(new NoContentResult());
                }
                return(new ContentResult {
                    Content = bxmlResponse.ToXml(), ContentType = "text/xml"
                });
            }
Example #3
0
        public async Task <string> GatherCallback()
        {
            string json;

            using (var reader = new StreamReader(Request.Body))
            {
                json = await reader.ReadToEndAsync();
            }

            dynamic      gatherEvent  = JsonConvert.DeserializeObject <dynamic>(json);
            string       digits       = gatherEvent.digits;
            const string SUCCESS_FILE = "https://bw-demo.s3.amazonaws.com/tada.wav";
            const string FAIL_FILE    = "https://bw-demo.s3.amazonaws.com/fail.wav";

            string    media     = digits.Equals("11") ? SUCCESS_FILE : FAIL_FILE;
            PlayAudio playAudio = new PlayAudio();

            playAudio.Url = media;
            Hangup hangup = new Hangup();

            Response response = new Response();

            response.Add(playAudio);
            response.Add(hangup);

            string bxml = response.ToBXML();

            return(bxml);
        }
Example #4
0
        public Response SaveDatabaseDictionary(string project, string application, DatabaseDictionary dict)
        {
            StringBuilder sb       = new StringBuilder();
            Response      response = new Response();

            try
            {
                sb.Append(dbDictionaryFullFilePath);
                sb.Append("DatabaseDictionary.");
                sb.Append(project);
                sb.Append(".");
                sb.Append(application);
                sb.Append(".xml");
                Utility.Write <DatabaseDictionary>(dict, sb.ToString());

                response.Add("Database Dictionary saved successfully");
                return(response);
            }
            catch (Exception ex)
            {
                _logger.Error("Error in SaveDatabaseDictionary: " + ex);
                response.Add("Error in saving database dictionary" + ex.Message);
                return(response);
            }
        }
Example #5
0
        //====================================================================================
        //Form Constructor
        //------------------------------------------------------------------------------------
        public FormClient()
        {
            InitializeComponent();

            toolStripComboBoxCardSize.SelectedIndex = 1;

            // Hack to fix the ugly selection lines on the splitters
            menuStrip1.Select();



            //Debug code to let me test the GUI without having all the network code done.
            //This is all dummy data for testing rendering.
            //This data will eventually come from the server.
            Random RNG = new Random();

            /*
             * public List<Player> Players = new List<Player>();
             * public List<Response> Responses = new List<Response>();
             * public bool GameOver = false;
             */
            status.currentBlack = new BlackCard("My _____ needs a heavy dose of _____.", 2);

            dataGridPlayerList.Rows.Add("Cadika", RNG.Next(15), "CZAR");
            dataGridPlayerList.Rows.Add("Skylark", RNG.Next(15), "");
            dataGridPlayerList.Rows.Add("Conrad", RNG.Next(15), "");
            dataGridPlayerList.Rows.Add("Damen", RNG.Next(15), "");
            dataGridPlayerList.Rows.Add("Jacen", RNG.Next(15), "");

            Hand.Add(new Card("Test Card #1"));
            Hand.Add(new Card("Test Card #2. \nCard #1 had little text."));
            Hand.Add(new Card("Test Card #3. \nThese cards need to test several different lengths of cards."));
            Hand.Add(new Card("Test Card #4. \nSupport for scaling cards with window size is still in the works."));
            Hand.Add(new Card("Test Card #5. \nCard size is adjustable under Options. Please test on high and low DPI conditions."));
            Hand.Add(new Card("Test Card #6"));
            Hand.Add(new Card("Test Card #7 with abnormally long text to test the Card.Render() method. I hope this works because it seems unlikely that any card is going to be longer than this, but the program should be ready for this. This message is finally too long!"));

            Response newResponse = new Response();

            newResponse.Add(new Card("Giant Head"));
            newResponse.Add(new Card("Aspirin"));
            Responses.Add(newResponse);
            newResponse = new Response();
            newResponse.Add(new Card("Aunt"));
            newResponse.Add(new Card("Humility"));
            Responses.Add(newResponse);
            newResponse = new Response();
            newResponse.Add(new Card("Professor"));
            newResponse.Add(new Card("Acid"));
            Responses.Add(newResponse);
            newResponse = new Response();
            newResponse.Add(new Card("PC"));
            newResponse.Add(new Card("GabeN's Love"));
            Responses.Add(newResponse);

            RenderHand();
            RenderBlackCard();
            RenderResponses();
        }
Example #6
0
        /// <summary>
        /// Check each matchItem to see if the matchString starts with that item. Returns the best (longest) match, or null.
        /// </summary>
        /// <param name="matchItems">List of items to compare against the matchString.</param>
        /// <param name="matchString">The string that will be compared against the matchItems.</param>
        /// <param name="arg">The argument being matched.</param>
        /// <param name="matchLowerInvariants">If true, matchItems and matchString will be compared all in lower-case form, increasing forgiveness for capitalization errors.</param>
        private string BestMatch(List <string> matchItems, string matchString, Arg arg, bool matchLowerInvariants = true)
        {
            List <string> matches = Match(matchItems, matchString, arg, matchLowerInvariants);

            if (matches != null && matches.Count > 0)
            {
                // Detect if two identical matches were found
                if (matches.Count > 1 && (matches[0] ?? "") == (matches[1] ?? ""))
                {
                    // Failed - indeterminate match
                    if (arg.IsRequired)
                    {
                        IsValid = false;
                        Response.Add("Command Failed: There was more than one match for the " + arg.Name + " parameter.");
                    }
                    return(null);
                }
                // Otherwise the result is the first (longest) match
                else
                {
                    return(matches[0]);
                }
            }
            else
            {
                // Failed: Match not found
                if (arg.IsRequired)
                {
                    IsValid = false;
                    Response.Add("Command Failed: Unable to find " + arg.Name + ".");
                }
                return(null);
            }
        }
Example #7
0
        /// <summary>
        /// A request was received from the parser.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRequest(object sender, FactoryRequestEventArgs e)
        {
            _context = this;
            Response = HttpFactory.Current.Get <IResponse>(this, e.Request);
            _logger.Debug("Received '" + e.Request.Method + " " + e.Request.Uri.PathAndQuery + "' from " +
                          Socket.RemoteEndPoint);

            // keep alive.
            if (e.Request.Connection != null && e.Request.Connection.Type == ConnectionType.KeepAlive)
            {
                Response.Add(new StringHeader("Keep-Alive", "timeout=5, max=100"));

                // refresh timer
                if (_keepAlive != null)
                {
                    _keepAlive.Change(_keepAliveTimeout, _keepAliveTimeout);
                }
            }

            Request = e.Request;
            CurrentRequestReceived(this, new RequestEventArgs(this, e.Request, Response));
            RequestReceived(this, new RequestEventArgs(this, e.Request, Response));

            //
            if (Response.Connection.Type == ConnectionType.KeepAlive)
            {
                if (_keepAlive == null)
                {
                    _keepAlive = new Timer(OnConnectionTimeout, null, _keepAliveTimeout, _keepAliveTimeout);
                }
            }

            RequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
            CurrentRequestCompleted(this, new RequestEventArgs(this, e.Request, Response));
        }
Example #8
0
        public CurrenciesResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <CurrenciesController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _currencyLocalizer = localizer;

            Currency currency;

            try
            {
                currency = obj as Currency;
            }
            catch (Exception)
            {
                currency = new Currency {
                    ID = 0
                };
            }

            var responseObj = currency;

            if (currency != null)
            {
                responseObj = currency.ID == 0 ? null : currency;
            }

            if (obj is ICollection)
            {
                key = "Currencies";
                Response.Add(_currencyLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_currencyLocalizer[key].Value, responseObj);
            }
        }
Example #9
0
        public PaymentMethodsResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <PaymentMethodsController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _currencyLocalizer = localizer;

            PaymentMethod paymentMethod;

            try
            {
                paymentMethod = obj as PaymentMethod;
            }
            catch (Exception)
            {
                paymentMethod = new PaymentMethod {
                    ID = 0
                };
            }

            var responseObj = paymentMethod;

            if (paymentMethod != null)
            {
                responseObj = paymentMethod.ID == 0 ? null : paymentMethod;
            }

            if (obj is ICollection)
            {
                key += "s";
                Response.Add(_currencyLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_currencyLocalizer[key].Value, responseObj);
            }
        }
Example #10
0
        public UsersResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <UsersController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _recipientLocalizer = localizer;

            UserDetailsModel userDetails;

            try
            {
                userDetails = obj as UserDetailsModel;
            }
            catch (Exception)
            {
                userDetails = new UserDetailsModel {
                    UserID = 0
                };
            }

            var responseObj = userDetails;

            if (userDetails != null)
            {
                responseObj = userDetails.UserID == 0 ? null : userDetails;
            }

            if (obj is ICollection)
            {
                key += "s";
                Response.Add(_recipientLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_recipientLocalizer[key].Value, responseObj);
            }
        }
Example #11
0
        public SavedCardsResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <SavedCardsController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _recipientLocalizer = localizer;

            SavedCard card;

            try
            {
                card = obj as SavedCard;
            }
            catch (Exception)
            {
                card = new SavedCard {
                    ID = 0
                };
            }

            var responseObj = card;

            if (card != null)
            {
                responseObj = card.ID == 0 ? null : card;
            }

            if (obj is ICollection)
            {
                key += "s";
                Response.Add(_recipientLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_recipientLocalizer[key].Value, responseObj);
            }
        }
Example #12
0
        public WalletAccountsResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <WalletAccountsController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _recipientLocalizer = localizer;

            WalletAccount walletAccount;

            try
            {
                walletAccount = obj as WalletAccount;
            }
            catch (Exception)
            {
                walletAccount = new WalletAccount {
                    ID = 0
                };
            }

            var responseObj = walletAccount;

            if (walletAccount != null)
            {
                responseObj = walletAccount.ID == 0 ? null : walletAccount;
            }

            if (obj is ICollection)
            {
                key += "s";
                Response.Add(_recipientLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_recipientLocalizer[key].Value, responseObj);
            }
        }
Example #13
0
        public BankAccountsResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <BankAccountsController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _bankAccountLocalizer = localizer;

            BankAccount bankAccount;

            try
            {
                bankAccount = obj as BankAccount;
            }
            catch (Exception)
            {
                bankAccount = new BankAccount {
                    ID = 0
                };
            }

            var responseObj = bankAccount;

            if (bankAccount != null)
            {
                responseObj = bankAccount.ID == 0 ? null : bankAccount;
            }

            if (obj is ICollection)
            {
                key = "BankAccounts";
                Response.Add(_bankAccountLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_bankAccountLocalizer[key].Value, responseObj);
            }
        }
Example #14
0
        public CountriesResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <CountriesController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _recipientLocalizer = localizer;

            Country country;

            try
            {
                country = obj as Country;
            }
            catch (Exception)
            {
                country = new Country {
                    ID = 0
                };
            }

            var responseObj = country;

            if (country != null)
            {
                responseObj = country.ID == 0 ? null : country;
            }

            if (obj is ICollection)
            {
                key = "Countries";
                Response.Add(_recipientLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_recipientLocalizer[key].Value, responseObj);
            }
        }
Example #15
0
        private void CheckMandatoryFields()
        {
            isValid = false;

            List <string> keys = new List <string>(Parameters.AllKeys);

            foreach (string field in mandatoryFields)
            {
                if (keys.Contains(field))
                {
                    continue;
                }

                Response.Add(FailureKey, (BEncodedString)("mandatory announce parameter " + field + " in query missing"));
                return;
            }
            byte[] hash = UriHelper.UrlDecode(Parameters["info_hash"]);
            if (hash.Length != 20)
            {
                Response.Add(FailureKey, (BEncodedString)(string.Format("infohash was {0} bytes long, it must be 20 bytes long.", hash.Length)));
                return;
            }
            infoHash = new InfoHash(hash);
            isValid  = true;
        }
        public Response <T> Deserialize <T>(string row) where T : ISplitted, new()
        {
            try
            {
                var response = new Response <T>(true);

                var output = new T();
                var valid  = output.IsValidRow(row);
                if (!valid.Success)
                {
                    return(new Response <T>(valid));
                }

                var props = Reflection.GetPropertiesWithAttribute <T, Split>();

                foreach (var prop in props)
                {
                    var value = prop.Attr.GetValue(row, prop.Type);
                    response.Add(value);

                    if (value.Success)
                    {
                        prop.Prop.SetValue(output, value.Data);
                    }
                }

                return(response.SetData(output));
            }
            catch (Exception ex)
            {
                return(new Response <T>(ex));
            }
        }
Example #17
0
        public static Response <FileRef> Get(string filePath, byte[] content)
        {
            var fileref = new FileRef()
            {
                FilePath = filePath, FileName = new System.IO.FileInfo(filePath).Name
            };
            var response = new Response <FileRef>(true).SetData(fileref);
            var alltext  = Encoding.UTF8.GetString(content);
            var rows     = alltext.Split(new char[] { '\r', '\n' }).Where(p => !string.IsNullOrEmpty(p));

            var splitter = new SIR.Common.Batch.BatchSplitter();

            foreach (var row in rows)
            {
                switch (row.Substring(0, 2))
                {
                case FileHeader.Index:
                    var header = splitter.Deserialize <FileHeader>(row);
                    response.Add(header);

                    if (fileref.Header != null)
                    {
                        return(new Response <FileRef>($"El archivo {fileref.FilePath} posee mƔs de un registro con ƭndice de Cabecera."));
                    }

                    fileref.Header = header.Data;
                    break;

                case FileDependencia.Index:
                    var dependencia = splitter.Deserialize <FileDependencia>(row);
                    response.Add(dependencia);

                    fileref.Dependencias.Add(dependencia.Data);
                    break;

                case FileDetalle.Index:
                    var detalle = splitter.Deserialize <FileDetalle>(row);
                    response.Add(detalle);

                    fileref.Detalles.Add(detalle.Data);
                    break;
                }
            }

            return(response);
        }
Example #18
0
        public ApiBuilder <T> CreateRequest(string uri, RequestMethod method = RequestMethod.GET, Dictionary <string, string> body = null)
        {
            if (uri == "")
            {
                Logger.Instance.WriteLine("Incorrect URI for run API request.", LogLevel.Error);

                return(this);
            }

            try
            {
                Task <string> awaiter;

                if (method == RequestMethod.GET)
                {
                    awaiter = GetAsync(uri);
                    awaiter.Wait();
                }
                else
                {
                    awaiter = PostAsync(uri, body);
                    awaiter.Wait();
                }

                try
                {
                    if (RequestHeaders.Count > 0)
                    {
                        foreach (var header in RequestHeaders)
                        {
                            Http.DefaultRequestHeaders.Remove(header.Key);
                        }

                        RequestHeaders.Clear();
                    }

                    var response = JsonConvert.DeserializeObject <T[]>(awaiter.GetAwaiter().GetResult());

                    foreach (var item in response)
                    {
                        Response.Add(item);
                    }
                }
                catch (Exception)
                {
                    var response = JsonConvert.DeserializeObject <T>(awaiter.GetAwaiter().GetResult());

                    Response.Add(response);
                }
            }
            catch (Exception ex)
            {
                //ex.Report("UNKNOWN WEB ERROR");
                ex.ToLog(LogLevel.Error);
            }

            return(this);
        }
        public Response Summary()
        {
            Response response = new Response();
              //  response.Add("AccountTests", accountService.GetAccountTestSummary());
              response.Add("CardSummary", summaryService.GetMasterDataSummary<Card>(card => card.Class));
              //response.Add("EquipSummary", summaryService.GetMasterDataSummary<Equip>());
              //response.Add("AreaSummary", summaryService.GetMasterDataSummary<Area>());

              return response;
        }
Example #20
0
        private Response ReceiveResponse()
        {
            Response response = new Response();

            while (!response.Valid)
            {
                response.Add(ReceiveReply());
            }

            return(response);
        }
Example #21
0
        public void TestToXml3()
        {
            var response = new Response();

            response.Add(new TestItem
            {
                StringValue = "Test",
                Attribute1  = 10
            });
            Assert.Equal(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Response>\n  <TestItem Attribute1=\"10\">\n    <StringValue>Test</StringValue>\n  </TestItem>\n</Response>",
                response.ToXml().Replace("\r\n", "\n"));
        }
Example #22
0
        public void TestToXmlWithNested()
        {
            var response = new Response();

            response.Add(new TestItem
            {
                Attribute1 = 10,
                Nested     = new TestItem {
                    Attribute1 = 20
                }
            });
            Assert.Equal(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Response>\n  <TestItem Attribute1=\"10\">\n    <Nested Attribute1=\"20\" />\n  </TestItem>\n</Response>",
                response.ToXml().Replace("\r\n", "\n"));
        }
        public Response <Twitter> BuscarTweets()
        {
            var response = new Response <Twitter>();

            try
            {
                var auth = new MvcAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey      = "###############",
                        ConsumerSecret   = "##############",
                        OAuthToken       = OAuthKeys.TwitterAccessToken,
                        OAuthTokenSecret = OAuthKeys.TwitterAccessTokenSecret,
                    }
                };
                auth.AuthorizeAsync();

                var ctx = new TwitterContext(auth);

                List <Search> searchResponse =
                    (from search in ctx.Search
                     where search.Type == SearchType.Search &&
                     search.Query == "#vexpro"
                     select search)
                    .ToList();

                var rnd   = new Random();
                var tweet = searchResponse[rnd.Next(searchResponse.Count)];

                if (tweet != null)
                {
                    response.Result = new Twitter
                    {
                        status = tweet.Statuses.ToString()
                    };
                    return(response);
                }
                ;
            }
            catch (Exception)
            {
                response.Add("Ocorreu um problema ");
                return(response);
            }
            return(response);
        }
Example #24
0
        public RecipientsResponse(string key, object obj, int state, IStringLocalizer <SharedLocaleController> baseLocalizer, IStringLocalizer <RecipientsController> localizer)
            : base(key, obj, state, baseLocalizer)
        {
            _recipientLocalizer = localizer;

            switch (state)
            {
            case RecipientStatusCodes.MissingEmailandPhone:
                Response.Add(_baseLocalizer["Status"].Value, _baseLocalizer["Failed"].Value);
                Response.Add(_baseLocalizer["Message"].Value, _recipientLocalizer["please_provide_either_email_or_phone"].Value);
                break;

            default:
                break;
            }

            Recipient recipient;

            try
            {
                recipient = obj as Recipient;
            }
            catch (Exception)
            {
                recipient = new Recipient {
                    ID = 0
                };
            }

            var responseObj = recipient;

            if (recipient != null)
            {
                responseObj = recipient.ID == 0 ? null : recipient;
            }

            if (obj is ICollection)
            {
                key += "s";
                Response.Add(_recipientLocalizer[key].Value, obj);
            }
            else
            {
                Response.Add(_recipientLocalizer[key].Value, responseObj);
            }
        }
Example #25
0
        public void CloseZip()
        {
            Response.Add("fileSize", ZipFs.Length / 1024);
            Response["success"] = true;

            // Archive.Finish();

            Archive.Dispose();

            ZipFs.Seek(0, SeekOrigin.Begin);

            bytes = ZipFs.ToArray();

            // Archive.Close();
            ZipFs.Close();

            StepCompleted();
        }
        static void Main(string[] args)
        {
            Response resp = new Response();

            resp.AddRecord(new Dictionary <string, string>()
            {
                { "action", "http://some.domain/recordfile" },
                { "startOnDialAnswer", "true" }
            });

            Dial dial = new Dial(new Dictionary <string, string>()
            {
                { "callerId", "12222222222" },
            });

            dial.AddNumber("12121212121", new Dictionary <string, string>());
            resp.Add(dial);
            Console.WriteLine(resp.ToString());
        }
Example #27
0
        public string VoiceCallback()
        {
            SpeakSentence speakSentence = new SpeakSentence();

            speakSentence.Voice    = "kate";
            speakSentence.Sentence = "Let's play a game, what is 9 plus 2";

            Gather gather = new Gather();

            gather.SpeakSentence     = speakSentence;
            gather.MaxDigits         = 2;
            gather.GatherUrl         = "gather";
            gather.FirstDigitTimeout = 10;

            Response response = new Response();

            response.Add(gather);

            string bxml = response.ToBXML();

            return(bxml);
        }
Example #28
0
        public void GetProcessed()
        {
            if (!Verification.CheckServerLoad(Coin.Trend))
            {
                Response.Add("Error: Transaction declined.");
                Response.Add("Message: Transactions temporarily unavailable. We apologise for inconvinience.");
                return;
            }
            if (!Verification.CheckEnoughFunds(Amount, User.BalanceCoin))
            {
                Response.Add("Error: Transaction declined.");
                Response.Add("Message: Insufficient funds!");
                return;
            }
            double amountOfCoinYouPay = Amount;
            double amountOfUsdYouGet  = Math.Round(amountOfCoinYouPay * Coin.Price, 2);

            User.BalanceMoney += amountOfUsdYouGet;
            User.BalanceCoin  -= amountOfCoinYouPay;
            Response.Add("Message: Transaction accepted.");
            Response.Add($"Message: You get {amountOfUsdYouGet:0.00} Money for {amountOfCoinYouPay:0.000000} Coin.");
        }
Example #29
0
        InfoHash CheckMandatoryFields()
        {
            var keys = new List <string> (Parameters.AllKeys);

            foreach (string field in MandatoryFields)
            {
                if (keys.Contains(field))
                {
                    continue;
                }

                Response.Add(FailureKey, (BEncodedString)("mandatory announce parameter " + field + " in query missing"));
                return(null);
            }
            byte[] hash = UriHelper.UrlDecode(Parameters["info_hash"]);
            if (hash.Length != 20)
            {
                Response.Add(FailureKey, (BEncodedString)(
                                 $"infohash was {hash.Length} bytes long, it must be 20 bytes long."));
                return(null);
            }
            return(new InfoHash(hash));
        }
Example #30
0
        public void TestAllXml()
        {
            var resp = new Response();

            resp.AddConference("My room",
                               new Dictionary <string, string>()
            {
                { "callbackUrl", "http://foo.com/confevents/" },
                { "callbackMethod", "POST" },
                { "digitsMatch", "#0,99,000" }
            });

            Plivo.XML.Dial dial = new Plivo.XML.Dial(new
                                                     Dictionary <string, string>()
            {
                { "confirmSound", "http://foo.com/sound/" },
                { "confirmKey", "3" }
            });
            dial.AddNumber("18217654321",
                           new Dictionary <string, string>()
            {
                { "sendDigits", "wwww2410" }
            });
            dial.AddUser("sip:[email protected]",
                         new Dictionary <string, string>()
            {
                { "sendDigits", "wwww2410" }
            });
            resp.Add(dial);

            Plivo.XML.Dial dial1 = new Plivo.XML.Dial(new
                                                      Dictionary <string, string>()
            {
                { "timeout", "20" },
                { "action", "http://foo.com/dial_action/" }
            });

            dial1.AddNumber("18217654321",
                            new Dictionary <string, string>()
            {
            });

            Plivo.XML.Dial dial2 = new Plivo.XML.Dial(new
                                                      Dictionary <string, string>()
            {
            });
            dial2.AddNumber("15671234567",
                            new Dictionary <string, string>()
            {
            });
            resp.Add(dial1);
            resp.Add(dial2);

            resp.AddDTMF("12345",
                         new Dictionary <string, string>()
            {
            });

            Plivo.XML.GetDigits get_digits = new
                                             Plivo.XML.GetDigits("",
                                                                 new Dictionary <string, string>()
            {
                { "action", "http://www.foo.com/gather_pin/" },
                { "method", "POST" }
            });
            resp.Add(get_digits);

            get_digits.AddSpeak("Enter PIN number.",
                                new Dictionary <string, string>()
            {
            });
            resp.AddSpeak("Input not recieved.",
                          new Dictionary <string, string>()
            {
            });

            resp.AddHangup(new Dictionary <string, string>()
            {
                { "schedule", "60" },
                { "reason", "rejected" }
            });
            resp.AddSpeak("Call will hangup after a min.",
                          new Dictionary <string, string>()
            {
                { "loop", "0" }
            });

            resp.AddMessage("Hi, message from Plivo.",
                            new Dictionary <string, string>()
            {
                { "src", "12023222222" },
                { "dst", "15671234567" },
                { "type", "sms" },
                { "callbackUrl", "http://foo.com/sms_status/" },
                { "callbackMethod", "POST" }
            });

            resp.AddPlay("https://amazonaws.com/Trumpet.mp3",
                         new Dictionary <string, string>()
            {
            });

            Plivo.XML.PreAnswer answer = new
                                         Plivo.XML.PreAnswer();
            answer.AddSpeak("This call will cost $2 a min.",
                            new Dictionary <string, string>()
            {
            });
            resp.Add(answer);
            resp.AddSpeak("Thanks for dropping by.",
                          new Dictionary <string, string>()
            {
            });

            resp.AddRecord(new Dictionary <string, string>()
            {
                { "action", "http://foo.com/get_recording/" },
                { "startOnDialAnswer", "true" },
                { "redirect", "false" }
            });

            Plivo.XML.Dial dial3 = new Plivo.XML.Dial(new
                                                      Dictionary <string, string>()
            {
            });

            dial3.AddNumber("15551234567",
                            new Dictionary <string, string>()
            {
            });
            resp.Add(dial3);

            resp.AddSpeak("Leave message after the beep.",
                          new Dictionary <string, string>()
            {
            });
            resp.AddRecord(new Dictionary <string, string>()
            {
                { "action", "http://foo.com/get_recording/" },
                { "maxLength", "30" },
                { "finishOnKey", "*" }
            });
            resp.AddSpeak("Recording not received.",
                          new Dictionary <string, string>()
            {
            });

            resp.AddSpeak("Your call is being transferred.",
                          new Dictionary <string, string>()
            {
            });
            resp.AddRedirect("http://foo.com/redirect/",
                             new Dictionary <string, string>()
            {
            });

            resp.AddSpeak("Go green, go plivo.",
                          new Dictionary <string, string>()
            {
                { "loop", "3" }
            });

            resp.AddSpeak("I will wait 7 seconds starting now!",
                          new Dictionary <string, string>()
            {
            });
            resp.AddWait(new Dictionary <string, string>()
            {
                { "length", "7" }
            });
            resp.AddSpeak("I just waited 7 seconds.",
                          new Dictionary <string, string>()
            {
            });

            resp.AddWait(new Dictionary <string, string>()
            {
                { "length", "120" },
                { "beep", "true" }
            });
            resp.AddPlay("https://s3.amazonaws.com/abc.mp3",
                         new Dictionary <string, string>()
            {
            });

            resp.AddWait(new Dictionary <string, string>()
            {
                { "length", "10" }
            });
            resp.AddSpeak("Hello",
                          new Dictionary <string, string>()
            {
            });

            resp.AddWait(new Dictionary <string, string>()
            {
                { "length", "10" },
                { "silence", "true" },
                { "minSilence", "3000" }
            });
            resp.AddSpeak("Hello, welcome to the Jungle.",
                          new Dictionary <string, string>()
            {
            });

            var output = resp.ToString();

            // Console.WriteLine(output);
            Assert.Equal(
                "<Response>\n  <Conference callbackUrl=\"http://foo.com/confevents/\" callbackMethod=\"POST\" digitsMatch=\"#0,99,000\">My room</Conference>\n  <Dial confirmSound=\"http://foo.com/sound/\" confirmKey=\"3\">\n    <Number sendDigits=\"wwww2410\">18217654321</Number>\n    <User sendDigits=\"wwww2410\">sip:[email protected]</User>\n  </Dial>\n  <Dial timeout=\"20\" action=\"http://foo.com/dial_action/\">\n    <Number>18217654321</Number>\n  </Dial>\n  <Dial>\n    <Number>15671234567</Number>\n  </Dial>\n  <DTMF>12345</DTMF>\n  <GetDigits action=\"http://www.foo.com/gather_pin/\" method=\"POST\">\n    <Speak>Enter PIN number.</Speak>\n  </GetDigits>\n  <Speak>Input not recieved.</Speak>\n  <Hangup schedule=\"60\" reason=\"rejected\" />\n  <Speak loop=\"0\">Call will hangup after a min.</Speak>\n  <Message src=\"12023222222\" dst=\"15671234567\" type=\"sms\" callbackUrl=\"http://foo.com/sms_status/\" callbackMethod=\"POST\">Hi, message from Plivo.</Message>\n  <Play>https://amazonaws.com/Trumpet.mp3</Play>\n  <PreAnswer>\n    <Speak>This call will cost $2 a min.</Speak>\n  </PreAnswer>\n  <Speak>Thanks for dropping by.</Speak>\n  <Record action=\"http://foo.com/get_recording/\" startOnDialAnswer=\"true\" redirect=\"false\" />\n  <Dial>\n    <Number>15551234567</Number>\n  </Dial>\n  <Speak>Leave message after the beep.</Speak>\n  <Record action=\"http://foo.com/get_recording/\" maxLength=\"30\" finishOnKey=\"*\" />\n  <Speak>Recording not received.</Speak>\n  <Speak>Your call is being transferred.</Speak>\n  <Redirect>http://foo.com/redirect/</Redirect>\n  <Speak loop=\"3\">Go green, go plivo.</Speak>\n  <Speak>I will wait 7 seconds starting now!</Speak>\n  <Wait length=\"7\" />\n  <Speak>I just waited 7 seconds.</Speak>\n  <Wait length=\"120\" beep=\"true\" />\n  <Play>https://s3.amazonaws.com/abc.mp3</Play>\n  <Wait length=\"10\" />\n  <Speak>Hello</Speak>\n  <Wait length=\"10\" silence=\"true\" minSilence=\"3000\" />\n  <Speak>Hello, welcome to the Jungle.</Speak>\n</Response>",
                output.Replace(Environment.NewLine, "\n"));
        }
Example #31
0
        public void TestAllXml()
        {
            var resp = new Response();
            resp.AddConference("My room",
                new Dictionary<string, string>()
                {
                    {"callbackUrl", "http://foo.com/confevents/"},
                    {"callbackMethod", "POST"},
                    {"digitsMatch", "#0,99,000"}
                });

            Plivo.XML.Dial dial = new Plivo.XML.Dial(new
                Dictionary<string, string>()
                {
                    {"confirmSound", "http://foo.com/sound/"},
                    {"confirmKey", "3"}
                });
            dial.AddNumber("18217654321",
                new Dictionary<string, string>()
                {
                    {"sendDigits", "wwww2410"}
                });
            dial.AddUser("sip:[email protected]",
                new Dictionary<string, string>()
                {
                    {"sendDigits", "wwww2410"}
                });
            resp.Add(dial);

            Plivo.XML.Dial dial1 = new Plivo.XML.Dial(new
                Dictionary<string, string>()
                {
                    {"timeout", "20"},
                    {"action", "http://foo.com/dial_action/"}
                });

            dial1.AddNumber("18217654321",
                new Dictionary<string, string>() { });

            Plivo.XML.Dial dial2 = new Plivo.XML.Dial(new
                Dictionary<string, string>()
            { });
            dial2.AddNumber("15671234567",
                new Dictionary<string, string>() { });
            resp.Add(dial1);
            resp.Add(dial2);

            resp.AddDTMF("12345",
                new Dictionary<string, string>() { });

            Plivo.XML.GetDigits get_digits = new
                Plivo.XML.GetDigits("",
                    new Dictionary<string, string>()
                    {
                        {"action", "http://www.foo.com/gather_pin/"},
                        {"method", "POST"}
                    });
            resp.Add(get_digits);

            get_digits.AddSpeak("Enter PIN number.",
                new Dictionary<string, string>() { });
            resp.AddSpeak("Input not recieved.",
                new Dictionary<string, string>() { });

            resp.AddHangup(new Dictionary<string, string>()
            {
                {"schedule", "60"},
                {"reason", "rejected"}
            });
            resp.AddSpeak("Call will hangup after a min.",
                new Dictionary<string, string>()
                {
                    {"loop", "0"}
                });

            resp.AddMessage("Hi, message from Plivo.",
                new Dictionary<string, string>()
                {
                    {"src", "12023222222"},
                    {"dst", "15671234567"},
                    {"type", "sms"},
                    {"callbackUrl", "http://foo.com/sms_status/"},
                    {"callbackMethod", "POST"}
                });

            resp.AddPlay("https://amazonaws.com/Trumpet.mp3",
                new Dictionary<string, string>() { });

            Plivo.XML.PreAnswer answer = new
                Plivo.XML.PreAnswer();
            answer.AddSpeak("This call will cost $2 a min.",
                new Dictionary<string, string>() { });
            resp.Add(answer);
            resp.AddSpeak("Thanks for dropping by.",
                new Dictionary<string, string>() { });

            resp.AddRecord(new Dictionary<string, string>()
            {
                {"action", "http://foo.com/get_recording/"},
                {"startOnDialAnswer", "true"},
                {"redirect", "false"}
            });

            Plivo.XML.Dial dial3 = new Plivo.XML.Dial(new
                Dictionary<string, string>()
            { });

            dial3.AddNumber("15551234567",
                new Dictionary<string, string>() { });
            resp.Add(dial3);

            resp.AddSpeak("Leave message after the beep.",
                new Dictionary<string, string>() { });
            resp.AddRecord(new Dictionary<string, string>()
            {
                {"action", "http://foo.com/get_recording/"},
                {"maxLength", "30"},
                {"finishOnKey", "*"}
            });
            resp.AddSpeak("Recording not received.",
                new Dictionary<string, string>() { });

            resp.AddSpeak("Your call is being transferred.",
                new Dictionary<string, string>() { });
            resp.AddRedirect("http://foo.com/redirect/",
                new Dictionary<string, string>() { });

            resp.AddSpeak("Go green, go plivo.",
                new Dictionary<string, string>()
                {
                    {"loop", "3"}
                });

            resp.AddSpeak("I will wait 7 seconds starting now!",
                new Dictionary<string, string>() { });
            resp.AddWait(new Dictionary<string, string>()
            {
                {"length", "7"}
            });
            resp.AddSpeak("I just waited 7 seconds.",
                new Dictionary<string, string>() { });

            resp.AddWait(new Dictionary<string, string>()
            {
                {"length", "120"},
                {"beep", "true"}
            });
            resp.AddPlay("https://s3.amazonaws.com/abc.mp3",
                new Dictionary<string, string>() { });

            resp.AddWait(new Dictionary<string, string>()
            {
                {"length", "10"}
            });
            resp.AddSpeak("Hello",
                new Dictionary<string, string>() { });

            resp.AddWait(new Dictionary<string, string>()
            {
                {"length", "10"},
                {"silence", "true"},
                {"minSilence", "3000"}
            });
            resp.AddSpeak("Hello, welcome to the Jungle.",
                new Dictionary<string, string>() { });

            var output = resp.ToString();
            Console.WriteLine(output);
        }
Example #32
0
        /// <summary>Transmits the specified command APDU.</summary>
        /// <param name="commandApdu">The command APDU.</param>
        /// <returns>A response containing one ore more <see cref="ResponseApdu" />.</returns>
        public virtual Response Transmit(CommandApdu commandApdu) {
            if (commandApdu == null) {
                throw new ArgumentNullException("commandApdu");
            }

            // prepare send buffer (Check Command APDU and convert it to an byte array)
            byte[] sendBuffer;
            try {
                sendBuffer = commandApdu.ToArray();
            } catch (InvalidOperationException exception) {
                throw new InvalidApduException("Invalid APDU.", commandApdu, exception);
            }

            // create Response object
            var response = new Response();

            // prepare receive buffer (Response APDU)
            var receiveBufferLength = commandApdu.ExpectedResponseLength; // expected size that shall be returned
            var receiveBuffer = new byte[receiveBufferLength];

            var receivePci = new SCardPCI();

            var responseApdu = SimpleTransmit(
                sendBuffer,
                sendBuffer.Length,
                commandApdu.Case, // ISO case used by the Command APDU
                commandApdu.Protocol, // Protocol used by the Command APDU
                receivePci,
                ref receiveBuffer,
                ref receiveBufferLength);

            /* Check status word SW1SW2:
             * 
             * 1. 0x6cxx -> Set response buffer size Le <- SW2
             * 2. AND/OR 0x61xx -> More data can be read with GET RESPONSE
             */

            if (responseApdu.SW1 == (byte) SW1Code.ErrorP3Incorrect) {
                // Case 1: SW1=0x6c, Previous Le/P3 not accepted -> Set le = SW2
                var resendCmdApdu = (CommandApdu) commandApdu.Clone();
                if (responseApdu.SW2 == 0) {
                    resendCmdApdu.Le = 0; // 256
                    receiveBufferLength = 256 + 2; // 2 bytes for status word
                } else {
                    resendCmdApdu.Le = responseApdu.SW2;
                    receiveBufferLength = responseApdu.SW2 + 2; // 2 bytes for status word
                }

                receiveBuffer = new byte[receiveBufferLength];
                receivePci = new SCardPCI();

                try {
                    sendBuffer = resendCmdApdu.ToArray();

                    // Shall we wait until we re-send we APDU/TPDU?
                    if (RetransmitWaitTime > 0) {
                        Thread.Sleep(RetransmitWaitTime);
                    }

                    // send Command APDU again with new Le value
                    responseApdu = SimpleTransmit(
                        sendBuffer,
                        sendBuffer.Length,
                        resendCmdApdu.Case,
                        resendCmdApdu.Protocol,
                        receivePci,
                        ref receiveBuffer,
                        ref receiveBufferLength);
                } catch (InvalidOperationException ex) {
                    throw new InvalidApduException("Got SW1=0x6c. Retransmission failed because of an invalid APDU.",
                        resendCmdApdu, ex);
                }
            }

            if (responseApdu.SW1 == (byte) SW1Code.NormalDataResponse) {
                // Case 2: SW1=0x61, More data available -> GET RESPONSE

                /* The transmission system shall issue a GET RESPONSE command APDU (or TPDU)
                 * to the card by assigning the minimum of SW2 and Le to parameter Le (or P3)). 
                 * Le = min(Le,SW2) 
                 */
                var le = (commandApdu.Le < responseApdu.SW2)
                    ? commandApdu.Le
                    : responseApdu.SW2;

                do {
                    // add the last ResponseAPDU to the Response object
                    response.Add(responseApdu);
                    response.Add(receivePci);

                    var getResponseApdu = ConstructGetResponseApdu(ref le);

                    if (le == 0) {
                        receiveBufferLength = 256 + 2; // 2 bytes for status word
                    } else {
                        receiveBufferLength = le + 2; // 2 bytes for status word
                    }

                    receiveBuffer = new byte[receiveBufferLength];

                    try {
                        sendBuffer = getResponseApdu.ToArray();

                        // Shall we wait until we re-send we APDU/TPDU?
                        if (RetransmitWaitTime > 0) {
                            Thread.Sleep(RetransmitWaitTime);
                        }

                        // send Command APDU again with new Le value
                        responseApdu = SimpleTransmit(
                            sendBuffer,
                            sendBuffer.Length,
                            getResponseApdu.Case,
                            getResponseApdu.Protocol,
                            receivePci,
                            ref receiveBuffer,
                            ref receiveBufferLength);
                    } catch (InvalidOperationException ex) {
                        throw new InvalidApduException(
                            "Got SW1=0x61. Retransmission failed because of an invalid GET RESPONSE APDU.",
                            getResponseApdu, ex);
                    }

                    // In case there is more data available.
                    le = responseApdu.SW2;
                } while (
                    // More data available.
                    responseApdu.SW1 == (byte) SW1Code.NormalDataResponse ||
                    // Warning condition: data may be corrupted. Iso7816-4 7.1.5
                    (responseApdu.SW1 == (byte) SW1Code.WarningNVDataNotChanged && responseApdu.SW2 == 0x81));
            }

            response.Add(responseApdu);
            response.Add(receivePci);

            return response;
        }