public async Task RemoveCorpAsync(string ticker) { Collection <string> tickers = await dataBaseService.getIDs("companies"); if (!tickers.Contains(ticker)) { await ReplyAsync("That company does not exist"); } else { await dataBaseService.RemoveObjectAsync(ticker, "companies"); Collection <string> shareholderIDs = await dataBaseService.getIDs("shares"); foreach (string ID in shareholderIDs) { UserShares shares = new UserShares(await dataBaseService.getJObjectAsync(ID, "shares"), true); shares.ownedShares.Remove(ticker); await dataBaseService.RemoveObjectAsync(ID, "shares"); await dataBaseService.SetJObjectAsync(dataBaseService.SerializeObject <UserShares>(shares), "shares"); } await ReplyAsync("Company deleted"); } }
[Route("api/file/load/{*folder?}")]//{username}")] public IHttpActionResult Load(string folder = "") { FTPabilitazioni utente = db.FTPabilitazioni.Where(e => e.ftpUser == User.Identity.Name).FirstOrDefault(); Boolean bCheck = false; if (utente == null) { return(Content(HttpStatusCode.NoContent, "Abilitazione non trovata")); } var nodes = new List <FtpModel>(); string sDir = "C:\\inetpub\\wwwroot\\FTP"; if (folder == "") { //FTPabilitazioni utente = db.FTPabilitazioni.Where(e => e.ftpUser == User.Identity.Name).FirstOrDefault(); nodes.Add(new FtpModel() { FileName = "FTP", Folder = "#", Type = "Folder", ReadWrite = "R" }); var data = DirSearch(sDir, nodes); } else { folder = folder.Replace("#/", ""); folder = folder.Replace('/', Path.DirectorySeparatorChar); string cartella = (sDir + "\\" + folder); string cartellaAttuale = cartella.Substring(sDir.Length + 1); string[] percorso = cartellaAttuale.Split(Path.DirectorySeparatorChar); string sRight; using (ExtranetDB dbContext = new ExtranetDB()) { string toCheck = percorso[0]; UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == toCheck).FirstOrDefault(); if (abilitazioni != null) { bCheck = true; } sRight = abilitazioni.abilitazione; } if (bCheck == false) { return(Content(HttpStatusCode.NoContent, "404")); } DirectoryInfo nomeFolder = new DirectoryInfo(cartella); nodes.Add(new FtpModel() { FileName = nomeFolder.Name, Folder = folder, Type = "Folder", Size = GetDirectorySize(nomeFolder.FullName).ToString(), ReadWrite = sRight }); var data = DirSearch(cartella, nodes); } return(Ok(nodes));//, System.Web.Mvc.Jso.nRequestBehavior.AllowGet); }
private void addSharesToTable() { UserShares shares = new UserShares(db.getJObject(userID, "shares")); DataTable table = new DataTable(); table.Columns.Add("Ticker"); table.Columns.Add("Owned Shares"); foreach (string ticker in shares.ownedShares.Keys) { DataRow row = table.NewRow(); row["Ticker"] = ticker; row["Owned Shares"] = shares.ownedShares[ticker]; table.Rows.Add(row); } dataGridViewShares.DataSource = table; }
public async Task <Collection <ulong> > GetShareholders(string ticker) { Collection <string> shareholders = await db.getIDs("shares"); Dictionary <string, int> ownedShares; Collection <ulong> corpShareholders = new Collection <ulong>(); foreach (string ID in shareholders) { UserShares userShares = new UserShares(await db.getJObjectAsync(ID, "shares"), true); ownedShares = userShares.ownedShares; if (ownedShares.ContainsKey(ticker)) { corpShareholders.Add(Convert.ToUInt64(ID)); } } return(corpShareholders); }
public async Task SetShares(string userID, string ticker, int amount) { UserShares SharesObj; try { SharesObj = new UserShares(await db.getJObjectAsync(userID, "shares"), true); } catch (System.NullReferenceException) { SharesObj = new UserShares(userID); } if (SharesObj.ownedShares.ContainsKey(ticker) == true) { SharesObj.ownedShares.Remove(ticker); } SharesObj.ownedShares.Add(ticker, amount); await db.SetJObjectAsync(db.SerializeObject <UserShares>(SharesObj), "shares"); }
public async Task <int> GetShares(string userID, string ticker) { UserShares SharesObj; try { SharesObj = new UserShares(await db.getJObjectAsync(userID, "shares"), true); } catch (System.NullReferenceException) { return(0); } if (SharesObj.ownedShares.ContainsKey(ticker) == false) { return(0); } else { return(SharesObj.ownedShares[ticker]); } }
public async Task <UserShareView> BuyShare(int shareId, int userId, int amount) { UserShares existingRecord = await _context.UserShares.FirstOrDefaultAsync(s => s.ShareId == shareId && s.UserId == userId); if (existingRecord != null) { existingRecord.Count += amount; } else { UserShares newRecord = new UserShares { UserId = userId, ShareId = shareId, Count = amount }; _context.UserShares.Add(newRecord); } await _context.SaveChangesAsync(); return(await _context.UserShareView.FirstOrDefaultAsync(s => s.ShareId == shareId && s.UserId == userId)); }
public async Task SharesAsync() { UserShares sharesObj; try { sharesObj = new UserShares(await db.getJObjectAsync(Context.User.Id.ToString(), "shares"), true); } catch (System.NullReferenceException) { await ReplyAsync("You shares have been sent to you privately"); await Context.User.SendMessageAsync("You do not own any shares"); return; } Dictionary <string, int> ownedShares = sharesObj.ownedShares; Collection <EmbedFieldBuilder> embedFields = new Collection <EmbedFieldBuilder>(); foreach (string ticker in ownedShares.Keys) { EmbedFieldBuilder embedField = new EmbedFieldBuilder().WithIsInline(false).WithName($"{(string)await db.GetFieldAsync(ticker, "name", "companies")} ({ticker}) ").WithValue(ownedShares[ticker]); embedFields.Add(embedField); } EmbedBuilder embed = new EmbedBuilder().WithColor(Color.Gold).WithTitle($"Shares Owned by {Context.User.Username.ToString()}").WithDescription($"This is a list of all shares owned by {Context.User.Username.ToString()}"); foreach (EmbedFieldBuilder field in embedFields) { embed.AddField(field); } await ReplyAsync("Your shares have been sent to you privately"); await Context.User.SendMessageAsync("", false, embed.Build()); }
public async Task <int> CorpShares(string ticker) { Company company = new Company(await db.getJObjectAsync(ticker, "companies")); Collection <string> shareholders = await db.getIDs("shares"); Dictionary <string, int> ownedShares; int shares = 0; foreach (string ID in shareholders) { UserShares userShares = new UserShares(await db.getJObjectAsync(ID, "shares"), true); ownedShares = userShares.ownedShares; if (ownedShares.ContainsKey(ticker)) { shares += ownedShares[ticker]; } } company.shares = shares; await db.SetJObjectAsync(db.SerializeObject <Company>(company), "companies"); return(shares); }
public async Task SellOfferAsync([Summary("The ticker of the company whose shares you want to sell")] string ticker, [Summary("The amount of shares you wish to sell")] int shares, [Summary("Price per share")] double price) { string AuthorMoneyt = (string)await db.GetFieldAsync(Context.User.Id.ToString(), "money", "users"); double AuthorMoney; if (shares < 0 || price < 0) { await ReplyAsync("You cant sell negative shares sell buy them for a negative amount of money!"); return; } if (AuthorMoneyt == null) { AuthorMoney = 50000; await db.SetFieldAsync(Context.User.Id.ToString(), "money", AuthorMoney, "users"); } else { AuthorMoney = double.Parse(AuthorMoneyt); } UserShares tempObj; try { tempObj = new UserShares(await db.getJObjectAsync(Context.User.Id.ToString(), "shares"), true); } catch (System.NullReferenceException) { tempObj = new UserShares(Context.User.Id.ToString()); await ReplyAsync("You cannot complete this transaction as you own no shares in the specified company"); return; } Dictionary <string, int> ownedShares = tempObj.ownedShares; if (ownedShares.ContainsKey(ticker) == false) { await ReplyAsync("You cannot complete this transaction as you own no shares in the specified company"); return; } int outcomeAmount = ownedShares[ticker] - shares; if (outcomeAmount < 0) { await ReplyAsync("You cannot complete this transaction as it would leave you with a negative amount of shares in the specified company."); } else if (ownedShares[ticker] == 0) { await ReplyAsync("You cannot complete this transaction as you own no shares in the specified company."); } else { Transaction transaction = new Transaction(price, shares, "sell", Context.User.Id.ToString(), ticker, db, CommandService); try { JObject tmp = db.SerializeObject(transaction); await db.SetJObjectAsync(tmp, "transactions"); await ReplyAsync($"Sell offer lodged in <#{await db.GetFieldAsync("MarketChannel", "channel", "system")}>"); } catch (Exception e) { await Log.Logger(Log.Logs.ERROR, e.Message); await ReplyAsync("Something went wrong: " + e.Message); } } }
public object DirSearch(string sDir, List <FtpModel> nodes) { string ftpRoot = "C:\\inetpub\\wwwroot\\FTP"; string cartellaAttuale = ""; if (ftpRoot != sDir) { cartellaAttuale = sDir.Substring(ftpRoot.Length + 1); } try { foreach (string d in Directory.GetDirectories(sDir)) { Boolean bCheck = true; //string oldFolder = d; DirectoryInfo nomeFolder = new DirectoryInfo(d); if (sDir == ftpRoot) { bCheck = false; //var user = (CustomMembershipUser)Membership.GetUser(LoginView.UserName, false); var user = User.Identity.Name; using (ExtranetDB dbContext = new ExtranetDB()) { //var utente = dbContext.Users.Include("UserShares"); //FTPabilitazioni[] abilitazioni = dbContext.FTPabilitazioni.Include("UserShares").Where(e => e.ftpUser == User.Identity.Name && e.UserShares).FirstOrDefault(); UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == nomeFolder.Name).FirstOrDefault(); if (abilitazioni != null) { bCheck = true; } } if (bCheck == true) { nodes.Add(new FtpModel() { FileName = nomeFolder.Name, Folder = "#" /*nomeFolder.Parent.Name*/, Type = "Folder", LastEdit = nomeFolder.LastWriteTimeUtc.ToLocalTime().ToString(), Size = GetDirectorySize(nomeFolder.FullName).ToString() + "Kb" }); } } else { nodes.Add(new FtpModel() { FileName = nomeFolder.Name, Folder = cartellaAttuale, Type = "Folder", LastEdit = nomeFolder.LastWriteTimeUtc.ToLocalTime().ToString(), Size = GetDirectorySize(nomeFolder.FullName).ToString() + "Kb" }); } } if (cartellaAttuale != "") { DirectoryInfo nomeFolder2 = new DirectoryInfo(sDir); //var cartella = sDir.Substring(ftpRoot.Length+1); foreach (var f in nomeFolder2.GetFiles()) { nodes.Add(new FtpModel() { FileName = f.Name, Folder = cartellaAttuale, Type = f.Extension, LastEdit = f.LastWriteTimeUtc.ToLocalTime().ToString(), Size = f.Length.ToString() + "Kb" }); } } return(Ok("")); } catch (System.Exception excpt) { Console.WriteLine(excpt.InnerException); return(InternalServerError(excpt.InnerException)); } }
[Route("api/file/upload/")] //{username}")] public HttpResponseMessage Upload() //non più usata, ora è in FileController { HttpResponseMessage result = null; try { var httpRequest = HttpContext.Current.Request; var filecontent = httpRequest.Files[0]; var sFolder = httpRequest["PathToSave"].ToString().TrimEnd(); string[] sDir = sFolder.Split('\\'); Boolean bCheck = false; var user = User.Identity.Name; string sRight = "R"; using (ExtranetDB dbContext = new ExtranetDB()) { var sPathToCheck = sDir[0]; //var utente = dbContext.Users.Include("UserShares"); //FTPabilitazioni[] abilitazioni = dbContext.FTPabilitazioni.Include("UserShares").Where(e => e.ftpUser == User.Identity.Name && e.UserShares).FirstOrDefault(); UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == sPathToCheck).FirstOrDefault(); if (abilitazioni != null) { sRight = abilitazioni.abilitazione; bCheck = true; } } if (bCheck == false || sRight == "R") { result = Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"); return(result); } // var a=httpRequest.Files["uFile"]; if (httpRequest.Files.Count > 0) { if (sFolder != "#" && sFolder != "FTP" && sFolder != "") { var docfiles = new List <string>(); foreach (string file in httpRequest.Files) { var postedFile = httpRequest.Files[file]; //FTPROOT var filePath = HostingEnvironment.MapPath("~/FTP") + '\\' + sFolder + '\\' + postedFile.FileName; postedFile.SaveAs(filePath); docfiles.Add(filePath); } result = Request.CreateResponse(HttpStatusCode.Created, docfiles); } else { result = Request.CreateResponse(HttpStatusCode.BadRequest, "Cannot upload in this folder"); return(result); } } else { result = Request.CreateResponse(HttpStatusCode.BadRequest, "File non allegato"); } return(result); } catch (Exception e) { result = Request.CreateResponse(HttpStatusCode.BadRequest, e.Message); } return(result); }
public HttpResponseMessage DownloadM(DownloadUrl t) { if (t == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } HttpResponseMessage result = null; try { var httpRequest = HttpContext.Current.Request; Boolean bCheck = false; var user = User.Identity.Name; string sRight = "R"; using (ZipFile zip = new ZipFile()) { zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AddDirectoryByName("Files"); foreach (var percorso in t.Urls) { bCheck = false; //var user = User.Identity.Name; using (ExtranetDB dbContext = new ExtranetDB()) { var sPath = percorso.Split('/'); var sPathToCheck = sPath[0]; //var utente = dbContext.Users.Include("UserShares"); //FTPabilitazioni[] abilitazioni = dbContext.FTPabilitazioni.Include("UserShares").Where(e => e.ftpUser == User.Identity.Name && e.UserShares).FirstOrDefault(); UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == sPathToCheck).FirstOrDefault(); if (abilitazioni != null) { bCheck = true; } } if (bCheck == false) { var resultB = new HttpResponseMessage(HttpStatusCode.BadRequest); return(resultB); } var sPercorso = ftpRoot + "\\" + percorso; sPercorso = sPercorso.Replace("/", "\\"); zip.AddFile(sPercorso.ToString(), "Files"); } return(ZipContentResult(zip)); } } catch (Exception e) { result = Request.CreateResponse(HttpStatusCode.BadRequest, e.Message); } return(result); }
[Route("api/file/download/{sTipo}/{*sFile?}")]//{username}")] public HttpResponseMessage Download(string sTipo, string sFile) { try { sFile = sFile.Substring(0, sFile.Length - 1); string filePath = ftpRoot + "\\" + sFile + "." + sTipo; //filePath = filePath.Substring(5); filePath = filePath.Replace('/', '\\'); string[] sFolder = sFile.Split('/'); Boolean bCheck = false; var user = User.Identity.Name; using (ExtranetDB dbContext = new ExtranetDB()) { var sPathToCheck = sFolder[0]; //var utente = dbContext.Users.Include("UserShares"); //FTPabilitazioni[] abilitazioni = dbContext.FTPabilitazioni.Include("UserShares").Where(e => e.ftpUser == User.Identity.Name && e.UserShares).FirstOrDefault(); UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == sPathToCheck).FirstOrDefault(); if (abilitazioni != null) { bCheck = true; } } if (bCheck == false) { //var resultB = new HttpResponseMessage(HttpStatusCode.BadRequest); //resultB.ReasonPhrase = "Not permitted"; var resultB = Request.CreateResponse(HttpStatusCode.BadRequest, "Not allowed"); return(resultB); } var dataBytes = File.ReadAllBytes(filePath); var sName = filePath.Split('\\').Last(); HttpContext.Current.Response.BufferOutput = false; //adding bytes to memory stream var dataStream = new MemoryStream(dataBytes); HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { //Content = new ByteArrayContent(dataStream.ToArray()) Content = new ByteArrayContent(dataStream.ToArray()) }; //.BufferOutput = false; result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = sName }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(result); // System.Diagnostics.Debugger.Break(); //byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext"); //byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\\inetpub\\wwwroot\\Condivisione\\" + filePath); //string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1); //return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); } catch (System.Exception e) { Console.WriteLine(e.Message); //var result = new HttpResponseMessage(HttpStatusCode.BadRequest); //result.ReasonPhrase = e.Message; var result = Request.CreateResponse(HttpStatusCode.BadRequest, e.Message); return(result); } }
public ActionResult Download(string file) { var sFile = ""; sFile = ftpRoot + "/" + System.Uri.UnescapeDataString(file); //string file = @"C:\inetpub\wwwroot\FTP\IDIADA\20190706 EPOLE ERIC GRANADO.mp4"; //file = ftpRoot+"/" + System.Uri.UnescapeDataString(file); //var filePath = @"C:\inetpub\wwwroot\FTP\IDIADA\20190706 EPOLE ERIC GRANADO.mp4"; //var filePath = ftpRoot + file; if (sFile == "") { Response.StatusCode = 400; Response.StatusDescription = "File request error"; Response.End(); return(FTP()); } sFile = file; //sFile = sFile.Substring(0, sFile.Length - 1); string filePath = sFile; //filePath = filePath.Substring(5); filePath = filePath.Replace('/', '\\'); sFile = sFile.Replace('/', '\\'); string[] sFolder = sFile.Split('\\'); Boolean bCheck = false; var user = User.Identity.Name; using (ExtranetDB dbContext = new ExtranetDB()) { var sPathToCheck = sFolder[0]; //var utente = dbContext.Users.Include("UserShares"); //FTPabilitazioni[] abilitazioni = dbContext.FTPabilitazioni.Include("UserShares").Where(e => e.ftpUser == User.Identity.Name && e.UserShares).FirstOrDefault(); UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == sPathToCheck).FirstOrDefault(); if (abilitazioni != null) { bCheck = true; } } if (bCheck == false) { //var resultB = new HttpResponseMessage(HttpStatusCode.BadRequest); //resultB.ReasonPhrase = "Not permitted"; Response.StatusCode = 400; Response.StatusDescription = "File request error"; Response.End(); return(FTP()); //return resultB; } filePath = ftpRoot + "\\" + filePath; FileInfo OutFile = new FileInfo(filePath); Response.Clear(); Response.ContentType = "application/octet-stream"; Response.Buffer = false; Response.BufferOutput = false; //Response.AppendHeader("Content-Lenght", OutFile.Length.ToString()); filePath = OutFile.FullName; string fileName = OutFile.Name; //filePath = @"C:\inetpub\wwwroot\FTP\IDIADA\20190706 EPOLE ERIC GRANADO.mp4"; Response.AppendHeader("Content-Disposition", "filename=" + System.Uri.EscapeDataString(fileName)); Response.TransmitFile(filePath, 0, OutFile.Length); Response.End(); //return null; //return FTP(); return(FTP()); }
[Route("/Files/MultiUpload/")]//{username}")] public string MultiUpload() { //HttpResponseMessage result = null; try { var httpRequest = HttpContext.Request; //var filecontent = httpRequest.Files[0]; //var httpRequest = Request; //var filecontent = Request.Files[0]; string filename = System.Uri.UnescapeDataString(Request.Headers["x-filename"].ToString().TrimEnd()); var sFolder = System.Uri.UnescapeDataString(Request.Headers["PathToSave"].ToString().TrimEnd()); string[] sDir = sFolder.Split('\\'); Boolean bCheck = false; var user = User.Identity.Name; string sRight = "R"; using (ExtranetDB dbContext = new ExtranetDB()) { var sPathToCheck = sDir[0]; UserShares abilitazioni = dbContext.UserShares.Where(e => e.username == User.Identity.Name && e.SharePath == sPathToCheck).FirstOrDefault(); if (abilitazioni != null) { sRight = abilitazioni.abilitazione; bCheck = true; } } if (bCheck == false || sRight == "R") { //result = Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"); return("Forbidden"); } var chunks = Request.InputStream; string path = HostingEnvironment.MapPath("~/FTP/upload"); //test //var filePath = HostingEnvironment.MapPath("~/FTP") string nome = filename + ".tmp" + Request.Headers["completed"].ToString().TrimEnd().PadLeft(4, '0'); //path = ftpRoot + '\\' + sFolder; //20190830: utilizzo cartella temp x upload path = ftpRoot + "\\UPLOAD"; if (sFolder != "#" && sFolder != "FTP" && sFolder != "") { string newpath = Path.Combine(path, nome); using (System.IO.FileStream fs = System.IO.File.Create(newpath)) { byte[] bytes = new byte[1024000];//[77570]; int bytesRead; //var httpRequest = HttpContext.Request; //var filecontent = httpRequest.Files[0]; while ((bytesRead = Request.InputStream.Read(bytes, 0, bytes.Length)) > 0) { fs.Write(bytes, 0, bytesRead); } } return("test"); } else { return("Cannot upload in this folder"); } } catch (Exception ex) { return("Error: " + ex.Message); } }