In my ASP.NET Web API project, i could access Session object in local (both debug and release model).
But when i deploy it to the server, it doesn't work.
Global.asax
public override void Init()
{
this.PostAuthenticateRequest +=MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
UserApiController.cs
[HttpGet]
public string GetVerificationCode(string mobileNumber)
{
if (!string.IsNullOrWhiteSpace(mobileNumber) &&
Regex.Match(mobileNumber, #"^1\d{10}$", RegexOptions.IgnoreCase).Success)
{
string VerificationCode = "1234";
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["VerificationCode"] = VerificationCode;
}
return VerificationCode;
}
throw new ArgumentException("Phone number format is incorrect");
}
[HttpGet]
public string GetSessionString()
{
if (HttpContext.Current.Session != null)
{
return HttpContext.Current.Session["VerificationCode"].ToString();
}
return string.Empty;
}
Why it doesn't work?
Related
I'm using a webview in my Xamarin Forms project with Hybrid Renderer and webview, because I have to inject javascript code inside the page.
In my main project I have a CustomWebview.cs:
namespace ClotureSiadForms.Renderer
{
public class CustomWebView : WebView
{
public string js = "";
public CustomWebView()
{
Navigating+= WebViewNavigating;
Navigated+=WebViewNavigated;
}
private void WebViewNavigated(object sender, WebNavigatedEventArgs args)
{
EvaluateJavaScriptAsync(js);
}
public void WebViewNavigating(object sender, WebNavigatingEventArgs args)
{
if (args.Url.StartsWith("tel:"))
{
var tel = args.Url.Split(':')[1];
args.Cancel = true;
Xamarin.Essentials.PhoneDialer.Open(tel);
}
else if (!args.Url.StartsWith("http") || args.Url.EndsWith(".apk") || args.Url.EndsWith(".pdf") || args.Url.EndsWith(".zip"))
{
args.Cancel = true;
Xamarin.Essentials.Launcher.OpenAsync(args.Url);
}
}
}
}
In my Android project I have a HybridWebViewRenderer.cs:
[assembly: ExportRenderer(typeof(CustomWebView), typeof(HybridWebViewRenderer))]
namespace ClotureSiadForms.Droid.Renderer
{
internal class HybridWebViewRenderer : WebViewRenderer
{
public HybridWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
}
}
}
}
As is, it worked and was able to download files
But as I needed basic authentication, I added a custom webviewclient inside HybridWebViewRenderer.cs:
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
CustomWebView webview = e.NewElement as CustomWebView;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
var login = Preferences.Get("login", "");
var password = Preferences.Get("password", "");
Control.SetWebViewClient(new AuthWebViewClient(login, password));
}
}
public class AuthWebViewClient : WebViewClient
{
private string Username;
private string Password;
public AuthWebViewClient(string username, string password)
{
Username = username;
Password = password;
}
public override void OnReceivedHttpAuthRequest(Android.Webkit.WebView view, HttpAuthHandler handler, string host, string realm)
{
handler.Proceed( Username,Password);
}
}
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
Then my question is, can't I use basic auth without a custom client or is there a way to keep using my customwebview with the client ?
And authentication works, but WebViewNavigating is now called once, then the custom client is set and then WebViewNavigating is never more called.
I tested the code you provided and added Breakpoint to WebViewNavigating method. Even if you do not add webviewclient, it will only call WebViewNavigating once.
You can put the code in WebViewNavigating to ShouldInterceptRequest:
public class AuthWebViewClient : WebViewClient
{
...
public override WebResourceResponse ShouldInterceptRequest(Android.Webkit.WebView view, IWebResourceRequest request)
{
var url = request.Url;
...
}
}
Whenever the WebView begins loading a new page, it will call ShouldInterceptRequest.
I have an ASP.net mvc application that uses Fluent Nhiberate, SQL Server, and autofac. When my application is published, IIS creates a lot of connections to SQL Server that are not being closed.
My SessionManager class:
public class SessionPerRequestModule : IHttpModule
{
private static readonly string NH_SESSION_ISOK_KEY = "NH_SESSION_ISOK";
private static readonly string NH_SESSION_PREFFIX_KEY = "NH_SESSION";
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.EndRequest += CtxEndRequest;
context.Error += CtxOnError;
}
private void CtxOnError(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Items[NH_SESSION_ISOK_KEY] = false;
}
private void CtxEndRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
foreach (string dbKey in DatabaseKeys.AllKeys)
{
ISession session = GetCurrentSession(dbKey, false);
CloseSession(session);
SetSession(dbKey, null);
}
}
public static bool IsOnError
{
get { return Convert.ToBoolean(HttpContext.Current.Items[NH_SESSION_ISOK_KEY]); }
set { HttpContext.Current.Items[NH_SESSION_ISOK_KEY] = value; }
}
private static ISession OpenSession(string dbKey)
{
try
{
var interceptor = new SetSystemPropertiesInterceptor(
() => DependencyResolver.Current.GetService<IAuthenticationService>()
);
ISession session;
session = NHibernateSessionHelper.GetFactory(dbKey).OpenSession(interceptor);
if (session == null)
throw new InvalidOperationException(string.Format("Call to factory.OpenSession('{0}') returned null.", dbKey));
session.FlushMode = FlushMode.Never;
session.BeginTransaction();
interceptor.SetSession(session);
return session;
}
catch (Exception ex)
{
throw new Exception(string.Format("Error on database with key '{0}'", dbKey), ex);
}
}
private static void CloseSession(ISession session)
{
if (session != null)
{
try
{
if (!IsOnError)
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
else
session.Flush();
}
else
session.Transaction.Rollback();
}
finally
{
session.Dispose();
}
}
}
public static ISession GetCurrentSession(string dbKey)
{
return GetCurrentSession(dbKey, true);
}
public static ISession GetCurrentSession(string dbKey, bool createIfNotFound)
{
string fullKey = FormatFullContextKey(dbKey);
ISession session = HttpContext.Current.Items[fullKey] as ISession;
if (createIfNotFound && session == null)
{
session = OpenSession(dbKey);
SetSession(dbKey, session);
}
return session;
}
private static void SetSession(string dbKey, ISession session)
{
string fullKey = FormatFullContextKey(dbKey);
HttpContext.Current.Items[fullKey] = session;
}
private static string FormatFullContextKey(string dbKey)
{
return string.Concat(NH_SESSION_PREFFIX_KEY, "_", dbKey);
}
}
Part of my NHibernate session helper:
factory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.FormatSql().ShowSql().AdoNetBatchSize(50).ConnectionString(c => c.FromConnectionStringWithKey(databaseKey)))
.Mappings(x =>
x.FluentMappings.AddFromAssemblyOf<ColaboradorMapping>()
.Conventions.AddFromAssemblyOf<CustomTypeConvention>()
).BuildSessionFactory();
factories.Add(databaseKey, factory);
My Autofac injection:
public static IContainer RegisterAllDependencies()
{
var builder = new ContainerBuilder();
builder.Register(x => new VejoSeriesDb(SessionPerRequestModule.GetCurrentSession(DatabaseKeys.VejoSeriesDb))).As<IVejoSeriesDb>();
builder.Register(x => new StarkDb(SessionPerRequestModule.GetCurrentSession(DatabaseKeys.MySQLStarkDb))).As<IStarkDb>();
//session mongo
builder.Register(x => new StarkMongoDb()).As<IStarkMongoDb>();
builder.RegisterAssemblyTypes(typeof(IUsuarioSerieN).Assembly)
.AsImplementedInterfaces();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
return container;
}
Where I´m forgetting to close the connections?
I was assigned to a older project been done in asp webforms. So in every page load I found code like
if (HttpContext.Current.Session["UserDetails"] != null)
For checking if session is active for visiting the page. Is there any single point where I can write this code so that if user is inactive loginPage is presented.
Maybe you could achieve your task with a HTTPModule:
Example from MSDN
using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; }
}
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source,
EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
// test here your session
}
}
private void Application_EndRequest(Object source, EventArgs e)
{
}
public void Dispose() { }
}
You should register this module in your web.config:
<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>
If you have controller page, how about this way?
Controller page.
[SessionExpireFilter]
public void functionname()
{
//you're function region page?
}
New createpage.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session["UserDetails"] == null)
{
filterContext.Result = new RedirectResult("~/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
I'm implementing a multiplayer card game for windows phone 8 using multicast networking.
However, when I try to link a windows phone and the emulator nothing happens (no errors as well).
I can surf the web using internet explorer so my emulator is connected to the internet.
Do I have to make a special operation on the emulator in order to enable it to do multicast operations?
Or is there something missing in the code?
Here is the code:
Initialization
channel = new UdpChannel(IPAddress.Parse("224.109.108.106"), 3000);
this.channel.OnAfterOpened += new EventHandler<UdpPacketEventArgs>(channel_OnAfterOpen);
this.channel.OnPacketReceived += new EventHandler<UdpPacketEventArgs(Channel_PacketReceived);
this.channel.Open();
My multicast operating class:
public UdpChannel(IPAddress address, int port)
{
groupAddress = address;
localPort = port;
client = new UdpAnySourceMulticastClient(groupAddress, localPort);
}
public void Open()
{
if (!isJoined)
{
this.client.BeginJoinGroup(
result =>
{
try
{
this.client.EndJoinGroup(result);
isJoined = true;
this.AfterOpened();
this.Receive();
}
catch (Exception e)
{
throw e;
}
}, null);
}
}
private void AfterOpened()
{
EventHandler<UdpPacketEventArgs> handler = this.OnAfterOpened;
if (handler != null)
handler(this, new UdpPacketEventArgs(string.Empty, string.Empty));
}
private void Receive()
{
if (isJoined)
{
Array.Clear(this.buffer, 0, this.buffer.Length);
this.client.BeginReceiveFromGroup(this.buffer, 0, this.buffer.Length, result =>
{
if (!isDisposed)
{
IPEndPoint source;
try
{
this.client.EndReceiveFromGroup(result, out source);
this.AfterReceived(source, this.buffer);
this.Receive();
}
catch
{
isJoined = false;
this.Open();
}
}
}, null);
}
}
public void SendTo(int cardId)
{
byte[] data = Encoding.UTF8.GetBytes(cardId.ToString());
if (isJoined)
{
this.client.BeginSendToGroup(data, 0, data.Length,
result =>
{
this.client.EndSendToGroup(result);
}, null);
}
}
private void AfterReceived(IPEndPoint source, byte[] p)
{
EventHandler<UdpPacketEventArgs> handler = this.OnPacketReceived;
if (handler != null)
handler(this, new UdpPacketEventArgs(source.Address.ToString(), Encoding.UTF8.GetString(p, 0, p.Length)));
}
private void BeforeClose()
{
EventHandler<UdpPacketEventArgs> handler = this.OnBeforeClosing;
if (handler != null)
handler(this, new UdpPacketEventArgs(string.Empty, string.Empty));
}
#region IDisposable
public void Dispose()
{
if (!isDisposed)
{
Dispose(true);
GC.SuppressFinalize(this);
}
isDisposed = true;
}
~UdpChannel()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
client.Dispose();
}
}
My events
public class UdpPacketEventArgs : EventArgs
{
public string Message { get; private set; }
public string Source { get; private set; }
public UdpPacketEventArgs(string source, string data)
{
this.Message = data;
this.Source = source;
}
}
My events handlers
private void Channel_PacketReceived(object sender, UdpPacketEventArgs e)
{
MessageBox.Show("Something Received");
}
private void channel_OnAfterOpen(object sender, UdpPacketEventArgs e)
{
this.Status.Text = "Connected";
}
I implement standart scenario in asp.net session per reqest.
My asp.net module:
public class NHibernateSessionModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
context.EndRequest += context_EndRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
var session = SessionManager.SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
void context_EndRequest(object sender, EventArgs e)
{
var session = SessionManager.CurrentSession;
if (session != null)
{
try
{
if (session.Transaction != null && session.Transaction.IsActive)
session.Transaction.Commit();
}
catch (Exception ex)
{
session.Transaction.Rollback();
throw new ApplicationException("Error committing database transaction", ex);
}
finally
{
session.Close();
}
}
CurrentSessionContext.Unbind(SessionManager.SessionFactory);
}
}
My sessionManager is thread-safe singletone:
public class SessionManager
{
private readonly ISessionFactory sessionFactory;
public static ISessionFactory SessionFactory
{
get { return Instance.sessionFactory; }
}
private ISessionFactory GetSessionFactory()
{
return sessionFactory;
}
public static ISession OpenSession()
{
return Instance.GetSessionFactory().OpenSession();
}
public static ISession CurrentSession
{
get
{
if (!CurrentSessionContext.HasBind(Instance.GetSessionFactory()))
return null;
return Instance.GetSessionFactory().GetCurrentSession();
}
}
public static SessionManager Instance
{
get
{
return NestedSessionManager.sessionManager;
}
}
private SessionManager()
{
Configuration configuration = new Configuration().Configure();
sessionFactory = configuration.BuildSessionFactory();
}
class NestedSessionManager
{
internal static readonly SessionManager sessionManager =
new SessionManager();
}
}
The main idea open session in begin of request and then use session through SessionManager.CurrentSession;
Session is stored in configured context:
<property name="current_session_context_class">web</property>
My repository:
public class RepositoryNew<T> : BaseRepository<T>, IDisposable
{
public RepositoryNew()
{
if (NHibernateSession == null)
//Start session for not web version
}
public void Dispose()
{
//flush session for not web version
}
protected override sealed ISession NHibernateSession
{
get
{
return SessionManager.CurrentSession;
}
}
}
Usage
protected void Page_Load(object sender, EventArgs e)
{
var repo = new RepositoryNew<Client>()
clients = repo.GetAll();
}
By some reason this repository doesn't use opened session in module.
CurrentSessionContext.HasBind(Instance.GetSessionFactory())
returns false, so my code starts second session in request.
At debugger I see that I have instantieted my SessionManager twice.
My be I have two different ISesssion factories.
I haven't ideas yet what's wrong. I have spent on it a lot of hours.
Maybe another thing open session in Http Begin Request because every http request will open new session like request static image you must change this strategy to eliminate this unnecessary session in every Http request you can read this blog and change your strategy http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx
It was strange error. When I remove link to SessionManager from my project, it starts work properly.