I am trying to test some methods in my library using Google API. More specifically the Cloud Vision API. When I reference the library in LINQPad I get an error
FileNotFoundException: Error loading native library. Not found in any of the possible locations: C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf\grpc_csharp_ext.x86.dll,C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf\runtimes/win/native\grpc_csharp_ext.x86.dll,C:\Users\\AppData\Local\Temp\LINQPad5_dgzgzeqb\shadow_fxuunf../..\runtimes/win/native\grpc_csharp_ext.x86.dll
I have tried copying the dll into all of these locations as well as my LINQPad Plugins and the LINQPad folder. I have tried clearing Cancel and Clear query thinking I needed to reset it. I have also closed and reopened LINQPad thinking maybe it re-scans the directory on load. None of this has worked. Has LINQPad changed where to put dlls or am I missing something?
I am using Google.Cloud.Vision.V1
`
var file = new byte[128];
var _settingsCon = new SettingConnector();
var apiKey = Task.Run(() => _settingsCon.Get("Google:Key")).Result.Value;
var credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromJson(apiKey);
var channel = new Grpc.Core.Channel(
ImageAnnotatorClient.DefaultEndpoint.ToString(),
credential.ToChannelCredentials());
var builder = new StringBuilder();
var image = Image.FromBytes(file);
var client = ImageAnnotatorClient.Create(channel);
var response = client.DetectDocumentText(image);
foreach (var page in response.Pages)
{
foreach (var block in page.Blocks)
{
foreach (var paragraph in block.Paragraphs)
{
builder.Append(paragraph);
}
}
}
builder.ToString().Dump();`
This is essentially the function. The file is a dummy file that would be passed in. It shouldn't matter cause it can't make the request any way. The Dump is used instead of return.
Related
I am issuing (with own Certificate Authority) a certificate in c# code (based on: .NET Core 2.0 CertificateRequest class)
In CertificateRequest, unable to add Certificate ocsp Authority Information Access (oid: 1.3.6.1.5.5.7.1.1) and certificate policies (oid: 2.5.29.32) extensions (similar results of: Authority Information Access extension)
I do not want to use external libraries, perhaps only ASN1 libraries if needed.
Anyone can help with c# code to add these extensions as I didn't find any suitable types in .Net?
certificateRequestObject.CertificateExtensions.Add(
new X509Extension("2.5.29.32", **[Authority Information Access text] to RawData?** , false));
[Authority Information Access text]
Authority Information Access 1.3.6.1.5.5.7.1.1
[1]Authority Info Access
Access Method=On-line Certificate Status Protocol (1.3.6.1.5.5.7.48.1)
Alternative Name:
URL=example.org
[2]Authority Info Access
Access Method=Certification Authority Issuer (1.3.6.1.5.5.7.48.2)
Alternative Name:
URL=example.org
Disclaimer: I do strongly believe that you should not roll own crypto/CA and use standard CA software to issue certificate since they are intended to solve this problem.
There is no built-in support for ASN encoding/decoding in .NET (including .NET Core), you have to use 3rd party libraries.
For ASN encoding you can use ASN.1 library I developed: Asn1DerParser.NET
And use for your particular case will be:
Byte[] encodedData = new Asn1Builder()
.AddSequence(x => x.AddObjectIdentifier(new Oid("1.3.6.1.5.5.7.48.1")
.AddImplicit(6, Encoding.ASCII.GetBytes("http://ocsp.example.com"), true))
.GetEncoded();
var extension = new X509Extension("1.3.6.1.5.5.7.1.1", encodedData, false);
and add extension item to your request. If you need to add more URLs, then add more SEQUENCE elements:
Byte[] encodedData = new Asn1Builder()
.AddSequence(x => x.AddObjectIdentifier(new Oid("1.3.6.1.5.5.7.48.1")
.AddImplicit(6, Encoding.ASCII.GetBytes("http://ocsp1.example.com"), true))
.AddSequence(x => x.AddObjectIdentifier(new Oid("1.3.6.1.5.5.7.48.1")
.AddImplicit(6, Encoding.ASCII.GetBytes("http://ocsp2.example.com"), true))
.GetEncoded();
var extension = new X509Extension("1.3.6.1.5.5.7.1.1", encodedData, false);
I needed to add an AIA (Authority Information Access) extension using dotnet also. It is super cool #Crypt32 shared the code from Asn1DerParser.NET. It made me curious. I started looking at other code like BouncyCastle and I didn't see any code that did the same thing. There is a AuthorityInformationAccess class, but I couldn't find any tests that created an AIA extension. Maybe the implementation isn't finished. I could dig further but I instead looked at the dotnet runtime code. While of course there isn't a dotnet AIA builder, there is a SubjectAlternativeNameBuilder]2 I could learn from. So, I did just that. Essensually it uses the AsnWriter to encapsulate the mechanics of building an ASN1 Sequence. Below is an example where I add two certificate authority issuers. Next steps would be to encapuslate this in an AIA Builder but here is an example.
The parts that I struggled with were ensuring when to call writer.Encode and writer.WriteEncodedValue. After an hour or so everything made sense.
#Guru_07, I believe this allows you to avoid third party code. Although it has been some time since you posted your question.
List<byte[]> encodedUrls = new List<byte[]>();
List<byte[]> encodedSequences = new List<byte[]>();
AsnWriter writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteObjectIdentifier("1.3.6.1.5.5.7.48.2");
encodedUrls.Add(writer.Encode());
writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteCharacterString(
UniversalTagNumber.IA5String,
"http://ocsp.example.com",
new Asn1Tag(TagClass.ContextSpecific, 6)
);
encodedUrls.Add(writer.Encode());
writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSequence())
{
foreach (byte[] encodedName in encodedUrls)
{
writer.WriteEncodedValue(encodedName);
}
}
encodedSequences.Add(writer.Encode());
encodedUrls = new List<byte[]>();
writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteObjectIdentifier("1.3.6.1.5.5.7.48.2");
encodedUrls.Add(writer.Encode());
writer = new AsnWriter(AsnEncodingRules.DER);
writer.WriteCharacterString(
UniversalTagNumber.IA5String,
"http://ocsp2.example.com",
new Asn1Tag(TagClass.ContextSpecific, 6)
);
encodedUrls.Add(writer.Encode());
writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSequence())
{
foreach (byte[] encodedName in encodedUrls)
{
writer.WriteEncodedValue(encodedName);
}
}
encodedSequences.Add(writer.Encode());
writer = new AsnWriter(AsnEncodingRules.DER);
using (writer.PushSequence())
{
foreach (byte[] encodedSequence in encodedSequences)
{
writer.WriteEncodedValue(encodedSequence);
}
}
var ext = new X509Extension(
new Oid("1.3.6.1.5.5.7.1.1"),
writer.Encode(),
false);
Purpose: I have an SSIS Solution with various packages, one set of these packages is currently created with a package per table due to them having different structures. The aim is to create a template package (done), update variables/table names (done), reinitialise and re-map columns, execute package for each table.
Problem: So, as you can tell, I'm up to the point that i need to reinitialise but I am unable to get to the data flow task and keep getting this error:
No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))
When I run this code:
//// Get Data Flow task
TaskHost tHost = pkgOut.Executables[0] as TaskHost;
MainPipe dataFlowTask = (MainPipe)tHost.InnerObject;
The code that I am using is below:
public void Main()
{
// Set Project Variables
List<string> pkgVars = new List<string>
{
#"pPR_SSIS_Catalog_Server",
#"pPR_SSIS_Catalog_Project",
#"pPR_SSIS_Catalog_Folder"
};
// Get Package
String pkgLocation = #"C:\PATH\TO\TEMPLATE\PACKAGE\a_Load_SAP_Template.dtsx";
Application app = new Application();
Package pkgIn = app.LoadPackage(pkgLocation, null);
String pkgName = "DynamicPackage";
// Add Connections (cos they're project connections and aren't stored in package)
ConnectionEnumerator allConns = Dts.Connections.GetEnumerator();
while ((allConns.MoveNext()) && (allConns.Current != null))
pkgIn.Connections.Join(allConns.Current);
// Convert new package to XML so we can cheat and just do a find and replace
XmlDocument pkgXML = new XmlDocument();
pkgIn.SaveToXML(ref pkgXML, null, null);
// Replace strings
// Set SAP table
String pkgStr = pkgXML.OuterXml.ToString();
pkgStr = pkgStr.Replace("#SAP_SRC_TABLE#", "MyF-ingSAPTables"); // Replace SAP Table Name
// Set Project Variables references == values -- REMEMBER TO CHECK FOR INT PARAMS zzz
foreach (string var in pkgVars)
pkgStr = pkgStr.Replace(#"#[$Project::" + var + #"]", #"""" + Convert.ToString(Dts.Variables[var].Value) + #"""");
// Convert back to XML
XmlDocument newXML = new XmlDocument();
newXML.LoadXml(pkgStr);
Package pkgOut = new Package();
pkgOut.LoadFromXML(newXML, null);
//// Get Data Flow task
TaskHost tHost = pkgOut.Executables[0] as TaskHost;
MainPipe dataFlowTask = (MainPipe)tHost.InnerObject; // THIS IS WHERE THE CODE ERRORS
new Application().SaveToXml(String.Format(#"D:\PATH\TO\SAVE\LOCATION\{0}.dtsx", pkgName), pkgOut, null);
Dts.TaskResult = (int)ScriptResults.Success;
}
I have tried:
Removing everything but the data flow
Recreated a blank data flow
Recreated the package
Made a package in the script and created the data flow (this works but when i open the package, the data flow does not appear...might have added it wrong but it can see it when I run the TaskHost section)
I am not sure what else I can try, I have seen information that I might need to re-register some .dlls but I do not have admin access and I'd prefer not to go through the hassle for something where I do not know whether it will work.
Any help would be appreciated.
Thanks,
Fixed, was due to version difference in the .DLL that was being loaded. Loaded an older version and all went through fine.
I'm an Amazon FBA seller and I would like to begin to upload data regarding my sales in a more automated process using Amazon MWS. I just made an amazon MWS account and received my different IDs (Access Key Id, secret Access Key, ...).
I have the impression that most MWS developers use C#. I have a lot of Excel VBA experience but not in C#. Therefore, I'm not sure of the steps I have to follow.
On the webpage below, you can find a C# code that I would like to run:
http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
Could you confirm the steps below are correct? :
1) Download Visual Studio => Do I need to download any extra package from Amazon?
2) In Visual Studio: File => New Project => C# console application
3) Erase all code and replace it by a copy-paste of the code found on above website => Do I need to put the code Inside something like "Sub - end Sub" in VBA?
4) Change "YourSecretKey", "YourSecretAccessKey", "YourSecretAccessKey", "YourMerchantID", "YourMarketplaceID" by my IDs.
5) Hit the run button
If it works, what will be the output like: An array inside Visual studio? A text file? A csv file? Where will it be stored?
I realize this is a very newbie question. However, I think that once I have a first code running correctly, my VBA experience will allow me to start efficiently from there.
Thanks in advance,
Diego.
After looking the code from http://www.samswiches.com/2011/02/how-to-use-amazon-mws-to-download-unshipped-order-reports/
I tried and changed something, and it works. Here is my solution:
Download the C# MWS Reports API Client Library: https://developer.amazonservices.com/doc/bde/reports/v20090101/cSharp.html
Use Visual Studio to create a project to get reports using MWS Reports API Client Library
Here is the code.
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using MarketplaceWebService;
using MarketplaceWebService.Mock;
using MarketplaceWebService.Model;
using System.IO;
using System.Threading;
public void testReport()
{
String accessKeyId = "Your Access Key ID";
String secretAccessKey = "Your Secret Access Key";
const string merchantId = "Merchant ID";
const string marketplaceId = "Marketplace ID";
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = "https://mws.amazonservices.com";
const string applicationName = "ApplicationName";
const string applicationVersion = "0.01";
MarketplaceWebServiceClient service =
new MarketplaceWebServiceClient(
accessKeyId,
secretAccessKey,
applicationName,
applicationVersion,
config);
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
// you can change ReportType here:
//http://docs.developer.amazonservices.com/en_IN/reports/Reports_ReportType.html
reportRequestRequest.ReportType = “_GET_FLAT_FILE_ACTIONABLE_ORDER_DATA_";
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
IdList lstRequestID = new IdList();
lstRequestID.Id.Add
(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportRequestListRequest reportRequestListRequest = new
GetReportRequestListRequest();
reportRequestListRequest.Merchant = merchantId;
reportRequestListRequest.ReportRequestIdList = lstRequestID;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new
GetReportRequestListResponse();
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new
GetReportRequestListResult();
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
if (myListzz.Count > 0)
{
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Console.WriteLine("Waiting for Report");
Thread.Sleep(61000);
reportRequestListResponse =
service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult =
reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
if (myListzz[0].GeneratedReportId !=null)
{
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
String source = "C:\\myreport.txt";
reportRequest.ReportId = myListzz[0].GeneratedReportId;
reportRequest.Report = File.Open(source, FileMode.Create,
FileAccess.ReadWrite);
service.GetReport(reportRequest);
}
}
}
You are missing step 1b) Download the C# MWS Reports API Client Library. You may need other libraries to access other parts of the MWS API, but from a quick glance at that code above library is the main one.
Note that it refers to a lblStatus, which seems to be a label on a form, but nowhere in that post does it say anything else about that form. So step 2) probably is not a "console" style application, but a form based one, which also means, you shouldn't erase all code in step 3, but paste the code into whatever is the equivalent of a main() function (I've only ever used C and C++, but not C#, so I have no clue)
I need to download files from opensubtitles.org trough my application which is written in GTK# and C#. The app is based on .NET 4.0 framework.
At first this was the code I was using:
var tZip = new FastZip();
try {
var tRequest = (HttpWebRequest)HttpWebRequest.Create(tDownloadUrl);
var tZipResponse = (HttpWebResponse)tRequest.GetResponse();
using (var tStream = tZipResponse.GetResponseStream()) {
using (var tMemStream = new MemoryStream()) {
tStream.CopyTo(tMemStream);
var tTempPath = Globals.video_location + "OSD";
Directory.CreateDirectory(tTempPath);
tZip.ExtractZip(tMemStream, tTempPath, FastZip.Overwrite.Always, null, #"\.srt$", null, false, true);
var tDirInfo = new DirectoryInfo(tTempPath);
var tFileInfo = new FileInfo(Globals.location_video);
var tSrtFile = tDirInfo.EnumerateFiles().FirstOrDefault();
if (tSrtFile == null) {
writeLog("No .srt file found in zip..");
goto text;
}
writeLog("Downloaded and unpacked: " + tSrtFile.Name);
File.Copy(tSrtFile.FullName, Globals.video_location+Globals.video_name+".srt", true);
Globals.savedTitle = Globals.video_location+Globals.video_name+".srt";
// clean up..
Directory.Delete(tTempPath, true);
writeLog("Deleted temp folder.");
return true;
}
}}
And that worked really well up until few days ago, now it is returning a bunch of html code instead of .zip file. I tried even something like this:
WebClient client = new WebClient();
client.DownloadFile(link, #"OSD\test.zip");
But everything just keeps returning bunch of html code.
The link I am usually trying to download is something like this:
http://dl.opensubtitles.org/en/download/subad/4287952
If you click on the link above it will just redirect you to the opensubtitles.org page of that particular subtitle. But if you right mouse click on that link and then select "open in new tab" or "open in new window" it will automatically start the download. (Tested in Firefox)
Also as soon as I paste that link in "Internet Download Manager" application, it will start the download of the zip file automatically.
If you can help me to resolve this problem I will truly be grateful.
Kind Regards.
I got into this problem because I was filtering the website xml directly. Like from a link such as this one: opensubtitles.org example
And in the beginning it used to work well, but then they changed something on the website and it stopped working. So what I did was build on top of this: OSHandler
That handler library is using XML-RPC so I believe there won't be any problems in the future.
After scouring the web I am completely stuck on an application I am building to push directories up to Amazon S3 using C# (Targeting .NET 4.5). I am getting NullReferenceExceptions on the line of code that pushes the directory files using the UploadDirectory(TransferUtilityUploadDirectoryRequest) method of the TransferManager class. The problem is I cannot find anything that is null! The debugger doesn't show anything null either, so I'm obviously missing something here.
I read up that if you are uploading to buckets that have periods in them, you need to change the protocol to HTTP otherwise a NullReferenceException might be thrown, however I've done this as well and am continuing to receive the error, even when I created another bucket for testing that has no periods in it.
The portion of my code up to & including the line that causes the exception is below. The class called S3Info is just a helper class that I created that just stores some configuration info such as access/secret keys and other info:
public static void uploadDirectories(S3Info info, List<DirectoryInfo> dirs, Logger logger = null)
{
AmazonS3Config alterConfig = new AmazonS3Config();
alterConfig.CommunicationProtocol = Protocol.HTTP;
AmazonS3Client s3Client = new AmazonS3Client(info.getCredentials(), alterConfig);
TransferUtility directoryTransferUtil = new TransferUtility(s3Client);
TransferUtilityUploadDirectoryRequest uploadDirRequest;
PutObjectRequest completeFileUploadRequest;
uint uploadSuccessCount = 0;
if (dirs == null || dirs.Count == 0)
{
logger.log("Nothing to upload.");
return;
}
//upload directory with PDFs
foreach (DirectoryInfo dir in dirs)
{
try
{
//configure upload request
uploadDirRequest = new TransferUtilityUploadDirectoryRequest();
uploadDirRequest.BucketName = info.selectedBucket.BucketName;
uploadDirRequest.Directory = dir.FullName;
uploadDirRequest.KeyPrefix = dir.Name + #"\";
uploadDirRequest.SearchOption = SearchOption.TopDirectoryOnly;
uploadDirRequest.SearchPattern = "*.pdf";
uploadDirRequest.Timeout = 600000; //10 minutes
//upload directory!
directoryTransferUtil.UploadDirectory(uploadDirRequest); //exception thrown here
I'm a bit stuck at this point so I'm open to any suggestions the community can provide. Thanks.
EDIT: Stack Trace-
Object reference not set to an instance of an object. :
at Amazon.S3.Transfer.Internal.UploadDirectoryCommand.Execute()
at Amazon.S3.Transfer.TransferUtility.UploadDirectory(TransferUtilityUploadDirectoryRequest request)
at S3Delivery.AmazonActions.uploadDirectories(S3Info info, List`1 dirs, Logger logger) in c:\Users\jblacker\Documents\Visual Studio 2012\Projects\S3Delivery\S3Delivery\AmazonActions.cs:line 173
Line 173 is the line referred to above.
A patched version of the SDK (version 1.5.30.1) was released earlier today that fixes this issue.
I posted this same question on the AWS Forums. Apparently the API was broken for the method: UploadDirectory() in version 1.5.30 of the .NET SDK.
Amazon has just posted a patch as version 1.5.30.1