Getting wrong file path when generating file route in C# Console App - c#

I'm trying to read in a SQL script in a C# console app. I'm having issues as the file route that it's generating always starts in the bin folder of the project.
public static void ApiResources(IConfiguration config, string testUrlExtension)
{
try
{
var azureDatabaseUrl = String.Format(config["SqlDatabase:BaseUrl"], $"test{testUrlExtension}");
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.DataSource = azureDatabaseUrl;
connBuilder.UserID = config["SqlDatabase:ZupaKeyReleaseUserName"];
connBuilder.Password = config["SqlDatabase:ZupaKeyReleasePassword"];
connBuilder.InitialCatalog = "zupaauthentication";
using (SqlConnection connection = new SqlConnection(connBuilder.ConnectionString))
{
using (SqlCommand command = connection.CreateCommand())
{
connection.Open();
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
var routeToApiResourseSqlScript = $"{GetLocalPathToProject}Zupa.ReleaseDeploymentAutoConfigure\\Zupa.ReleaseDeploymentAutoConfigure\\Sql\\Scripts\\";
var apiResourcesFileName = "AddApiResorces.sql";
var fullPathToSqlScript = $"{routeToApiResourseSqlScript}{apiResourcesFileName}";
command.CommandText = File.ReadAllText(fullPathToSqlScript);
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.InnerException);
}
}
The error I'm receiving is as follows:
Something went wrong try configuring the release again.
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect. :
'C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\bin\Debug\netcoreapp3.1\file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql'
The correct path is being added to the end of the bin directory which is
file:\C:\Zupa_Source_Code\Zupa.ReleaseDeploymentAutoConfigure\Zupa.ReleaseDeploymentAutoConfigure\Sql\Scripts\AddApiResorces.sql

Change "CodeBase" in this line
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
to be Location:
var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];

Related

Is there a Method to read the Content of a Website?

