Say I have the following expression:
=DateAdd(DateInterval.Year,-1,Today())
Is there a SQL Server web service endpoint that'll allow me to pass in an expression and return the result of the executed expression? I looked through the endpoints listed here but couldn't find one.
Or is there another way to evaluate this expression?
I've found another way to evaluate the expression using VB.net (This assumes that #Wolfgang Kais is correct about VB.net use instead of VBA)
Here is the code snippet:
using System;
using System.CodeDom.Compiler;
using System.Text;
using Microsoft.VisualBasic;
namespace VbStringCompiler
{
internal class Program
{
public static void Main(string[] args)
{
new Program();
}
private const string CRLF = "\r\n";
private Program()
{
var vbCodeProvider = new VBCodeProvider();
var compilerParameters = new CompilerParameters();
compilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll");
compilerParameters.ReferencedAssemblies.Add("System.dll");
compilerParameters.CompilerOptions = "/t:library";
compilerParameters.GenerateInMemory = true;
var stringBuilder = new StringBuilder();
stringBuilder.Append("Imports Microsoft.VisualBasic" + CRLF);
stringBuilder.Append("Imports System" + CRLF + CRLF);
stringBuilder.Append("Namespace Evaluate" + CRLF);
stringBuilder.Append("Class RunTime" + CRLF);
stringBuilder.Append("Public Function Run() As Object" + CRLF);
// insert code to return
stringBuilder.Append("Return DateAdd(DateInterval.Year, -1, Today())" + CRLF);
stringBuilder.Append("End Function" + CRLF);
stringBuilder.Append("End Class" + CRLF);
stringBuilder.Append("End Namespace" + CRLF);
try
{
var compilerResults =
vbCodeProvider.CompileAssemblyFromSource(compilerParameters, stringBuilder.ToString());
if (compilerResults.Errors.Count > 0)
{
foreach (CompilerError compilerError in compilerResults.Errors)
{
Console.Error.WriteLine(compilerError.ToString());
}
return;
}
var instance = compilerResults.CompiledAssembly.CreateInstance("Evaluate.RunTime");
var methodInfo = instance.GetType().GetMethod("Run");
var methodReturn = methodInfo.Invoke(instance, null);
Console.WriteLine(methodReturn);
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
}
}
Related
I have data stored in dockerized Memgraph database. How can I connect from my C# app to the database?
You have to use Neo4j.Driver.Simple package which implements a blocking interface around the 'main' driver.
Once you have the latest version of driver installed you can connect to your database using one of the ways.
First way:
using System;
using System.Linq;
using Neo4j.Driver;
namespace MemgraphApp
{
public class Program
{
public static void Main()
{
string message = "Hello, World!";
using var _driver = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.None);
using var session = _driver.Session();
var greeting = session.WriteTransaction(tx =>
{
var result = tx.Run("CREATE (n:FirstNode) " +
"SET n.message = $message " +
"RETURN 'Node ' + id(n) + ': ' + n.message",
new { message });
return result.Single()[0].As<string>();
});
Console.WriteLine(greeting);
}
}
}
Second way:
using System;
using System.Linq;
using Neo4j.Driver;
namespace MemgraphApp
{
public class Program : IDisposable
{
private readonly IDriver _driver;
public Program(string uri, string user, string password)
{
_driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
}
public void PrintGreeting(string message)
{
using (var session = _driver.Session())
{
var greeting = session.WriteTransaction(tx =>
{
var result = tx.Run("CREATE (n:FirstNode) " +
"SET n.message = $message " +
"RETURN 'Node ' + id(n) + ': ' + n.message",
new { message });
return result.Single()[0].As<string>();
});
Console.WriteLine(greeting);
}
}
public void Dispose()
{
_driver?.Dispose();
}
public static void Main()
{
using (var greeter = new Program("bolt://localhost:7687", "", ""))
{
greeter.PrintGreeting("Hello, World!");
}
}
}
}
Detailed instructions can be found at https://memgraph.com/docs/memgraph/connect-to-memgraph/drivers/c-sharp.
I'm a newbie to SSIS, my current workplace requires that we use SSIS to read from ActiveMQ (hosted service by Amazon) and populate certain SQLServer DB tables.
I've used NiFi to some extent in the past but not SSIS and SSIS 2016 doesn't have an ActiveMQ connectior
After googling around, learnt SSIS-ActiveMQ connection can be achieved using Script component of SSIS.
I can do bit of .net / C# scripting if need be, please advise if theres a template project out there or a how-to-guide to write the Script using NMS .net libraries. Many thanks
After few hours of reading through AMQ documentation, I could do this myself. Below is the complete code which currently works but obviously needs bit of TLC, all suggestions welcome.
using System;
using System.Text;
using System.Data.SqlClient;
using Apache.NMS;
using Serilog;
namespace AMQ_ConsoleApp
{
class Program
{
private const string AMQ_URI = "activemq:ssl://abc.net";
private const string AMQ_Queue = "test";
private const string AMQ_User = "userId";
private const string AMQ_Pwd = "password";
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
)
.WriteTo.File("AMQ_SSIS_Connector.log"
, rollingInterval: RollingInterval.Day
, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
, retainedFileCountLimit:30
)
.CreateLogger();
try
{ Log.Information("#### BEGIN #####");
IConnectionFactory factory = new NMSConnectionFactory(new Uri(AMQ_URI));
IConnection Q_connection = factory.CreateConnection(AMQ_User, AMQ_Pwd);
ISession Q_session = Q_connection.CreateSession();
Log.Debug("Attempting to connect to Queue {Queue}", AMQ_Queue);
Q_connection.Start();
IDestination destination = Q_session.GetQueue(AMQ_Queue);
IMessageConsumer consumer = Q_session.CreateConsumer(destination);
IMessage message;
while (true)
{
Log.Information("______________________________");
Log.Information("Awaiting new message...");
message = consumer.Receive();
if (message != null)
{
ITextMessage textMessage = message as ITextMessage;
if (!string.IsNullOrEmpty(textMessage.Text))
{
Log.Information("Reading message with ID : " + textMessage.NMSMessageId);
WriteToDB(textMessage);
}
}
}
}
catch (Exception ex)
{
Log.Error(ex.ToString());
throw;
}
//ShutDown(Q_session, Q_connection);
}
public static void WriteToDB(ITextMessage msg)
{
try
{
const string SQL_Datasource = "(localdb)\\LocalDBv14";
const string SQL_InitialCatalog = "Customer";
const string SQL_User = "";
const string SQL_User_Pwd = "";
const string SQL_TargetTable = "TableA";
const string SQL_Schema = "dbo";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = SQL_Datasource;
builder.InitialCatalog = SQL_InitialCatalog;
builder.IntegratedSecurity = true; // Disable for Named SQLServer A/c
StringBuilder sb_SQL = new StringBuilder();
sb_SQL.Append("INSERT INTO ");
sb_SQL.Append("[");
sb_SQL.Append(SQL_Schema);//
sb_SQL.Append("].[");
sb_SQL.Append(SQL_TargetTable);//
sb_SQL.Append("] (");
sb_SQL.Append("[" + "MessageID" + "]");//Fields
sb_SQL.Append(",[" + "Message" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_URI" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Queue" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Type" + "]");//Fields
sb_SQL.Append(",[" + "AMQ_Timestamp" + "]");//Fields
sb_SQL.Append(",[" + "RECORD_INSERTED_AT" + "]");//Fields
sb_SQL.Append(",[" + "RECORD_INSERTED_BY" + "]");//Fields
sb_SQL.Append(") VALUES (");
sb_SQL.Append("'" + msg.NMSMessageId + "'");//Data
sb_SQL.Append(",'" + msg.Text + "'");//Data
sb_SQL.Append(",'" + AMQ_URI + "'");//Data
sb_SQL.Append(",'" + msg.NMSDestination.ToString() + "'");//Data
sb_SQL.Append(",'" + msg.NMSType + "'");//Data
sb_SQL.Append("," + msg.NMSTimestamp );//Data
sb_SQL.Append("," + "getdate()" + "");//Data
sb_SQL.Append(",'" + "SSIS_User" + "'");//Data
sb_SQL.Append(")");
// Connect to SQL
Log.Information("Connecting to SQL Server...{Server}", SQL_Datasource);
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
int ret_rows = 0;
Log.Information("Opening DB Connection...{Connection}", SQL_Datasource+"."+SQL_InitialCatalog+"."+SQL_Schema);
connection.Open();
Log.Information("Inserting data into...{Table}", SQL_TargetTable);
using (SqlCommand command = new SqlCommand(sb_SQL.ToString(), connection))
ret_rows = command.ExecuteNonQuery();
if (ret_rows > 0)
{
Log.Information("Data committed to DB successfully, Inserted {records} records." , ret_rows);
//DequeueMessage(msg);
}
else {
Log.Fatal("Data commit to DB Failed.");
}
Log.Information("Closing DB connection...");
connection.Close();
Log.Information("DB Connection closed.");
}
}
catch (SqlException e)
{
Log.Error(e.ToString());
}
}
private static void DequeueMessage(IMessage message)
{
try
{
message.Acknowledge();
Log.Information("Message with ID {msg} de-queued from AMQ.", message.NMSMessageId);
}
catch (Exception ex)
{
Log.Error(ex.ToString());
}
}
private static void ShutDown(ISession session, IConnection connection)
{
Log.Information("Ending AMQ Session");
session.Close();
Log.Information("Closing AMQ Connection");
connection.Close();
}
}
}
i'm trying to connect my unity in sqlite database but i have an error. what does the error means ?
IndexOutOfRangeException: Array index is out of range.
Mono.Data.Sqlite.SqliteDataReader.GetSQLiteType (Int32 i)
Mono.Data.Sqlite.SqliteDataReader.VerifyType (Int32 i, DbType typ)
Mono.Data.Sqlite.SqliteDataReader.GetString (Int32 i)
callOneUser.GetOneUsername () (at Assets/callOneUser.cs:41)
callOneUser.Start () (at Assets/callOneUser.cs:22)
i'm trying to use this code. this is my void Start()
void Start()
{
Connection = "URI=file:" + Application.dataPath + "/English_Booster_Game_DB.s3db"; //Path to database.
GetOneUsername();
}
this is the GetOneUsername() process.
public void GetOneUsername()
{
using (IDbConnection dbConnection = new SqliteConnection(Connection))
{
dbConnection.Open();
using (IDbCommand dbCmd = dbConnection.CreateCommand())
{
string selectoneusername = "select UserData_name from user_data where UserData_status = 1";
dbCmd.CommandText = selectoneusername;
using (IDataReader reader = dbCmd.ExecuteReader())
{
while (reader.Read())
{
name.text = reader.GetString(1);
}
dbConnection.Close();
reader.Close();
}
}
}
}
In your query string, you get one column UserData_name.
string selectoneusername = "select UserData_name from user_data where UserData_status = 1";
It only returns you a column and index in C# start from "Zero". So you should change this line of your script:
name.text = reader.GetString(1);
to:
name.text = reader.GetString(0);
I hope it helps you
Seems, like a very basic thing, but I could not find it.
I have a bunch of log4j/log4net log files. I would like to dump them into a database in order to be able to analyze them with ease.
I thought I would find a tool to do it in no time, apparently I am wrong.
Does anyone know of such a tool?
OK, so I found no utility. Had to write my own. Of course, it is strictly tailored to my immediate needs (time is money), however, it can save you a bit of time to start your own, in case of a need. Here is the complete code in C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication3
{
class Program
{
public class LogEntry
{
private const string PATTERN = #"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{4}) (\S+) \[(\d+)\] (\w+) (\S+) - (.*)$";
private static readonly Regex s_regex = new Regex(PATTERN, RegexOptions.Compiled);
public DateTime TS;
public string Machine;
public int Thread;
public string Level;
public string Logger;
public string Message;
public static LogEntry TryCreate(string line)
{
var match = s_regex.Match(line);
return match.Success ? new LogEntry
{
TS = DateTime.ParseExact(match.Groups[1].Value, "yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture),
Machine = match.Groups[2].Value,
Thread = int.Parse(match.Groups[3].Value),
Level = match.Groups[4].Value,
Logger = match.Groups[5].Value,
Message = match.Groups[6].Value,
} : null;
}
public void AppendToMessage(string line)
{
Message += Environment.NewLine + line;
}
}
static void Main()
{
const string SQL = #"
INSERT INTO log ( ts, machine, thread, level, logger, message, journalId)
VALUES (#ts, #machine, #thread, #level, #logger, #message, #journalId)
";
using (var connection = new SqlConnection("server=localhost;database=misc;uid=SantaClaus;pwd=MerryChristmas"))
{
connection.Open();
using (var command = new SqlCommand(SQL, connection))
{
var tsParam = new SqlParameter("#ts", SqlDbType.DateTime);
var machineParam = new SqlParameter("#machine", SqlDbType.NVarChar, 32);
var threadParam = new SqlParameter("#thread", SqlDbType.Int);
var levelParam = new SqlParameter("#level", SqlDbType.NVarChar, 10);
var loggerParam = new SqlParameter("#logger", SqlDbType.NVarChar, 128);
var messageParam = new SqlParameter("#message", SqlDbType.NVarChar, -1);
var journalIdParam = new SqlParameter("#journalId", SqlDbType.Int);
command.Parameters.Add(tsParam);
command.Parameters.Add(machineParam);
command.Parameters.Add(threadParam);
command.Parameters.Add(levelParam);
command.Parameters.Add(loggerParam);
command.Parameters.Add(messageParam);
command.Parameters.Add(journalIdParam);
// Call Prepare after setting the Commandtext and Parameters.
command.Prepare();
int i = 0;
foreach (var file in Directory.GetFiles(#"c:\tmp\dfbje01"))
{
journalIdParam.Value = OpenJournal(connection, file);
command.Transaction = connection.BeginTransaction();
foreach (var e in GetLogEntries(file))
{
tsParam.Value = e.TS;
machineParam.Value = e.Machine;
threadParam.Value = e.Thread;
levelParam.Value = e.Level;
loggerParam.Value = e.Logger;
messageParam.Value = e.Message;
command.ExecuteNonQuery();
++i;
if (i == 1000)
{
i = 0;
command.Transaction.Commit();
command.Transaction = connection.BeginTransaction();
}
}
command.Transaction.Commit();
CloseJournal(connection, journalIdParam.Value);
}
}
}
}
private static void CloseJournal(SqlConnection connection, object id)
{
const string SQL = "UPDATE journal SET done = 1 WHERE id = #id";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#id", id));
command.ExecuteNonQuery();
}
}
private static object OpenJournal(SqlConnection connection, string filePath)
{
const string SQL = "INSERT INTO journal (filePath) OUTPUT inserted.id VALUES (#filePath)";
using (var command = new SqlCommand(SQL, connection))
{
command.Parameters.Add(new SqlParameter("#filePath", filePath));
return command.ExecuteScalar();
}
}
private static IEnumerable<LogEntry> GetLogEntries(string filePath)
{
LogEntry prev = null;
foreach (var line in File.ReadLines(filePath))
{
var logEntry = LogEntry.TryCreate(line);
if (logEntry != null)
{
if (prev != null)
{
yield return prev;
}
prev = logEntry;
}
else if (prev != null)
{
prev.AppendToMessage(line);
}
else
{
// Oops
Console.WriteLine(line);
}
}
if (prev != null)
{
yield return prev;
}
}
}
}
Mind trying out the filtering, search, colorizing features of the latest developer snapshot of Chainsaw? It has a good number of features which may avoid the need to use a DB. If you use a VFSLogFilePatternReceiver, it can parse and tail any regular text file, including those created by log4net.
Latest developer snapshot of Chainsaw is available here:
http://people.apache.org/~sdeboy
I want to print a report (RDL) directly without previewing it. Is there a solution for this work?
So I think you want to print a Report without Preview so check this out
http://msdn.microsoft.com/en-us/library/ms252091.aspx
in that article youfind following code
using System;
using System.IO;
using System.Data;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Collections.Generic;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
public class Demo : IDisposable
{
private int m_currentPageIndex;
private IList<Stream> m_streams;
private DataTable LoadSalesData()
{
// Create a new DataSet and read sales data file
// data.xml into the first DataTable.
DataSet dataSet = new DataSet();
dataSet.ReadXml(#"..\..\data.xml");
return dataSet.Tables[0];
}
// Routine to provide to the report renderer, in order to
// save an image for each page of the report.
private Stream CreateStream(string name,string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
{
Stream stream = new FileStream(#"..\..\" + name +
"." + fileNameExtension, FileMode.Create);
m_streams.Add(stream);
return stream;
}
// Export the given report as an EMF (Enhanced Metafile) file.
private void Export(LocalReport report)
{
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>EMF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.25in</MarginTop>" +
" <MarginLeft>0.25in</MarginLeft>" +
" <MarginRight>0.25in</MarginRight>" +
" <MarginBottom>0.25in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
m_streams = new List<Stream>();
report.Render("Image", deviceInfo, CreateStream,
out warnings);
foreach (Stream stream in m_streams)
stream.Position = 0;
}
// Handler for PrintPageEvents
private void PrintPage(object sender, PrintPageEventArgs ev)
{
Metafile pageImage = new
Metafile(m_streams[m_currentPageIndex]);
ev.Graphics.DrawImage(pageImage, ev.PageBounds);
m_currentPageIndex++;
ev.HasMorePages = (m_currentPageIndex < m_streams.Count);
}
private void Print()
{
const string printerName =
"Microsoft Office Document Image Writer";
if (m_streams == null || m_streams.Count == 0)
return;
PrintDocument printDoc = new PrintDocument();
printDoc.PrinterSettings.PrinterName = printerName;
if (!printDoc.PrinterSettings.IsValid)
{
string msg = String.Format(
"Can't find printer \"{0}\".", printerName);
MessageBox.Show(msg, "Print Error");
return;
}
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
printDoc.Print();
}
// Create a local report for Report.rdlc, load the data,
// export the report to an .emf file, and print it.
private void Run()
{
LocalReport report = new LocalReport();
report.ReportPath = #"..\..\Report.rdlc";
report.DataSources.Add(
new ReportDataSource("Sales", LoadSalesData()));
Export(report);
m_currentPageIndex = 0;
Print();
}
public void Dispose()
{
if (m_streams != null)
{
foreach (Stream stream in m_streams)
stream.Close();
m_streams = null;
}
}
public static void Main(string[] args)
{
using (Demo demo = new Demo())
{
demo.Run();
}
}
}