BrightSoul ha scritto:
Uhm, non ho ben capito lo scenario. Se devi realizzare una chat puoi certamente usare Sql Server per memorizzare i messaggi: quando il tuo Hub di ASP.NET SignalR riceve un messaggio, salvalo nel db e poi invialo a tutti gli altri client.
Ciao Moreno, prima di tutto grazie ancora per la risposta e si ho fatto una cosa del genere, cercando di capire tra la documentazione e gli esempi che stanno in giro (anche se sono per lo più orientati al MVC).
iL mio problema sta nel fatto che ad ogni messaggio inviato mi mantiene tutta la tabella precedente e riportando dinuovo il tutto nel front (mentre nel DB il msg è singolo).
Per capire nella "chat" avviene questo
invio msg:
1
invio 2 msg:
1
1
2
ecc....
ora ti posto un elenco dei file che tengo.
NEL MIO WEBFORM
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.chatHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start({ transport: 'longPolling' } );
getData();
});
function getData() {
var $tbl = $('#tbl');
$.ajax({
url: 'Chat.aspx/GetData',
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (data) {
//debugger;
if (data.d.length > 0) {
newdata = data.d;
$tbl.empty();
var rows = [];
for (var i = 0; i < newdata.length; i++) {
rows.push(' <tr><td>' + newdata[i].Id + '</td><td>' + newdata[i].Username +
$tbl.append(rows.join(''));
}
}
}
});
}
</script>
NEL CODEBEHIND DELLA WEB FORM ( messaggi è una classe con delle proprietà)
<WebMethod>
Public Shared Function GetData() As List(Of messaggi)
Using connection = New SqlConnection(ConfigurationManager.ConnectionStrings("DatabaseSQL").ConnectionString)
connection.Open()
Dim lstRecords = New List(Of messaggi)()
lstRecords.Clear()
Using command As SqlCommand = New SqlCommand("select id, username, messaggio, tipomessaggio,inviaa from chat_1", connection)
command.Notification = Nothing
Dim dependency As SqlDependency = New SqlDependency(command)
AddHandler dependency.OnChange, AddressOf Dependency_OnChange ' += new onchangeeventhandler(dependency_onchange)
If connection.State = ConnectionState.Closed Then connection.Open()
Using reader = command.ExecuteReader()
'lstRecords.ingresso =
lstRecords = reader.Cast(Of IDataRecord)().[Select](Function(x) New messaggi() With {.Id = x.GetInt32(0), .Username = x.GetString(1), .Messaggio = x.GetString(2), .TipoMessaggio = x.GetInt32(3), .InviaA = x.GetString(4)}).ToList()
Return lstRecords
End Using
End Using
End Using
End Function
Private Shared Sub Dependency_OnChange(ByVal sender As Object, ByVal e As SqlNotificationEventArgs)
'If (e.Type = SqlNotificationType.Change) Then
ChatHub.Show()
'End If
End Sub
Private Sub BtnInvia_Click(sender As Object, e As EventArgs) Handles BtnInvia.Click
Dim client = New Net.WebClient()
client.Headers.Add("apikey", ConfigurationManager.AppSettings("apikey"))
Dim data = New NameValueCollection()
Dim username As String = String.Empty
If (Request.Cookies("UserSettings") IsNot Nothing) Then
username = Request.Cookies("UserSettings")("Username")
End If
Dim InviaA As String = 0
Dim TipoMessaggio As Integer = 1
Dim testo As String = TxtMessaggio.Text
''SUSSURRO''
Dim controlloStringa As Boolean = testo.Contains("@")
If controlloStringa AndAlso (testo.IndexOf("@") = 0) Then
Dim sussurro As String() = Split(testo, "@")
If sussurro.Length = 3 Then
InviaA = sussurro(1)
testo = sussurro(2)
TipoMessaggio = 2
End If
End If
With data
.Add("Username", username)
.Add("Messaggio", testo)
.Add("TipoMessaggio", TipoMessaggio)
.Add("InviaA", InviaA)
End With
Dim result = client.UploadValues(ConfigurationManager.AppSettings("EndPointUrl") & "Chat/Inserisci", data)
'Dim ObjectResult As ServicesResult.ObjectResult = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ServicesResult.ObjectResult)(Encoding.ASCII.GetString(result))
'If Not ObjectResult.ErrorResult Then
' Dim _result As List(Of Models.Missiva) = Newtonsoft.Json.JsonConvert.DeserializeObject(Of List(Of Models.Missiva))(ObjectResult.ValueResult.ToString)
' listaMissive.DataSource = _result
' listaMissive.DataBind()
'Else
' Response.Write(ObjectResult.ErrorMessage)
'End If
TxtMessaggio.Text = ""
TxtMessaggio.Focus()
End Sub
NEL MIO HUB
<HubName("chatHub")>
Public Class ChatHub
Inherits Hub
Public Shared Sub Show()
Dim context As IHubContext = GlobalHost.ConnectionManager.GetHubContext(Of ChatHub)()
context.Clients.All.DisplayStatus()
End Sub
End Class