Hi Xamarin forum
I just found a chat plugin in google and I want to modify it, (tried but unsuccessful when I modify it) coz I want to remove that popup window that ask what would be the name to be displayed in the chatroom and it triggers connection to the api of the chat what I want is
- remove that popup window
- the credentials of my login will be used to connect to the chat
anyway I will post the code of my login and that chat codes
Login.cs
async void LogIn(object sender, EventArgs e)
{
Pipeline databaseConnect = new Pipeline();
var page = new LoadingPage();
var user = new User
{
Username = usernameEntry.Text,
Password = passwordEntry.Text
};
try
{
await PopupNavigation.Instance.PushAsync(page);
SqlCommand selectTbl = new SqlCommand("SELECT Username, Password, Firstname, Lastname FROM tblname WHERE Username='"+user.Username+"'AND Password='"+user.Password+"'", databaseConnect.connectDB());
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectTbl);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
if (dataTable.Rows.Count > 0)
{
App.IsUserLoggedIn = true;
App.Username = usernameEntry.Text.ToString();
App.Password = passwordEntry.Text.ToString();
App.FirstName = dataTable.Rows[0]["Firstname"].ToString();
App.LastName = dataTable.Rows[0]["Lastname"].ToString();
Navigation.InsertPageBefore(new LoadingDataPage(), this);
await PopupNavigation.Instance.PopAsync();
await Navigation.PopAsync();
}
else
{
await DisplayAlert("Wrong Password","Please type your Username / Password","OK");
await PopupNavigation.Instance.PopAsync();
}
databaseConnect.connectDB().Dispose();
}
catch(Exception ex)
{
await DisplayAlert("Error","There's something wrong with the internet, Please try again.","OK");
await PopupNavigation.Instance.PopAsync();
}
}
ChatView Model
public class ChatViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
private string _message;
private ObservableCollection<ChatMessage> _messages;
private bool _isConnected;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged();
}
}
public string Message
{
get
{
return _message;
}
set
{
_message = value;
OnPropertyChanged();
}
}
public ObservableCollection<ChatMessage> Messages
{
get
{
return _messages;
}
set
{
_messages = value;
OnPropertyChanged();
}
}
public bool IsConnected
{
get
{
return _isConnected;
}
set
{
_isConnected = value;
OnPropertyChanged();
}
}
private HubConnection hubConnection;
public Command SendMessageCommand { get; }
public Command ConnectCommand { get; }
public Command DisconnectCommand { get; }
public ChatViewModel()
{
Messages = new ObservableCollection<ChatMessage>();
SendMessageCommand = new Command(async () => { await SendMessage(Name, Message); });
ConnectCommand = new Command(async () => await Connect());
DisconnectCommand = new Command(async () => await Disconnect());
IsConnected = true;
hubConnection = new HubConnectionBuilder()
.WithUrl($"http://xxx.xx.xxx.xxx:5000/Hub")
.Build();
hubConnection.On<string>("JoinChat", (user) =>
{
Messages.Add(new ChatMessage() { User = Name, Message = $"{user} has joined the chat", IsSystemMessage = true });
});
hubConnection.On<string>("LeaveChat", (user) =>
{
Messages.Add(new ChatMessage() { User = Name, Message = $"{user} has left the chat", IsSystemMessage = true });
});
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
Messages.Add(new ChatMessage() { User = user, Message = message, IsSystemMessage = false, IsOwnMessage = Name == user });
});
}
async Task Connect()
{
var page = new LoadingPage();
await PopupNavigation.Instance.PushAsync(page);
await hubConnection.StartAsync();
await hubConnection.InvokeAsync("JoinChat", Name);
await PopupNavigation.Instance.PopAsync();
IsConnected = true;
}
async Task SendMessage(string user, string message)
{
await hubConnection.InvokeAsync("SendMessage", user, message);
Pipeline sqlConnection = new Pipeline();
if (sqlConnection.connectDB().State == System.Data.ConnectionState.Open)
{
SqlCommand sqlInsert = new SqlCommand("INSERT INTO tblname(chatName, messageContent)" +
"VALUES(@chatName, @MessageChat)", sqlConnection.connectDB());
//sqlInsert.Parameters.AddWithValue("@chatName", emailfield.Text);
sqlInsert.Parameters.AddWithValue("@chatName", user);
sqlInsert.Parameters.AddWithValue("@MessageChat", message);
int i = sqlInsert.ExecuteNonQuery();
sqlConnection.connectDB().Close();
}
}
async Task Disconnect()
{
await hubConnection.InvokeAsync("LeaveChat", Name);
await hubConnection.StopAsync();
var homepage = new HomePage();
var page = new LoadingPage();
await PopupNavigation.Instance.PushAsync(page);
Application.Current.MainPage = new NavigationPage(homepage);
await PopupNavigation.Instance.PopAsync();
IsConnected = false;
}
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Chat.xaml
<ContentPage.Resources>
<ResourceDictionary>
<converters:InverseBoolConverter x:Key="InverseBool" />
</ResourceDictionary>
</ContentPage.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<BoxView BackgroundColor="Black"/>
<Label
Margin="10"
FontSize="20"
HorizontalOptions="FillAndExpand"
HorizontalTextAlignment="Start"
TextColor="White" />
<Label
Margin="10"
FontSize="20"
HorizontalOptions="End"
HorizontalTextAlignment="Start"
Text="Close"
TextColor="White">
<Label.GestureRecognizers>
<TapGestureRecognizer Command="{Binding DisconnectCommand}" />
</Label.GestureRecognizers>
</Label>
<ListView
Grid.Row="1"
FlowDirection="RightToLeft"
HasUnevenRows="True"
ItemsSource="{Binding Messages}"
SeparatorVisibility="None"
VerticalOptions="End">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Grid>
<Grid IsVisible="{Binding IsSystemMessage}">
<Label
Margin="20,5"
FontSize="16"
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
Text="{Binding Message}"
TextColor="#969daf" />
</Grid>
<Grid IsVisible="{Binding IsSystemMessage, Converter={StaticResource InverseBool}}">
<Grid IsVisible="{Binding IsOwnMessage, Converter={StaticResource InverseBool}}" RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label
Grid.Column="1"
Margin="10,0"
HorizontalOptions="End"
HorizontalTextAlignment="End"
Text="{Binding User}"
TextColor="#969daf" />
<Grid
Grid.Row="1"
Grid.Column="1"
Margin="20,5"
Padding="10"
HorizontalOptions="End"
VerticalOptions="FillAndExpand">
<BoxView
BackgroundColor="#f5f9fa"
CornerRadius="30"
HorizontalOptions="FillAndExpand" />
<Label
Margin="10"
LineBreakMode="CharacterWrap"
Text="{Binding Message}"
TextColor="#696f7f"
VerticalOptions="FillAndExpand" />
</Grid>
</Grid>
<Grid IsVisible="{Binding IsOwnMessage}" RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label
Margin="10,0"
HorizontalOptions="Start"
Text="{Binding User}"
TextColor="#969daf" />
<Grid
Grid.Row="1"
Margin="20,5"
Padding="10"
HorizontalOptions="Start"
VerticalOptions="FillAndExpand">
<BoxView
BackgroundColor="#2ac2c5"
CornerRadius="30"
HorizontalOptions="FillAndExpand" />
<Label
Margin="10"
LineBreakMode="CharacterWrap"
Text="{Binding Message}"
TextColor="White"
VerticalOptions="FillAndExpand" />
</Grid>
</Grid>
</Grid>
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Grid
Grid.Row="2"
ColumnSpacing="0"
RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="70" />
</Grid.ColumnDefinitions>
<Entry
BackgroundColor="#f5f9fa"
Placeholder="Message"
PlaceholderColor="#969daf"
Text="{Binding Message}"
x:Name="ChatEntry"
TextColor="Black" />
<Button
Grid.Column="1"
Command="{Binding SendMessageCommand}"
HorizontalOptions="FillAndExpand"
Text="Send"
VerticalOptions="FillAndExpand" />
</Grid>
The following line is the one that triggers the pop up windows
<Grid
Grid.RowSpan="3"
BackgroundColor="#99FFFFFF"
IsVisible="{Binding IsConnected, Converter={StaticResource InverseBool}}">
<StackLayout
Margin="20,40"
BackgroundColor="White"
HorizontalOptions="Center"
VerticalOptions="Center">
<Label
HorizontalOptions="Center"
Text="Continue As"
TextColor="Black"
VerticalOptions="Center" />
<Entry
BackgroundColor="#f5f9fa"
Placeholder="Name"
x:Name="NameHolder"
PlaceholderColor="#969daf"
Text="{Binding Name}"
WidthRequest="150" />
<Button
Grid.Column="1"
Command="{Binding ConnectCommand}"
HorizontalOptions="FillAndExpand"
Text="Submit"
VerticalOptions="FillAndExpand" />
End of popup code
</StackLayout>
</Grid>
</Grid>
Hope someone can help me out here
Thanks in advance