Firebase Auth returns System.NullReference exception - c#

I am new to this. When I try to create a user with email and password it tells me that my FirebaseAuth is null and doesn't let me create a user.
I am initializing Firebase through this.
void InitializeFirebase()
{
var app = FirebaseApp.InitializeApp(this);
if (app == null)
{
var options = new FirebaseOptions.Builder()
.SetApplicationId("")
.SetApiKey("")
.SetDatabaseUrl("")
.SetStorageBucket("")
.Build();
app = FirebaseApp.InitializeApp(this, options);
database = FirebaseDatabase.GetInstance(app);
mAuth = FirebaseAuth.Instance;
}
else
{
database = FirebaseDatabase.GetInstance(app);
mAuth = FirebaseAuth.Instance;
}
}
I am getting an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Which pops up here
mAuth.CreateUserWithEmailAndPassword(email, password)
.AddOnSuccessListener(this, TaskCompletionListener)
.AddOnFailureListener(this, TaskCompletionListener);
And registering user here:
void RegisterUser(string email, string password)
{
TaskCompletionListener.Success += TaskCompletionListener_Success;
TaskCompletionListener.Failure += TaskCompletionListener_Failure;
mAuth.CreateUserWithEmailAndPassword(email, password)
.AddOnSuccessListener(this, TaskCompletionListener)
.AddOnFailureListener(this, TaskCompletionListener);
}
TaskCompletioListener
public class TaskCompletionListener : Java.Lang.Object, IOnSuccessListener, IOnFailureListener
{
public EventHandler Success;
public EventHandler Failure;
public void OnFailure(Java.Lang.Exception e)
{
Failure.Invoke(this, new EventArgs());
}
public void OnSuccess(Java.Lang.Object result)
{
Success.Invoke(this, new EventArgs());
}
}

I fixed it by installing NuGet package "Xamarin.android.manifestmerger" from NuGet.org:
https://www.nuget.org/packages/Xamarin.Android.ManifestMerger/1.0.0-preview03
This is how to install it:
https://learn.microsoft.com/en-us/nuget/quickstart/install-and-use-a-package-in-visual-studio
And this is where I found the fix:
https://github.com/xamarin/GooglePlayServicesComponents/issues/216

Related

Firebase Function throwing internal error when trying to call it from Unity

