How can I connect to Memgraph from my C# application? - graph-databases

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.

Related

SQL Server Reporting Services - Report Expressions Execution

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

Can't get Novell.Directory.Ldap.NETStandard library to query

I need to let the user query an Active Directory for names in .Net Core.
So I am building an Active Directory Search Web API Service.
I am able to connect with the bind statement.
But I am not able to get any results back with my query although there is no error.
Another programmer sent me some code he uses in other applications. But it uses the DirectoryEntry object which is not available in .Net Core.
So I am trying to use the Novell.Directory.Ldap.NetStandard library.
Here is the code the other developer sent me:
public static List<UserProfileModel> GetADUsers(string alias)
{
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
// Ad path LDAP://ourOrg.gov/CN=Users,DC=ourOrg,DC=gov
DirectoryEntry de2 = new DirectoryEntry(ConfigurationManager.AppSettings["AD_Path"], ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Password"]);
de2.Path = ConfigurationManager.AppSettings["AD_Path"];
de2.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de2;
deSearch.Filter = "(samaccountname=*" + alias + "*)";
LOGGER.Debug(String.Format("Active Directory Search Filter {0}", deSearch.Filter));
SearchResultCollection results = deSearch.FindAll();
String raw = "";
LOGGER.Debug(String.Format("Active Directory Search Result Counts {0}", results.Count));
if (results.Count > 0)
{
foreach (SearchResult item in results)
{
UserProfileModel userProfileModel = new UserProfileModel();
userProfileModel.Name = GetADProperty("name", item);
userProfileModel.email = GetADProperty("mail", item);
userProfileModel.identity = GetADProperty("userPrincipalName", item);
userProfileModel.first_name = GetADProperty("givenName", item);
userProfileModel.last_name = GetADProperty("sn", item);
users.Add(userProfileModel);
raw = String.Format("{0}/n{1}", raw, userProfileModel.ToString());
}
LOGGER.Debug(String.Format("Active Directory Search Resuts ToString: {0}", raw));
}
}
catch (Exception e)
{
LOGGER.Error("Unable to Query Active Directory", e);
}
return users;
}
I need to translate this into Novell's LDAP library.
Here is my attempt:
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = "ourOrg.gov";
string loginDn = #"ourOrg\myName";
string password = "myPass";
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchResults results = con.Search(
"cn=users,dc=ourOrg,dc=gov",
LdapConnection.SCOPE_ONE,
"samaccountname=*",
null,
false);
// NO RESULTS:(
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
I don't get an error.
But there are 0 results.
I originally had this part:
"samaccountname=*",
like:
"samaccountname={alias}",
but I'm just trying to get back results at this point.
I got this working:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Hrsa.Core.Web.App.Models.ViewModels;
using Novell.Directory.Ldap;
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Hrsa.Core.Web.App.Controllers.Api
{
[Route("api/[controller]")]
public class ActiveDirectoryController : Controller
{
private readonly AppSettings _appSettings;
public ActiveDirectoryController(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
[HttpGet]
public async Task<List<UserProfileModel>> GetByName(string alias)
{
int ldapPort = LdapConnection.DEFAULT_PORT;
string ldapHost = _appSettings.HrsaLdapHost; // ourOrgName.gov
string loginDn = _appSettings.AdUser;
string password = _appSettings.AdPassword;
string searchBase = _appSettings.HrsaAdSearchBase;
string searchFilter = $"(samaccountname=*{alias}*)";
string[] attributes = new string[] { "cn", "userPrincipalName", "st", "givenname", "samaccountname",
"description", "telephonenumber", "department", "displayname", "name", "mail", "givenName", "sn" };
List<UserProfileModel> users = new List<UserProfileModel>();
if (alias == null || alias.Trim().Equals(""))
{
return users;
}
try
{
using (var con = new LdapConnection())
{
con.Connect(ldapHost, ldapPort);
con.Bind(loginDn, password);
LdapSearchQueue queue = con.Search(
searchBase,
LdapConnection.SCOPE_SUB,
searchFilter,
attributes,
false,
(LdapSearchQueue)null,
(LdapSearchConstraints)null);
LdapMessage message;
while ((message = queue.getResponse()) != null)
{
if (message is LdapSearchResult)
{
LdapEntry entry = ((LdapSearchResult)message).Entry;
LdapAttributeSet attributeSet = entry.getAttributeSet();
users.Add(new UserProfileModel
{
Cn = attributeSet.getAttribute("cn")?.StringValue,
UserPrincipalName = attributeSet.getAttribute("userPrincipalName")?.StringValue,
St = attributeSet.getAttribute("st")?.StringValue,
Givenname = attributeSet.getAttribute("givenname")?.StringValue,
Samaccountname = attributeSet.getAttribute("samaccountname")?.StringValue,
Description = attributeSet.getAttribute("description")?.StringValue,
Telephonenumber = attributeSet.getAttribute("telephonenumber")?.StringValue,
Department = attributeSet.getAttribute("department")?.StringValue,
Displayname = attributeSet.getAttribute("displayname")?.StringValue,
Name = attributeSet.getAttribute("name")?.StringValue,
Mail = attributeSet.getAttribute("mail")?.StringValue,
GivenName = attributeSet.getAttribute("givenName")?.StringValue,
Sn = attributeSet.getAttribute("sn")?.StringValue
});
}
}
}
return users;
}
catch(Exception ex)
{
throw ex;
}
}
}
}

How to generate report (Extent Report) in Specflow Project

Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But these steps are getting unreachable. Can anyone please guide me how i can design my flow and how i can integrate with the feature file?
Please find the below BaseReport.cs file and my Step definition file.
namespace Verivox.CommonLib
{
public class BaseReport
{
public static ExtentReports extent;
public static ExtentTest test;
[BeforeFeature()]
public static void BasicSetUp()
{
//string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
extent = new ExtentReports(reportPath, true);
extent.LoadConfig(projectPath + "CommonLib\\Extent-config.xml");
}
[BeforeScenario()]
public static void BeforeScenarioSetUp()
{
test = extent.StartTest("Running Scenario -->" + ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario()]
public static void AfterScnario()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.EndTest(test);
}
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
// extent.Close();
}
}
}
Steps
namespace Verivox.Steps
{
[Binding]
class CalculationVerificationSteps
{
[Given(#"I have navigate to Home Page")]
public void GivenIHaveNavigateToHomePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseUrl"]);
PropertyCollection.currentPage = new HomePage();
Browser.Current.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[Given(#"Navigate to Mobile Calculator under All Comparison Section")]
public void GivenNavigateToMobileCalculatorUnderAllComparisonSection()
{
PropertyCollection.currentPage.As<HomePage>().MainCompItemClick("Telekommunikation");
PropertyCollection.currentPage.As<HomePage>().SubCompItemClick("Mobilfunk");
PropertyCollection.currentPage.As<HomePage>().CalculatorLinkClick("Mobiles Internet");
}
[Then(#"Mobile Calculator should appear")]
public void ThenMobileCalculatorShouldAppear()
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().IsMobileInternetCalcExistance());
}
[Then(#"(.*) option and (.*) option is selected by default\.")]
public void ThenMonatsflatrateOptionAndSIMOptionIsSelectedByDefault_(string defaultTarif, string hardware)
{
try
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().VerifyMobiIntSelectedItem(defaultTarif));
string colorCode = PropertyCollection.currentPage.As<HomePage>().VerifySelectedHardWare();
Assert.AreEqual(0, string.Compare("rgba(253, 138, 2, 1)", colorCode, StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
BaseReport.test.Log(LogStatus.Fail, "Default selections are incorrect.");
}
}
You are missing the Binding- attribute on the BaseReport class. Without that, the hooks defined there are not called.

SSRS ListRenderingExtension Unauthorised Exception

I am currently using Report Viewer 11 to connect to a SQL Server 2008 r2 SSRS endpoint in order to run reports within a web page. Previously this was all working when SSRS and the DB were running on the same virtual server.
We just moved the DB and SSRS off the web server onto a new virtual instance and I am getting an 401 - Unauthorised Exception back when running the ServerReport.ListRenderingExtensions() method but calling the report parameters list using ServerReport.GetParameters() works without issue.
Below is the class that I am using to load the reports and I am populating the CustomReportCredentials with the admin username and password and the Domain is populated with the name of the new DB/SSRS server.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Web.UI;
using Microsoft.Reporting.WebForms;
using System.Reflection;
public partial class ReportViewer : Page
{
private string ReportingServer = ConfigurationManager.AppSettings["ReportViewerEndpoint"];
private string UserName = ConfigurationManager.AppSettings["ReportViewerUser"];
private string Password = ConfigurationManager.AppSettings["ReportViewerPassword"];
private string Domain = ConfigurationManager.AppSettings["ReportViewerDomain"];
protected void Page_Load(object sender, EventArgs e)
{
ssrsReportViewer.ServerReport.ReportServerUrl = new Uri(ReportingServer);
if (!IsPostBack)
{
DisableUnwantedExportFormat();
IReportServerCredentials irsc = new CustomReportCredentials(UserName, Password, Domain);
ssrsReportViewer.ServerReport.ReportServerCredentials = irsc;
SetReportPath();
SetParameters();
}
}
private void SetReportPath()
{
if (Request.QueryString["Path"] != null)
ssrsReportViewer.ServerReport.ReportPath = Request.QueryString["Path"];
}
private void SetParameters()
{
if (!string.IsNullOrWhiteSpace(ssrsReportViewer.ServerReport.ReportPath))
{
List<string> filters = new List<string>();
List<ReportParameterInfo> reportParameters = ssrsReportViewer.ServerReport.GetParameters().ToList();
foreach (ReportParameterInfo param in reportParameters.Where(w => w.Nullable.Equals(true)))
ssrsReportViewer.ServerReport.SetParameters(new ReportParameter(param.Name, new string[] { null }, false));
foreach (string key in Request.QueryString)
{
string values = Request.QueryString[key];
if (reportParameters.Any(r => r.Name.Equals(key)))
{
ssrsReportViewer.ServerReport.SetParameters(new ReportParameter(key, values));
filters.Add(string.Format("{0} - {1}", key.ToUpper(CultureInfo.InvariantCulture), values));
}
}
if (reportParameters.Any(r => r.Name.Equals("Filters")))
ssrsReportViewer.ServerReport.SetParameters(new ReportParameter("Filters", string.Join("; ", filters)));
}
}
private void DisableUnwantedExportFormat()
{
FieldInfo info;
string[] removeFormats;
string exclusionsUrl = Request.QueryString["ExcludedExports"];
if (!string.IsNullOrWhiteSpace(exclusionsUrl))
{
removeFormats = exclusionsUrl.Split(',');
foreach (RenderingExtension extension in ssrsReportViewer.ServerReport.ListRenderingExtensions())
{
foreach(string format in removeFormats )
{
if (extension.Name.ToUpper().Equals(format.ToUpper()))
{
info = extension.GetType().GetField("m_isVisible", BindingFlags.Instance | BindingFlags.NonPublic);
info.SetValue(extension, false);
}
}
}
}
}
}
public class CustomReportCredentials : IReportServerCredentials
{
private readonly string userName;
private readonly string passWord;
private readonly string domainName;
public CustomReportCredentials(string userName, string passWord, string domainName)
{
this.userName = userName;
this.passWord = passWord;
this.domainName = domainName;
}
public WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get { return new NetworkCredential(userName, passWord, domainName); }
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}
Any idea why I am getting this 401 - Unauthorised exception back from the ServerReport.ListRenderingExtensions() method?
You are setting the credentials after calling:
DisableUnwantedExportFormat();
Change the code so that the credentials are set first:
IReportServerCredentials irsc = new CustomReportCredentials(UserName, Password, Domain);
ssrsReportViewer.ServerReport.ReportServerCredentials = irsc;
DisableUnwantedExportFormat();
SetReportPath();
SetParameters();

Is there a way for printing a report without previewing it on report viewer?

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();
}
}
}

Resources