/// <summary>
        /// Initiate an online transaction on behalf of the customer
        /// </summary>
        /// <param name="phone">The phone number sending money. </param>
        /// <param name="amount">The amount to be transacted</param>
        /// <param name="account">The account reference</param>
        /// <param name="description">This is any additional information/comment that can be sent along with the request from your system.</param>
        /// <param name="transactionType">This is the transaction type that is used to identify the transaction when sending the request to M-Pesa</param>
        public async Task <ApiResponse <PushStkResponse> > PushStk(string phone, string amount, string account, string description = "Lipa na Mpesa Online", TransactionTypeEnum transactionType = TransactionTypeEnum.CustomerPayBillOnline)
        {
            var requestId = ShortId.Generate(32);
            var response  = await PostHttp <PushStkResponse>("/stkpush/v1/processrequest", new Dictionary <string, string>
            {
                { "BusinessShortCode", Options.ShortCode },
                { "Password", Options.EncodedPassword },
                { "Timestamp", Options.Timestamp },
                { "TransactionType", transactionType.ToString() },
                { "Amount", amount },
                { "PartyA", phone },
                { "PartyB", Options.ShortCode },
                { "PhoneNumber", phone },
                { "CallBackURL", $"{Options.GetResultRL(requestId)}/lnm" },
                { "AccountReference", account },
                { "TransactionDesc", description }
            });

            var res = response.ToApiResponse();

            if (res.Success)
            {
                res.Data.RequestId = requestId;
            }
            return(res);
        }
Beispiel #2
0
        public void GenerateCreatesIdsWithoutNumbers()
        {
            string id = null;

            id = ShortId.Generate(false);
            id.Any(char.IsDigit).Should().BeFalse();
        }
Beispiel #3
0
        /// <summary>
        /// Enquires the balance for the specified Short Code
        /// </summary>
        /// <param name="identifierType">Type of orgnanization receiving the transaction</param>
        /// <param name="remarks">Comments that are sent along with the transaction.</param>
        public async Task <ApiResponse <Response> > QueryBalance(IdentifierTypeEnum identifierType = IdentifierTypeEnum.Organization, string remarks = "Query Account Balance")
        {
            if (identifierType == IdentifierTypeEnum.MSISDN)
            {
                throw new Exception("SDK does not support MSISDN");
            }

            var requestId = ShortId.Generate(32);

            var response = await PostHttp <Response>("/accountbalance/v1/query", new Dictionary <string, string>
            {
                { "Initiator", Options.Initiator },
                { "SecurityCredential", Options.SecurityCredential },
                { "CommandID", "AccountBalance" },
                { "PartyA", Options.ShortCode },
                { "IdentifierType", identifierType.ToString("D") },
                { "Remarks", remarks },
                { "QueueTimeOutURL", $"{Options.GetQueueTimeoutURL(requestId)}/balance" },
                { "ResultURL", $"{Options.GetResultRL(requestId)}/balance" },
            });

            var res = response.ToApiResponse();

            if (res.Success)
            {
                res.Data.RequestId = requestId;
            }
            return(res);
        }
Beispiel #4
0
        /// <summary>
        /// Check the status of a transaction
        /// </summary>
        /// <param name="transactionId">The trasaction Identifier</param>
        /// <param name="identifierType">Type of orgnanization receiving the transaction</param>
        /// <param name="phone">Used when identifierType is MSISDN</param>
        /// <param name="remarks">Comments that are sent along with the transaction.</param>
        /// <param name="occasion">Occasion</param>
        public async Task <ApiResponse <Response> > QueryTransactionStatus(string transactionId, IdentifierTypeEnum identifierType, string phone = null, string remarks = "TransactionStatus", string occasion = "TransactionStaus")
        {
            if (IdentifierTypeEnum.MSISDN == identifierType && string.IsNullOrEmpty(phone))
            {
                throw new ArgumentNullException("Phone cannot be null", nameof(phone));
            }

            var requestId = ShortId.Generate(32);

            var response = await PostHttp <Response>("/transactionstatus/v1/query", new Dictionary <string, string>
            {
                { "Initiator", Options.Initiator },
                { "SecurityCredential", Options.SecurityCredential },
                { "CommandID", "TransactionStatusQuery" },
                { "TransactionID", transactionId },
                { "PartyA", identifierType == IdentifierTypeEnum.MSISDN ? phone : Options.ShortCode },
                { "IdentifierType", identifierType.ToString("D") },
                { "QueueTimeOutURL", $"{ Options.GetQueueTimeoutURL(requestId)}/status" },
                { "ResultURL", $"{ Options.GetResultRL(requestId)}/status" },
                { "Remarks", remarks },
                { "Occasion", occasion }
            });

            var res = response.ToApiResponse();

            if (res.Success)
            {
                res.Data.RequestId = requestId;
            }
            return(res);
        }
