NetworkInfo.Type is obsolete:"deprecated" - c#

For example i have this method:
public static bool IsConnectedMobile
{
get
{
var info = ConnectivityManagers.ActiveNetworkInfo;
return info != null && info.IsConnected && info.Type == ConnectivityType.Mobile;
}
}
and i get an error here: info.Type == ConnectivityType.Mobile;
And my question is, can i found an alternative? (without using other libraries)

ActiveNetworkInfo you need get it from GetSystemService Just use this code
ConnectivityManager cm = (ConnectivityManager)this.GetSystemService(Context.ConnectivityService);
NetworkInfo activeNetwork = cm.ActiveNetworkInfo;
if (activeNetwork != null)
{
//connected to the internet
}
else
{
//not connected to the internet
}
& for more information go through this thread

This feature is platform-specific. Basically you can check the Network Connection status by using the below code:
var cm = (ConnectivityManager)GetSystemService(Context.ConnectivityService);
bool isConnected = cm.ActiveNetworkInfo.IsConnected;
Should be quite straightforward.
Thanks.

Related

Add binding to IIS-site - NullReferenceException

I am trying to add bindings to a website in IIS with C# code. It seem to work on my local computer, but not on the hosting server (Windows Server 2022). Adding http-binding works, but commit after https causes NullReferenceException, and i am wondering if any of you can explain to me why?
My code is like this (i replaced my actual domainname with . "sitename" and "hostHttpsBinding" always exists with the certificate i want to use):
public static bool AddBindings(IConfiguration configuration, ILogger logger, string subdomain)
{
if (string.IsNullOrWhiteSpace(subdomain)) return false;
try
{
var server = new ServerManager();
var sitename = EnvironmentHelper.IsProd(configuration) ? "<domain>.no" : "test.<domain>.no";
var hostname = $"{subdomain.ToLowerInvariant().Trim()}.<domain>.no";
var site = server.Sites.FirstOrDefault(a => a.Name == sitename);
if (site == null) return false;
logger.LogInformation($"IIS: Sitename {sitename} found. Trying to add bindings...");
var hostHttpsBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:443:{sitename}");
var httpBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:80:{hostname}");
var httpsBinding = site.Bindings.FirstOrDefault(a => a.BindingInformation == $"*:443:{hostname}");
if (httpBinding != null && httpsBinding != null) return false;
if (httpBinding == null)
{
site.Bindings.Add($"*:80:{hostname}", "http");
logger.LogInformation($"IIS: Http-binding added for {hostname}");
}
if (httpsBinding == null)
{
logger.LogInformation($"SSLName: {hostHttpsBinding.CertificateStoreName}, Hash: {hostHttpsBinding.CertificateHash}");
site.Bindings.Add($"*:443:{hostname}", hostHttpsBinding.CertificateHash, hostHttpsBinding.CertificateStoreName, SslFlags.Sni);
logger.LogInformation($"IIS: Https-binding added for {hostname}");
}
server.CommitChanges();
server.Dispose();
return true;
}
catch (Exception e)
{
logger.LogError($"IIS: Something went wrong when adding bindings: {e.Message}, {e.InnerException.Message}");
return false;
}
}
This is my error message:
ERROR|Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer|Connection ID "16717361851964326032", Request ID "40000091-0008-e800-b63f-84710c7967bb": An unhandled exception was thrown by the application.|System.NullReferenceException: Object reference not set to an instance of an object.

Session value returned null in mvc5 asp.net

