I am writing an application that loads parameters from the registry. Here is the code I use to load it:
public bool getRegValues() //get values used for the SQL Connection etc
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))
{
if (key != null)
{
this.serverName = key.GetValue("SQLserver").ToString();
this.timeout = key.GetValue("timeout").ToString();
this.Database = key.GetValue("database").ToString();
this.logTable = key.GetValue("table_log").ToString();
this.budgetTable = key.GetValue("table_budget").ToString();
this.personsTable = key.GetValue("table_persons").ToString();
this.tempTable = key.GetValue("table_temp").ToString();
this.cashiersDB = key.GetValue("cashiersDB").ToString();
this.customersTbl = key.GetValue("cashiersCustomersTable").ToString();
key.SetValue("version", version);
if (this.serverName == null || this.timeout == null || this.Database == null || this.logTable == null
|| this.budgetTable == null || this.personsTable == null || this.tempTable == null)
{
Console.WriteLine("One of the values could not be loaded.");
return false;
}
}
else
{
Console.WriteLine("Key is null.");
return false;
}
return true;
}
}
When I run the code on my workstation everything is perfect. When I do it on the server it returns false and writes "Key is null.".
When I compile the code using Registry.CurrentUser instead of Registry.LocalMachine it returns true (Of course the values in the different locations are identical).
What is wrong? I am domain admin and have also given myself explicitly full control permissions to the Key HKEY_LOCAL_MACHINE\SOFTWARE\Company\Application\NightJob\
Any ideas?
If you are using .Net 4 try this using:
using(RegistryKey SoftwareKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(#"SOFTWARE\Company\Application\NightJob\", RegistryKeyPermissionCheck.ReadWriteSubTree))
Related
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.
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;
}
I have a requirement to read registry values in HKEY_CLASSES_ROOT and HKEY_LOCAL_MACHINE. But when I am trying to get the subkey object with read access, I get this exception: "Requested registry access is not allowed". ( Note :: In my app i am not doing any write or modifications to registry.)
This error only occurs when I try running from client machine. In my machine, it works well. Since both the machines have administrative access, I think some other thing is causing the problem. I am able to read and edit registry values manually from the client machine.
I have edited manifest file and changed required permissions from asInvoker to requireAdministrator. But no luck. Any workarounds?
Here is my code sample.
public List<SysApps> GetAllApps()
{
List<SysApps> appList = new List<SysApps>();
// The area's we are scanning
appList.AddRange(this.LoadFiles(RegistryHive.CurrentUser, RegistryView.Registry32,
#"Software\Microsoft\Windows\CurrentVersion\Uninstall"));
appList.AddRange(this.LoadFiles(RegistryHive.LocalMachine, RegistryView.Registry32,
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"));
appList.AddRange(this.LoadFiles(RegistryHive.LocalMachine, RegistryView.Registry64,
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"));
return appList.OrderBy(r => r.DisplayName).ToList();
}
private List<SysApps> LoadFiles(RegistryHive reghive, RegistryView regview, string regkeypath)
{
ist<SysApps> appList = new List<SysApps>();
using (RegistryKey regedit = RegistryKey.OpenBaseKey(reghive, regview))
using (RegistryKey regkey = regedit.OpenSubKey(regkeypath, RegistryKeyPermissionCheck.ReadSubTree))
{
if (regkey == null) goto last;
foreach (string subkey in regkey.GetSubKeyNames())
{
if (subkey == null) continue;
using (RegistryKey key = regkey.OpenSubKey(subkey))
{
if (key == null) continue;
SysApps sysapp = new SysApps();
sysapp._displayName = key.GetValue("DisplayName") == null ? string.Empty : (string)key.GetValue("DisplayName");
sysapp._publisher = key.GetValue("Publisher") == null ? string.Empty : (string)key.GetValue("Publisher");
sysapp._installDate = key.GetValue("InstallDate") == null ? string.Empty : (string)key.GetValue("InstallDate");
var decValue = key.GetValue("EstimatedSize") == null ? "0" : key.GetValue("EstimatedSize");
sysapp._estimatedSize = decValue.ToString() == "0" ? string.Empty : AppCommon.GetSize(decValue.ToString());
sysapp._displayIcon = key.GetValue("DisplayIcon") == null ? string.Empty : (string)key.GetValue("DisplayIcon");
if (string.IsNullOrEmpty(sysapp._displayIcon) && !string.IsNullOrEmpty(sysapp._displayName))
sysapp._displayIcon = this.GetIconForRoot(sysapp._displayName);
if (!string.IsNullOrEmpty(sysapp._displayIcon))
sysapp._displayIcon = sysapp._displayIcon.Replace("\"", string.Empty).Trim();
sysapp._displayVersion = key.GetValue("DisplayVersion") == null ? string.Empty : (string)key.GetValue("DisplayVersion");
sysapp._uninstallString = key.GetValue("UninstallString") == null ? string.Empty : (string)key.GetValue("UninstallString");
sysapp._modifyPath = key.GetValue("ModifyPath") == null ? string.Empty : (string)key.GetValue("ModifyPath");
// Validate
var rType = (string)key.GetValue("ReleaseType");
var sComponent = key.GetValue("SystemComponent");
var pName = (string)key.GetValue("ParentDisplayName");
if (!string.IsNullOrEmpty(sysapp._displayName) && string.IsNullOrEmpty(rType) && string.IsNullOrEmpty(pName) && (sComponent == null))
{
AppCommon.FileSize += Int32.Parse(decValue.ToString());
appList.Add(sysapp);
}
key.Flush();
key.Close();
}
}
regkey.Flush();
regkey.Close();
}
last:
return appList;
}
private string GetIconForRoot(string productName)
{
string result = string.Empty;
string installerKey = #"Installer\Products";
bool isFound = false;
using (RegistryKey regedit = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32))
using (RegistryKey regkey = regedit.OpenSubKey(installerKey, RegistryKeyPermissionCheck.ReadSubTree))
{
if (regkey == null) goto last;
foreach (string subkey in regkey.GetSubKeyNames())
{
if (subkey == null) continue;
using (RegistryKey key = regkey.OpenSubKey(subkey))
{
if (key.GetValue("ProductName") != null)
if (productName == key.GetValue("ProductName").ToString())
if (key.GetValue("ProductIcon") != null)
{
isFound = true;
result = key.GetValue("ProductIcon").ToString();
}
key.Flush();
key.Close();
if (isFound) break;
}
}
egkey.Flush();
regkey.Close();
}
last:
return result;
}
Finally I found the answer. I did following changes to my code.
public async Task<List<Apps>> GetAllApps()
{
List<Apps> _installedApps = new List<Apps>();
_installedApps.AddRange(await this.LoadFiles(Registry.CurrentUser,
#"Software\Microsoft\Windows\CurrentVersion\Uninstall"));
_installedApps.AddRange(await this.LoadFiles(Registry.LocalMachine,
#"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"));
_installedApps.AddRange(await this.LoadFiles(Registry.LocalMachine,
#"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall"));
return _installedApps.OrderBy(x => x.DisplayName).ToList();
}
private async Task<List<Apps>> LoadFiles(RegistryKey rkey, string regkeypath)
{
List<Apps> appList = new List<Apps>();
RegistryKey regkey =
rkey.OpenSubKey(regkeypath,
RegistryKeyPermissionCheck.ReadSubTree,
RegistryRights.ReadKey);
if (regkey == null) goto last;
foreach (string subkey in regkey.GetSubKeyNames())
{
if (subkey == null) continue;
using (RegistryKey key = regkey.OpenSubKey(subkey))
{
if (key == null) continue;
// Validating
var rType = (string)key.GetValue("ReleaseType");
var sComponent = key.GetValue("SystemComponent");
var pName = (string)key.GetValue("ParentDisplayName");
var dName = (string)key.GetValue("DisplayName");
if (!string.IsNullOrEmpty(dName) && string.IsNullOrEmpty(rType) && string.IsNullOrEmpty(pName) && (sComponent == null))
appList.Add(await ReadKeyValues(key));
key.Flush();
key.Close();
}
}
regkey.Flush();
regkey.Close();
last:
return appList;
}
private Task<string> GetIconForRoot(string productName)
{
string result = string.Empty;
string installerKey = #"Installer\Products";
bool isFound = false;
RegistryKey regkey = Registry.ClassesRoot.OpenSubKey(installerKey,
RegistryKeyPermissionCheck.ReadSubTree,
RegistryRights.ReadKey);
if (regkey == null) goto last;
foreach (string subkey in regkey.GetSubKeyNames())
{
if (subkey == null) continue;
using (RegistryKey key = regkey.OpenSubKey(subkey))
{
if (key.GetValue("ProductName") != null)
if (productName == key.GetValue("ProductName").ToString())
if (key.GetValue("ProductIcon") != null)
{
isFound = true;
result = key.GetValue("ProductIcon").ToString();
}
key.Flush();
key.Close();
if (isFound) break;
}
}
regkey.Flush();
regkey.Close();
last:
return Task.FromResult(result);
}
private async Task<Apps> ReadKeyValues(RegistryKey key)
{
Apps installedApp = new Apps();
installedApp._displayName = key.GetValue("DisplayName") == null ? string.Empty : (string)key.GetValue("DisplayName");
installedApp._publisher = key.GetValue("Publisher") == null ? string.Empty : (string)key.GetValue("Publisher");
installedApp._installDate = key.GetValue("InstallDate") == null ? string.Empty : (string)key.GetValue("InstallDate");
var decValue = key.GetValue("EstimatedSize") == null ? "0" : key.GetValue("EstimatedSize");
installedApp._estimatedSize = decValue.ToString() == "0" ? string.Empty : Common.GetSize(decValue.ToString());
installedApp._systemIcon = key.GetValue("DisplayIcon") == null ? string.Empty : (string)key.GetValue("DisplayIcon");
if (string.IsNullOrEmpty(installedApp._systemIcon) && !string.IsNullOrEmpty(installedApp._displayName))
installedApp._systemIcon = await this.GetIconForRoot(installedApp._displayName);
if (!string.IsNullOrEmpty(installedApp._systemIcon))
installedApp._systemIcon = installedApp._systemIcon.Replace("\"", string.Empty).Trim();
installedApp._displayVersion = key.GetValue("DisplayVersion") == null ? string.Empty : (string)key.GetValue("DisplayVersion");
installedApp._uninstallString = key.GetValue("UninstallString") == null ? string.Empty : (string)key.GetValue("UninstallString");
installedApp._modifyPath = key.GetValue("ModifyPath") == null ? string.Empty : (string)key.GetValue("ModifyPath");
Common.FileSize += Int32.Parse(decValue.ToString());
return installedApp;
}
Then I added the app.manifest
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="asInvoker"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
</application>
</compatibility>
</assembly>
I am having two accounts in HKEY_USERS in registry entry for the same user.
These are:
HKEY_USERS\S-1-5-21-507921405-1993962763-682003330-1012
HKEY_USERS\S-1-5-21-507921405-1993962763-682003330-1014
The problem comes when I fetch the value for the current user using Registry.CurrentUser.OpenSubKey() method.
It fetches the value from HKEY_USERS\S-1-5-21-507921405-1993962763-682003330-1012 while HKEY_CURRENT_USER is mapped(or in sync) with HKEY_USERS\S-1-5-21-507921405-1993962763-682003330-1014.
So the actual values are not fetched. Can someone please help me out in this context as why two accounts exists in registry for the same user and how i can map(or do sync) for HKEY_CURRENT_USER with
HKEY_USERS\S-1-5-21-507921405-1993962763-682003330-1014.
My code is as follows:
string strKeyIESettings = #"Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Ranges";
string valRange1 = "", valRange2 = "", valRange3 = "", valRange4 = "";
using (Microsoft.Win32.RegistryKey keyIESettings = Registry.CurrentUser.OpenSubKey(strKeyIESettings))
{
foreach (string subkey_name in keyIESettings.GetSubKeyNames())
{
using (RegistryKey subkey = keyIESettings.OpenSubKey(subkey_name))
{
switch (subkey_name)
{
case "Range1" :
if (subkey.GetValue(":Range") != null)
{
valRange1 = subkey.GetValue(":Range").ToString();
}
break;
case "Range2" :
if (subkey.GetValue(":Range") != null)
{
valRange2 = subkey.GetValue(":Range").ToString();
}
break;
case "Range3":
if (subkey.GetValue(":Range") != null)
{
valRange3 = subkey.GetValue(":Range").ToString();
}
break;
case "Range4":
if (subkey.GetValue(":Range") != null)
{
valRange4 = subkey.GetValue(":Range").ToString();
}
break;
default:
break;
}
}
}
}
if (valRange1 == "10.237.24.165" && valRange2 == "10.237.24.166" && valRange3 == "10.237.24.167" && valRange4 == "10.237.24.168")
{
flagIESettings = true;
}
I have to fetch these values as my application pre-requisite.
I have found the solution for the above question. It is as follows:
I am having two accounts in HKEY_USERS in registry entry for the same user because I have installed ASP.NET.
One account is for ASP.NET
and Other one is my current user.
It is always the case when ASP.NET is installed on a user's machine, there are two accounts for the current user in the registry. And one is mapped with HKCU.
Thanks
key = Registry.CurrentUser.OpenSubKey(#"Software\Clients\StartMenuInternet", false);
if (key == null)
{
key = Registry.LocalMachine.OpenSubKey(#"Software\Clients\StartMenuInternet", false);
}
On a very few machines this is coming up blank. When regedit is probed, the key is found to be (value not found). What are my options?
I'm assuming you want to launch a website in the default browser:
string url = "http://server.com";
Process.Start(url);
will do it.
I needed
if (key == null || key.ValueCount == 0)
{
key = Registry.LocalMachine.OpenSubKey(#"Software\Clients\StartMenuInternet", false);
}