public Task Handle(SendMessageRequest message, IMessageHandlerContext context) { ChatDatabase db = ChatDatabase.getInstance(); ServiceBusResponse response = db.insertNewChatMessage(message.message); return(context.Reply(response)); }
public ActionResult SaveReview(string comment) { string cameFrom = Request.UrlReferrer.ToString(); if (cameFrom.Split('/').Length == 6 && !String.IsNullOrWhiteSpace(cameFrom.Split('/')[5])) { SaveReviewRequest req = new SaveReviewRequest(new ReviewModel { Review = comment, User = Globals.getUser(), CompanyName = cameFrom.Split('/')[5], Rating = 0 }); ServiceBusResponse res = ConnectionManager.getConnectionObject(Globals.getUser()).sendReview(req); if (res.result) { return(RedirectToAction("DisplayCompany", new { id = cameFrom.Split('/')[5] })); } else { ViewBag.SaveReviewResponse = res.response; return(RedirectToAction("DisplayCompany", new { id = cameFrom.Split('/')[5] })); } } else { return(View("Index")); } }
/// <summary> /// Sends the given message to the client along with the msgEndDelim on the end /// </summary> /// <param name="msg">The message to send to the client</param> private void sendToClient(ServiceBusResponse message) { //TODO Low importance: use below instead of "" //String.IsNullOrEmpty(msg); /* * if (connection.Connected == true && !"".Equals(msg)) * { * //connection.Send(Encoding.ASCII.GetBytes(msg + SharedData.msgEndDelim)); * * msg += SharedData.msgEndDelim; * connectionStream.Write(Encoding.UTF8.GetBytes(msg)); * connectionStream.Flush(); * } */ MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); binForm.Serialize(memStream, message); //memStream.Write(SharedData.msgEndDelim.) byte[] msg = memStream.ToArray(); //byte[] msg = Encoding.UTF8.GetBytes(message + SharedData.msgEndDelim); int msgSize = msg.Length; //First write the total size of the message connectionStream.Write(BitConverter.GetBytes(msgSize)); connectionStream.Flush(); //Then write the serialized object connectionStream.Write(msg); connectionStream.Flush(); }
/// <summary> /// Parses new account info and attempts to insert the new account into the authentication database /// It also publishes an "AccountCreated" event /// </summary> /// <returns>A response message</returns> private ServiceBusResponse attemptNewAccountCreation(CreateAccountRequest request) { CreateAccount command = request.createCommand; ServiceBusResponse dbResponse = AuthenticationDatabase.getInstance().insertNewUserAccount(command); if (dbResponse.result == true) { authenticated = true; username = command.username; password = command.password; initializeRequestingEndpoint(); eventPublishingEndpoint.Publish(new AccountCreated(command)); // Publish company event for company to be saved in DB if (request.createCommand.type == Messages.DataTypes.AccountType.business) { string[] loc = new string[1]; loc[0] = request.createCommand.address; CompanyListingsEvent comp = new CompanyListingsEvent(new CompanyInstance(request.createCommand.username, request.createCommand.phonenumber, request.createCommand.email, loc)); eventPublishingEndpoint.Publish(comp); } } return(dbResponse); }
public ActionResult CreateAccount(string textUsername, string textPassword, string textAddress, string textPhoneNumber, string textEmail, bool accountType) { CreateAccount msg = new CreateAccount { username = textUsername, password = textPassword, address = textAddress, phonenumber = textPhoneNumber, email = textEmail, type = accountType ? AccountType.business : AccountType.user }; CreateAccountRequest request = new CreateAccountRequest(msg); ServiceBusResponse response = ConnectionManager.sendNewAccountInfo(request); if (response.result == true) { return(RedirectToAction("Index", "Home")); } ViewBag.AccountCreationResult = response.response; return(View("CreateAccount")); }
//HTTP Get /// <summary> /// This function is called by the client on the users computer when they request to log in /// </summary> /// <param name="username">The clients username</param> /// <param name="password">The clients password</param> /// <returns>Either redirects to homepage on correct log in or returns an error message to the create account screen</returns> public ActionResult UserLogIn(string username, string password) { LogInRequest request = new LogInRequest(username, password); ServiceBusResponse response = ConnectionManager.sendLogIn(request); if (response.response.Equals("")) { if (response.result) { return(RedirectToAction("Index", "Home", new { msg = "Hello " + username + " logged in sucessfully!" })); } else { ViewBag.LogInResponse = "Invalid username or password!"; } } else { ViewBag.LogInResponse = "Invalid log in request: " + response.response; } ViewBag.LogInResult = response.result; return(View("Index")); }
public ActionResult CreateAccount(CreateAccount account) { /* Trimming all the white spaces */ account.phonenumber = account.phonenumber.Trim(); account.email = account.email.Trim(); account.password = account.password.Trim(); account.username = account.username.Trim(); account.address = account.address.Trim(); /* Removing the - from the phone number */ account.phonenumber = account.phonenumber.Replace("-", ""); AuthenticationDatabase db = AuthenticationDatabase.getInstance(); ServiceBusResponse response = db.insertNewUserAccount(account); if (response.result) { ViewBag.userCreationSuccess = "Successfully created the new user. You can log in using your new credentials now."; return(View("Index")); } else { ViewBag.userCreationFailure = "Could not create the new user. " + response.response; return(View()); } }
public GetCompanyInfoResponse getCompanyInfo(GetCompanyInfoRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return((GetCompanyInfoResponse)resp); }
public CompanyReviewResponse searchCompanyReview(CompanyReviewSearchRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return((CompanyReviewResponse)resp); }
public WeatherNeededResponse getWeatherData(WeatherNeededRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return((WeatherNeededResponse)resp); }
public ServiceBusResponse sendChatMessage(SendMessageRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return(resp); }
public GetChatHistoryResponse getChatHistory(GetChatHistoryRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return((GetChatHistoryResponse)resp); }
public ServiceBusResponse addCompanyReview(AddCompanyReviewRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return(resp); }
/// <summary> /// This function is called by the client on the users computer when they request to create account /// </summary> /// <param name="username">The clients desired username</param> /// <param name="password">The clients password</param> /// <param name="address">The clients address</param> /// <param name="accountType">The clients account type (user, business, or notspecified)</param> /// <param name="email">The clients desired email address</param> /// <param name="phonenumber">The clients phonenumber</param> /// <returns>Either redirects to homepage on correct log in or returns an error message to the log in screen</returns> public ActionResult UserCreateAccount(string username, string password, string address, string phonenumber, string email, string accountType) { var account = AccountType.notspecified; switch (accountType) { case "user": account = AccountType.user; break; case "business": account = AccountType.business; break; } phonenumber = phonenumber.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", ""); CreateAccountRequest request = new CreateAccountRequest(new CreateAccount() { username = username, password = password, address = address, email = email, phonenumber = phonenumber, type = account }); ServiceBusResponse response = ConnectionManager.sendNewAccountInfo(request); if (response.result) { return(RedirectToAction("Index", "Home", new { msg = "Hello " + username + " account successfully created!" })); } ViewBag.CreateAccountResponse = response.response; return(View("CreateAccount")); }
public ActionResult SaveReview() { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } String review = Request.Form["reviewData"]; String company = Request.Form["companyName"]; int time = (int)DateTimeOffset.Now.ToUnixTimeSeconds(); String rating = Request.Form["star"]; string json = "{review:{companyName:\"" + company + "\"," + "username:\"" + Globals.getUser() + "\"," + "review:\"" + review + "\"," + "stars:" + rating + "," + "timestamp:" + time + "}}"; SaveReviewRequest srRequest = new SaveReviewRequest(company, json); ServiceBusResponse response = connection.saveCompanyReview(srRequest); Response.Write("<script>alert('" + response.response + "')</script>"); return(View("Index")); }
public ActionResult createAccountEntry(string username, string password, string address, string phonenumber, string email, string accountType) { var account = AccountType.notspecified; switch (accountType) { case "user": account = AccountType.user; break; case "business": account = AccountType.business; break; } phonenumber = phonenumber.Replace(" ", "").Replace("(", "").Replace(")", "").Replace("-", ""); CreateAccountRequest request = new CreateAccountRequest(new CreateAccount() { username = username, password = password, address = address, email = email, phonenumber = phonenumber, type = account }); ServiceBusResponse response = ConnectionManager.sendNewAccountInfo(request); if (response.result) { ViewBag.CreateAccountResponse = "Account successfully created. You are now logged in"; } return(View("CreateAccount")); }
public ActionResult SendMessage(string receiver = "", int timestamp = -1, string message = "") { if (Globals.isLoggedIn() == false) { return(RedirectToAction("Index", "Authentication")); } if ("".Equals(receiver) || "".Equals(message) || timestamp == -1) { throw new System.Exception("Did not supply all required arguments."); } ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { return(RedirectToAction("Index", "Authentication")); } ChatMessage chatMessage = new ChatMessage { sender = Globals.getUser(), receiver = receiver, unix_timestamp = timestamp, messageContents = message }; SendMessageRequest request = new SendMessageRequest(chatMessage); ServiceBusResponse resp = connection.sendChatMessage(request); System.Diagnostics.Debug.WriteLine("CHECK: " + resp.response); return(null); }
public async Task HandleAsync(SaveReviewRequest message, IMessageHandlerContext context) { ServiceBusResponse returnedMessage; try { string uri = "http://35.188.33.235/api/Review/PostReview"; var stringContent = new StringContent(message.jsonreview, Encoding.UTF8, "application/json"); var response = await httpPostRequest.PostAsync(uri, stringContent); var responseString = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { returnedMessage = new ServiceBusResponse(false, "Successfully saved review for company: " + message.companyName); } else { returnedMessage = new ServiceBusResponse(false, "Failed to save review for company: " + message.companyName); } } catch (Exception e) { returnedMessage = new ServiceBusResponse(false, e.Message); } await context.Reply(returnedMessage); }
public ActionResult logIn(string username, string password) { LogInRequest request = new LogInRequest(username, password); ServiceBusResponse response = ConnectionManager.sendLogIn(request); if (response.response.Equals("")) { if (response.result) { ViewBag.LoggedInMessage = "Hello " + username + ", you have successfully logged in"; return(View("LoggedInIndex")); return(RedirectToAction("Index", "Home", new { msg = " log in sucessfull" })); } else { ViewBag.LogInResult = "Incorrect username or password!"; return(View("Index")); } } else { ViewBag.LogInResult = "Invalid log in request: " + response.response; return(View("Index")); } //ViewBag.LogInResult = response.result; }
public ActionResult AsIsLogin(string usernameText, string passwordText) { LogInRequest request = new LogInRequest(usernameText, passwordText); ServiceBusResponse response = null; ServiceBusConnection connection = ConnectionManager.getConnectionObject(Globals.getUser()); if (connection == null) { response = ConnectionManager.sendLogIn(request); } else { response = connection.sendLogIn(request); } if (response.result == false) { ViewBag.AsIsResponse = "Login Failed"; return(View("Index")); } else { return(View("~/Views/Home/Index.cshtml")); } }
/// <summary> /// Notify the CompanyReviewService that a new review has been written /// </summary> /// <param name="request">Information about the review that was written</param> /// <param name="context">Information about the calling endpoint</param> /// <returns>Nothing</returns> public Task Handle(SaveCompanyReviewRequest request, IMessageHandlerContext context) { CompanyReviewAPIRequest webRequest = new CompanyReviewAPIRequest(); ServiceBusResponse response = webRequest.saveCompanyReview(request); return(context.Reply(response)); }
public ActionResult Register(string proposedUsername, string proposedPassword, string proposedAddress, string proposedPhoneNumber, string proposedEmail, AccountType proposedType) { CreateAccount newAcc = new CreateAccount(); newAcc.username = proposedUsername; newAcc.password = proposedPassword; newAcc.address = proposedAddress; newAcc.phonenumber = proposedPhoneNumber; newAcc.email = proposedEmail; newAcc.type = proposedType; CreateAccountRequest CAR = new CreateAccountRequest(newAcc); ServiceBusResponse response = ConnectionManager.sendNewAccountInfo(CAR); if (!response.result) { ViewBag.createaccountresponse = "Error in creating account.\n" + response.response; } else { ViewBag.createaccountresponse = "New account successfully created. Successfully logged in!\n"; return(View("LoggedIn")); } return(View("CreateAccount")); }
public GetChatContactsResponse getAllChatContacts(GetChatContactsRequest request) { send(request); ServiceBusResponse resp = readUntilEOF(); return((GetChatContactsResponse)resp); }
/// <summary> /// Saves the echo to the database, reverses the data, and returns it back to the calling endpoint. /// </summary> /// <param name="request">Information about the echo</param> /// <param name="context">Used to access information regarding the endpoints used for this handle</param> /// <returns>The response to be sent back to the calling process</returns> public Task Handle(SendMessageRequest request, IMessageHandlerContext context) { //Save the echo to the database ServiceBusResponse response = ChatServiceDatabase.getInstance().sendMessage(request.message); //The context is used to give a reply back to the endpoint that sent the request return(context.Reply(response)); }
/// <summary> /// Sends the data to be echo'd to the service bus /// </summary> /// <param name="request">The data to be echo'd</param> /// <returns>The response from the servicebus</returns> public static ServiceBusResponse echoAsIs(AsIsEchoRequest request) { ServiceBusConnection tempConnection = new ServiceBusConnection(""); ServiceBusResponse response = tempConnection.echoAsIs(request); tempConnection.close(); return(response); }
public ActionResult SignUp(string username, string email, string address, string phone, string password, string type) { AccountType accType; switch (type) { case "user": accType = AccountType.user; break; case "business": accType = AccountType.business; break; default: accType = AccountType.notspecified; break; } CreateAccount account = new CreateAccount() { username = username, email = email, address = address, phonenumber = phone, password = password, type = accType }; CreateAccountRequest req = new CreateAccountRequest(account); try { ServiceBusResponse response = ConnectionManager.sendNewAccountInfo(req); if (response.result) { return(RedirectToAction("Index", "Home")); } else { ViewBag.Message = "Please fill out this form to sign up"; ViewBag.CreateAccountResponse = response.response; return(View("CreateAccount")); } } catch (Exception err) { ViewBag.Message = "Please fill out this form to sign up"; ViewBag.CreateAccountResponse = "Something went wrong, please verify your input and try again."; return(View("CreateAccount")); } }
public ActionResult Login(string username, string password) { LogInRequest logInRequest = new LogInRequest(username, password); ServiceBusResponse result = ConnectionManager.sendLogIn(logInRequest); if (!result.result) { ViewBag.LoginResponse = "Login Failed. Please verify the username and password and try again."; return(View("Index")); } else { return(RedirectToAction("Index", "Home")); } }
/// <summary> /// Continuously reads one byte at a time from the client until the end of file string of characters defined in the Messages library is found /// </summary> /// <returns>The string representation of bytes read from the server socket</returns> private ServiceBusResponse readUntilEOF() { int sizeOfMsg = 0; int bytesRead = 0; byte[] msgSize = new byte[4]; string thing; while (bytesRead < msgSize.Length) { try { bytesRead += connectionStream.Read(msgSize, bytesRead, msgSize.Length - bytesRead); } catch (SocketException) // This is thrown when the timeout occurs. The timeout is set in the constructor { Thread.Yield(); // Yield this threads remaining timeslice to another process, this process does not appear to need it currently because the read timed out } } //First we will receive the size of the message sizeOfMsg = BitConverter.ToInt32(msgSize, 0); byte[] requestBytes = new byte[sizeOfMsg]; ServiceBusResponse request = null; bytesRead = 0; while (bytesRead < requestBytes.Length) { try { bytesRead += connectionStream.Read(requestBytes, bytesRead, requestBytes.Length - bytesRead); } catch (SocketException) // This is thrown when the timeout occurs. The timeout is set in the constructor { Thread.Yield(); // Yield this threads remaining timeslice to another process, this process does not appear to need it currently because the read timed out } } MemoryStream memStream = new MemoryStream(requestBytes); BinaryFormatter binForm = new BinaryFormatter(); request = (ServiceBusResponse)binForm.Deserialize(memStream); return(request); }
/// <summary> /// Parses new account info and attempts to insert the new account into the authentication database /// It also publishes an "AccountCreated" event /// </summary> /// <returns>A response message</returns> private ServiceBusResponse attemptNewAccountCreation(CreateAccountRequest request) { CreateAccount command = request.createCommand; ServiceBusResponse dbResponse = AuthenticationDatabase.getInstance().insertNewUserAccount(command); if (dbResponse.result == true) { authenticated = true; username = command.username; password = command.password; initializeRequestingEndpoint(); eventPublishingEndpoint.Publish(new AccountCreated(command)); } return(dbResponse); }
public ServiceBusResponse insertNewChatMessage(ChatMessage chatmessage) { bool result = false; string message = ""; string sender = chatmessage.sender; string receiver = chatmessage.receiver; int timeStamp = chatmessage.unix_timestamp; string messagecontent = chatmessage.messageContents; ServiceBusResponse insertcontacts = insertNewChatContact(sender, receiver); string query = "INSERT INTO " + dbname + ".chatmessages(sender, receiver, timestamp, message) " + "VALUES ('" + sender + "','" + receiver + "','" + timeStamp + "','" + messagecontent + "');"; if (openConnection() == true) { try { MySqlCommand command = new MySqlCommand(query, connection); command.ExecuteNonQuery(); result = true; } catch (MySqlException e) { Messages.Debug.consoleMsg("Unable to complete insert new chat message into database." + " Error :" + e.Number + e.Message); Messages.Debug.consoleMsg("The query was:" + query); message = e.Message; } catch (Exception e) { Messages.Debug.consoleMsg("Unable to complete insert new chat message into database." + " Error:" + e.Message); message = e.Message; } finally { closeConnection(); } } else { message = "Unable to connect to database"; } return(new ServiceBusResponse(result, message)); }