“Requested registry access is not allowed” in HKEY_CLASSES_ROOT - c#

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>

Related

Exception thrown filtering IEnumerable collection using Regex on ASP.NET Web API C#

I'm working with a POST method in my ASP.NET MVC + Web API project. The problem is that I want to filter the results of an IEnumerable collection applying a Regex to clear out non alphanumeric characters.
Whenever the program gets to that line it throws an "ArgumentNullException" which also says "Value cannot be null. Parameter name: input".
I understand that it has something to be with the parameters that a method is receiving so I suspect that there might be a problem with the Regex.Replace method so I tried to debug it with no success.
At the beginning I thought that I was using the repository to fill the IEnumerable collection in the wrong way because it's an static attribute declared outside the transaction scope. So then I created another repository instance inside the scope but that didn't resolve the issue.
Any help would be appreciated. Thank you.
Here's my the method with the problematic line (indicated with -------->):
[HttpPost]
public object Post(string token, [FromBody]ExternoApi externo)
{
var ValidateToken = TokensRepository.Validate(token);
if (ValidateToken == null)
throw new NotImplementedException(string.Format("El token ID = \"{0}\" no se encuentra habilitado o aun no se realizo el emparejamiento.", token));
if (externo == null)
throw new ParameterNullException(string.Format("Debe informar un externo."));
Externo externoNew;
var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions()
{
IsolationLevel = IsolationLevel.ReadCommitted
}
);
using (scope)
{
IExternoRepository _repository = new ExternoRepository();
try
{
externoNew = new Externo()
{
dsNombre = externo.dsNombre,
dsApellido = externo.dsApellido,
dsDocumento = externo.dsDocumento,
IdCliente = externo.IdCliente,
dsPatente = externo.dsPatente,
dtCreado = DateTime.Now,
dtModificado = DateTime.Now
};
Regex rgx = new Regex("[^a-zA-Z0-9]");
string pattern = "[^a-zA-Z0-9]";
var _externos = _repository.GetAll();
//var _ExternoExistente = _externos.Where(x => rgx.Replace(x.dsDocumento, "") == rgx.Replace(externoNew.dsDocumento, "")
// && rgx.Replace(x.dsPatente, "") == rgx.Replace(externoNew.dsPatente, "")
// && rgx.Replace(x.IdCliente, "") == rgx.Replace(externoNew.IdCliente, "")).OrderBy(x => x.IdExterno).FirstOrDefault();
This line throws exception --------> var _ExternoExistente = _externos.Where(x => Regex.Replace(x.dsDocumento, pattern, "") == Regex.Replace(externoNew.dsDocumento, pattern, "")
&& Regex.Replace(x.dsPatente, pattern, "") == Regex.Replace(externoNew.dsPatente, pattern, "")
&& Regex.Replace(x.IdCliente, pattern, "") == Regex.Replace(externoNew.IdCliente, pattern, "")).OrderBy(x => x.IdExterno).FirstOrDefault();
if (_ExternoExistente == null)
{
externoNew = _repository.Add(externoNew);
}
else {
externoNew = _ExternoExistente;
}
if (!string.IsNullOrEmpty(externo.binaryImage))
{
var filename = string.Format("E{0}.jpg", externo.IdExterno);
string uploadFolder = WebConfigurationManager.AppSettings["UploadFolder"] != null ? WebConfigurationManager.AppSettings["UploadFolder"] : "upload";
string path = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, uploadFolder);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var imageExterno = ImageEngine.StringToImage(externo.binaryImage);
imageExterno.Save(Path.Combine(path, filename));
externoNew.dsPath = string.Concat("~/", uploadFolder, "/", filename);
_repository.Update(externoNew);
}
var externoDB = _repository.Get(externoNew.IdExterno);
string strPath = HostingEnvironment.ApplicationPhysicalPath;
scope.Complete();
return new ExternoApi()
{
IdExterno = externoDB.IdExterno,
dsNombre = externoDB.dsNombre,
dsApellido = externoDB.dsApellido,
dsDocumento = externoDB.dsDocumento,
IdCliente = externoDB.IdCliente,
binaryImage = !string.IsNullOrEmpty(externoDB.dsPath) ? ImageEngine.ImageToString(string.Concat(strPath, externoDB.dsPath.Replace("~/", "").Replace("/", "\\"))) : "",
dsPatente = externoDB.dsPatente,
};
}
catch (Exception ex)
{
scope.Dispose();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
IApiLogRepository _repoLog = new ApiLogRepository();
var log = new ApiLog();
log.IdDispositivo = ValidateToken.IdDispositivo;
log.dsLog = string.Concat("Dispositivo: ", ValidateToken.IdDispositivo, "\n", ex.Message, "\n || \n", (ex.InnerException != null ? ex.InnerException.Message : ""), (ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ""));
log.dsRequest = serializer.Serialize(externo);
_repoLog.Add(log);
throw new DataRestrictDBException(string.Concat(ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : (ex.InnerException != null ? ex.InnerException.Message : ex.Message), "Externo: ", externo));
}
}
}
either externo.dsDocumento or x.dsDocumento must be null
could do something like:
_externos.Where(x => x.dsDocumento != null && externoNew.dsDocumento != null && Regex.Replace(x.dsDocumento, pattern, "") == Regex.Replace(externoNew.dsDocumento, pattern, "")

C# Unable to load registry values in LocalMachine

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))

