Chat Application using SignalR in Asp.Net with mvc - javascript

I followed this link. In this site project will be working fine.but when i'm create new project by following this link UI will be opened but messgae passing not done.so please help me.
Html script:
#{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div id="divLogin" class="mylogin">
User Name:<input id="txtUserName" type="text" /><br />
<br />Password : <input id="txtPassword" type="password" /><br />
<input id="btnLogin" type="button" value="Login" />
<div id="divalarm"></div>
</div>
<div id="divChat" class="mylogin">
<input type="text" id="txtMessage" />
<input type="button" id="SendMessage" value="broadcast" />
<input type="hidden" id="displayname" />
<ul id="listMessages"></ul>
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
$("#divChat").hide();
$("#divLogin").show();
var IWannaChat = $.connection.chatHub;
IWannaChat.client.addMessage = function (name, message) {
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#listMessages').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
$("#SendMessage").click(function () {
IWannaChat.server.send($('#txtUserName').val(), $('#txtMessage').val());
});
$("#btnLogin").click(function () {
$("#divChat").show();
$("#divLogin").hide();
});
$.connection.hub.start();
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
ChatHub.cs:
public void send(string username, string message)
{
Clients.All.addMessage(username, message);
}
public void send1(string message)
{
Console.WriteLine("hi");
}
Thanks.

Related

How to get the url of your backend api to use it in jquery in html

I am writing a login form and I need to make an authentication for the username and password.
The form is written in dreamweaver html code. And the database is local in visual studio .net core code. I am still trying to figure out a way to use $post and $get methods, but I even can't write the url correctly. I am using swagger to host my api.
Here is my visual studio controller code :
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using authentication.Models;
using authentication.Repository;
using Microsoft.AspNetCore.Http;
namespace Taskb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private UsersRepository users = new UsersRepository();
private int count = 0;
[HttpGet]
public ActionResult<IEnumerable<user>> GetAllUser()
{
return users.GetAllUsers();
}
[HttpPost]
public ActionResult<user> CreateUser( user newUser)
{
foreach (user item in users.GetAllUsers())
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
}
}
And here is my html code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Roy Daher</title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial scale 1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
type="text/javascript"></script>
<!--include jQuery Validation Plugin-->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
</head>
<body bgcolor="#F1F1F1" class="body">
<div class="cont" >
<div class="top"></div>
<div class="bottom"></div>
<div class="center">
<form id="form" method="post">
<!--<div class="image">
<img src="images/28-287073_elonlol-discord-emoji-elon-musk-laughing-deer-hd.png" width="282" height="290" alt="Picture" class="elon">
</div>-->
<div class="container">
<label for="user"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="user" required id="userinput">
<label for="pass"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required id="passinput">
<button id="loginButton" type="button">Login</button>
<label for="remember">Remember me</label>
<input type="checkbox" checked="checked" name="remember">
</div>
<div class="container" style="background-color:#F1F1F1">
<span class="forgot">Forgot <a href="pages/PassRecovery.html" target="_blank" >password?</a></span>
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
$("button").click(function(){
var inputVal = document.getElementById("userinput").value;
var passVal = document.getElementById("passinput").value;
var obj ={
username:inputVal,
password:passVal
};
console.log(obj);
$.post("https://44332/api/User",
{
},
});
});
});
</script>
</html>
Thank you in advance for your help.
Your post method should use [FromBody] user newUser as the input parameter like below:
[HttpPost]
public ActionResult<user> CreateUser([FromBody] user newUser)
{
List<user> users = new List<user> {
new user{ username="a",password="a"},
new user{ username="b",password="b"},
new user{ username="c",password="c"}
};
foreach (user item in users)
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
And your ajax request should send like this:
<button id="loginButton">login</button>
<script>
$("#loginButton").click(function(){
var obj ={
username:"a",
password:"a"
};
$.ajax({
url: "https://localhost:44317/api/user",
type: 'post',
contentType: 'application/json',
data: JSON.stringify(obj),
success: function(data) {
alert(data);
}
})
});
</script>

How to save file in folder and show ?Jquery javascript

I'm developing a simple chatroom in which different user join chatroom and chat with each others.It working fine but i also want that users share pics or any other file with each other.How can i save file and show file .
How can i get input file and save in folder and show in divchatwindow as well.
ASPX CODE :
Chat Room
<div id="divContainer">
<div id="divLogin" class="login">
<div>
Your Name:<br />
<input id="txtNickName" type="text" class="textBox" />
</div>
<div id="divButton">
<input id="btnStartChat" type="button" class="submitButton" value="Start Chat" />
</div>
</div>
<div id="divChat" class="chatRoom">
<div class="title">
Welcome to Chat Room [<span id='spanUser'></span>]
</div>
<div class="content">
<div id="divChatWindow" class="chatWindow">
</div>
<div id="divusers" class="users">
</div>
</div>
<div class="messageBar">
<input class="textbox" type="text" id="txtMessage" />
<input id="btnSendMsg" type="button" value="Send" class="submitButton" />
<input type ="file" id="uploadfile" />
</div>
</div>
<input id="hdId" type="hidden" />
<input id="hdUserName" type="hidden" />
</div>
<script type="text/javascript">
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var userName = $('#hdUserName').val();
chatHub.server.sendMessageToAll(userName, msg);
$("#txtMessage").val('');
}
});
function AddMessage(userName, message) {
$('#divChatWindow').append('<div class="message"><span class="userName">' + userName + '</span>: ' + message + '</div>');
var height = $('#divChatWindow')[0].scrollHeight;
$('#divChatWindow').scrollTop(height);
}
</script>
chatHub.cs Class
public void SendMessageToAll(string userName, string message)
{
// store last 100 messages in cache
AddMessageinCache(userName, message);
// Broad cast message
Clients.All.messageReceived(userName, message);
}
private void AddMessageinCache(string userName, string message)
{
CurrentMessage.Add(new MessageDetail { UserName = userName, Message = message });
if (CurrentMessage.Count > 100)
CurrentMessage.RemoveAt(0);
}
MessageDetail.cs
public class MessageDetail
{
public string UserName { get; set; }
public string Message { get; set; }
}