I wanted to write a Program that reads an online Calendar, compares it with Names in a Database and uses this Data in some way. But if I use the WebClient, it reads the Source Code of the Website, not the Content. This is my Code:
using System;
using System.Diagnostics;
using System.Net;
using MySql.Data.MySqlClient;
namespace CalendarCrawler
{
class Program
{
static void KillTask(string Task)
{
Process[] Process = new Process[] { };
Process = Process.GetProcessesByName(Task);
foreach (Process Instance in Process)
{
Instance.Kill();
}
}
static String ReadContent(String Website)
{
WebClient web = new WebClient();
System.IO.Stream stream = web.OpenRead(Website);
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
String text = reader.ReadToEnd();
return text;
}
}
static void Main(string[] args)
{
Console.WriteLine("Getting Connection ...");
var datasource = "localhost";//your server
var database = "database"; //your database name
var username = "username"; //username of server to connect
var password = "password"; //password
//your connection string
string connStr = $"Server={datasource};Database={database};Uid={username};Pwd={password}";
//create instanace of database connection
using (var conn = new MySqlConnection(connStr))
{
try
{
Console.WriteLine("Openning Connection ...");
//open connection
conn.Open();
Console.WriteLine("Connection successful!");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
String Websitetext = ReadContent("http://www.esel.at/termine");
var stm = $"INSERT INTO content(Content) VALUES (#1);";
var cmd = new MySqlCommand(stm, conn);
cmd.Parameters.AddWithValue("#1", Websitetext);
cmd.ExecuteNonQuery();
Console.WriteLine(Websitetext);
KillTask("CalendarCrawler");
}
}
}
}
The Killtask Method is only to Clear it from the Background Processes, so there are no Problems with building a new Version.
I hope someone can help me.
There are effectively 2 different users of the web. People and computers. People like shiney things like buttons and tables (UI), computers prefer things like XML or JSON (API).
Your calendar web site has a UI, this is what you are currently seeing (both in a browser and when you 'download the code'). It probably has an API too and that is what you should be using in your program.
I've just had a quick look at esel.at and it doesn't appear to have a (public) API (but maybe that is because Google can't translate the page properly).

unable to update the oracle DB using ExecuteNonQuery()

Please find the source code below. I am not getting any error but
_oracleCommand.ExecuteNonQuery() is going infinite - debugger is not moving to next line. I am able to update the data using Toad. I am stuck with this.
public void UpdateNewResignationRequestInSynergy(string _employeeno, string _comment, string _changeby, string _changeddt, string _reason)
{
int rowsaffected = 0;
string returnStatus;
string _synquery = "";
DateTime dtDate;
_employeeno = "774647";
_comment = "contract eand";
dtDate = DateTime.Parse(_changeddt, System.Globalization.CultureInfo.CreateSpecificCulture("en-CA"));
_oracleCommand = new OracleCommand(_synquery, _synergyDb);
_synergyDb.Open();
_oracleCommand.CommandText = string.Format(#"update wipinfo.fms_resignation set str_comments = 'contract end' where STR_CONTRACTOR_ID = 774647");
_oracleCommand.CommandType = CommandType.Text;
try
{
_oracleCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
}
_synergyDb.Close();
}
You have to stop the oracle server and start again( do not restart it will not help you). I solved this problem by doing this process.

Handling file in WP-- oplock broken

I am trying to, in some instances, read from, and in others, write to a file in Windows Phone 8.1. I am using the following code to read it:
var folder = ApplicationData.Current.LocalFolder;
try
{
var connectionsFile = await folder.OpenStreamForReadAsync("connections");
using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
{
while (!streamReader.EndOfStream)
{
String con = await streamReader.ReadLineAsync();
String[] props = con.Split('\t');
Connection newConnection = new Connection() { Name = props[0], Url = props[1] };
ConnectionsCollection.Add(newCollection);
}
await connectionsFile.FlushAsync();
connectionsFile.Dispose();
}
}
catch(Exception e)
{
//handle exception
}
My problem is that it unfailingly hits the catch with an inner exception of "The handle with which this oplock was associated has been closed. The oplock is now broken." (I get the same error when trying to write to it.) I can't figure out what the problem is, especially since I am successfully using the same code to read the same file in two other places.
I think you needs to remove the await connectionsFile.FlushAsync(); line because you're using the file for reading. Also remove the connectionsFile.Dispose(); and use the using(...) in connectionsFile assignment.
var folder = ApplicationData.Current.LocalFolder;
try
{
using (var connectionsFile = await folder.OpenStreamForReadAsync("connections"))
using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
{
while (!streamReader.EndOfStream)
{
String con = await streamReader.ReadLineAsync();
String[] props = con.Split('\t');
Connection newConnection = new Connection() {Name = props[0], Url = props[1]};
ConnectionsCollection.Add(newCollection);
}
}
}
catch (Exception e)
{
//handle exception
}
I hope it helps.

Umbraco 6.1.6 Web API SSO Implementation - Final Page Accepting Token

I've worked out all the problems with the WEB API implementation in Umbraco (Token & Member creation in an http post), the problem I'm having here is this final macro, I've created to drop in an Umbraco page, it will not collect the token and email from the querystring. I keep getting a System.Data.SqlClient.SqlException (expects the parameter '#token', which was not supplied) Am I not able to grab a querystring in Umbraco, or more specifically an Umbraco macro?
namespace ****.SSO
{
public partial class ****SSOMacro : System.Web.UI.UserControl,
umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
{
static Token token = new Token();
static string connStr = ConfigurationManager.ConnectionStrings["umbracoDbDSN"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
try{
**string tmpToken = Request.QueryString["token"];
string tmpEmail = Request.QueryString["email"];
//Check If Token Still Exists
using (SqlConnection myConnection = new SqlConnection(connStr))
{
myConnection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM [DBTokenTable] WHERE tokens = #token and email = #email and valid = 'true'", myConnection);
command.Parameters.AddWithValue("#token", tmpToken);
command.Parameters.AddWithValue("#email", tmpEmail);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
token = new Token { token = reader["Tokens"].ToString(), email = reader["Email"].ToString(), valid = reader["Valid"].ToString() };
}
}
myConnection.Close();
}**
}
catch (Exception ex)
{
string error = ex.ToString();
//Log Any Form Cookies Out
FormsAuthentication.SignOut();
RawrLabel.Text = error;
//Response.Redirect(HttpUtility.UrlEncode("https://google.com/#q=" + error));
}
}
private string _umbval;
public object value
{
get { return _umbval; }
set { _umbval = value.ToString(); }
}
I was adding my macro onto a template page with Razor, so MVC didn't recognize the web forms Request.Querystring["value"] method. Instead just add the macro directly onto a content page with a Richtext editor.

Passing ConnectionString from SqlConnectionSringBuilder to ConnectionManager

I want to get a ConnectionString from an instance of SqlConnectionStringBuilder as a String.
This seems simple, and should be as easy as this:
String conString = builder.ConnectionString;
However the String that SqlConnectionStringBuilder gives up doesn't include the Password field/value. I'm guessing this is some sort of security feature, is there a way to force Password to be included in the String?
Looking at this further I'm thinking this may have something to do with ConnectionManager. What I am trying to do is modify the ConnectionString for a Package, changing the Initial Catalog.
Below is my code, the point that builder's connection string is passed back into connectionManager's the Password is lost...
public void DataTransfer(String sourceConnection, String destConnection, String pkgLocation)
{
Package pkg;
Application app;
DTSExecResult pkgResults;
try
{
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
foreach (ConnectionManager connectionManager in pkg.Connections)
{
SqlConnectionStringBuilder builder;
switch (connectionManager.Name)
{
case "SourceConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
connectionManager.ConnectionString = builder.ConnectionString.ToString();
connectionManager.ConnectionString += ";Provider=SQLNCLI;Auto Translate=false;";
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
case "DestinationConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
connectionManager.ConnectionString = builder.ConnectionString.ToString();
connectionManager.ConnectionString += ";Provider=SQLNCLI;Auto Translate=false;";
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
}
}
pkgResults = pkg.Execute();
}
catch (Exception e)
{
throw;
}
Console.WriteLine(pkgResults.ToString());
}
Set PersistSecurityInfo to True before setting other properties in the SqlConnectionStringBuilder : D
I need to rename this a little maybe, as the question is different now, but here is my solution:
The first part of this question was answered correctly by #madd0. The ConnectionString does contain the Password field.
The second part was solved with formatting code is below:
public void DataTransfer(String sourceConnection, String destConnection, String pkgLocation)
{
Package pkg;
Application app;
DTSExecResult pkgResults;
try
{
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
foreach (ConnectionManager connectionManager in pkg.Connections)
{
SqlConnectionStringBuilder builder;
switch (connectionManager.Name)
{
case "SourceConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
var sourceCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
//Added spaces to retain password!!!
sourceCon = sourceCon.Replace(";", "; ");
connectionManager.ConnectionString = sourceCon;
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
case "DestinationConnection":
builder = new SqlConnectionStringBuilder(sourceConnection) { PersistSecurityInfo = true };
builder.Remove("Initial Catalog");
builder.Add("Initial Catalog", "StagingArea");
var destCon = builder.ConnectionString + ";Provider=SQLNCLI;Auto Translate=false;";
//Added spaces to retain password!!!
destCon = destCon.Replace(";", "; ");
connectionManager.ConnectionString = destCon;
Debug.WriteLine(connectionManager.ConnectionString.ToString());
break;
}
}
pkgResults = pkg.Execute();
}
catch (Exception e)
{
throw;
}
Console.WriteLine(pkgResults.ToString());
}
I played about with the ConnectionStrings and noticed after a while that the original String had spaces between each property.
Running 2 tests I found that without spaces the Password was lost...
connectionManager.ConnectionString = destCon;
Test 1: No Spaces:
When destCon = Data Source=xxx.xxx.xxx.xxx;Initial Catalog=StagingArea;User ID=*****;Password=*****;Provider=SQLNCLI;Auto Translate=false;
Then connectionManager.ConnectionString = Data Source=xxx.xxx.xxx.xxx;User ID=*****;Initial Catalog=StagingArea;Provider=SQLNCLI;Auto Translate=false;
Test 2: Spaces:
When destCon = Data Source=xxx.xxx.xxx.xxx; Initial Catalog=StagingArea; User ID=*****; Password=*****; Provider=SQLNCLI; Auto Translate=false;
Then connectionManager.ConnectionString = Data Source=xxx.xxx.xxx.xxx; Initial Catalog=StagingArea; User ID=*****; Password=*****; Provider=SQLNCLI; Auto Translate=false;
No idea why this happens, but without spaces the ordering is adjusted and the Password field is lost.

Categories