I have develop a ASP.NET (C#) application to store the images and videos into Amazon S3. Images are being uploaded fine but when i try to upload videos it saves as an image format in Amazon S3.
Does anyone know what the issue is or how to I can upload videos?
private void Amzon(string imageName,string imgcontenttype,int imglength,byte[] fileData)
{
AmazonS3 myS3 = new AmazonS3();
DateTime myTime = DateTime.Now;
// Create a signature for this operation
string strMySignature = S3Helper.GetSignature(mySecretAccessKeyId, "PutObjectInline", myTime);
// Create a new Access grant for anonymous users.
Grant myGrant = new Grant();
Grant[] myGrants = new Grant[1];
// Setup Access control, allow Read access to all
Group myGroup = new Group();
myGroup.URI = "http://acs.amazonaws.com/groups/global/AllUsers";
myGrant.Grantee = myGroup;
myGrant.Permission = Permission.READ;
myGrants[0] = myGrant;
string key = imageName;
// Setup some metadata to indicate the content type
MetadataEntry myContentType = new MetadataEntry();
myContentType.Name = "ContentType";
myContentType.Value = imgcontenttype;
MetadataEntry[] myMetaData = new MetadataEntry[1];
myMetaData[0] = myContentType;
// Finally upload the object
PutObjectResult myResult = myS3.PutObjectInline(
bucketname,
key,
myMetaData,
fileData,
imglength,
myGrants,
StorageClass.STANDARD,
true,
myAWSAccessKeyId,
S3Helper.GetTimeStamp(myTime),
true,
strMySignature, null
);
// Print out the results.
if (myResult != null)
{
cn.Open();
Url = "https://s3.amazonaws.com/" + bucketname + "/" + key;
string Query = "Insert into S3Image(ImageName,ImageUrl)Values('" + key + "','" + Url + "')";
SqlCommand cmd = new SqlCommand(Query, cn);
cmd.ExecuteNonQuery();
cn.Close();
//MyPrint("ETag: " + myResult.ETag);
MyPrint("<img src=https://s3.amazonaws.com/" + bucketname + "/" + key);
}
}
Thank you.
There's a lot of code to get up and running with Amazon's web service. I think this part of code is what you need, you might not be setting the right content type:
// Setup some metadata to indicate the content type
MetadataEntry myContentType = new MetadataEntry();
myContentType.Name = "ContentType";
myContentType.Value = FileUpload1.PostedFile.ContentType;
Here's the full code: Enjoy.
`private const string accessKeyId = "REMOVED";
private const string secretAccessKey = "REMOVED";
private static DateTime GetTimeStamp(DateTime myTime)
{
DateTime myUniversalTime = myTime.ToUniversalTime();
DateTime myNewTime = new DateTime(myUniversalTime.Year,
myUniversalTime.Month, myUniversalTime.Day,
myUniversalTime.Hour, myUniversalTime.Minute,
myUniversalTime.Second, myUniversalTime.Millisecond);
return myNewTime;
}
private static string GetSignature(string secretAccessKey, string strOperation, DateTime myTime)
{
Encoding myEncoding = new UTF8Encoding();
// Create the source string which is used to create the digest
string mySource = "AmazonS3" + strOperation + FormatTimeStamp(myTime);
// Create a new Cryptography class using the
// Secret Access Key as the key
HMACSHA1 myCrypto = new HMACSHA1(myEncoding.GetBytes(secretAccessKey));
// Convert the source string to an array of bytes
char[] mySourceArray = mySource.ToCharArray();
// Convert the source to a UTF8 encoded array of bytes
byte[] myUTF8Bytes = myEncoding.GetBytes(mySourceArray);
// Calculate the digest
byte[] strDigest = myCrypto.ComputeHash(myUTF8Bytes);
return Convert.ToBase64String(strDigest);
}
private static string FormatTimeStamp(DateTime myTime)
{
DateTime myUniversalTime = myTime.ToUniversalTime();
return myUniversalTime.ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z", System.Globalization.CultureInfo.InvariantCulture);
}
/// <summary>
/// Upload Images.
/// </summary>
/// <param name="a">Ex. FileUpload1.PostedFile.ContentType</param>
/// <param name="b">Ex. FileUpload1.PostedFile.FileName</param>
/// <param name="c">Ex. FileUpload1.FileBytes</param>
/// <param name="d">Ex. FileUpload1.FileBytes.Length</param>
/// <param name="id">The ID for this Product Group</param>
public void UploadImage_ProductGroup(string a, string b, byte[] c, long d, int id)
{
AmazonS3 myS3 = new AmazonS3();
DateTime myTime = DateTime.Now;
// Create a signature for this operation
string strMySignature = GetSignature(
secretAccessKey,
"PutObjectInline",
myTime);
// Create a new Access grant for anonymous users.
Grant myGrant = new Grant();
Grant[] myGrants = new Grant[1];
// Setup Access control, allow Read access to all
Group myGroup = new Group();
myGroup.URI = "http://acs.amazonaws.com/groups/global/AllUsers";
myGrant.Grantee = myGroup;
myGrant.Permission = Permission.READ;
myGrants[0] = myGrant;
// Setup some metadata to indicate the content type
MetadataEntry myContentType = new MetadataEntry();
myContentType.Name = "ContentType";
myContentType.Value = a;
MetadataEntry[] myMetaData = new MetadataEntry[1];
myMetaData[0] = myContentType;
//Format the file name to prepend thumbnail before the file extension.
/* int lastIndex = b.LastIndexOf('.');
string fileName = b.Remove(lastIndex);
string ext = b.Remove(0, lastIndex);
string thumbPath = string.Format("images/public/{0}thumb{1}",fileName,ext);
//Resize the thumbnail
*/
// Finally upload the object
PutObjectResult myResult = myS3.PutObjectInline(
"mywebsite",
"images/public/" + b,
myMetaData,
c,
d,
myGrants,
StorageClass.STANDARD,
true,
accessKeyId,
GetTimeStamp(myTime),
true,
strMySignature, null
);`
Related
The first part of the program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered. (Which I have done)
The second part, the user will enter a specific "to" and "from" date.
Using the signature obtained from the first part and the dates that the user enters, the program should pass this information to an API address and obtain information accordingly.
My question is that I am not sure how to pass the obtained signature to the new API address + the "to" and "from" date.
The first part of the program to retrieve the signature (works perfectly):
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
string signame = status.Select(js => js.signature).First();
return signame;
}
The second part that I have written so far:
public string[] GetTime(double fromDate, double toDate, string username)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlNcert), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string url = "";
url = StaticStrings.UrlNcert + username + "&fromDate=" + fromDate + "&toDate=" + toDate;
var respons = wc.DownloadString(url);
OracleHour ndata = JsonConvert.DeserializeObject<OracleHour>(respons);
var Get_Odnum = ndata.orderNumber;
var Dt_Work = ndata.dateOfWork;
var hrType = ndata.hourType;
var hr = ndata.hours;
var des = ndata.description;
var surname = ndata.surveyor;
string[] myncertdata = { Get_Odnum, Dt_Work.ToString(), hrType, hr.ToString(), des, surname };
return myncertdata;
}
}
}
The API strings:
namespace TimeSheets_Try_11.Controllers
{
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT" + #"\";
}
}
For example if we are using the name "Jane Dow" from the date 9/22/20 - 9/29/20, the api strings will be
UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/Jane
UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost?user=VERIT\JDOW&fromDate=2020-09-22&toDate=2020-09-29"
Trivial way - change UrlNcert to url without query at first:
class StaticStrings
{
public static string UrlIora = "https://iora.dnvgl.com/api/dictionary/employee/";
public static string UrlNcert = "https://cmcservices.dnvgl.com/Finance/api/oracleReportingCost";
}
Then in your api call get values for username, fromDate and toDate and use string interpolation.
var url = $"{StaticStrings.UrlNcert}?user={username}&fromDate={fromDate:yyyy-MM-dd}&toDate={toDate:yyyy-MM-dd}";
If you want more complex way, check UriBuilder
I'm trying to create a HTTP url request to get Amazon items by its ASIN Array. I'm using the same code in my Objective-c code for the same reason and it's work perfectly.
But i'm getting this messeage everytime i try to access the url in my chrome:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
This is the code i'm using:
private void GetFinalUrlForAsinArray(ArrayList asinArr)
{
String timeStamp = GetTimeStamp();
String amazonAPIUrl = "http://webservices.amazon.com/onca/xml?";
ArrayList param = new ArrayList();
param.Add("AWSAccessKeyId=myawsaccesskeyid");
param.Add("AssociateTag=myassociatetag");
param.Add("IdType=ASIN");
param.Add(string.Join(",", asinArr.ToArray()));
param.Add("Operation=ItemLookup");
param.Add("ResponseGroup=ItemAttributes,Offers");
param.Add("Service=AWSECommerceService");
param.Add(String.Format("Timestamp={0}", timeStamp));
amazonAPIUrl += string.Join("&", param.ToArray());
string queryString = new System.Uri(amazonAPIUrl).Query;
var queryDictionary = HttpUtility.ParseQueryString(queryString);
ArrayList queryItemsNew = new ArrayList();
foreach (var query in queryDictionary)
{
String name = HttpUtility.UrlEncode((string)query);
String value = HttpUtility.UrlEncode((string)queryDictionary.Get((string)query));
queryItemsNew.Add(String.Format("{0}={1}", name,value));
}
String path = string.Join("&", queryItemsNew.ToArray());
String finalPath = String.Format("GET\nwebservices.amazon.com\n/onca/xml\n{0}",path);
string signature = HmacSha256Digest(finalPath);
String finalUrl = String.Format("http://webservices.amazon.com/onca/xml?{0}&Signature={1}", path, signature);
}
private String GetTimeStamp()
{
DateTime d = DateTime.UtcNow;
String str = d.ToString("yyyy-MM-dd''T''HH:mm:ss''Z''");
return str;
}
private static string HmacSha256Digest(string message)
{
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA256 hmac = new HMACSHA256(encoding.GetBytes(mysecret));
string signature = Convert.ToBase64String(hmac.ComputeHash(encoding.GetBytes(message)));
String sigEncoded = Uri.EscapeDataString(signature);
return sigEncoded;
}
Having had a look at the API documentation it looks like you've missed the ItemId key here:
param.Add(string.Join(",", asinArr.ToArray()));
I'm guessing you meant it to be:
param.Add("ItemId=" + string.Join(",", asinArr.ToArray()));
It otherwise looks to comply with the spec, the only other thing I noted was the example had the URL encoding as uppercase i.e. %3A rather than the C# default %3a.
Amazingly low on doco when it comes to rest api. Can anyone give me a working example of Sugar CRM REST calls using C#?
I was trying out SugarSharp but it's just listing the services and not coming up with Data(null)
Appreciate this is an old question but for anyone else that comes across it, took me a while to get it all working with creating and updating relationships being the toughest to fathom.
Here is part of a wrapper class I wrote around the v4_1 rest api, hope it helps:-
public void Login()
{
object loginData = new
{
user_auth = new
{
user_name = Username,
password = CalculateMD5Hash(Password)
}
};
string jsonData = CreateFormattedPostRequest("login", loginData);
var request = GetRestRequest(jsonData, "POST");
var loginResponse = GetRestResponseByType<LoginResponse>(request);
if (string.IsNullOrEmpty(loginResponse.id))
{
throw new SugarException(string.Concat("Authorisation Failed for user: {0}, did not retrieve access token", Username));
}
SessionID = loginResponse.id;
}
Format the request:-
private string CreateFormattedPostRequest(string method, object data)
{
StringBuilder buffer = new StringBuilder();
using (StringWriter writer = new StringWriter(buffer))
{
serializer.Serialize(data, buffer);
}
string result = "method=" + method;
result += "&input_type=JSON&response_type=JSON&rest_data=" + buffer.ToString();
return result;
}
And finally get the response:-
private object GetRestResponseAsObject(HttpWebRequest request)
{
using (var response = (HttpWebResponse)request.GetResponse())
{
using (Stream input = response.GetResponseStream())
{
StreamReader reader = new StreamReader(input);
string buffer = reader.ReadToEnd();
var responseObj = serializer.DeserializeObject(buffer);
return responseObj;
}
}
}
And here is an example call to the set_entry method:-
/// <summary>
/// Creates or Updates a single bean, for update ensure that the name_value_list contains the ID of the record
/// name_value_lists - Dictionary where the keys of the are the SugarBean attributes (columns), the values of the array are the values the attributes should have.
/// </summary>
/// <param name="module">Module to update i.e Account</param>
/// <param name="record">key value pair object of record, include ID for update</param>
/// <returns>Returns the updated or created Bean ID</returns>
public string CreateUpdateBean(string module, object record)
{
var parameters = new Dictionary<string, object>();
parameters.Add("session", SessionID);
parameters.Add("module_name", module);
parameters.Add("name_value_list", record);
parameters.Add("track_view", false);
string jsonData = CreateFormattedPostRequest("set_entry", parameters);
var request = GetRestRequest(jsonData, "POST");
var result = GetRestResponseByType<object>(request);
return result.ToString();
}
For calling rest api SugarCRM/SuiteCRM with c#, you can use SugarRestSharp
Example for create Account:
var client = new SugarRestClient(TestAccount.Url, TestAccount.Username, TestAccount.Password);
Account insertAccount = AccountsModule.GetTestAccount();
// -------------------Create Account-------------------
SugarRestResponse response = AccountsModule.CreateAccount(client, insertAccount);
Assert.NotNull(response);
Assert.Equal(response.StatusCode, HttpStatusCode.OK);
string insertId = (response.Data == null) ? string.Empty : response.Data.ToString();
Assert.NotNull(insertId);
Assert.NotEmpty(insertId);
// -------------------End Create Account-------------------
How can I call eBay and request it to return search results array?
This is what I came up with so far:
string endpoint = "https://api.ebay.com/wsapi";
string siteId = "0";
string appId = "*"; // use your app ID
string devId = "*"; // use your dev ID
string certId = "*"; // use your cert ID
string version = "405";
string requestURL = endpoint
+ "?callname=FindProducts"
+ "&siteid=" + siteId
+ "&appid=" + appId
+ "&version=" + version
+ "&routing=default"
+ "&AvailableItemsOnly=true"
+ "&QueryKeywords=nvidia"
+ "&itemFilter(0).name=ListingType"
+ "&itemFilter(0).value(0)=FixedPrice"
+ "&itemFilter(0).value(1)=Auction"
+ "&CategoryID=27386";
How can I wrap it into request and get a response in some-sort of data-structure? I have gotten the SDK.
I needed to use the eBay finding API;
public GetItemCall getItemDataFromEbay(String itemId)
{
ApiContext oContext = new ApiContext();
oContext.ApiCredential.ApiAccount.Developer = ""; // use your dev ID
oContext.ApiCredential.ApiAccount.Application = ""; // use your app ID
oContext.ApiCredential.ApiAccount.Certificate = ""; // use your cert ID
oContext.ApiCredential.eBayToken = ""; //set the AuthToken
//set the endpoint (sandbox) use https://api.ebay.com/wsapi for production
oContext.SoapApiServerUrl = "https://api.ebay.com/wsapi";
//set the Site of the Context
oContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;
//the WSDL Version used for this SDK build
oContext.Version = "735";
//very important, let's setup the logging
ApiLogManager oLogManager = new ApiLogManager();
oLogManager.ApiLoggerList.Add(new eBay.Service.Util.FileLogger("GetItem.log", true, true, true));
oLogManager.EnableLogging = true;
oContext.ApiLogManager = oLogManager;
GetItemCall oGetItemCall = new GetItemCall(oContext);
//' set the Version used in the call
oGetItemCall.Version = oContext.Version;
//' set the Site of the call
oGetItemCall.Site = oContext.Site;
//' enable the compression feature
oGetItemCall.EnableCompression = true;
oGetItemCall.DetailLevelList.Add(eBay.Service.Core.Soap.DetailLevelCodeType.ReturnAll);
oGetItemCall.ItemID = itemId;
try
{
oGetItemCall.GetItem(oGetItemCall.ItemID);
}
catch (Exception E)
{
Console.Write(E.ToString());
oGetItemCall.GetItem(itemId);
}
GC.Collect();
return oGetItemCall;
}
I'm trying to get the following to work on my machine but I get an error (Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader')
using System;
using System.IO;
using System.Reflection;
namespace com.companyname.business
{
/// <summary>
/// Summary description for SessionCreateRQClient.
/// </summary>
class SessionCreateRQClient
{
/// <summary>
/// The main entry point.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "user";
string password = "password";
string ipcc = "IPCC";
string domain = "DEFAULT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreateRQService serviceObj = new SessionCreateRQService();
serviceObj.MessageHeaderValue = msgHeader;
serviceObj.SecurityValue = security;
SessionCreateRS resp = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
msgHeader = serviceObj.MessageHeaderValue;
security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid="+msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken="+security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc="+ipcc; // IPCC to a string
File.Delete(PropsFileName); // Clean up
TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
tw.WriteLine(DateTime.Now); // Write the date for reference
tw.WriteLine(TokenLine); // Write the BinarySecurityToken
tw.WriteLine(ConvIdLine); // Write the ConversationId
tw.WriteLine(ipccLine); // Write the IPCC
tw.Close();
//Console.Read();
}
}
catch(Exception e)
{
Console.WriteLine("Exception Message : " + e.Message );
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
I have added the reference System.ServiceModel and the lines:
using System.ServiceModel;
using System.ServiceModel.Channels;
but I continue to get that error when trying to compile --
Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader'
I am using Microsoft Visual Studio 2008
Version 9.0.21022.8 RTM
Microsoft .NET Framework
Version 3.5 SP1
Professional Edition
Is there another reference I have to add? Or a dll to move over?
I wonder was the code above written for Framework 2.0 only?
Thanks for your help.
The error message is correct, you cannot create an instance of that class, it is declared abstract.
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messageheader.aspx
See if the static method MessageHeader.CreateHeader will work for you. Note there is several overloads, so pick the best one for you.