I have a asp.net web forms site which runs well in PC. However when I try to access it from mobile it gives an object reference error. The site is asp.net 4.5.1 and used normal asp.net server controls.
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoginView lView = (LoginView)this.Master.FindControl("LoginView1");
lView.Visible = false;
if (Request.QueryString["exp"] != null)
{
string msg = "Session expired please login.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
ManchesterContext context = new ManchesterContext();
if (Membership.ValidateUser(txtUserId.Text, txtPassword.Text))
{
MembershipUser user = Membership.GetUser(txtUserId.Text);
aspnet_Users dbUser = context.aspnet_Users.Where(u => u.UserName.Equals(user.UserName)).FirstOrDefault();
if (dbUser.PassUpdated)//This means user has already changed default password. Perform login.
{
SetAuthenticationCookie(user);
aspnet_Users dbEntry = context.aspnet_Users.Where(u => u.UserName == user.UserName).FirstOrDefault();
SessionInfo.InitSession(dbEntry.UserId, dbEntry.UserName);
Session.Add("USR_KEY", dbEntry.UserId);
FormsAuthentication.RedirectFromLoginPage(user.UserName,false);
}
else //User has not updated default password.
{
Session.Add("TEMP_USR", txtUserId.Text);
Session.Add("TEMP_PASS", txtPassword.Text);
Response.Redirect("ChangePassword.aspx");
}
}
else
{
string msg = "Invalid User Id or Password.";
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "$(function() { LoginFail('" + msg + "'); });", true);
}
}
public void SetAuthenticationCookie(MembershipUser user)
{
Response.Cookies.Clear();
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName)
{
Expires = System.DateTime.Now.AddDays(-1),
HttpOnly = true
};
HttpContext.Current.Response.Cookies.Add(cookie);
return;
}
}
Related
I'm a beginner in android xamarin programming and I'm trying to develop an app that needs to send a report mail using company cloud services (office365).
The main problem is that the user has no computer skills, therefore it is necessary to authenticate the app on azure (no login done by the user).
what is the correct identification flow? and what is the correct credential provider? ( on windows in a console app i used ClientSecretCredential, and it works fine!)
on android i tried :ClientSecretCredential, InteractiveBrowserCredential and UsernamePasswordCredential but i receive always the same error :
Message: An error occurred sending the request.
I don't understand if the request is not even sent or not answered or what?
here is my code:
async private void Button_buttonSendReport(object sender, EventArgs e)
{
AzureSettings settings = new AzureSettings();
settings.LoadSettings();
GraphHelper.InitializeGraphForAppOnlyAuth(settings);
try
{
await GraphHelper.SendMailAsync("Testing Microsoft Graph", "Hello!", "recipient#inwind.it");
Android.Widget.Toast.MakeText(this, "Mail sent.", Android.Widget.ToastLength.Long).Show();
}
catch (Exception ex)
{
Android.Widget.Toast.MakeText(this, "Error sending mail:"+ex.Message, Android.Widget.ToastLength.Long).Show();
}
}
public class AzureSettings
{
public string? ClientId { get; set; }
public string? ClientSecret { get; set; }
public string? TenantId { get; set; }
public string? AuthTenant { get; set; }
public string? redirectUri { get; set; }
public string[]? GraphUserScopes { get; set; }
public AzureSettings LoadSettings()
{
// Load settings
ClientId = "xxxxxxx-xxxx-xxxxxx-xxxx-xxxxxxxxx";
ClientSecret = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
TenantId = "zzzzzzzz-zzzzz-zzzzz-zzzzzzz-zzzzzzzzzzzz";
AuthTenant = "common";
GraphUserScopes = new[] { "User.Read.All", "User.Read", "Mail.Send" };
redirectUri = "msauth://com.companyname.packageName/<signature_of_app >";
return this;
}
}
this is initialization of client GraphHelper.InitializeGraphForAppOnlyAuth(settings);
public static void InitializeGraphForAppOnlyAuth(AzureSettings settings)
{
_settings = settings;
if (_appClient == null)
{
var options = new InteractiveBrowserCredentialOptions
{
TenantId = _settings.TenantId,
ClientId = _settings.ClientId,
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
RedirectUri = new Uri(_settings.redirectUri),
};
// https://learn.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
var interactiveCredential = new InteractiveBrowserCredential(options);
_appClient = new GraphServiceClient(interactiveCredential, _settings.GraphUserScopes);
}
}
this is GraphHelper.SendMailAsync
public static async Task SendMailAsync(string subject, string body, string recipient)
{
// Create a new message
var message = new Microsoft.Graph.Message
{
Subject = subject,
Body = new ItemBody
{
Content = body,ContentType = BodyType.Text
},
ToRecipients = new Recipient[]
{
new Recipient{EmailAddress = new EmailAddress {Address=recipient}}
}
};
await _appClient.Users["kkkkkkkkk-kkkkkk-kkkk-kkkkk-kkkkkkkkk"].SendMail(message).Request().PostAsync();
}
guys.
I'm trying to use vk api sdk in Xamarin.Android. I create a request:
var token = VKHelper.GetVkUserToken(App.Data.Setting.List);
var iparams = new Dictionary<string, Java.Lang.Object>();
iparams.Add(VKApiConst.UserId, VKBuffer.Friend.Id);
iparams.Add("type", "invite");
iparams.Add("access_token", token);
v = new VKRequest("apps.sendRequest", new VKParameters(iparams));
By clicking in button I call ExecuteWithListener:
v.ExecuteWithListener(new ReqvList(new Action(o =>
{
RunOnUiThread(() =>
{
if (o.IsComplete)
{
try
{
showCustomAlert(Resource.Drawable.checkmark, GetString(Resource.String.SentInvite), Android.Graphics.Color.Argb(100, 0, 0, 200));
}
catch { }
}
else
{
try
{
showCustomAlert(Resource.Drawable.ic_post, GetString(Resource.String.NotSentInvite) + "\n" + GetString(o.MessageId), Android.Graphics.Color.Argb(100, 200, 0, 0));
}
catch { }
}
});
})));
Listener:
public class ReqvList : VKRequest.VKRequestListener
{
Action<CallBackVKResponse> Complete;
CallBackVKResponse callBackVKResponse = new CallBackVKResponse
{
IsComplete = false,
MessageId = 0
};
public ReqvList(Action<CallBackVKResponse> Complete)
{
this.Complete = Complete;
}
public override void OnComplete(VKResponse p0)
{
base.OnComplete(p0);
var response = p0.Json.ToString();
callBackVKResponse.IsComplete = true;
Complete(callBackVKResponse);
}
public override void OnError(VKError p0)
{
int errorCode = p0.ApiError != null ? p0.ApiError.ErrorCode : 0;
callBackVKResponse.IsComplete = false;
if (errorCode == 15)
callBackVKResponse.MessageId = Resource.String.VkInviteError;
Complete(callBackVKResponse);
base.OnError(p0);
}
}
Summary: if I press to invite a friend, I will see a "vkontakte" dialog window with suggest message (here you can accept or skip). If I press "invite" a friend which has disabled to invite him (or her) then it works fine. This is:
....
else
{
try
{
showCustomAlert(Resource.Drawable.ic_post, GetString(Resource.String.NotSentInvite) + "\n" + GetString(o.MessageId), Android.Graphics.Color.Argb(100, 200, 0, 0));
}
catch { }
}
....
But if a user has enabled to invite him (or her) then listener won't work and my app will freeze. In the phone you can press back button and the app will unfreez and after I can press again the button - invite will has worked fine. Listener OnComplete works only the second time. This is:
...
if (o.IsComplete)
{
try
{
showCustomAlert(Resource.Drawable.checkmark, GetString(Resource.String.SentInvite), Android.Graphics.Color.Argb(100, 0, 0, 200));
}
catch { }
}
...
Help please.
There are two users A and B.
First is logged in and B is Offline.
A send message to B.
Now B is going to online but unable get message what A
has sent to B.
If A and B both logged in different devices at a time and
both are chatting then message sending and receiving is done
perfectly.
Help me how to get chat history for one to one chat ?
This is for send message :
public void sendTextMessage(View v) {
String message = msg_edittext.getEditableText().toString();
if (!message.equalsIgnoreCase("")) {
final ChatMessage chatMessage = new ChatMessage(user1, user2,
message, "" + random.nextInt(1000), false);
chatMessage.setMsgID();
chatMessage.body = message;
chatMessage.Date = CommonMethods.getCurrentDate();
chatMessage.Time = CommonMethods.getCurrentTime();
msg_edittext.setText("");
chatAdapter.add(chatMessage);
chatAdapter.notifyDataSetChanged();
//MainActivity activity = ((MainActivity) context);
getmService().xmpp.sendMessage(chatMessage);
}
}
public void sendMessage(ChatMessage chatMessage)
{
String body = gson.toJson(chatMessage);
if (!chat_created)
{
Mychat = ChatManager.getInstanceFor(connection).createChat(
chatMessage.receiver + "#"
+ "sspl163",
mMessageListener);
chat_created = true;
}
final Message message = new Message();
message.setBody(body);
message.setStanzaId(chatMessage.msgid);
message.setType(Message.Type.chat);
try {
if (connection.isAuthenticated())
Mychat.sendMessage(message);
else
login();
}
catch (NotConnectedException e) {
Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
}
catch (Exception e) {}
}
This is for retrieving message :
private class MMessageListener implements ChatMessageListener
{
public MMessageListener(Context contxt) {}
#Override
public void processMessage(final org.jivesoftware.smack.chat.Chat chat, final Message message)
{
if (message.getType() == Message.Type.chat && message.getBody() != null)
{
final ChatMessage chatMessage = gson.fromJson(message.getBody(), ChatMessage.class);
processMessage(chatMessage);
}
}
private void processMessage(final ChatMessage chatMessage)
{
chatMessage.isMine = false;
SharedPreferences shared = context.getSharedPreferences("MyPREFERENCES", MODE_PRIVATE);
String user = (shared.getString("username", ""));
if(chatMessage.receiver.equalsIgnoreCase(user) && Chats.user2.equalsIgnoreCase(chatMessage.sender))
Chats.chatlist.add(chatMessage);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Chats.chatAdapter.notifyDataSetChanged();
}
});
}
}
First Check your openfire settings from web admin
From
Server -> Server Settings -> Offline Messages and check Your settings
For me Following work.
Sending Email in Android using JavaMail API without using the default/built-in app
Using this tutorial, I've loaded up the code into a sample android project and imported the libraries. Changed the parameters in the lines:
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
GMailSender sender = new GMailSender("sender#gmail.com", "sender_password");
sender.sendMail("This is Subject", "This is Body", "sender#gmail.com", "recipient#gmail.com");
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
Wanted to test it out and in this code, the try block of code gets executed successfully when I press the button, but I don't receive the mail, nor do I get any errors. Since there's no readme or any guidelines as to how to use this code, I have no choice but to ask what I'm doing wrong.
Just to clear the confusion, I've put the senders email instead of sender#gmail.com, same goes for password and recipient#gmail.com.
I've also added the INTERNET permission to the manifest.
If you want to use mailgun instead you can do it like this:
public void sendEmailInBackground(final String subject, final String body, final String... toAddress) {
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
String hostname = "smpt.mailgun.org";
int port = 25;
String login = "login";
String password = "password";
String from = "from#example.com";
AuthenticatingSMTPClient client = null;
try {
client = new AuthenticatingSMTPClient();
// optionally set a timeout to have a faster feedback on errors
client.setDefaultTimeout(10 * 1000);
// you connect to the SMTP server
client.connect(hostname, port);
// you say helo and you specify the host you are connecting from, could be anything
client.ehlo("localhost");
// if your host accepts STARTTLS, we're good everything will be encrypted, otherwise we're done here
if (client.execTLS()) {
client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, login, password);
checkReply(client);
client.setSender(from);
checkReply(client);
String address = "";
if (toAddress != null) {
for (String to : toAddress) {
if(to != null && to.length() > 0) {
client.addRecipient(to);
if (address.length() == 0) {
address += ",";
}
address += to;
}
}
}
if(address.length() == 0){
logger.warning("No address specified for mail message");
return null;
}
checkReply(client);
Writer writer = client.sendMessageData();
if (writer != null) {
SimpleSMTPHeader header = new SimpleSMTPHeader(from, address, subject);
writer.write(header.toString());
writer.write(body);
writer.close();
if (!client.completePendingCommand()) {// failure
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("Failure to send the email " + client.getReply() + client.getReplyString());
}
} else {
throw new IOException("STARTTLS was not accepted " + client.getReply() + client.getReplyString());
}
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException e) {
logger.severe("Error sending email",e);
} finally {
if (client != null) {
try {
client.logout();
client.disconnect();
} catch (Exception e) {
logger.warning("Error closing email client: " + e.getMessage());
}
}
}
return null;
}
};
task.execute();
}
private static void checkReply(SMTPClient sc) throws IOException {
if (SMTPReply.isNegativeTransient(sc.getReplyCode())) {
throw new IOException("Transient SMTP error " + sc.getReplyString());
} else if (SMTPReply.isNegativePermanent(sc.getReplyCode())) {
throw new IOException("Permanent SMTP error " + sc.getReplyString());
}
}
so here is my code for connecting and getting the values:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook;
using SmartLocalization;
public class mainMenuFacebook : MonoBehaviour {
public string FBname;
public string FBsurname;
Dictionary<string, string> profile = new Dictionary<string, string>();
// Use this for initialization
void OnMouseDown()
{
FB.Login("publish_actions,public_profile", LoginCallback); // logine tıklama
}
void Awake() {
FB.Init(SetInit, OnHideUnity); //facebook başlangıcı
}
private void SetInit()
{
if (FB.IsLoggedIn)
{
// Util.Log("Already logged in");
OnLoggedIn();
}
}
private void OnHideUnity(bool isGameShown)
{
if (!isGameShown)
{
// pause the game - we will need to hide
Time.timeScale = 0;
}
else
{
// start the game back up - we're getting focus again
Time.timeScale = 1;
}
}
void LoginCallback(FBResult result)
{
Util.Log("LoginCallback");
if (FB.IsLoggedIn)
{ gameObject.guiTexture.enabled = false;
OnLoggedIn();
}
}
void OnLoggedIn()
{
FB.API("/me?fields=first_name,last_name,email", Facebook.HttpMethod.GET, APICallback); // adını ve idyi çekiyoruz.
}
void APICallback(FBResult result)
{
if (result.Error != null)
{
// Let's just try again
// FB.API("/me?fields=id,first_name,last_name,email,friends.limit(100).fields(first_name,last_name,id)", Facebook.HttpMethod.GET, APICallback);
return;
}
Debug.Log(result.Text);
profile = Util.DeserializeJSONProfile(result.Text);
FBname = profile["first_name"];
FBsurname = profile["last_name"]; // **IT GIVES ERROR**
Debug.Log(FBsurname + " " + FBname);
//PlayerPrefs.SetString("surname",profile["last_name"]);
//PlayerPrefs.SetString("email",profile["email"]);
gameObject.guiTexture.enabled = false;
GameObject.Find("Wellcome").guiText.enabled = true;
GameObject.Find("Wellcome").guiText.text = LanguageManager.Instance.GetTextValue("menu.hosgeldin") + " <b><color=#ffa500ff>" + FBname + "</color></b>, <i>" + LanguageManager.Instance.GetTextValue("menu.cikis") +"</i>";
PlayerPrefs.SetString("name",FBname);
}
}
when i only try to get first_name everything is okay. But i need to get last_name and email too. I think i cant serialize because when i try to Debug.Log(profile.Count); it shows 1.
How can i fix it?
Given error is:
KeyNotFoundException: The given key was not present in the dictionary.
System.Collections.Generic.Dictionary`2[System.String,System.String].get_Item (System.String key) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:150)
mainMenuFacebook.APICallback (.FBResult result) (at Assets/Scripts/mainMenuFacebook.cs:84)
Facebook.AsyncRequestString+<Start>c__Iterator0.MoveNext ()
Try this:
public void OnMouseDown()
{
List<string> permissions = new List<string>() { "public_profile", "email" };
FB.LogInWithReadPermissions(permissions,AuthCallback);
Debug.Log("Facebook Login");
}
In AuthCallback: if user logs in successfully, get info from FB api.
private void AuthCallback(ILoginResult result)
{
if(FB.IsLoggedIn)
{
GetInfo();
}
else
{
Debug.Log("User cancelled login");
}
}
FB API returns json result, so you will need FacebookUser class to deserialize it.
class FacebookUser
{
public string id;
public string first_name;
public string last_name;
public string email;
}
public void GetInfo()
{
FB.API("/me?fields=id,first_name,last_name,email", HttpMethod.GET, result =>
{
if(result.Error != null)
{
Debug.Log("Result error");
}
var facebookUser = Newtonsoft.Json.JsonConvert.DeserializeObject<FacebookUser>(result.RawResult);
Debug.Log(" facebook id - " + facebookUser.id);
Debug.Log(" facebook first name - " + facebookUser.first_name);
Debug.Log(" facebook last name - " + facebookUser.last_name);
Debug.Log(" facebook email - " + facebookUser.email);
});
}
NOTE: You should have Email permission from facebook to access it.
Check it in Graph API Explorer