Пример #1
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
            }));
        }
Пример #2
0
        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});
        }
Пример #3
0
        public void GenerateCreatesIdsOfASpecifiedLength()
        {
            string id = null;

            id = ShortId.Generate(false, true, 8);
            id.Length.Should().Be(8);
        }
Пример #4
0
        public async Task CanDownloadDataBlobWithShortId()
        {
            var dataBlob = new DataBlob(IdGenerator.FromGuid(), new byte[] { 0x01, 0x02, 0x03 }, "testFile.bin");
            var shortId  = new ShortId("unittest_datablob", nameof(DataBlob), dataBlob.Id);

            if (!await analystDataApiClient.ExistsAsync <DataBlob>(dataBlob.Id))
            {
                await analystDataApiClient.InsertAsync(dataBlob, dataBlob.Id);
            }
            if (!await analystDataApiClient.ExistsAsync <ShortId>(shortId.Id))
            {
                await analystDataApiClient.InsertAsync(shortId, shortId.Id);
            }
            try
            {
                var httpHandler = new HttpClientHandler();
                var httpClient  = new HttpClient(httpHandler);
                var accessToken = analystAuthenticationResult.AccessToken;
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var uri = RequestUriBuilder.Build(ApiSetup.ApiConfiguration, "download/getFile");
                uri += $"?shortId={Uri.EscapeDataString(shortId.Id)}";
                var response = await httpClient.GetAsync(uri);

                Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
                Assert.That(response.Content.Headers.ContentDisposition, Is.Not.Null);
                var content = await response.Content.ReadAsByteArrayAsync();

                CollectionAssert.AreEqual(dataBlob.Data, content);
            }
            finally
            {
                await analystDataApiClient.DeleteAsync <ShortId>(shortId.Id);
                await TryDeleteDataBlob(dataBlob.Id);
            }
        }
Пример #5
0
        /// <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);
        }
Пример #6
0
        public void GenerateCreatesIdsWithoutNumbers()
        {
            string id = null;

            id = ShortId.Generate(false);
            id.Any(char.IsDigit).Should().BeFalse();
        }
Пример #7
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);
        }
Пример #8
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);
        }
Пример #9
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));
        }
Пример #10
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);
        }
Пример #11
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 }));
        }
Пример #12
0
        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));
        }
Пример #13
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);
        }
Пример #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"));
            }
        }
Пример #15
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);
        }
Пример #16
0
        public void ShouldAllowForACustomSeed()
        {
            Action action = () => { ShortId.SetSeed(678309202); };

            action.Should()
            .NotThrow <Exception>();
        }
Пример #17
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.");
        }
Пример #18
0
        static List <string> CreateFromShortId()
        {
            var ids = from i in Enumerable.Range(1, 100)
                      select ShortId.Generate(true, false, 18);

            return(ids.ToList());
        }
Пример #19
0
        public void GenerateCreatesIdsWithoutSpecialCharacters()
        {
            var id = ShortId.Generate(true, false);
            var ans = new[] { "-", "_" }.Any(x => id.Contains(x));

            ans.Should().BeFalse();
        }
Пример #20
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());
        }
Пример #21
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);
        }
Пример #22
0
        public void SetSeedThrowsWhenCharacterSetIsEmptyOrNull()
        {
            var    seed   = string.Empty;
            Action action = () => { ShortId.SetCharacters(seed); };

            action.Should().Throw <ArgumentException>()
            .WithMessage("The replacement characters must not be null or empty.");
        }
Пример #23
0
        public void GeneratedWithoutExceptions()
        {
            var    id     = string.Empty;
            Action action = () => { id = ShortId.Generate(); };

            action.Should().NotThrow();
            id.Should().NotBeEmpty();
        }
Пример #24
0
        public void GenerateShouldSucceedWithLengthOptions()
        {
            var options  = new GenerationOptions(length: 22);
            var response = ShortId.Generate(options);

            response.Should().NotBeNullOrEmpty();
            response.Length.Should().Be(22);
        }
Пример #25
0
        public void GenerateShouldSucceedWithoutOptions()
        {
            var response = ShortId.Generate();

            response.Should().NotBeNullOrEmpty();
            response.Length.Should().BeGreaterThan(6);
            response.Length.Should().BeLessThan(15);
        }
Пример #26
0
        public void GenerateThrowsWhenOptionsAreNull()
        {
            var action = () => { ShortId.Generate(null); };

            action
            .Should()
            .Throw <ArgumentNullException>();
        }
Пример #27
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);
        }
Пример #28
0
 public IActionResult Index()
 {
     return(Json(new
     {
         controller = "Things",
         Action = "Index",
         Hash = ShortId.Generate(7)
     }));
 }
Пример #29
0
        public void SetSeedThrowsWhenCharacterSetIsLessThan20Characters()
        {
            const string seed   = "783ujrcuei039kj4";
            Action       action = () => { ShortId.SetCharacters(seed); };

            action.Should().Throw <InvalidOperationException>()
            .WithMessage(
                "The replacement characters must be at least 20 letters in length and without whitespace.");
        }
Пример #30
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));
        }