I work on a Unity C# app with Firebase Auth and Firebase Functions SDK installed.
I have three callable functions I developed and tested thanks to the Firebase emulators and they seem to work correctly.
I deployed my functions, launched the game in Unity Editor and I get an error whenever I call a function. The error is always INTERNAL.
I checked the logs on Google Cloud dashboard and it seems my function doesn't even run.
I put a breakpoint and decide to inspect the exception to gather some information.
However, there isn't any useful information other than "One or more errors occurred" and "INTERNAL".
After numerous searches on Google/SO I've found two possible culprits :
Outdated SDK -> I redownload latest SDK and re-import Firebase Auth and Firebase Functions into my Unity project --> same error.
Need to specify region when getting the Functions instance if different than us-central1. According to the Google dashboard my functions are located in the us-central1 region but just in case I specify it anyway --> same error.
Then I notice that my actual Firebase project is in europe-west3 so I specify this in my code when getting the instance of Firebase Functions or App --> still the same error.
Now I'm starting to doubt everything so I comment out UseFunctionsEmulator() and test again with the emulators -> it works fine.
What could be the problem?
Here is my FirebaseManager.cs that run before anything else:
public class FirebaseManager : MonoBehaviour
{
private static bool gameQuitting = false;
private static readonly object Lock = new object();
private static FirebaseManager _instance;
public static FirebaseManager Instance
{
get
{
// [check if instance exists etc..]
}
}
private FirebaseApp _app;
private FirebaseAuth _auth;
public FirebaseAuth Auth
{
get
{
if (_auth == null)
{
_auth = FirebaseAuth.GetAuth(_app);
}
return _auth;
}
}
private FirebaseUser _user;
public FirebaseUser User
{
get
{
return _user;
}
set
{
_user = value;
}
}
private FirebaseFunctions _func;
public FirebaseFunctions Func
{
get
{
if (_func == null)
{
_func = FirebaseFunctions.DefaultInstance;
}
return _func;
}
}
// Events to subscribe to for this service
public delegate void FirebaseInitialized();
public static event FirebaseInitialized OnFirebaseInitialized;
public static bool IsInitialized = false;
private void Awake()
{
if (_instance == null)
{
DontDestroyOnLoad(this.gameObject);
_instance = this;
}
else { Destroy(this.gameObject); }
}
private void Start()
{
InitializeFirebase();
}
private void InitializeFirebase()
{
Debug.Log($"FirebaseManager.cs > INITIALIZING FIREBASE");
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
_app = FirebaseApp.DefaultInstance;
// _app = FirebaseApp.GetInstance("europe-west3");
// Create and hold a reference to FirebaseAuth
_auth = FirebaseAuth.DefaultInstance;
// Create and hold a reference to already logged in user (if any)
_user = _auth.CurrentUser;
// Create and hold a reference to Functions
_func = FirebaseFunctions.DefaultInstance;
// _func = FirebaseFunctions.GetInstance(FirebaseApp.DefaultInstance, "europe-west3");
// _func = FirebaseFunctions.GetInstance("europe-west3");
// #if UNITY_EDITOR
// _func.UseFunctionsEmulator("http://localhost:5001"); // LOCAL FUNCS
// #endif
// Subscribing to AuthStateChanged
FirebaseManager.Instance.Auth.StateChanged += AuthService.AuthStateChanged;
Debug.Log($"FirebaseManager.cs > INITIALIZED");
IsInitialized = true;
if (OnFirebaseInitialized != null) OnFirebaseInitialized.Invoke();
}
else
{
UnityEngine.Debug.LogError(System.String.Format(
"FirebaseManager.cs > Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
}
private void OnDestroy()
{
if (_auth != null) _auth = null;
}
private void OnApplicationQuit()
{
FirebaseManager.Instance.Auth.StateChanged -= AuthService.AuthStateChanged;
gameQuitting = true;
}
}
I call my function from Unity like this :
HttpsCallableReference function = FirebaseManager.Instance.Func.GetHttpsCallable("GetAllCharacters");
// Call the function and extract the operation from the result.
function.CallAsync().ContinueWithOnMainThread((task) =>
{
if (task.IsFaulted)
{
// this foreach is a debug attempt
foreach (var e in task.Exception.Flatten().InnerExceptions)
{
Debug.LogWarning($"Received Exception: {e.Message}");
}
foreach (var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
var e = (FunctionsException)inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.Message;
Debug.LogError($"Code: {code} // Message: {message}");
// [Handle error]
}
}
}
else
{
// [Handle data returned by the function]
}
});
Finally, my Firebase Functions look like this: (index.ts)
import * as Characters from "./Characters/Characters";
// CHARACTERS
export const CreateNewCharacter = Characters.CreateNewCharacter;
export const GetAllCharacters = Characters.GetAllCharacters;
export const DeleteCharacterByID = Characters.DeleteCharacterByID;
Characters.ts:
import * as functions from "firebase-functions";
import { initializeApp } from "firebase-admin/app";
// [custom classes imports]
// DATABASE INITIALIZATION
initializeApp();
const db = getFirestore();
// CREATE NEW CHARACTER
export const CreateNewCharacter =
functions.https.onCall(async (data, context) =>
{
...
});
// GET ALL CHARACTERS
export const GetAllCharacters =
functions.https.onCall(async (data, context) =>
{
...
});
// DELETE CHARACTER BY ID
export const DeleteCharacterByID =
functions.https.onCall(async (data, context) =>
{
...
});
In step-by-step debugging, here is what I find:
The StackTrace value is :
" at Firebase.Functions.HttpsCallableReference.b__9_0 (System.Threading.Tasks.Task'1[TResult] task) [0x00063] in <9b40ff23f61a4fcf97a5710997860279>:0 \n at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2[TAntecedentResult,TResult].InnerInvoke () [0x00024] in <4ba27aa039714eafa1e8892e51af2932>:0 \n at System.Threading.Tasks.Task.Execute () [0x00000] in <4ba27aa039714eafa1e8892e51af2932>:0 "

Why does HttpClient GetAsync() not return in Xamarin?

I'm new to Xamarin and I'm trying to create a cross-platform app where users can login using a JSON API call. A token is then returned on a successful login attempt which I can use in other API's to display user data.
It works when I use the same code in a console application, but when I run it in Xamarin the code after await client.GetAsync(url) is never reached and after a while the application breaks and I get an unknown error. Am I experiencing a deadlock?
private async void loginButton_Click(object sender, EventArgs e)
{
var login = await loginAPI(LoginPage.nameEntry.Text, LoginPage.passEntry.Text);
if (login.state == "success")
{
...
}
else
{
...
}
}
public static async Task<LoginData> loginAPI(String username, String password)
{
try
{
using (var client = new HttpClient())
{
var loginUrl = new Uri("https://my-api/login?username=" + username + "&password=" + password);
var result = await client.GetAsync(loginUrl);
return JsonConvert.DeserializeObject<LoginData>(await result.Content.ReadAsStringAsync());
}
}
catch (Exception e)
{
return null;
}
}
public class LoginData
{
[JsonProperty("state")]
public String state { get; set; }
[JsonProperty("token")]
public String token { get; set; }
}

How to use signalr in Android

I am trying to integrate signalR in android app but no luck. I've been looking at various links but none of them provide proper information about implementation.
I've the following questions.
SignalR integration has to be done inside Service/Intent Service?
If we want to receive response via same calling method then how to get?
I've added three libraries i.e signalr android,signalr client and gson but unable to understand how code works, no proper documentation is available to understand the code.
Some of the questions asked but not much information
SignalR in Android Studio
Unable to implement p2p chat using SignalR in Android
If anyone experienced in signal for native apps, it would be very helpful for me.
Update
public class SignalRService extends Service {
private static final String TAG = "Service";
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder();
private SharedPreferences sp;
#Override
public void onCreate() {
super.onCreate();
Utility.showLog(TAG, "Service Created");
sp = getSharedPreferences(Utility.SHARED_PREFS, MODE_PRIVATE);
mHandler = new Handler(Looper.myLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public IBinder onBind(Intent intent) {
startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void sendMessage() {
String SERVER_METHOD_SEND = "iAmAvailable";
final String string = new String();
mHubProxy.invoke(new String(), SERVER_METHOD_SEND, sp.getString("user_id", null), sp.getString("pass", null), "TransMedic").done(new Action() {
#Override
public void run(Object o) throws Exception {
Utility.showLog(TAG, o.toString());
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable throwable) {
}
});
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String serverUrl = "http://transit.alwaysaware.org/signalr";
mHubConnection = new HubConnection(serverUrl);
String SERVER_HUB_CHAT = "ChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
sendMessage();
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
}
UPDATE 2018:
If you are using SignalR.net Core use this library otherwise you will get error on connection.
SERVER SIDE:
The following is my sample server-side code, you can pay attention to public void Send(string message) and public void SendChatMessage(string to, string message).
Server-side app: public void SendChatMessage(string to, string message)
Android client app: mHubProxy.invoke("SendChatMessage", receiverName, message);
Server-side app: public void Send(string message)
Android client app: mHubProxy.invoke("Send", message);
namespace SignalRDemo
{
public class ChatHub : Hub
{
private static ConcurrentDictionary<string, string> FromUsers = new ConcurrentDictionary<string, string>(); // <connectionId, userName>
private static ConcurrentDictionary<string, string> ToUsers = new ConcurrentDictionary<string, string>(); // <userName, connectionId>
private string userName = "";
public override Task OnConnected()
{
DoConnect();
Clients.AllExcept(Context.ConnectionId).broadcastMessage(new ChatMessage() { UserName = userName, Message = "I'm Online" });
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
if (stopCalled) // Client explicitly closed the connection
{
string id = Context.ConnectionId;
FromUsers.TryRemove(id, out userName);
ToUsers.TryRemove(userName, out id);
Clients.AllExcept(Context.ConnectionId).broadcastMessage(new ChatMessage() { UserName = userName, Message = "I'm Offline" });
}
else // Client timed out
{
// Do nothing here...
// FromUsers.TryGetValue(Context.ConnectionId, out userName);
// Clients.AllExcept(Context.ConnectionId).broadcastMessage(new ChatMessage() { UserName = userName, Message = "I'm Offline By TimeOut"});
}
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
DoConnect();
Clients.AllExcept(Context.ConnectionId).broadcastMessage(new ChatMessage() { UserName = userName, Message = "I'm Online Again" });
return base.OnReconnected();
}
private void DoConnect()
{
userName = Context.Request.Headers["User-Name"];
if (userName == null || userName.Length == 0)
{
userName = Context.QueryString["User-Name"]; // for javascript clients
}
FromUsers.TryAdd(Context.ConnectionId, userName);
String oldId; // for case: disconnected from Client
ToUsers.TryRemove(userName, out oldId);
ToUsers.TryAdd(userName, Context.ConnectionId);
}
public void Send(string message)
{
// Call the broadcastMessage method to update clients.
string fromUser;
FromUsers.TryGetValue(Context.ConnectionId, out fromUser);
Clients.AllExcept(Context.ConnectionId).broadcastMessage(new ChatMessage() { UserName = fromUser, Message = message });
}
public void SendChatMessage(string to, string message)
{
FromUsers.TryGetValue(Context.ConnectionId, out userName);
string receiver_ConnectionId;
ToUsers.TryGetValue(to, out receiver_ConnectionId);
if (receiver_ConnectionId != null && receiver_ConnectionId.Length > 0)
{
Clients.Client(receiver_ConnectionId).broadcastMessage(new ChatMessage() { UserName = userName, Message = message });
}
}
}
public class ChatMessage
{
public string UserName { get; set; }
public string Message { get; set; }
}
}
CLIENT SIDE:
If you have not read my answer at the following question:
SignalR integration in android studio
Then, here is my working basic code:
public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients
public SignalRService() {
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void sendMessage(String message) {
String SERVER_METHOD_SEND = "Send";
mHubProxy.invoke(SERVER_METHOD_SEND, message);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader("User-Name", "BNK");
}
};
String serverUrl = "http://192.168.1.100";
mHubConnection = new HubConnection(serverUrl);
mHubConnection.setCredentials(credentials);
String SERVER_HUB_CHAT = "ChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
try {
signalRFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
String HELLO_MSG = "Hello from Android!";
sendMessage(HELLO_MSG);
String CLIENT_METHOD_BROADAST_MESSAGE = "broadcastMessage";
mHubProxy.on(CLIENT_METHOD_BROADAST_MESSAGE,
new SubscriptionHandler1<CustomMessage>() {
#Override
public void run(final CustomMessage msg) {
final String finalMsg = msg.UserName + " says " + msg.Message;
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), finalMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
, CustomMessage.class);
}
}
Activity:
public class MainActivity extends AppCompatActivity {
private final Context mContext = this;
private SignalRService mService;
private boolean mBound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClass(mContext, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void sendMessage(View view) {
if (mBound) {
// Call a method from the SignalRService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
EditText editText = (EditText) findViewById(R.id.edit_message);
if (editText != null && editText.getText().length() > 0) {
String message = editText.getText().toString();
mService.sendMessage(message);
}
}
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to SignalRService, cast the IBinder and get SignalRService instance
SignalRService.LocalBinder binder = (SignalRService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
CustomMessage Class:
public class CustomMessage {
public String UserName;
public String Message;
}
You can also see my sample client project at this GitHub link
UPDATE FOR RESPONSE FROM INVOKE:
I have just added new sample methods:
Server side:
public string iAmAvailable(string username, string password, string message)
{
return "BNK Response for testing Android INVOKE";
}
Client side:
mHubProxy.invoke(String.class, "iAmAvailable", "username", "password", "TransMedic").done(new Action<String>() {
#Override
public void run(String s) throws Exception {
Log.w("SimpleSignalR", s);
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable throwable) {
Log.e("SimpleSignalR", throwable.toString());
}
});
And here is the screenshot:
This work for me : Full source Android (Client) & Server GitHub
Server Slide If one argument must use this interface SubscriptionHandler1 if two argument must use this interfaceSubscriptionHandler2 ,...
Sample for two argument like :
Server slide :
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Two argument must use this interfaceSubscriptionHandler2 .
Clients.All.broadcastMessage(name, message);
}
}
}
Client slide :
mHubProxy.on(CLIENT_METHOD_BROADAST_MESSAGE,
new SubscriptionHandler2<String, String>() {
#Override
public void run(final String name,final String msg) {
final String finalMsg = msg.toString();
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), finalMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
, String.class,String.class);
For catch all message can use this :
mHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(final JsonElement json) {
Log.e("onMessageReceived ", json.toString());
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});
The SignalR team recently released a Java client for ASP.NET Core SignalR. Here is a link to getting started docs https://learn.microsoft.com/en-us/aspnet/core/signalr/java-client?view=aspnetcore-2.2
do this tutorial step by step :
https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?tabs=visual-studio-mac&view=aspnetcore-5.0
1.According above tutorial publish your chat server to favorite host
2.add this dependency to your android sample:
implementation 'com.microsoft.signalr:signalr:3.0.0'
3.add these permission to manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4.below code is MainActivity.class:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HubConnection hubConnection =
HubConnectionBuilder.create("https://your_chat_server_url/chatHub").build();
TextView textView = (TextView)findViewById(R.id.tvMain);
ListView listView = (ListView)findViewById(R.id.lvMessages);
Button sendButton = (Button)findViewById(R.id.bSend);
EditText editText = (EditText)findViewById(R.id.etMessageText);
List<String> messageList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, messageList);
listView.setAdapter(arrayAdapter);
hubConnection.on("ReceiveMessage", (user, message)-> {
runOnUiThread(new Runnable() {
#Override
public void run() {
arrayAdapter.add( user + " : " + message);
arrayAdapter.notifyDataSetChanged();
}
});
}, String.class,String.class);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = editText.getText().toString();
String user = "SAEID";
editText.setText("");
try {
hubConnection.send("SendMessage", user,message);
} catch (Exception e) {
e.printStackTrace();
}
}
});
new HubConnectionTask().execute(hubConnection);
}
static class HubConnectionTask extends AsyncTask<HubConnection, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(HubConnection... hubConnections) {
HubConnection hubConnection = hubConnections[0];
hubConnection.start().blockingAwait();
return null;
}
}
}
5.below code is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvMain" />
<ListView
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="fill_parent"
android:id="#+id/lvMessages"
android:transcriptMode="alwaysScroll">
</ListView>
<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="#+id/etMessageText"
android:hint="Enter Message" />
<Button
android:text="Send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bSend" />
</LinearLayout>
For those who are implementing signalR client in android and the given answer here doesn't help in receiving the messages can check out this answer by rejnev.
The answer implements a different method connection.received() which is able to receive message callbacks from the server in my case.

