how to update my notification? - asp.net

i made an application that allow me to open conversation between friends, when someone send me a message i got a notification "John send you a new message" and when another person in the conversation send me a message a new notification is made ,,, my problem is that i don't want to make a new notification but i want to update the old notification to be for ex. like this " John and Alfred send you a new message"..
var user = users.Where(x => x != CurrentUserId);
foreach (var item in user)
{
var check = entities.Notifications.SingleOrDefault(i => (i.NotificationForId == id
&& i.NotificationForType == IdType && i.UserId == item));
if (check == null)
{
Notification notify = new Notification()
{
NotificationForId = id,
NotificationForType = IdType,
DateTime = DateTime.Now,
Message = GenerateMessage(),
UserId = item,
SenderID = CurrentUserId.ToString(),
SenderName = CurrentUserName
};
entities.Notifications.AddObject(notify);
}
else
{
check.Checked = false;
check.DateTime = DateTime.Now;
}
here it check if there are any notification for a user , if null then make a new notification else " Update the notification "

Your else block indicates the notification exists on the database, you can update the properties there. To save the changes made, both for insert and update call the method entities.SaveChanges()

Related

How to keep user logged in when using FB plugin to sign in?

I am trying to find out how to keep user logged in. I am using Facebook Plugin and storing the user data in CosmosDB, however i am not sure what data do i need to keep the user logged in or when to actually ask his permission as i am redirected straight to Facebook login.
This is the code that i am using to sign in
async Task LoginFacebookAsync(User user)
{
try
{
if (_facebookService.IsLoggedIn)
{
_facebookService.Logout();
}
EventHandler<FBEventArgs<string>> userDataDelegate = null;
userDataDelegate = async (object sender, FBEventArgs<string> e) =>
{
if (e == null) return;
switch (e.Status)
{
case FacebookActionStatus.Completed:
var facebookProfile = await Task.Run(() => JsonConvert.DeserializeObject<FacebookProfile>(e.Data));
var socialLoginData = new User
{
UserEmail = facebookProfile.Email,
UserName = $"{facebookProfile.FirstName} {facebookProfile.LastName}",
Id = facebookProfile.UserId,
};
user.UserEmail = socialLoginData.UserEmail;
user.UserName = socialLoginData.UserName;
user.Id = socialLoginData.Id;
user = await UserViewModel.GetOrCreateUser(user);
UserViewModel.SetUser(user);
await App.Current.SavePropertiesAsync();
App.Current.MainPage = new AppShell();
break;
case FacebookActionStatus.Canceled:
break;
}
_facebookService.OnUserData -= userDataDelegate;
};
_facebookService.OnUserData += userDataDelegate;
string[] fbRequestFields = { "email", "first_name", "gender", "last_name" };
string[] fbPermisions = { "email" };
await _facebookService.RequestUserDataAsync(fbRequestFields, fbPermisions);
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
Please if you could help how to approach this.
You may use local db like Sqlite or Settings Plugin to save the authentication token, expire date etc. So when the app run you can check them and let the user automatically login or not.

Firebase UI Email Link signin intent extra is null

The following 3 functions are used to set up email and other auth checks (called in order)
private void buildSignInIntentBuilder() {
ActionCodeSettings actionCodeSettings = ActionCodeSettings.newBuilder()
.setAndroidPackageName(getString(R.string.packageName), true, null)
.setHandleCodeInApp(true)
.setUrl(getString(R.string.dynamic_link_url))
.build();
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.EmailBuilder()
.enableEmailLinkSignIn()
.setActionCodeSettings(actionCodeSettings)
.build(),
// new AuthUI.IdpConfig.EmailBuilder().setRequireName(false).build(),
new AuthUI.IdpConfig.PhoneBuilder()
.build(),
new AuthUI.IdpConfig.GoogleBuilder()
.build(),
new AuthUI.IdpConfig.FacebookBuilder()
.build());
signInIntentBuilder = AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.setLogo(R.drawable.icon_forget_me_not_1);
}
private void catchEmailLinkSignIn() {
Log.d(TAG, "Intent: " + getIntent().getExtras());
if (AuthUI.canHandleIntent(getIntent())) {
if (getIntent().getExtras() == null) {
return;
}
String link = getIntent().getExtras().getString(ExtraConstants.EMAIL_LINK_SIGN_IN);
Log.d(TAG, "link: " + link);
if (link != null) {
signInIntentBuilder.setEmailLink(link);
}
}
}
private void createCheckAndSigninListener() {
// set firebase sign in listener
mAuthStateListner = firebaseAuth -> {
// Already logged in
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "user already signed in");
// Check user even if signed in to register him to database (if haven't)
FirebaseAuthHelper.getInstance().checkRegisterUser(user, this, CHECK_USER_DB);
} else {
Log.d(TAG, "user hasn't signed in");
// Signed out or hasn't logged in
startActivityForResult(
signInIntentBuilder
.build(),
RC_SIGN_IN
);
}
};
}
I have set up a dynamic link with firebase hosting. And being able to redirect into the same activity upon clicking the received email link.
However,
String link = getIntent().getExtras().getString(ExtraConstants.EMAIL_LINK_SIGN_IN);
Log.d(TAG, "link: " + link); // --> produces "link: null"
Shows despite successfully getting a intent, there is no EMAIL_LINK_SIGNIN extra in the getExtras(). I spend few hours looking into the source code of FirebaseUi, but I didn't find where the constant EMAIL_LINK_SIGN_IN is used and how is the intent from dynamic link parsed.
Any idea how to fix this problem is appreciated. I had already spent a whole day trying to figure this out.
Instead of using String link = getIntent().getExtras().getString(ExtraConstants.EMAIL_LINK_SIGN_IN);
use getIntent().getData().toString(); instead.

