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

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

Related

Firebase Auth returns System.NullReference exception

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

WebSocket Implementation

I want to Create WebSocket Example in which i do not want to refresh the page for getting latest data.
I Create one Html page in which create one object of websocket.
E.g
ClientSide Implementation
var ws = new WebSocket(hostURL);
ws.onopen = function ()
{
// When Connection Open
};
ws.onmessage = function (evt)
{
// When Any Response come from WebSocket
}
ws.onclose = function (e)
{
// OnClose of WebSocket Conection
}
Server Side Implementation
public class WebSocketManager : WebSocketHandler
{
private static WebSocketCollection WebSocketObj4AddMessage = new WebSocketCollection();
public override void OnOpen()
{
// Do when Connection Is Open
}
public override void OnClose()
{
// Close Connection
}
public override void OnMessage(string message)
{
// When Any Message Sent to Client
}
}
Is I am doing right way to use WebSocket ?
Please help me to clear out in this section.
Here a sample.
First you have to install Asp.net SignalR package along with its dependenies.
You have call the SignalR when the app starts
namespace ABC
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR(); <--{Add this line}
}
}
}
You have start the SqlDependency when app start and stop when app stops in the Global.asax file.
string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionStringsName"].ConnectionString;
protected void Application_Start()
{
SqlDependency.Start(ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConnectionString);
}
You have to create custom Hubclass extending Hub Base class
public class MessagesHub : Hub
{
[HubMethodName("sendMessages")]
public void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}
Then in the client page, you have add these code in the javascript section
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.messagesHub;
//debugger;
// Create a function that the hub can call to broadcast messages.
notifications.client.updateMessages = function () {
getAllMessages()
};
// Start the connection.
$.connection.hub.start().done(function () {
getAllMessages();
}).fail(function (e) {
alert(e);
});
});
function getAllMessages() {
$.ajax({
url: '../../Notifications/GetNotificationMessages',
.
.
}
The server call this function when there there is any change in the database table using sqlDependency
The getAllMessages() is the controller for your code to handle, that should be shown in the view page and it will be call when the app starts and any change in db
public ActionResult GetNotificationMessages()
{
NotificationRepository notification = new NotificationRepository();
return PartialView("_NotificationMessage");
}
The in model class
public class NotificationRepository
{
readonly string connectionString = ConfigurationManager.ConnectionStrings["InexDbContext"].ConnectionString;
public IEnumerable<Notification> GetAllMessages(string userId)
{
var messages = new List<Notification>();
using(var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT [NotificationID], [Message], [NotificationDate], [Active], [Url], [userId] FROM [dbo].[Notifications] WHERE [Active] = 1 AND [userId] ='" + userId + "'", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
var reader = command.ExecuteReader();
while (reader.Read())
{
messages.Add(item: new Notification { NotificationID = (int)reader["NotificationID"], Message = (string)reader["Message"], Url = (string)reader["Url"] });
}
}
}
return messages;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub message = new MessagesHub();
message.SendMessages();
}
}
}
This well show latest data when the database table is updated. the message will shown at runtime.
Hope this helps
You are on the right path
You can refer this if I am not late ...This is working example
CLIENT SIDE
var ws;
var username = "JOHN";
function startchat() {
var log= $('log');
var url = 'ws://<server path>/WebSocketsServer.ashx?username=' + username;
ws = new WebSocket(url);
ws.onerror = function (e) {
log.appendChild(createSpan('Problem with connection: ' + e.message));
};
ws.onopen = function () {
ws.send("I am Active-" +username);
};
ws.onmessage = function (e) {
if (e.data.toString() == "Active?") {
ws.send("I am Active-" + username);
}
else {
}
};
ws.onclose = function () {
log.innerHTML = 'Closed connection!';
};
}
</script>
<div id="log">
</div>
Server Side in Websocketserver.ashx page
public class WebSocketsServer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new MicrosoftWebSockets());
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Add below class in the server side
public class MicrosoftWebSockets : WebSocketHandler
{
private static WebSocketCollection clients = new WebSocketCollection();
private string msg;
public override void OnOpen()
{
this.msg = this.WebSocketContext.QueryString["username"];
clients.Add(this);
clients.Broadcast(msg);
}
public override void OnMessage(string message)
{
clients.Broadcast(string.Format(message));
}
public override void OnClose()
{
clients.Remove(this);
clients.Broadcast(string.Format(msg));
}
add this dll to the above class
using Microsoft.Web.WebSockets;
I donot remeber where I got the reference ...but above code is derived from my current working application

Check Session timeout on invoking constructor of a controller in MVC 4

I'am handling session expiry in my MVC 4 application using the following method:
step 1: created the following class:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
string actonName = filterContext.ActionDescriptor.ActionName.ToLower();
if (!(controllerName.Contains("account")||(controllerName.Contains("home") && actonName.Contains("index"))))
{
// If the browser session or authentication session has expired...
if (SessionManager.Instance["PlatformId"] == null || !filterContext.HttpContext.Request.IsAuthenticated)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult { Data = "_Logon_" };
}
else
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "TimeoutRedirect" }
});
}
}
}
base.OnActionExecuting(filterContext);
}
}
step 2: Added it to RegisterGlobalFilters as follows:
filters.Add(new SessionExpireFilterAttribute());
I tested this while session is alive and its working fine- while executing each action it is checking whether session is active. But the problem is I'am initializing some objects in constructor using session values as follows:
public class DashboardController : BaseController
{
private DashboardService dashboardService;
public DashboardController()
{
dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"]);
}
}
When session times out obviously null reference exception is thrown at
dashboardService = new DashboardService(this.DbContext, (int)SessionManager.Instance["PlatformId"])
before session expiry check is made. I cannot move all these initializations to every actions because it is hectic-I already have a lot of action methods.
So is there any way to check session time out when Constructor method is invoked? Please help.
Well,
What I am doing is Checking for the Session in application's Application_AcquireRequestState method (Global.asax)
something like this
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Handler is IRequiresSessionState)
{
var usrobj = HttpContext.Current.Session["User"];
if(usrobj == null)
{
Response.Redirect("~/Login/Index");
}
}
}
I don't know if you want something along the same lines.

