So I'm trying to use TweetSharp in VB.NET 2012 with C# to post a tweet with a image.
I found the code example of how to do it:
service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = "message",
Images = dictionary
}
);
However I'm not sure how to create the "dictionary" with the picture stream.
I tried this:
Dictionary<string, Stream> imageDict = new Dictionary<string, Stream>();
then referenced that later:
Images = imageDict
But it gives the error:
Error Screenshot
Anyone have any ideas of how this is supposed to work?
Another block of code I found and tried is:
using (var stream = new FileStream("Image.jpg", FileMode.Open))
{
var result = tservice.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = "Message",
Images = new Dictionary<string, Stream> { { "john", stream } }
});
lblResult.Text = result.Text.ToString();
}
But it gives the same error about "FileStream".
You need to add a reference to the System.IO namespace, this is why you receive this error in the image you posted.
Here is an example:
var thumb = "http://somesite.net/imageurl";
var service = new TwitterService(key, secret);
service.AuthenticateWith(token, tokenSecret);
var req = WebRequest.Create(thumb);
using (var stream = req.GetResponse().GetResponseStream())
{
response = service.SendTweetWithMedia(new SendTweetWithMediaOptions
{
Status = tweet.Trim(),
Images = new Dictionary<string, Stream> { { fullname, stream } }
});
}
A GIF may fail during Tweet creation even if it is within the file size limit. Adhere to the following constraints to improve success rates.
Resolution should be <= 1280x1080 (width x height)
Number of frames <= 350
Number of pixels (width * height * num_frames) <= 300 million
Filesize <= 15Mb
Related
I am using the following code to upload video on Vimeo. I want to add filename as video title currently I am getting Untitled video with the above code
please guide me how to add Title/Name
public async Task<IActionResult> UploadVideos([FromForm] IFormFile videoFile)
{
string tagName = "tagName";
//var files = Request.Form.Files;
//IFormFile file = files[0];
string uploadStatus = "";
var getVideo = new Video();
try
{
if (videoFile != null)
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
VimeoClient vimeoClient = new VimeoClient(accessToken);
var authcheck = await vimeoClient.GetAccountInformationAsync();
if (authcheck.Name != null)
{
IUploadRequest uploadRequest = new UploadRequest();
//Stream stream = file.OpenReadStream();
//using(var memoryStream = new MemoryStream())
//{
// stream.CopyTo(memoryStream);
// memoryStream.ToArray();
//}
BinaryContent binaryContent = new BinaryContent(obj.videoFile.OpenReadStream(), obj.videoFile.ContentType);
int chunkSize = 0;
int contentLength = Convert.ToInt32(obj.videoFile.Length);
int temp1 = contentLength / 1024;
binaryContent.OriginalFileName = "Test Name";
if (temp1 > 1)
{
chunkSize = temp1 / 1024;
if (chunkSize == 0)
{
chunkSize = 1048576;
}
else
{
if (chunkSize > 10)
{
chunkSize = chunkSize / 10;
}
chunkSize = chunkSize * 1048576;
}
}
else
{
chunkSize = 1048576;
}
var checkChunk = chunkSize;
var status = "uploading";
uploadRequest = await vimeoClient.UploadEntireFileAsync(binaryContent, chunkSize, null);
var _tag = tagName;
var tagVideo = await vimeoClient.AddVideoTagAsync(uploadRequest.ClipId.GetValueOrDefault(), _tag);
while (status != "available")
{
getVideo = await vimeoClient.GetVideoAsync(long.Parse(uploadRequest.ClipId.Value.ToString()));
status = getVideo.Status;
}
uploadStatus = String.Concat("file Uploaded ", getVideo.Files[0].LinkSecure);
}
}
return Ok(new { status = uploadStatus, video = getVideo });
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
I tried to set title with this binaryContent.OriginalFileName but its results untitled video. Please guide by providing the modification required in the api
I try to refer to the Vimeo documentation and come to know that you could use the Pull approach or you could set metadata for the video to set the title.
Video uploads on Vimeo include metadata such as the name of the video and the video's privacy settings. Besides being useful as titles and text descriptors, metadata are also a key component in strategies for search engine optimization.
You can specify values for a video's metadata fields in the body of the initial POST request of an upload, like this:
{
"upload": {
"approach": "tus",
"size": 800000000
},
"name": "My Video",
"privacy": { "view": "nobody" }
}
If you don’t specify a name for your video, we automatically give it the name Untitled, unless you upload it with the pull approach. In that case, we use the file name of the video.
For more detailed information, please refer to Setting video metadata point in this document.
I have successfully used Grpc in Unity and sent request to Dialog flow and received response. You can check the details here
However the whole returned result is the following only
{ "queryResult": { "languageCode": "ja" } }
The expected response id, query text, etc are not returned.
When testing in console.dialogflow.com I get the following result
{
"responseId": "cdf8003e-6599-4a28-9314-f4462c36e21b",
"queryResult": {
"queryText": "おはようございます",
"speechRecognitionConfidence": 0.92638445,
"languageCode": "ja"
}
}
However when I tried in console.dialogflow.com and didn't say anything I got
{ "queryResult": { "languageCode": "ja" } }
So perhaps the InputAudio encoding is wrong somehow.
Here's how I do it
var serializedByteArray = convertToBytes(samples);
request.InputAudio = Google.Protobuf.ByteString.CopyFrom(serializedByteArray);
And convert to bytes is like the following
public static byte[] convertToBytes(float[] audio)
{
List<byte> bytes = new List<byte>();
foreach (float audioI in audio) {
bytes.AddRange(BitConverter.GetBytes(audioI));
}
return bytes.ToArray();
}
The audio source is define as follows where sampleRate is 16000
audioSource.clip = Microphone.Start(null, true, 30, sampleRate);
I made sure to set sample rate hz properly.
queryInput.AudioConfig.SampleRateHertz = sampleRate;
Edit:
I have logged the recorded bytes from unity to a file (have all the bytes streamed appended together) and have written a console application to test the binary generated but using DetectIntent rather than streaming detect intent.
GoogleCredential credential = GoogleCredential.FromJson(privateKey);
var url = "dialogflow.googleapis.com";
Grpc.Core.Channel channel = new Grpc.Core.Channel(url, credential.ToChannelCredentials());
var client = SessionsClient.Create(channel);
CallOptions options = new CallOptions();
DetectIntentRequest detectIntentRequest = new DetectIntentRequest();
detectIntentRequest.Session = "projects/projectid/agent/sessions/" + "detectIntent";
QueryInput queryInput = new QueryInput();
queryInput.AudioConfig = new InputAudioConfig();
queryInput.AudioConfig.LanguageCode = "ja";
queryInput.AudioConfig.SampleRateHertz = sampleRate;//must be between 8khz and 48khz
queryInput.AudioConfig.AudioEncoding = AudioEncoding.Linear16;
detectIntentRequest.QueryInput = queryInput;
detectIntentRequest.InputAudio = Google.Protobuf.ByteString.CopyFrom(File.ReadAllBytes("D:\\temp\\audio.bytes"));
var response = client.DetectIntent(detectIntentRequest);
Console.WriteLine(response.ToString());
Console.WriteLine(response.ResponseId);
Console.Read();
I still get this (and empty response.ResponseId)
{ "queryResult": { "languageCode": "ja" } }
Thanks for advance.
Finally found the answer. The way I converted the datasource float to linear16 byte array was obviously wrong. Here's the code that worked
Credits to that post on unity forum.
https://forum.unity.com/threads/writing-audiolistener-getoutputdata-to-wav-problem.119295/#post-899142
public static byte[] convertToBytes(float[] dataSource)
{
var intData = new Int16[dataSource.Length];
//converting in 2 steps : float[] to Int16[], //then Int16[] to Byte[]
var bytesData = new Byte[dataSource.Length * 2];
//bytesData array is twice the size of
//dataSource array because a float converted in Int16 is 2 bytes.
var rescaleFactor = 32767; //to convert float to Int16
for (var i = 0; i < dataSource.Length; i++)
{
intData[i] = (short)(dataSource[i] * rescaleFactor);
var byteArr = new byte[2];
byteArr = BitConverter.GetBytes(intData[i]);
byteArr.CopyTo(bytesData, i * 2);
}
return bytesData;
}
I am using the following method to post to a web service. When I use it, I constantly get a 400 error. If I use the same data that I pass in though using Posty, the service returns the expected data
public static async Task<T> SendData<T>(string apiToUse, params string[] data)
{
var url = string.Format("{0}/{1}", Constants.BaseTestUrl, apiToUse);
dynamic t;
var kvp = new Dictionary<string, string>();
for (var i = 0; i < data.Length; i += 2)
{
kvp.Add(data[i], data[i + 1]);
}
var dta = new FormUrlEncodedContent(kvp);
dta.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
using (var client = new HttpClient())
{
var result = client.PostAsync(url, dta).Result;
//result.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
var rv = result.Content.ReadAsStringAsync().Result;
t = JsonConvert.DeserializeObject<T>(rv);
}
return t;
}
In my test example, I pass into the param string[] data the two keys and two values.
The only thing that I can see that is different is that on posty I have the Content-Type defined before I click send (which I have also done here).
This is driving me somewhat insane, so any pointers would be appreciated.
It's hard to provide a complete answer without exactly knowing how the request should look like. Can you try / adjust the code as follows:
var kvp = string.Empty;
for (var i = 0; i < data.Length; i += 2)
{
kvp += string.Format("{0}={1}; ", data[i], data[i+1]);
}
// remove last ';' character
kvp = kvp.TrimEnd(new char[] { ' ', ';' });
var dta = new MultipartFormDataContent();
dta.Add(new StringContent(kvp));
The change consists in using MultipartFormDataContent to comply with the request format. Obviously, this code is just for testing. Additional validation and content creation (kvp) should be done before placing it into production.
I'm using Ghostscript.NET, a handy C# wrapper for Ghostscript functionality. I have a batch of PDFs being sent from the clientside to be converted to images on the ASP .NET WebAPI server and returned to the client.
public static IEnumerable<Image> PdfToImagesGhostscript(byte[] binaryPdfData, int dpi)
{
List<Image> pagesAsImages = new List<Image>();
GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(AppDomain.CurrentDomain.BaseDirectory + #"\bin\gsdll32.dll");
using (var pdfDataStream = new MemoryStream(binaryPdfData))
using (var rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
{
rasterizer.Open(pdfDataStream, gvi, true);
for (int i = 1; i <= rasterizer.PageCount; i++)
{
Image pageAsImage = rasterizer.GetPage(dpi, dpi, i); // Out of Memory Exception on this line
pagesAsImages.Add(pageAsImage);
}
}
return pagesAsImages;
}
This generally works fine (I generally use 500 dpi, which I know is high, but even dropping to 300 I can reproduce this error). But if I give it many PDFs from the clientside (150 1-page PDFs, for example) it will often hit an Out of Memory Exception in Ghostscript.NET Rasterizer. How can I overcome this? Should this be threaded? If so how would that work? Would it help to use the 64 bit version of GhostScript? Thanks in advance.
I'm new to this myself, on here looking for techniques.
According to the example in the documentation here, they show this:
for (int page = 1; page <= _rasterizer.PageCount; page++)
{
var docName = String.Format("Page-{0}.pdf", page);
var pageFilePath = Path.Combine(outputPath, docName);
var pdf = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
pdf.Save(pageFilePath);
pagesAsImages.Add(pdf);
}
It looks like you aren't saving your files.
I am still working at getting something similar to this to work on my end as well. Currently, I have 2 methods that I'm going to try, using the GhostscriptProcessor first:
private static void GhostscriptNetProcess(String fileName, String outputPath)
{
var version = Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion();
var source = (fileName.IndexOf(' ') == -1) ? fileName : String.Format("\"{0}\"", fileName);
var gsArgs = new List<String>();
gsArgs.Add("-q");
gsArgs.Add("-dNOPAUSE");
gsArgs.Add("-dNOPROMPT");
gsArgs.Add("-sDEVICE=pdfwrite");
gsArgs.Add(String.Format(#"-sOutputFile={0}", outputPath));
gsArgs.Add(source);
var processor = new Ghostscript.NET.Processor.GhostscriptProcessor(version, false);
processor.Process(gsArgs.ToArray());
}
This version below is similar to yours, and what I started out using until I started finding other code examples:
private static void GhostscriptNetRaster(String fileName, String outputPath)
{
var version = Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion();
using (var rasterizer = new Ghostscript.NET.Rasterizer.GhostscriptRasterizer())
{
rasterizer.Open(File.Open(fileName, FileMode.Open, FileAccess.Read), version, false);
for (int page = 0; page < rasterizer.PageCount; page++)
{
var img = rasterizer.GetPage(96, 96, page);
img.Save(outputPath);
}
}
}
Does that get you anywhere?
You don't have to rasterize all pages at the same GhostscriptRasterizer instance. Use disposable rasterizer on each page and collect results in List Image or List byte[] .
Example with results List of Jpeg encoded byte arrays.
List<byte[]> result = new List<byte[]>();
for (int i = 1; i <= pdfPagesCount; i++)
{
using (var pageRasterizer = new GhostscriptRasterizer())
{
pageRasterizer.Open(stream, gsVersion, true);
using (Image tempImage = pageRasterizer.GetPage(dpiX, dpiY, i))
{
var encoder = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid);
var encoderParams = new EncoderParameters() { Param = new[] { new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L) } };
using (MemoryStream memoryStream = new MemoryStream())
{
tempImage.Save(memoryStream, encoder, encoderParams);
result.Add(memoryStream.ToArray());
}
}
}
}
If you don't know number of pages in PDF you could call rasterizer one time, and get PageCount property.
I having an issue uploading / sending images from a stream to a generic handler in ASP.NET. I’ve build a windows phone app that can take an image and send it to the generic handler on my website.
Unfortunately in some occasions the image turns out to be (partially) gray. I think it might have something to to with a lost/bad internet connection of the mobile device. This problem happens every 50 images or so.
When the faulty image is send I do not get an error of any kind. I’m looking for two possible solutions.
How do i prevent the windows phone uploading a partially gray image to the generic handler.
How do i check if an image is partially gray on the server so can send a error message back to the phone.
to make this question more compleet I included the code of the generic handler and an example image. Second I’m very curious why this occus. TCPIP has an handshake so above isseu should not be possible ?
public class UploadImages : IHttpHandler
{
private IWorkOrderRepository _workOrderRepository;
private IDigitalFileRepository _digitalFileRepository;
private IUserRepository _userRepository;
public UploadImages()
{
_workOrderRepository = ((Global)HttpContext.Current.ApplicationInstance).Kernel.Get<IWorkOrderRepository>();
_digitalFileRepository = ((Global)HttpContext.Current.ApplicationInstance).Kernel.Get<IDigitalFileRepository>();
_userRepository = ((Global)HttpContext.Current.ApplicationInstance).Kernel.Get<IUserRepository>();
}
public void ProcessRequest(HttpContext context)
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
var user = (Domain.Users.User)HttpContext.Current.User;
string WorkOrderId = context.Request.QueryString["workOrderId"];
string latitude = context.Request.QueryString["LATITUDE"];
string Longitude = context.Request.QueryString["LONGITUDE"];
if (latitude != "0" && Longitude != "0")
{
string file = "Filename.jpg";
string uploadPath = context.Server.MapPath("~/Temp/");
using (var stream = new MemoryStream())
{
var image = ImageResizer.Resize(Image.FromStream(context.Request.InputStream), 700);
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var workOrder = _workOrderRepository.GetAll(x => x.Id == Convert.ToInt32(WorkOrderId)).FirstOrDefault();
workOrder.AddPhoto(_workOrderRepository, _digitalFileRepository, new AuditInfo((Domain.Users.User)user), stream, file, "image/jpeg", Convert.ToDouble(latitude), Convert.ToDouble(Longitude));
}
}
else
{
string file = "Filename.jpg";
string uploadPath = context.Server.MapPath("~/Temp/");
using (var stream = new MemoryStream())
{
var image = ImageResizer.Resize(Image.FromStream(context.Request.InputStream), 700);
image.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
var workOrder = _workOrderRepository.GetAll(x => x.Id == Convert.ToInt32(WorkOrderId)).FirstOrDefault();
workOrder.AddPhoto(_workOrderRepository, _digitalFileRepository, new AuditInfo((Domain.Users.User)user), stream, file, "image/jpeg");
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}