VB.NET Exception when running System.Security.Cryptography.ECDsa.Create (ECCurve curve) - vb.net

I am getting an exception when I use the System.Security.Cryptography.ECCurve.NamedCurves.brainpoolP256r1 property of Framework 4.7.
The exception I am getting is (stackoverflow):
The specified 'brainpoolP256r1' curve or its parameters are not valid
for this platform. Stackoverflow:
in System.Security.Cryptography.CngKey.Create (ECCurve curve, Func`2
algorithihmResolver) in
System.Security.Cryptography.ECDsaCng.GenerateKey (ECCurve curve) in System.Security.Cryptography.ECDsa.Create (ECCurve curve)
In local machines that I have in the office it works for me in all, but in the different servers that I have tried, it has not worked in any.
Dim pubKeyX As Byte() = _Key.Skip(1).Take(32).ToArray()
Dim pubKeyY As Byte() = _Key.Skip(33).ToArray()
Dim params As New ECParameters() With
{
.Q = New ECPoint With
{
.X = pubKeyX,
.Y = pubKeyY
},
.Curve = _ECCurve
}
Dim oRes As ECDsa = ECDsa.Create(_ECCurve)
This last line is the one that causes the exception

Related

XERO There is an error in XML (1,1)

I've had code working for several years now and I had to upgrade the project to .Net 4. After upgrading the project, I am getting the following error after accessing any method:
There is an error in XML document (1,1) - hexadecimal value 0x1F, is an invalid character. Line 1 position 1.
Here is a sample of the code I'm attempting to run:
Dim ConsumerKey As String = "XXXXXXXXXXXXXXXXXXXXXX"
Dim UserAgentString As String = "TEST Xero Interface (Private App Testing)"
Dim privateCertificate As X509Certificate2 = New X509Certificate2("C:\Data\public_privatekey.pfx", "xxxxxxx")
Dim uConsumerSession As IOAuthSession = New XeroApiPrivateSession(UserAgentString, ConsumerKey, privateCertificate)
Dim uRepository As New Repository(uConsumerSession)
Dim uInvoice As New Model.Invoice
Dim uContact As New Model.Contact
uContact.Name = "ABC Ltd"
uContact.IsCustomer = True
uInvoice.Contact = uContact
uInvoice.Type = "ACCREC"
uInvoice.Date = Now
uInvoice.DueDate = DateAdd(DateInterval.Day, 14, Now)
uInvoice.Status = "DRAFT"
uInvoice.LineAmountTypes = 0
uInvoice.LineItems = New LineItems
Dim uLineItem = New Model.LineItem
uLineItem.Quantity = 1
uLineItem.ItemCode = "TEST TRANS"
uLineItem.Description = "Testing Router"
uLineItem.AccountCode = "400"
uLineItem.UnitAmount = 200
uInvoice.LineItems.Add(uLineItem)
uRepository.Create(Of Model.Invoice)(uInvoice)
What am I doing wrong here? Why did the same code I've used for years stop working?
TLDR; Your code will be using TLS 1.0 which is deprecated - use the following in your code to force TLS 1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I am sure you have worked this out already but I was getting the same thing, API was returning an undocumented response code 412 so being rejected prior to even getting to the API and doing things,
The error response handling in that Older SDK which you look to be using for .NET was not working that well so was trying to parse the error response hence the error - which put me off for a bit while i debugged.
I decided to upgrade to the new Xeronet SDK which is actively being maintained - https://github.com/XeroAPI/Xero-Net
Then i got the same error except this time the error message was useful, stated that TLS 1.0 was not supported please upgrade, Ah. Ha... they turned support of for this end of June 2018 according to their site, I think it actually happened end of July as I had things working on this code at the end of July.
Anyway upgrade your code ideally to the new SDK and then force .net to use TLS 1.2 using the below if on .net 4.5
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
if using 4.0 then
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Error with SPPID's Interop.Llama library : System.Runtime.InteropServices.COMException (0x80000008): No DBConnect for Data_Dictionary

I'm having the following error usiing SmartPlant P&ID (SPPID) automation library Llama (Interop.Llama.dll):
System.Runtime.InteropServices.COMException (0x80000008): No DBConnect for Data_Dictionary
at Llama._LMEquipments.Collect(LMADataSource& DataSource, _LMAItem& Parent, String& RelationshipName, LMAFilter& Filter)
Here is the code that calls it:
Dim objDS As Llama.LMADataSource
Dim objEquips As Llama.LMEquipments
objDS = New Llama.LMADataSource
objDS.ProjectNumber = Project.SPPIDName & "!" & Project.SPPIDName
objDS.SiteNode = Project.SiteServer
objEquips = New Llama.LMEquipments
objEquips.Collect(objDS) ' throws Exception
Any ideas on what might be wrong?
SPPID is an engineering tool used to develop and manage piping and instrumentation diagrams. Llama is an automation library supplied with SPPID.
This means that your code can't find that specific project in SPPID available plant structures database. Beware that the ProjectNumber string is case sensitive .
In my case, all I had to do was to change project name, from PF2_REF to PF2_Ref (replaced last two letters for lowercase equivalents).

How to use SqlFileStream for transactional access to SQL Server 2012 FileTable?

I'm trying to use the SqlFileStream object in a WCF service to get a handle to a specific file that is in a SQL Server 2012 FileTable. I'm able to get the path and transaction context like you would expect with no issues using this piece of code:
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["FileStorage"].ConnectionString))
{
con2.Open();
string getFileHandleQuery = String.Format(
#"SELECT FileTableRootPath(), file_stream.GetFileNamespacePath(), GET_FILESTREAM_TRANSACTION_CONTEXT()
FROM {0}
WHERE stream_id = #streamId", "FSStore");
byte[] serverTransactionContext;
string serverPath;
using (SqlCommand sqlCommand = new SqlCommand(getFileHandleQuery, con2))
{
sqlCommand.Parameters.Add("#streamId", SqlDbType.UniqueIdentifier).Value = new Guid(finalFileHandleStreamId);
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
sqlDataReader.Read();
serverPath = String.Concat(sqlDataReader.GetSqlString(0).Value, sqlDataReader.GetSqlString(1).Value);
serverTransactionContext = sqlDataReader.GetSqlBinary(2).Value;
sqlDataReader.Close();
}
}
con2.Close();
}
However, once I try and actually use the path and transaction context to create a new SqlFileStream:
using (SqlFileStream dest =
new SqlFileStream(serverPath, serverTxn, FileAccess.Write))
{
...
}
The above blows ups with the following exception: The mounted file system does not support extended attributes.
Can someone please explain to me what I'm doing wrong here?
Thanks!
If you are trying to use FileTable and receive an error when new a SqlFileStream object, please check the filePath value.
SqlFileStream sfs = new SqlFileStream(filePath, objContext, System.IO.FileAccess.Read); <-- Error "The mounted file system does not support extended attributes"
Correct way to obtain the filePath value is
SELECT [file_stream].PathName() FROM dbo.fTable WHERE name = 'test.xlsx'
filePath value should look like:
\\HOSTNAME\MSSQLSERVER\v02-A60EC2F8-2B24-11DF-9CC3-AF2E56D89593\test\dbo\fTable\file_stream\A654465D-1D9F-E311-B680-00155D98CA00\VolumeHint-HarddiskVolume1
not like:
\\HOSTNAME\MSSQLSERVER\Store\fDirectory\test.xlsx
That is required by design. Please refer to
https://connect.microsoft.com/SQLServer/feedback/details/729273/sql-server-denali-filetable-access-using-sqlfilestream-returns-error-the-mounted-file-system-does-not-support-extended-attributes
and
Access FILESTREAM Data with OpenSqlFilestream
http://technet.microsoft.com/en-us/library/bb933972.aspx

Cached Variables in VSTO Office 2010

After having a look around the web, I have found the following posts (below) which are quite similar to my problem. However, after trying the solutions, I am still stuck.
VSTO Frustration
Setting cached variables in VSTO 3.0
Basically, I want to populate some data in a Excel file on a web server before I send it to the client.
Here is my code in the Workbook:
namespace Inno.Data.Excel
{
public partial class ThisWorkbook
{
[Cached]
public DataSet Config = new DataSet();
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
//InitializeCachedData();
var baseUrl = (string)Config.Tables["Config"].Rows[0].ItemArray[0];
var streamIds = (string)Config.Tables["Config"].Rows[0].ItemArray[1];
MessageBox.Show(baseUrl + " " + streamIds);
}
}
}
and on the server side I have the following:
let rootUrl = Uri(x.Request.Url.GetLeftPart(UriPartial.Authority))
let setUpData (report : Report) (sd : ServerDocument) =
let url = rootUrl.AbsoluteUri
let streamIds = String.Join(",", report.series |> Seq.map(fun s -> s.id))
let dt = new System.Data.DataTable("Config")
dt.Columns.Add("BaseUrl", typeof<String>) |> ignore
dt.Columns.Add("StreamIds", typeof<String>) |> ignore
dt.Rows.Add([|box url; box streamIds|]) |> ignore
dt.AcceptChanges()
let cache = sd.CachedData.HostItems.["Inno.Data.Excel.ThisWorkbook"]
let urlItem = cache.CachedData.["Config"]
urlItem.SerializeDataInstance(dt)
sd.Save()
sd.Close()
let initialiseDocument (report : Report) (path : string) =
let fileName = report.name.Replace(" ", "_") + ".xlsx"
let sd = (new ServerDocument(path))
sd |> setUpData report
fileName
let docPath = x.Request.MapPath(Path.Combine(liveReportPath, "Inno.Data.Excel.xlsx"))
let fileName = initialiseDocument report docPath
x.File(File.OpenRead(docPath), "application/vnd.ms-excel", fileName) :> ActionResult
However, when I go to open the file after it has downloaded, I get the following error:
Microsoft.VisualStudio.Tools.Applications.Runtime.CannotFindObjectToFillException: Cannot find any public instance member with ID Config in object Inno.Data.Excel.ThisWorkbook.
Things I have tried:-
Using a simple string rather than a DataSet
Calling StartCaching("Config")
Manipulating the ServerDocument in memory using the byte[] file overload
Copying the original Excel file and operating on the copy
But now I'm out of ideas. I see that a fair number of people have had this error, and as is pointed out in this post, there was a known bug in VSTO 3.0 with manipulating files in memory.
Thanks in advance.

Test zip password correctness in vb.net

I want to test if a zip has a particular password in vb.net. How can I create a function like check_if_zip_pass(file, pass) As Boolean?
I can't seem to find anything in the .net framework that does this already, unless I'm missing something incredibly obvious.
This method should NOT extract the files, only return True if the attempted pass is valid and False if not.
Use a 3rd party library, like DotNetZip. Keep in mind that passwords in zipfiles are applied to entries, not to the entire zip file. So your test doesn't quite make sense.
One reason WinZip may refuse to unpack the zipfile is that the very first entry is protected with a password. It could be the case that only some entries are protected by password, and some are not. It could be that different passwords are used on different entries. You'll have to decide what you want to do about these possibilities.
One option is to suppose that only one password is used on any entries in the zipfile that are encrypted. (This is not required by the zip specification) In that case, below is some sample code to check the password. There is no way to check a password without doing the decryption. So this code decrypts and extracts into Stream.Null.
public bool CheckZipPassword(string filename, string password)
{
bool success = false;
try
{
using (ZipFile zip1 = ZipFile.Read(filename))
{
var bitBucket = System.IO.Stream.Null;
foreach (var e in zip1)
{
if (!e.IsDirectory && e.UsesEncryption)
{
e.ExtractWithPassword(bitBucket, password);
}
}
}
success = true;
}
catch(Ionic.Zip.BadPasswordException) { }
return success;
}
Whoops! I think in C#. In VB.NET this would be:
Public Function CheckZipPassword(filename As String, password As String) As System.Boolean
Dim success As System.Boolean = False
Try
Using zip1 As ZipFile = ZipFile.Read(filename)
Dim bitBucket As System.IO.Stream = System.IO.Stream.Null
Dim e As ZipEntry
For Each e in zip1
If (Not e.IsDirectory) And e.UsesEncryption Then
e.ExtractWithPassword(bitBucket, password)
End If
Next
End Using
success = True
Catch ex As Ionic.Zip.BadPasswordException
End Try
Return success
End Function
I use SharpZipLib in .NET to do this, here is a link to their wiki with a helper function for unzipping password protected zip files. Below is a copy of the helper function for VB.NET.
Imports ICSharpCode.SharpZipLib.Core
Imports ICSharpCode.SharpZipLib.Zip
Public Sub ExtractZipFile(archiveFilenameIn As String, password As String, outFolder As String)
Dim zf As ZipFile = Nothing
Try
Dim fs As FileStream = File.OpenRead(archiveFilenameIn)
zf = New ZipFile(fs)
If Not [String].IsNullOrEmpty(password) Then ' AES encrypted entries are handled automatically
zf.Password = password
End If
For Each zipEntry As ZipEntry In zf
If Not zipEntry.IsFile Then ' Ignore directories
Continue For
End If
Dim entryFileName As [String] = zipEntry.Name
' to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
' Optionally match entrynames against a selection list here to skip as desired.
' The unpacked length is available in the zipEntry.Size property.
Dim buffer As Byte() = New Byte(4095) {} ' 4K is optimum
Dim zipStream As Stream = zf.GetInputStream(zipEntry)
' Manipulate the output filename here as desired.
Dim fullZipToPath As [String] = Path.Combine(outFolder, entryFileName)
Dim directoryName As String = Path.GetDirectoryName(fullZipToPath)
If directoryName.Length > 0 Then
Directory.CreateDirectory(directoryName)
End If
' Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
' of the file, but does not waste memory.
' The "Using" will close the stream even if an exception occurs.
Using streamWriter As FileStream = File.Create(fullZipToPath)
StreamUtils.Copy(zipStream, streamWriter, buffer)
End Using
Next
Finally
If zf IsNot Nothing Then
zf.IsStreamOwner = True ' Makes close also shut the underlying stream
' Ensure we release resources
zf.Close()
End If
End Try
End Sub
To test, you could create a file compare that looks at the file before it's zipped and again after it has been unzipped (size, date, etc...). You could even compare the contents if you wanted to use a simple test file, like a file with the text "TEST" inside. Lots of choices, depends on how much and how far you want to test.
There's not much built into the framework for doing this. Here's a big sloppy mess you could try using the SharpZipLib library:
public static bool CheckIfCorrectZipPassword(string fileName, string tempDirectory, string password)
{
byte[] buffer= new byte[2048];
int n;
bool isValid = true;
using (var raw = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
using (var input = new ZipInputStream(raw))
{
ZipEntry e;
while ((e = input.GetNextEntry()) != null)
{
input.Password = password;
if (e.IsDirectory) continue;
string outputPath = Path.Combine(tempDirectory, e.FileName);
try
{
using (var output = File.Open(outputPath, FileMode.Create, FileAccess.ReadWrite))
{
while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, n);
}
}
}
catch (ZipException ze)
{
if (ze.Message == "Invalid Password")
{
isValid = false;
}
}
finally
{
if (File.Exists(outputPath))
{
// careful, this can throw exceptions
File.Delete(outputPath);
}
}
if (!isValid)
{
break;
}
}
}
}
return isValid;
}
Apologies for the C#; should be fairly straightforward to convert to VB.NET.