I have login controller and in this i get my session values
[HttpPost]
public ActionResult Login(Models.AdminUsers adminUsers)
{
try
{
if (Session["iUserId"] != null || GetCookie("iUserId") != null)
{
return Redirect("/Home/Index");
}
if (ModelState.IsValid)
{
using (Data.DataClassesDataContext dc = new Data.DataClassesDataContext())
{
var resultUsers =
(from tableAdminUsers in dc.AdminUsers
where
tableAdminUsers.cEmail == adminUsers.cEmail &&
tableAdminUsers.cPassaword == new Class.AesCryption().Encryption(adminUsers.cPassaword) &&
tableAdminUsers.iActive == 1
select new Models.AdminUsers
{
iUserId = tableAdminUsers.iUserId,
cEmail = tableAdminUsers.cEmail,
cUserName = tableAdminUsers.cUserName,
cUserSurname = tableAdminUsers.cUserSurname,
cImage = tableAdminUsers.cImage
}).FirstOrDefault();
if (resultUsers != null)
{
if (adminUsers.lBeniHatirla == false)
{
Session.Add("iUserId", resultUsers.iUserId);
Session.Add("cEmail", resultUsers.cEmail);
Session.Add("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
Session.Add("cUserSurname", resultUsers.cUserSurname.ToUpper());
Session.Add("cImage", resultUsers.cImage);
}
else
{
CreateCookie("iUserId", resultUsers.iUserId.ToString());
CreateCookie("cEmail", resultUsers.cEmail);
CreateCookie("cUserName", new Class.TextLowerAndFirstUpper().Send(resultUsers.cUserName));
CreateCookie("cUserSurname", resultUsers.cUserSurname.ToUpper());
CreateCookie("cImage", resultUsers.cImage);
}
return Redirect("/Home/Index");
}
else
{
ViewBag.iSonuc = -7;
}
}
}
else
{
ViewBag.iSonuc = -6;
}
}
catch (Exception Ex)
{
new Class.Log().Hata("AdminUsers", "AdminUsers_Post", Ex.Message);
}
return View();
}
And i want to control to session in another controller but my session value return null. My control like this :
if (Session["iUserId"] == null && GetCookie("iUserId") == null)
{
return Redirect("/AdminUsers/Login");
}
int iUserLogin = 0;
if (Session["iUserId"] != null && Convert.ToInt32(Session["iUserId"]) > 0)
{
iUserLogin = Convert.ToInt32(Session["iUserId"]);
}
else if (GetCookie("iUserId") != null && Convert.ToInt32(GetCookie("iUserId")) > 0)
{
iUserLogin = Convert.ToInt32(GetCookie("iUserId"));
}
if (Session["iUserId"] == null && GetCookie("iUserId") == null) this row return true and redict to login page again.But i getting cookie correctly Why session value return null?
Where am I making mistakes? Can you help me?
If it is a .net core, use httpcontext. You can solve it using a distribution cache such as Redis. https://learn.microsoft.com/tr-tr/aspnet/core/fundamentals/app-state?view=aspnetcore-5.0
If you want to develop a User Manager
Use a thirty part nuget like Jwt. What it does is sso logic gives you a token for the user you use it
Try using Session with HttpContext as below:-
HttpContext.Current.Session["iUserId"]=value;
Alternativly, you can try using TempData rather then Session.
TempData["iUserId"]=value;
There is a localization function that I use for language change, in this function I am changing the value of the culture using thread, I realized that this function resets my session value.

Not able to access previous stored value in Keychain after update

We’re having a problem to access a value we stored previously in keychain in a previous version of our app. We have updated our Xamarin.iOS version from 11.6.14 to 12.2.1.15 and our XCode version from 9.4.1 to 10.1.
We are not able to access that value anymore after the update.
I have read there are some changes in the security settings, but I’m not able to find the specifics about that. Is there anybody that had that problem before or has lot of experience with keychain? Thanks for your help!
bool WriteGenericPasswordValueToSecureKeychain(string service, string account, string value)
{
if (service == null || account == null || value == null)
{
throw new ArgumentNullException("Both arguments need a value and cannot be null");
}
var query = new SecRecord(SecKind.GenericPassword)
{
Service = service,
Account = account
};
var newRecord = new SecRecord(SecKind.GenericPassword)
{
Service = service,
Account = account,
ValueData = NSData.FromString(value, NSStringEncoding.UTF8)
};
SecStatusCode error;
var match = SecKeyChain.QueryAsRecord(query, out error);
if (error == SecStatusCode.Success)
{
error = SecKeyChain.Update(match, newRecord);
}
else
{
error = SecKeyChain.Add(newRecord);
}
if (error != SecStatusCode.Success && error != SecStatusCode.DuplicateItem)
{
return false;
}
return true;
}

How to obtain Public IP of a device using C# with out using external API/Services

public static string GetPublicIp()
{
HttpContext context = HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
I'm trying to get the client Public IP but the above code only returns the client Local IP. If different people are connecting to my organisation from the same organisations network, i want to get only their public IP address. I'm not intrested in their local IPs, is this possible.
Below is one solution i have so far seen but i'm NOT liking it.
public static string GetPublicIp()
{
string direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
using (WebResponse response1 = request.GetResponse())
using (StreamReader stream1 = new StreamReader(response1.GetResponseStream()))
{
direction = stream1.ReadToEnd();
}
//Search for the ip in the html
int first1 = direction.IndexOf("Address: ") + 9;
int last1 = direction.LastIndexOf("</body>");
direction = direction.Substring(first1, last1 - first1);
return direction;
}
The above sample solution can get me the public IP but i don't want to be tied to an external service that i have no control over because if that service is down then iam screwed and the performance is terrible.
Does any one know how i can get the clients public IP with out calling external services?
This method gives you the local ip address. I've copied it from a WinRT-Solution, maybe the class names are a bit different in other .NET environments.
private static string GetLocalAddress()
{
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
return hn.DisplayName;
}
}
return IpAddress.Broadcast.Address;
}
EDIT: The following method prints out all local ip addresses.
private static void PrintLocalAddresses()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var ni in interfaces)
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
{
var adapterProperties = ni.GetIPProperties();
foreach (var x in adapterProperties.UnicastAddresses)
{
if (x.Address.AddressFamily == AddressFamily.InterNetwork)
{
Console.WriteLine(x.Address);
}
}
}
}
}

HttpContext IP Problem

I have a problem when I use HttpContext.Current.Request.UserHostAddress, some times returns "192.168.0.17" (IPv4) and some times returns "fe80::99be:a05d:7938:1c30%8" (IPv6), calling from the same computer and navigator.
What I do to return always IPv4?
Check out this post on 4GuysFromRolla and see if it helps at all. I think this is the information you're looking for.
https://web.archive.org/web/20201028122055/https://aspnet.4guysfromrolla.com/articles/071807-1.aspx
~md5sum~
public static string GetIP4Address()
{
string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(HttpContext.Current.Request.UserHostAddress))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
if (IP4Address != String.Empty)
{
return IP4Address;
}
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily.ToString() == "InterNetwork")
{
IP4Address = IPA.ToString();
break;
}
}
return IP4Address;
}
Found a solution that somebody hacked up. Can't say if it'll work, tho =)
http://www.eggheadcafe.com/software/aspnet/30078410/request-object.aspx

Categories