Using the Tridion UGC web service to add ratings - tridion

I know I can add comments through the UGC web service by using something like the following:-
WebServiceClient ugcCall = new WebServiceClient();
string ugcData = "{ \"d\" :{\"Content\":\"" + comment + "\",\"Status\":2,\"ItemPublicationId\":\"" + PublicationId + "\",\"ItemId\":\"" + itemid + "\",\"ItemType\":\"16\",\"Id\":0,\"ModeratedDate\":\"\",\"LastModifiedDate\":\"\",\"CreationDate\":\"\",\"Score\":0,\"Moderator\":\"\",\"User\":{\"Id\":\"ACME%5Cjbloggs\",\"Name\":\"Joe Bloggs\"}}}";
string result = ugcCall.UploadString("/Comments", "POST", ugcData);
My question is what is the syntax for adding ratings and likes and dislikes? Is this documented anywhere?
MTIA
John

The command for uploading ratings is '/Ratings' instead of '/Comments'. The JSON is different too, of course. In the code below, I don't write out the JSON manually, instead I construct a simple Rating object and use the JavascriptSerializer to convert it to JSON:
TcmUri tcmUri = new TcmUri(itemUri);
WSR_ContentDelivery.User user = new WSR_ContentDelivery.User { Id = GetUserId() };
WSR_ContentDelivery.Rating rating = new WSR_ContentDelivery.Rating
{
CreationDate = DateTime.UtcNow,
LastModifiedDate = DateTime.UtcNow,
ItemPublicationId = tcmUri.PublicationId,
ItemId = tcmUri.ItemId,
ItemType = tcmUri.ItemTypeId,
RatingValue = ratingValue.ToString(),
User = user,
Id = "0"
};
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
WSClient.UploadString("/Ratings", "POST", "{d:" + oSerializer.Serialize(rating) + "}", GetUserId());

Related

Upload file into S3 with AWS SDK ASP.NET

I am trying to upload an image from ASP.NET to S3. I am using AWS SDK for that and have already set up what is needed. However, after i run my project, i received an error. I'll be replacing my bucket name to ... for this sample code.
I set up my secretkey and accesskey from User in my Web.config. Please do tell me if u need more codes. I need help.
controller
private static readonly string _awsAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
private static readonly string _awsSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];
[HttpPost]  
        public ActionResult UploadFile(HttpPostedFileBase file)  
        {
try  
            {
if (file.ContentLength > 0)
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = "...",
CannedACL = S3CannedACL.PublicRead,
Key = "images/" + (DateTime.Now.ToBinary() + "-" + file.FileName),
FilePath = Server.MapPath("~/UploadedFiles")
};
client.PutObject(request);
}
}
imageUrls = "File Uploaded Successfully!!";
System.Diagnostics.Debug.WriteLine("File Uploaded Successfully!!");
return Json(imageUrls);
            }  
            catch  
            {  
                ViewBag.Message = "File upload failed!!";
System.Diagnostics.Debug.WriteLine("File upload failed!!");
return Json(ViewBag.Message);  
            }  
        }
You're getting the error due to DateTime.Now.ToBinary() which contains invalid characters to be used in a URL. For example, you could use a GUID or a Unix timestamp instead.
Also, the FilePath property you're assigning to the PutObjectRequest is the full path and name to a file to be uploaded. So, you don't need it when you already have HttpPostedFileBase as an input parameter, which contains the InputStream property (i.e., the stream object).
Your PutObjectRequest should look something like this:
.
.
.
Guid guid = Guid.NewGuid();
// Create a client
AmazonS3Client client = new AmazonS3Client(_awsAccessKey, _awsSecretKey);
// Create a PutObject request
PutObjectRequest request = new PutObjectRequest
{
BucketName = "...",
CannedACL = S3CannedACL.PublicRead,
Key = "images/" + guid + "-" + file.FileName
};
using (System.IO.Stream inputStream = file.InputStream)
{
request.InputStream = inputStream;
// Put object
PutObjectResponse response = client.PutObject(request);
}
.
.
.
I finally solved it. I realized i did not place region in AWSClientFactory, right at the end after the keys.

Unknown authentication scheme when liking post (LinkedIn API)

Below goal is to like a post!
I get an error when trying to "Like" a post with the REST API (LinkedIn)
I have created an accesstoken with all scopes:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
I can retreive comments from posts with the accesstoken which tell us that I have set it up correctly as a base.
However when I try to like a comment with the below code (just after in the same code where I have collected a comment), I receive this error:
"unknown authentication scheme"
I wonder why I can't like a post when I have set all scopes and I also have them checked in my application settings. Also notice that the postID is correct as I can retreive the comments for the post?
Thank you!
String accessToken = "MYLONGTOKEN"; //Just dummy example
String postID = "g-123456-S-123456789"; //Just dummy example
String requestUrl = "https://api.linkedin.com/v1/posts/" + postID + "/relation-to-viewer/is-liked&oauth2_access_token=" + accessToken;
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.PUT);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
restResponse = (RestSharp.RestResponse)rc.Execute(request);
responseStatus = restResponse.ResponseStatus;
//unknown authentication scheme
MessageBox.Show(restResponse.Content.ToString());
I found a solution which seems to work. The additional and replacement code is:
//Comment this post
requestUrl = "https://api.linkedin.com/v1/posts/" + postID + "/comments?oauth2_access_token=" + accessToken;
var comment = new
{
text = "This is a comment!"
};
rc = new RestSharp.RestClient();
request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(comment);
restResponse = (RestSharp.RestResponse)rc.Execute(request);
responseStatus = restResponse.ResponseStatus;
MessageBox.Show(responseStatus.ToString() + "," + restResponse.Content.ToString());