OAuthException: (#200) The user hasn't authorized the application to perform this action

Using the Facebook C# SDK, I'm getting the following error when I try to post a status update:
OAuthException: (#200) The user hasn't authorized the application to perform this action
I am getting this error only with some users. For some other,status is updating fine. App is successfully getting access for all users.
This is the full code :
public partial class Authorize : Form
{
public Authorize()
{
InitializeComponent();
}
public string ApplicationId
{
get
{
return ConfigurationManager.AppSettings["ApplicationId"];
}
}
public string ExtendedPermissions
{
get
{
return ConfigurationManager.AppSettings["ExtendedPermissions"];
}
}
public string AppSecret
{
get
{
return ConfigurationManager.AppSettings["ApplicationSecret"];
}
}
public string AccessToken { get; set; }
private void LoadAuthorize(object sender, EventArgs e)
{
var destinationURL = String.Format(
#"https://www.facebook.com/dialog/oauth?client_id={0}&scope={1}&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token",
this.ApplicationId,
this.ExtendedPermissions);
webBrowser.Navigated += WebBrowserNavigated;
webBrowser.Navigate(destinationURL);
}
private void WebBrowserNavigated(object sender, WebBrowserNavigatedEventArgs e)
{
// get token
var url = e.Url.Fragment;
if (url.Contains("access_token") && url.Contains("#"))
{
this.Hide();
url = (new Regex("#")).Replace(url, "?", 1);
this.AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get("access_token");
//MessageBox.Show(facebookCore.AccessToken);
try
{
//var facebooking = new FacebookingTest(facebookCore.AccessToken);
//facebooking.UpdateStatus();
var fb = new FacebookClient(this.AccessToken);
dynamic result = fb.Post("me/feed", new { message = "Hi..Test33" });
var newPostId = result.id;
}
catch (Exception exception)
{
Console.Write(exception);
}
}
}
}
Try opening the file App.Config and modify the last line of the
<appsettings>
section as follows:
<add key="ExtendedPermissions" value="offline_access,publish_stream,publish_actions" />

Object reference not set to an instance of an object. in HttpModule

I want save users's IPs and activity in a table named logPublic,I want when a unAthenticated user try to access a speacial folder e.g Admin folder i can add a record in logpublic table that it have some fields for e,g : ID,IP,Activity,datetime .after that unathenticated user will be lock utomatically
I am use below code in Load_Page Event of masterpage in Admin folder:
$public partial class Admin : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
Session["IsBlocked"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
HttpContext.Current.Session["Activity"] = HttpContext.Current.Request.Url;
HttpContext.Current.Session["DateTime"] = System.DateTime.Now;
}
else
{
if(! HttpContext.Current.User.IsInRole("Admin"))
{
Session["BlockUser"] = true;
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
HttpContext.Current.Session["UserIP"] = ip;
}
}
}
}
$namespace StoreProject.Data
{
public class CustomSecurityModule :IHttpModule
{
storedbEntities StoreEnt = new storedbEntities();
public void Dispose()
{
throw new NotImplementedException();
}
public void Init(HttpApplication context)
{
//throw new NotImplementedException();
context.BeginRequest += new EventHandler(this.app_DoSecuriy);
}
private void app_DoSecuriy(object sender, EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
storedbEntities StoreEnt = new storedbEntities();
if (context.Session["BlockUser"]!= null && Convert.ToBoolean(context.Session["BlockUser"])== true)
{
logPrivate Log = new logPrivate()
{
Username = context.User.Identity.Name,
IP = context.Session["UserIP"].ToString(),
Enter = System.DateTime.Now,
};
StoreEnt.logPrivates.AddObject(Log);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
//ublock != null && bool.TryParse(ublock.ToString(),out isblocked) && isblocked
else if ( context.Session["BlockPublick"] != null
&& System.Convert.ToBoolean(context.Session["BlockPublick"]) == true)
{
LogPublic newLog = new LogPublic()
{
IP = context.Session["UserIP"].ToString(),
Activity = context.Session["Activity"].ToString(),
Enter = Convert.ToDateTime(context.Session["DateTime"])
};
StoreEnt.LogPublics.AddObject(newLog);
StoreEnt.SaveChanges();
context.Response.Redirect("~/UnAuthorizedAccess.aspx");
}
}
}
}
but when i run my application website ,i get an error from httpmodule :Object reference not set to an instance of an object. error in below line
if (context.Session["BlockUser"]!= null
&& Convert.ToBoolean(
context.Session["BlockUser"])== true)
i dont have any record in LogPublic table or logPrivate table when i want visit a page in Admin Folder
please guide me
thanks
Module's BeginRequest is too early to access the Session object as it hasn't been yet created by the ASP.NET Pipeline. You'd have to move your logic to one of later events in the processing pipeline (after PostAcquireRequestState)
http://msdn.microsoft.com/en-us/library/ms178473.aspx

Categories