Beispiel #5
0
        public IActionResult ShortenURL(Url url)
        {
            var authDb = new Authentication(_connectionString);
            var user   = authDb.GetByEmail(User.Identity.Name);

            var repo = new UrlRepository(_connectionString);

            if (!repo.DoesOriginalUrlExist(url.UrlOriginal))
            {
                url.UserId = user.Id;
                url.Views  = 0;
                var foo = true;
                while (foo)
                {
                    url.UrlShortened = ShortId.Generate(8);
                    if (!repo.DoesShortenedUrlExist(url.UrlShortened))
                    {
                        repo.AddUrl(url);
                        foo = false;
                        break;
                    }
                }
            }

            return(Json(url.UrlShortened));
        }
Beispiel #6
0
        /// <summary>
        /// Reverses an M-Pesa Transaction
        /// </summary>
        /// <param name="transactionId">Transaction Identifier</param>
        /// <param name="amount">The amount specified for the transaction</param>
        /// <param name="remarks">Comments that are sent along with the transaction.</param>
        /// <param name="occassion">Occasion</param>
        public async Task <ApiResponse <Response> > RequestReversal(string transactionId, string amount, string remarks = "Reversal", string occassion = "Reversal")
        {
            var requestId = ShortId.Generate(32);
            var response  = await PostHttp <Response>("/reversal/v1/request", new Dictionary <string, string>
            {
                { "Initiator", Options.Initiator },
                { "SecurityCredential", Options.SecurityCredential },
                { "CommandID", "TransactionReversal" },
                { "TransactionID", transactionId },
                { "Amount", amount },
                { "ReceiverParty", Options.ShortCode },
                { "RecieverIdentifierType", "11" },
                { "Remarks", remarks },
                { "Occasion", occassion },
                { "QueueTimeOutURL", $"{ Options.GetQueueTimeoutURL(requestId)}/reversal" },
                { "ResultURL", $"{ Options.GetResultRL(requestId)}/reversal" },
            });

            var res = response.ToApiResponse();

            if (res.Success)
            {
                res.Data.RequestId = requestId;
            }
            return(res);
        }
Beispiel #7
0
        public async Task <IActionResult> Create([FromForm] Job job, [FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Index)));
            }

            job.CompanyId = id;
            job.JobId     = ShortId.Generate(false, false);

            var currentUser = await _userManager.GetUserAsync(HttpContext.User);

            var company = await _db.Companies.FirstOrDefaultAsync(x => x.Id == job.CompanyId && x.Manager == currentUser);

            if (company == null)
            {
                return(RedirectToAction(nameof(Index)));
            }

            job.Company = company;

            await _db.Jobs.AddAsync(job);

            await _db.SaveChangesAsync();

            return(RedirectToAction(nameof(View), new { id }));
        }
        public async Task <IActionResult> ShortenUrl(string longUrl)
        {
            // get shortened url collection
            var shortenedUrlCollection = mongoDatabase.GetCollection <ShortenedUrl>("shortened-urls");
            // first check if we have the url stored
            var shortenedUrl = await shortenedUrlCollection
                               .AsQueryable()
                               .FirstOrDefaultAsync(x => x.OriginalUrl == longUrl);

            // if the long url has not been shortened
            if (shortenedUrl == null)
            {
                var shortCode = ShortId.Generate(length: 8);
                shortenedUrl = new ShortenedUrl
                {
                    CreatedAt   = DateTime.UtcNow,
                    OriginalUrl = longUrl,
                    ShortCode   = shortCode,
                    ShortUrl    = $"{ServiceUrl}?u={shortCode}"
                };
                // add to database
                await shortenedUrlCollection.InsertOneAsync(shortenedUrl);
            }

            return(View(shortenedUrl));
        }
Beispiel #9
0
        public async Task <string> JoinAsync(TbAirdrop data)
        {
            data.Email = data.Email.ToLower().Trim();
            var existed = dc.Table <TbAirdrop>().FirstOrDefault(x => data.Email == x.Email);

            if (existed != null)
            {
                await SendNotification(existed);

                return(existed.Code);
            }

            data.Symbol         = "ETH";
            data.Code           = "VC" + ShortId.Generate(true, false, 8).ToLower();
            data.ActivationCode = ShortId.Generate(true, false, 8);

            dc.DbTran(() =>
            {
                dc.Table <TbAirdrop>().Add(data);
            });

            await SendNotification(existed);

            return(data.Code);
        }
