how to get sql server instance name currently running programatically - sql-server-express

I was creating connection string for sql express database dynamically.I wanted to know how to get the name of the server instance running currently in the local machine,programatically using c#.

You can use the following code:
using System;
using Microsoft.Win32;
namespace TestConsoleApp
{
class Program
{
static void Main()
{
RegistryKey rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Microsoft SQL Server");
String[] instances = (String[])rk.GetValue("InstalledInstances");
if (instances.Length > 0)
{
foreach (String element in instances)
{
if (element == "MSSQLSERVER")
Console.WriteLine(System.Environment.MachineName);
else
Console.WriteLine(System.Environment.MachineName + #"\" + element);
}
}
Console.ReadKey();
}
}
}
Edit:
If you wish to get the instances that are in running state, please refer to this link: http://support.microsoft.com/kb/q287737/

Related

How to preserve variable value between application starts in ASP.Net Core MVC?

I have an ASP.NET Core MVC application that might be restarted from time to time (maintenance); how can make some variable values persistent from an execution to the next?
PS: That's the code that needs to write value as persistent. For example "LastMaintenanceRestartTime = 03/04-2020", the maintenance restart occurs once a day so the code needs to remember the last time it was restarted.
In UWP, I could do the following code but I can't seem to find an equivalent for ASP.NET Core:
Windows.Storage.ApplicationData.Current.LocalSettings.Values[key] = value;
The best I could find is the following code but the values are only persistent within the same execution:
AppDomain.CurrentDomain.SetData(key, value);
Some talk about "Application.Settings" but I can't seem to be able to reach this namespace...
I've also seen some people talking about "AppSettings" files that can be modified during execution but it seems rather complex to keep a simple value persistent...
Do you have any recommendation, solution or ideas for me?
I found the solution:
static void ReadSetting(string key)
{
try
{
var appSettings = ConfigurationManager.AppSettings;
string result = appSettings[key] ?? "Not Found";
Console.WriteLine(result);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error reading app settings");
}
}
static void AddUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
Link: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.appsettings?redirectedfrom=MSDN&view=dotnet-plat-ext-5.0#System_Configuration_ConfigurationManager_AppSettings
Create a model to save data and last execution time
public class ApplicationData {
public DateTime LastExecutionTime {get;set;}
public string Data {get;set;}
public bool isRunningFirstTime {get;set}
}
1.On first application run, model should be updated to current values and isRunningFirstTime should be set to false.
2. On second run, read or update values based on date and application running count
Expanding on #rashidali answer (and not saying best, but):
public class ApplicationData
{
private DateTime _lastExecutionTime;
public DateTime LastExecutionTime
{
get
{
_lastExecutionTime = (read from file/database);
return _lastExecutionTime;
}
set
{
_lastExecutionTime = value;
(write _lastExecutionTime to file/database);
}
}
public string Data {get;set;}
public bool isRunningFirstTime {get;set}
}

Using both Microsoft.Web.RedisSessionStateProvider and Microsoft.Web.RedisOutputCacheProvider

I have installed and used Microsoft.Web.RedisSessionStateProvider for a while and after looking at OutputCaching I thought of installing Microsoft.Web.RedisOutputCacheProvider as well but they both have Microsoft.Web.Redis.ISerializer interface which breaks my JsonCacheSerializer as it uses the ISerializer interface.
I am getting an error in VS 2017, which reads ...
"The type 'ISerializer' exists in both Microsoft.Web.RedisOutputCacheProvider and Microsoft.Web.RedisSessionStateProvider"
The JsonCacheSerializer code I use for SessionState is :
public class JsonCacheSerializer : Microsoft.Web.Redis.ISerializer
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Error = (serializer, err) => {
err.ErrorContext.Handled = true;
}
};
public byte[] Serialize(object data)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data, Settings));
}
public object Deserialize(byte[] data)
{
return data == null ? null : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(data), Settings);
}
}
Does this mean one has to use one or the other, not both?
You may use extern alias feature of C#
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/extern-alias
Visual Studio example:
1) right click Microsoft.Web.RedisOutputCacheProvider and put following into Aliases field:
global,redisoutputcacheprovider
2) right click Microsoft.Web.RedisSessionStateProvider and put following into Aliases field:
global,redissessionstateprovider
then on top of your code file add:
extern alias redissessionstateprovider;
extern alias redisoutputcacheprovider;
and finally declare your class as:
public class JsonCacheSessionStateSerializer : redissessionstateprovider::Microsoft.Web.Redis.ISerializer