How do I export Google Script form data to Google Drive?

I have built a very simple form in google scripts. The file upload feature is functional: it uploads a file to my google drive. I cannot figure out how to grab the form information (Name, Organization, Content Type), save it into a spreadsheet, and upload that to my google drive.
How do I upload the form data (text fields) to my drive?
!!UPDATE 7/19!!
Code updated with Spreadsheet App code. and improved HTML. CSS not included as I don't think it's relevant to this issue.
!!UPDATE 7/20!!
Code is working. Updated to reflect full functionality. Thanks to Sandy for the assistance.
form.html
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<div id="main">
<div class="form">
<form id='myForm'>
<div class="header">
<h1>Information Submission Form</h1>
<h2>Center For Alternative Fuels</h2>
</div>
<div class="row">
<div class="col-md-6">
<input id='name' type="text" name="name" placeholder="Full name" class="full item" spellcheck="false">
</div>
<div class="col-md-6">
<input id='email' type="text" name="email" placeholder="Email" class="full item" spellcheck="false">
</div>
</div>
<div class="row indent item">
<input id='organization' type="text" name="organization" placeholder="Organization" class="full" spellcheck="false">
</div>
<div class="row indent item">
<textarea id='type' name="type" class="full" placeholder="What are you submitting? (Presentation, Educational Content,...)" rows='2'></textarea>
</div>
<div id='success'>
</div>
<div class="row indent item">
<textarea id='info' name="info" class="full" placeholder="Describe the content you are submitting" rows='8'></textarea>
</div>
<input type="file" name="myFile">
<input type="submit" value="Submit"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;" style="margin-top: 20px">
</form>
</div>
</div>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
server.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
var url;
function uploadToSheet(form){
var fullName, emailAdd, organization, fileType, fileInfo;
var ss = SpreadsheetApp.openById("INSERT SHEET ID HERE");
var dataArray = [];
fullName = form.name;
emailAdd = form.email;
organization = form.organization;
fileType = form.type;
fileInfo = form.info;
dataArray.push(fullName);
dataArray.push(emailAdd);
dataArray.push(organization);
dataArray.push(fileType);
dataArray.push(fileInfo);
ss.appendRow('dataArray');
}
function uploadFiles(form) {
try {
var dropbox = "Form Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
}
else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
url=file.getUrl();
return "File uploaded successfully " + file.getUrl();
}
catch (error) {
return error.toString();
}
}
The code might look something like this:
var dataArray,org,ss,userName;
ss = SpreadsheetApp.openById("spreadsheet_File_ID");
dataArray = [];
userName = form.myName;
org = form.myOrganization;
dataArray.push(userName);
dataArray.push(org);
ss.appendRow(dataArray);