how to update database fields by checking the success of sending email?

I am trying to make a form in google app maker. I've created a form. which has a "preview(save" button, It will create a new item and I have a field named "status". The default value of this field is "draft". In the next page I have a "sent email" button. This page won't create any new item. It'll send the email and if the email deliver is successful then it'll update the field of status from "draft" to "completed"
This is my client script
function sendMessage(to, subject, msg){
// some part is omitted
var status = app.popups.NotificationDialog.descendants.notificationText;
var success = app.datasources.ChangeSystem;
google.script.run
.withFailureHandler(function(error){
// success.Success = "draft"
status.text = error.message;
})
.withSuccessHandler(function(result){
status.text = 'sent';
success.Success = "completed";
clearEmailForm();
})
.sendEmailMessage(to, subject, msg);
}
and this is my email sent button function
var widgets = app.pages.Email.descendants;
var to;
var subject = widgets.systemName.value
var msg = "Description:\n\t\t" + widgets.Objective.value;
widgets.EmailStatus.text = 'Sending email...';
sendMessage(to, subject, msg);
So far I am successful to send the email also I have created and saved all fields. But the problem is after sending the email the "status" field doesn't update. It remains the same as default value "draft". my expected result is after pressing the send button it will update one of the existing fields.
After some additional thinking on this topic I think I found the problem. Here is some updated code assuming your send email button is the same inherited datasource as the field that you are trying to update.
var success = widget.datasource.item;
google.script.run
.withFailureHandler(function(error)
status.text = error.message;
success.Success = 'draft';
})
.withSuccessHandler(function(result) {
status.text = 'Email sent';
success.Success = 'completed';
clearEmailForm();
})
.sendEmailMessage(to,subject, msg);

Apple Notification Failed: ID=2, Code=ConnectionError

I'm using PushSharp 4.0.4, installed from NuGet
In the OnNotificationFailed(ApnsNotification, AggregateException) event of the Apns broker, I often get this exception:
Apple Notification Failed: ID=2, Code=ConnectionError .
According to me it appears due to p12 file. It may not have all the right to access by the external API.
private void SendPushNotification(string deviceToken, string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("Certificates.p12"));
//Configuration(NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox ,appleCert, "1234567890");
//Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
//Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = $"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
lblStatus.Text = desc;
}
else
{
string desc = $"Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
lblStatus.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
lblStatus.Text = "Apple Notification Sent successfully!";
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
// Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
};
//Start Proccess
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception)
{
throw;
}
}
I'm using PushSharp 4.0.4, installed from NuGet .
To be run APNS push notification in C#.I got an error:
Apple Notification Failed: ID=1, Code=ConnectionError
Solution:
In this Error to Export key chain private key certificate .p12 format and place the certificate try again.To be get the out put.

Login users at the same time problems in signalr

I'm working on a social network with ASP.NET and signalr. I have a simple login page, if it finds the user in the database it creates an Application variable and redirect the user to the profile page and in this page i invoke my Connect method declared in my hub class, this method takes the userid in the session and it give the friend list of this user. That works great when two or many users logged in at different time. The thing is, when two or several users logged in at the same time, the connect method declared in my hub takes the last user id stored in the Application variable and it give the friend list of this last user id and it send it to all user connected.
I can't find the correct approach.
Loggin Page code:
protected void btn_login_Click(object sender, EventArgs e)
{
Tbl_User user = new Tbl_User();
user = FonctionCommun.Login(txt_UserName.Text , txt_PassWord.Text);
if (user != null)
{
Application["UserID"] = user.UserID.ToString();
Response.Redirect("Profile.aspx");
}
else {
Label1.Visible = true;
}
}
My connect method code:
public void connect()
{
UserID = Guid.Parse(HttpContext.Current.Application["UserID"].ToString());
string OutPut = "";
if (ListOnlineUser.Count(x => x.UserID == UserID) == 0)
{
ListOnlineUser.Add(new OnlineUsers { UserID = UserID, ConnetionID = Guid.Parse(Context.ConnectionId) });
objchat.SetOnline(UserID);
ListFriends = objchat.GetFriendLoginStatus(UserID);
}
foreach (Tbl_User item in ListFriends)
{
if (item.Status == "1")
{
OnlineUsers onlineFriend = ListOnlineUser.FirstOrDefault(x => x.UserID == Guid.Parse(item.UserID.ToString()));
if (onlineFriend != null)
{
using (FIESTA_ADVISOREntities BD = new FIESTA_ADVISOREntities())
{
Tbl_User Obj_User = BD.Tbl_User.Where(o => o.UserID == UserID).FirstOrDefault();
if (Obj_User.ProfileImage != null)
{
string ext = BD.Assets.Where(o => o.url == Obj_User.ProfileImage).Select(o => o.MimeType).FirstOrDefault();
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = Obj_User.ProfileImage.ToString(), Ext = ext };
OutPut = JsonConvert.SerializeObject(res);
}
else {
UserDetaille res = new UserDetaille() { UserID = Guid.Parse(Obj_User.UserID.ToString()), Username = Obj_User.UserName, ProfileImage = "111", Ext = "png" };
OutPut = JsonConvert.SerializeObject(res); }
Clients.Client(onlineFriend.ConnetionID.ToString()).OnNewUserConnect(OutPut);
}
}
}
}
Clients.Caller.ShowFriends(ListFriends);
}
Try session variable instead of application variable. Application variable shared through out application working. So Whenever new user this is override. But if you use session variable that will never override by any other user
Also you can use query string in signalr in which you can pass userid as query string so in each request userid will be in query string
$.connection.hub.qs = 'userid=' + "UserId";

Resources