Mono.CSharp: how do I inject a value/entity *into* a script?

Just came across the latest build of Mono.CSharp and love the promise it offers.
Was able to get the following all worked out:
namespace XAct.Spikes.Duo
{
class Program
{
static void Main(string[] args)
{
CompilerSettings compilerSettings = new CompilerSettings();
compilerSettings.LoadDefaultReferences = true;
Report report = new Report(new Mono.CSharp.ConsoleReportPrinter());
Mono.CSharp.Evaluator e;
e= new Evaluator(compilerSettings, report);
//IMPORTANT:This has to be put before you include references to any assemblies
//our you;ll get a stream of errors:
e.Run("using System;");
//IMPORTANT:You have to reference the assemblies your code references...
//...including this one:
e.Run("using XAct.Spikes.Duo;");
//Go crazy -- although that takes time:
//foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
//{
// e.ReferenceAssembly(assembly);
//}
//More appropriate in most cases:
e.ReferenceAssembly((typeof(A).Assembly));
//Exception due to no semicolon
//e.Run("var a = 1+3");
//Doesn't set anything:
//e.Run("a = 1+3;");
//Works:
//e.ReferenceAssembly(typeof(A).Assembly);
e.Run("var a = 1+3;");
e.Run("A x = new A{Name=\"Joe\"};");
var a = e.Evaluate("a;");
var x = e.Evaluate("x;");
//Not extremely useful:
string check = e.GetVars();
//Note that you have to type it:
Console.WriteLine(((A) x).Name);
e = new Evaluator(compilerSettings, report);
var b = e.Evaluate("a;");
}
}
public class A
{
public string Name { get; set; }
}
}
And that was fun...can create a variable in the script's scope, and export the value.
There's just one last thing to figure out... how can I get a value in (eg, a domain entity that I want to apply a Rule script on), without using a static (am thinking of using this in a web app)?
I've seen the use compiled delegates -- but that was for the previous version of Mono.CSharp, and it doesn't seem to work any longer.
Anybody have a suggestion on how to do this with the current version?
Thanks very much.
References:
* Injecting a variable into the Mono.CSharp.Evaluator (runtime compiling a LINQ query from string)
* http://naveensrinivasan.com/tag/mono/
I know it's almost 9 years later, but I think I found a viable solution to inject local variables. It is using a static variable but can still be used by multiple evaluators without collision.
You can use a static Dictionary<string, object> which holds the reference to be injected. Let's say we are doing all this from within our class CsharpConsole:
public class CsharpConsole {
public static Dictionary<string, object> InjectionRepository {get; set; } = new Dictionary<string, object>();
}
The idea is to temporarily place the value in there with a GUID as key so there won't be any conflict between multiple evaluator instances. To inject do this:
public void InjectLocal(string name, object value, string type=null) {
var id = Guid.NewGuid().ToString();
InjectionRepository[id] = value;
type = type ?? value.GetType().FullName;
// note for generic or nested types value.GetType().FullName won't return a compilable type string, so you have to set the type parameter manually
var success = _evaluator.Run($"var {name} = ({type})MyNamespace.CsharpConsole.InjectionRepository[\"{id}\"];");
// clean it up to avoid memory leak
InjectionRepository.Remove(id);
}
Also for accessing local variables there is a workaround using Reflection so you can have a nice [] accessor with get and set:
public object this[string variable]
{
get
{
FieldInfo fieldInfo = typeof(Evaluator).GetField("fields", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo != null)
{
var fields = fieldInfo.GetValue(_evaluator) as Dictionary<string, Tuple<FieldSpec, FieldInfo>>;
if (fields != null)
{
if (fields.TryGetValue(variable, out var tuple) && tuple != null)
{
var value = tuple.Item2.GetValue(_evaluator);
return value;
}
}
}
return null;
}
set
{
InjectLocal(variable, value);
}
}
Using this trick, you can even inject delegates and functions that your evaluated code can call from within the script. For instance, I inject a print function which my code can call to ouput something to the gui console window:
public delegate void PrintFunc(params object[] o);
public void puts(params object[] o)
{
// call the OnPrint event to redirect the output to gui console
if (OnPrint!=null)
OnPrint(string.Join("", o.Select(x => (x ?? "null").ToString() + "\n").ToArray()));
}
This puts function can now be easily injected like this:
InjectLocal("puts", (PrintFunc)puts, "CsInterpreter2.PrintFunc");
And just be called from within your scripts:
puts(new object[] { "hello", "world!" });
Note, there is also a native function print but it directly writes to STDOUT and redirecting individual output from multiple console windows is not possible.