Beispiel #10
0
        public void GenerateCreatesIdsOfASpecifiedLength()
        {
            string id = null;

            id = ShortId.Generate(false, true, 8);
            id.Length.Should().Be(8);
        }
Beispiel #11
0
        public async Task <IActionResult> CreateFolder([FromBody] CreateFolderModel model)
        {
            p_logger.LogInformation("[FileController] Folder creating {0}", model.Name);

            var item = new Item {
                Id          = ShortId.Generate(10),
                DateCreated = DateTime.UtcNow,
                Name        = model.Name,
                Type        = ItemType.Folder,
                ParentId    = model.ParentId
            };

            p_ctx.Items.Add(item);
            await p_ctx.SaveChangesAsync();

            p_logger.LogInformation("[FileController] Folder created {0}", model.Name);
            return(Ok(new ItemVM {
                Id = item.Id,
                Name = item.Name,
                DateCreated = item.DateCreated,
                Extension = item.Extension,
                SizeInBytes = item.SizeInBytes,
                Type = item.Type
            }));
        }
Beispiel #12
0
        static List <string> CreateFromShortId()
        {
            var ids = from i in Enumerable.Range(1, 100)
                      select ShortId.Generate(true, false, 18);

            return(ids.ToList());
        }
Beispiel #13
0
        public void DoesNotAllowLengthsLessThan7()
        {
            Action action = () => { ShortId.Generate(6); };

            action.Should().ThrowExactly <ArgumentException>()
            .WithMessage("The specified length of 6 is less than the lower limit of 7.");
        }
Beispiel #14
0
        public ActionResult RenewToken([FromBody] Customer customer)

        {
            try
            {
                Response objResponse = new Response();

                var customerObj = db.customers.FirstOrDefault(x => x.Id == customer.Id);
                if (customerObj == null)
                {
                    return(this.NotFound("person doesnt exist"));
                }
                else
                {
                    customerObj.Token = ShortId.Generate(true, false);
                    db.customers.Update(customerObj);
                    db.SaveChanges();
                }


                objResponse.Data    = customerObj;
                objResponse.Status  = true;
                objResponse.Message = " Edit Successfully";


                return(Ok(objResponse));
            }

            catch (Exception e)
            {
                writeException.Write(e.Message, DateTime.Now, "Customer", "Post", "Admin");
                return(this.NotFound("Dosnt Create successfully"));
            }
        }
Beispiel #15
0
        public void GenerateCreatesIdsWithoutSpecialCharacters()
        {
            var id = ShortId.Generate(true, false);
            var ans = new[] { "-", "_" }.Any(x => id.Contains(x));

            ans.Should().BeFalse();
        }
Beispiel #16
0
        public Room CreateRoom(CreateRoomInputModel input)
        {
            // Map input to new room
            var room = new Room
            {
                RoomName = input.RoomName,

                Users = new List <User>(),

                CreatedDateTime = DateTime.UtcNow,
                UpdatedDateTime = DateTime.UtcNow,
            };

            // Generate unique short id for the RoomId
            var shortIdGenerationOptions = new GenerationOptions {
                Length = 8
            };

            do
            {
                room.RoomId = ShortId.Generate(shortIdGenerationOptions);
            } while (DbContext.Rooms.Any(r => r.RoomId == room.RoomId));

            DbContext.Rooms.Add(room);
            DbContext.SaveChanges();
            return(room);
        }
        public async Task <IActionResult> UploadImageMulti(List <IFormFile> files)
        {
            if (files == null || files.Count == 0)
            {
                return(Content("file not selected"));
            }


            // full path to file in temp location

            // var fileURL = this.Request.Scheme + "://" + this.Request.Host + "/upload/" + newFileName;


            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var newFileName = ShortId.Generate() + "_" + formFile.FileName;
                    var filePath    = Path.Combine(_env.WebRootPath, "upload", newFileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }



            // process uploaded files
            // Don't rely on or trust the FileName property without validation.
            return(RedirectToRoute("Images"));
            // return Ok(new ImageModel{ImageName=newFileName,ImagePath=fileURL});
        }
