Unity3D Webrequest SSL IOS CertificateHandler - unity3d

Im trien to have a "Ignore all SSL Certificates" Checkbox for a Webrequest in Unity.
On Android it was working fine, but on IOS, I wasnt able to reset certhandler to default, it always returned true, once it was set. I tried dispose the handler by myself, set it to null and also I tried to clear cache.
Here is my code atm
using UnityEngine.Networking;
internal class AcceptAllCertificatesOrVerify : CertificateHandler
{
Main main = null;
protected override bool ValidateCertificate(byte[] certificateData)
{
if (main == null)
{
GameObject go = GameObject.Find("Main");
if (go != null)
{
main = go.GetComponent<Main>();
}
}
if (main != null && main.currentMandant != null && main.currentMandant.mandantIgnoreSSL)
{
main.ConsoleLog("ValidateCertificate: mandantIgnoreSSL");
return true;
}
else
{
if (main == null)
{
Debug.Log("ValidateCertificate: main null");
}
else
{
if (main.currentMandant == null)
{
main.ConsoleLog("ValidateCertificate: main.currentMandant null");
}
else
{
main.ConsoleLog("ValidateCertificate: main.currentMandant.mandantIgnoreSSL false");
}
}
}
main.ConsoleLog("Default ValidateCertificate");
return base.ValidateCertificate(certificateData);
}
}
it has some debugging activated, but when I check my adb log, I see only "ValidateCertificate: mandantIgnoreSSL". And never one of the other messages.
I also tried to set an remove certificateHandler dynamic like this:
{
webRequest.certificateHandler = new AcceptAllCertificatesOrVerify();
}
else
{
webRequest.certificateHandler = null;
}
But after AcceptAllCertificatesOrVerify was set once, I cant unset.
Is it a unity bug?

Related

How to setting firebase remote config for unity?

lets to the point, so i want to make some configuration with my game to show Ads but I avoid to update game version too much, because of that I choose firebase remote config with this I can update setting/configuration without update the game version.
there is document for this but not very clear for newbie like me, you can check it here https://firebase.google.com/docs/remote-config/use-config-unity
I already make the script like on doc, but I don't understand how its work on show data because error string format, which is what I know on this firebase console is int format
the script like this :
public static _FirebaseRemoteConfig instance;
private void Awake()
{
instance = this;
}
Firebase.DependencyStatus dependencyStatus = Firebase.DependencyStatus.UnavailableOther;
// Use this for initialization
void Start()
{
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
InitializeFirebase();
}
else
{
Debug.LogError(
"Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
public void InitializeFirebase()
{
System.Collections.Generic.Dictionary<string, object> defaults =
new System.Collections.Generic.Dictionary<string, object>();
defaults.Add("config_test_string", "default local string");
defaults.Add("config_test_int", 1);
defaults.Add("config_test_float", 1.0);
defaults.Add("config_test_bool", false);
Firebase.RemoteConfig.FirebaseRemoteConfig.SetDefaults(defaults);
Debug.Log("Remote config ready!");
}
public void FetchFireBase()
{
FetchDataAsync();
}
public void ShowData()
{
Debug.Log("maxCountToShowAdmob: " +
Firebase.RemoteConfig.FirebaseRemoteConfig.GetValue("MaxCountShowIntersitialAds").LongValue);
}
// Start a fetch request.
public Task FetchDataAsync()
{
Debug.Log("Fetching data...");
System.Threading.Tasks.Task fetchTask = Firebase.RemoteConfig.FirebaseRemoteConfig.FetchAsync(
TimeSpan.Zero);
return fetchTask.ContinueWith(FetchComplete);
}
void FetchComplete(Task fetchTask)
{
if (fetchTask.IsCanceled)
{
Debug.Log("Fetch canceled.");
}
else if (fetchTask.IsFaulted)
{
Debug.Log("Fetch encountered an error.");
}
else if (fetchTask.IsCompleted)
{
Debug.Log("Fetch completed successfully!");
}
var info = Firebase.RemoteConfig.FirebaseRemoteConfig.Info;
switch (info.LastFetchStatus)
{
case Firebase.RemoteConfig.LastFetchStatus.Success:
Firebase.RemoteConfig.FirebaseRemoteConfig.ActivateFetched();
Debug.Log(String.Format("Remote data loaded and ready (last fetch time {0}).",
info.FetchTime));
break;
case Firebase.RemoteConfig.LastFetchStatus.Failure:
switch (info.LastFetchFailureReason)
{
case Firebase.RemoteConfig.FetchFailureReason.Error:
Debug.Log("Fetch failed for unknown reason");
break;
case Firebase.RemoteConfig.FetchFailureReason.Throttled:
Debug.Log("Fetch throttled until " + info.ThrottledEndTime);
break;
}
break;
case Firebase.RemoteConfig.LastFetchStatus.Pending:
Debug.Log("Latest Fetch call still pending.");
break;
}
}

How to effectively handle session in asp.net

I have one web site with multiple accounts like staff, end user and admin.
However I am creating each session while the user is logged into their account.
if (Page.IsValid)
{
string type_name="";
int returnValue = DatabaseHelper.GetLogin(txtusername.Text.Trim(), txtpassword.Text.Trim(), out type_name);
if (returnValue == 1)
{
if (chk_remember.Checked == true)
{
if (type_name.Trim()=="Admin")
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else if (type_name.Trim()=="User")
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
else
{
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(-1);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(-1);
if (type_name.Trim()== "Admin")
{
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else if (type_name.Trim()== "User")
{
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
}
else if (returnValue == -1)
{
ltr_error.Text = "Authentication failed..contact administrator";
}
else
{
ltr_error.Text = "Invalid username or password";
}
}
}
Here, sessions are created but how I handle them for long time as possible in ASP.NET timeout? Is that way to handle them with global.asax file?
Also, how do I redirect the user to login page if no session found in application?
-------------------------------------Updated----------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreRender(EventArgs e)
{
if (Context.Session != null && Context.Session.IsNewSession)
{
if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Default.aspx");
}
}
base.OnPreRender(e);
}
}
session by default lasts for 20 mins - depending on the setting in IIS and also the web.config.
if session is expires, the Session_End event in the global.asax gets fired. from there, you cannot exactly redirect and would not be the right place to redirect anyway.
you should create a user control for example, which is on every page or even better a master page from which all pages derive from, then you can check on every request if Session is empty. if so, redirect to the logon page.
I have done this many times and works a treat.
I have this on a prerender event in a user control:
if (Context.Session != null && Context.Session.IsNewSession)
{
if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
}

addautomtioneventhandler on web pages

I'm trying to add an automation event handler for a ui button. I've tested on desktop applications and it's working but I've a problem with buttons in web pages.In fact I can invoke them with InvokePattern.Invoke() but I don't see the handler working after that!
this is my code :
if ((wantedElement != null))
{
element = wantedElement;
buttonEvent = new AutomationEventHandler(close_event);
Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, element,TreeScope.Element,buttonEvent );
object pattern;
if (wantedElement.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))
{
InvokePattern invokePattern = (InvokePattern)pattern;
invokePattern.Invoke();
}
}
...
private static void close_event(object sender, AutomationEventArgs e)
{
AutomationElement sourceElement;
try
{
sourceElement = sender as AutomationElement;
Console.WriteLine("button try");
}
catch (ElementNotAvailableException)
{
return;
}
if (e.EventId == InvokePattern.InvokedEvent)
{
// TODO Add handling code.
Console.WriteLine("button invoked");
}
else
{
// TODO Handle any other events that have been subscribed to.
Console.WriteLine("button event");
}
}

WP - How to constantly update my location

Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}