Logging to a local file in Flex

I have my application frontend developed in Flex 3.
For logging, we are using traces and Logger at times yet we dont have a specific way to store logs in a local file of User's machine.
In fact, what I learned from Adobe livedocs is that flashplayer manages itself all logs in flashlog.txt file.
Is there any other way I can maintain a copy of logs? flashlog.txt gets cleared everytime we perform "Logout".
You have not mentioned whether your application is a desktop application, or a browser based.
In case of a desktop application you can write a new class,
import mx.core.mx_internal;
use namespace mx_internal;
public class LoggingFileTarget extends LineFormattedTarget {
private const DEFAULT_LOG_PATH:String = "C:/mylogfile.txt";
private var log:File;
public function LoggingFileTarget(logFile:File = null) {
if(logFile != null) {
log = logFile;
} else {
log = new File(DEFAULT_LOG_PATH);
}
}
public function get logURI():String {
return log.url;
}
mx_internal override function internalLog(message:String):void {
write(message);
}
private function write(msg:String):void {
var fs:FileStream = new FileStream();
try {
fs.open(log, FileMode.APPEND);
fs.writeUTFBytes(msg + "\n");
fs.close();
} catch(e:Error) {
trace("FATAL:: Unable to write to log file.");
}
}
public function clear():void {
var fs:FileStream = new FileStream();
fs.open(log, FileMode.WRITE);
fs.writeUTFBytes("");
fs.close();
}
}
In case of a browser based application, you can keep writing either to an in-memory string, or to a local shared object. Using a shared local object, keep appending to logs, and then collate via a web call.

UDA generating error, insufficient buffer size

