422 unprocessable entity error received from pastebin POST request - c#

I've been making a big project recently and have been trying to figure out how to make my C# .Net program post a string to Pastebin and return the URL of the paste created. I've gotten a few lines of code down (not mine, I found it on this site) but even after much troubleshooting I always get some kind of error from it. I'm not familiar with webrequest or any of the similar methods designed to interact with the internet, so I had to rely on advice from other people online, yet even after multiple hours worth of searching online for solutions to my problem I still get a (422) unprocessable entity error from my code when run:
using System.Net;
using System.IO;
using System.Text;
using System.IO;
public class Program
{
public static void Main()
{
WebRequest wr = WebRequest.Create("https://pastebin.com/api/api_post.php");
//ASCIIEncoding encoding = new ASCIIEncoding();
byte[] bData = Encoding.UTF8.GetBytes(string.Concat("api_option=paste&api_paste_code=", Console.ReadLine(), "&paste_private=0&api_dev_key=" + api_dev_key));
wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = bData.Length;
Stream sMyStream = wr.GetRequestStream();
sMyStream.Write(bData, 0, bData.Length);
wr.GetResponse();
sMyStream.Close();
}
}
Exact error:
Run-time exception (line 36): The remote server returned an error: (422) Unprocessable Entity.
Stack Trace:
[System.Net.WebException: The remote server returned an error: (422) Unprocessable Entity.]
at System.Net.HttpWebRequest.GetResponse()
at Program.Main() :line 36
I've decided the best course of action to take to solve my problem is just to get help directly from people who know this kind of stuff well. I've just been running this code on dotnetfiddle. If you need more information please ask.
Edits: updated a few parameters (such as api_option)

After taking a look at the docs I think you're using a unsuitable parameter (paste_subdomain) for posting your API key.
Have a try using api_dev_key instead:
byte[] bData = Encoding.UTF8.GetBytes(string.Concat("paste_code=", encoded, "&paste_private=0&paste_expire_date=1D&api_dev_key=" + api_dev_key));
If this doesn't work, better have a look at the other parameters, too.
Just a blind guess, but probably the error occurs because you don't url-encode the code to be posted.
Maybe it'll do the trick if you encode the code entered:
var toBePosted = Console.ReadLine();
var encoded = HttpUtility.UrlEncode(toBePosted);
byte[] bData = Encoding.UTF8.GetBytes(string.Concat("paste_code=", encoded, "&paste_private=0&paste_expire_date=1D&paste_subdomain=" + api_dev_key));

I've had working code for a while, and just recently got this error showing up on one of my bots that paste to pastebin.. worked fine # 1230MST started erroring # 100pm MST..
Could be something on their end, and nothing has changed here, and its worked for many years.

Related

Unsupported Media Type error when using json-patch in Ramone