Is EntityReference.Load checking for EntityReference.IsLoaded?

Hi I was wondering if EntityReference.Load method includes
If Not ref.IsLoaded Then ref.Load()
My question is basically:
Dim person = Context.Persons.FirstOrDefault
person.AddressReference.Load()
person.AddressReference.Load() 'Does it do anything?
It does Load again. I verified this by Profiler and it shown two queries. Default merge option is MergeOption.AppendOnly and it doesn't prevent from querying again. Code from Reflector:
public override void Load(MergeOption mergeOption)
{
base.CheckOwnerNull();
ObjectQuery<TEntity> query = base.ValidateLoad<TEntity>(mergeOption, "EntityReference");
base._suppressEvents = true;
try
{
List<TEntity> collection = new List<TEntity>(RelatedEnd.GetResults<TEntity>(query));
if (collection.Count > 1)
{
throw EntityUtil.MoreThanExpectedRelatedEntitiesFound();
}
if (collection.Count == 0)
{
if (base.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One)
{
throw EntityUtil.LessThanExpectedRelatedEntitiesFound();
}
if ((mergeOption == MergeOption.OverwriteChanges) || (mergeOption == MergeOption.PreserveChanges))
{
EntityKey entityKey = ObjectStateManager.FindKeyOnEntityWithRelationships(base.Owner);
EntityUtil.CheckEntityKeyNull(entityKey);
ObjectStateManager.RemoveRelationships(base.ObjectContext, mergeOption, (AssociationSet) base.RelationshipSet, entityKey, (AssociationEndMember) base.FromEndProperty);
}
base._isLoaded = true;
}
else
{
base.Merge<TEntity>(collection, mergeOption, true);
}
}
finally
{
base._suppressEvents = false;
}
this.OnAssociationChanged(CollectionChangeAction.Refresh, null);
}
Just for reference for anyone else finding the accepted answer, here is the extension method I created for my current project.
using System.Data.Objects.DataClasses;
namespace ProjectName
{
public static class EntityFrameworkExtensions
{
public static void EnsureLoaded<TEntity>(this EntityReference<TEntity> reference)
where TEntity : class, IEntityWithRelationships
{
if (!reference.IsLoaded)
reference.Load();
}
}
}
And usage:
Patient patient = // get patient
patient.ClinicReference.EnsureLoaded();
patient.Clinic.DoStuff();