I have a UDA in SQL 2005 that keeps generating the below error. I'm guessing this is most likely due to the limitations of the max byte size of 8000....Is there any work around I can use to get around this? Any suggestions for avoiding this limitation in 2005? I know 2008 supposedly took these limitations off but I cannot upgrade for the time being.
A .NET Framework error occurred during execution of user-defined routine or aggregate "CommaListConcatenate":
System.Data.SqlTypes.SqlTypeException: The buffer is insufficient. Read or write operation failed.
System.Data.SqlTypes.SqlTypeException:
at System.Data.SqlTypes.SqlBytes.Write(Int64 offset, Byte[] buffer, Int32 offsetInBuffer, Int32 count)
at System.Data.SqlTypes.StreamOnSqlBytes.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.BinaryWriter.Write(String value)
at TASQLCLR.CommaListConcatenate.Write(BinaryWriter w)
For SQL 2005 you can solve the 8000 byte limit by turning one parameter into multiple parameters by using a delimiter. I didn't need to go into the details myself, but you can find the answer here: http://www.mssqltips.com/tip.asp?tip=2043
For SQL 2008 you need to pass MaxByteSize as -1. If you try and pass a number greater than 8000, SQL will not let you create the aggregate, complaining that there is an 8000 byte limit. If you pass in -1, it seems to get around this issue and lets you create the aggregate (which I have also tested with > 8000 bytes).
The error is:
The size (100000) for
"Class.Concatenate" is not in the
valid range. Size must be -1 or a
number between 1 and 8000.
Here is the working class definition for VB.NET to support > 8000 bytes in SQL 2008.
<Serializable(), SqlUserDefinedAggregate(Format.UserDefined,
IsInvariantToNulls:=True,
IsInvariantToDuplicates:=False,
IsInvariantToOrder:=False, MaxByteSize:=-1)>
<System.Runtime.InteropServices.ComVisible(False)> _
Public Class Concatenate Implements IBinarySerialize
End Class
The code below shows how to calculate the media of a set of decimal numbers within an SQLAggregate. It resolves the issue of size parameter limitation implementing a data dictionary. The idea is taken from Expert SQL Express 2005.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using SafeDictionary;
[Microsoft.SqlServer.Server.SqlUserDefinedAggregate(
Format.UserDefined, MaxByteSize=16)]
public struct CMedian2 : IBinarySerialize
{
readonly static SafeDictionary<Guid , List<String>> theLists = new SafeDictionary<Guid , List<String>>();
private List<String> theStrings;
//Make sure to use SqlChars if you use
//VS deployment!
public SqlString Terminate()
{
List<Decimal> ld = new List<Decimal>();
foreach(String s in theStrings){
ld.Add(Convert.ToDecimal(s));
}
Decimal median;
Decimal tmp;
int halfIndex;
int numberCount;
ld.Sort();
Decimal[] allvalues = ld.ToArray();
numberCount = allvalues.Count();
if ((numberCount % 2) == 0)
{
halfIndex = (numberCount) / 2;
tmp = Decimal.Add(allvalues[halfIndex-1], allvalues[halfIndex]);
median = Decimal.Divide(tmp,2);
}
else
{
halfIndex = (numberCount + 1) / 2;
median = allvalues[halfIndex - 1];
tmp = 1;
}
return new SqlString(Convert.ToString(median));
}
public void Init()
{
theStrings = new List<String>();
}
public void Accumulate(SqlString Value)
{
if (!(Value.IsNull))
theStrings.Add(Value.Value);
}
public void Merge(CMedian2 Group)
{
foreach (String theString in Group.theStrings)
this.theStrings.Add(theString);
}
public void Write(System.IO.BinaryWriter w)
{
Guid g = Guid.NewGuid();
try
{
//Add the local collection to the static dictionary
theLists.Add(g, this.theStrings);
//Persist the GUID
w.Write(g.ToByteArray());
}
catch
{
//Try to clean up in case of exception
if (theLists.ContainsKey(g))
theLists.Remove(g);
}
}
public void Read(System.IO.BinaryReader r)
{
//Get the GUID from the stream
Guid g = new Guid(r.ReadBytes(16));
try
{
//Grab the collection of strings
this.theStrings = theLists[g];
}
finally
{
//Clean up
theLists.Remove(g);
}
}
}
you also need to implement the dictionary as Expert 2005 does:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace SafeDictionary
{
public class SafeDictionary<K, V>
{
private readonly Dictionary<K, V> dict = new Dictionary<K,V>();
private readonly ReaderWriterLock theLock = new ReaderWriterLock();
public void Add(K key, V value)
{
theLock.AcquireWriterLock(2000);
try
{
dict.Add(key, value);
}
finally
{
theLock.ReleaseLock();
}
}
public V this[K key]
{
get
{
theLock.AcquireReaderLock(2000);
try
{
return (this.dict[key]);
}
finally
{
theLock.ReleaseLock();
}
}
set
{
theLock.AcquireWriterLock(2000);
try
{
dict[key] = value;
}
finally
{
theLock.ReleaseLock();
}
}
}
public bool Remove(K key)
{
theLock.AcquireWriterLock(2000);
try
{
return (dict.Remove(key));
}
finally
{
theLock.ReleaseLock();
}
}
public bool ContainsKey(K key)
{
theLock.AcquireReaderLock(2000);
try
{
return (dict.ContainsKey(key));
}
finally
{
theLock.ReleaseLock();
}
}
}
}
The dictionary must be deployed in a separate assembly with unsafe code grants. The idea is to avoid to serializate all the numbers by keeping in memory data structure dictionary. I recommend the Expert SQL 2005 chapter:
CHAPTER 6 ■ SQLCLR: ARCHITECTURE AND
DESIGN CONSIDERATIONS.
By the way, this solution didn't work for me. Too many conversions from Decimal to String and viceversa make it slow when working with millions of rows, anyway, I enjoyed to try it. For other usages it is a good pattern.