textarea.val() sends original value not edited

I have this textarea in my MVC project
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
but when I try to send this to a Json call like this
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
I get the original value of #Model.content instead of the new value.
Edit
my script.js code
function updateComment(id, title, content) {
return $.get("/Chapter/GetJSON_Update",
{
id: id,
title: title,
content: content
},
'json');
};
the entire code from my Edit.cshtml
#model Academia_Unitate.Models.Chapter
#{
ViewBag.Title = "Edit " + Model.title;
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("~/Views/Shared/_TinyMCE.cshtml")
<div id="edit">
<h1>
Edit #Model.type.name
</h1>
<div class="" role="form">
<div class="form-group">
<label class="sr-only" for="title">Title</label>
<input class="form-control" type="text" id="edit-title" placeholder="Enter a title" value="#Model.title" required="required" />
</div>
<div class="form-group">
<label class="sr-only" for="content">Content</label>
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
</div>
<button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> Save</button>
<span id="message-edit-loading" class="alert hidden"></span>
<span id="message-edit-error" class="alert alert-danger hidden"></span>
</div>
</div>
<input type="hidden" value="#Model.id" id="edit-id"/>
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
You most likely have more than one on your page, either make their id attributes unique or target the index in your jQuery.

No change when click on login button in ios phonegap app

My index.html page is:
<link rel="stylesheet" href="../css/jquery.mobile-1.3.1.min.css">
<link rel="stylesheet" type="text/css" href="../css/style.css" />
<script src="../js/jquery-1.9.1.min.js"></script>
<script src="../js/jquery.mobile-1.3.1.min.js"></script>
<script src="../js/common.js"></script>
<script src="../js/cordova.js"></script>
<script src="../js/jstorage.js"></script>
<script type="text/javascript">
$(document).ready(function(){
loadHeader("YSN Login", false);
});
</script>
</head>
<body>
<!-- Home -->
<div id="header"></div>
<div class="firstDiv"></div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain">
<label for="textinput6">
Email Address
</label>
<input name="username" id="username" type="text" onkeyup="toggle(this)" value="">
</div>
<span class="ValidationErrors" id="userNameMsg" style="display: none;">Should be a valid Email Id</span>
<div data-role="fieldcontain">
<label for="textinput6">
Password
</label>
<input name="password" id="password" type="password" onkeyup="toggle(this)" value="" class="btn btn-8 btn-8a">
</div>
<span class="ValidationErrors" id="passwordMsg" style="display: none;">Should be a valid password</span>
<a data-role="button" data-theme="b" onclick="loginUser();">
Login
</a>
<div>
<a href ="#" onclick="openSelfWindow('resetPassword.html')" data-transition="fade">
Forget your password?
</a>
</div>
</form>
and my loginUser function which runs on click of login button, I am calling restful web services through ajax
function loginUser(){
var loginData = new Object();
loginData.username = $("#username").val();
loginData.password = $("#password").val();
var loginObj = new function(){
this.url = ysnURL + "userservice/login/user/"
this.data = JSON.stringify(loginData)
this.success = loginSuccess
this.error = loginError
this.beforeSend = validateLoginForm//validates the login form
}
tugnavAjaxPOST(loginObj);
}
function loginSuccess(data){
console.debug(JSON.stringify(data));
stopSpinner();
if(data.success == "true"){
setSession($.parseJSON(data.message));
var ref = openSelfWindow("dashboard.html");
}
else{
showAlert("YSN Login", data.message, function(){});
}
}
function loginError(data){
console.debug(JSON.stringify(data));
stopSpinner();
showAlert("YSN Login", "Error while logging to YSN", function(){});
}
I am ruuning this app on ios simulator, when I click on resetpassword link it takes me to the next page but clicking on login button does not show any alert or in simple words screen remains same.The same code is running properly for android but not for ios,even I have included the cordova.js file for ios then also the problem remains same.

Categories