Update: I downloaded Ramone project, added it to my project and then ran the application again with debugger. The error is shown below:
public MediaTypeWriterRegistration GetWriter(Type t, MediaType mediaType)
{
...
CodecEntry entry = SelectWriters(t, mediaType).FirstOrDefault(); => this line throws error
...
}
Error occurs in CodecManager.cs. I am trying to figure out why it does not recognize json-patch media type. Could it be because writer is not being registered correctly? I am looking into it. If you figure out the problem, please let me know. Since you are the author of the library, it will be easier for you to figure out the issue. I will have to go through all the code files and methods to find the issue. Thanks!
I was excited to know that Ramone library supports json-patch operations but when I tried it, I got following error:
415- Unsupported Media Type
This is the same error that I get when I use RestSharp. I thought may be RestSharp does not support json-patch and errors out so I decided to try Ramone lib but I still get same error. Endpoint has no issues because when I try same command using Postman, it works but when I try it programmatically in C#, it throws unsupported media type error. Here is my code:
var authenticator = new TokenProvider("gfdsfdsfdsafdsafsadfsdrj5o97jgvegh", "sadfdsafdsafdsfgfdhgfhehrerhgJ");
JsonPatchDocument patch = new JsonPatchDocument<MetaData>();
patch.Add("/Resident2", "Boyle");
//patch.Replace("/Resident", "Boyle");
RSession = RamoneConfiguration.NewSession(new Uri("https://api.box.com"));
RSession.DefaultRequestMediaType = MediaType.ApplicationJson;
RSession.DefaultResponseMediaType = MediaType.ApplicationJson;
Ramone.Request ramonerequest = RSession.Bind("/2.0/files/323433290812/metadata");
ramonerequest.Header("Authorization", "Bearer " + authenticator.GetAccessToken(code).AccessToken);
//var ramoneresponse = ramonerequest.Patch(patch); //results in error: 405 - Method Not Allowed
var ramoneresponse = ramonerequest.Put(patch); //results in error: 415 - Unsupported Media Type
var responsebody = ramoneresponse.Body
Endpoint information is available here: http://developers.box.com/metadata-api
I used json-patch section in the following article as a reference:
http://elfisk.dk/Ramone/Documentation/Ramone.pdf
By the way I tried Patch() method (as shown in above ref. article) but that resulted in "Method not allowed" so I used Put() method which seems to work but then errors out because of json-patch operation.
Any help, guidance, tips in resolving this problem will be highly appreciated. Thanks much in advance.
-Sham
The Box documentation says you should use PUT (which is quite a bit funny). The server even tells you that it doesn't support the HTTP PATCH method (405 Method Not Allowed) - so PUT it must be.
Now, you tell Ramone to use JSON all the time (RSession.DefaultRequestMediaType = MediaType.ApplicationJson), so you end up PUT'ing a JSON document to Box - where you should be PUT'ing a JSON-Patch document.
Drop the "RSession.DefaultRequestMediaType = MediaType.ApplicationJson" statement and send the patch document as JSON-Patch with the use of: ramonerequest.ContentType("application/json-patch+json").Put(...).

Does LibGit2Sharp support cloning a repository from the local file system?

I am trying to clone a git repository from the local file system:
using System;
using LibGit2Sharp;
class Program
{
static void Main()
{
var sourceUrl = #"file:///c:/work/libgit2sharp";
using (Repository.Clone(sourceUrl, "targetDir", bare: true))
{
Console.WriteLine("repository successfully cloned");
}
}
}
and I get an exception:
Unhandled Exception: LibGit2Sharp.LibGit2SharpException: An error was raised by libgit2. Category = Odb (Error).
Failed to find the memory window file to deregister
at LibGit2Sharp.Core.Ensure.Success(Int32 result, Boolean allowPositiveResult) in c:\work\libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 85
at LibGit2Sharp.Core.Proxy.git_clone_bare(String url, String workdir, git_transfer_progress_callback transfer_cb) in c:\work\libgit2sharp\LibGit2Sharp\Core\Proxy.cs:line 219
at LibGit2Sharp.Repository.Clone(String sourceUrl, String workdirPath, Boolean bare, Boolean checkout, TransferProgressHandler onTransferProgress, CheckoutProgressHandler onCheckoutProgress) in c:\work\libgit2sharp\LibGit2Sharp\Repository.cs:line 431
at Program.Main() in c:\work\ConsoleApplication1\Program.cs:line 10
I've also tried the following source url:
var sourceUrl = #"c:\work\libgit2sharp\.git\";
and got another exception:
Unhandled Exception: LibGit2Sharp.LibGit2SharpException: An error was raised by libgit2. Category = Config (Error).
Failed to parse config file: Unexpected end of file while parsing multine var (in c:/work/ConsoleApplication1/bin/Debug/targetDir/config:23, column 0)
at LibGit2Sharp.Core.Ensure.Success(Int32 result, Boolean allowPositiveResult) in c:\work\libgit2sharp\LibGit2Sharp\Core\Ensure.cs:line 85
at LibGit2Sharp.Core.Proxy.git_clone_bare(String url, String workdir, git_transfer_progress_callback transfer_cb) in c:\work\libgit2sharp\LibGit2Sharp\Core\Proxy.cs:line 219
at LibGit2Sharp.Repository.Clone(String sourceUrl, String workdirPath, Boolean bare, Boolean checkout, TransferProgressHandler onTransferProgress, CheckoutProgressHandler onCheckoutProgress) in c:\work\libgit2sharp\LibGit2Sharp\Repository.cs:line 431
at Program.Main() in c:\work\ConsoleApplication1\Program.cs:line 12
targetDir is never created.
If on the other hand I use HTTP transport, the Repository.Clone method works fine:
var sourceUrl = "https://github.com/libgit2/libgit2sharp";
So my question is if I am doing something wrong or if this is unsupported feature or a bug in the native git2.dll?
So my question is if I am doing something wrong or if this is unsupported feature or a bug in the native git2.dll?
A bit a both, actually.
The first exception is clearly a bug. This should not happen and will be troubleshot.
The second one requires a deeper analysis. Would you be so kind as to open a issue in the LibGit2Sharp project?
Good news are that a pull request from BenStraub was recently merged. This pull request implements the local fetch transport which should pretty solve the issue.
LibGit2Sharp will be updated in the following days with a new a new version of libgit2 binaries which should allow you perform a local clone/fetch. I'll update this answer as soon as it's been done.
Update
This test shows how do to a Clone and a Push over against a local repository.

