I'm currently trying retrieve list share available in my Azure account from salesforce. I'm trying to implement the example from below sample code:
https://learn.microsoft.com/en-us/rest/api/storageservices/list-shares#samplerequestandresponse
//private key: access key of my account
string storageKey =private key;
string storageName = 'accountName';
Datetime dt = Datetime.now();
string formattedDate = dt.formatGMT('EEE, dd MMM yyyy HH:mm:ss')+ ' GMT';
system.debug('formattedDate--'+formattedDate);
string CanonicalizedHeaders = 'x-ms-date:'+formattedDate+'\nx-ms-version:2016-05-31';
string CanonicalizedResource = '/' + storageName + '/\ncomp:list';
string StringToSign = 'GET\n\n\n\n\n\n\n\n\n\n\n\n' + CanonicalizedHeaders+'\n'+CanonicalizedResource;
system.debug('StringToSign--'+StringToSign);
Blob temp = EncodingUtil.base64Decode(storageKey);
Blob hmac = Crypto.generateMac('HmacSHA256',Blob.valueOf(StringToSign),temp ); //StringToSign
system.debug('oo-'+EncodingUtil.base64Encode(hmac));
HttpRequest req = new HttpRequest();
req.setMethod('GET');
//req.setHeader('content-type', 'application/xml');
req.setHeader('x-ms-version','2016-05-31' );
req.setHeader('x-ms-date', formattedDate);
string signature = EncodingUtil.base64Encode(hmac);
string authHeader = 'SharedKey salesforcestrongaccount'+':'+signature;
req.setHeader('Authorization',authHeader);
req.setEndpoint('https://<accountName>.file.core.windows.net/?comp=list');
Http http = new Http();
HTTPResponse res;
res = http.send(req);
System.debug(LoggingLevel.INFO, 'http.send result status: ' + res.getStatus());
Any help?
As Gaurav Mantri says, there are something wrong with your stringToSign. So you will get this error.
The right Shared Key Authentication is like this:
StringToSign = VERB + "\n" +
Content-Encoding + "\n" +
Content-Language + "\n" +
Content-Length + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
If-Modified-Since + "\n" +
If-Match + "\n" +
If-None-Match + "\n" +
If-Unmodified-Since + "\n" +
Range + "\n" +
CanonicalizedHeaders +
CanonicalizedResource;
Here I create a test demo, you could refer to it.
List share:
string storageAccount = "storage account";
string accessKey = "accountkey";
string resourcePath = "?comp=list";
string uri = #"https://" + storageAccount + ".file.core.windows.net/" + resourcePath;
// Web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
request.Headers["x-ms-version"] = "2015-02-21";
String stringToSign = "GET\n"
+ "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + request.Headers["x-ms-date"] + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + storageAccount + "/" + "\ncomp:list"; // resources
System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
string strAuthorization = "SharedKey " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));
request.Headers["Authorization"] = strAuthorization;
Task<WebResponse> response = request.GetResponseAsync();
HttpWebResponse responseresult = (HttpWebResponse)response.Result;
using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
{
string jsonData = r.ReadToEnd();
Console.WriteLine(jsonData);
}
Result:
Java:
private static final String account = "accountname";
private static final String key = "Key";
public static void main(String args[]) throws Exception {
// String urlString = "http://" + account + ".file.core.windows.net/sampleshare/name.txt";
String urlString = "https://" + account + ".file.core.windows.net/?comp=list";
HttpURLConnection connection = (HttpURLConnection) (new URL(urlString)).openConnection();
getFileRequest(connection, account, key);
connection.connect();
System.out.println("Response message : " + connection.getResponseMessage());
System.out.println("Response code : " + connection.getResponseCode());
BufferedReader br = null;
if (connection.getResponseCode() != 200) {
br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));
} else {
br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
}
System.out.println("Response body : " + br.readLine());
}
public static void getFileRequest(HttpURLConnection request, String account, String key) throws Exception {
SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = fmt.format(Calendar.getInstance().getTime()) + " GMT";
String stringToSign = "GET\n" + "\n" // content encoding
+ "\n" // content language
+ "\n" // content length
+ "\n" // content md5
+ "\n" // content type
+ "\n" // date
+ "\n" // if modified since
+ "\n" // if match
+ "\n" // if none match
+ "\n" // if unmodified since
+ "\n" // range
+ "x-ms-date:" + date + "\nx-ms-version:2015-02-21\n" // headers
+ "/" + account + request.getURL().getPath() + "\ncomp:list"; // resources
System.out.println("stringToSign : " + stringToSign);
String auth = getAuthenticationString(stringToSign);
request.setRequestMethod("GET");
request.setRequestProperty("x-ms-date", date);
request.setRequestProperty("x-ms-version", "2015-02-21");
request.setRequestProperty("Authorization", auth);
}
private static String getAuthenticationString(String stringToSign) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(Base64.decode(key), "HmacSHA256"));
String authKey = new String(Base64.encode(mac.doFinal(stringToSign.getBytes("UTF-8"))));
String auth = "SharedKey " + account + ":" + authKey;
return auth;
}
Related
Using com.sun.jersey.api.client.Client,ClientResponse and WebResource.
Client client = this.client;
WebResource webResource = null;
ClientResponse response = null;
String url = "";
url = "https://test.com/rest/V1/cart/" + quoteId + "/items";
webResource = client.resource(url);
String jsonString = "{\"cartItem\":{\"quote_id\":" + quoteId + ",\"id\": " + id+ ",\"qty\":" + qty + "}}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(jsonString);
JsonNode actualObj = mapper.readTree(parser);
response = webResource.header("Authorization", "Bearer " + this.token).type("application/json")
.post(ClientResponse.class, actualObj);
I have error
Illegal character in path at index 52: https://test.com/rest/V1/cart/"IerwexsKLchKYmZ1ryKZkor9RdfJ2Dp3"/items
I am passing quoteId as parameter String quoteId="IerwexsKLchKYmZ1ryKZkor9RdfJ2Dp3";
How to remove quotes for quoteId from URL?
Thank you.
I'm trying to create an attendance project. I'm using update & insert in my code. Please check my code below. I know I'm vulnerable to SQL injection.
My problem is when I tried to Time In using the same ID even if I use that same ID for time out, it displays the time out not time-in. Any idea how I can time in again using same ID?
MySqlCommand cmd = new MySqlCommand("SELECT * FROM tbl_student_list INNER JOIN attendance_tbl On tbl_student_list.ID = attendance_tbl.stud_id WHERE stud_id ='" + dataGridView1.Rows[i].Cells["Column1"].Value + "'", conn);
cmd.Parameters.AddWithValue("stud_id", dataGridView1.Rows[i].Cells["Column1"].Value);
conn.Open();
MySqlDataReader DataRead = cmd.ExecuteReader();
DataRead.Read();
This is my Update Code:
//If already Time-In execute Time-Out
if (DataRead.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataRead[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataRead[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataRead[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
conn.Close();
conn.Open();
string sqla = "Update attendance_tbl SET TimeOut = '" + Time + "' , Name ='" + dataGridView1.Rows[i].Cells["Column3"].Value + "' where stud_id = '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
cmd = new MySqlCommand(sqla, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column7"].Value = DateTime.Now.ToLongTimeString();
This is My Insert Code:
//IF Not In Execute Time-In/Not exist in tbl attendance
string sqlQu = "select ID,Name,Course,Image from tbl_student_list where ID= '" + dataGridView1.Rows[i].Cells["Column1"].Value + "'";
md = new MySqlCommand(sqlQu, conn);
MySqlDataReader DataReaders = cmd.ExecuteReader();
DataReaders.Read();
if (DataReaders.HasRows)
{
dataGridView1.Rows[i].Cells["Column3"].Value = DataReaders[1].ToString();
dataGridView1.Rows[i].Cells["Column4"].Value = DataReaders[2].ToString();
dataGridView1.Rows[i].Cells["Column2"].Value = DateTime.Now.ToString("yy/MM/dd");
byte[] images = ((byte[])DataReaders[3]);
if (images == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream mstreem = new MemoryStream(images);
pictureBox1.Image = Image.FromStream(mstreem);
Purpose f2 = new Purpose();
if (f2.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows[i].Cells["Column5"].Value = f2.Rad;
}
conn.Close();
conn.Open();
string sql = "insert into attendance_tbl(stud_id,Date,Name,Course,Purpose,TimeIn)values('" + dataGridView1.Rows[i].Cells["Column1"].Value + "','" + Date + "','" + dataGridView1.Rows[i].Cells["Column3"].Value + "','" + dataGridView1.Rows[i].Cells["Column4"].Value + "','" + dataGridView1.Rows[i].Cells["Column5"].Value + "','" + Time + "')";
cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
dataGridView1.Rows[i].Cells["Column6"].Value = DateTime.Now.ToLongTimeString();
Now am facing issue in Querybuilder api while trying with Multiple Path with Multiple Properties.
Code is attached here what I did. It is working fine one path with multiple properties and multiple path with one property. My requirement is like multiple path with multiple properties and also some predicates
suggestion would be appreciated
Map<String, String> map = new HashMap<String, String>();
ArrayList<Predicate> group = new ArrayList<Predicate>();
JSONArray jsonArray = new JSONArray();
if (null != searchPathList && searchPathList.size() > 0) {
mapCount = searchPathList.size();
for (int i = 0; i < searchPathList.size(); i++) {
//map.put("group." + (i + 1) + "_path", searchPathList.get(i));
}
}
// group.add(new Predicate("mypath1").set("path", "/content/opinion/columns"));
// group.add(new Predicate("mypath2").set("path", "/content/opinion/books"));
map.put("group.1_path","/content/opinion/columns");
map.put("group.2_path","/content/opinion/books");
map.put("type", CQJCRConstants.JCRPRIMARYTYPEPAGE);
//combine this group with OR
map.put("group.p.or", "true");
map.put("p.offset", "0");
map.put("p.hits", "full");
if (!TheCommonUtility.isEmpty(searchKeyWord)) {
/* map.put("group." + (mapCount + 1) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 1) + "_fulltext.relPath", "jcr:content/#jcr:title");
map.put("group." + (mapCount + 2) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 2) + "_fulltext.relPath", "jcr:content/#jcr:description");
map.put("group." + (mapCount + 3) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 3) + "_fulltext.relPath", "jcr:content/#cq:tags");
map.put("group." + (mapCount + 4) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 4) + "_fulltext.relPath", "jcr:content/#authorName");
map.put("group." + (mapCount + 5) + "_fulltext", searchKeyWord);
map.put("group." + (mapCount + 5) + "_fulltext.relPath", "jcr:content/#SlugName");
PredicateGroup searchpathgroup = new PredicateGroup("path");
searchpathgroup.setAllRequired(false);
searchpathgroup.add(new Predicate("mypath1").set("path", "/content/opinion/columns"));
searchpathgroup.add(new Predicate("mypath2").set("path", "/content/opinion/books"));
*/
PredicateGroup searchKeyWordgroup = new PredicateGroup("property");
searchKeyWordgroup.setAllRequired(false);
Predicate titleskPredicate = new Predicate("title");
titleskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
titleskPredicate.set("property", "fn:lower-case(#" + "jcr:content/jcr:title");
titleskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(titleskPredicate);
Predicate desskPredicate = new Predicate("description");
desskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
desskPredicate.set("property", "fn:lower-case(#" + "jcr:content/jcr:description");
desskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(desskPredicate);
Predicate tagskPredicate = new Predicate("tagssk");
tagskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
tagskPredicate.set("property", "fn:lower-case(#" + "jcr:content/cq:tags");
tagskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(tagskPredicate);
Predicate authorNameskPredicate = new Predicate("authorNameSk");
authorNameskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
authorNameskPredicate.set("property", "fn:lower-case(#" + JcrConstants.JCR_CONTENT + "/" + "authorName"
+ ")");
authorNameskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(authorNameskPredicate);
Predicate slugskPredicate = new Predicate("SlugName");
slugskPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
slugskPredicate.set("property", "fn:lower-case(#" + "jcr:content/SlugName");
slugskPredicate.set("value", "%" + searchKeyWord.toLowerCase() + "%");
searchKeyWordgroup.add(slugskPredicate);
group.add(searchKeyWordgroup);
}
Predicate notPredicate = new Predicate("hideInNav", "property");
notPredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_NOT);
notPredicate.set("property", JcrConstants.JCR_CONTENT + "/" + "hideInNav");
notPredicate.set("value", "true");
group.add(notPredicate);
Predicate notMasterTitlePredicate = new Predicate("pageMasterNot", "property");
notMasterTitlePredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_UNEQUALS);
notMasterTitlePredicate.set("property", JcrConstants.JCR_CONTENT + "/" + JcrConstants.JCR_TITLE);
notMasterTitlePredicate.set("value", "Master Article");
group.add(notMasterTitlePredicate);
if (!ThecommonUtility.isEmpty(author)) {
Predicate authorNamePredicate = new Predicate("authorName", "property");
authorNamePredicate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
authorNamePredicate
.set("property", "fn:lower-case(#" + JcrConstants.JCR_CONTENT + "/" + "authorName" + ")");
authorNamePredicate.set("value", "%" + author.toLowerCase() + "%");
group.add(authorNamePredicate);
}
if (!ThecommonUtility.isEmpty(tagId)) {
Predicate tagPredecate = new Predicate("tags", "tagid");
tagPredecate.set(JcrPropertyPredicateEvaluator.OPERATION, JcrPropertyPredicateEvaluator.OP_LIKE);
tagPredecate.set(JcrPropertyPredicateEvaluator.PROPERTY, JcrConstants.JCR_CONTENT + "/" + "cq:tags");
tagPredecate.set("1_" + JcrPropertyPredicateEvaluator.VALUE, tagId);
group.add(tagPredecate);
}
if (!ThecommonUtility.isEmpty(start_time) && !ThecommonUtility.isEmpty(end_time)) {
final Predicate createdDatePredicate = new Predicate("issueDate", "daterange");
createdDatePredicate.set("property", JcrConstants.JCR_CONTENT + "/" + CQJCRConstants.ISSUEDATE);
createdDatePredicate.set("lowerBound", start_time);
createdDatePredicate.set("lowerOperation", ">=");
createdDatePredicate.set("upperBound", end_time);
createdDatePredicate.set("upperOperation", "<=");
group.add(createdDatePredicate);
}
if (!ThecommonUtility.isEmpty(order_by) && order_by.equalsIgnoreCase("cq:lastModified")) {
final Predicate orderByPredicate = new Predicate("orderBy", Predicate.ORDER_BY);
orderByPredicate.set(Predicate.ORDER_BY, "#" + JcrConstants.JCR_CONTENT + "/" + order_by);
orderByPredicate.set("orderby.index", "true");
orderByPredicate.set(Predicate.PARAM_SORT, Predicate.SORT_DESCENDING);
group.add(orderByPredicate);
} else if (!ThecommonUtility.isEmpty(order_by) && order_by.equalsIgnoreCase("oldest")) {
final Predicate orderByPredicate = new Predicate("orderBy", Predicate.ORDER_BY);
orderByPredicate.set(Predicate.ORDER_BY, "#" + JcrConstants.JCR_CONTENT + "/" + order_by);
orderByPredicate.set("orderby.index", "true");
orderByPredicate.set(Predicate.PARAM_SORT, Predicate.SORT_ASCENDING);
group.add(orderByPredicate);
}
try {
session = request.getResourceResolver().adaptTo(Session.class);
Query query = qbuilder.createQuery(PredicateGroup.create(map), session);
for (Predicate p : group) {
query.getPredicates().add(p);
}
query.setExcerpt(true);
query.setStart(startHit);
query.setHitsPerPage(showMoreCount);
result = query.getResult();
Solution : map.put("group.p.or", "true"); put this code in top and use PredicateGroup concept for search path {group=group: or=true[
{3_fulltext=fulltext: relPath=jcr:content/#jcr:title, fulltext=bibi}
{4_fulltext=fulltext: relPath=jcr:content/#jcr:description, fulltext=bibi}
{5_fulltext=fulltext: relPath=jcr:content/#cq:tags, fulltext=bibi}
{6_fulltext=fulltext: relPath=jcr:content/#authorName, fulltext=bibi}
{7_fulltext=fulltext: relPath=jcr:content/#weekSlugName, fulltext=bibi}
]}
{type=type: type=cq:Page}
{path=group: or=true[
{1_mypath1=mypath1: path=/content/week/opinion/columns}
{2_mypath2=mypath2: path=/content/week/opinion/books}
]}
{hideInNav=property: operation=not, value=true, property=jcr:content/hideInNav}
{pageMasterNot=property: operation=unequals, value=Master Article, property=jcr:content/jcr:title}
{authorName=property: operation=like, value=%ajish%, property=fn:lower-case(#jcr:content/authorName)}
{orderBy=orderby: orderby.index=true, sort=desc, orderby=#jcr:content/cq:lastModified}
I'm using graph api v2.1. AS3-code generates data, calls JS-code via ExternalInterface, JS-code calls FB API
I'm able to upload photo via {image-url}, but getting error when trying to upload photo via {image-data}:
{message: "(#324) Requires upload file", type: "OAuthException", code:
324}
I guess, i'm formatting {image-data} wrong. here is my code:
AS3:
var id:int = Math.random()*10000;
var stream:ByteArray = new ByteArray();
var imageName:String = id.toString() + ".png";
var boundary:String = "I" + id.toString();
stream.writeUTFBytes(
'Content-Type: multipart/form-data; boundary=' + boundary +
'\r\n\r\n--' + boundary +
'\r\nContent-Disposition: file; filename="' + imageName + '"' +
'\r\nContent-Type: image/png' +
'\r\nContent-Transfer-Encoding: binary' +
'\r\n\r\n');
stream.writeBytes(picture);
stream.writeUTFBytes("\r\n--" + boundary + '--\r\n');
if (ExternalInterface.available)
{
ExternalInterface.call('savePhoto', stream, null, id);
}
JS:
function savePhoto(bytes, url, requestId)
{
var data;
if (bytes != null)
data = {"source": bytes, "no_story":true}; //getting error
else
data = {"url": url, "no_story":true}; //works fine
FB.api(
"/me/photos",
"POST",
data,
function (response)
{
//handle response
}
);
}
UPD:
Here is how picture initialised:
[Embed(source="../res/logo_2.png", mimeType="image/png")]
private var testImage:Class;
<...>
var data:Bitmap = new testImage() as Bitmap;
var picture:ByteArray = PNGEncoder.encode(data.bitmapData);
Did you try base64?
var params: Object = new Object;
var encoder:JPGEncoder = new JPGEncoder(75);
var bytes:ByteArray = encoder.encode(bmp.bitmapData);
params.message = message;
params.image = bytes;
params.fileName = "image.jpg";
Facebook.api("/me/photos",null,params,"POST");
https://code.google.com/p/as3corelib/
Try this code to prepare data:
var pngData:ByteArray = PNGEncoder.encode(image.bitmapData);
var strForStart:String = "\r\n--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"photo\"; filename=\"file1.png\"\r\n" + "Content-Type: image/png\r\n\r\n" + "";
var strForEnd:String = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"Upload\"\r\n\r\n" + "Submit Query\r\n" + "--" + boundary + "--";
var beginBA:ByteArray = new ByteArray();
beginBA.writeMultiByte(strForStart, "ascii");
var endBA:ByteArray = new ByteArray();
endBA.writeMultiByte(strForEnd, "ascii");
var resultBytes:ByteArray = new ByteArray();
resultBytes.writeBytes(beginBA, 0, beginBA.length);
resultBytes.writeBytes(pngData, 0, pngData.length);
resultBytes.writeBytes(endBA, 0, endBA.length);
Here is my code:
//order my baselist is context.Entity
public static GridData Getdata<T>(ObjectSet<T> baseList,
int currentPage,
int rowsPerPage,
string sortcolumn,
string sortord,
string searchQuery,
string searchColumns)where T: class{
var query = baseList.OrderBy("it." + sortcolumn + " " + sortord);
string strPredicate = string.Empty;
if (!string.IsNullOrEmpty(searchColumns))
{
strPredicate = "it." + searchColumns + " LIKE #" + searchColumns + " ";
query = baseList.Where(strPredicate, new ObjectParameter(searchColumns, searchQuery)).OrderBy("it." + sortcolumn + " " + sortord);
}
}
My problem is i am trying to write down or form a like query in entity framework and seems like it does not support it.
You can use .Contains which is the LIKE operator equivalent in entity framework.
you can use this
query = baseList.Where(baseli=>baseli.Contains(searchColumns )).OrderBy("it." + sortcolumn + " " + sortord);
:)