Follow Company issue (LinkedIn API)

I am trying to follow a company without success.
I have generated an access token for all scopes which also works for other functions with the API:
scope=w_messages+rw_company_admin+rw_nus+r_emailaddress+r_basicprofile+rw_groups+r_fullprofile+r_network+r_contactinfo
The below code reaches the end and shows the MessageBox with message:
"BadRequest,Can not parse JSON company document.\nRequest body:\n\nError:\nnull"
I will be happy for help. I have follwed the below documentation but it doesn't exactly show how to follow the company, so it leaves me with this question and example below:
https://developer.linkedin.com/documents/company-follow-and-suggestions
String companyID = "9288340";
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies/id=" + companyID + "?oauth2_access_token=MYTOKENGOESHERE";
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());
After a lot of testing, I just managed to be able to follow a company.
So the below code is working:
requestUrl = "https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token=MYTOKENGOESHERE";
var BODY = new
{
id = "9288340" //companyID
};
RestSharp.RestClient rc = new RestSharp.RestClient();
RestSharp.RestRequest request = new RestSharp.RestRequest(requestUrl, RestSharp.Method.POST); //POST = Follow
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = RestSharp.DataFormat.Json;
request.AddBody(BODY);
RestSharp.RestResponse restResponse = (RestSharp.RestResponse)rc.Execute(request);
RestSharp.ResponseStatus responseStatus = restResponse.ResponseStatus;
MessageBox.Show(restResponse.StatusCode.ToString() + "," + restResponse.Content.ToString());

Select query with multiple parameterized in-clauses

I have a form with 2 dropdown lists and 3 checkbox sections that users select from to search the database. Since all of the tables are small, I'd like to use a single SELECT statement to return the results. I found an extension on mikesdotnetting that works great with a single IN clause
using System;
using System.Collections.Generic;
using WebMatrix.Data;
using System.Linq;
public static class DatabaseExtensions
{
public static IEnumerable<dynamic> QueryIn(this Database db, string commandText, string values)
{
if (string.IsNullOrEmpty(values))
throw new ArgumentException("Value cannot be null or an empty string", "values");
var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var temp2 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var temp3 = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var parms = temp.Select((s, i) => "#" + i.ToString()).ToArray();
var parms2 = temp2.Select((s, i) => "#" + i.ToString()).ToArray();
var parms3 = temp3.Select((s, i) => "#" + i.ToString()).ToArray();
var inclause = string.Join(",", parms, parms2, parms3);
return db.Query(string.Format(commandText, inclause), temp, temp2, temp3);
}
public static int ExecuteIn(this Database db, string commandText, string values)
{
if (string.IsNullOrEmpty(values))
throw new ArgumentException("Value cannot be null or an empty string", "values");
var temp = values.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var parms = temp.Select((s, i) => "#" + i.ToString()).ToArray();
var inclause = string.Join(",", parms);
return db.Execute(string.Format(commandText, inclause), temp);
}
}
Here is the page code showing how I envision the query:
var gender = Request["genderSvd"];
var person = Request["chkPerson"];
var spec = Request["chkSpec"];
var county = Request["ctyLoc"];
var crim = Request["chkCrim"];
var db = Database.Open("HBDatabase");
var sql = "SELECT DISTINCT tblProgram.* FROM lnkPrgPersonSvd INNER JOIN tblProgram ON lnkPrgPersonSvd.prgId = tblProgram.prgId";
sql += "INNER JOIN lnkPrgSpecial ON tblProgram.prgId = lnkPrgSpecial.prgId INNER JOIN tblProgram.prgId = lnkPrgCriminal.prgId ";
sql += "WHERE (lnkPrgPersonSvd.personId IN ({0})) AND (lnkPrgSpecial.specId IN ({1})) AND tblProgram.prgGenderSvdId = #2 ";
sql += "AND tblProgram.prgCounty = #3 AND (lnkPrgCriminal.criminalId IN ({4}))";
var prgList = db.QueryIn(sql, person, spec, gender, county, crim);
That, obviously, doesn't work, because the extension cannot take that many arguments. I'm looking for a way to modify the class to allow for the additional parameters so that the query can run with just the one execution. This may not be possible.
Also, I did find several threads that dealt with handling a single parameterized in clause, but no real mention of multiples with variable lists.
I am not adept with stored procedures or writing my own classes. Any suggestions?

Get id of new record in DNN Module

Am new to DNN Module development and using MVC and Linq. Have built a class and controller that allows me to create a record in a table on the database. Can anyone tell me the best way to retrieve the id of the newly created record? The part of the controller for creating the record is below.
class BlockController
{
public void CreateBlock(Block b)
{
using (IDataContext ctx = DataContext.Instance())
{
var rep = ctx.GetRepository<Block>();
rep.Insert(b);
}
}
}
Call to the controller from the code
var bC = new BlockController();
var b = new Block()
{
SectionId = int.Parse(ddlPickSection.SelectedValue),
PlanId = int.Parse(ddlPickPlan.SelectedValue),
BlockName = bId,
BlockDesc = "",
xPos = bX,
yPos = bY,
width = arrBWidths[i],
ModuleId = ModuleId,
CreatedOnDate = DateTime.Now,
CreatedByUserId = UserId,
LastModifiedOnDate = DateTime.Now,
LastModifiedByUserId = UserId,
};
bC.CreateBlock(b);
Thanks
When you submit changes (insert the record in DB) the ID would available in b object:
...
rep.InsertOnSubmit(b);
ctx.SubmitChanges();
int desireID = b.id;

Resources