Beispiel #18
0
        public CommonReturnValue AddJsFile(string name)
        {
            if (string.IsNullOrWhiteSpace(name) || name.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
            {
                return(CommonReturnValue.UserError("Filenames may not be empty or contain special characters. Valid characters include A to Z and 0 to 9."));
            }

            if (this.JsFiles == null)
            {
                this.JsFiles = new List <JsFile>();
            }

            if (!name.ToLower().Trim().EndsWith(".js"))
            {
                name = name.Trim() + ".js";
            }

            var existing = this.JsFiles.FirstOrDefault(f => f.Filename.ToLower() == name.ToLower());

            if (existing != null)
            {
                return(CommonReturnValue.UserError($"The output file '{name}' already exists against this data source."));
            }

            var jsfile = new JsFile();

            jsfile.Filename = name;
            jsfile.Id       = ShortId.Generate();

            this.JsFiles.Add(jsfile);

            return(CommonReturnValue.Success());
        }
Beispiel #19
0
        /// <summary>
        /// Send Money from Business to Customer
        /// </summary>
        /// <param name="phone">Phone to Send money</param>
        /// <param name="amount">Amonunt</param>
        /// <param name="commandId">The type of transaction being perfomed</param>
        /// <param name="comment">Comments that are sent along with the transaction.</param>
        /// <param name="occasion">Occasion</param>
        public async Task <ApiResponse <Response> > SendMoney(string phone, string amount, B2CCommandIdEnum commandId = B2CCommandIdEnum.SalaryPayment, string comment = "B2C Payment", string occasion = "B2C Payment")
        {
            var requestId = ShortId.Generate(32);
            var response  = await PostHttp <Response>("/b2c/v1/paymentrequest", new Dictionary <string, string>
            {
                { "InitiatorName", Options.Initiator },
                { "SecurityCredential", Options.SecurityCredential },
                { "CommandID", commandId.ToString() },
                { "Amount", amount },
                { "PartyA", Options.ShortCode },
                { "PartyB", phone },
                { "Remarks", comment },
                { "Occassion", occasion },
                { "QueueTimeOutURL", $"{Options.GetQueueTimeoutURL(requestId)}/b2c" },
                { "ResultURL", $"{Options.GetResultRL(requestId)}/b2c" },
            });

            var res = response.ToApiResponse();

            if (res.Success)
            {
                res.Data.RequestId = requestId;
            }
            return(res);
        }
Beispiel #20
0
        public void GeneratedWithoutExceptions()
        {
            var    id     = string.Empty;
            Action action = () => { id = ShortId.Generate(); };

            action.Should().NotThrow();
            id.Should().NotBeEmpty();
        }
Beispiel #21
0
        public void GenerateShouldSucceedWithLengthOptions()
        {
            var options  = new GenerationOptions(length: 22);
            var response = ShortId.Generate(options);

            response.Should().NotBeNullOrEmpty();
            response.Length.Should().Be(22);
        }
Beispiel #22
0
        public void GenerateShouldSucceedWithoutOptions()
        {
            var response = ShortId.Generate();

            response.Should().NotBeNullOrEmpty();
            response.Length.Should().BeGreaterThan(6);
            response.Length.Should().BeLessThan(15);
        }
Beispiel #23
0
        public void GenerateThrowsWhenOptionsAreNull()
        {
            var action = () => { ShortId.Generate(null); };

            action
            .Should()
            .Throw <ArgumentNullException>();
        }
Beispiel #24
0
        public async Task <IActionResult> Post([FromBody] AddDScan command)
        {
            command.id = ShortId.Generate(true);
            await _commandDispatcher.DispatchAsync(command);

            var obj = new { id = command.id };

            return(Json(obj));
        }
Beispiel #25
0
 public IActionResult Index()
 {
     return(Json(new
     {
         controller = "Things",
         Action = "Index",
         Hash = ShortId.Generate(7)
     }));
 }
 public static string Rnd()
 {
     return(ShortId.Generate(new GenerationOptions
     {
         UseNumbers = false,
         UseSpecialCharacters = false,
         Length = 8
     }));
 }
        private async Task insertData(object name, object tele, object address)
        {
            string uuidGen = ShortId.Generate(true);
            var    conn    = new Connection();

            Console.WriteLine($"INSERT INTO CustomerI_Info SET id= '{uuidGen}', name= '{name}', address ='{address}', telephone = '{tele}'");
            conn.getData($"INSERT INTO CustomerI_Info SET id= '{uuidGen}', name= '{name}', address ='{address}', telephone = '{tele}'");
            await Task.CompletedTask;
        }
Beispiel #28
0
        public void SetSeedIsStable()
        {
            Action action = () =>
            {
                ShortId.Generate(0);
            };

            action.ShouldNotThrow();
        }
Beispiel #29
0
        public string GenerateCategoryID()
        {
            string today = DateTime.Now.ToString("yyMM");
            string id    = ShortId.Generate(true, false, 10).ToUpper();
            string result;

            result = today + "/" + id;
            return(result);
        }
Beispiel #30
0
 /// <summary>
 /// Generate a unique ID string
 /// </summary>
 public static string Generate()
 {
     return(ShortId.Generate(new GenerationOptions
     {
         Length = 14,
         UseSpecialCharacters = false,
         UseNumbers = true
     }));
 }