How to use Session Variable in MVC

I have declared Session variable in "Global.asax" file as,
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
int temp=4;
HttpContext.Current.Session.Add("_SessionCompany",temp);
}
And want to use this Session Variable into My Controller's action as,
public ActionResult Index()
{
var test = this.Session["_SessionCompany"];
return View();
}
But I am Getting Exception While accessing the Session Variable.
Please help me on this that How can I access the Session Variable into my controller's Action.
I am getting an Exception like
"Object Reference not set to an Insatance of an object"
in Application_Start in Global.asax on line
HttpContext.Current.Session.Add("_SessionCompany",temp);
The thread that starts the Application is not the request thread used when the user makes a request to the web page.
That means when you set in the Application_Start, you're not setting it for any user.
You want to set the session on Session_Start event.
Edit:
Add a new event to your global.asax.cs file called Session_Start and remove the session related stuff from Application_Start
protected void Session_Start(Object sender, EventArgs e)
{
int temp = 4;
HttpContext.Current.Session.Add("_SessionCompany",temp);
}
This should fix your issue.
You should not set session variables in Application_Start(), as that method is only called once, when the application kicks off in IIS. It is not session based.
In addition, I assume your controller has a Session property? Have you set it correctly?
Use HttpContext.Current.Session["_SessionCompany"] rather than this.Session["_SessionCompany"] - that should work.
In controller, you can access like this..
YourControllerID.ControllerContext.HttpContext.Session["_SessionCompany"]
Use this helper class:
namespace Projectname.UI.HtmlHelpers
{
//[DebuggerNonUserCodeAttribute()]
public static class SessionHelper
{
public static T Get<T>(string index)
{
//this try-catch is done to avoid the issue where the report session is timing out and breaking the entire session on a refresh of the report
if (HttpContext.Current.Session == null)
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session has expired or you are currently logged out.", index));
}
try
{
if (HttpContext.Current.Session.Keys.Count > 0 && !HttpContext.Current.Session.Keys.Equals(index))
{
return (T)HttpContext.Current.Session[index];
}
else
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session does not contain {0} or has expired or you are currently logged out.", index));
}
}
catch (Exception e)
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
return default(T);
}
}
public static void Set<T>(string index, T value)
{
HttpContext.Current.Session[index] = (T)value;
}
}
}
and in your controller you set everything e.g. a login controller:
Session Helper.Set<string>("Username", Login User.User Name);
Session Helper.Set<int?>("Tenant Id", Login User.Tenant Id);
SessionHelper.Set<User Type>("User Type");
SessionHelper.Set<string>("", Login User To String());
SessionHelper.Set<int>("Login User Id", Login User.Login UserId);
SessionHelper.Set<string>("Login User", Login User.To String());
SessionHelper.Set<string>("Tenant", Tenant);
SessionHelper.Set<string>("First name", Login User.First Name);
SessionHelper.Set<string>("Surname", Login User.Surname);
SessionHelper.Set<string>("Vendor ", Vendor );
SessionHelper.Set<string>("Wholesaler ", Wholesaler );
SessionHelper.Set<int?>("Vendor Id", Login User );
SessionHelper.Set<int?>("Wholesaler Id", Login User Wholesaler Id);
and you just call it anywhere you want:
var CreatedBy = SessionHelper.Get<int>("LoginUserId"),
it is a simple get to the the entity or set to assign it.
public ActionResult DeclareSession()
{
int id=3;
Session["User"]=id;
int iUserID =Convert.ToInt32(HttpContext.Current.Session["User"].toString());
return true;
}

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" />

Categories