FlourineFX rtmp ssl

I'm trying to connect to an rtmps server using C# and FluorineFX.
I'm doing this using this code
netConnection = new NetConnection();
netConnection.OnConnect += onConnect;
netConnection.NetStatus += netStatus;
netConnection.ObjectEncoding = ObjectEncoding.AMF3;
Console.WriteLine(netConnection.PlayerVersion = "WIN 10,1,85,3");
netConnection.Connect("rtmps://example.com:2099/");
example.com is replacing the real url in this example.
But this code only gives me an exception stating that:
System.UriFormatException: One of the identified items was in an invalid format
the FluorineFX webpage states that it supports rtmps, so i would think that would be the case. Any help would be greatly appreciated.
I found a github repo that adds RTMPS support into FlourineFX
https://github.com/epicvrvs/FluorineFXMods
All you need to do is follow the instructions in the top and compile it.

Disagreement between OpenSSL asn1parse and asn1Editor

I am trying to implement a SCEP service, my experience with cryptography++ is quite limited so this has been an uphill battle. Currently I am accepting a certificate request from a client, and I am working de interpret the request. The certificate request should be in the form of a CMS/PKCS#7, however I am having great difficulties interpreting it:
When using the ASN.1 edtor at http://lipingshare.com/Asn1Editor/ I just get "Failed to read data".
When using 'openssl asn1parse -inform DER < bytes' on Linux I get something which seems quite sensible. The application should run on Windows .NET so the detr into linux was mainly one of despair.
Trying to decode in .NET fails:
byte[] data = Convert.FromBase64String( input_message );
SignedCms signerInfo = new SignedCms();
EnvelopedCms contentInfo = new EnvelopedCms();
signerInfo.decode(data);
contentInfo.Decode( signerInfo.ContentInfo.Content );
contentInfo.Decrypt();[*]
[*]: This fails with a CryptographicException and message: "Cannot find object or property".
Trying to decode with BouncyCastle .NET classes fails:
byte[] data = Convert.FromBase64String( input_message );
Org.BouncyCastle.Cms.CmsSignedData signedData = new CmsDignedData( data );
Org.BouncyCastle.Cms.CmsEnvelopedData ed = new CmsEnvelopedData( signedD.ContentInfo);[*]
[*] This fails with "ArgumentException" and message: "unknown object in factor: BerTaggedObject".
I realize this does not satisfy StackOverflows requirements of a clear and concise question; but I guess that just reflects the lack of clearness on my side :-( Basically I would be very grateful for any tips on how to to interpret a SCEP message (CMS/PKCS#7) in .NET, using either standard Windows classes or the BouncyCastle API; but to conclude with some concrete questions:
Can I infer something from the fact that asn1parse on Linux seems to handle my message, whereas the Lipingshare Asn.1 editor fails?
The SCEP standards says that the CMS message should be BER encoded; whereas the asn1parse programs takes a '-inform DER' switch (and still works...), and the BouncyCastle class seems to complain about a BERTaggedObject.
Grateful for any ideas, thoughts or suggestions.
Joakim

verbot 5 sdk - loading KnowledgeBases

I'm looking for help from anyone who's worked with the verbot sdk.
I'm making a program that I want to use the LearnedKnowledge.vkb, Teacher.vkb, and any standard bot (julia, for example). Those who've used this before will know that with the rules in Teacher, you can essentially write responses to things that the bot doesn't understand, and train it on the fly.
I'm planning on using speech recognition and text-to-speech, but my problem right now is that after I load the knowledgebases, I can't seem to get any response from the bot.
Here's what I have: The Verbot5Library.dll, from verbots.sourceforge.net (I got the editor and player too, to make sure the files were working). In my program, I set up the variables as such:
Verbot5Engine verbot = new Verbot5Engine();
KnowledgeBase kb = new KnowledgeBase();
KnowledgeBaseItem kbi = new KnowledgeBaseItem();
State state = new State();
XMLToolbox xmlToolboxKB = new XMLToolbox(typeof(KnowledgeBase));
Then I initialize the verbot engine and load the kbs:
// using the xmlToolboxKB method I saw in this forum: http://www.verbots.com/forums/viewtopic.php?t=2984
kbi.Fullpath = #"C:\\[full path to kb...]\\";
kbi.Filename = "LearnedKnowledge.vkb";
kb = (KnowledgeBase)xmlToolboxKB.LoadXML(kbi.Fullpath + kbi.Filename);
verbot.AddKnowledgeBase(kb, kbi);
kbi.Filename = "julia.vkb";
kb = (KnowledgeBase)xmlToolboxKB.LoadXML(kbi.Fullpath + kbi.Filename);
verbot.AddKnowledgeBase(kb, kbi);
//trying to use LoadKnowledgeBase and LoadCompiledKnowledgeBase methods: verbot.LoadKnowledgeBase("C:\\[full path to kb...]\\LearnedKnowledge.vkb");
//verbot.LoadCompiledKnowledgeBase("C:\\[full path...]\\julia.ckb");
//verbot.LoadCompiledKnowledgeBase("C:\\[full path...]\\Teacher.ckb");
// set up state
state.CurrentKBs.Add("C:\\[full path...]\\LearnedKnowledge.vkb");
state.CurrentKBs.Add("C:\\[full path...]\\Teacher.vkb");
state.CurrentKBs.Add("C:\\[full path...]\\julia.ckb");
Finally, I attempt to get a response from the verbot engine:
Reply reply = verbot.GetReply("hello", state);
if (reply != null)
Console.WriteLine(reply.AgentText);
else
Console.WriteLine("No reply found.");
I know julia has a response for "hello", as I've tested it with the editor. But all it ever returns is "No reply found". This code has been taken from the example console program in the SDK download (as very little documentation is available). That's why I need some pointers from someone who's familiar with the SDK.
Am I not loading the KBs correctly? Do they all need to be compiled (.ckb) instead of the XML files (.vkb)? I've used the verbot.OnKnowledgeBaseLoadError event handler and I get no errors. I even removed the resource file Default.vsn needed to load the Teacher, and it throws an error when trying to load it so I'm pretty sure it's all loading correctly. So why do I always get "No reply found"?
resolved: see http://www.verbots.com/forums/viewtopic.php?p=13021#13021

Categories

Resources