public void RequestUriShouldBeBuiltCorrectly() { var mockResponse = new HttpResponseMessage(HttpStatusCode.OK); mockResponse.Content = new StringContent(String.Empty); var mockHttpMessageHandler = new MockHttpMessageHandler(mockResponse); string mockAddress = "http://127.0.0.1:5001"; string expectedRequestUri = String.Format("{0}/api/v0/commands", mockAddress); using (var client = new IpfsClient(new Uri(mockAddress), new HttpClient(mockHttpMessageHandler))) { client.Commands().Wait(); } Assert.IsTrue(Equals(mockHttpMessageHandler.LastRequest.RequestUri, expectedRequestUri)); }
public void RequestUriShouldBeBuiltCorrectlyWithFlagsNoArgs() { var mockResponse = new HttpResponseMessage(HttpStatusCode.OK); mockResponse.Content = new StringContent(String.Empty); var mockHttpMessageHandler = new MockHttpMessageHandler(mockResponse); string mockAddress = "http://127.0.0.1:5001"; string mockFileLocation = @"MyFilePath.txt"; string expectedRequestUri = String.Format("{0}/api/v0/diag/net?timeout=1&vis=d3", mockAddress, mockFileLocation); using (var client = new IpfsClient(new Uri(mockAddress), new HttpClient(mockHttpMessageHandler))) { client.Diag.Net("1", IpfsVis.D3).Wait(); } Assert.IsTrue(Equals(mockHttpMessageHandler.LastRequest.RequestUri, expectedRequestUri)); }
public void RequestUriShouldBeBuiltCorrectlyWithArgs() { var mockResponse = new HttpResponseMessage(HttpStatusCode.OK); mockResponse.Content = new StringContent("{\"Objects\":[{\"Hash\":\"QmXarR6rgkQ2fDSHjSY5nM2kuCXKYGViky5nohtwgF65Ec\",\"Links\":[{\"Name\":\"about\",\"Hash\":\"QmZTR5bcpQD7cFgTorqxZDYaew1Wqgfbd2ud9QqGPAkK2V\",\"Size\":1688,\"Type\":2},{\"Name\":\"contact\",\"Hash\":\"QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y\",\"Size\":200,\"Type\":2},{\"Name\":\"help\",\"Hash\":\"QmY5heUM5qgRubMDD1og9fhCPA6QdkMp3QCwd4s7gJsyE7\",\"Size\":322,\"Type\":2},{\"Name\":\"quick-start\",\"Hash\":\"QmXifYTiYxz8Nxt3LmjaxtQNLYkjdh324L4r81nZSadoST\",\"Size\":1707,\"Type\":2},{\"Name\":\"readme\",\"Hash\":\"QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB\",\"Size\":1102,\"Type\":2},{\"Name\":\"security-notes\",\"Hash\":\"QmTumTjvcYCAvRRwQ8sDRxh8ezmrcr88YFU7iYNroGGTBZ\",\"Size\":1027,\"Type\":2}]}]}\n"); var mockHttpMessageHandler = new MockHttpMessageHandler(mockResponse); string mockAddress = "http://127.0.0.1:5001"; string mockHash = "QmXarR6rgkQ2fDSHjSY5nM2kuCXKYGViky5nohtwgF65Ec"; string expectedRequestUri = String.Format("{0}/api/v0/ls?arg={1}", mockAddress, mockHash); using (var client = new IpfsClient(new Uri(mockAddress), new HttpClient(mockHttpMessageHandler))) { client.Ls(mockHash).Wait(); } Assert.IsTrue(Equals(mockHttpMessageHandler.LastRequest.RequestUri, expectedRequestUri)); }
public void ClientShouldThrowIfMethodCalledAfterBeingDisposed() { var mockResponse = new HttpResponseMessage(HttpStatusCode.OK); mockResponse.Content = new StringContent(String.Empty); var mockHttpMessageHandler = new MockHttpMessageHandler(mockResponse); string mockAddress = "http://127.0.0.1:5001"; var client = new IpfsClient(new Uri(mockAddress), new HttpClient(mockHttpMessageHandler)); client.Dispose(); try { client.Commands().Wait(); } catch (AggregateException ex) { throw ex.InnerException; } }
public IpfsService() { ipfs = new IpfsClient(Constants.IpfsHost); }
public IpfsProviderService(IpfsClient ipfsClient) { _ipfsClient = ipfsClient; }
/// <summary> /// Creates a new instance of a <see cref="BaseApi"/> /// </summary> /// <param name="client"></param> protected BaseApi(IpfsClient client) => Client = client;
public IpfsHashResolver(IpfsClient ipfs) { _ipfs = ipfs; }
public void AccessingIPFS() { IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001/api/"); file_hash = ipfs.FileSystem.AddFileAsync(file_path).Result.Id.Hash.ToString(); }
public static async System.Threading.Tasks.Task CheckMailAsync()//string toemail, string username, string password) { try { MailServer oServer = new MailServer("imap.asia.secureserver.net", "*****@*****.**", "Punnose1!", EAGetMail.ServerProtocol.Imap4); // Enable SSL connection. oServer.SSLConnection = true; // Set 993 SSL port oServer.Port = 993; MailClient oClient = new MailClient("TryIt"); try { oClient.Connect(oServer); } catch (Exception e) { Console.WriteLine("Total {0} unread email(s)\r\n", e.Message); } MongoDbRepository <MailInvoice> mi = new MongoDbRepository <MailInvoice>();// retrieve unread/new email only oClient.GetMailInfosParam.Reset(); oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly; //oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.; MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Receive email from IMAP4 server Mail oMail = oClient.GetMail(info); if (oMail.Attachments.Length > 0) { foreach (var attachment in oMail.Attachments) { if (attachment.ContentType == "application/json") { var stream = new MemoryStream(attachment.Content); IFormFile file = new FormFile(stream, 0, attachment.Content.Length, "name", "Invoice.json"); var filePath = Path.GetTempFileName(); using (var streamfile = System.IO.File.Create(filePath)) { await file.CopyToAsync(streamfile); } IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001"); var result = ipfs.FileSystem.AddFileAsync(filePath).Result; var url = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + "Invoice.json"; using (StreamReader r = new StreamReader(new MemoryStream(attachment.Content))) { var json = r.ReadToEnd(); var invoiceJSON = JsonConvert.DeserializeObject <InvoiceJSON>(json); MailInvoice mailInvoice = new MailInvoice(); mailInvoice.ToEmail = oMail.From.Address; mailInvoice.invoiceJSON = invoiceJSON; mailInvoice.CreatedOn = DateTime.Now; mailInvoice.InvoiceStatus = MailInvoiceStatus.Created; mailInvoice.IsSend = false; mailInvoice.HashUrl = url; mailInvoice.mailInvoiceCreationType = MailInvoiceCreationType.SMTP; mi.Insert(mailInvoice); } } } } Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); if (!info.Read) { oClient.MarkAsRead(info, true); } } // Quit and expunge emails marked as deleted from IMAP4 server. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine(ep.Message); } }
public async Task <ActionResult> UploadInvoice(List <Microsoft.AspNetCore.Http.IFormFile> file, string toemail) { try { var formFile = file[0]; if (formFile.Length > 0) { var filePath = Path.GetTempFileName(); using (var stream = System.IO.File.Create(filePath)) { await formFile.CopyToAsync(stream); } StreamReader streamReader = new StreamReader(filePath);// Server.MapPath("~/FileUpload/" + Path.GetFileName(file.FileName))); string data = streamReader.ReadToEnd(); InvoiceJSON invoiceJSON = JsonConvert.DeserializeObject <InvoiceJSON>(data); IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001"); var result = ipfs.FileSystem.AddFileAsync(filePath).Result; var url = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + formFile.FileName.Replace(" ", "%20"); MailInvoice mailInvoice = new MailInvoice(); mailInvoice.ToEmail = toemail; mailInvoice.invoiceJSON = invoiceJSON; mailInvoice.CreatedOn = DateTime.Now; mailInvoice.InvoiceStatus = MailInvoiceStatus.Created; mailInvoice.FromEmail = User.Identity.Name.ToString(); mailInvoice.mailInvoiceCreationType = MailInvoiceCreationType.Uploaded; mailInvoice.HashUrl = url; //mailInvoice.Hash = Hash; MongoDbRepository <MailInvoice> mi = new MongoDbRepository <MailInvoice>(); mi.Insert(mailInvoice); // var a = collection.Save(mailInvoice); var id = mailInvoice.Id.ToString(); //string json = JsonConvert.SerializeObject(invoicejson, Formatting.Indented); var menstream = formFile.OpenReadStream();// new MemoryStream(Encoding.Default.GetBytes(json)); var fromAddress = new MailAddress("*****@*****.**", "From Name"); var toAddress = new MailAddress(toemail, "To Name"); const string fromPassword = "******"; const string subject = "Invoice"; ///const string body = "Body"; Attachment attachment = new Attachment(menstream, new ContentType("application/json")); attachment.ContentDisposition.FileName = "Invoice.json"; // attachment.ContentType= "application/json"; //mailMessage.Attachments.Add(attachment); string authorityAccept = "http://" + HttpContext.Request.Host.Value + "/TaxInvoice/Accept?id=" + id; string authorityReject = "http://" + HttpContext.Request.Host.Value + "/TaxInvoice/Reject?id=" + id; //string a1= "<html>You have received an Invoice. Please do check the invoice and conform <a href=\'"; var html = "<html> You have received an Invoice. Please do check the invoice and conform<br /><a href='" + authorityAccept + "' style= \"background-color: #90EE90\" > Accept </a>   <a href='" + authorityReject + "' style= \"background-color: #FFFF00\" > Reject </a></ html >"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = html, IsBodyHtml = true }) { message.Attachments.Add(attachment); smtp.Send(message); } } //ViewBag.Message = "File Uploaded Successfully!!"; return(RedirectToAction("UploadInvoice")); } catch { // ViewBag.Message = "File upload failed!!"; return(RedirectToAction("UploadInvoice")); } }
public IpfsService(string host) { ipfsClient = new IpfsClient(host); getUrl = $"{ipfsClient.ApiUri.Scheme}://{ipfsClient.ApiUri.Host}/ipfs/".ToString(); }
/// <summary> /// Recover the files from the list of string: filename and CIDs: download, merge and decrypt /// </summary> /// <param name="cidArray"></param> public async void RecoverFilesMergeDecrypt(List <string> cidArray) { //We connect var ipfs = new IpfsClient(ipfsServer); if (cidArray.Count >= 0) { // First need to get the right folder. For ease of test, the part of the file are downloaded // on a folder filename-extension, i.e. test.txt to blockget/test-txt string fileName = Path.GetFileNameWithoutExtension(cidArray[0]); string extensionPt = Path.GetExtension(cidArray[0]); //string extension = extensionPt.Skip(1).ToArray(); string extension = extensionPt.Remove(0, 1); //string inputFolder = Globals.BLOCKGET_FILE_FOLDER + fileName + "-" + extension + "\\"; string inputFolder = Globals.OPERATION_FOLDER + fileName + "-" + extension + "\\"; string[] SplittedFilesArray = new string[Globals.SPLIT_NB]; string baseFileName = Path.GetFileNameWithoutExtension(cidArray[0]); int i = 0; //Create input forlder for download and merge Directory.CreateDirectory(inputFolder); foreach (string s in cidArray.Skip(1)) // We want to skip the first (contre intuitive, not 0) { try { //SplittedFilesArray[i] = inputFolder + baseFileName + "." + // i.ToString().PadLeft(5, Convert.ToChar("0")) + extensionPt + ".tmp"; SplittedFilesArray[i] = inputFolder + baseFileName + extensionPt + ".aes." + i.ToString().PadLeft(5, Convert.ToChar("0")) + ".tmp"; //We download bytes => File Stream result = await ipfs.FileSystem.ReadFileAsync(s); //We want to save them in the SaveFolder + cidArray folder //Could also try: Stream result = await ipfs.FileSystem.ReadFileAsync(s).Result; using (FileStream DestinationStream = File.Create(SplittedFilesArray[i])) //TODO ERROR: System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\Blockget\ifmalesuperfherodresedlikewomen-jpg\ifmalesuperfherodresedlikewomen.jpg.aes.00000.tmp'.' { await result.CopyToAsync(DestinationStream); } i++; } //System.Net.Http.HttpRequestException: 'invalid path "": path does not begin with '/'' catch (HttpRequestException e) { Console.WriteLine(e.Message); Console.WriteLine("FAIL! Don't forget to run IPFS on your computer"); break; } } // We merge string pathEncryptedFile = Split.MergeFile(inputFolder); //We decrypt //string pathEncryptedFile = inputFolder + fileName + ".aes"; //Globals.BLOCKGET_FILE_FOLDER + "\\" + cidArray[0]; //string pathEncryptedFile = inputFolder + baseFileName + extensionPt + ".aes"; string outputPath = Encryption.DecryptFile(pathEncryptedFile); // Test if the file downloaded is the same as the one already present if (File.Exists(cidArray[0]) && Filesys.compare2FilesByBlocks(outputPath, cidArray[0])) { Console.WriteLine("{0} and {1} have been compared bit by bit and are the same", outputPath, cidArray[0]); } else { Console.WriteLine("{0} and {1} have been compared bit by bit and are different, we download and store the file in the Blockget Folder", outputPath, cidArray[0]); // Could use the Path.Combine method to safely append the file name to the path. // Will overwrite if the destination file already exists. File.Copy(outputPath, cidArray[0], true); } //We delete folder and file downloaded File.Delete(outputPath); Directory.Delete(inputFolder); } else { Console.WriteLine("Problem this entry is empty"); } }
public static async Task CreateInvoiceWithMailSending(CreateTaxInvoice invoice, string fromEmail, string path, ApplicationUser au) { int counter = 0; try { //var collectionmr = db.GetCollection<MerchantRegistration>("MerchantRegistration"); // var mr = collectionmr.FindAll().ToList<MerchantRegistration>().FirstOrDefault(); InvoiceJSON invoicejson = new InvoiceJSON(); invoicejson.version = "1.0.1118"; billLists[] billListarray = new billLists[1]; billLists billlist = new billLists(); billlist.userGstin = au.GstId; billlist.supplyType = "O"; billlist.subSupplyType = 1; billlist.docType = "INV"; billlist.docNo = "20"; //Test billlist.docDate = invoice.DateIssue; billlist.transType = 1; billlist.fromGstin = invoice.GSTIDSeller; billlist.fromTrdName = invoice.NameoFSeller; //T2 // billlist.fromAddr1 = mr.Address1; // billlist.fromAddr2 = mr.Address2; // billlist.fromPlace = mr.City; billlist.fromStateCode = 27; billlist.actualFromStateCode = 27; //T2 billlist.toGstin = invoice.GSTIdBuyer; billlist.toTrdName = invoice.NameBuyer; billlist.toAddr1 = "1st floor, Jain Complex, opp.Bhoot Nath Mandir, Indra Nagar"; billlist.toAddr2 = ""; billlist.toPlace = "Pune"; billlist.toStateCode = 27; billlist.actualToStateCode = 27; //Test billlist.totalValue = invoice.TotalAmount;// 121.00; billlist.cgstValue = invoice.GSTAmount / 2; billlist.sgstValue = invoice.GSTAmount / 2; billlist.igstValue = 0.00; billlist.cessValue = 0.00; billlist.TotNonAdvolVal = 0.00; billlist.OthValue = 0.0000; billlist.totInvValue = invoice.TotalAmount; billlist.transMode = 1; billlist.transDistance = 60; counter++; billlist.transporterName = ""; billlist.transporterId = ""; billlist.transDocNo = ""; billlist.transDocDate = invoice.DateIssue; billlist.vehicleNo = ""; billlist.vehicleType = "R"; counter++; ItemLists[] itemlistarray = new ItemLists[invoice.itemDetails.Count]; for (int count = 0; count < invoice.itemDetails.Count; count++) { ItemLists itemlist = new ItemLists(); itemlist.itemNo = count + 1; itemlist.productName = invoice.itemDetails[count].Product; itemlist.productDesc = invoice.itemDetails[count].Product; itemlist.quantity = invoice.itemDetails[count].Quantity; //il.qtyUnit = invoice.itemDetails[count].Q; itemlist.qtyUnit = "Qty"; itemlist.taxableAmount = invoice.itemDetails[count].Amount;// (invoice.itemDetails[count].GST / 100) * invoice.itemDetails[count].Amount; itemlist.sgstRate = Convert.ToInt32(itemlist.taxableAmount / 2); itemlist.cgstRate = Convert.ToInt32(itemlist.taxableAmount / 2); itemlist.igstRate = 0; itemlist.cessRate = 0; itemlist.cessNonAdvol = 0; itemlistarray[count] = itemlist; } billlist.itemList = itemlistarray; billListarray[0] = billlist; invoicejson.billLists = billListarray; string json = JsonConvert.SerializeObject(invoicejson, Formatting.Indented); var menstream = new MemoryStream(Encoding.Default.GetBytes(json)); // var filePath = Path.GetTempFileName(); //File.WriteAllBytes(filePath, menstream.ToArray()); var stream = new MemoryStream(Encoding.Default.GetBytes(json)); IFormFile file = new FormFile(stream, 0, (Encoding.Default.GetBytes(json)).Length, "name", "Invoice.json"); // var filePath = Path.GetTempFileName(); var filePath = Path.GetTempFileName(); using (var streamfile = System.IO.File.Create(filePath)) { await file.CopyToAsync(streamfile); } //File.WriteAllBytes(filePath, attachment.Content); //using (var streamcreate = System.IO.File.Create(filePath)) //{ //} //StreamReader streamReader = new StreamReader(new MemoryStream // using (var stream = System.IO.File.Create(filePath)) { //File.WriteAllBytes(filePath, menstream.ToArray()); //await filePath.CopyToAsync(menstream); } StreamReader streamReader = new StreamReader(filePath);// Server.MapPath("~/FileUpload/" + Path.GetFileName(file.FileName))); string data = streamReader.ReadToEnd(); //InvoiceJSON invoiceJSON = JsonConvert.DeserializeObject<InvoiceJSON>(data); IpfsClient ipfs = new IpfsClient("https://ipfs.infura.io:5001"); var result = ipfs.FileSystem.AddFileAsync(filePath).Result; var url = "https://ipfs.io/ipfs/" + result.Id.Hash.ToString() + "?filename=" + "Invoice.json"; MongoDbRepository <MailInvoice> mdr = new MongoDbRepository <MailInvoice>(); MailInvoice mi = new MailInvoice(); mi.invoiceJSON = invoicejson; mi.FromEmail = fromEmail; mi.ToEmail = invoice.EmailBuyer; mi.InvoiceStatus = MailInvoiceStatus.Created; mi.mailInvoiceCreationType = MailInvoiceCreationType.Created; mi.HashUrl = url; // mi.Hash = Hash; mdr.Insert(mi); var id = mi.Id.ToString(); var fromAddress = new MailAddress("*****@*****.**", "From Name"); var toAddress = new MailAddress(invoice.EmailBuyer, "To Name"); counter++; const string fromPassword = "******"; const string subject = "Invoice"; ///const string body = "Body"; Attachment attachment = new Attachment(menstream, new ContentType("application/json")); attachment.ContentDisposition.FileName = "Invoice.json"; // attachment.ContentType= "application/json"; //mailMessage.Attachments.Add(attachment); string authorityAccept = "http://" + path + "/TaxInvoice/Accept?id=" + id; string authorityReject = "http://" + path + "/TaxInvoice/Reject?id=" + id; //string a1= "<html>You have received an Invoice. Please do check the invoice and conform <a href=\'"; var html = "<html> You have received an Invoice. Please do check the invoice and conform<br /><a href='" + authorityAccept + "' style= \"background-color: #90EE90\" > Accept </a>   <a href='" + authorityReject + "' style= \"background-color: #FFFF00\" > Reject </a></ html >"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = html, IsBodyHtml = true }) { message.Attachments.Add(attachment); smtp.Send(message); } // return invoicejson; } catch (Exception e) { // return invoicejson; } }
public IpfsHelpers(IpfsDaemonBase daemon) { _daemon = daemon; _client = new IpfsClient(); }
public IpfsDeployment(IpFsDaemon daemon) { _daemon = daemon; _client = daemon.Client; L = daemon.L; }