How can I write to a folder in another mvc application with web client c#

I hope someone can advise me on the situation I have. I have two asp mvc applications, one is the desktop and the other the mobile version. I want to be able to write files uploaded on the mobile version to a folder in the desktop version, because this latter holds the administrative section of the application. I can download files from one to the other with the WebClient class of .Net, but I haven't been able to upload files from one to the other. I have a console application to test the uploading and whenever I try it I get an error saying "access is denied" to the folder in the application. I tried creating a folder in the application outside of the App_Data folder because I thought this folder is restricted, but I get the same error. Can someone please advise me what to do? I've read googling here and there that this can be easily solved from the IIS administration, but I doubt the guys in my hosting company will be willing to grant me any rights on the administration of any application.
The code I wrote only fails when I try to save the files. Here is the code of the site that receives the request:
[HttpPost]
[AllowAnonymous]
public string SubirArchivosRegistro(HttpPostedFileBase file)
{
string MensajeError = "";
string path = "";
string Success = " El (los) diplomas subidos exitosamente ";
try
{
if (file != null && file.ContentLength > 0)
{
path = Path.Combine(Server.MapPath("~/ArchivosRegistroUsuarios"), file.FileName);
file.SaveAs(path);
Success += file.FileName +",";
}
///return path;
return Success;
}
catch(Exception ex)
{
MensajeError = "Ha ocurrido un error, no se pudieron subir los archivos solicitados "+ex.Message;
return MensajeError;
}
}
And this is the code in the client part (none of the codes is failing, it's just a permissions issue):
try
{
WebClient cliente = new WebClient();
if (GendarmeriaCertNombre != null && GendarmeriaCertNombre.ElementAt(0) != null)
{
gendarmeria = new List<Guid?>();
gendarmeriaNombre = new List<string>();
foreach (HttpPostedFileBase file in GendarmeriaCertNombre)
{
if (file != null)
{
string filename = Path.GetFileName(file.FileName);
Guid guidnum = _fileStore.SaveUploadedFile(file, "gendarmeria");
gendarmeria.Add(guidnum);
gendarmeriaNombre.Add(file.FileName);
string ruta = _fileStore.GetDiskLocation(guidnum);
byte[] respuesta = cliente.UploadFile("http://localhost/DiplomadoEnMandoPolicial/Account/SubirArchivosRegistro", "POST", ruta);
response = System.Text.Encoding.ASCII.GetString(respuesta);
}
}
if (gendarmeria != null && gendarmeria.Count > 0 && gendarmeriaNombre != null && gendarmeriaNombre.Count > 0)
{
registro.GendarmeriaCertificado = String.Join(",", gendarmeria.Select(t => t.Value.ToString("D")));
registro.GendarmeriaCertNombre = String.Join(",", gendarmeriaNombre);
}
}
if (CursoInacipeCertNombre != null && CursoInacipeCertNombre.ElementAt(0) != null)
{
inacipe = new List<Guid?>();
inacipeNombre = new List<string>();
foreach (HttpPostedFileBase file in CursoInacipeCertNombre)
{
if (file != null)
{
string filename = Path.GetFileName(file.FileName);
Guid guidnum = _fileStore.SaveUploadedFile(file, "inacipe");
inacipe.Add(guidnum);
inacipeNombre.Add(file.FileName);
string ruta = _fileStore.GetDiskLocation(guidnum);
byte[] respuesta = cliente.UploadFile("http://localhost/DiplomadoEnMandoPolicial/Account/SubirArchivosRegistro", "POST", ruta);
response = System.Text.Encoding.ASCII.GetString(respuesta);
}
}
if (inacipe != null && inacipe.Count > 0 && inacipeNombre != null && inacipeNombre.Count > 0)
{
registro.CursoInacipeCertificado = String.Join(",", inacipe.Select(t => t.Value.ToString("D")));
registro.CursoInacipeCertNombre = String.Join(",", inacipeNombre);
}
}
if (CursoCideCertNombre != null && CursoCideCertNombre.ElementAt(0) != null)
{
cide = new List<Guid?>();
cideNombre = new List<string>();
foreach (HttpPostedFileBase file in CursoCideCertNombre)
{
if (file != null)
{
string filename = Path.GetFileName(file.FileName);
Guid guidnum = _fileStore.SaveUploadedFile(file, "cide");
cide.Add(guidnum);
cideNombre.Add(file.FileName);
string ruta = _fileStore.GetDiskLocation(guidnum);
byte[] respuesta = cliente.UploadFile("http://localhost/DiplomadoEnMandoPolicial/Account/SubirArchivosRegistro", "POST", ruta);
response = System.Text.Encoding.ASCII.GetString(respuesta);
}
}
if (cide != null && cide.Count > 0 && cideNombre != null && cideNombre.Count > 0)
{
registro.CursoCideCertificado = String.Join(",", cide.Select(t => t.Value.ToString("D")));
registro.CursoCideCertNombre = String.Join(",", cideNombre);
}
cliente.Dispose();
}
}
Well, that's the problem, I'm open to any suggestions.

Strings and text, and anger

I am trying to find a certain string in a text file, then create a folder based off of what that string says, somewhere along the lines, what I have just stops, it doesn't exception, it doesn't spit out errors, it just stops.
the strings I am trying to find are set up like this:
50.1 : Oxygas ------> = 1
50.2 : laser -------> = 0
etc.
foreach (string file in files)
{
string thepathoflife = Path.GetFullPath(file);
//CreatetheFolder(file)
string filetocopy = file;
object bob = file.Clone();
string bobby = bob.ToString();
string location = file;
bool b = false;
string extension = Path.GetExtension(file);
string thenameofdoom = Path.GetFileNameWithoutExtension(file);
string filename = Path.GetFileName(file);
////bobby.Move(#"\\TEST12CVG\Public\Posts\Temporaryjunk" + filename);
// string oldlocation = filename+extension;
if (extension == ".pst" ||
extension == ".tec" ||
extension == ".pas" ||
extension == ".snc" ||
extension == ".cst" ||
extension == ".xml")
{
b = true;
}
if (thenameofdoom == "Plasma" ||
thenameofdoom == "Oxygas" ||
thenameofdoom == "plasma" ||
thenameofdoom == "oxygas" ||
thenameofdoom == "Oxyfuel" ||
thenameofdoom == "oxyfuel")
{
b = false;
}
if (b == true)
// System.IO.File.WriteAllText(newlocation, bobby);
{
bool plasma = false;
bool oxygas = false;
bool punch = false;
bool laser = false;
var findLevel = 6;
var path = #thepathoflife;
var levels = path.Split(Path.DirectorySeparatorChar);
var second = levels.Length > findLevel ? levels[findLevel] : null;
//this is where the problem starts.
StreamReader s = new StreamReader(#thepathoflife);
StreamReader st = new StreamReader(#thepathoflife);
string currentLine;
string searchString = "50.2 :";
bool foundText = false;
string searchStringab = "= 1";
bool foundTextab = false;
do
{
currentLine = st.ReadLine();
if (currentLine != null)
{
foundText = currentLine.Contains(searchString);
foundTextab = currentLine.Contains(searchStringab);
}
}
while (currentLine != null && !foundText || currentLine != null && !foundTextab);
if (foundText||foundTextab)
{
plasma = true; //do something
}
You opened two StreamReader on same file without closing first one:
StreamReader s = new StreamReader(#thepathoflife);
StreamReader st = new StreamReader(#thepathoflife);
and finally you didn't dispose any of them, use using to prevent such a mistakes:
using(StreamReader st = new StreamReader(#thepathoflife))
{
do stuff;
}
I think you can simplify things with:
foreach (var currentLine in File.ReadLines(thepathoflife))
{
foundText = currentLine.Contains(searchString);
foundTextab = currentLine.Contains(searchStringab);
if (foundText || foundTextab)
break;
}
surround all your code with a try catch block, then spit out the exception to the console (I am assuming you are using a console project)
try{, your code...
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

How to retrieve connectionStrings from Server Explorer

I would like to write an extension to Visual Studio, which will enable me to generate a model for specified table.
I have used the following code to add MyCommand item into context menu of table in server explorer:
Commands2 commands = (Commands2)_applicationObject.Commands;
CommandBar menuBarCommandBar = ((CommandBars)_applicationObject.CommandBars)["Object Node"];
Command command = commands.AddNamedCommand2(_addInInstance, "MyCommand", "MyCommand",
"Executes the command for MyCommand", true, 59, ref contextGUIDS,
(int)vsCommandStatus.vsCommandStatusSupported + (int)vsCommandStatus.vsCommandStatusEnabled,
(int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);
if ((command != null) && (menuBarCommandBar != null))
{
command.AddControl(menuBarCommandBar, 1);
}
To get the name of the selected Table item:
string fileName = "Dafault.cs";
var serverExplorer = _applicationObject.ToolWindows.GetToolWindow("Server Explorer") as UIHierarchy;
if (serverExplorer != null)
{
dynamic item = ((object[])serverExplorer.SelectedItems)[0];
fileName = string.Format("{0}.cs", item.Name);
}
//...
// Generate model based on table from database
//...
_applicationObject.ItemOperations.NewFile("General\\Text File", fileName, Constants.vsViewKindCode);
How can I get information about the database connection?
Brad Larson, why my question was deleted?
Found the solution.
Used this
public static IDbConnection GetConnection(DSRefNavigator navigator, out string type)
{
type = null;
try
{
if (navigator != null)
{
IVsDataConnectionsService dataConnectionsService =
(IVsDataConnectionsService) Package.GetGlobalService(typeof(IVsDataConnectionsService));
string itemName = navigator.GetConnectionName();
if (itemName != null)
{
int iConn; // = dataConnectionsService.GetConnectionIndex(itemName);
DataViewHierarchyAccessor dataViewHierarchy = null;
for(iConn = 0; iConn < dataConnectionsService.Count; iConn++)
{
DataViewHierarchyAccessor hierarchyAccessor =
new DataViewHierarchyAccessor((IVsUIHierarchy) dataConnectionsService.GetConnectionHierarchy(iConn));
try
{
if (hierarchyAccessor.Connection.DisplayConnectionString == itemName)
{
dataViewHierarchy = hierarchyAccessor;
break;
}
}
catch
{
}
}
if (dataViewHierarchy != null)
{
DataConnection connection = dataViewHierarchy.Connection;
if (connection != null && connection.ConnectionSupport.ProviderObject != null)
{
type = connection.ConnectionSupport.ProviderObject.GetType().FullName;
return (IDbConnection) connection.ConnectionSupport.ProviderObject;
}
}
}
}
}
catch
{
}
return null;
}

Categories