because of having always open Oracle connections and want to track them down using performance counters. Because of missing admin rights I can't use the perfmon.
I googled and just found 1 promissing example but I can't manage to get it running and would really appreciate your help!
the performance Monitoring class (pmc) looks like this:
List<PerformanceCounter> lstPerfCounters = new List<PerformanceCounter>();
public virtual void InitializeCounters(string AppInstanceName, Type PerfCountersList)
{
foreach (string counterName in Enum.GetNames(PerfCountersList))
{
PerformanceCounter PerfCounter = new PerformanceCounter();
PerfCounter.CategoryName = ".NET Data Provider for SqlServer";
PerfCounter.CounterName = counterName;
PerfCounter.InstanceName = AppInstanceName;
lstPerfCounters.Add(PerfCounter);
}
}
public virtual void PrintCounters()
{
foreach (PerformanceCounter p in lstPerfCounters)
{
Console.WriteLine("{0} = {1}", p.CounterName, p.NextValue());
}
Console.WriteLine("****************************************************************");
}
and has those enums:
public enum DBPerformanceCounters
{
NumberOfActiveConnectionPools,
NumberOfActiveConnections,
NumberOfFreeConnections,
NumberOfNonPooledConnections,
NumberOfPooledConnections,
SoftDisconnectsPerSecond,
SoftConnectsPerSecond,
NumberOfReclaimedConnections,
HardConnectsPerSecond,
HardDisconnectsPerSecond,
NumberOfActiveConnectionPoolGroups,
NumberOfInactiveConnectionPoolGroups,
NumberOfInactiveConnectionPools,
NumberOfStasisConnections
}
When starting my Programm I wanted to initialise it with the code given
PMC pc = new PMC();
string InstanceName = "myProgram";
pc.InitializeCounters(InstanceName, typeof(CountersList.DBPerformanceCounters));
pc.PrintCounters();
and here is the problem: the ide tells me, that CountersList doesn't exist. If I create a List for the DBPerformanceCounter manually, I get told that it is a varibale that is used like a type.
I'm sure its just a small bug, but I'm clueless and would really appreciate your help!
Thanks in advance.
*Earased some typos.
Related
I have a C# program (actually it's just a C# library that is being used by NUnit) that I wish to modify slightly which is based off of this article: How to Programmatically move items in outlook. I'm currently faced with a folder that has bout 3500 messages all around 350kb and is taking FOREVER to move to my archive so I can send and receive emails again (since my inbox is currently at 1.5Gb out of 500Mb... lol) but for the life of me I can't figure out how to get my archive folder. I'm a little bit multitasking since I'm at work so I can edit as I go. So if you have any code readily available that finds the archive folder that would be great. Thank you
EDIT
ok to show that I do have some work in progress (based on negative feedback) here is the code I have in place right now (since yes I know I have a give me teh codez)
here is my NUnit test case that looks at a folder and gives me specific information
[Test]
public void CheckMessages()
{
List<EmailMessage> messages = new List<EmailMessage>();
using (var target = new EmailMessageProvider())
{
messages.AddRange(target.GetEmailMessages("UnexpectedErrors\\NotFindImage"));
}
Dictionary<int, string> asdf = new Dictionary<int, string>();
foreach (var item in messages)
{
var line = item.Body.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[2];
var revisionId = int.Parse(Regex.Match(line, #"\-*\d+").Value);
var path = line.Substring(line.IndexOf("\\\\"));
if (asdf.ContainsKey(revisionId))
{
Assert.That(path, Is.EqualTo(asdf[revisionId]));
}
else
{
asdf.Add(revisionId, path);
}
}
foreach (var item in asdf.OrderBy(x => x.Key))
{
Console.WriteLine($"{item.Key} {item.Value}");
}
}
I use the same class to find messages (in another test) and move it to that subfolder which that test is using.
here is the code I have that does the moving
public void MoveSurveyPrintComponentsNotFound()
{
var destination = _baseFolder.Folders["UnexpectedErrors"].Folders["NotFindImage"];
foreach (var mailItem in _baseFolder.Folders["UnexpectedErrors"].Items.OfType<MailItem>())
{
mailItem.UseMailItem(x =>
{
if (x.Body.Contains("Foobar.Common.Exceptions.ImageNotFound"))
x.Move(destination);
});
}
}
EDIT 2
looks like I may have just about got it. I found that in the MAPI Namspace one of the subfolders is Archives. I'm going to try to change a few of the variables and see if it moves. Problem is just checking one folder takes over 31 seconds. oh well. better than never.
I figured it out. It wasn't as hard as I had thought either so I'll share what i have just incase someone else has this problem. In my program I did 2 things. One was to set _basefolder as my default email address's Folder. Second was to to set _mapi to the Outlook.GetNamespace("MAPI"). Those two thinsg I already had in my constructor.
private readonly OutlookApplication _outlook;
private readonly NameSpace _mapi;
private MAPIFolder _baseFolder;
public EmailMessageProvider()
{
_outlook = new OutlookApplication();
_mapi = _outlook.GetNamespace("MAPI");
_baseFolder = _mapi.Folders["robert#defaultEmail.com"];
}
Archives works just like any other MAPIFolder so it's just a matter of getting said folder. For me it was in _mapi.Folders["Archive"]. I would imagine this is fairly standard so if you copy and paste it should work just fine.
So now to list out all of my emails I want to go through and move tham appropriatly.
public void MoveSpecificEmailsToArchives()
{
var destination = _mapi.Folders["Archives"];
foreach (var mailItem in _baseFolder.Folders["Unexpected Error"].Items.OfType<MailItem>())
{
mailItem.UseMailItem(x =>
{
if (x.Body.Contains("offensiveProgram.exe ERROR "))
x.Move(destination);
});
}
Release(destination);
}
fyi the UseMailItem is an extension method. Looks like this
public static void UseMailItem(this MailItem item, Action<MailItem> mailItemAction)
{
mailItemAction(item);
Marshal.ReleaseComObject(item);
}
how can i use System.Data.Sql.SqlDataSourceEnumerator class to know about available sql datasources...?
because while i am creating connection to sql server if sql server is not ready we will get exception… so first i want to know is sql server is ready to accept request or not… how to know it….
So, according to the following references:
http://social.msdn.microsoft.com/forums/en-US/sqlsmoanddmo/thread/49ba019f-e8b5-457c-80ea-fac5febb9d3d/
http://connect.microsoft.com/SQLServer/feedback/details/146323/enumavailablesqlservers-or-sqldatasourceenumerator-incorrect-list-of-available-databases
http://blogs.msdn.com/b/sushilc/archive/2004/10/14/242395.aspx
http://sqlblogcasts.com/blogs/jonsayce/archive/2008/02/10/programatically-listing-sql-servers.aspx
GetDataSources() is not a perfect method, meaning, it may not list all the available data sources on first try. In fact, I found that it also does not list all of your local sources.
For my purposes, I had some time between when the program started and when I needed to get the list of available sources, both on the network AND local. So, I put the code in a thread that goes on forever collecting all the sources. Here it is below. If you take out the while loop, you can call it manually as many times as you'd like.
private List<string> sqlInstances = new List<string>();
private void collectInstances()
{
while (true)
{
System.Data.Sql.SqlDataSourceEnumerator instance = System.Data.Sql.SqlDataSourceEnumerator.Instance;
System.Data.DataTable dataTable = instance.GetDataSources();
foreach (DataRow row in dataTable.Rows)
{
string instanceName = String.Format(#"{0}\{1}", row["ServerName"].ToString(), row["InstanceName"].ToString());
//Do not add the local instance, we will add it in the next section. Otherwise, duplicated!
if (!sqlInstances.Contains(instanceName) && !instanceName.Contains(Environment.MachineName))
{
sqlInstances.Add(instanceName);
}
}
/*
* For some reason, GetDataSources() does not get local instances. So using code from here to get them
* http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
*/
List<string> lclInstances = GetLocalSqlServerInstanceNames();
foreach (var lclInstance in lclInstances)
{
string instanceName = String.Format(#"{0}\{1}", Environment.MachineName, lclInstance);
if (!sqlInstances.Contains(instanceName)) sqlInstances.Add(instanceName);
}
sqlInstances.Sort();
}
}
//Got code from: http://stackoverflow.com/questions/6824188/sqldatasourceenumerator-instance-getdatasources-does-not-locate-local-sql-serv
/// <summary>
/// get local sql server instance names from registry, search both WOW64 and WOW3264 hives
/// </summary>
/// <returns>a list of local sql server instance names</returns>
public static List<string> GetLocalSqlServerInstanceNames()
{
RegistryValueDataReader registryValueDataReader = new RegistryValueDataReader();
string[] instances64Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow64,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
string[] instances32Bit = registryValueDataReader.ReadRegistryValueData(RegistryHive.Wow6432,
Registry.LocalMachine,
#"SOFTWARE\Microsoft\Microsoft SQL Server",
"InstalledInstances");
//FormatLocalSqlInstanceNames(ref instances64Bit);
//FormatLocalSqlInstanceNames(ref instances32Bit);
List<string> localInstanceNames = new List<string>(instances64Bit);
foreach (var item in instances32Bit)
{
if (!localInstanceNames.Contains(item)) localInstanceNames.Add(item);
}
//localInstanceNames = localInstanceNames.Union(instances32Bit).ToList();
return localInstanceNames;
}
GetDataSources() may help you, have you tried it?
SqlDataSourceEnumerator.GetDataSources Method
Currently SqlDataSourceEnumerator isn't available in .NetCore or .Net5 either and
whilst not a direct replacement for SqlDataSourceEnumerator you could try a Udp solution.
This repo is targetted at .Net5, but the code should work just fine on .NetCore flavours.
https://github.com/mrsquish/SqlBrowserClient
Ok, so I have the following class library, which I wrote in C#:
public class Program
{
public void GetProductID(string location, out string productId)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product");
ManagementObjectCollection collection = searcher.Get();
var item = new Win32Product();
//var crap = (collection as IEnumerable<ManagementObject>).Where(o => o["InstallLocation"].ToString().StartsWith(location));
foreach (ManagementObject obj in collection)
{
try
{
item = new Win32Product();
item.IdentifyingNumber = (string)obj["IdentifyingNumber"];
item.InstallLocation = (string)obj["InstallLocation"];
item.Name = (string)obj["Name"];
}
catch
{ } //shut up. I know it's an empty catch block. Its fine.
//If there are exceptions thrown, I don't want the data, I just
//want to keep running.
}
productId = item.ProductID.ToString();
}
}
public class Win32Product
{
//properties
}
Not a lot to it, GetProductId() just searches for any installed programs below a given directory. It works fine if I test it elsewhere, but when running from installshield (as a control event), it fails (return value 3).
Kind of a vague question, I guess, but any idea why GetProductInfo() would be failing coming from installshield?
Here's some reading material for you:
Deployment Tools Foundation (DTF) Managed Custom Actions
Reasons DTF is Better
BTW, the Win32_Product class is a POS. It does a very poor job of wrapping the underlying MSI API. When you switch to DTF, use the ProductInstallation::GetProducts method instead. It does a much better job of calling MsiEnumProductsEx.
I have a couple of load balanced application server running on IIS 7. I need to check how many webservice calls are made from each of the server. I also need to check this at a particular instance. Do we have some thing in .net which communicates with both the server and gives me the snapshot at a particular instance.
Thanks
You could use Perfmon to add statistics regarding the number of calls. Once you're doing that you could also add timing data as well... You can then use Perfmon on the local box or hook up to it remotely with any number of tools.
Sorry I can't point you to specifics -- I've only seen it done, not done it myself :) But I think it is pretty straightforward.
And some sample code, showing how you could implement performance counters:
using System;
using System.Configuration;
using System.Diagnostics;
namespace TEST
{
// sample implementation
public static class PerformanceHelper
{
// update a performance counter value
public static void UpdateCounter(string WebMethodName, int count)
{
// to be able to turn the monitoring on or off
if (ConfigurationManager.AppSettings["PerformanceMonitor"].ToUpper() == "TRUE")
{
PerformanceCounter counter;
if (!PerformanceCounterCategory.Exists("SAMPLE"))
{
CounterCreationDataCollection listCounters = new CounterCreationDataCollection();
CounterCreationData newCounter = new CounterCreationData(WebMethodName, WebMethodName, PerformanceCounterType.NumberOfItems64);
listCounters.Add(newCounter);
PerformanceCounterCategory.Create("SAMPLE", "DESCRIPTION", new PerformanceCounterCategoryType(), listCounters);
}
else
{
if (!PerformanceCounterCategory.CounterExists(WebMethodName, "SAMPLE"))
{
CounterCreationDataCollection rebuildCounterList = new CounterCreationDataCollection();
CounterCreationData newCounter = new CounterCreationData(WebMethodName, WebMethodName, PerformanceCounterType.NumberOfItems64);
rebuildCounterList.Add(newCounter);
PerformanceCounterCategory category = new PerformanceCounterCategory("SAMPLE");
foreach (var item in category.GetCounters())
{
CounterCreationData existingCounter = new CounterCreationData(item.CounterName, item.CounterName, item.CounterType);
rebuildCounterList.Add(existingCounter);
}
PerformanceCounterCategory.Delete("SAMPLE");
PerformanceCounterCategory.Create("SAMPLE", "DESCRIPTION", new PerformanceCounterCategoryType(), rebuildCounterList);
}
}
counter = new PerformanceCounter("SAMPLE", WebMethodName, false);
if (count == -1)
counter.IncrementBy(-1);
else
counter.IncrementBy(count);
}
}
}
}
I'm using fluent migrator to manage my database migrations, but what I'd like to do is have the migrations run at app start. The closest I have managed is this:
public static void MigrateToLatest(string connectionString)
{
using (var announcer = new TextWriterAnnouncer(Console.Out)
{
ShowElapsedTime = true,
ShowSql = true
})
{
var assembly = typeof(Runner).Assembly.GetName().Name;
var migrationContext = new RunnerContext(announcer)
{
Connection = connectionString,
Database = "SqlServer2008",
Target = assembly
};
var executor = new TaskExecutor(migrationContext);
executor.Execute();
}
}
I'm sure I had this working, but I've not looked at it for sometime (hobby project) and it's now throwing null reference exceptions when it gets to the Execute line. Sadly there are no docs for this and I've been banging my head on it for ages.
Has anyone managed to get this kind of thing working with FluentMigrator?
PM> Install-Package FluentMigrator.Tools
Manually add a reference to:
packages\FluentMigrator.Tools.1.6.1\tools\AnyCPU\40\FluentMigrator.Runner.dll
Note that the folder name will vary on version number, this illustration uses the current 1.6.1 release. If you need the .NET 3.5 runner use the \35\ directory.
public static class Runner
{
public class MigrationOptions : IMigrationProcessorOptions
{
public bool PreviewOnly { get; set; }
public string ProviderSwitches { get; set; }
public int Timeout { get; set; }
}
public static void MigrateToLatest(string connectionString)
{
// var announcer = new NullAnnouncer();
var announcer = new TextWriterAnnouncer(s => System.Diagnostics.Debug.WriteLine(s));
var assembly = Assembly.GetExecutingAssembly();
var migrationContext = new RunnerContext(announcer)
{
Namespace = "MyApp.Sql.Migrations"
};
var options = new MigrationOptions { PreviewOnly=false, Timeout=60 };
var factory =
new FluentMigrator.Runner.Processors.SqlServer.SqlServer2008ProcessorFactory();
using (var processor = factory.Create(connectionString, announcer, options))
{
var runner = new MigrationRunner(assembly, migrationContext, processor);
runner.MigrateUp(true);
}
}
}
Note the SqlServer2008ProcessorFactory this is configurable dependent upon your database, there is support for: 2000, 2005, 2008, 2012, and 2014.
I have actually accomplished running migrations in the application_start however it is hard to tell from that code what could be wrong... Since it is open source I would just grab the code and pull it into your solution and build it to find out what the Execute method is complaining about. I found that the source code for Fluent Migrator is organized pretty well.
One thing that you might have to be concerned about if this is a web app is making sure that no one uses the database while you are migrating. I used a strategy of establishing a connection, setting the database to single user mode, running the migrations, setting the database to multi user mode, then closing the connection. This also handles the scenario of a load balanced web application on multiple servers so 2 servers don't try to run migrations against the same database.